@xiee/utils 1.14.110 → 1.14.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,62 +1,50 @@
1
1
  /* lt-interactive.js — opt-in interactivity for lt tables (search, sort, column
2
- * filters, pagination, column resizing, column show/hide).
2
+ * filters, pagination, column resize, column show/hide).
3
3
  *
4
- * A plugin on the existing LT global (see lt.js): it adds no new global. For a
5
- * table whose spec carries `interactive`, it adds the requested controls and
6
- * re-renders <tbody> through the core `spec._viewRows` seam. Every control is a
7
- * row of the table itself — the search box in <thead>, the pager in <tfoot> —
8
- * so it is exactly as wide as the table and scrolls with it. Row structure is
9
- * honored: separator row groups, indentation, and rowspan row groups all
10
- * sort/filter within each group or subtree, never across it (see computeView).
4
+ * Plugin on the LT global (see lt.js); no new global. For a spec with
5
+ * `interactive`, adds controls and re-renders <tbody> via core `spec._viewRows`.
6
+ * Controls are table rows (search in <thead>, pager in <tfoot>), so they match
7
+ * table width and scroll with it. Separator groups, indentation, and rowspan
8
+ * groups sort/filter within their group or subtree, never across (see
9
+ * computeView).
11
10
  */
12
11
  (root => {
13
12
  "use strict";
14
13
  const LT = root.LT;
15
- // Bail out if core is absent or too old, or the plugin already loaded.
14
+ // Bail if core is absent/old or plugin already loaded.
16
15
  if (!LT?.onMount || LT.plugins.interactive) return;
17
16
 
18
- const MIN_COL = 24; // px: a dragged column never gets narrower than this
19
- let coll; // locale-aware comparator, built on first use and reused
20
- // A column is numeric if its first non-null value is a number (how core
21
- // lt.js decides alignment and formatting).
22
- const numCol = col => typeof col.find(v => v != null) === "number";
23
- // A number as subscript digits (₁ ₂ …), for the sort-order ordinals.
17
+ const MIN_COL = 24; // px: min dragged column width
18
+ let coll; // lazy locale-aware comparator
19
+ // Numeric if first non-null value is a number (same rule as core lt.js).
20
+ // Subscript digits (₁ ₂ …) for sort-order ordinals.
24
21
  const sub = n => String(n).replace(/\d/g, d => "₀₁₂₃₄₅₆₇₈₉"[d]);
25
- // A sort key: a `"col"` (ascending) or `"-col"` (descending) string, or an
26
- // explicit `{col, dir}` object. Normalizes either to `{col, dir}`.
22
+ // Sort key `"col"`, `"-col"` (desc), or `{col, dir}` -> `{col, dir}`.
27
23
  const parseKey = k => typeof k !== "string" ? { ...k } :
28
24
  k[0] === "-" ? { col: k.slice(1), dir: "desc" } : { col: k, dir: "asc" };
29
- // Compare two non-null values: numeric subtraction for a numeric column, else
30
- // a locale-aware string compare (the collator built once, lazily reused).
25
+ // Compare non-null values: subtraction if numeric, else locale string compare.
31
26
  const cmpVals = (x, y, num) => {
32
27
  coll ||= new Intl.Collator();
33
28
  return num ? x - y : coll.compare(String(x), String(y));
34
29
  };
35
30
 
36
- // --- Small DOM helpers, so building the controls stays terse ---
37
- const $ = (el, sel) => el.querySelector(sel),
38
- $$ = (el, sel) => el.querySelectorAll(sel),
39
- on = (t, type, fn, opts) => t.addEventListener(type, fn, opts),
40
- off = (t, type, fn) => t.removeEventListener(type, fn);
41
- // A row's data cells, in column order: its children minus the leading rowspan
42
- // group-column cells (class `lt-row-group`), which are not in `spec._cols` and,
43
- // in rowspan mode, appear on some rows but not others (a run's later rows have
44
- // none). Selecting by class — not position — is what lets the positional code
45
- // (hide, detail, display capture) stay correct whatever leads the row.
31
+ // --- Small DOM helpers ---
32
+ const { $, $$, on, off, numCol } = LT;
33
+ // A row's data cells in column order: children minus leading rowspan group
34
+ // cells (`lt-row-group`), which aren't in `spec._cols` and are missing on a
35
+ // run's later rows. Class-based, not positional, so index code stays correct.
46
36
  const dataCells = tr =>
47
37
  [...tr.children].filter(c => !c.classList.contains("lt-row-group"));
48
- // Create a <tag> and assign `props`: a dashed key ("aria-label") sets an
49
- // attribute, any other key ("className", "type", "textContent") a DOM
50
- // property. Appends to `parent` when given, and returns the new element.
38
+ // Create <tag> with `props`: dashed key = attribute, else DOM property.
39
+ // Appends to `parent` if given; returns the element.
51
40
  function elem(doc, tag, props = {}, parent) {
52
41
  const e = doc.createElement(tag);
53
42
  for (const k in props)
54
43
  k.includes("-") ? e.setAttribute(k, props[k]) : (e[k] = props[k]);
55
44
  return parent ? parent.appendChild(e) : e;
56
45
  }
57
- // Pointer-drag: after a pointerdown `e`, call `onMove(ev)` for every move until
58
- // pointerup, then `onEnd()` (if given). Shared by column resize and the range
59
- // filter's slider thumbs; suppresses text selection during the drag.
46
+ // Pointer drag from pointerdown `e`: `onMove(ev)` per move until pointerup,
47
+ // then `onEnd()`. Used by column resize and slider thumbs; blocks text selection.
60
48
  function drag(e, onMove, onEnd) {
61
49
  e.preventDefault();
62
50
  const doc = e.target.ownerDocument || document, move = ev => onMove(ev);
@@ -67,16 +55,14 @@
67
55
  }, { once: true });
68
56
  }
69
57
 
70
- // Compile a search term into a predicate over one row's cells (`{raw, disp}`
71
- // objects), or null to keep every row. Ported from forestly's
72
- // inst/js/search-filter.js so results stay consistent across the projects.
73
- // - Expression mode, when the term references the cell variable `x` (e.g.
74
- // `x > 5`, `x !== "Rash"`): evaluated as JavaScript against the *raw*
75
- // value, as a string and (when finite) as a number. A leading `!` or an
76
- // `!=` is negation, which keeps a row only when *every* cell satisfies the
77
- // test; otherwise *any* matching cell keeps the row.
78
- // - Substring mode otherwise: case-insensitive match against the *display*
79
- // text, with a leading `!` negating.
58
+ // Compile a search term to a predicate over a row's cells (`{raw, disp}`), or
59
+ // null to keep every row. Ported from forestly's inst/js/search-filter.js for
60
+ // consistent results.
61
+ // - Expression mode, if the term uses cell variable `x` (`x > 5`): JS run on
62
+ // the *raw* value, as string and (if finite) number. Leading `!` or `!=` is
63
+ // negation: keep a row only if *every* cell passes; else *any* match keeps it.
64
+ // - Otherwise substring mode: case-insensitive match on *display* text; leading
65
+ // `!` negates.
80
66
  function matcher(term) {
81
67
  const v = String(term ?? "").trim();
82
68
  if (v === "") return null;
@@ -101,14 +87,11 @@
101
87
  );
102
88
  }
103
89
 
104
- // The view pipeline (pure — no DOM): per-column filters, the table-wide
105
- // search, then any externally registered predicates, then sort, yielding the
106
- // 1-based original row indices for `spec._viewRows`. `disp[col][i]` is a
107
- // cell's displayed text (what substring search matches); `state` holds the
108
- // filter terms (`filters[col]`), the search term, the predicates
109
- // (`predicates`, keyed by id — see el._lt.filter), and the sort keys (`sort`,
110
- // an array of `{col, dir}` applied in order). Filters, the search, and the
111
- // predicates are combined with AND: a row must pass all of them.
90
+ // View pipeline (pure, no DOM): column filters, table search, external
91
+ // predicates (ANDed), then sort -> 1-based original row indices for
92
+ // `spec._viewRows`. `disp[col][i]` = displayed text (what substring search
93
+ // matches). `state`: `filters[col]` terms, `term` search, `predicates` by id
94
+ // (see el._lt.filter), `sort` = ordered `{col, dir}` keys.
112
95
  function computeView(spec, disp, state) {
113
96
  const cols = spec._cols || [], data = spec.data || {},
114
97
  nRow = (data[cols[0]] || []).length,
@@ -116,9 +99,7 @@
116
99
  raw: data[c]?.[r - 1] ?? null, disp: disp[c]?.[r - 1] ?? ""
117
100
  });
118
101
 
119
- // The per-row keep test: the column filters, the table-wide search, then the
120
- // externally registered predicates, combined with AND (a row must pass all).
121
- // A filter looks at one cell, so the cheap tests come first.
102
+ // Per-row keep test, ANDed; cheap single-cell filters first.
122
103
  const tests = [];
123
104
  for (const c in state.filters || {}) {
124
105
  const pred = matcher(state.filters[c]);
@@ -126,11 +107,9 @@
126
107
  }
127
108
  const sPred = matcher(state.term);
128
109
  if (sPred) tests.push(r => sPred(cols.map(c => cell(c, r))));
129
- // predicates registered from outside (el._lt.filter) run last, each a
130
- // function of the row's raw values keyed by column. The row carries *every*
131
- // column (not just the visible `cols`), so a widget can filter on a hidden
132
- // helper column — e.g. forestly's incidence slider reads the hidden
133
- // `hide_prop`, its parameter dropdown the hidden `parameter`.
110
+ // External predicates (el._lt.filter) run last, on the row's raw values by
111
+ // column. Row has *every* column, not just visible `cols`, so widgets can
112
+ // filter on hidden helpers (e.g. forestly's `hide_prop`, `parameter`).
134
113
  const fns = Object.values(state.predicates || {});
135
114
  if (fns.length) {
136
115
  const all = Object.keys(data),
@@ -139,10 +118,8 @@
139
118
  }
140
119
  const keep = r => tests.every(t => t(r));
141
120
 
