@xiee/utils 1.14.109 → 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,37 +454,35 @@
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 table's current view as a CSV file. The header
546
- // row is the column labels; each body row is a view row (every row the filters
547
- // and search keep, in sort order, across all pages — `el._lt.view()` gives the
548
- // 1-based original indices) rendered with the displayed cell text from
549
- // `spec._display`. `name` is the file name (`true` = a default); group columns
550
- // (null in `cols`) are skipped. No library, no network: a Blob and an <a>.
551
- function addDownload(cell, el, spec, cols, labels, name) {
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.
481
+ function addDownload(cell, el, spec, cols, labels, opt) {
552
482
  const doc = el.ownerDocument,
553
- file = (typeof name === "string" && name ? name : "table")
483
+ o = typeof opt === "object" ? opt : { file: opt },
484
+ raw = o.mode === "raw",
485
+ file = (typeof o.file === "string" && o.file ? o.file : "table")
554
486
  .replace(/(\.csv)?$/i, ".csv"),
555
487
  keep = cols.map((c, i) => i).filter(i => cols[i] != null),
556
488
  btn = elem(doc, "button", {
@@ -558,10 +490,10 @@
558
490
  "aria-label": "Download table as CSV"
559
491
  }, cell);
560
492
  btn.onclick = () => {
561
- const disp = spec._display || {},
493
+ const src = (raw ? spec.data : spec._display) || {},
562
494
  lines = [keep.map(i => csvField(labels[i] ?? cols[i])).join(",")];
563
495
  for (const r of el._lt.view())
564
- lines.push(keep.map(i => csvField((disp[cols[i]] || [])[r - 1])).join(","));
496
+ lines.push(keep.map(i => csvField((src[cols[i]] || [])[r - 1])).join(","));
565
497
  const url = URL.createObjectURL(
566
498
  new Blob([lines.join("\n")], { type: "text/csv" }));
567
499
  elem(doc, "a", { href: url, download: file }).click();
@@ -569,25 +501,22 @@
569
501
  };
570
502
  }
571
503
 
572
- // Advance one column through asc → desc → unsorted, updating `state.sort` (an
573
- // ordered list of `{col, dir}` keys). A plain click sorts by that column
574
- // alone; a shift-click adds it as a further tie-breaker (or re-cycles it where
575
- // 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).
576
506
  function cycle(state, col, additive) {
577
507
  const order = (state.sort || []).slice(),
578
508
  i = order.findIndex(k => k.col === col),
579
509
  dir = i < 0 ? "asc" : order[i].dir === "asc" ? "desc" : null;
580
510
  if (!additive) { state.sort = dir ? [{ col, dir }] : []; return; }
581
- if (i < 0) order.push({ col, dir }); // dir is "asc" here
511
+ if (i < 0) order.push({ col, dir }); // "asc" here
582
512
  else if (dir) order[i] = { col, dir };
583
513
  else order.splice(i, 1);
584
514
  state.sort = order;
585
515
  }
586
516
 
587
- // Click-to-sort headers (shift-click to sort by several at once). The
588
- // indicators and aria-sort live on the <th>s, which survive the <tbody> swap,
589
- // so repainting them needs no re-render. An ordinal (₁ ₂ …) marks each key's
590
- // 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.
591
520
  function addSort(hrow, cols, state, refresh) {
592
521
  const doc = hrow.ownerDocument, marks = {};
593
522
  const paint = () => {
@@ -608,31 +537,25 @@
608
537
  const col = cols[ci];
609
538
  if (col == null) return;
610
539
  th.classList.add("lti-sortable");
611
- // sort on the label only, not the whole cell, so the resize grip (a <th>
612
- // child outside the label) stays unclickable for sorting
540
+ // label only, so the resize grip (outside it) doesn't sort
613
541
  const lab = elem(doc, "span", { className: "lti-label" }, th);
614
542
  while (th.firstChild !== lab) lab.append(th.firstChild);
615
543
  marks[col] = { th, ind: elem(doc, "span", { className: "lti-sort" }, lab) };
616
544
  lab.onclick = e => { cycle(state, col, e.shiftKey); paint(); refresh(); };
617
545
  });
618
- paint(); // reflect any initial sort carried on the spec
546
+ paint(); // reflect initial sort
619
547
  }
620
548
 
