@xiee/utils 1.14.110 → 1.14.112

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.
package/js/lt.js CHANGED
@@ -1,63 +1,61 @@
1
- /* lt.js — build a semantic <table> from a JSON spec.
2
- * Call LT.build(spec) from an inline <script> to render a table in place, or
3
- * LT.render(el, spec) to render one into a container at any later time.
4
- * One runtime per page renders any number of tables.
1
+ /* lt.js — build semantic <table> from JSON spec.
2
+ * LT.build(spec) from inline <script> renders in place; LT.render(el, spec)
3
+ * renders into container anytime. One runtime per page serves all tables.
5
4
  */
6
5
  (root => {
7
6
  "use strict";
8
- if (root.LT?.buildHtml) return; // duplicate inclusion is a no-op
9
-
10
- const $ = (el, sel) => el.querySelector(sel);
11
-
12
- // Inline-graphics cell renderers (error bars, sparklines, …), keyed by op
13
- // type and shipped by lt-plot.js (loaded before core). Captured as a live
14
- // reference and re-exposed on root.LT below, so a plot module loaded either
15
- // before or after core registers into the same object. Empty when no plot
16
- // module is present; core itself contains no plot code (see LT.cells docs).
7
+ if (root.LT?.buildHtml) return; // duplicate include: no-op
8
+
9
+ // DOM helpers, shared with the extensions via LT.
10
+ const $ = (el, sel) => el.querySelector(sel),
11
+ $$ = (el, sel) => el.querySelectorAll(sel),
12
+ on = (t, type, fn, opts) => t.addEventListener(type, fn, opts),
13
+ off = (t, type, fn) => t.removeEventListener(type, fn);
14
+
15
+ // Inline-graphics cell renderers keyed by op type, registered by lt-plot.js
16
+ // (loaded before core). Live reference re-exposed on root.LT, so plot
17
+ // module loaded before or after core registers into same object. Empty
18
+ // without plot module; core has no plot code (see LT.cells docs).
17
19
  const cellRenderers = root.LT?.cells || {};
18
20
 
19
- // `[<]` (not `<`) avoids `</…` so this file is safe to inline in <script>.
21
+ // `[<]` not `<` avoids `</…`, so file is safe to inline in <script>.
20
22
  const esc = s => String(s)
21
23
  .replace(/&/g, "&amp;").replace(/[<]/g, "&lt;")
22
24
  .replace(/>/g, "&gt;").replace(/"/g, "&quot;");
23
- // Text fields (title, labels, footnotes, ...) arrive as a plain string
24
- // (escape it) or, when the R side wrapped them in I(), a one-element array
25
- // (emit verbatim as raw HTML). `txt` renders either form.
25
+ // Text fields arrive as plain string (escape) or, if wrapped in I() in R,
26
+ // one-element array (verbatim raw HTML). `txt` handles both.
26
27
  const txt = v => Array.isArray(v) ? String(v[0] ?? "") : esc(v);
27
- // Raw (verbatim) if `raw`, else escaped — for values already stringified
28
- // (e.g. body cells whose column is flagged raw via spec.html_cols).
28
+ // Raw if `raw`, else escaped; for already-stringified values (e.g. cells of
29
+ // columns in spec.html_cols).
29
30
  const escIf = (raw, s) => raw ? String(s ?? "") : esc(s);
30
- // Is column `c` flagged raw HTML? `hc` is spec.html_cols: true (all columns)
31
- // or an array of column names.
31
+ // Column `c` raw HTML? `hc` = spec.html_cols: true (all) or column names.
32
32
  const rawCol = (hc, c) => hc === true || (Array.isArray(hc) && hc.includes(c));
33
33
  const sup = i => `<sup class="lt-fnref">${i}</sup>`;
34
- // Stringify, mapping null/undefined to "" (0 and false stringify normally).
35
- // ±Infinity render as ∞/-∞ (ASCII minus, as raw values); formatted columns get
36
- // the typographic minus via fmtNumber.
34
+ // Stringify; null/undefined -> "". ±Infinity -> ∞/-∞ (ASCII minus, raw
35
+ // values); formatted columns get typographic minus via fmtNumber.
37
36
  const str = v => v === Infinity ? "∞" : v === -Infinity ? "-∞" : String(v ?? "");
38
37
 
39
38
  // --- Number formatting ---
40
39
  const isNum = v => typeof v === "number" && isFinite(v);
41
- // Like isNum but also accepts ±Infinity (which fmtNumber renders as ∞/−∞).
40
+ // Like isNum, plus ±Infinity (fmtNumber renders ∞/−∞).
42
41
  const isNumInf = v => isNum(v) || Math.abs(v) === Infinity;
43
- // A column is "numeric" if its first non-null value is a number.
42
+ // Numeric column: first non-null value is a number.
44
43
  const numCol = col => col?.length && typeof col.find(v => v != null) === "number";
45
44
 
46
- // Column order. Prefer the explicit `spec.columns` sent by R: a JSON object
47
- // reorders integer-like keys (e.g. "1", "2") ahead of string keys, so
48
- // Object.keys(data) alone would scramble columns whose names are numbers.
45
+ // Column order: prefer spec.columns from R; JSON objects put integer-like
46
+ // keys ("1", "2") first, so Object.keys(data) would scramble numeric names.
49
47
  const colOrder = spec => (spec.columns || Object.keys(spec.data || {}))
50
48
  .filter(c => c in (spec.data || {}));
51
49
 
52
- // Display label for a column: the last "label" op that names it, else `c`.
50
+ // Column label: last "label" op naming it, else `c`.
53
51
  const colLabel = (ops, c) => {
54
52
  let lbl = c;
55
53
  for (const op of ops) if (op.type === "label" && op.labels?.[c] != null) lbl = op.labels[c];
56
54
  return lbl;
57
55
  };
58
56
 
59
- // Expand JS exponential notation (e.g. "4.2e+3") to plain decimal,
60
- // preserving the significant digits produced by toPrecision.
57
+ // Expand exponential notation ("4.2e+3") to plain decimal, keeping
58
+ // toPrecision digits.
61
59
  function expandExp(s) {
62
60
  if (!/e/i.test(s)) return s;
63
61
  const [, sign, int, frac = "", expStr] =
@@ -128,25 +126,24 @@
128
126
 
129
127
  if (/year/i.test(lbl) && col.every(v => v == null || /^\d{4}$/.test(String(v)))) continue;
130
128
 
131
- // Determine decimal places: find max significant decimals across column,
132
- // then cap dynamically based on the largest integer-part width (targeting
133
- // ~4 total significant digits): e.g., values <1 get up to 4 decimals,
134
- // 10-99 get 2, >=1000 get 0.
129
+ // Decimals: max significant decimals across column, capped by
130
+ // largest integer-part width (~4 significant digits): <1 up to 4,
131
+ // 10-99 2, >=1000 0.
135
132
  let maxInt = 0, n = 0;
136
133
  for (const v of col) {
137
134
  if (!isNum(v)) continue;
138
- // Number of digits before the decimal point
135
+ // Integer digits
139
136
  const a = Math.abs(pct ? v * 100 : v),
140
137
  intW = a < 1 ? 0 : Math.floor(Math.log10(a)) + 1;
141
138
  if (intW > maxInt) maxInt = intW;
142
- // Significant decimals (strip trailing zeros; adjust for pct *100)
139
+ // Significant decimals (trailing zeros stripped; pct adjusts
140
+ // *100)
143
141
  const m = String(v).match(/\.(\d+)/);
144
142
  if (!m) continue;
145
143
  const d = m[1].replace(/0+$/, "").length - (pct ? 2 : 0);
146
144
  if (d > n) n = d;
147
145
  }
148
- // Cap: 4 decimals max, minus integer width (so large numbers get fewer).
149
- // n is already >= 0, so only the upper cap is needed.
146
+ // Cap 4 decimals minus integer width; n >= 0, so only upper cap.
150
147
  n = Math.min(n, Math.max(4 - maxInt, 0));
151
148
 
152
149
  for (let i = 0; i < nRow; i++) {
@@ -165,7 +162,7 @@
165
162
  colNames = colOrder(spec),
166
163
  nRow = colNames.length ? data[colNames[0]].length : 0;
167
164
 
168
- // Working copy: display[col][row] = string
165
+ // display[col][row] = string
169
166
  const display = {};
170
167
  for (const c of colNames) {
171
168
  display[c] = data[c].map(str);
@@ -173,7 +170,7 @@
173
170
 
174
171
  autoFmt(spec, display, nRow);
175
172
 
176
- // Run fn(col, row, rawValue) over each existing cell of the given columns.
173
+ // Run fn(col, row, raw) over existing cells of columns.
177
174
  const eachCell = (cols, fn) => {
178
175
  for (const c of cols) {
179
176
  if (!data[c]) continue;
@@ -230,10 +227,9 @@
230
227
  }
231
228
  }
232
229
 
233
- // Default display for missing (null/NA) cells: an em dash unless spec.missing
234
- // overrides it (set to "" to keep them blank). A per-column lt_sub(missing=)
235
- // has already filled its cells above, so only still-empty null cells get the
236
- // default; empty strings in the data stay empty.
230
+ // Missing (null/NA) default: em dash unless spec.missing overrides (""
231
+ // = blank). Per-column lt_sub(missing=) already filled above, so only
232
+ // still-empty null cells get default; empty strings stay.
237
233
  const miss = spec.missing === undefined ? "—" : spec.missing;
238
234
  if (miss) {
239
235
  for (const c of colNames)
@@ -250,10 +246,10 @@
250
246
  ops = spec.ops || [],
251
247
  colNames = colOrder(spec),
252
248
  nRow = colNames.length ? data[colNames[0]].length : 0,
253
- // Run fn on each op of the given type, in document order.
249
+ // Run fn on each op of type, in document order.
254
250
  onOp = (t, fn) => { for (const op of ops) if (op.type === t) fn(op); };
255
251
 
256
- // row_group: array → rowspan mode; string → separator-row mode
252
+ // row_group: array = rowspan mode; string = separator-row mode
257
253
  let rowGroupSep = typeof spec.row_group === "string";
258
254
  const rowGroupCols = Array.isArray(spec.row_group) ? spec.row_group
259
255
  : (spec.row_group ? [spec.row_group] : []);
@@ -286,7 +282,7 @@
286
282
  }
287
283
  });
288
284
 
289
- // Set arr[i] = val where i is the position of column c in `visible`.
285
+ // arr[i] = val, i = position of c in `visible`.
290
286
  const setByCol = (arr, c, val) => { const i = visible.indexOf(c); if (i >= 0) arr[i] = val; };
291
287
 
292
288
  // Alignment: default from data type (number→right, else left), then overrides
@@ -315,8 +311,8 @@
315
311
  if (op.rows) for (const r of op.rows) indent[r - 1] = op.level ?? 1;
316
312
  });
317
313
 
318
- // Runs of equal consecutive values in col → [{ label, rows (1-based) }].
319
- // Used for both separator-row groups and rowspan span sizes.
314
+ // Runs of equal consecutive values in col -> [{label, rows (1-based)}];
315
+ // for separator groups and rowspans.
320
316
  const runs = col => {
321
317
  const out = [];
322
318
  for (let i = 0; i < nRow;) {
@@ -327,15 +323,15 @@
327
323
  return out;
328
324
  };
329
325
 
330
- // Row groups from data column (separator-row mode only). A group label is
331
- // raw HTML when its source column is flagged raw via html_cols.
326
+ // Row groups from data column (separator mode); label raw if source
327
+ // column in html_cols.
332
328
  let groups = [];
333
329
  if (rowGroupSep && rowGroupCols.length && data[rowGroupCols[0]]) {
334
330
  const raw = rawCol(spec.html_cols, rowGroupCols[0]);
335
331
  groups.push(...runs(data[rowGroupCols[0]]).map(g => ({ ...g, raw })));
336
332
  }
337
- // Manual groups (labels always escaped; the label comes from an R argument
338
- // name, which cannot carry an I() raw-HTML marker)
333
+ // Manual groups (label always escaped: comes from R arg name, cannot
334
+ // carry I())
339
335
  onOp("row_group", op => groups.push({ label: op.label, rows: op.rows }));
340
336
  // Group ordering
341
337
  onOp("group_order", op => {
@@ -362,12 +358,10 @@
362
358
  // Styles: the style ops are consumed directly (css/class/columns/rows/test).
363
359
  const styles = ops.filter(op => op.type === "style");
364
360
 
365
- // Explicit spanners: reorder each spanner's columns to match the final
366
- // (post-move) body order, so a spanner is recorded/rendered correctly
367
- // regardless of the order in which its columns were listed. A spanner is
368
- // matched to the visual position of its first column and then spans the
369
- // next columns.length cells, so a first column that is not the leftmost in
370
- // `visible` would otherwise misalign the header row.
361
+ // Explicit spanners: reorder columns to final (post-move) body order.
362
+ // Spanner matches visual position of first column, then spans next
363
+ // columns.length cells, so a non-leftmost first column would misalign
364
+ // header.
371
365
  let spanners = (spec.spanners || []).map(sp => {
372
366
  const cols = sp.columns.slice().sort((a, b) => visible.indexOf(a) - visible.indexOf(b));
373
367
  return { ...sp, columns: cols };
@@ -396,11 +390,10 @@
396
390
  }
397
391
  }
398
392
 
399
- // Inline-graphics cells: an op whose type has a renderer registered on
400
- // LT.cells (shipped by lt-plot.js) draws its value column as inline SVG
401
- // (e.g. an error bar). The renderer maps the op to a per-column config
402
- // here; pushRow and the footer consult cellMap[col] = { rnd, cfg }. Keeping
403
- // the drawing in a module leaves core with no plot-specific code.
393
+ // Inline-graphics cells: op type with renderer on LT.cells (from
394
+ // lt-plot.js) draws its value column as inline SVG. Renderer maps op to
395
+ // per-column config; pushRow and footer consult cellMap[col] = { rnd,
396
+ // cfg }.
404
397
  const cellMap = {};
405
398
  for (const op of ops) {
406
399
  const rnd = cellRenderers[op.type];
@@ -419,7 +412,7 @@
419
412
  };
420
413
  }
421
414
 
422
- // Footnotes: dedup by text, assign 1..N in first-seen order.
415
+ // Footnotes: dedup by text, number 1..N by first appearance.
423
416
  function indexFootnotes(fns) {
424
417
  const order = [], idx = {};
425
418
  fns.forEach(f => {
@@ -428,9 +421,8 @@
428
421
  return { order, idx };
429
422
  }
430
423
 
431
- // Find the footnote index for a (type, value) location; 0 if none.
432
- // `val` is a scalar: the title group, a single column, a spanner label,
433
- // or a row-group label, depending on `type`.
424
+ // Footnote index for (type, value) location; 0 if none. `val` scalar: title
425
+ // group, column, spanner label, or row-group label, per `type`.
434
426
  const matcher = (fns, idx) => (type, val) => {
435
427
  for (const f of fns) {
436
428
  const loc = f.location;
@@ -468,7 +460,7 @@
468
460
  return 0;
469
461
  });
470
462
  for (const c of colNames) data[c] = idx.map(i => data[c][i]);
471
- // Remap 1-based row indices in ops to reflect the new order
463
+ // Remap 1-based row indices in ops to new order
472
464
  const newPos = new Array(nRow);
473
465
  for (let i = 0; i < nRow; i++) newPos[idx[i]] = i + 1;
474
466
  for (const op of (spec.ops || [])) {
@@ -476,17 +468,16 @@
476
468
  }
477
469
  }
478
470
 
479
- // Materialize columns from `add_col` ops: build an empty column (filled with
480
- // op.value ?? "") from the shipped column name, so the rest of the runtime
481
- // treats it as an ordinary data column. Appended last (use lt_move() to
482
- // position it).
471
+ // Materialize `add_col` ops: empty column (op.value ?? "") from shipped
472
+ // name, so runtime treats it as ordinary. Appended last (lt_move()
473
+ // positions it).
483
474
  function addColumns(spec) {
484
475
  const data = spec.data || (spec.data = {}),
485
476
  nRow = data[colOrder(spec)[0]]?.length || 0;
486
477
  for (const op of (spec.ops || []))
487
478
  if (op.type === "add_col" && op.column && !(op.column in data)) {
488
479
  data[op.column] = new Array(nRow).fill(op.value ?? "");
489
- // when an explicit column order is shipped, keep the new column in it
480
+ // keep new column in explicit column order, if shipped
490
481
  if (spec.columns && !spec.columns.includes(op.column))
491
482
  spec.columns = [...spec.columns, op.column];
492
483
  }
@@ -499,34 +490,35 @@
499
490
  { display, nRow } = applyOps(spec),
500
491
  { visible: cols, align, colLabels, colWidths, tableWidth, indent,
501
492
  groups, rowSpans, styles, spanners, cellMap, footnotes: fns, notes, header: hdr } = resolveSpec(spec),
502
- // Core helpers passed to a cell renderer (see LT.cells / lt-plot.js).
493
+ // Core helpers for cell renderer (see LT.cells /
494
+ // lt-plot.js).
503
495
  U = { esc, isNum, str },
504
496
  reg = indexFootnotes(fns),
505
497
  fIdx = matcher(fns, reg.idx),
506
498
  nGrp = rowSpans.length,
507
499
  nCol = cols.length + nGrp,
508
- // Whether column `c`'s body cells are raw HTML (see lt_html() on the
509
- // R side); spec.html_cols is true (all columns) or a name array.
500
+ // Column `c` body cells raw HTML? (see lt_html() in R);
501
+ // spec.html_cols true or names.
510
502
  isRaw = c => rawCol(spec.html_cols, c),
511
503
  out = [`<table class="lt-table"${tableWidth ? ` style="width:${tableWidth}"` : ""}>`],
512
- // Cap the initial render to the first page (pager[0], 0 = all), so a
513
- // huge table doesn't build the whole row string before the plugin
514
- // pages it down. Only when the plugin is loaded to page the rest back
515
- // in; a static bake renders every row. `_viewRows` overrides it.
504
+ // Cap initial render to first page (pager[0], 0 = all) so
505
+ // huge tables don't build whole row string before plugin
506
+ // pages. Only when plugin loaded to page rest in; static
507
+ // bake renders all. `_viewRows` overrides.
516
508
  pg = root.LT?.plugins?.interactive && spec.interactive?.pager,
517
509
  lim = (!spec._viewRows && Array.isArray(pg) && pg[0]) ? pg[0] : 0;
518
510
  const mark = (type, val) => { const i = fIdx(type, val); return i ? sup(i) : ""; },
519
511
  cell = (c, r) => display[c]?.[r - 1] ?? "";
520
- // ` name="val"` for a truthy val, else "" — for optional HTML attributes.
512
+ // ` name="val"` if val truthy, else "" (optional attrs).
521
513
  const attr = (n, v) => v ? ` ${n}="${v}"` : "";
522
- // Plain class names per column (alignment + leading-indent), "" if none.
514
+ // Plain class names per column (alignment + indent), "" if none.
523
515
  const colCls = cols.map((_, i) => (
524
516
  (i === 0 && groups.length ? "lt-indent " : "") +
525
517
  ({right: "al-r", center: "al-c"}[align[i]] || "")
526
518
  ).trimEnd());
527
519
 
528
- // Visit each cell at (rows × cols) that exists in the table, calling
529
- // fn(key, c, r). rows null = all rows; cols falls back to all columns.
520
+ // Visit existing cells at rows x cols, calling fn(key, c, r). rows null
521
+ // = all; cols default all.
530
522
  const eachLoc = (rows, locCols, fn) => {
531
523
  for (let r = 1; r <= nRow; r++) {
532
524
  if (rows && !rows.includes(r)) continue;
@@ -547,8 +539,8 @@
547
539
  if (s.class) addTo(classMap, key, s.class, " ");
548
540
  });
549
541
 
550
- // <colgroup>: leading empty <col>s for rowspan group columns, so widths
551
- // align with the body columns (which are offset by nGrp on the left).
542
+ // <colgroup>: leading empty <col>s for rowspan group columns, aligning
543
+ // widths with body columns (offset nGrp).
552
544
  if (colWidths && colWidths.some(w => w)) {
553
545
  out.push(`<colgroup>`);
554
546
  if (nGrp) out.push("<col>".repeat(nGrp));
@@ -556,7 +548,7 @@
556
548
  out.push(`</colgroup>`);
557
549
  }
558
550
 
559
- // <caption>: title + subtitle, each a <div> rendered only when non-empty.
551
+ // <caption>: title + subtitle, each <div> only if non-empty.
560
552
  const caption = [["title", "lt-title"], ["subtitle", "lt-subtitle"]]
561
553
  .filter(([g]) => hdr[g] != null && hdr[g] !== "")
562
554
  .map(([g, cls]) => `<div class="${cls}">${txt(hdr[g])}${mark("title", g)}</div>`);
@@ -599,15 +591,13 @@
599
591
  // Row rendering
600
592
  const pushRow = (r, spanCells) => {
601
593
  out.push(`<tr>`);
602
- // Row-group cells. For a group spanning n > 1 rows, the label goes in a
603
- // non-spanning cell on the first row — so vertical-align centers it
604
- // within that row's height (matching the body cells) instead of across
605
- // the whole span — followed by an empty filler cell spanning the
606
- // remaining n - 1 rows. A single-row group is just the label cell. The
607
- // per-column descriptor ({label, open} for the label cell, {fill} for the
608
- // filler, nothing when covered by a filler above) is supplied by the
609
- // caller when rows are reordered (`spanCells`, computed in view order),
610
- // else derived from the file-order spans.
594
+ // Row-group cells. Group spanning n > 1 rows: label in non-spanning
595
+ // cell on first row (vertical-align centers within that row like
596
+ // body cells, not across span), then empty filler spanning
597
+ // remaining n - 1 rows. Single-row group: label cell only.
598
+ // Per-column descriptor ({label, open} label cell, {fill} filler,
599
+ // nothing if covered above) comes from caller for reordered rows
600
+ // (`spanCells`, view order), else from file-order spans.
611
601
  for (let gi = 0; gi < rowSpans.length; gi++) {
612
602
  const rs = rowSpans[gi];
613
603
  let d = spanCells ? spanCells[gi] : null;
@@ -630,8 +620,8 @@
630
620
  if (ci === 0 && ind) s = (s ? s + ";" : "") + `padding-left:${ind + 1}em`;
631
621
  const cm = cellMap[c];
632
622
  if (cm) {
633
- // A plot cell: the renderer supplies the inner SVG and may add a <td>
634
- // class (e.g. to zero padding so a gridline background runs unbroken).
623
+ // Plot cell: renderer supplies inner SVG, may add <td>
624
+ // class (e.g. zero padding for unbroken gridlines).
635
625
  const extra = cm.rnd.cellClass?.(cm.cfg) || "",
636
626
  pcls = [cls, extra].filter(Boolean).join(" ");
637
627
  out.push(`<td${attr("class", pcls)}${attr("style", s)}>${cm.rnd.cell(cm.cfg, data, r, U)}${m ? sup(m) : ""}</td>`);
@@ -644,17 +634,16 @@
644
634
  out.push(`</tr>`);
645
635
  };
646
636
 
647
- // A separator row-group header: a single full-width cell carrying the label.
637
+ // Separator row-group header: one full-width cell with label.
648
638
  const groupHeader = (label, raw) =>
649
639
  `<tr class="lt-row-group"><th colspan="${nCol}" scope="colgroup">${escIf(raw, label)}${mark("row_groups", label)}</th></tr>`;
650
640
 
651
- // Rowspan group cells recomputed for a reordered view: the file-order
652
- // `rs.spans` no longer describe the runs, so walk the view sequence and
653
- // group its rows into runs sharing the same group-value prefix (column gi's
654
- // run breaks when its value or any earlier group column's value changes).
655
- // Each run's first row gets the label cell, its second a filler spanning the
656
- // rest; the remaining rows get nothing. Returns one descriptor array per
657
- // view position, matching pushRow's `spanCells`.
641
+ // Rowspan group cells for reordered view: file-order `rs.spans` no
642
+ // longer fit, so walk view sequence, grouping rows into runs sharing
643
+ // group-value prefix (column gi's run breaks when its or any earlier
644
+ // group column's value changes). Run's first row gets label cell,
645
+ // second a filler spanning rest, others nothing. Returns descriptor
646
+ // array per view position (pushRow's `spanCells`).
658
647
  const viewRowSpans = seq => {
659
648
  const info = seq.map(() => []);
660
649
  for (let gi = 0; gi < rowSpans.length; gi++) {
@@ -673,14 +662,13 @@
673
662
  return info;
674
663
  };
675
664
 
676
- // <tbody>. An optional `spec._viewRows` sets the order/subset of rows — the
677
- // seam the interactive plugin uses to sort/filter without re-implementing row
678
- // rendering. Each entry is a 1-based original row index, or (for a grouped
679
- // table) an object `{label, raw}` for a separator group header the plugin
680
- // decided to re-emit. It takes precedence over the file-order branches below,
681
- // which draw the static table. Row-indexed styles/footnotes/indent stay
682
- // correct because they remain keyed to the original indices. In rowspan mode
683
- // the span cells are recomputed from the view order (viewRowSpans).
665
+ // <tbody>. Optional `spec._viewRows` sets row order/subset: seam for
666
+ // interactive plugin sort/filter without reimplementing row rendering.
667
+ // Entry = 1-based original row index or, for grouped tables, `{label,
668
+ // raw}` separator header the plugin re-emits. Overrides file-order
669
+ // branches (static table). Row-indexed styles/footnotes/indent stay
670
+ // keyed to original indices. Rowspan mode recomputes spans from view
671
+ // order (viewRowSpans).
684
672
  out.push(`<tbody>`);
685
673
  if (spec._viewRows) {
686
674
  const info = rowSpans.length ?
@@ -705,10 +693,10 @@
705
693
  }
706
694
  out.push(`</tbody>`);
707
695
 
708
- // <tfoot>: an optional plot-footer row (e.g. a shared error-bar axis), then
709
- // footnotes and source notes. The footer row carries a per-column cell so
710
- // each renderer's footer SVG lines up under its plot column; the footnote/
711
- // note rows span the full width.
696
+ // <tfoot>: optional plot-footer row (e.g. shared error-bar axis), then
697
+ // footnotes and source notes. Footer row has per-column cell so each
698
+ // renderer's footer SVG aligns under its plot column; note rows span
699
+ // full width.
712
700
  const footCells = cols.map(c =>
713
701
  cellMap[c] ? (cellMap[c].rnd.foot?.(cellMap[c].cfg, U) || "") : "");
714
702
  const hasFoot = footCells.some(h => h);
@@ -720,7 +708,7 @@
720
708
  out.push(`<td></td>`.repeat(nGrp));
721
709
  cols.forEach((c, i) => {
722
710
  const cm = cellMap[c];
723
- // reuse the renderer's cell class so the footer lines up with the plot
711
+ // reuse renderer's cell class to align footer with plot
724
712
  const extra = footCells[i] && cm ? (cm.rnd.cellClass?.(cm.cfg) || "") : "",
725
713
  ac = [colCls[i], extra].filter(Boolean).join(" ");
726
714
  out.push(`<td${attr("class", ac)}>${footCells[i]}</td>`);
@@ -733,61 +721,58 @@
733
721
  }
734
722
 
735
723
  out.push(`</table>`);
736
- // Expose the resolved visible column order (after hide/move) so plugins can
737
- // sort/filter without re-deriving it. Set as a side effect, never read by
738
- // core; harmless for the static/Node render path.
724
+ // Expose resolved visible column order (after hide/move) for plugin
725
+ // sort/filter. Side effect only; core never reads it; harmless for
726
+ // static/Node.
739
727
  spec._cols = cols;
740
- // Also expose the formatted cell text (every column, including hidden ones),
741
- // so plugins can show the displayed values (e.g. a row detail).
728
+ // Also formatted cell text (all columns, hidden too), so plugins can
729
+ // show displayed values (e.g. row detail).
742
730
  spec._display = display;
743
- // Expose the resolved row structure so the interactive plugin can honor it:
744
- // the separator row groups (each `{label, rows, raw}`), the per-row indent
745
- // levels (an array, or null when none), and the rowspan group columns (the
746
- // column names drawn as spanning cells, outermost first, or null) — the
747
- // plugin sorts/filters within each run and recomputes the spans in view
748
- // order (see buildHtml's viewRowSpans).
731
+ // Expose resolved row structure for interactive plugin: separator
732
+ // groups ({label, rows, raw}), per-row indent levels (array or null),
733
+ // rowspan group columns (outermost first, or null). Plugin
734
+ // sorts/filters within each run and recomputes spans in view order (see
735
+ // viewRowSpans).
749
736
  spec._groups = groups.length ? groups : null;
750
737
  spec._indent = indent.some(v => v) ? indent : null;
751
738
  spec._rowspan = rowSpans.length ? rowSpans.map(rs => rs.col) : null;
752
- // Wrap in a div so a wide table can scroll horizontally (`overflow-x`)
753
- // instead of overflowing the page. `spec.wrap` (set by lt_wrap()) carries
754
- // arbitrary attributes for this div: `class` is appended to the base
755
- // `lt-wrap`, the rest emitted as-is (escaped) -- a hook for scoping custom
756
- // CSS, an id, a fixed width, etc.
739
+ // Wrap in div so wide tables scroll horizontally (`overflow-x`).
740
+ // `spec.wrap` (lt_wrap()) gives attributes: `class` appended to base
741
+ // `lt-wrap`, rest emitted escaped; hook for scoped CSS, id, fixed
742
+ // width.
757
743
  const w = spec.wrap || {}, cls = ["lt-wrap"].concat(w.class || []).join(" ");
758
744
  const wa = Object.keys(w).filter(k => k !== "class")
759
745
  .map(k => attr(k, esc(w[k]))).join("");
760
746
  return `<div${attr("class", cls)}${wa}>${out.join("")}</div>`;
761
747
  }
762
748
 
763
- // Plugin seam (see lt-interactive.js): a plugin attaches its handle under
764
- // LT.plugins and pushes a callback onto LT.onMount, which core calls with
765
- // each table element and its spec right after the table is mounted.
766
- // Cell-renderer seam (see lt-plot.js): a module registers an inline-graphics
767
- // renderer under LT.cells, keyed by op type, which core consults *during*
768
- // buildHtml (not post-mount) to draw a column's cells and an optional footer.
749
+ // Plugin seam (lt-interactive.js): plugin attaches handle under LT.plugins
750
+ // and pushes callback onto LT.onMount; core calls it with each table
751
+ // element and spec after mount.
752
+ // Cell-renderer seam (lt-plot.js): module registers renderer under LT.cells
753
+ // by op type; core consults it *during* buildHtml to draw a column's cells
754
+ // and optional footer.
769
755
  const plugins = root.LT?.plugins || {}, onMount = root.LT?.onMount || [];
770
756
 
771
- // Alt-click toggles raw values in this table; alt-dblclick toggles page-wide.
772
- // The handlers must not *return* false (a false return from a DOM0 handler
773
- // cancels the click's default action — which would, e.g., stop a checkbox
774
- // inside the table from toggling), so they use statement bodies.
757
+ // Alt-click toggles raw values in this table; alt-dblclick page-wide.
758
+ // Handlers must not *return* false (cancels click default, e.g. checkbox in
759
+ // table wouldn't toggle), so use statement bodies.
775
760
  const wireRaw = tbl => {
776
761
  const raw = (e, el) => { if (e.altKey) el.classList.toggle("lt-raw"); };
777
762
  tbl.onclick = e => { if (e.detail === 1) raw(e, tbl); };
778
763
  tbl.ondblclick = e => { raw(e, tbl.ownerDocument.documentElement); };
779
764
  };
780
765
 
781
- // Finish a freshly inserted table: remember its spec, wire the raw-value
782
- // toggle, and let the plugins enhance it. Returns the table element.
766
+ // Finish inserted table: remember spec, wire raw toggle, let plugins
767
+ // enhance. Returns table element.
783
768
  const ready = (tbl, spec) => {
784
- // Stash the spec so a plugin loaded *after* this table mounted (the usual
785
- // case — core drains the queue before a plugin file runs) can still find
786
- // and enhance it by scanning `.lt-table`.
769
+ // Stash spec so plugin loaded *after* mount (usual: core drains queue
770
+ // before plugin file runs) can find and enhance it by scanning
771
+ // `.lt-table`.
787
772
  tbl._ltSpec = spec;
788
- // Map each visible column to its header cell, for a plugin tracking a column
789
- // (e.g. observing its width). Built before any plugin adds <thead> rows, so
790
- // the last header row is the labels row; nGrp offsets the data columns.
773
+ // Map visible column to header cell, for plugins tracking a column
774
+ // (e.g. width). Built before plugins add <thead> rows, so last header
775
+ // row is labels; nGrp offsets data columns.
791
776
  const hr = tbl.tHead && [...tbl.tHead.rows].pop(),
792
777
  nGrp = (spec._rowspan || []).length;
793
778
  if (hr) {
@@ -804,18 +789,17 @@
804
789
  ready($(s.nextElementSibling, "table"), spec);
805
790
  };
806
791
 
807
- // Render a spec into `el` (replacing its content) at any time, e.g. long
808
- // after the page loaded, for a table built on demand. Unlike build(), it
809
- // needs no inline <script> to anchor to, and the caller may hold on to the
810
- // returned table element.
792
+ // Render spec into `el` (replacing content) anytime, e.g. on-demand tables
793
+ // long after load. Unlike build(), needs no anchoring <script>; caller may
794
+ // keep returned table.
811
795
  const render = (el, spec) => {
812
796
  el.innerHTML = buildHtml(spec);
813
797
  return ready($(el, "table"), spec);
814
798
  };
815
- // Rebuild an already-mounted table in place from its stashed spec. Used by a
816
- // cell module (lt-plot.js) that loads *after* core has built a table (e.g. a
817
- // litedown/knitr doc where an earlier plain table pulled in lt.js first): the
818
- // module registers its renderer, then refreshes the tables that needed it.
799
+ // Rebuild mounted table in place from stashed spec. For cell module
800
+ // (lt-plot.js) loading *after* core built a table (e.g. earlier plain table
801
+ // pulled in lt.js first): module registers renderer, then refreshes tables
802
+ // needing it.
819
803
  const refresh = tbl => {
820
804
  const spec = tbl?._ltSpec, wrap = tbl?.closest(".lt-wrap");
821
805
  if (!spec || !wrap) return;
@@ -824,11 +808,12 @@
824
808
  wrap.remove();
825
809
  return ready($(next, "table"), spec);
826
810
  };
827
- // q.push renders immediately; replay any entries queued before we loaded.
811
+ // q.push renders now; replay entries queued before load.
828
812
  const q = { push: e => mount(e.s, e.d) };
829
813
  (root.LT?.q || []).forEach(q.push);
830
814
  root.LT = {
831
815
  build: spec => mount(document.currentScript, spec),
832
816
  render, refresh, buildHtml, plugins, onMount, cells: cellRenderers, q,
817
+ $, $$, on, off, numCol,
833
818
  };
834
819
  })(window);