142
- // Build a comparator from a list of sort keys: each key in turn, falling
143
- // through to the next on a tie; a key's column (resolved once) carries its
144
- // numeric test and direction. nulls sort last regardless of direction, so the
145
- // direction never applies to them. Null when the list sorts nothing.
121
+ // Comparator from sort keys, next key on tie. nulls sort last regardless of
122
+ // direction. Null if nothing to sort.
146
123
  const makeCmp = sortKeys => {
147
124
  const keys = sortKeys.map(k => {
148
125
  const col = data[k.col];
@@ -159,12 +136,10 @@
159
136
  } : null;
160
137
  };
161
138
 
162
- // Reduce a list of rows (in document order) to the kept rows in view order,
163
- // sorted by `cmp`. With no indentation this is a plain filter + sort. With
164
- // indentation the rows form a tree (a row's parent is the nearest earlier row
165
- // one level up): filtering keeps any row with a surviving descendant, so a
166
- // match stays in context, and a sort reorders siblings while each subtree
167
- // travels with its parent.
139
+ // Rows (document order) -> kept rows in view order, sorted by `cmp`. Without
140
+ // indentation: plain filter + sort. With it, rows form a tree (parent = nearest
141
+ // earlier row one level up): filter keeps rows with a surviving descendant (match
142
+ // stays in context); sort reorders siblings, subtrees move with their parent.
168
143
  const indent = spec._indent;
169
144
  const reduce = (rows, cmp) => {
170
145
  if (!indent) {
@@ -194,14 +169,11 @@
194
169
 
195
170
  const all = () => Array.from({ length: nRow }, (_, i) => i + 1);
196
171
 
197
- // Rowspan row groups: the group columns (outermost first) nest, so the view
198
- // must stay a hierarchy — sorting a data column may only reorder rows within
199
- // the innermost group, never across a group boundary, or a spanning cell
200
- // would have to split. So partition by group column 1, then recurse on
201
- // column 2 within each block, …, and only at the leaves sort by the data
202
- // keys. A group column the reader clicked orders its blocks by that column
203
- // (its key is pulled out of the leaf sort); untouched, blocks keep their
204
- // first-appearance order. Rendering recomputes the spans from this order.
172
+ // Rowspan groups nest (outermost first), so data sorting may only reorder
173
+ // within the innermost group, or a spanning cell would split. Partition by
174
+ // group column 1, recurse into column 2 per block, ..., sort by data keys at
175
+ // leaves. A clicked group column orders its blocks (key pulled from leaf
176
+ // sort); else blocks keep first-appearance order. Render recomputes spans.
205
177
  const gcols = spec._rowspan;
206
178
  if (gcols) {
207
179
  const dir = {}, leaf = [];
@@ -229,11 +201,9 @@
229
201
  return partition(all(), 0);
230
202
  }
231
203
 
232
- // Separator row groups keep their place (the group is the unit that does not
233
- // move): each group's rows filter/sort within it, and the surviving rows of
234
- // all groups concatenate in group order, then any ungrouped rows (manual
235
- // groups need not cover every row). A group left with no row simply
236
- // contributes nothing — its header is re-emitted at render only when a row
204
+ // Separator groups keep their place: rows filter/sort within a group; survivors
205
+ // concatenate in group order, then ungrouped rows (manual groups needn't cover
206
+ // all). An empty group contributes nothing; its header re-emits only if a row
237
207
  // remains.
238
208
  const cmp = makeCmp(state.sort || []), groups = spec._groups;
239
209
  if (!groups) return reduce(all(), cmp);
@@ -244,10 +214,8 @@
244
214
  return [...out, ...reduce(rest, cmp)];
245
215
  }
246
216
 
247
- // The rows of `view` on the current page. `state.page` is clamped into range
248
- // first (in place, so the pager reads back the page actually shown): the row
249
- // count shrinks as filters are typed. A `state.pageSize` of 0 means every row
250
- // on one page.
217
+ // Rows of `view` on the current page. Clamps `state.page` in place (row count
218
+ // shrinks as filters are typed; pager reads it back). `pageSize` 0 = one page.
251
219
  function pageSlice(view, state) {
252
220
  const n = state.pageSize;
253
221
  if (!n) { state.page = 0; return view; }
@@ -256,13 +224,11 @@
256
224
  return view.slice(state.page * n, (state.page + 1) * n);
257
225
  }
258
226
 
259
- // Displayed text per column, keyed to the original row order. It does not
260
- // change with the view, so capture it once from the initial full render.
261
- // `order[i]` is the original 1-based index of the i-th body row as rendered
262
- // (for a grouped table whose groups do not follow file order); absent ⇒ body
263
- // rows are in index order. Separator group-header rows are skipped — they are
264
- // no column's cell. `dataCells` drops any leading rowspan group cell, so the
265
- // index lines up with `cols` whatever precedes the data cells.
227
+ // Displayed text per column in original row order; view-independent, so
228
+ // captured once from the initial render. `order[i]` = original 1-based index of
229
+ // the i-th rendered body row (groups out of file order); absent = index order.
230
+ // Skips group-header rows. `dataCells` drops rowspan group cells so indexes
231
+ // line up with `cols`.
266
232
  function captureDisplay(el, cols, order) {
267
233
  const disp = {};
268
234
  cols.forEach(c => disp[c] = []);
@@ -280,19 +246,17 @@
280
246
  const opts = spec.interactive, cols = spec._cols || [],
281
247
  data = spec.data || {}, nRow = (data[cols[0]] || []).length,
282
248
  groups = spec._groups,
283
- // each row's group (for re-emitting a surviving header), and the body
284
- // render order: groups in order, then any ungrouped rows (so a manual
285
- // group listed out of file order maps the display text correctly)
249
+ // row -> group (to re-emit headers), and body render order (groups,
250
+ // then ungrouped rows) so out-of-order manual groups map display text
286
251
  groupOf = {}, order = groups ? [] : null;
287
252
  if (groups) {
288
253
  const seen = new Set();
289
254
  groups.forEach(g => g.rows.forEach(r => { groupOf[r] = g; order.push(r); seen.add(r); }));
290
255
  for (let r = 1; r <= nRow; r++) if (!seen.has(r)) order.push(r);
291
256
  }
292
- // turn a page's data rows into the row list core renders: a group header
293
- // (an object core draws as a full-width label row) is inserted whenever the
294
- // group changes, so a group spanning a page boundary re-shows its header at
295
- // the top of the next page; ungrouped rows get none.
257
+ // Page rows -> core's row list: insert a group header object (full-width
258
+ // label row) when the group changes, so a group split across pages re-shows
259
+ // its header; ungrouped rows get none.
296
260
  const withGroups = rows => {
297
261
  if (!groups) return rows;
298
262
  const out = []; let prev;
@@ -303,88 +267,74 @@
303
267
  }
304
268
  return out;
305
269
  };
306
- // the rowspan group columns lead the header row (they are hidden from
307
- // `cols`); the full header order drives sort, so clicking a group header
308
- // reorders its blocks (computeView pulls a group-column key out of the leaf
309
- // sort — see the `_rowspan` branch there)
270
+ // Rowspan group columns lead the header (hidden from `cols`); the full
271
+ // header order drives sort, so clicking one reorders its blocks (see
272
+ // `_rowspan` in computeView)
310
273
  const nGroup = spec._rowspan ? spec._rowspan.length : 0,
311
274
  allCols = nGroup ? [...spec._rowspan, ...cols] : cols,
312
- // the table's full column count: a full-width row (control bar, pager,
313
- // no-match placeholder, detail) must span the leading group columns too
275
+ // full column count: full-width rows must span group columns too
314
276
  nAll = nGroup + cols.length;
315
- // buildHtml computed the displayed text for *every* row (spec._display),
316
- // independent of the first-page render cap, so use it for substring
317
- // matching. The DOM holds only the initial page, so scraping it (the
318
- // fallback) would make filters miss every off-page row.
277
+ // spec._display has text for *every* row (beyond the first-page cap); use it
278
+ // for substring matching. Scraping the DOM (fallback) misses off-page rows.
319
279
  const disp = spec._display || captureDisplay(el, cols, order),
320
- // the bottom header row: the one whose cells line up with `cols`
280
+ // bottom header row: cells line up with `cols`
321
281
  hrow = [...$$(el, "thead tr")].pop(),
322
- // an array `sort` on the options is an initial sort (a list of key
323
- // strings or objects, see parseKey); `true` just turns sorting on
282
+ // array `sort` = initial sort (see parseKey); `true` just enables it
324
283
  state = {
325
284
  filters: {}, predicates: {}, page: 0, pageSize: 0,
326
285
  sort: Array.isArray(opts.sort) ? opts.sort.map(parseKey) : []
327
286
  };
328
287
  let view, // filtered + sorted indices, cached across page turns
329
288
  sync = () => {}; // pager readout, replaced by addPaginate()
330
- // hooks run on each freshly-built <tbody>, in order, to re-assert the state a
331
- // swap drops: expand carets / detail rows (addDetail), the hidden cells of a
332
- // column turned off in the column menu (addColumnToggle). Each gets the new
333
- // <tbody> and its row indices.
289
+ // Hooks run on each new <tbody> to restore state a swap drops: expand carets
290
+ // / details (addDetail), hidden columns (addColumnToggle). Args: <tbody>,
291
+ // row indices.
334
292
  const postSwap = [];
335
293
 
336
- // `stale` means the view itself changed (a term or the sort), as opposed to
337
- // only the page: recompute it and go back to the first page.
294
+ // `stale`: view changed (term/sort), not just page; recompute, go to page 1.
338
295
  const refresh = (stale = true) => {
339
296
  if (stale) { view = computeView(spec, disp, state); state.page = 0; }
340
297
  const rows = pageSlice(view, state),
341
- // _viewRows carries the page's data rows with group headers spliced
342
- // back in; postSwap hooks get the same list, one entry per <tbody> row
298
+ // _viewRows = page rows with group headers; postSwap gets the same
299
+ // list, one entry per <tbody> row
343
300
  vr = withGroups(rows),
344
301
  tmp = elem(el.ownerDocument, "template", {
345
302
  innerHTML: LT.buildHtml({ ...spec, _viewRows: vr })
346
303
  });
347
304
  const body = $(tmp.content, "tbody");
348
- if (!rows.length) // no matches: a neutral symbol spanning all columns
305
+ if (!rows.length) // no match: neutral symbol across all columns
349
306
  body.innerHTML = `<tr class="lti-empty"><td colspan="${nAll}">—</td></tr>`;
350
307
  else postSwap.forEach(f => f(body, vr));
351
308
  $(el, "tbody").replaceWith(body);
352
309
  sync(view.length);
353
310
  };
354
311
 
355
- // refresh() rebuilds the body synchronously, freezing the page on a large
356
- // table. uiRefresh() shows a busy state during that freeze (see busyRender).
357
- // Paging stays synchronous (cheap); view recomputes (search, sort, filter,
358
- // external predicates) and row-detail toggles route through a busy wrapper.
312
+ // refresh() rebuilds the body synchronously (freezes large tables). uiRefresh()
313
+ // shows a busy state (see busyRender). Paging stays direct (cheap); view
314
+ // recomputes and detail toggles go through the busy wrapper.
359
315
  const wrap = el.closest(".lt-wrap");
360
316
  const uiRefresh = busyRender(wrap, (stale = true) => refresh(stale));
361
- // While the controls are being built, a seeded filter/sort would each fire
362
- // its own full-table body render (forestly seeds a parameter select and an
363
- // incidence slider), every one thrown away by the next — and the early ones
364
- // run before the pager sets a page size, so they render *every* matching row.
365
- // Suppress body renders during construction and coalesce them into the one
366
- // final render below (`building` is cleared just before it).
317
+ // During construction each seeded filter/sort (forestly seeds a select and a
318
+ // slider) would trigger a wasted full-table render, early ones before the pager
319
+ // sets a page size (rendering *every* row). Suppress and coalesce into the one
320
+ // final render below (`building` cleared just before it).
367
321
  let building = true, dirty = false;
368
322
  const requestRefresh = (stale = true) => {
369
323
  if (building) { dirty = true; return; }
370
324
  uiRefresh(stale);
371
325
  };
372
326
 
373
- // a small controller for driving the table from outside (e.g. forestly's
374
- // own dropdown and range-slider widgets): register a predicate over a row's
375
- // raw values (`{col: value}`, including hidden columns) under an id,
376
- // replacing or (with a null `fn`) removing it, then re-render. `spec`/`state`
377
- // are exposed for reading (a widget's choices come from `el._ltSpec.data`).
378
- // `bar` (set once the control bar is built) and `resetDetail` (set when the
379
- // table has row detail) are added below.
327
+ // Controller for outside widgets (e.g. forestly's): `filter(id, fn)` registers
328
+ // a predicate on a row's raw values (`{col: value}`, incl. hidden columns),
329
+ // replacing it, or removing with null `fn`, then re-renders. `spec`/`state`
330
+ // are read-only exposure. `bar` and `resetDetail` are added below.
380
331
  el._lt = {
381
332
  spec, state,
382
- // re-render the body. `stale` (default) recomputes the view and resets to
383
- // page 1; `false` keeps the current view and page (e.g. a plot refit)
333
+ // Re-render body. `stale` (default) recomputes view, page 1; `false` keeps
334
+ // view and page (e.g. plot refit)
384
335
  refresh: (stale = true) => uiRefresh(stale),
385
- // the current filtered + sorted row indices (1-based, every row, not just
386
- // the page) — e.g. for a "download what's shown" button that must honor the
387
- // typed filters (which live in state.filters, not external predicates)
336
+ // Current filtered + sorted 1-based indices (all pages), e.g. for download,
337
+ // which must honor typed filters (in state.filters, not predicates)
388
338
  view: () => view || computeView(spec, disp, state),
389
339
  filter(id, fn) {
390
340
  fn ? (state.predicates[id] = fn) : (delete state.predicates[id]);
@@ -392,103 +342,88 @@
392
342
  }
393
343
  };
394
344
 
395
- // the `filter` option is normalized (R side) to { default?, cols? }: a
396
- // `default` spec applies to every visible column left unnamed, `cols` maps a
397
- // column to its spec (`true` = a plain box, else a typed select/range). A
398
- // typed filter on a hidden column (not in `cols` = spec._cols) can't live
399
- // under a header, so it becomes a chip in the head bar; everything else sits
400
- // under its column header.
345
+ // `filter` is normalized (R side) to { default?, cols? }: `default` covers
346
+ // unnamed visible columns; `cols` maps column -> spec (`true` = plain box, else
347
+ // typed). A typed filter on a hidden column has no header, so it becomes a
348
+ // head-bar chip; the rest go under their headers.
401
349
  const flt = opts.filter,
402
350
  barCols = flt?.cols ?
403
351
  Object.keys(flt.cols).filter(c => flt.cols[c] !== true && !cols.includes(c)) : [];
404
- // the table-wide controls share one full-width head row, laid out left to
405
- // right: an icon group (the column menu and the download button), then the
406
- // head-bar filter chips, then the search box (which absorbs the free space)
352
+ // Table-wide controls share one head row: icons (column menu, download), chips,
353
+ // then search (absorbs free space)
407
354
  const headBar = (opts.search !== false || opts.hide || barCols.length || opts.download) ?
408
355
  elem(el.ownerDocument, "div", { className: "lti-bar" },
409
356
  fullRow(el.tHead || el.createTHead(), "lti-head", nAll, 0)) : null;
410
- // the data-column header labels (skipping any leading group cell), read
411
- // before sort/resize decorate the cells, so the column menu can list the
412
- // displayed labels rather than the raw names
357
+ // Data-column header labels, read before sort/resize decorate cells, so the
358
+ // column menu shows displayed labels, not raw names
413
359
  const labels = dataCells(hrow).map(th => th.textContent);
414
- // wire sort before adding the filter row, so it sees the header row only;
415
- // `allCols` so every header cell binds (a group header is sortable too)
360
+ // Sort before the filter row exists (sees header row only); `allCols` binds
361
+ // group headers too
416
362
  if (opts.sort !== false) addSort(hrow, allCols, state, requestRefresh);
417
- // the under-header filter row: needed when a default applies to visible
418
- // columns or any named column is itself visible
363
+ // Under-header filter row: needed if a default applies or a named column is visible
419
364
  if (flt && (flt.default || (flt.cols && Object.keys(flt.cols).some(c => cols.includes(c)))))
420
365
  addFilter(hrow, cols, flt, spec.data, state, requestRefresh, nGroup);
421
366
  const layout = opts.resize ? fixedLayout(el, hrow, cols.length, nGroup) : null;
422
367
  if (opts.resize) addResize(el, layout);
423
- // the icon buttons sit together in a group that keeps its natural width;
424
- // append them (menu first, download second) before the chips and search so
425
- // the DOM order is the visual order
368
+ // Icon group (natural width); append before chips/search so DOM order = visual
426
369
  const icons = (opts.hide || opts.download) ?
427
370
  elem(el.ownerDocument, "div", { className: "lti-icons" }, headBar) : null;
428
371
  if (opts.hide)
429
372
  addColumnToggle(icons, el, hrow, cols, labels, opts.hide, layout, postSwap);
430
373
  if (opts.download) addDownload(icons, el, spec, cols, labels, opts.download);
431
- // the chips share a group so the bar has three parts (icons, chips, search)
432
- // with a wider gap between them than within each. The group is created
433
- // whenever there is a bar (even with no typed-filter chips) so a caller can
434
- // drop its own chip in beside them via el._lt.chips; an empty group collapses
435
- // (CSS :empty) so it adds no gap.
374
+ // Chips group makes three bar parts with wider gaps between. Always created
375
+ // with a bar so callers can add chips via el._lt.chips; empty collapses
376
+ // (CSS :empty).
436
377
  const chips = headBar ?
437
378
  elem(el.ownerDocument, "div", { className: "lti-chips" }, headBar) : null;
438
379
  if (barCols.length) addControlFilters(chips, barCols, flt.cols, spec.data, state, requestRefresh);
439
380
  if (opts.search !== false) addSearch(headBar, el, state, requestRefresh);
440
- // the assembled control bar (`.lti-bar`), or null when the table has no
441
- // table-wide controls, for a caller to append its own widget to; `chips` is
442
- // its chip group (null only when there is no bar), the right home for a
443
- // caller's own labelled chip
381
+ // Control bar (`.lti-bar`; null if no table-wide controls) for callers to add
382
+ // widgets to; `chips` is its chip group (null only without a bar), home for
383
+ // caller chips
444
384
  el._lt.bar = headBar;
445
385
  el._lt.chips = chips;
446
- // row detail re-renders through the same seam: toggling a row only changes
447
- // which rows carry a detail block, so a plain re-render (no new view) is
448
- // enough
386
+ // Row detail re-renders via the same seam; toggling changes no view, so a
387
+ // plain re-render suffices
449
388
  if (opts.detail) {
450
389
  const detail = addDetail(el, spec, nAll, state, opts.detail, () => refresh(false));
451
390
  postSwap.push(detail);
452
- // bust the per-row detail cache and re-render open details (one row, or
453
- // all); for a caller whose widget changes what the detail callback returns
391
+ // Bust detail cache and re-render open details (one row or all), for
392
+ // widgets that change the detail callback's output
454
393
  el._lt.resetDetail = detail.reset;
455
394
  }
456
- // controls are built; let the coalesced final render(s) below run
395
+ // controls built; allow the coalesced final render
457
396
  building = false;
458
- // `pager` is the page sizes to offer, the first one being the initial
397
+ // `pager` = page sizes to offer; first is initial
459
398
  if (opts.pager) {
460
399
  const sizes = Array.isArray(opts.pager) ? opts.pager : [10, 25, 50, 100];
461
400
  sync = addPaginate(el, nAll, sizes, nRow, state, () => refresh(false));
462
401
  refresh(); // cut the full render down to the first page
463
402
  } else if (state.sort.length || opts.detail || dirty) {
464
- // core rendered the rows in file order; re-render to apply an initial
465
- // sort, a seeded filter (`dirty`), and/or to add the expand carets
403
+ // core rendered file order; re-render for initial sort, seeded filter
404
+ // (`dirty`), and/or expand carets
466
405
  refresh();
467
406
  }
468
407
  }
469
408
 
470
- // A search input: `type="search"` lets the browser supply the affordance (and
471
- // a clear button), so there is no icon or placeholder text to translate; the
472
- // label is for screen readers only.
409
+ // `type="search"` gives the browser's affordance and clear button, so no icon
410
+ // or translatable placeholder; label is for screen readers.
473
411
  function searchInput(doc, label) {
474
412
  return elem(doc, "input", {
475
413
  type: "search", className: "lti-search", "aria-label": label
476
414
  });
477
415
  }
478
416
 
479
- // A full-width row of the table, for a control that belongs to the table as a
480
- // whole. Living inside the table (instead of beside it) is what keeps the
481
- // controls exactly as wide as the table, however narrow that is, and keeps
482
- // everything inside the core `.lt-wrap` scroll box. Returns its single cell.
417
+ // Full-width table row for a table-wide control. Inside the table keeps it as
418
+ // wide as the table and inside the `.lt-wrap` scroll box. Returns its cell.
483
419
  function fullRow(sect, cls, nCol, pos) {
484
420
  const row = sect.insertRow(pos);
485
421
  row.className = cls;
486
422
  return elem(sect.ownerDocument, "td", { colSpan: nCol }, row);
487
423
  }
488
424
 
489
- // Run `fn` (which reads its own live state) only after `ms` of quiet; `.now()`
490
- // flushes a pending call at once (Enter, drag end). Used by the search/filter
491
- // boxes and the range slider.
425
+ // Run `fn` (reads its own live state) after `ms` of quiet; `.now()` flushes at
426
+ // once (Enter, drag end). Used by search/filter boxes and slider.
492
427
  function debounce(fn, ms = 400) {
493
428
  let timer;
494
429
  const run = () => { clearTimeout(timer); timer = setTimeout(fn, ms); };
@@ -496,12 +431,11 @@
496
431
  return run;
497
432
  }
498
433
 
499
- // Wrap a synchronous, page-freezing render so a slow one shows a busy state
500
- // (.lti-busy on `wrap`: wait cursor + dimmed body). The busy class can only
501
- // paint if set *before* the blocking pass, so predict from the previous call's
502
- // cost: run inline unless the last run was over BUSY_MS. `run(arg)` does the
503
- // work; the returned function forwards its argument. Shared by view recomputes
504
- // (search, sort, filter, external predicates) and row-detail toggles.
434
+ // Show a busy state (.lti-busy on `wrap`) for slow synchronous renders. Class
435
+ // paints only if set *before* the blocking pass, so predict from the previous
436
+ // cost: run inline unless last run exceeded BUSY_MS. `run(arg)` does the work;
437
+ // the returned function forwards its arg. Used by view recomputes and detail
438
+ // toggles.
505
439
  function busyRender(wrap, run) {
506
440
  const BUSY_MS = 120;
507
441
  let frame, lastCost = 0;
@@ -520,33 +454,30 @@
520
454
  };
521
455
  }