621
- // A row of per-column filters below the headers, inside <thead> so the <tbody>
622
- // swap leaves it (and what has been typed into it) alone. `flt` is the
623
- // normalized { default?, cols? }: each visible column takes its named spec, or
624
- // the default when unnamed. A `true` spec is a plain search box; a typed spec
625
- // 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).
626
552
  function addFilter(hrow, cols, flt, data, state, refresh, nGroup = 0) {
627
553
  const doc = hrow.ownerDocument,
628
554
  row = elem(doc, "tr", { className: "lti-filters" }),
629
555
  def = flt.default, explicit = flt.cols || {};
630
- // leading rowspan group columns carry no filter, but their cells must still
631
- // 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
632
557
  for (let i = 0; i < nGroup; i++) elem(doc, "td", {}, row);
633
- // mirror each column's alignment onto its filter cell, so a funnel sits under
634
- // the header's text (e.g. right-aligned for a numeric column), read off the
635
- // header cells, which line up with `cols`
558
+ // copy header alignment onto filter cells so funnels sit under header text
636
559
  const hCells = dataCells(hrow);
637
560
  cols.forEach((c, ci) => {
638
561
  const al = ["al-r", "al-c"].find(k => hCells[ci]?.classList.contains(k)),
@@ -648,32 +571,25 @@
648
571
  hrow.after(row);
649
572
  }
650
573
 
651
- // Filterable only if the column holds some non-blank value; a plot-only `into`
652
- // 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.
653
575
  const filterable = (data, col) => {
654
576
  const a = data && data[col];
655
577
  return Array.isArray(a) && a.some(v => v != null && v !== "");
656
578
  };
657
579
 
658
- // Expandable row detail. `detailOpt` is either an array of column names (the
659
- // detail is a one-row table of those columns' displayed values) or a callback
660
- // `(rawRow, index, displayedRow) => spec` (or the name of such a global one),
661
- // called the first time a row is expanded (and cached) to build the spec for
662
- // its drop-down detail table. Returns a
663
- // `decorate(body, rows)` that each <tbody> re-render runs: it prepends an
664
- // expand caret to every row and, after each open row, inserts a full-width
665
- // detail row rendered through LT.render (so a detail table can itself be
666
- // interactive). Expanded rows are tracked by their original index, so detail
667
- // follows its row across sort/filter/page. Resolving `detailOpt` is deferred
668
- // 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.
669
587
  function addDetail(el, spec, nCol, state, detailOpt, rerender) {
670
- // `nCol` is the table's full width, so the detail row spans the leading
671
- // rowspan group columns too
588
+ // `nCol` = full width, incl. group columns
672
589
  const doc = el.ownerDocument, cache = {};
673
590
  state.expanded = new Set();
674
- // a row as an object keyed by column (every column, including ones hidden
675
- // from the table), built from `src`: spec.data gives raw values, spec._display
676
- // the formatted text the table shows
591
+ // Row as {col: value} (all columns, incl. hidden) from `src`: spec.data =
592
+ // raw, spec._display = formatted
677
593
  const pick = (src, r) => {
678
594
  const o = {}; for (const c in src) o[c] = src[c]?.[r - 1] ?? null; return o;
679
595
  };
@@ -682,27 +598,25 @@
682
598
  const disp = pick(spec._display || {}, r);
683
599
  let out = null;
684
600
  if (Array.isArray(detailOpt)) {
685
- // a list of column names: show those columns' displayed values as a
686
- // 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)
687
602
  const data = {};
688
603
  for (const c of detailOpt) data[c] = [disp[c] ?? null];
689
604
  out = { data };
690
605
  } else {
691
- // a callback (or the name of one): (raw row, index, displayed row)
606
+ // callback or its global name
692
607
  const fn = typeof detailOpt === "function" ? detailOpt : root[detailOpt];
693
608
  if (typeof fn === "function") out = fn(pick(spec.data || {}, r), r, disp);
694
609
  }
695
610
  return cache[r] = out;
696
611
  };
697
- // a slow render (a large detail table, or a full rebuild on reset) shows a
698
- // busy state; `busy(fn)` runs `fn` through it
612
+ // slow renders (big detail, reset rebuild) show busy state via `busy(fn)`
699
613
  const wrap = el.closest(".lt-wrap"), busy = busyRender(wrap, fn => fn());
700
614
  const setCaret = (btn, open) => {
701
615
  btn.textContent = open ? "▾" : "▸";
702
616
  btn.setAttribute("aria-expanded", String(open));
703
617
  };
704
- // build a row's detail once, inserted hidden after its <tr>; the row stays in
705
- // 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.
706
620
  const openDetail = (tr, r) => {
707
621
  const child = build(r);
708
622
  if (!child) return null;
@@ -715,33 +629,30 @@
715
629
  const d = tr.nextElementSibling;
716
630
  return d?.classList.contains("lti-detail") ? d : openDetail(tr, r);
717
631
  };
718
- // the table's base width (no detail shown), captured each render by presize
632
+ // base width (no detail), captured per render by presize
719
633
  let baseW = 0;
720
- // Grow the table's explicit `width` (not min-width, so a wrapping container's
721
- // max-width still caps it) to fit a just-shown detail wider than the base
722
- // width. Width only grows, so a wide detail widens the table once and
723
- // 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.
724
636
  const grow = () => {
725
637
  const w = Math.ceil(el.getBoundingClientRect().width);
726
638
  if (w > baseW && w > (parseFloat(el.style.width) || 0)) el.style.width = w + "px";
727
639
  };
728
- // toggle one row in place: just flip the (already built) detail's visibility.
640
+ // toggle: flip the built detail's visibility
729
641
  const toggle = (tr, btn, r) => {
730
642
  const open = state.expanded.has(r);
731
643
  open ? state.expanded.delete(r) : state.expanded.add(r);
732
644
  setCaret(btn, !open);
733
645
  const d = ensureDetail(tr, r);
734
646
  if (!d) return;
735
- d.hidden = open; // was open -> hide; was closed -> show
736
- 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
737
649
  };
738
- // Pre-size the table from its first row detail so a typical expand never
739
- // jumps the width: at idle, open just the first detail to measure, re-hide
740
- // it, and grow the table to it. Other details stay deferred; a wider one
741
- // 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.
742
653
  const win = doc.defaultView, idle = win.requestIdleCallback || win.setTimeout;
743
654
  const presize = (body) => idle(() => {
744
- if (!body.isConnected) return; // a newer render replaced it
655
+ if (!body.isConnected) return; // replaced by newer render
745
656
  el.style.width = "";
746
657
  baseW = el.getBoundingClientRect().width;
747
658
  const c = $(body, ".lti-expand[aria-expanded='false']");
@@ -753,9 +664,8 @@
753
664
  const decorate = (body, rows) => {
754
665
  [...body.rows].forEach((tr, i) => {
755
666
  const r = rows[i];
756
- if (typeof r !== "number") return; // a separator group-header row
757
- // the first data cell (past any leading rowspan group cell), so the caret
758
- // 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
759
669
  const td0 = dataCells(tr)[0], open = state.expanded.has(r);
760
670
  if (!td0) return;
761
671
  const btn = elem(doc, "button", {
@@ -768,9 +678,8 @@
768
678
  });
769
679
  presize(body);
770
680
  };
771
- // drop a row's cached detail (or every row's) and re-render, so the callback
772
- // re-runs and the detail — and its own sort/filter state — rebuilds fresh,
773
- // 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.
774
683
  decorate.reset = r => {
775
684
  if (r == null) for (const k in cache) delete cache[k];
776
685
  else delete cache[r];
@@ -779,30 +688,26 @@
779
688
  return decorate;
780
689
  }
781
690
 
782
- // The table's <colgroup>, created when core emitted none (it only does so for
783
- // a table given explicit widths on the R side). It gets `nGroup` leading <col>s
784
- // for the rowspan group columns (which lead each header/body row) then one per
785
- // 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.
786
694
  function colGroup(el, nCol, nGroup = 0) {
787
695
  let g = $(el, "colgroup");
788
696
  if (!g) {
789
697
  const doc = el.ownerDocument;
790
698
  g = elem(doc, "colgroup");
791
699
  for (let i = 0; i < nGroup + nCol; i++) elem(doc, "col", {}, g);
792
- // <colgroup> comes after <caption> (the title), before <thead>
700
+ // after <caption>, before <thead>
793
701
  el.caption ? el.caption.after(g) : el.prepend(g);
794
702
  }
795
703
  return [...g.children];
796
704
  }
797
705
 
798
- // Fixed-layout machinery for column resize. The widths live on the
799
- // <colgroup>, outside <tbody>, so they survive every
800
- // re-render. `freeze()` switches the table to fixed layout once, pinning every
801
- // column at the width it has then, so a later width change moves that one
802
- // column instead of reflowing the whole table. `natural(i)` is column i's
803
- // content width (an unconstrained reflow, with the widths put back after).
804
- // `setWidth(i, w, min)` sets column i to `w` px (clamped to `min`), widening or
805
- // 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.
806
711
  function fixedLayout(el, hrow, nCol, nGroup = 0) {
807
712
  const ths = [...$$(hrow, "th")],
808
713
  cs = colGroup(el, nCol, nGroup), wOf = e => e.getBoundingClientRect().width;
@@ -830,14 +735,12 @@
830
735
  el.style.width =
831
736
  `${parseFloat(el.style.width) + parseFloat(cs[i].style.width) - old}px`;
832
737
  };
833
- // `dataCs` drops the leading group <col>s, so a data-column consumer (the
834
- // column-hide menu) indexes it by data-column position
738
+ // `dataCs` drops group <col>s: index by data-column position
835
739
  return { ths, cs, dataCs: cs.slice(nGroup), freeze, natural, setWidth };
836
740
  }
837
741
 
838
- // Drag-to-resize column edges: a grip on the right edge of each header cell.
839
- // On the first drag the table switches to fixed layout (see fixedLayout) so
840
- // 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
841
744
  // content.
842
745
  function addResize(el, layout) {
843
746
  const doc = el.ownerDocument, { ths, cs, freeze, natural, setWidth } = layout;
@@ -853,49 +756,41 @@
853
756
  freeze();
854
757
  const x0 = e.clientX, w0 = parseFloat(cs[i].style.width);
855
758
  el.classList.add("lti-resizing");
856
- // no label floor: omit setWidth's min arg to take its default, and the
857
- // cell clips its overflow (CSS) instead of spilling when shrunk
759
+ // default min width; CSS clips overflow when shrunk
858
760
  drag(e, ev => setWidth(i, w0 + ev.clientX - x0),
859
761
  () => el.classList.remove("lti-resizing"));
860
762
  };
861
763
  });
862
764
  }
863
765
 
864
- // Column-visibility menu: an eye button at the start of the head cell that
865
- // opens a checklist, one box per column. Unchecking a column hides it
866
- // outright — its header and every body cell take the `hidden` attribute (which
867
- // a <tbody> swap drops, so it is re-applied via postSwap). Every column is
868
- // listed; `opt` is `true` (all start shown) or `{ hidden: [...] }` (those names
869
- // start hidden). `layout` is resize's fixed layout, used when present to drop a
870
- // 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.
871
770
  function addColumnToggle(cell, el, hrow, cols, labels, opt, layout, postSwap) {
872
771
  const doc = el.ownerDocument,
873
772
  start = (opt && opt.hidden) || [], hidden = new Set();
874
- // show/hide column i's cell in one row (indexing the row's data cells, past
875
- // any leading rowspan group cell), skipping the single colspan cell of a
876
- // 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)
877
775
  const setCell = (tr, i, on) => {
878
776
  const c = dataCells(tr)[i];
879
777
  if (c && c.colSpan === 1) c.hidden = on;
880
778
  };
881
- // re-hide every hidden column's cells on each freshly-built <tbody>
779
+ // re-hide on each new <tbody>
882
780
  postSwap.push(body => hidden.forEach(i => {
883
781
  for (const tr of body.rows) setCell(tr, i, true);
884
782
  }));
885
- // The spanner row merges cells, so column i is not at cell index i there as
886
- // in every other row; handle it separately (applySpan). Map each spanner-row
887
- // cell to the column range it covers (skipping the leading row-group
888
- // placeholders): hide a plain colspan-1 slot outright, and shrink a real
889
- // spanner's colSpan — hiding it only once all its columns are gone — so the
890
- // 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.
891
787
  const nGrp = [...hrow.children].length - dataCells(hrow).length,
892
788
  spanRow = [...el.rows].find(tr => tr.classList.contains("lt-spanner-row")),
893
789
  spanCells = spanRow ? dataCells(spanRow).slice(nGrp) : [];
894
790
  let col0 = 0;
895
791
  spanCells.forEach(c => { c._span = c.colSpan; c._start = col0; col0 += c._span; });
896
- // Recompute every spanner cell from the current `hidden` set (idempotent, so
897
- // it is safe to call on each apply): a real spanner's colSpan is its columns
898
- // still showing, and it vanishes once all are hidden.
792
+ // Recompute spanner cells from `hidden` (idempotent): colSpan = columns still
793
+ // showing; hidden when none.
899
794
  const applySpan = () => {
900
795
  for (const c of spanCells) {
901
796
  let gone = 0;
@@ -904,13 +799,10 @@
904
799
  c.hidden = gone >= c._span;
905
800
  }
906
801
  };
907
- // show/hide column i everywhere it lives: the <col> (fixed layout only) and,
908
- // one row at a time, every per-column cell — the header labels, the filter
909
- // boxes, the body cells, and a plot's axis footer, plus the spanner row via
910
- // applySpan. The setCell colspan guard skips the other full-width rows
911
- // (search bar, detail, footnotes, pager). <thead>/<tfoot> survive a <tbody>
912
- // swap, so this one pass keeps them in sync; only the fresh <tbody> is
913
- // 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.
914
806
  const apply = i => {
915
807
  const on = hidden.has(i);
916
808
  if (layout?.dataCs[i]) layout.dataCs[i].hidden = on;
@@ -924,7 +816,7 @@
924
816
  "aria-label": "Show or hide columns", "aria-expanded": "false"
925
817
  }, wrap),
926
818
  menu = elem(doc, "div", { className: "lti-menu", hidden: true }, wrap);
927
- // one checkbox per column; `sub` indents it under a spanner group header
819
+ // checkbox per column; `sub` indents under a spanner header
928
820
  const addBox = (i, sub) => {
929
821
  const c = cols[i];
930
822
  if (c == null) return;
@@ -937,17 +829,16 @@
937
829
  apply(i);
938
830
  };
939
831
  };
940
- // Group the checkboxes under their spanners: the same column label can repeat
941
- // across spanners (e.g. auto-span's "Sepal.Length"/"Petal.Length" both show as
942
- // "Length"), so a flat list would be ambiguous. Walk the spanner row, emitting
943
- // a group header before a real spanner's columns and listing a non-spanned
944
- // 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.
945
836
  if (spanCells.length) for (const c of spanCells) {
946
837
  const span = c.classList.contains("lt-spanner");
947
838
  if (span) elem(doc, "div", { className: "lti-group", textContent: c.textContent }, menu);
948
839
  for (let i = c._start; i < c._start + c._span; i++) addBox(i, span);
949
840
  } else cols.forEach((_, i) => addBox(i));
950
- cols.forEach((_, i) => apply(i)); // reflect any columns that start hidden
841
+ cols.forEach((_, i) => apply(i)); // apply initially hidden columns
951
842
  const open = on => {
952
843
  menu.hidden = !on;
953
844
  btn.setAttribute("aria-expanded", String(on));
@@ -957,20 +848,16 @@
957
848
  on(doc, "keydown", e => { if (e.key === "Escape") open(false); });
958
849
  }
959
850
 
960
- // --- Typed column filters (the `filter` named-list form). A typed spec is
851
+ // --- Typed column filters (`filter` named-list form). A typed spec is
961
852
  // {type:"select"|"range"|"checklist", label?, choices?, min?, max?, step?,
962
- // value?, selected?}; it renders as a funnel + popover, under its own header
963
- // when the column is visible or as a labelled head-bar chip when it is hidden
964
- // (the column still travels in spec.data, which is what computeView filters
965
- // on). The popover holds an expression box AND a widget (a value dropdown, a
966
- // range slider, or a checklist of values); both edit the one filter term for
967
- // that column (state.filters[col]) and stay in sync, so the widget is a
968
- // friendly face on the same expression a
969
- // 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.
970
858
 
971
- // A filter term string <-> a widget value, per type. A `null` parse means the
972
- // term is something the widget can't show (a hand-typed expression), so the
973
- // 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.
974
861
  const selExpr = v => v === "" ? "" : `x == ${JSON.stringify(String(v))}`,
975
862
  selParse = s => {
976
863
  const m = /^\s*x\s*==\s*(['"])([\s\S]*)\1\s*$/.exec(s || "");
@@ -982,8 +869,8 @@
982
869
  const m = /^\s*x\s*>=\s*(-?[\d.]+)\s*&&\s*x\s*<=\s*(-?[\d.]+)\s*$/.exec(s || "");
983
870
  return m ? [parseFloat(m[1]), parseFloat(m[2])] : null;
984
871
  },
985
- // a set filter keeps rows whose value is one of the checked ones; every
986
- // 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)
987
874
  setExpr = (sel, all) =>
988
875
  sel.length === all.length ? "" : `${JSON.stringify(sel.map(String))}.includes(x)`,
989
876
  setParse = s => {
@@ -992,9 +879,8 @@
992
879
  try { return JSON.parse(m[1]); } catch (e) { return null; }
993
880
  };
994
881
 
995
- // A "nice" slider step for a data span: the 1/2/5 x 10^k value nearest ~1% of
996
- // the span (so ~50-100 increments), like pretty()'s tick spacing. An integer
997
- // 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.
998
884
  function niceStep(span, integer) {
999
885
  if (!(span > 0) || !isFinite(span)) return integer ? 1 : 0.1;
1000
886
  const raw = span / 100, mag = Math.pow(10, Math.floor(Math.log10(raw)));
@@ -1002,9 +888,9 @@
1002
888
  return integer ? Math.max(1, Math.round(step)) : step;
1003
889
  }
1004
890
 
1005
- // Fill a typed spec's choices (select) or min/max/step (range) from the
1006
- // column's data when the R side left them out, so `filter = list(x = "select")`
1007
- // 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.
1008
894
  function resolveSpec(spec, column) {
1009
895
  if (spec.type === "select" || spec.type === "checklist") {
1010
896
  let choices = spec.choices;
@@ -1015,9 +901,8 @@
1015
901
  ? a - b : String(a).localeCompare(String(b)));
1016
902
  choices = vals.map(v => ({ value: String(v), label: String(v) }));
1017
903
  }
1018
- // a select offers a leading blank "no filter" choice, so it shows every
1019
- // row until the reader picks a value; a checklist starts with every box
1020
- // 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
1021
906
  if (spec.type === "select" && !choices.some(o => o.value === ""))
1022
907
  choices = [{ value: "", label: "" }, ...choices];
1023
908
  return { ...spec, choices };
@@ -1037,16 +922,15 @@
1037
922
  }
1038
923
  const loB = min != null ? min : lo, hiB = max != null ? max : hi;
1039
924
  if (step == null) step = niceStep(hiB - loB, allInt);
1040
- // round() clears float dust from the arithmetic below; the derived endpoints
1041
- // snap out to whole steps so they are round and bracket the data (the extreme
1042
- // 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)
1043
927
  const tidy = x => Math.round(x * 1e9) / 1e9;
1044
928
  if (min == null) min = tidy(Math.floor(lo / step) * step);
1045
929
  if (max == null) max = tidy(Math.ceil(hi / step) * step);
1046
930
  return { ...spec, min, max, step };
1047
931
  }
1048
932
 
1049
- // A dropdown of {value, label} options; `onInput(value)` fires on change.
933
+ // Dropdown of {value, label}; `onInput(value)` on change.
1050
934
  function makeSelect(doc, options, onInput) {
1051
935
  const sel = elem(doc, "select", { className: "lti-filter-pick" });
1052
936
  options.forEach(o => elem(doc, "option", { value: o.value, textContent: o.label }, sel));
@@ -1054,11 +938,10 @@
1054
938
  return { el: sel, set: v => sel.value = v };
1055
939
  }
1056
940
 
1057
- // A list of {value, label} checkboxes (every box starts checked); `onInput`
1058
- // fires with the array of checked values on any change. Returns
1059
- // { el: [<label>...], set(values) }. Exposed on LT.ui so a caller can drop a
1060
- // checklist control into its own popover (e.g. forestly's treatment-group
1061
- // 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).
1062
945
  function makeChecklist(doc, options, onInput) {
1063
946
  const boxes = options.map(o => {
1064
947
  const label = elem(doc, "label", { className: "lti-check" }),
@@ -1074,12 +957,10 @@
1074
957
  };
1075
958
  }
1076
959
 
1077
- // A control-bar chip: a label, the caller's control (a funnel popover) dropped
1078
- // in, and a value-summary slot. `mark(on)` toggles the active highlight (color
1079
- // only, no reflow); `summarize(text)` sets the readout. Returns { el, mark,
1080
- // summarize }. The typed-filter chips use it, and it is exposed on LT.ui so a
1081
- // caller building its own control-bar widget (e.g. forestly's treatment-group
1082
- // 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.
1083
964
  function makeChip(doc, label, control) {
1084
965
  const el = elem(doc, "span", { className: "lti-chip" });
1085
966
  elem(doc, "span", { className: "lti-chip-name", textContent: label }, el);
@@ -1092,12 +973,10 @@
1092
973
  };
1093
974
  }
1094
975
 
1095
- // A two-thumb range slider from a track, a fill band, and two <button> thumbs —
1096
- // no native <input type=range>, so no vendor pseudo-element CSS and no stacked-
1097
- // input z-index hacks. Thumbs drag via the shared drag() helper and step with
1098
- // the arrow keys (Home/End jump to the ends); the low thumb never passes the
1099
- // high one. `cfg` is {min, max, step}; `onInput([lo, hi])` fires as a thumb
1100
- // 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]) }.
1101
980
  function makeSlider(doc, cfg, onInput, onMove) {
1102
981
  const min = cfg.min, max = cfg.max, span = max - min || 1,
1103
982
  step = cfg.step || span / 100,
@@ -1109,15 +988,12 @@
1109
988
  }, track),
