Skip to content

Commit c110859

Browse files
author
Bo Peng
committed
Allow dataframe to be sorted and searched #42
1 parent 420f3a1 commit c110859

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/index.ts

+77
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,83 @@ function registerSoSWidgets(app: JupyterFrontEnd) {
926926
app.docRegistry.addWidgetExtension("Notebook", new SoSWidgets());
927927
}
928928

929+
930+
(<any>window).filterDataFrame = function(id) {
931+
var input = document.getElementById("search_" + id) as HTMLInputElement;;
932+
var filter = input.value.toUpperCase();
933+
var table = document.getElementById("dataframe_" + id) as HTMLTableElement;
934+
var tr = table.getElementsByTagName("tr");
935+
936+
// Loop through all table rows, and hide those who do not match the search query
937+
for (var i = 1; i < tr.length; i++) {
938+
for (var j = 0; j < tr[i].cells.length; ++j) {
939+
var matched = false;
940+
if (tr[i].cells[j].innerHTML.toUpperCase().indexOf(filter) !== -1) {
941+
tr[i].style.display = "";
942+
matched = true;
943+
break;
944+
}
945+
if (!matched) {
946+
tr[i].style.display = "none";
947+
}
948+
}
949+
}
950+
};
951+
952+
(<any>window).sortDataFrame = function(id, n, dtype) {
953+
var table = document.getElementById("dataframe_" + id) as HTMLTableElement;
954+
955+
var tb = table.tBodies[0]; // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
956+
var tr = Array.prototype.slice.call(tb.rows, 0); // put rows into array
957+
958+
var fn =
959+
dtype === "numeric"
960+
? function(a, b) {
961+
return parseFloat(a.cells[n].textContent) <=
962+
parseFloat(b.cells[n].textContent)
963+
? -1
964+
: 1;
965+
}
966+
: function(a, b) {
967+
var c = a.cells[n].textContent
968+
.trim()
969+
.localeCompare(b.cells[n].textContent.trim());
970+
return c > 0 ? 1 : c < 0 ? -1 : 0;
971+
};
972+
var isSorted = function(array, fn) {
973+
if (array.length < 2) {
974+
return 1;
975+
}
976+
var direction = fn(array[0], array[1]);
977+
for (var i = 1; i < array.length - 1; ++i) {
978+
var d = fn(array[i], array[i + 1]);
979+
if (d === 0) {
980+
continue;
981+
} else if (direction === 0) {
982+
direction = d;
983+
} else if (direction !== d) {
984+
return 0;
985+
}
986+
}
987+
return direction;
988+
};
989+
990+
var sorted = isSorted(tr, fn);
991+
var i;
992+
993+
if (sorted === 1 || sorted === -1) {
994+
// if sorted already, reverse it
995+
for (i = tr.length - 1; i >= 0; --i) {
996+
tb.appendChild(tr[i]); // append each row in order
997+
}
998+
} else {
999+
tr = tr.sort(fn);
1000+
for (i = 0; i < tr.length; ++i) {
1001+
tb.appendChild(tr[i]); // append each row in order
1002+
}
1003+
}
1004+
};
1005+
9291006
/**
9301007
* Initialization data for the sos-extension extension.
9311008
*/

0 commit comments

Comments
 (0)