522
456
 
523
- // Debounce typing so a long list is not re-rendered per keystroke; Enter (or
524
- // leaving the box) applies at once. Longer than the default debounce: a filter
525
- // recompute is far heavier than a slider nudge, so wait out a typist's gaps.
457
+ // Debounce typing; Enter or blur applies at once. Longer than default: filter
458
+ // recompute is far heavier than a slider nudge.
526
459
  function onType(input, apply) {
527
460
  const go = debounce(() => apply(input.value), 1000);
528
461
  input.oninput = go;
529
462
  input.onchange = go.now;
530
463
  }
531
464
 
532
- // Table-wide search box, appended to the shared head cell.
465
+ // Table-wide search box in the shared head cell.
533
466
  function addSearch(cell, el, state, refresh) {
534
467
  const input = cell.appendChild(searchInput(el.ownerDocument, "Search"));
535
468
  onType(input, v => { state.term = v; refresh(); });
536
469
  }
537
470
 
538
- // Escape one value for a CSV field: wrap in quotes (doubling any inside) only
539
- // when it holds a comma, quote, or newline, so plain values stay bare.
471
+ // CSV-escape: quote (doubling quotes) only if comma, quote, or newline.
540
472
  function csvField(v) {
541
473
  const s = v == null ? "" : String(v);
542
474
  return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
543
475
  }