1110
989
  thumbs = [mk("Minimum"), mk("Maximum")];
1111
990
  let val = [min, max];
1112
- // paint() tracks the thumb live; the onInput filter never fires mid-drag. A
1113
- // live filter re-flows the table (and shifts the chip the thumb lives in)
1114
- // out from under the cursor, so a mouse drag only commits on release
1115
- // (fire.now via onEnd). Arrow keys repaint live too but only debounce the
1116
- // filter — no commit on key-up — so stepping several times quickly (or an
1117
- // 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.
1118
995
  const fire = debounce(() => onInput(val.slice())),
1119
- // a no-op gesture (a bare thumb click, or an arrow key at an end) leaves
1120
- // 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)
1121
997
  changed = from => val[0] !== from[0] || val[1] !== from[1];
1122
998
  const pct = v => (v - min) / span * 100,
1123
999
  snap = v => {
@@ -1132,19 +1008,18 @@
1132
1008
  fill.style.left = pct(val[0]) + "%";
1133
1009
  fill.style.right = `${100 - pct(val[1])}%`;
1134
1010
  },
1135
- move = (i, v) => { // update + repaint a thumb, without filtering
1011
+ move = (i, v) => { // update + repaint, no filtering
1136
1012
  val[i] = snap(v);
1137
1013
  if (val[0] > val[1]) val = [Math.min(...val), Math.max(...val)];
1138
1014
  paint();
1139
- onMove && onMove(val.slice()); // live readout; filtering waits for commit
1015
+ onMove && onMove(val.slice()); // live readout
1140
1016
  };
1141
1017
  thumbs.forEach((t, i) => {
1142
1018
  const at = clientX => {
1143
1019
  const r = track.getBoundingClientRect();
1144
1020
  return min + span * Math.min(1, Math.max(0, (clientX - r.left) / r.width));
1145
1021
  };
1146
- // drag repaints live but filters only on release (fire.now via onEnd), and
1147
- // 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
1148
1023
  t.onpointerdown = e => {
1149
1024
  t.focus();
1150
1025
  const from = val.slice();
@@ -1165,10 +1040,9 @@
1165
1040
  return { el: track, set: v => { val = v.slice(); paint(); } };
1166
1041
  }
1167
1042
 
1168
- // A funnel button that toggles a floating panel built by `build(panel)`; closes
1169
- // on an outside click or Escape. Returns the wrapper element. `host`, when
1170
- // given, is a larger element (a chip) that becomes the click target in place of
1171
- // 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.
1172
1046
  function popover(doc, label, build, onClose, host) {
1173
1047
  const wrap = elem(doc, "span", { className: "lti-pop" }),
1174
1048
  btn = elem(doc, "button", {
@@ -1177,13 +1051,11 @@
1177
1051
  }, wrap),
1178
1052
  panel = elem(doc, "div", { className: "lti-pop-panel", hidden: true }, wrap);
1179
1053
  build(panel);
1180
- // keep the panel inside the table's scroll box: it opens to the funnel's left
1181
- // edge by default, but a funnel near the right edge would push it past the
1182
- // box (raising its horizontal scrollbar), so anchor it to the funnel's right
1183
- // instead. The limit is the scroll box's right edge, not the viewport's — the
1184
- // 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.
1185
1057
  const place = () => {
1186
- panel.style.left = panel.style.right = ""; // back to the CSS default (left:0)
1058
+ panel.style.left = panel.style.right = ""; // CSS default (left:0)
1187
1059
  const vw = (doc.defaultView || window).innerWidth,
1188
1060
  box = wrap.closest(".lt-wrap"),
1189
1061
  limit = Math.min(vw, box ? box.getBoundingClientRect().right : vw);
@@ -1197,29 +1069,24 @@
1197
1069
  btn.setAttribute("aria-expanded", String(on));
1198
1070
  if (on) place(); else if (was) onClose && onClose();
1199
1071
  };
1200
- // the click target is the whole chip when hosted in one (so a chip's panel
1201
- // opens flush with the chip's left edge via CSS), else the funnel wrap; a
1202
- // 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
1203
1074
  const anchor = host || wrap;
1204
1075
  anchor.onclick = e => { if (!panel.contains(e.target)) open(panel.hidden); };
1205
- // close on an outside press, not click: using a widget re-renders the table,
1206
- // so a press inside and release can land on different elements, firing a stray
1207
- // click on their ancestor outside the panel (as a native <select> pick does).
1208
- // 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.
1209
1079
  on(doc, "pointerdown", e => { if (!anchor.contains(e.target)) open(false); });
1210
1080
  on(doc, "keydown", e => { if (e.key === "Escape") open(false); });
1211
1081
  return wrap;
1212
1082
  }
1213
1083
 
1214
- // One bundle per filter type, so adding a type is a single entry rather than a
1215
- // branch in each of describe/build/init. `describe(term, cfg)` is the chip's
1216
- // one-line summary; `init(cfg)` is the term for the configured default;
1217
- // `parse(term)` reads the term back to a widget value, or null when it is a
1218
- // hand-typed expression the widget can't show (so the widget hides); and
1219
- // `build(doc, cfg, setTerm)` makes the widget as a syncing editor `{ el,
1220
- // reflect(term) }`, where `el` (a node or array of nodes) goes in the popover
1221
- // and the widget's own input writes the term through `setTerm`. The term <->
1222
- // 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.
1223
1090
  const KINDS = {
1224
1091
  select: {
1225
1092
  describe: (t, cfg) => {
@@ -1249,15 +1116,14 @@
1249
1116
  }
1250
1117
  },
1251
1118
  checklist: {
1252
- // the chip summary: the chosen labels (few), else a count; empty when every
1253
- // box is checked (term "", no filter)
1119
+ // chip summary: chosen labels (few) else a count; empty if all checked
1254
1120
  describe: (t, cfg) => {
1255
1121
  const sel = setParse(t);
1256
1122
  if (sel == null) return t ? "⋯" : "";
1257
1123
  const labs = cfg.choices.filter(o => sel.includes(o.value)).map(o => o.label);
1258
1124
  return labs.length <= 2 ? labs.join(", ") : `${labs.length} selected`;
1259
1125
  },
1260
- // `[].concat` so a single `selected` value (a scalar from R) still seeds
1126
+ // `[].concat`: a scalar `selected` from R still seeds
1261
1127
  init: cfg => setExpr([].concat(cfg.selected ?? cfg.choices.map(o => o.value)), cfg.choices),
1262
1128
  parse: setParse,
1263
1129
  build: (doc, cfg, setTerm) => {
@@ -1269,21 +1135,19 @@
1269
1135
  }
1270
1136
  };
1271
1137
 
1272
- // Build one typed column filter and return its element. The funnel + popover
1273
- // machinery is shared by both placements: a head-bar chip when `chipLabel` is a
1274
- // string (a label + current-value summary wrap the funnel), or a bare funnel
1275
- // 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).
1276
1141
  function typedFilter(doc, col, spec, data, state, refresh, chipLabel) {
1277
1142
  const cfg = resolveSpec(spec, data[col] || []),
1278
1143
  kind = KINDS[cfg.type],
1279
- editors = []; // the expression box + widget, kept in sync
1280
- let mark = () => {}, // paints the active state once `root` exists (below)
1281
- showSummary = () => {}, // updates the chip's value readout (chip only)
1282
- widget = null; // the widget's wrapper, hidden when it can't fit the term
1283
- // set the one term, re-render, and reflect it into every editor but the one
1284
- // that caused the change (`from`), so the slider and box update each other.
1285
- // The widget hides when the term outruns it (a hand-typed expression it can't
1286
- // 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.
1287
1151
  const setTerm = (expr, from) => {
1288
1152
  expr ? (state.filters[col] = expr) : delete state.filters[col];
1289
1153
  refresh();
@@ -1292,14 +1156,11 @@
1292
1156
  if (widget) widget.hidden = !!cur && kind.parse(cur) == null;
1293
1157
  mark(cur);
1294
1158
  };
1295
- // a hidden column wraps the funnel in a labelled chip (via makeChip), which
1296
- // also becomes the popover's click target; a visible column shows the bare
1297
- // funnel under its own header. Build the chip first so it can host the
1298
- // 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.
1299
1161
  const chip = chipLabel && makeChip(doc, chipLabel);
1300
1162
  const wrap = popover(doc, `Filter ${cfg.label || col}`, panel => {
1301
- // `box = FALSE` drops the free-text expression box, restricting the column
1302
- // 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
1303
1164
  if (cfg.box !== false) {
1304
1165
  const box = elem(doc, "input", {
1305
1166
  type: "search", className: "lti-search",
@@ -1309,15 +1170,14 @@
1309
1170
  editors.push(boxEd);
1310
1171
  onType(box, v => setTerm(v.trim(), boxEd));
1311
1172
  }
1312
- 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
1313
1174
  editors.push(wEd);
1314
1175
  widget = elem(doc, "div", { className: "lti-widget" }, panel);
1315
1176
  widget.append(...[].concat(wEd.el));
1316
- setTerm(kind.init(cfg), null); // seed the configured default
1317
- }, () => showSummary(), chip && chip.el); // refresh the chip text on close
1318
- // the active-state class tracks every change, but the chip's value text is
1319
- // variable width, so a live update while dragging the slider would shift the
1320
- // 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.
1321
1181
  let root = wrap;
1322
1182
  if (chip) {
1323
1183
  chip.el.append(wrap);
@@ -1327,12 +1187,12 @@
1327
1187
  } else {
1328
1188
  mark = cur => root.classList.toggle("lti-on", !!cur);
1329
1189
  }
1330
- mark(state.filters[col] || ""); // paint the seeded term
1190
+ mark(state.filters[col] || ""); // paint seeded term
1331
1191
  showSummary();
1332
1192
  return root;
1333
1193
  }
1334
1194
 
1335
- // A head-bar chip for each hidden typed column (see typedFilter).
1195
+ // Head-bar chip per hidden typed column (see typedFilter).
1336
1196
  function addControlFilters(cell, barCols, cfg, data, state, refresh) {
1337
1197
  const doc = cell.ownerDocument;
1338
1198
  for (const col of barCols)
@@ -1340,21 +1200,19 @@
1340
1200
  typedFilter(doc, col, cfg[col], data, state, refresh, cfg[col].label || col));
1341
1201
  }
1342
1202
 
1343
- // Pager as the last row of <tfoot> (after any footnotes), with a page-size
1344
- // <select> when there is more than one size to offer. Both are symbols or
1345
- // numbers only: « ‹ › » for first/previous/next/last and `from–to / total`
1346
- // for the position. Returns the callback that updates them for a new row
1347
- // 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.
1348
1206
  function addPaginate(el, nCol, sizes, nRow, state, repage) {
1349
1207
  const doc = el.ownerDocument;
1350
1208
  let foot = el.tFoot;
1351
- // 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
1352
1210
  if (!foot) (foot = el.createTFoot()).className = "lt-footer";
1353
1211
  const bar = elem(doc, "div", { className: "lti-pager" },
1354
1212
  fullRow(foot, "lti-pager-row", nCol, -1)),
1355
1213
  pos = elem(doc, "span", { className: "lti-pos" });
1356
1214
  state.pageSize = sizes[0];
1357
- // the last page is clamped by pageSlice(), so a large number will do
1215
+ // pageSlice() clamps the last page, so any large number works
1358
1216
  const steps = [() => 0, p => p - 1, p => p + 1, () => 1e9];
1359
1217
  const btns = ["«", "‹", "›", "»"].map((glyph, i) => {
1360
1218
  const b = elem(doc, "button", {
@@ -1365,18 +1223,18 @@
1365
1223
  return b;
1366
1224
  });
1367
1225
  bar.append(pos);
1368
- // no dropdown when even the smallest size holds every row (none would split)
1226
+ // no dropdown if the smallest size holds every row
1369
1227
  if (sizes.length > 1 && nRow > Math.min(...sizes.filter(n => n > 0))) {
1370
1228
  const sel = elem(doc, "select", { "aria-label": "Rows per page" }, bar);
1371
- // 0: every row on one page (∞)
1229
+ // 0 = all rows (∞)
1372
1230
  sizes.forEach(n => elem(doc, "option", { value: n, textContent: n || "∞" }, sel));
1373
1231
  sel.onchange = () => { state.pageSize = +sel.value; state.page = 0; repage(); };
1374
1232
  }
1375
1233
  return total => {
1376
- // a page size of 0 is one page holding everything
1234
+ // size 0 = one page of everything
1377
1235
  const n = state.pageSize || total || 1,
1378
1236
  last = Math.max(0, Math.ceil(total / n) - 1),
1379
- // under a filter, append the full count in parens (a symbol, no i18n)
1237
+ // when filtered, append full count in parens (no i18n)
1380
1238
  all = total < nRow ? ` (${nRow})` : "";
1381
1239
  pos.textContent = (total ?
1382
1240
  `${state.page * n + 1}–${Math.min(total, (state.page + 1) * n)} / ${total}` :
@@ -1385,7 +1243,7 @@
1385
1243
  };
1386
1244
  }
1387
1245
 
1388
- // Enhance a mounted table that opted in (idempotent via the dataset flag).
1246
+ // Enhance an opted-in table (idempotent via dataset flag).
1389
1247
  const onMount = (el, spec) => {
1390
1248
  if (!spec?.interactive || el.dataset.ltiOn) return;
1391
1249
  el.dataset.ltiOn = "1";
@@ -1393,13 +1251,12 @@
1393
1251
  };
1394
1252
 
1395
1253
  LT.plugins.interactive = { matcher, computeView, pageSlice, enhance };
1396
- // reusable control bits for callers building their own control-bar widgets
1397
- // (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
1398
1256
  LT.ui = Object.assign(LT.ui || {}, { popover, checklist: makeChecklist, chip: makeChip });
1399
1257
  LT.onMount.push(onMount);
1400
- // Core drains its render queue before this file loads, so the callback above
1401
- // only sees later renders; enhance the tables already on the page now.
1402
- // (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.)
1403
1260
  if (typeof document !== "undefined")
1404
1261
  $$(document, ".lt-table").forEach(el => onMount(el, el._ltSpec));
1405
1262
  })(typeof window !== "undefined" ? window : globalThis);