mirror of https://github.com/onweru/compose.git

git-hub-9999
09.15.2026 73580d9b0dfe1d257378412d0a97b764080b0c8e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*!
 * Compose theme — chart-table filter/sort.
 * Self-authored replacement for the two W3Schools w3.js functions
 * (filterHTML / sortHTML) previously used by the `chart` shortcode.
 * MIT — part of the Compose theme; no third-party code.
 *
 * Behaviour is a faithful port of the originals:
 *  - filter: case-insensitive substring match on each row's innerHTML.
 *  - sort:   lexicographic (lowercased) sort by a cell selector, toggling
 *            ascending -> descending when the column is already ascending.
 */
(function () {
  "use strict";
 
  function filter(tableSel, rowSel, term) {
    var needle = (term || "").toUpperCase();
    var rows = document.querySelectorAll(rowSel);
    for (var i = 0; i < rows.length; i++) {
      var match = rows[i].innerHTML.toUpperCase().indexOf(needle) > -1;
      rows[i].style.display = match ? "" : "none";
    }
  }
 
  function sort(tableSel, rowSel, cellSel) {
    var table = document.querySelector(tableSel);
    if (!table) {
      return;
    }
    var rows = Array.prototype.slice.call(table.querySelectorAll(rowSel));
    if (rows.length < 2) {
      return;
    }
    function value(row) {
      var cell = cellSel ? row.querySelector(cellSel) : row;
      return cell ? cell.innerHTML.toLowerCase() : "";
    }
    var ascending = rows.slice().sort(function (a, b) {
      var x = value(a), y = value(b);
      return x < y ? -1 : x > y ? 1 : 0;
    });
    // Match w3.sortHTML: if the column is already ascending, sort descending.
    var alreadyAscending = rows.every(function (row, i) {
      return row === ascending[i];
    });
    var ordered = alreadyAscending
      ? rows.slice().sort(function (a, b) {
          var x = value(a), y = value(b);
          return x < y ? 1 : x > y ? -1 : 0;
        })
      : ascending;
    var parent = rows[0].parentNode;
    ordered.forEach(function (row) {
      parent.appendChild(row);
    });
  }
 
  window.composeTable = { filter: filter, sort: sort };
})();