544
476
 
545
- // A button that downloads the current view (every row the filters and search
546
- // keep, across all pages — `el._lt.view()`) as a CSV file. `opt` is the file
547
- // name or `{file?, mode?}`; `mode: "raw"` exports the raw values (`spec.data`)
548
- // instead of the displayed text (`spec._display`). Group columns (null in
549
- // `cols`) are skipped. No library: a Blob and an <a>.
477
+ // Button downloading the current view (all pages, `el._lt.view()`) as CSV.
478
+ // `opt` = file name or `{file?, mode?}`; `mode: "raw"` exports `spec.data`
479
+ // instead of displayed text (`spec._display`). Skips group columns (null in
480
+ // `cols`). Uses Blob + <a>, no library.
550
481
  function addDownload(cell, el, spec, cols, labels, opt) {
551
482
  const doc = el.ownerDocument,
552
483
  o = typeof opt === "object" ? opt : { file: opt },
@@ -570,25 +501,22 @@
570
501
  };
571
502
  }
572
503
 
573
- // Advance one column through asc → desc → unsorted, updating `state.sort` (an
574
- // ordered list of `{col, dir}` keys). A plain click sorts by that column
575
- // alone; a shift-click adds it as a further tie-breaker (or re-cycles it where
576
- // it already is), so several columns can sort together.
504
+ // Cycle a column asc -> desc -> unsorted in `state.sort`. Plain click sorts by
505
+ // it alone; shift-click adds a tie-breaker (or re-cycles it in place).
577
506
  function cycle(state, col, additive) {
578
507
  const order = (state.sort || []).slice(),
579
508
  i = order.findIndex(k => k.col === col),
580
509
  dir = i < 0 ? "asc" : order[i].dir === "asc" ? "desc" : null;
581
510
  if (!additive) { state.sort = dir ? [{ col, dir }] : []; return; }
582
- if (i < 0) order.push({ col, dir }); // dir is "asc" here
511
+ if (i < 0) order.push({ col, dir }); // "asc" here
583
512
  else if (dir) order[i] = { col, dir };
584
513
  else order.splice(i, 1);
585
514
  state.sort = order;
586
515
  }
587
516
 
588
- // Click-to-sort headers (shift-click to sort by several at once). The
589
- // indicators and aria-sort live on the <th>s, which survive the <tbody> swap,
590
- // so repainting them needs no re-render. An ordinal (₁ ₂ …) marks each key's
591
- // place when more than one column sorts.
517
+ // Click-to-sort headers (shift-click for several). Indicators and aria-sort
518
+ // live on <th>s, which survive the <tbody> swap, so repaint needs no re-render.
519
+ // Ordinals (₁ ₂ …) mark key order when several sort.
592
520
  function addSort(hrow, cols, state, refresh) {
593
521
  const doc = hrow.ownerDocument, marks = {};
594
522
  const paint = () => {
@@ -609,31 +537,25 @@
609
537
  const col = cols[ci];
610
538
  if (col == null) return;
611
539
  th.classList.add("lti-sortable");
612
- // sort on the label only, not the whole cell, so the resize grip (a <th>
613
- // child outside the label) stays unclickable for sorting
540
+ // label only, so the resize grip (outside it) doesn't sort
614
541
  const lab = elem(doc, "span", { className: "lti-label" }, th);
615
542
  while (th.firstChild !== lab) lab.append(th.firstChild);
616
543
  marks[col] = { th, ind: elem(doc, "span", { className: "lti-sort" }, lab) };
617
544
  lab.onclick = e => { cycle(state, col, e.shiftKey); paint(); refresh(); };
618
545
  });
619
- paint(); // reflect any initial sort carried on the spec
546
+ paint(); // reflect initial sort
620
547
  }
621
548
 
622
- // A row of per-column filters below the headers, inside <thead> so the <tbody>
623
- // swap leaves it (and what has been typed into it) alone. `flt` is the
624
- // normalized { default?, cols? }: each visible column takes its named spec, or
625
- // the default when unnamed. A `true` spec is a plain search box; a typed spec
626
- // is a funnel + popover under the header (see typedFilter).
549
+ // Per-column filter row below headers, in <thead> so the <tbody> swap keeps it
550
+ // and typed input. `flt` = normalized { default?, cols? }: named spec else
551
+ // default. `true` = plain box; typed = funnel + popover (see typedFilter).
627
552
  function addFilter(hrow, cols, flt, data, state, refresh, nGroup = 0) {
628
553
  const doc = hrow.ownerDocument,
629
554
  row = elem(doc, "tr", { className: "lti-filters" }),
630
555
  def = flt.default, explicit = flt.cols || {};
631
- // leading rowspan group columns carry no filter, but their cells must still
632
- // be present so each data column's box lines up under its own header
556
+ // group columns get no filter but need cells so boxes line up under headers
633
557
  for (let i = 0; i < nGroup; i++) elem(doc, "td", {}, row);
634
- // mirror each column's alignment onto its filter cell, so a funnel sits under
635
- // the header's text (e.g. right-aligned for a numeric column), read off the
636
- // header cells, which line up with `cols`
558
+ // copy header alignment onto filter cells so funnels sit under header text
637
559
  const hCells = dataCells(hrow);
638
560
  cols.forEach((c, ci) => {
639
561
  const al = ["al-r", "al-c"].find(k => hCells[ci]?.classList.contains(k)),
@@ -649,32 +571,25 @@
649
571
  hrow.after(row);
650
572
  }
651
573
 
652
- // Filterable only if the column holds some non-blank value; a plot-only `into`
653
- // column (no data array) has nothing to match, so gets no box.
574
+ // Filterable only with a non-blank value; plot-only `into` columns have no data.
654
575
  const filterable = (data, col) => {
655
576
  const a = data && data[col];
656
577
  return Array.isArray(a) && a.some(v => v != null && v !== "");
657
578
  };
658
579
 
659
- // Expandable row detail. `detailOpt` is either an array of column names (the
660
- // detail is a one-row table of those columns' displayed values) or a callback
661
- // `(rawRow, index, displayedRow) => spec` (or the name of such a global one),
662
- // called the first time a row is expanded (and cached) to build the spec for
663
- // its drop-down detail table. Returns a
664
- // `decorate(body, rows)` that each <tbody> re-render runs: it prepends an
665
- // expand caret to every row and, after each open row, inserts a full-width
666
- // detail row rendered through LT.render (so a detail table can itself be
667
- // interactive). Expanded rows are tracked by their original index, so detail
668
- // follows its row across sort/filter/page. Resolving `detailOpt` is deferred
669
- // to the first expand, so a global built after the table still works.
580
+ // Expandable row detail. `detailOpt` = array of column names (one-row table of
581
+ // their displayed values) or callback `(rawRow, index, displayedRow) => spec`
582
+ // (or global name), called on first expand and cached. Returns
583
+ // `decorate(body, rows)`, run per <tbody> render: prepends an expand caret per
584
+ // row and inserts a full-width detail row (via LT.render, so it can itself be
585
+ // interactive) after open rows. Expanded rows tracked by original index, so
586
+ // detail follows its row. `detailOpt` resolves lazily, so late globals work.
670
587
  function addDetail(el, spec, nCol, state, detailOpt, rerender) {
671
- // `nCol` is the table's full width, so the detail row spans the leading
672
- // rowspan group columns too
588
+ // `nCol` = full width, incl. group columns
673
589
  const doc = el.ownerDocument, cache = {};
674
590
  state.expanded = new Set();
675
- // a row as an object keyed by column (every column, including ones hidden
676
- // from the table), built from `src`: spec.data gives raw values, spec._display
677
- // the formatted text the table shows
591
+ // Row as {col: value} (all columns, incl. hidden) from `src`: spec.data =
592
+ // raw, spec._display = formatted
678
593
  const pick = (src, r) => {
679
594
  const o = {}; for (const c in src) o[c] = src[c]?.[r - 1] ?? null; return o;
680
595
  };
@@ -683,27 +598,25 @@
683
598
  const disp = pick(spec._display || {}, r);
684
599
  let out = null;
685
600
  if (Array.isArray(detailOpt)) {
686
- // a list of column names: show those columns' displayed values as a
687
- // one-row table (the columns can be ones hidden from the main table)
601
+ // column names: one-row table of displayed values (may be hidden columns)
688
602
  const data = {};
689
603
  for (const c of detailOpt) data[c] = [disp[c] ?? null];
690
604
  out = { data };
691
605
  } else {
692
- // a callback (or the name of one): (raw row, index, displayed row)
606
+ // callback or its global name
693
607
  const fn = typeof detailOpt === "function" ? detailOpt : root[detailOpt];
694
608
  if (typeof fn === "function") out = fn(pick(spec.data || {}, r), r, disp);
695
609
  }
696
610
  return cache[r] = out;
697
611
  };
698
- // a slow render (a large detail table, or a full rebuild on reset) shows a
699
- // busy state; `busy(fn)` runs `fn` through it
612
+ // slow renders (big detail, reset rebuild) show busy state via `busy(fn)`
700
613
  const wrap = el.closest(".lt-wrap"), busy = busyRender(wrap, fn => fn());
701
614
  const setCaret = (btn, open) => {
702
615
  btn.textContent = open ? "▾" : "▸";
703
616
  btn.setAttribute("aria-expanded", String(open));
704
617
  };
705
- // build a row's detail once, inserted hidden after its <tr>; the row stays in
706
- // the DOM and the caret toggles visibility. null if the callback yields none.
618
+ // Build detail once, hidden after its <tr>; caret toggles visibility. null if
619
+ // callback yields none.
707
620
  const openDetail = (tr, r) => {
708
621
  const child = build(r);
709
622
  if (!child) return null;
@@ -716,33 +629,30 @@
716
629
  const d = tr.nextElementSibling;
717
630
  return d?.classList.contains("lti-detail") ? d : openDetail(tr, r);
718
631
  };
719
- // the table's base width (no detail shown), captured each render by presize
632
+ // base width (no detail), captured per render by presize
720
633
  let baseW = 0;
721
- // Grow the table's explicit `width` (not min-width, so a wrapping container's
722
- // max-width still caps it) to fit a just-shown detail wider than the base
723
- // width. Width only grows, so a wide detail widens the table once and
724
- // reopening it never jumps again.
634
+ // Grow explicit `width` (not min-width, so container max-width still caps) to
635
+ // fit a wider detail. Only grows: reopening never jumps.
725
636
  const grow = () => {
726
637
  const w = Math.ceil(el.getBoundingClientRect().width);
727
638
  if (w > baseW && w > (parseFloat(el.style.width) || 0)) el.style.width = w + "px";
728
639
  };
729
- // toggle one row in place: just flip the (already built) detail's visibility.
640
+ // toggle: flip the built detail's visibility
730
641
  const toggle = (tr, btn, r) => {
731
642
  const open = state.expanded.has(r);
732
643
  open ? state.expanded.delete(r) : state.expanded.add(r);
733
644
  setCaret(btn, !open);
734
645
  const d = ensureDetail(tr, r);
735
646
  if (!d) return;
736
- d.hidden = open; // was open -> hide; was closed -> show
737
- if (!open) grow(); // a newly shown detail may be wider than the table
647
+ d.hidden = open;
648
+ if (!open) grow(); // may be wider than table
738
649
  };
739
- // Pre-size the table from its first row detail so a typical expand never
740
- // jumps the width: at idle, open just the first detail to measure, re-hide
741
- // it, and grow the table to it. Other details stay deferred; a wider one
742
- // grows the table when first opened (see grow). Re-run per <tbody> render.
650
+ // Pre-size from the first detail so typical expands don't jump width: at idle,
651
+ // open it to measure, re-hide, grow table. Others stay deferred (grow on first
652
+ // open). Re-runs per <tbody> render.
743
653
  const win = doc.defaultView, idle = win.requestIdleCallback || win.setTimeout;
744
654
  const presize = (body) => idle(() => {
745
- if (!body.isConnected) return; // a newer render replaced it
655
+ if (!body.isConnected) return; // replaced by newer render
746
656
  el.style.width = "";
747
657
  baseW = el.getBoundingClientRect().width;
748
658
  const c = $(body, ".lti-expand[aria-expanded='false']");
@@ -754,9 +664,8 @@
754
664
  const decorate = (body, rows) => {
755
665
  [...body.rows].forEach((tr, i) => {
756
666
  const r = rows[i];
757
- if (typeof r !== "number") return; // a separator group-header row
758
- // the first data cell (past any leading rowspan group cell), so the caret
759
- // sits in the row's own first column, not a group label
667
+ if (typeof r !== "number") return; // group-header row
668
+ // first data cell (past group cells): caret goes in row's own first column
760
669
  const td0 = dataCells(tr)[0], open = state.expanded.has(r);
761
670
  if (!td0) return;
762
671
  const btn = elem(doc, "button", {
@@ -769,9 +678,8 @@
769
678
  });
770
679
  presize(body);
771
680
  };
772
- // drop a row's cached detail (or every row's) and re-render, so the callback
773
- // re-runs and the detail — and its own sort/filter state — rebuilds fresh,
774
- // e.g. after a caller's widget changes what the callback returns.
681
+ // Drop cached detail (one row or all) and re-render; callback re-runs and
682
+ // detail (with its sort/filter state) rebuilds.
775
683
  decorate.reset = r => {
776
684
  if (r == null) for (const k in cache) delete cache[k];
777
685
  else delete cache[r];
@@ -780,30 +688,26 @@
780
688
  return decorate;
781
689
  }
782
690
 
783
- // The table's <colgroup>, created when core emitted none (it only does so for
784
- // a table given explicit widths on the R side). It gets `nGroup` leading <col>s
785
- // for the rowspan group columns (which lead each header/body row) then one per
786
- // data column, matching core's own layout so widths line up.
691
+ // Table <colgroup>, created if core emitted none (only with explicit R widths):
692
+ // `nGroup` leading <col>s for rowspan group columns, then one per data column,
693
+ // matching core's layout.
787
694
  function colGroup(el, nCol, nGroup = 0) {
788
695
  let g = $(el, "colgroup");
789
696
  if (!g) {
790
697
  const doc = el.ownerDocument;
791
698
  g = elem(doc, "colgroup");
792
699
  for (let i = 0; i < nGroup + nCol; i++) elem(doc, "col", {}, g);
793
- // <colgroup> comes after <caption> (the title), before <thead>
700
+ // after <caption>, before <thead>
794
701
  el.caption ? el.caption.after(g) : el.prepend(g);
795
702
  }
796
703
  return [...g.children];
797
704
  }
798
705
 
799
- // Fixed-layout machinery for column resize. The widths live on the
800
- // <colgroup>, outside <tbody>, so they survive every
801
- // re-render. `freeze()` switches the table to fixed layout once, pinning every
802
- // column at the width it has then, so a later width change moves that one
803
- // column instead of reflowing the whole table. `natural(i)` is column i's
804
- // content width (an unconstrained reflow, with the widths put back after).
805
- // `setWidth(i, w, min)` sets column i to `w` px (clamped to `min`), widening or
806
- // narrowing the table by as much; the other columns keep their widths.
706
+ // Fixed layout for column resize. Widths live on <colgroup> (outside <tbody>),
707
+ // surviving re-renders. `freeze()` pins every column at its current width once,
708
+ // so later changes move one column without reflow. `natural(i)` = column i's
709
+ // content width (unconstrained reflow, widths restored). `setWidth(i, w, min)`
710
+ // sets column i to `w` px (>= `min`), resizing the table by the difference.
807
711
  function fixedLayout(el, hrow, nCol, nGroup = 0) {
808
712
  const ths = [...$$(hrow, "th")],
809
713
  cs = colGroup(el, nCol, nGroup), wOf = e => e.getBoundingClientRect().width;
@@ -831,14 +735,12 @@
831
735
  el.style.width =
832
736
  `${parseFloat(el.style.width) + parseFloat(cs[i].style.width) - old}px`;
833
737
  };
834
- // `dataCs` drops the leading group <col>s, so a data-column consumer (the
835
- // column-hide menu) indexes it by data-column position
738
+ // `dataCs` drops group <col>s: index by data-column position
836
739
  return { ths, cs, dataCs: cs.slice(nGroup), freeze, natural, setWidth };
837
740
  }
838
741
 
839
- // Drag-to-resize column edges: a grip on the right edge of each header cell.
840
- // On the first drag the table switches to fixed layout (see fixedLayout) so
841
- // that dragging one edge moves it alone. A double-click fits the column to its
742
+ // Drag-to-resize: grip on each header's right edge. First drag switches to
743
+ // fixed layout (see fixedLayout) so one edge moves alone. Double-click fits
842
744
  // content.
843
745
  function addResize(el, layout) {
844
746
  const doc = el.ownerDocument, { ths, cs, freeze, natural, setWidth } = layout;
@@ -854,49 +756,41 @@
854
756
  freeze();
855
757
  const x0 = e.clientX, w0 = parseFloat(cs[i].style.width);
856
758
  el.classList.add("lti-resizing");
857
- // no label floor: omit setWidth's min arg to take its default, and the
858
- // cell clips its overflow (CSS) instead of spilling when shrunk
759
+ // default min width; CSS clips overflow when shrunk
859
760
  drag(e, ev => setWidth(i, w0 + ev.clientX - x0),
860
761
  () => el.classList.remove("lti-resizing"));
861
762
  };
862
763
  });
863
764
  }
864
765
 
865
- // Column-visibility menu: an eye button at the start of the head cell that
866
- // opens a checklist, one box per column. Unchecking a column hides it
867
- // outright — its header and every body cell take the `hidden` attribute (which
868
- // a <tbody> swap drops, so it is re-applied via postSwap). Every column is
869
- // listed; `opt` is `true` (all start shown) or `{ hidden: [...] }` (those names
870
- // start hidden). `layout` is resize's fixed layout, used when present to drop a
871
- // hidden column's <col> so the fixed table reflows too.
766
+ // Column-visibility menu: eye button opening a checklist, one box per column.
767
+ // Unchecking sets `hidden` on the header and body cells (a <tbody> swap drops
768
+ // it, so postSwap re-applies). `opt` = `true` (all shown) or `{ hidden: [...] }`
769
+ // (start hidden). `layout` (resize) also hides the <col> so a fixed table reflows.
872
770
  function addColumnToggle(cell, el, hrow, cols, labels, opt, layout, postSwap) {
873
771
  const doc = el.ownerDocument,
874
772
  start = (opt && opt.hidden) || [], hidden = new Set();
875
- // show/hide column i's cell in one row (indexing the row's data cells, past
876
- // any leading rowspan group cell), skipping the single colspan cell of a
877
- // detail or empty row (which spans every column and is no column's own)
773
+ // Show/hide column i's cell in a row (data-cell index), skipping the colspan
774
+ // cell of detail/empty rows (no column's own)
878
775
  const setCell = (tr, i, on) => {
879
776
  const c = dataCells(tr)[i];
880
777
  if (c && c.colSpan === 1) c.hidden = on;
881
778
  };
882
- // re-hide every hidden column's cells on each freshly-built <tbody>
779
+ // re-hide on each new <tbody>
883
780
  postSwap.push(body => hidden.forEach(i => {
884
781
  for (const tr of body.rows) setCell(tr, i, true);
885
782
  }));
886
- // The spanner row merges cells, so column i is not at cell index i there as
887
- // in every other row; handle it separately (applySpan). Map each spanner-row
888
- // cell to the column range it covers (skipping the leading row-group
889
- // placeholders): hide a plain colspan-1 slot outright, and shrink a real
890
- // spanner's colSpan — hiding it only once all its columns are gone — so the
891
- // spanners stay aligned with the body as columns come and go.
783
+ // Spanner row merges cells, so column i isn't cell i there; handled by
784
+ // applySpan. Map each spanner cell to its column range (skipping row-group
785
+ // placeholders): hide a colspan-1 slot outright; shrink a real spanner's
786
+ // colSpan, hiding it only when all its columns are gone.
892
787
  const nGrp = [...hrow.children].length - dataCells(hrow).length,
893
788
  spanRow = [...el.rows].find(tr => tr.classList.contains("lt-spanner-row")),
894
789
  spanCells = spanRow ? dataCells(spanRow).slice(nGrp) : [];
895
790
  let col0 = 0;
896
791
  spanCells.forEach(c => { c._span = c.colSpan; c._start = col0; col0 += c._span; });
897
- // Recompute every spanner cell from the current `hidden` set (idempotent, so
898
- // it is safe to call on each apply): a real spanner's colSpan is its columns
899
- // still showing, and it vanishes once all are hidden.
792
+ // Recompute spanner cells from `hidden` (idempotent): colSpan = columns still
793
+ // showing; hidden when none.
900
794
  const applySpan = () => {
901
795
  for (const c of spanCells) {
902
796
  let gone = 0;
@@ -905,13 +799,10 @@
905
799
  c.hidden = gone >= c._span;
906
800
  }
907
801
  };
908
- // show/hide column i everywhere it lives: the <col> (fixed layout only) and,
909
- // one row at a time, every per-column cell — the header labels, the filter
910
- // boxes, the body cells, and a plot's axis footer, plus the spanner row via
911
- // applySpan. The setCell colspan guard skips the other full-width rows
912
- // (search bar, detail, footnotes, pager). <thead>/<tfoot> survive a <tbody>
913
- // swap, so this one pass keeps them in sync; only the fresh <tbody> is
914
- // re-hidden (via postSwap).
802
+ // Show/hide column i everywhere: <col> (fixed layout only) and per-column
803
+ // cells (headers, filters, body, plot axis footer), plus spanners via
804
+ // applySpan. setCell's colspan guard skips other full-width rows. <thead>/
805
+ // <tfoot> survive a <tbody> swap; only a fresh <tbody> needs postSwap.
915
806
  const apply = i => {
916
807
  const on = hidden.has(i);
917
808
  if (layout?.dataCs[i]) layout.dataCs[i].hidden = on;
@@ -925,7 +816,7 @@
925
816
  "aria-label": "Show or hide columns", "aria-expanded": "false"
926
817
  }, wrap),
927
818
  menu = elem(doc, "div", { className: "lti-menu", hidden: true }, wrap);
928
- // one checkbox per column; `sub` indents it under a spanner group header
819
+ // checkbox per column; `sub` indents under a spanner header
929
820
  const addBox = (i, sub) => {
930
821
  const c = cols[i];
931
822
  if (c == null) return;
@@ -938,17 +829,16 @@
938
829
  apply(i);
939
830
  };
940
831
  };
941
- // Group the checkboxes under their spanners: the same column label can repeat
942
- // across spanners (e.g. auto-span's "Sepal.Length"/"Petal.Length" both show as
943
- // "Length"), so a flat list would be ambiguous. Walk the spanner row, emitting
944
- // a group header before a real spanner's columns and listing a non-spanned
945
- // column on its own. With no spanner row, list columns flat.
832
+ // Group boxes under spanners: labels can repeat across spanners (auto-span's
833
+ // "Sepal.Length"/"Petal.Length" both show "Length"), so flat is ambiguous.
834
+ // Walk the spanner row: group header before a real spanner's columns; unspanned
835
+ // columns alone. No spanner row: flat.
946
836
  if (spanCells.length) for (const c of spanCells) {
947
837
  const span = c.classList.contains("lt-spanner");
948
838
  if (span) elem(doc, "div", { className: "lti-group", textContent: c.textContent }, menu);
949
839
  for (let i = c._start; i < c._start + c._span; i++) addBox(i, span);
950
840
  } else cols.forEach((_, i) => addBox(i));
951
- cols.forEach((_, i) => apply(i)); // reflect any columns that start hidden
841
+ cols.forEach((_, i) => apply(i)); // apply initially hidden columns
952
842
  const open = on => {
953
843
  menu.hidden = !on;
954
844
  btn.setAttribute("aria-expanded", String(on));
@@ -958,20 +848,16 @@
958
848
  on(doc, "keydown", e => { if (e.key === "Escape") open(false); });
959
849
  }
960
850
 
961
- // --- Typed column filters (the `filter` named-list form). A typed spec is
851
+ // --- Typed column filters (`filter` named-list form). A typed spec is
962
852
  // {type:"select"|"range"|"checklist", label?, choices?, min?, max?, step?,
963
- // value?, selected?}; it renders as a funnel + popover, under its own header
964
- // when the column is visible or as a labelled head-bar chip when it is hidden
965
- // (the column still travels in spec.data, which is what computeView filters
966
- // on). The popover holds an expression box AND a widget (a value dropdown, a
967
- // range slider, or a checklist of values); both edit the one filter term for
968
- // that column (state.filters[col]) and stay in sync, so the widget is a
969
- // friendly face on the same expression a
970
- // reader could type.
853
+ // value?, selected?}, rendered as a funnel + popover under its header (visible
854
+ // column) or a labeled head-bar chip (hidden; its data is still in spec.data,
855
+ // which computeView filters). The popover holds an expression box AND a widget
856
+ // (dropdown, slider, or checklist) editing the same term (state.filters[col]),
857
+ // kept in sync: the widget is a friendly face on a typeable expression.
971
858
 
972
- // A filter term string <-> a widget value, per type. A `null` parse means the
973
- // term is something the widget can't show (a hand-typed expression), so the
974
- // widget falls back to neutral and the box stays authoritative.
859
+ // Filter term <-> widget value, per type. `null` parse = a hand-typed term the
860
+ // widget can't show: widget goes neutral, box stays authoritative.
975
861
  const selExpr = v => v === "" ? "" : `x == ${JSON.stringify(String(v))}`,
976
862
  selParse = s => {
977
863
  const m = /^\s*x\s*==\s*(['"])([\s\S]*)\1\s*$/.exec(s || "");
@@ -983,8 +869,8 @@
983
869
  const m = /^\s*x\s*>=\s*(-?[\d.]+)\s*&&\s*x\s*<=\s*(-?[\d.]+)\s*$/.exec(s || "");
984
870
  return m ? [parseFloat(m[1]), parseFloat(m[2])] : null;
985
871
  },
986
- // a set filter keeps rows whose value is one of the checked ones; every
987
- // choice checked -> "" (no filter), none -> "[].includes(x)" (no rows)
872
+ // keeps rows whose value is checked; all checked -> "" (no filter), none ->
873
+ // "[].includes(x)" (no rows)
988
874
  setExpr = (sel, all) =>
989
875
  sel.length === all.length ? "" : `${JSON.stringify(sel.map(String))}.includes(x)`,
990
876
  setParse = s => {
@@ -993,9 +879,8 @@
993
879
  try { return JSON.parse(m[1]); } catch (e) { return null; }
994
880
  };
995
881
 
996
- // A "nice" slider step for a data span: the 1/2/5 x 10^k value nearest ~1% of
997
- // the span (so ~50-100 increments), like pretty()'s tick spacing. An integer
998
- // column rounds up to a whole step. Degenerate spans fall back to a tenth / 1.
882
+ // "Nice" slider step: 1/2/5 x 10^k nearest ~1% of span (~50-100 increments),
883
+ // like pretty(). Integer columns round to a whole step. Degenerate span: 0.1 / 1.
999
884
  function niceStep(span, integer) {
1000
885
  if (!(span > 0) || !isFinite(span)) return integer ? 1 : 0.1;
1001
886
  const raw = span / 100, mag = Math.pow(10, Math.floor(Math.log10(raw)));
@@ -1003,9 +888,9 @@
1003
888
  return integer ? Math.max(1, Math.round(step)) : step;
1004
889
  }
1005
890
 
1006
- // Fill a typed spec's choices (select) or min/max/step (range) from the
1007
- // column's data when the R side left them out, so `filter = list(x = "select")`
1008
- // or `list(x = "range")` needs no enumeration or bounds. Returns a filled copy.
891
+ // Fill a typed spec's choices (select) or min/max/step (range) from column data
892
+ // when R omitted them, so `list(x = "select")` / `"range"` needs no bounds.
893
+ // Returns a copy.
1009
894
  function resolveSpec(spec, column) {
1010
895
  if (spec.type === "select" || spec.type === "checklist") {
1011
896
  let choices = spec.choices;
@@ -1016,9 +901,8 @@
1016
901
  ? a - b : String(a).localeCompare(String(b)));
1017
902
  choices = vals.map(v => ({ value: String(v), label: String(v) }));
1018
903
  }
1019
- // a select offers a leading blank "no filter" choice, so it shows every
1020
- // row until the reader picks a value; a checklist starts with every box
1021
- // checked (which is itself "no filter"), so it needs no blank
904
+ // select gets a leading blank "no filter" choice; checklist starts all
905
+ // checked (also "no filter"), so needs none
1022
906
  if (spec.type === "select" && !choices.some(o => o.value === ""))
1023
907
  choices = [{ value: "", label: "" }, ...choices];
1024
908
  return { ...spec, choices };
@@ -1038,16 +922,15 @@
1038
922
  }
1039
923
  const loB = min != null ? min : lo, hiB = max != null ? max : hi;
1040
924
  if (step == null) step = niceStep(hiB - loB, allInt);
1041
- // round() clears float dust from the arithmetic below; the derived endpoints
1042
- // snap out to whole steps so they are round and bracket the data (the extreme
1043
- // rows stay inside, so none is dropped to float rounding or a step mismatch)
925
+ // tidy() clears float dust; derived endpoints snap outward to whole steps so
926
+ // they bracket the data (extreme rows aren't dropped)
1044
927
  const tidy = x => Math.round(x * 1e9) / 1e9;
1045
928
  if (min == null) min = tidy(Math.floor(lo / step) * step);
1046
929
  if (max == null) max = tidy(Math.ceil(hi / step) * step);
1047
930
  return { ...spec, min, max, step };
1048
931
  }
1049
932
 
1050
- // A dropdown of {value, label} options; `onInput(value)` fires on change.
933
+ // Dropdown of {value, label}; `onInput(value)` on change.
1051
934
  function makeSelect(doc, options, onInput) {
1052
935
  const sel = elem(doc, "select", { className: "lti-filter-pick" });
1053
936
  options.forEach(o => elem(doc, "option", { value: o.value, textContent: o.label }, sel));
@@ -1055,11 +938,10 @@
1055
938
  return { el: sel, set: v => sel.value = v };
1056
939
  }
1057
940
 
1058
- // A list of {value, label} checkboxes (every box starts checked); `onInput`
1059
- // fires with the array of checked values on any change. Returns
1060
- // { el: [<label>...], set(values) }. Exposed on LT.ui so a caller can drop a
1061
- // checklist control into its own popover (e.g. forestly's treatment-group
1062
- // picker in the control bar) and reuse it as the checklist filter's widget.
941
+ // {value, label} checkboxes (all start checked); `onInput` gets the checked
942
+ // values on change. Returns { el: [<label>...], set(values) }. On LT.ui so
943
+ // callers can reuse it in their own popover (e.g. forestly's treatment-group
944
+ // picker).
1063
945
  function makeChecklist(doc, options, onInput) {
1064
946
  const boxes = options.map(o => {
1065
947
  const label = elem(doc, "label", { className: "lti-check" }),
@@ -1075,12 +957,10 @@
1075
957
  };
1076
958
  }
1077
959
 
1078
- // A control-bar chip: a label, the caller's control (a funnel popover) dropped
1079
- // in, and a value-summary slot. `mark(on)` toggles the active highlight (color
1080
- // only, no reflow); `summarize(text)` sets the readout. Returns { el, mark,
1081
- // summarize }. The typed-filter chips use it, and it is exposed on LT.ui so a
1082
- // caller building its own control-bar widget (e.g. forestly's treatment-group
1083
- // picker) gets the same chip rather than hand-rolling the DOM.
960
+ // Control-bar chip: label, caller's control (funnel popover), summary slot.
961
+ // `mark(on)` toggles active highlight (color only); `summarize(text)` sets the
962
+ // readout. Returns { el, mark, summarize }. Used by typed-filter chips; on
963
+ // LT.ui so callers (e.g. forestly) share it.
1084
964
  function makeChip(doc, label, control) {
1085
965
  const el = elem(doc, "span", { className: "lti-chip" });
1086
966
  elem(doc, "span", { className: "lti-chip-name", textContent: label }, el);
@@ -1093,12 +973,10 @@
1093
973
  };
1094
974
  }
1095
975
 
1096
- // A two-thumb range slider from a track, a fill band, and two <button> thumbs —
1097
- // no native <input type=range>, so no vendor pseudo-element CSS and no stacked-
1098
- // input z-index hacks. Thumbs drag via the shared drag() helper and step with
1099
- // the arrow keys (Home/End jump to the ends); the low thumb never passes the
1100
- // high one. `cfg` is {min, max, step}; `onInput([lo, hi])` fires as a thumb
1101
- // moves. Returns { el, set([lo, hi]) }.
976
+ // Two-thumb range slider: track, fill, two <button> thumbs. Avoids native
977
+ // <input type=range> (vendor CSS, stacked-input z-index hacks). Thumbs drag via
978
+ // drag(), arrow keys step, Home/End jump; low never passes high. `cfg` =
979
+ // {min, max, step}; `onInput([lo, hi])` fires on commit. Returns { el, set([lo, hi]) }.
1102
980
  function makeSlider(doc, cfg, onInput, onMove) {
1103
981
  const min = cfg.min, max = cfg.max, span = max - min || 1,
1104
982
  step = cfg.step || span / 100,
@@ -1110,15 +988,12 @@
1110
988
  }, track),
1111
989
  thumbs = [mk("Minimum"), mk("Maximum")];
1112
990
  let val = [min, max];
1113
- // paint() tracks the thumb live; the onInput filter never fires mid-drag. A
1114
- // live filter re-flows the table (and shifts the chip the thumb lives in)
1115
- // out from under the cursor, so a mouse drag only commits on release
1116
- // (fire.now via onEnd). Arrow keys repaint live too but only debounce the
1117
- // filter — no commit on key-up — so stepping several times quickly (or an
1118
- // autorepeat) batches into one filter rather than re-filtering per step.
991
+ // paint() tracks live; onInput never fires mid-drag (a live filter reflows
992
+ // the table and shifts the chip under the cursor), so drag commits on release
993
+ // (fire.now via onEnd). Arrow keys repaint live but only debounce the filter,
994
+ // batching rapid steps/autorepeat.
1119
995
  const fire = debounce(() => onInput(val.slice())),
1120
- // a no-op gesture (a bare thumb click, or an arrow key at an end) leaves
1121
- // the range untouched, so only fire the filter when `val` actually moved
996
+ // fire only if `val` moved (not a bare click or arrow at an end)
1122
997
  changed = from => val[0] !== from[0] || val[1] !== from[1];
1123
998
  const pct = v => (v - min) / span * 100,
1124
999
  snap = v => {
@@ -1133,19 +1008,18 @@
1133
1008
  fill.style.left = pct(val[0]) + "%";
1134
1009
  fill.style.right = `${100 - pct(val[1])}%`;
1135
1010
  },
1136
- move = (i, v) => { // update + repaint a thumb, without filtering
1011
+ move = (i, v) => { // update + repaint, no filtering
1137
1012
  val[i] = snap(v);
1138
1013
  if (val[0] > val[1]) val = [Math.min(...val), Math.max(...val)];
1139
1014
  paint();
1140
- onMove && onMove(val.slice()); // live readout; filtering waits for commit
1015
+ onMove && onMove(val.slice()); // live readout
1141
1016
  };
1142
1017
  thumbs.forEach((t, i) => {
1143
1018
  const at = clientX => {
1144
1019
  const r = track.getBoundingClientRect();
1145
1020
  return min + span * Math.min(1, Math.max(0, (clientX - r.left) / r.width));
1146
1021
  };
1147
- // drag repaints live but filters only on release (fire.now via onEnd), and
1148
- // only if the drag moved the range off where it started (not a bare click)
1022
+ // filter on release only, and only if the range moved
1149
1023
  t.onpointerdown = e => {
1150
1024
  t.focus();
1151
1025
  const from = val.slice();
@@ -1166,10 +1040,9 @@
1166
1040
  return { el: track, set: v => { val = v.slice(); paint(); } };
1167
1041
  }
1168
1042
 
1169
- // A funnel button that toggles a floating panel built by `build(panel)`; closes
1170
- // on an outside click or Escape. Returns the wrapper element. `host`, when
1171
- // given, is a larger element (a chip) that becomes the click target in place of
1172
- // the funnel, so the whole chip toggles and its panel aligns with the chip.
1043
+ // Funnel button toggling a floating panel from `build(panel)`; closes on outside
1044
+ // click or Escape. Returns the wrapper. `host` (e.g. a chip) replaces the funnel
1045
+ // as click target, so the whole chip toggles and the panel aligns with it.
1173
1046
  function popover(doc, label, build, onClose, host) {
1174
1047
  const wrap = elem(doc, "span", { className: "lti-pop" }),
1175
1048
  btn = elem(doc, "button", {
@@ -1178,13 +1051,11 @@
1178
1051
  }, wrap),
1179
1052
  panel = elem(doc, "div", { className: "lti-pop-panel", hidden: true }, wrap);
1180
1053
  build(panel);
1181
- // keep the panel inside the table's scroll box: it opens to the funnel's left
1182
- // edge by default, but a funnel near the right edge would push it past the
1183
- // box (raising its horizontal scrollbar), so anchor it to the funnel's right
1184
- // instead. The limit is the scroll box's right edge, not the viewport's — the
1185
- // box can have room on screen yet none of its own, and vice versa.
1054
+ // Keep the panel inside the scroll box: default left-aligned, but near the
1055
+ // right edge it would add a horizontal scrollbar, so right-align. Limit is the
1056
+ // box's right edge, not the viewport's.
1186
1057
  const place = () => {
1187
- panel.style.left = panel.style.right = ""; // back to the CSS default (left:0)
1058
+ panel.style.left = panel.style.right = ""; // CSS default (left:0)
1188
1059
  const vw = (doc.defaultView || window).innerWidth,
1189
1060
  box = wrap.closest(".lt-wrap"),
1190
1061
  limit = Math.min(vw, box ? box.getBoundingClientRect().right : vw);
@@ -1198,29 +1069,24 @@
1198
1069
  btn.setAttribute("aria-expanded", String(on));
1199
1070
  if (on) place(); else if (was) onClose && onClose();
1200
1071
  };
1201
- // the click target is the whole chip when hosted in one (so a chip's panel
1202
- // opens flush with the chip's left edge via CSS), else the funnel wrap; a
1203
- // click inside the open panel must not toggle it shut
1072
+ // click target: whole chip if hosted (panel flush via CSS), else funnel wrap;
1073
+ // clicks inside the panel mustn't close it
1204
1074
  const anchor = host || wrap;
1205
1075
  anchor.onclick = e => { if (!panel.contains(e.target)) open(panel.hidden); };
1206
- // close on an outside press, not click: using a widget re-renders the table,
1207
- // so a press inside and release can land on different elements, firing a stray
1208
- // click on their ancestor outside the panel (as a native <select> pick does).
1209
- // The press is always inside, so a pointerdown guard spares it.
1076
+ // Close on outside press, not click: a widget re-renders the table, so press
1077
+ // and release can land on different elements and fire a stray outside click
1078
+ // (native <select> pick). The press is always inside, so guard pointerdown.
1210
1079
  on(doc, "pointerdown", e => { if (!anchor.contains(e.target)) open(false); });
1211
1080
  on(doc, "keydown", e => { if (e.key === "Escape") open(false); });
1212
1081
  return wrap;
1213
1082
  }
1214
1083
 
1215
- // One bundle per filter type, so adding a type is a single entry rather than a
1216
- // branch in each of describe/build/init. `describe(term, cfg)` is the chip's
1217
- // one-line summary; `init(cfg)` is the term for the configured default;
1218
- // `parse(term)` reads the term back to a widget value, or null when it is a
1219
- // hand-typed expression the widget can't show (so the widget hides); and
1220
- // `build(doc, cfg, setTerm)` makes the widget as a syncing editor `{ el,
1221
- // reflect(term) }`, where `el` (a node or array of nodes) goes in the popover
1222
- // and the widget's own input writes the term through `setTerm`. The term <->
1223
- // value primitives (selExpr etc., above) back these.
1084
+ // One bundle per filter type: a new type is one entry. `describe(term, cfg)` =
1085
+ // chip summary; `init(cfg)` = term for the default; `parse(term)` = widget value,
1086
+ // or null for a hand-typed term (widget hides); `build(doc, cfg, setTerm)` =
1087
+ // syncing editor `{ el, reflect(term) }`, where `el` (node or array) goes in the
1088
+ // popover and the widget writes the term via `setTerm`. Backed by the term <->
1089
+ // value helpers above.
1224
1090
  const KINDS = {
1225
1091
  select: {
1226
1092
  describe: (t, cfg) => {
@@ -1250,15 +1116,14 @@
1250
1116
  }
1251
1117
  },
1252
1118
  checklist: {
1253
- // the chip summary: the chosen labels (few), else a count; empty when every
1254
- // box is checked (term "", no filter)
1119
+ // chip summary: chosen labels (few) else a count; empty if all checked
1255
1120
  describe: (t, cfg) => {
1256
1121
  const sel = setParse(t);
1257
1122
  if (sel == null) return t ? "⋯" : "";
1258
1123
  const labs = cfg.choices.filter(o => sel.includes(o.value)).map(o => o.label);
1259
1124
  return labs.length <= 2 ? labs.join(", ") : `${labs.length} selected`;
1260
1125
  },
1261
- // `[].concat` so a single `selected` value (a scalar from R) still seeds
1126
+ // `[].concat`: a scalar `selected` from R still seeds
1262
1127
  init: cfg => setExpr([].concat(cfg.selected ?? cfg.choices.map(o => o.value)), cfg.choices),
1263
1128
  parse: setParse,
1264
1129
  build: (doc, cfg, setTerm) => {
@@ -1270,21 +1135,19 @@
1270
1135
  }
1271
1136
  };
1272
1137
 
1273
- // Build one typed column filter and return its element. The funnel + popover
1274
- // machinery is shared by both placements: a head-bar chip when `chipLabel` is a
1275
- // string (a label + current-value summary wrap the funnel), or a bare funnel
1276
- // under the column header when `chipLabel` is null.
1138
+ // Build a typed column filter element. Funnel + popover is shared: head-bar chip
1139
+ // (label + summary around the funnel) if `chipLabel` is a string, else a bare
1140
+ // funnel under the header (null).
1277
1141
  function typedFilter(doc, col, spec, data, state, refresh, chipLabel) {
1278
1142
  const cfg = resolveSpec(spec, data[col] || []),
1279
1143
  kind = KINDS[cfg.type],
1280
- editors = []; // the expression box + widget, kept in sync
1281
- let mark = () => {}, // paints the active state once `root` exists (below)
1282
- showSummary = () => {}, // updates the chip's value readout (chip only)
1283
- widget = null; // the widget's wrapper, hidden when it can't fit the term
1284
- // set the one term, re-render, and reflect it into every editor but the one
1285
- // that caused the change (`from`), so the slider and box update each other.
1286
- // The widget hides when the term outruns it (a hand-typed expression it can't
1287
- // show), so it never displays a value out of step with the box.
1144
+ editors = []; // expression box + widget, kept in sync
1145
+ let mark = () => {}, // paints active state once `root` exists
1146
+ showSummary = () => {}, // chip value readout (chip only)
1147
+ widget = null; // wrapper; hidden when it can't show the term
1148
+ // Set the term, re-render, reflect into every editor but `from`, so slider and
1149
+ // box update each other. Widget hides on a hand-typed term it can't show, so it
1150
+ // never contradicts the box.
1288
1151
  const setTerm = (expr, from) => {
1289
1152
  expr ? (state.filters[col] = expr) : delete state.filters[col];
1290
1153
  refresh();
@@ -1293,14 +1156,11 @@
1293
1156
  if (widget) widget.hidden = !!cur && kind.parse(cur) == null;
1294
1157
  mark(cur);
1295
1158
  };
1296
- // a hidden column wraps the funnel in a labelled chip (via makeChip), which
1297
- // also becomes the popover's click target; a visible column shows the bare
1298
- // funnel under its own header. Build the chip first so it can host the
1299
- // popover.
1159
+ // Hidden column: funnel in a labeled chip (makeChip), also the popover's click
1160
+ // target; visible: bare funnel under its header. Chip built first to host it.
1300
1161
  const chip = chipLabel && makeChip(doc, chipLabel);
1301
1162
  const wrap = popover(doc, `Filter ${cfg.label || col}`, panel => {
1302
- // `box = FALSE` drops the free-text expression box, restricting the column
1303
- // to the widget's own choices (e.g. a single-select dropdown, no custom set)
1163
+ // `box = FALSE` drops the expression box, limiting to the widget's choices
1304
1164
  if (cfg.box !== false) {
1305
1165
  const box = elem(doc, "input", {
1306
1166
  type: "search", className: "lti-search",
@@ -1310,15 +1170,14 @@
1310
1170
  editors.push(boxEd);
1311
1171
  onType(box, v => setTerm(v.trim(), boxEd));
1312
1172
  }
1313
- const wEd = kind.build(doc, cfg, setTerm); // the widget as a syncing editor
1173
+ const wEd = kind.build(doc, cfg, setTerm); // widget as syncing editor
1314
1174
  editors.push(wEd);
1315
1175
  widget = elem(doc, "div", { className: "lti-widget" }, panel);
1316
1176
  widget.append(...[].concat(wEd.el));
1317
- setTerm(kind.init(cfg), null); // seed the configured default
1318
- }, () => showSummary(), chip && chip.el); // refresh the chip text on close
1319
- // the active-state class tracks every change, but the chip's value text is
1320
- // variable width, so a live update while dragging the slider would shift the
1321
- // chip (and its popover) sideways; the summary is deferred to the close.
1177
+ setTerm(kind.init(cfg), null); // seed default
1178
+ }, () => showSummary(), chip && chip.el); // refresh chip text on close
1179
+ // Active class tracks every change, but variable-width chip text would shift
1180
+ // the chip (and popover) mid-drag, so the summary waits for close.
1322
1181
  let root = wrap;
1323
1182
  if (chip) {
1324
1183
  chip.el.append(wrap);
@@ -1328,12 +1187,12 @@
1328
1187
  } else {
1329
1188
  mark = cur => root.classList.toggle("lti-on", !!cur);
1330
1189
  }
1331
- mark(state.filters[col] || ""); // paint the seeded term
1190
+ mark(state.filters[col] || ""); // paint seeded term
1332
1191
  showSummary();
1333
1192
  return root;
1334
1193
  }
1335
1194
 
1336
- // A head-bar chip for each hidden typed column (see typedFilter).
1195
+ // Head-bar chip per hidden typed column (see typedFilter).
1337
1196
  function addControlFilters(cell, barCols, cfg, data, state, refresh) {
1338
1197
  const doc = cell.ownerDocument;
1339
1198
  for (const col of barCols)
@@ -1341,21 +1200,19 @@
1341
1200
  typedFilter(doc, col, cfg[col], data, state, refresh, cfg[col].label || col));
1342
1201
  }
1343
1202
 
1344
- // Pager as the last row of <tfoot> (after any footnotes), with a page-size
1345
- // <select> when there is more than one size to offer. Both are symbols or
1346
- // numbers only: « ‹ › » for first/previous/next/last and `from–to / total`
1347
- // for the position. Returns the callback that updates them for a new row
1348
- // count.
1203
+ // Pager as the last <tfoot> row (after footnotes), plus a page-size <select> if
1204
+ // several sizes. Symbols/numbers only: « ‹ › » and `from–to / total`. Returns
1205
+ // the callback updating them for a new row count.
1349
1206
  function addPaginate(el, nCol, sizes, nRow, state, repage) {
1350
1207
  const doc = el.ownerDocument;
1351
1208
  let foot = el.tFoot;
1352
- // reuse the core footer if there is one, so the pager is sized like it
1209
+ // reuse core footer so the pager matches its sizing
1353
1210
  if (!foot) (foot = el.createTFoot()).className = "lt-footer";
1354
1211
  const bar = elem(doc, "div", { className: "lti-pager" },
1355
1212
  fullRow(foot, "lti-pager-row", nCol, -1)),
1356
1213
  pos = elem(doc, "span", { className: "lti-pos" });
1357
1214
  state.pageSize = sizes[0];
1358
- // the last page is clamped by pageSlice(), so a large number will do
1215
+ // pageSlice() clamps the last page, so any large number works
1359
1216
  const steps = [() => 0, p => p - 1, p => p + 1, () => 1e9];
1360
1217
  const btns = ["«", "‹", "›", "»"].map((glyph, i) => {
1361
1218
  const b = elem(doc, "button", {
@@ -1366,18 +1223,18 @@
1366
1223
  return b;
1367
1224
  });
1368
1225
  bar.append(pos);
1369
- // no dropdown when even the smallest size holds every row (none would split)
1226
+ // no dropdown if the smallest size holds every row
1370
1227
  if (sizes.length > 1 && nRow > Math.min(...sizes.filter(n => n > 0))) {
1371
1228
  const sel = elem(doc, "select", { "aria-label": "Rows per page" }, bar);
1372
- // 0: every row on one page (∞)
1229
+ // 0 = all rows (∞)
1373
1230
  sizes.forEach(n => elem(doc, "option", { value: n, textContent: n || "∞" }, sel));
1374
1231
  sel.onchange = () => { state.pageSize = +sel.value; state.page = 0; repage(); };
1375
1232
  }
1376
1233
  return total => {
1377
- // a page size of 0 is one page holding everything
1234
+ // size 0 = one page of everything
1378
1235
  const n = state.pageSize || total || 1,
1379
1236
  last = Math.max(0, Math.ceil(total / n) - 1),
1380
- // under a filter, append the full count in parens (a symbol, no i18n)
1237
+ // when filtered, append full count in parens (no i18n)
1381
1238
  all = total < nRow ? ` (${nRow})` : "";
1382
1239
  pos.textContent = (total ?
1383
1240
  `${state.page * n + 1}–${Math.min(total, (state.page + 1) * n)} / ${total}` :
@@ -1386,7 +1243,7 @@
1386
1243
  };
1387
1244
  }
1388
1245
 
1389
- // Enhance a mounted table that opted in (idempotent via the dataset flag).
1246
+ // Enhance an opted-in table (idempotent via dataset flag).
1390
1247
  const onMount = (el, spec) => {
1391
1248
  if (!spec?.interactive || el.dataset.ltiOn) return;
1392
1249
  el.dataset.ltiOn = "1";
@@ -1394,13 +1251,12 @@
1394
1251
  };
1395
1252
 
1396
1253
  LT.plugins.interactive = { matcher, computeView, pageSlice, enhance };
1397
- // reusable control bits for callers building their own control-bar widgets
1398
- // (with el._lt.bar): a labelled chip, a funnel popover, and a checkbox list
1254
+ // Reusable bits for callers' control-bar widgets (el._lt.bar): chip, popover,
1255
+ // checklist
1399
1256
  LT.ui = Object.assign(LT.ui || {}, { popover, checklist: makeChecklist, chip: makeChip });
1400
1257
  LT.onMount.push(onMount);
1401
- // Core drains its render queue before this file loads, so the callback above
1402
- // only sees later renders; enhance the tables already on the page now.
1403
- // (Skipped in non-DOM hosts, e.g. the Node.js tests.)
1258
+ // Core drains its queue before this loads, so the callback misses earlier
1259
+ // renders; enhance existing tables now. (Skipped without a DOM, e.g. Node tests.)
1404
1260
  if (typeof document !== "undefined")
1405
1261
  $$(document, ".lt-table").forEach(el => onMount(el, el._ltSpec));
1406
1262
  })(typeof window !== "undefined" ? window : globalThis);