@peter.prib/renderengine 0.7.0 → 0.9.0

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.
@@ -3668,153 +3668,155 @@
3668
3668
  }
3669
3669
  }
3670
3670
 
3671
- /**
3672
- * PopupMenu — the one popup/context menu: a small menu at a screen position,
3673
- * closed by choosing an item, clicking elsewhere, Escape, or scrolling (it
3674
- * would no longer be beside what it was opened on). One is open at a time.
3675
- * Editor menus, the graph engine's ContextMenu and the model tree's menus all
3676
- * render through it.
3677
- *
3678
- * Items: `{ label, action, danger?, checked?, disabled? }`,
3679
- * `{ label, items: [...] }` for a submenu, or `{ separator: true }`.
3680
- */
3681
- class PopupMenu {
3682
- static _open = null;
3683
-
3684
- static show(x, y, items, doc = document) {
3685
- PopupMenu.close();
3686
- if (!items.length) return null;
3687
- const menu = el({
3688
- ...PopupMenu._panel(items, doc),
3689
- style: { ...PopupMenu._panelStyle, position: 'fixed', left: `${x}px`, top: `${y}px` },
3690
- }, doc);
3691
- doc.body.appendChild(menu);
3692
- // Opened near the window's right or bottom edge, it moves back into the window.
3693
- const win = doc.defaultView;
3694
- const box = menu.getBoundingClientRect?.();
3695
- if (win && box?.width) {
3696
- const at = PopupMenu.fit(x, y, box.width, box.height, win.innerWidth, win.innerHeight);
3697
- Object.assign(menu.style, { left: `${at.x}px`, top: `${at.y}px` });
3698
- }
3699
- // Registered after the opening click has finished propagating.
3700
- const dismiss = () => PopupMenu.close();
3701
- const onKey = (e) => { if (e.key === 'Escape') PopupMenu.close(); };
3702
- setTimeout(() => {
3703
- if (PopupMenu._open?.menu !== menu) return; // closed meanwhile
3704
- doc.addEventListener('click', dismiss, { once: true });
3705
- doc.addEventListener('scroll', dismiss, { once: true, capture: true });
3706
- doc.addEventListener('keydown', onKey);
3707
- }, 0);
3708
- PopupMenu._open = { menu, dismiss, onKey, doc };
3709
- return menu;
3710
- }
3711
-
3712
- /**
3713
- * Where a menu of a size goes, asked for at (x, y), to be all inside a
3714
- * window of a size: left of the point when it would pass the right edge,
3715
- * above it when it would pass the bottom, never past the top-left.
3716
- */
3717
- static fit(x, y, width, height, windowWidth, windowHeight, margin = 4) {
3718
- const left = x + width + margin > windowWidth ? x - width : x;
3719
- const top = y + height + margin > windowHeight ? y - height : y;
3720
- return {
3721
- x: Math.max(margin, Math.min(left, windowWidth - width - margin)),
3722
- y: Math.max(margin, Math.min(top, windowHeight - height - margin)),
3723
- };
3724
- }
3725
-
3726
- /**
3727
- * Where a submenu opens beside its item (the item's box `{left, right, top}`),
3728
- * to be all inside the window: to the right, or to the left when the right
3729
- * would pass the edge (and there is more room on the left); level with the
3730
- * item, or lifted by as much as it would pass the bottom. `top` is relative
3731
- * to the item, as the submenu is positioned.
3732
- */
3733
- static submenuPlacement(item, width, height, windowWidth, windowHeight, margin = 4) {
3734
- const fitsRight = item.right + width + margin <= windowWidth;
3735
- const side = fitsRight || item.left < windowWidth - item.right ? 'right' : 'left';
3736
- const top = -4;
3737
- const overflow = item.top + top + height + margin - windowHeight;
3738
- return { side, top: overflow > 0 ? Math.max(top - overflow, margin - item.top) : top };
3739
- }
3740
-
3741
- static close() {
3742
- const open = PopupMenu._open;
3743
- if (!open) return;
3744
- open.menu.remove();
3745
- open.doc.removeEventListener('click', open.dismiss);
3746
- open.doc.removeEventListener('scroll', open.dismiss, { capture: true });
3747
- open.doc.removeEventListener('keydown', open.onKey);
3748
- PopupMenu._open = null;
3749
- }
3750
-
3751
- static get isOpen() {
3752
- return !!PopupMenu._open;
3753
- }
3754
-
3755
- static _panelStyle = {
3756
- background: '#fff', border: '1px solid #ccc', borderRadius: '3px', boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
3757
- zIndex: '10000', minWidth: '170px', fontSize: '12px', fontFamily: 'sans-serif', padding: '4px 0',
3758
- };
3759
-
3760
- static _panel(items, doc) {
3761
- return { attrs: { role: 'menu' }, children: items.map(item => PopupMenu._item(item, doc)) };
3762
- }
3763
-
3764
- static _item(item, doc) {
3765
- if (item.separator) return { attrs: { role: 'separator' }, style: { borderTop: '1px solid #ddd', margin: '4px 0' } };
3766
- const hover = item.danger ? '#ffe8e8' : '#f0f0f0';
3767
- const base = {
3768
- attrs: { role: 'menuitem', 'aria-disabled': item.disabled ? 'true' : null, 'aria-checked': item.checked != null ? String(!!item.checked) : null },
3769
- style: {
3770
- padding: '7px 14px', cursor: item.disabled ? 'default' : 'pointer', position: 'relative', whiteSpace: 'nowrap',
3771
- color: item.disabled ? '#aaa' : item.danger ? '#cc3333' : '', background: item.checked ? '#e3f2fd' : '',
3772
- },
3773
- };
3774
- if (item.items) {
3775
- let sub;
3776
- return {
3777
- ...base,
3778
- attrs: { ...base.attrs, 'aria-haspopup': 'menu' },
3779
- on: {
3780
- mouseenter: (e) => {
3781
- e.currentTarget.style.background = hover;
3782
- sub.style.display = 'block';
3783
- // Opened near the window's right or bottom edge, it opens left, or lifts.
3784
- const win = e.currentTarget.ownerDocument.defaultView;
3785
- const box = sub.getBoundingClientRect?.();
3786
- if (!win || !box?.width) return;
3787
- const at = PopupMenu.submenuPlacement(e.currentTarget.getBoundingClientRect(), box.width, box.height, win.innerWidth, win.innerHeight);
3788
- Object.assign(sub.style, at.side === 'left' ? { left: 'auto', right: '100%' } : { left: '100%', right: 'auto' }, { top: `${at.top}px` });
3789
- },
3790
- mouseleave: (e) => { e.currentTarget.style.background = ''; sub.style.display = 'none'; },
3791
- click: (e) => e.stopPropagation(),
3792
- },
3793
- children: [
3794
- `${item.label} ▸`,
3795
- {
3796
- ...PopupMenu._panel(item.items, doc),
3797
- style: { ...PopupMenu._panelStyle, position: 'absolute', left: '100%', top: '-4px', display: 'none' },
3798
- ref: (n) => { sub = n; },
3799
- },
3800
- ],
3801
- };
3802
- }
3803
- return {
3804
- ...base,
3805
- text: item.label,
3806
- on: {
3807
- mouseenter: (e) => { if (!item.disabled) e.currentTarget.style.background = hover; },
3808
- mouseleave: (e) => { e.currentTarget.style.background = item.checked ? '#e3f2fd' : ''; },
3809
- click: (e) => {
3810
- e.stopPropagation();
3811
- if (item.disabled) return;
3812
- PopupMenu.close();
3813
- item.action();
3814
- },
3815
- },
3816
- };
3817
- }
3671
+ /**
3672
+ * PopupMenu — the one popup/context menu: a small menu at a screen position,
3673
+ * closed by choosing an item, clicking elsewhere, Escape, or scrolling (it
3674
+ * would no longer be beside what it was opened on). One is open at a time.
3675
+ * Editor menus, the graph engine's ContextMenu and the model tree's menus all
3676
+ * render through it.
3677
+ *
3678
+ * Items: `{ label, action, danger?, checked?, disabled? }`,
3679
+ * `{ label, items: [...] }` for a submenu, or `{ separator: true }`.
3680
+ */
3681
+ class PopupMenu {
3682
+ static _open = null;
3683
+
3684
+ static show(x, y, items, doc = document) {
3685
+ PopupMenu.close();
3686
+ if (!items.length) return null;
3687
+ const menu = el({
3688
+ ...PopupMenu._panel(items, doc),
3689
+ style: { ...PopupMenu._panelStyle, position: 'fixed', left: `${x}px`, top: `${y}px` },
3690
+ }, doc);
3691
+ doc.body.appendChild(menu);
3692
+ // Opened near the window's right or bottom edge, it moves back into the window.
3693
+ const win = doc.defaultView;
3694
+ const box = menu.getBoundingClientRect?.();
3695
+ if (win && box?.width) {
3696
+ const at = PopupMenu.fit(x, y, box.width, box.height, win.innerWidth, win.innerHeight);
3697
+ Object.assign(menu.style, { left: `${at.x}px`, top: `${at.y}px` });
3698
+ }
3699
+ // Registered after the opening click has finished propagating.
3700
+ const dismiss = () => PopupMenu.close();
3701
+ const onKey = (e) => { if (e.key === 'Escape') PopupMenu.close(); };
3702
+ setTimeout(() => {
3703
+ if (PopupMenu._open?.menu !== menu) return; // closed meanwhile
3704
+ doc.addEventListener('click', dismiss, { once: true });
3705
+ doc.addEventListener('scroll', dismiss, { once: true, capture: true });
3706
+ doc.addEventListener('keydown', onKey);
3707
+ }, 0);
3708
+ PopupMenu._open = { menu, dismiss, onKey, doc };
3709
+ return menu;
3710
+ }
3711
+
3712
+ /**
3713
+ * Where a menu of a size goes, asked for at (x, y), to be all inside a
3714
+ * window of a size: left of the point when it would pass the right edge,
3715
+ * above it when it would pass the bottom, never past the top-left.
3716
+ */
3717
+ static fit(x, y, width, height, windowWidth, windowHeight, margin = 4) {
3718
+ const left = x + width + margin > windowWidth ? x - width : x;
3719
+ const top = y + height + margin > windowHeight ? y - height : y;
3720
+ return {
3721
+ x: Math.max(margin, Math.min(left, windowWidth - width - margin)),
3722
+ y: Math.max(margin, Math.min(top, windowHeight - height - margin)),
3723
+ };
3724
+ }
3725
+
3726
+ /**
3727
+ * Where a submenu opens beside its item (the item's box `{left, right, top}`),
3728
+ * to be all inside the window: to the right, or to the left when the right
3729
+ * would pass the edge (and there is more room on the left); level with the
3730
+ * item, or lifted by as much as it would pass the bottom. `top` is relative
3731
+ * to the item, as the submenu is positioned.
3732
+ */
3733
+ static submenuPlacement(item, width, height, windowWidth, windowHeight, margin = 4) {
3734
+ const fitsRight = item.right + width + margin <= windowWidth;
3735
+ const side = fitsRight || item.left < windowWidth - item.right ? 'right' : 'left';
3736
+ const top = -4;
3737
+ const overflow = item.top + top + height + margin - windowHeight;
3738
+ return { side, top: overflow > 0 ? Math.max(top - overflow, margin - item.top) : top };
3739
+ }
3740
+
3741
+ static close() {
3742
+ const open = PopupMenu._open;
3743
+ if (!open) return;
3744
+ open.menu.remove();
3745
+ open.doc.removeEventListener('click', open.dismiss);
3746
+ open.doc.removeEventListener('scroll', open.dismiss, { capture: true });
3747
+ open.doc.removeEventListener('keydown', open.onKey);
3748
+ PopupMenu._open = null;
3749
+ }
3750
+
3751
+ static get isOpen() {
3752
+ return !!PopupMenu._open;
3753
+ }
3754
+
3755
+ // The text colour is set with the background: inherited from a dark-themed page it was light
3756
+ // grey on this white panel, and every item but a disabled or danger one was unreadable.
3757
+ static _panelStyle = {
3758
+ background: '#fff', color: '#222', border: '1px solid #ccc', borderRadius: '3px', boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
3759
+ zIndex: '10000', minWidth: '170px', fontSize: '12px', fontFamily: 'sans-serif', padding: '4px 0',
3760
+ };
3761
+
3762
+ static _panel(items, doc) {
3763
+ return { attrs: { role: 'menu' }, children: items.map(item => PopupMenu._item(item, doc)) };
3764
+ }
3765
+
3766
+ static _item(item, doc) {
3767
+ if (item.separator) return { attrs: { role: 'separator' }, style: { borderTop: '1px solid #ddd', margin: '4px 0' } };
3768
+ const hover = item.danger ? '#ffe8e8' : '#f0f0f0';
3769
+ const base = {
3770
+ attrs: { role: 'menuitem', 'aria-disabled': item.disabled ? 'true' : null, 'aria-checked': item.checked != null ? String(!!item.checked) : null },
3771
+ style: {
3772
+ padding: '7px 14px', cursor: item.disabled ? 'default' : 'pointer', position: 'relative', whiteSpace: 'nowrap',
3773
+ color: item.disabled ? '#aaa' : item.danger ? '#cc3333' : '', background: item.checked ? '#e3f2fd' : '',
3774
+ },
3775
+ };
3776
+ if (item.items) {
3777
+ let sub;
3778
+ return {
3779
+ ...base,
3780
+ attrs: { ...base.attrs, 'aria-haspopup': 'menu' },
3781
+ on: {
3782
+ mouseenter: (e) => {
3783
+ e.currentTarget.style.background = hover;
3784
+ sub.style.display = 'block';
3785
+ // Opened near the window's right or bottom edge, it opens left, or lifts.
3786
+ const win = e.currentTarget.ownerDocument.defaultView;
3787
+ const box = sub.getBoundingClientRect?.();
3788
+ if (!win || !box?.width) return;
3789
+ const at = PopupMenu.submenuPlacement(e.currentTarget.getBoundingClientRect(), box.width, box.height, win.innerWidth, win.innerHeight);
3790
+ Object.assign(sub.style, at.side === 'left' ? { left: 'auto', right: '100%' } : { left: '100%', right: 'auto' }, { top: `${at.top}px` });
3791
+ },
3792
+ mouseleave: (e) => { e.currentTarget.style.background = ''; sub.style.display = 'none'; },
3793
+ click: (e) => e.stopPropagation(),
3794
+ },
3795
+ children: [
3796
+ `${item.label} ▸`,
3797
+ {
3798
+ ...PopupMenu._panel(item.items, doc),
3799
+ style: { ...PopupMenu._panelStyle, position: 'absolute', left: '100%', top: '-4px', display: 'none' },
3800
+ ref: (n) => { sub = n; },
3801
+ },
3802
+ ],
3803
+ };
3804
+ }
3805
+ return {
3806
+ ...base,
3807
+ text: item.label,
3808
+ on: {
3809
+ mouseenter: (e) => { if (!item.disabled) e.currentTarget.style.background = hover; },
3810
+ mouseleave: (e) => { e.currentTarget.style.background = item.checked ? '#e3f2fd' : ''; },
3811
+ click: (e) => {
3812
+ e.stopPropagation();
3813
+ if (item.disabled) return;
3814
+ PopupMenu.close();
3815
+ item.action();
3816
+ },
3817
+ },
3818
+ };
3819
+ }
3818
3820
  }
3819
3821
 
3820
3822
  /**
@@ -6898,6 +6900,16 @@
6898
6900
  dataShape: 'Array<{label, value?, children?}> — same hierarchical shape as treemap/sunburst (shares _hierarchyValue); drawn as an indented, collapsible list instead of nested rectangles/rings — a branch\'s value is auto-summed from its descendants and shown as a trailing count, a leaf\'s own extra fields (anything beyond label/value/children) shown as trailing descriptive text instead',
6899
6901
  streamShape: 'flat',
6900
6902
  },
6903
+ {
6904
+ key: 'table', label: 'Table', method: 'tableChart', category: '2d',
6905
+ coordSystem: COORD_SYSTEM.CARTESIAN, title: true, legend: false, colorMode: COLOR_MODE.NONE, camera: CAMERA_MODE.NONE,
6906
+ axes: [
6907
+ { role: 'row', kind: AXIS_KIND.CATEGORICAL, channel: ENCODING_CHANNEL.POSITION_ORDER, required: false },
6908
+ { role: 'value', kind: AXIS_KIND.NUMERIC, channel: ENCODING_CHANNEL.TEXT_VALUE, required: false },
6909
+ ],
6910
+ dataShape: 'Array<object> — one row per object, a column per key (options.columns: names or {key, label?, align?}; every key of the first row when absent); values shown exactly as text, numeric columns right-aligned; options.maxRows, options.nullText',
6911
+ streamShape: 'flat',
6912
+ },
6901
6913
  {
6902
6914
  key: 'gauge-dial', label: 'Gauge (Dial)', method: 'dialGauge', category: 'gauge',
6903
6915
  coordSystem: COORD_SYSTEM.RADIAL, title: true, legend: false, colorMode: COLOR_MODE.SINGLE, camera: CAMERA_MODE.NONE,
@@ -17669,6 +17681,729 @@
17669
17681
  OutlineChart.INDENT_W = 18;
17670
17682
  OutlineChart.HIERARCHY_STRUCTURAL_KEYS = new Set(['label', 'value', 'children']);
17671
17683
 
17684
+ /**
17685
+ * TableChart — rows of values as a table: a header row of column names, then one row per record,
17686
+ * numeric columns right-aligned. Drawn with the renderer's primitives like every chart, so it works
17687
+ * under SVG and canvas and needs no DOM table. Values are shown exactly (not an axis's "1.20k"):
17688
+ * a table is where a reader goes for the actual number.
17689
+ */
17690
+ class TableChart extends Chart {
17691
+ static chartType = 'table';
17692
+
17693
+ /** Layout constants for the rows. */
17694
+ static ROW_H = 26;
17695
+ static PAD_X = 8;
17696
+ static HEADER_FILL = '#eef1f6';
17697
+ static STRIPE_FILL = '#f8f9fb';
17698
+ static RULE = { color: '#d9dde4', width: 1 };
17699
+
17700
+ /**
17701
+ * The columns to show: `options.columns` (names, or `{ key, label?, align? }`), else every key of
17702
+ * the first row. A column is right-aligned when every value it holds is a number (or null).
17703
+ */
17704
+ static columns(data, given) {
17705
+ const specs = (given ?? Object.keys(data[0] ?? {})).map(c => (typeof c === 'string' ? { key: c } : { ...c }));
17706
+ return specs.map(c => ({
17707
+ key: c.key,
17708
+ label: c.label ?? c.key,
17709
+ align: c.align ?? (data.length > 0 && data.every(r => r[c.key] == null || typeof r[c.key] === 'number') ? 'end' : 'start'),
17710
+ }));
17711
+ }
17712
+
17713
+ /** The table has no axes, so none of a chart's axis margins: an edge all round, and room for a title. */
17714
+ static margins(title) {
17715
+ return { left: 8, right: 8, top: title ? 50 : 8, bottom: 8 };
17716
+ }
17717
+
17718
+ /**
17719
+ * The height a table of `rowCount` rows needs — header, rows (at most `maxRows`), the "more rows"
17720
+ * line, a title and the edges — so a page can size its container to fit before drawing.
17721
+ */
17722
+ static heightFor(rowCount, { title, maxRows = Infinity } = {}) {
17723
+ const shown = Math.min(rowCount, maxRows);
17724
+ const more = rowCount > shown ? 1 : 0;
17725
+ const { top, bottom } = TableChart.margins(title);
17726
+ return top + (1 + shown + more) * TableChart.ROW_H + bottom;
17727
+ }
17728
+
17729
+ /** A cell's text: a number exactly (to at most 4 decimals), null/undefined as `nullText`. */
17730
+ static cellText(value, nullText = '—') {
17731
+ if (value == null) return nullText;
17732
+ if (typeof value === 'number') return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(4)));
17733
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
17734
+ return String(value);
17735
+ }
17736
+
17737
+ _render() {
17738
+ const data = this.data ?? [];
17739
+ const box = ChartBox.fromRenderer(this.renderer, TableChart.margins(this.options.title));
17740
+ const { x = box.x, y = box.y, width = box.width, title, maxRows = Infinity, nullText = '—' } = this.options;
17741
+ const { ROW_H, PAD_X } = TableChart;
17742
+ const columns = TableChart.columns(data, this.options.columns);
17743
+ const colW = columns.length > 0 ? width / columns.length : width;
17744
+
17745
+ new ChartLabels({ title }).draw(this.renderer, { x, y, width, height: box.height });
17746
+
17747
+ const shown = data.slice(0, maxRows);
17748
+ let top = y;
17749
+ this.renderer.rect(x, top, width, ROW_H, TableChart.HEADER_FILL, null);
17750
+ columns.forEach((c, i) => this._cell(c.label, c, x + i * colW, top, colW, { fontWeight: 'bold', fill: '#333' }));
17751
+ top += ROW_H;
17752
+ this._rule(x, top, width);
17753
+
17754
+ shown.forEach((row, r) => {
17755
+ if (r % 2 === 1) this.renderer.rect(x, top, width, ROW_H, TableChart.STRIPE_FILL, null);
17756
+ columns.forEach((c, i) => this._cell(TableChart.cellText(row[c.key], nullText), c, x + i * colW, top, colW, { fill: '#222' }));
17757
+ top += ROW_H;
17758
+ this._rule(x, top, width);
17759
+ });
17760
+
17761
+ if (data.length > shown.length) {
17762
+ this.renderer.text(`${data.length - shown.length} more row(s) not shown`, x + PAD_X, top + ROW_H / 2, {
17763
+ textAnchor: 'start', verticalAlign: 'middle', fontSize: '11px', fill: '#888',
17764
+ });
17765
+ }
17766
+ }
17767
+
17768
+ _cell(text, column, left, top, colW, attrs) {
17769
+ const end = column.align === 'end';
17770
+ return this.renderer.text(text, end ? left + colW - TableChart.PAD_X : left + TableChart.PAD_X, top + TableChart.ROW_H / 2, {
17771
+ textAnchor: end ? 'end' : 'start', verticalAlign: 'middle', fontSize: '12px', ...attrs,
17772
+ });
17773
+ }
17774
+
17775
+ _rule(x, y, width) {
17776
+ this.renderer.path(`M${x},${y} L${x + width},${y}`, 'none', TableChart.RULE);
17777
+ }
17778
+ }
17779
+
17780
+ /**
17781
+ * ChartChooser — which catalog chart types fit a set of result rows, best first, each with the rows
17782
+ * already shaped as that chart's `dataShape`. A table always fits, so it is always offered, last.
17783
+ *
17784
+ * The caller may describe the columns (hints). `kind` is `'categorical'`, `'numeric'` or `'time'`; a
17785
+ * column with no hint is numeric when every value it holds is a number, else categorical. `measure`
17786
+ * is renderengine's measure kind (`'additive'`, `'semi-additive'`, `'non-additive'`), as a data model
17787
+ * gives it. The hints change the choice: a time column is drawn along a line, and only an additive
17788
+ * measure is offered as shares of a whole (a pie), since a part-of-a-whole slice of an average or a
17789
+ * balance means nothing.
17790
+ *
17791
+ * Every suggestion is checked against CHART_CATALOG: a chart type is offered only when the catalog
17792
+ * has it and every axis it requires is one the result's shape provides — so the catalog stays the
17793
+ * single source of truth for what each chart needs.
17794
+ *
17795
+ * const [best, ...others] = new ChartChooser().choose(rows, [{ name: 'Day', kind: 'time' }]);
17796
+ * engine.renderChartType(best.key, best.data, { title: best.label });
17797
+ */
17798
+ class ChartChooser {
17799
+ /** @param {ChartRegistry} [registry] — the built-in chart types, or another registry to choose from */
17800
+ constructor(registry = chartRegistry) {
17801
+ this.registry = registry;
17802
+ }
17803
+
17804
+ /**
17805
+ * @param {Array<object>} rows
17806
+ * @param {Array<{name:string, kind?:string, measure?:string}>} [columns] — hints; every key of the
17807
+ * first row when absent, in that order
17808
+ * @param {{complete?:boolean}} [options] — `complete: false` when the rows are only part of the
17809
+ * answer (a top N, a first page): then nothing is offered as shares of a whole, since the
17810
+ * slices would claim to be all of it
17811
+ * @returns {Array<{key:string, label:string, data:*, reason:string}>} best first; the table last
17812
+ */
17813
+ choose(rows, columns = null, { complete = true } = {}) {
17814
+ const described = ChartChooser.describe(rows, columns);
17815
+ const shape = RESULT_SHAPES.map(S => S.of(described, rows)).find(s => s !== null) ?? null;
17816
+ if (shape !== null) shape.complete = complete;
17817
+ const charts = shape === null ? [] : shape.candidates()
17818
+ .filter(({ key }) => this.fits(key, shape))
17819
+ .map(({ key, reason, data }) => ({ key, label: this.registry.get(key).label, data, reason }));
17820
+ return [...charts, this.table(rows, described, charts.length === 0)];
17821
+ }
17822
+
17823
+ /** A catalog entry fits a shape when every axis it requires is one the shape provides. */
17824
+ fits(key, shape) {
17825
+ const entry = this.registry.get(key);
17826
+ if (!entry) return false;
17827
+ if (shape.needsSeries && !entry.seriesCapable && !entry.axes.some(a => a.role === 'series')) return false;
17828
+ return entry.axes.filter(a => a.required).every(a => shape.provides[a.role] === a.kind);
17829
+ }
17830
+
17831
+ table(rows, described, only) {
17832
+ return {
17833
+ key: 'table', label: this.registry.get('table')?.label ?? 'Table',
17834
+ data: rows, columns: described.map(c => c.name),
17835
+ reason: only ? 'no chart fits these columns' : 'every value, exactly',
17836
+ };
17837
+ }
17838
+
17839
+ /** The columns with their kinds settled: the hint's, else derived from the rows' values. */
17840
+ static describe(rows, columns) {
17841
+ const given = columns ?? Object.keys(rows[0] ?? {}).map(name => ({ name }));
17842
+ return given.map(c => ({
17843
+ name: c.name,
17844
+ kind: c.kind ?? (rows.length > 0 && rows.every(r => r[c.name] == null || typeof r[c.name] === 'number') ? 'numeric' : 'categorical'),
17845
+ measure: c.measure ?? null,
17846
+ }));
17847
+ }
17848
+ }
17849
+
17850
+ /** The label a category value is drawn with. */
17851
+ function label(value) {
17852
+ return value == null ? '—' : value instanceof Date ? value.toISOString().slice(0, 10) : String(value);
17853
+ }
17854
+
17855
+ /** Rows in time order by `column` (numbers, dates and ISO strings all sort correctly this way). */
17856
+ function inOrder(rows, column) {
17857
+ return [...rows].sort((a, b) => (a[column] < b[column] ? -1 : a[column] > b[column] ? 1 : 0));
17858
+ }
17859
+
17860
+ /**
17861
+ * ResultShape — what a result's columns look like: how many category, time and numeric columns.
17862
+ * Each subclass recognises one shape (`static of`), says which catalog axes it provides, and lists
17863
+ * the chart types that suit it, best first, with the rows shaped for each.
17864
+ */
17865
+ class ResultShape {
17866
+ constructor() {
17867
+ /** Whether the rows are all of the answer (ChartChooser.choose's `complete`). */
17868
+ this.complete = true;
17869
+ }
17870
+
17871
+ /** The axes this shape can fill, role → AXIS_KIND. */
17872
+ get provides() { return {}; }
17873
+ /** Whether a chart must draw several series (one per numeric column). */
17874
+ get needsSeries() { return false; }
17875
+ /** @returns {Array<{key, reason, data}>} */
17876
+ candidates() { return []; }
17877
+
17878
+ static split(columns) {
17879
+ return {
17880
+ categories: columns.filter(c => c.kind !== 'numeric'),
17881
+ numbers: columns.filter(c => c.kind === 'numeric'),
17882
+ };
17883
+ }
17884
+
17885
+ /**
17886
+ * Whether each row has its own value of the category columns. Rows that repeat a category
17887
+ * (rows of orders, not totals per region) would be drawn as one bar per row with the same
17888
+ * label over and over — or, for two categories, one repeated pair would replace another's value
17889
+ * unseen. A chart of a value per category needs one row per category: a GROUP BY first.
17890
+ */
17891
+ static oneRowEach(rows, categories) {
17892
+ const keys = new Set(rows.map(r => JSON.stringify(categories.map(c => r[c.name] ?? null))));
17893
+ return keys.size === rows.length;
17894
+ }
17895
+ }
17896
+
17897
+ /** One number and nothing to group it by: a single figure. */
17898
+ class SingleFigure extends ResultShape {
17899
+ static of(columns, rows) {
17900
+ const { categories, numbers } = ResultShape.split(columns);
17901
+ return categories.length === 0 && numbers.length === 1 && rows.length === 1 ? new SingleFigure(numbers[0], rows) : null;
17902
+ }
17903
+ constructor(number, rows) { super(); this.number = number; this.rows = rows; }
17904
+ get provides() { return { value: AXIS_KIND.NUMERIC }; }
17905
+ candidates() {
17906
+ return [{ key: 'kpi-tile', reason: 'a single figure', data: { value: this.rows[0][this.number.name] } }];
17907
+ }
17908
+ }
17909
+
17910
+ /** One category (or time) column and one number: a value per category. */
17911
+ class CategoryValue extends ResultShape {
17912
+ static of(columns, rows) {
17913
+ const { categories, numbers } = ResultShape.split(columns);
17914
+ return categories.length === 1 && numbers.length === 1 && ResultShape.oneRowEach(rows, categories)
17915
+ ? new CategoryValue(categories[0], numbers[0], rows) : null;
17916
+ }
17917
+ constructor(category, number, rows) { super(); this.category = category; this.number = number; this.rows = rows; }
17918
+ get provides() { return { category: AXIS_KIND.CATEGORICAL, value: AXIS_KIND.NUMERIC }; }
17919
+
17920
+ candidates() {
17921
+ const { category, number } = this;
17922
+ const time = category.kind === 'time';
17923
+ const rows = time ? inOrder(this.rows, category.name) : this.rows;
17924
+ const data = rows.filter(r => r[number.name] != null).map(r => ({ label: label(r[category.name]), value: r[number.name] }));
17925
+ if (time) {
17926
+ return [
17927
+ { key: 'line', reason: `${number.name} over ${category.name}`, data },
17928
+ { key: 'area', reason: `${number.name} over ${category.name}, filled`, data },
17929
+ { key: 'bar', reason: `${number.name} for each ${category.name}`, data },
17930
+ ];
17931
+ }
17932
+ const options = [{ key: 'bar', reason: `${number.name} for each ${category.name}`, data }];
17933
+ if (this.isShareOfWhole(data)) {
17934
+ options.push({ key: 'pie', reason: `each ${category.name}'s share of the total ${number.name}`, data });
17935
+ options.push({ key: 'donut', reason: `each ${category.name}'s share of the total ${number.name}`, data });
17936
+ }
17937
+ return options;
17938
+ }
17939
+
17940
+ /**
17941
+ * Shares of a whole make sense only for an additive measure, over all of the rows (not a top N),
17942
+ * with no negatives, in few slices.
17943
+ */
17944
+ isShareOfWhole(data) {
17945
+ return this.complete && this.number.measure === 'additive' && data.length >= 2 && data.length <= CategoryValue.MAX_SLICES
17946
+ && data.every(d => d.value >= 0);
17947
+ }
17948
+ }
17949
+ CategoryValue.MAX_SLICES = 8;
17950
+
17951
+ /** One category (or time) column and several numbers: a series per number. */
17952
+ class CategorySeries extends ResultShape {
17953
+ static of(columns, rows) {
17954
+ const { categories, numbers } = ResultShape.split(columns);
17955
+ return categories.length === 1 && numbers.length >= 2 && ResultShape.oneRowEach(rows, categories)
17956
+ ? new CategorySeries(categories[0], numbers, rows) : null;
17957
+ }
17958
+ constructor(category, numbers, rows) { super(); this.category = category; this.numbers = numbers; this.rows = rows; }
17959
+ get provides() { return { category: AXIS_KIND.CATEGORICAL, value: AXIS_KIND.NUMERIC, series: AXIS_KIND.CATEGORICAL }; }
17960
+ get needsSeries() { return true; }
17961
+
17962
+ candidates() {
17963
+ const { category } = this;
17964
+ const time = category.kind === 'time';
17965
+ const rows = time ? inOrder(this.rows, category.name) : this.rows;
17966
+ // lineChart and groupedBarChart have no gap for a missing value: a null would have to be drawn
17967
+ // as 0, a figure the data does not hold. So a result with one is not offered as series.
17968
+ if (rows.some(r => this.numbers.some(n => r[n.name] == null))) return [];
17969
+ const data = this.numbers.map(n => ({
17970
+ name: n.name,
17971
+ values: rows.map(r => ({ label: label(r[category.name]), value: r[n.name] })),
17972
+ }));
17973
+ const names = this.numbers.map(n => n.name).join(', ');
17974
+ return time
17975
+ ? [{ key: 'line', reason: `${names} over ${category.name}`, data }, { key: 'groupedBar', reason: `${names} for each ${category.name}`, data }]
17976
+ : [{ key: 'groupedBar', reason: `${names} for each ${category.name}`, data }, { key: 'line', reason: `${names} across ${category.name}`, data }];
17977
+ }
17978
+ }
17979
+
17980
+ /** Two category (or time) columns and one number: a value per pair. */
17981
+ class TwoCategories extends ResultShape {
17982
+ static of(columns, rows) {
17983
+ const { categories, numbers } = ResultShape.split(columns);
17984
+ return categories.length === 2 && numbers.length === 1 && ResultShape.oneRowEach(rows, categories)
17985
+ ? new TwoCategories(categories, numbers[0], rows) : null;
17986
+ }
17987
+ constructor(categories, number, rows) {
17988
+ super();
17989
+ // A time column goes along the x axis, whichever order the columns came in.
17990
+ this.across = categories.find(c => c.kind === 'time') ?? categories[0];
17991
+ this.down = categories.find(c => c !== this.across);
17992
+ this.number = number;
17993
+ this.rows = rows;
17994
+ }
17995
+ get provides() {
17996
+ return { x: AXIS_KIND.CATEGORICAL, y: AXIS_KIND.CATEGORICAL, category: AXIS_KIND.CATEGORICAL, value: AXIS_KIND.NUMERIC, series: AXIS_KIND.CATEGORICAL };
17997
+ }
17998
+
17999
+ candidates() {
18000
+ const { across, down, number } = this;
18001
+ const rows = across.kind === 'time' ? inOrder(this.rows, across.name) : this.rows;
18002
+ const heat = rows.filter(r => r[number.name] != null)
18003
+ .map(r => ({ x: label(r[across.name]), y: label(r[down.name]), value: r[number.name] }));
18004
+ const heatmap = { key: 'heatmap', reason: `${number.name} for each ${across.name} and ${down.name}`, data: heat };
18005
+ // A series needs a value for every label; where a pair is missing (or null) only the heatmap,
18006
+ // which draws just the cells present, shows the data without inventing a 0.
18007
+ const labels = [...new Set(rows.map(r => label(r[across.name])))];
18008
+ const value = new Map(rows.map(r => [`${label(r[across.name])}\u0000${label(r[down.name])}`, r[number.name]]));
18009
+ const names = [...new Set(rows.map(r => label(r[down.name])))];
18010
+ if (names.some(name => labels.some(l => value.get(`${l}\u0000${name}`) == null))) return [heatmap];
18011
+ const series = names.map(name => ({ name, values: labels.map(l => ({ label: l, value: value.get(`${l}\u0000${name}`) })) }));
18012
+ const grouped = { key: 'groupedBar', reason: `${number.name} for each ${across.name}, by ${down.name}`, data: series };
18013
+ return across.kind === 'time'
18014
+ ? [{ key: 'line', reason: `${number.name} over ${across.name}, a line per ${down.name}`, data: series }, heatmap, grouped]
18015
+ : [grouped, heatmap];
18016
+ }
18017
+ }
18018
+
18019
+ /** Shapes in the order they are tried; the first that recognises the columns wins. */
18020
+ const RESULT_SHAPES = [SingleFigure, CategoryValue, CategorySeries, TwoCategories];
18021
+
18022
+ /**
18023
+ * TableView — the state of an interactive table over result rows, kept apart from drawing so all of
18024
+ * it can be tested without a DOM: the sort, the filters, the hidden columns and the page, and the
18025
+ * menus a table offers on a cell, a row, a column and the table itself (as PopupMenu item specs).
18026
+ *
18027
+ * Filtering is by choosing values from the table, not typing: a cell's menu keeps or excludes rows
18028
+ * with its value (and, for a number, rows above or below it); a column's menu filters to one of its
18029
+ * values. The table's menu offers "Show as", the chart types ChartChooser says fit what is showing.
18030
+ *
18031
+ * Every change calls `onChange(view)`; the host redraws. A host adds its own items with
18032
+ * `menus: { cell(ctx), row(ctx), column(ctx), table(ctx) }`, each returning PopupMenu items.
18033
+ */
18034
+ const FILTER_OPS = {
18035
+ '=': (v, x) => v === x,
18036
+ '!=': (v, x) => v !== x,
18037
+ '>': (v, x) => v != null && v > x,
18038
+ '<': (v, x) => v != null && v < x,
18039
+ 'is null': (v) => v == null,
18040
+ 'is not null': (v) => v != null,
18041
+ };
18042
+
18043
+ /** Order of two values for a sort: numbers numerically, everything else as text; nulls last. */
18044
+ function compareValues(a, b) {
18045
+ if (a == null) return b == null ? 0 : 1;
18046
+ if (b == null) return -1;
18047
+ if (typeof a === 'number' && typeof b === 'number') return a - b;
18048
+ const x = String(a), y = String(b);
18049
+ return x < y ? -1 : x > y ? 1 : 0;
18050
+ }
18051
+
18052
+ /** A value as copied text: null as empty, an object as JSON. */
18053
+ function plain(value) {
18054
+ if (value == null) return '';
18055
+ if (value instanceof Date) return value.toISOString();
18056
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
18057
+ }
18058
+
18059
+ class TableView {
18060
+ /** The most distinct values a column's "Filter to" menu lists. */
18061
+ static MAX_FILTER_VALUES = 20;
18062
+
18063
+ /**
18064
+ * @param {Array<object>} rows
18065
+ * @param {object} [options]
18066
+ * @param {Array<{name, kind?, measure?}>} [options.columns] hints, as ChartChooser takes them
18067
+ * @param {boolean} [options.complete] false when the rows are only part of the answer (a top N)
18068
+ * @param {number} [options.pageSize] rows per page (50; Infinity for all)
18069
+ * @param {function} [options.onChange] called with the view after every change
18070
+ * @param {object} [options.menus] the host's own items: { cell, row, column, table } → items
18071
+ * @param {function} [options.copy] writes text to the clipboard (navigator.clipboard by default)
18072
+ * @param {ChartChooser} [options.chooser]
18073
+ */
18074
+ constructor(rows, { columns = null, complete = true, pageSize = 50, onChange = null, menus = {}, copy = null, chooser = null } = {}) {
18075
+ this.rows = rows;
18076
+ this.columns = ChartChooser.describe(rows, columns);
18077
+ this.complete = complete;
18078
+ this.pageSize = pageSize;
18079
+ this.onChange = onChange;
18080
+ this.menus = menus;
18081
+ this.copy = copy ?? TableView.clipboard;
18082
+ this.chooser = chooser ?? new ChartChooser();
18083
+ this.sort = null; // { column, direction: 'asc' | 'desc' }
18084
+ this.filters = []; // { column, op, value }
18085
+ this.hidden = new Set();
18086
+ this.page = 0;
18087
+ }
18088
+
18089
+ static clipboard(text) {
18090
+ return globalThis.navigator?.clipboard?.writeText(text);
18091
+ }
18092
+
18093
+ // ── What is showing ───────────────────────────────────────────────────────
18094
+
18095
+ visibleColumns() { return this.columns.filter(c => !this.hidden.has(c.name)); }
18096
+
18097
+ filtered() {
18098
+ return this.filters.length === 0 ? this.rows
18099
+ : this.rows.filter(r => this.filters.every(f => FILTER_OPS[f.op](r[f.column], f.value)));
18100
+ }
18101
+
18102
+ /** The filtered rows in sort order (a copy; equal values keep their order). */
18103
+ ordered() {
18104
+ const rows = this.filtered();
18105
+ if (this.sort === null) return rows;
18106
+ const { column, direction } = this.sort;
18107
+ const sign = direction === 'desc' ? -1 : 1;
18108
+ // Nulls stay last whichever way: a reader looks for values, not for blanks.
18109
+ return [...rows].sort((a, b) => (a[column] == null || b[column] == null ? compareValues(a[column], b[column]) : sign * compareValues(a[column], b[column])));
18110
+ }
18111
+
18112
+ pageCount() {
18113
+ return Number.isFinite(this.pageSize) ? Math.max(1, Math.ceil(this.filtered().length / this.pageSize)) : 1;
18114
+ }
18115
+
18116
+ /** The rows on the current page, each with its position in the ordered rows (`index`, from 0). */
18117
+ pageRows() {
18118
+ const rows = this.ordered();
18119
+ const start = Number.isFinite(this.pageSize) ? this.page * this.pageSize : 0;
18120
+ const end = Number.isFinite(this.pageSize) ? start + this.pageSize : rows.length;
18121
+ return rows.slice(start, end).map((row, i) => ({ row, index: start + i }));
18122
+ }
18123
+
18124
+ /** "Region = West · Revenue > 100", or '' with no filters. */
18125
+ describeFilters() {
18126
+ return this.filters.map(f => (f.op.startsWith('is') ? `${f.column} ${f.op}` : `${f.column} ${f.op} ${plain(f.value)}`)).join(' · ');
18127
+ }
18128
+
18129
+ // ── Changes ───────────────────────────────────────────────────────────────
18130
+
18131
+ changed() {
18132
+ this.page = Math.min(this.page, this.pageCount() - 1);
18133
+ this.onChange?.(this);
18134
+ }
18135
+
18136
+ /** A header click: unsorted → ascending → descending → unsorted. */
18137
+ toggleSort(column) {
18138
+ const current = this.sort?.column === column ? this.sort.direction : null;
18139
+ this.sortBy(column, current === null ? 'asc' : current === 'asc' ? 'desc' : null);
18140
+ }
18141
+
18142
+ sortBy(column, direction) {
18143
+ this.sort = direction === null ? null : { column, direction };
18144
+ this.page = 0;
18145
+ this.changed();
18146
+ }
18147
+
18148
+ addFilter(column, op, value = null) {
18149
+ if (!Object.hasOwn(FILTER_OPS, op)) throw new Error(`Unknown filter "${op}"`);
18150
+ this.filters = [...this.filters.filter(f => !(f.column === column && f.op === op && f.value === value)), { column, op, value }];
18151
+ this.page = 0;
18152
+ this.changed();
18153
+ }
18154
+
18155
+ removeFilters(column) {
18156
+ this.filters = this.filters.filter(f => f.column !== column);
18157
+ this.changed();
18158
+ }
18159
+
18160
+ clearFilters() {
18161
+ this.filters = [];
18162
+ this.changed();
18163
+ }
18164
+
18165
+ /** Hides a column; the last one showing cannot be hidden. */
18166
+ hide(column) {
18167
+ if (this.visibleColumns().length <= 1) return;
18168
+ this.hidden.add(column);
18169
+ this.changed();
18170
+ }
18171
+
18172
+ showAll() {
18173
+ this.hidden.clear();
18174
+ this.changed();
18175
+ }
18176
+
18177
+ goToPage(page) {
18178
+ this.page = Math.max(0, Math.min(page, this.pageCount() - 1));
18179
+ this.changed();
18180
+ }
18181
+
18182
+ // ── Text out ──────────────────────────────────────────────────────────────
18183
+
18184
+ /** Rows as tab-separated text, header first, the visible columns only. */
18185
+ asTsv(rows = this.ordered()) {
18186
+ const columns = this.visibleColumns().map(c => c.name);
18187
+ const clean = (v) => plain(v).replace(/[\t\r\n]+/g, ' ');
18188
+ return [columns.map(clean).join('\t'), ...rows.map(r => columns.map(c => clean(r[c])).join('\t'))].join('\n');
18189
+ }
18190
+
18191
+ // ── Menus (PopupMenu items) ──────────────────────────────────────────────
18192
+
18193
+ cellMenu(row, column) {
18194
+ const value = row[column];
18195
+ const kind = this.columns.find(c => c.name === column)?.kind;
18196
+ const shown = value == null ? 'empty' : plain(value);
18197
+ const items = value == null
18198
+ ? [{ label: `Only rows where ${column} is empty`, action: () => this.addFilter(column, 'is null') },
18199
+ { label: `Exclude rows where ${column} is empty`, action: () => this.addFilter(column, 'is not null') }]
18200
+ : [{ label: `Only rows where ${column} = ${shown}`, action: () => this.addFilter(column, '=', value) },
18201
+ { label: `Exclude rows where ${column} = ${shown}`, action: () => this.addFilter(column, '!=', value) },
18202
+ ...(kind === 'numeric' ? [
18203
+ { label: `Only rows where ${column} > ${shown}`, action: () => this.addFilter(column, '>', value) },
18204
+ { label: `Only rows where ${column} < ${shown}`, action: () => this.addFilter(column, '<', value) },
18205
+ ] : [])];
18206
+ return [
18207
+ ...items,
18208
+ { separator: true },
18209
+ { label: 'Copy value', action: () => this.copy(plain(value)) },
18210
+ ...this.extra('cell', { row, column, value }),
18211
+ ];
18212
+ }
18213
+
18214
+ rowMenu(row) {
18215
+ return [
18216
+ { label: 'Copy row', action: () => this.copy(this.asTsv([row])) },
18217
+ { label: 'Copy row as JSON', action: () => this.copy(JSON.stringify(row)) },
18218
+ ...this.extra('row', { row }),
18219
+ ];
18220
+ }
18221
+
18222
+ columnMenu(column) {
18223
+ const sorted = this.sort?.column === column ? this.sort.direction : null;
18224
+ const values = [...new Set(this.filtered().map(r => r[column]))].sort(compareValues);
18225
+ const listed = values.slice(0, TableView.MAX_FILTER_VALUES);
18226
+ return [
18227
+ { label: 'Sort ascending', checked: sorted === 'asc', action: () => this.sortBy(column, 'asc') },
18228
+ { label: 'Sort descending', checked: sorted === 'desc', action: () => this.sortBy(column, 'desc') },
18229
+ ...(sorted ? [{ label: 'Clear sort', action: () => this.sortBy(column, null) }] : []),
18230
+ { separator: true },
18231
+ {
18232
+ label: 'Filter to',
18233
+ items: [
18234
+ ...listed.map(v => (v == null
18235
+ ? { label: '(empty)', action: () => this.addFilter(column, 'is null') }
18236
+ : { label: plain(v), action: () => this.addFilter(column, '=', v) })),
18237
+ ...(values.length > listed.length ? [{ label: `${values.length - listed.length} more — filter from a cell`, disabled: true }] : []),
18238
+ ],
18239
+ },
18240
+ ...(this.filters.some(f => f.column === column) ? [{ label: `Clear filters on ${column}`, action: () => this.removeFilters(column) }] : []),
18241
+ { separator: true },
18242
+ { label: 'Hide column', disabled: this.visibleColumns().length <= 1, action: () => this.hide(column) },
18243
+ { label: 'Copy column', action: () => this.copy([column, ...this.ordered().map(r => plain(r[column]))].join('\n')) },
18244
+ ...this.extra('column', { column }),
18245
+ ];
18246
+ }
18247
+
18248
+ /** The table's menu; `onShowAs(choice)` draws a chosen chart (the host's — RenderEngine.resultView). */
18249
+ tableMenu(onShowAs = null) {
18250
+ const choices = onShowAs ? this.chartChoices() : [];
18251
+ return [
18252
+ ...(onShowAs ? [{
18253
+ label: 'Show as',
18254
+ items: choices.length > 0
18255
+ ? choices.map(c => ({ label: `${c.label} — ${c.reason}`, action: () => onShowAs(c) }))
18256
+ : [{ label: 'No chart fits these columns', disabled: true }],
18257
+ }, { separator: true }] : []),
18258
+ { label: 'Clear all filters', disabled: this.filters.length === 0, action: () => this.clearFilters() },
18259
+ { label: 'Show hidden columns', disabled: this.hidden.size === 0, action: () => this.showAll() },
18260
+ { label: 'Copy table', action: () => this.copy(this.asTsv()) },
18261
+ ...this.extra('table', {}),
18262
+ ];
18263
+ }
18264
+
18265
+ /**
18266
+ * The chart types that fit what the table is showing — its filtered, sorted rows and visible
18267
+ * columns — as ChartChooser gives them, without the table. Filtered rows are not the whole
18268
+ * answer, so they are never offered as shares of a whole.
18269
+ */
18270
+ chartChoices() {
18271
+ const columns = this.visibleColumns();
18272
+ const names = columns.map(c => c.name);
18273
+ const rows = this.ordered().map(r => Object.fromEntries(names.map(n => [n, r[n]])));
18274
+ return this.chooser.choose(rows, columns, { complete: this.complete && this.filters.length === 0 })
18275
+ .filter(c => c.key !== 'table');
18276
+ }
18277
+
18278
+ extra(kind, context) {
18279
+ const items = this.menus?.[kind]?.({ view: this, ...context }) ?? [];
18280
+ return items.length > 0 ? [{ separator: true }, ...items] : [];
18281
+ }
18282
+ }
18283
+
18284
+ /**
18285
+ * TableViewChart — the interactive table: a TableChart drawn from a TableView's state, whose parts
18286
+ * answer clicks. A header sorts (and its ▾ opens the column's menu); a cell opens the cell's menu; a
18287
+ * row number opens the row's menu; the corner ⋮ opens the table's menu (with "Show as" when the host
18288
+ * can draw a chart); the footer's ‹ › page. Each change goes through the view, whose `onChange`
18289
+ * redraws.
18290
+ *
18291
+ * Interaction needs a renderer whose shapes are DOM elements (SVG: `supportsSceneGraph`); anywhere
18292
+ * else it draws the same table without the clicks.
18293
+ */
18294
+ class TableViewChart extends TableChart {
18295
+ static GUTTER_W = 44;
18296
+ static MENU_GLYPH = '▾';
18297
+ static TABLE_GLYPH = '⋮';
18298
+
18299
+ /**
18300
+ * @param renderer
18301
+ * @param {TableView} view
18302
+ * @param {object} [options] title, nullText; onShowAs(choice) — draws a chart for the table menu's
18303
+ * "Show as"; showMenu(x, y, items) — opens a menu (PopupMenu.show by default)
18304
+ */
18305
+ constructor(renderer, view, options = {}) {
18306
+ super(renderer, view.rows, options);
18307
+ this.view = view;
18308
+ this.showMenu = options.showMenu ?? ((x, y, items) => PopupMenu.show(x, y, items));
18309
+ }
18310
+
18311
+ /** The height this draws: title, header, the page's rows and the footer. */
18312
+ static heightFor(view, { title } = {}) {
18313
+ const { top, bottom } = TableChart.margins(title);
18314
+ return top + (2 + view.pageRows().length) * TableChart.ROW_H + bottom;
18315
+ }
18316
+
18317
+ _render() {
18318
+ const { view } = this;
18319
+ const { title, nullText = '—' } = this.options;
18320
+ const { ROW_H, PAD_X } = TableChart;
18321
+ const box = ChartBox.fromRenderer(this.renderer, TableChart.margins(title));
18322
+ const interactive = this.renderer.supportsSceneGraph === true;
18323
+ const columns = view.visibleColumns().map(c => ({ key: c.name, label: c.name, align: c.kind === 'numeric' ? 'end' : 'start' }));
18324
+ const gutter = TableViewChart.GUTTER_W;
18325
+ const colW = columns.length > 0 ? (box.width - gutter) / columns.length : box.width - gutter;
18326
+ const x0 = box.x + gutter;
18327
+
18328
+ new ChartLabels({ title }).draw(this.renderer, { x: box.x, y: box.y, width: box.width, height: box.height });
18329
+
18330
+ // Header: the corner (table menu), then a header per column (sort; ▾ column menu).
18331
+ let top = box.y;
18332
+ this.renderer.rect(box.x, top, box.width, ROW_H, TableChart.HEADER_FILL, null);
18333
+ const corner = this.renderer.rect(box.x, top, gutter, ROW_H, TableChart.HEADER_FILL, null);
18334
+ const cornerGlyph = this._text(TableViewChart.TABLE_GLYPH, box.x + gutter / 2, top, { textAnchor: 'middle', fontWeight: 'bold', fill: '#555' });
18335
+ this._on(interactive, [corner, cornerGlyph], (e) => this.showMenu(e.clientX, e.clientY, view.tableMenu(this.options.onShowAs ?? null)), 'Table menu');
18336
+
18337
+ columns.forEach((c, i) => {
18338
+ const left = x0 + i * colW;
18339
+ const sorted = view.sort?.column === c.key ? (view.sort.direction === 'asc' ? ' ▲' : ' ▼') : '';
18340
+ // In words: an arrow-like mark here read as a second sort arrow.
18341
+ const filtered = view.filters.some(f => f.column === c.key) ? ' (filtered)' : '';
18342
+ const head = this.renderer.rect(left, top, colW, ROW_H, TableChart.HEADER_FILL, null);
18343
+ // The label leaves room at the right for the ▾.
18344
+ const label = this._cell(`${c.label}${sorted}${filtered}`, c, left, top, colW - 16, { fontWeight: 'bold', fill: '#333' });
18345
+ this._on(interactive, [head, label], () => view.toggleSort(c.key), 'Sort');
18346
+ const glyph = this._text(TableViewChart.MENU_GLYPH, left + colW - 8, top, { textAnchor: 'middle', fill: '#777' });
18347
+ this._on(interactive, [glyph], (e) => this.showMenu(e.clientX, e.clientY, view.columnMenu(c.key)), `${c.label} menu`);
18348
+ });
18349
+ top += ROW_H;
18350
+ this._rule(box.x, top, box.width);
18351
+
18352
+ // Rows: a number in the gutter (row menu), a cell per column (cell menu).
18353
+ view.pageRows().forEach(({ row, index }, r) => {
18354
+ if (r % 2 === 1) this.renderer.rect(box.x, top, box.width, ROW_H, TableChart.STRIPE_FILL, null);
18355
+ const number = this._text(String(index + 1), box.x + gutter - PAD_X, top, { textAnchor: 'end', fill: '#999', fontSize: '11px' });
18356
+ this._on(interactive, [number], (e) => this.showMenu(e.clientX, e.clientY, view.rowMenu(row)), 'Row menu');
18357
+ columns.forEach((c, i) => {
18358
+ const left = x0 + i * colW;
18359
+ const hit = this.renderer.rect(left, top, colW, ROW_H, 'transparent', null);
18360
+ const text = this._cell(TableChart.cellText(row[c.key], nullText), c, left, top, colW, { fill: row[c.key] == null ? '#999' : '#222' });
18361
+ this._on(interactive, [hit, text], (e) => this.showMenu(e.clientX, e.clientY, view.cellMenu(row, c.key)), null);
18362
+ });
18363
+ top += ROW_H;
18364
+ this._rule(box.x, top, box.width);
18365
+ });
18366
+
18367
+ this._footer(box, top, interactive);
18368
+ }
18369
+
18370
+ /** "1–50 of 120 rows (filtered from 300: Region = West)", and ‹ › when there is more than a page. */
18371
+ _footer(box, top, interactive) {
18372
+ const { view } = this;
18373
+ const shown = view.pageRows();
18374
+ const total = view.filtered().length;
18375
+ const range = shown.length === 0 ? 'No rows' : `${shown[0].index + 1}–${shown.at(-1).index + 1} of ${total} row${total === 1 ? '' : 's'}`;
18376
+ const filters = view.filters.length > 0 ? ` (filtered from ${view.rows.length}: ${view.describeFilters()})` : '';
18377
+ this._text(`${range}${filters}`, box.x + TableChart.PAD_X, top, { textAnchor: 'start', fill: '#666', fontSize: '11px' });
18378
+ if (view.pageCount() > 1) {
18379
+ const right = box.x + box.width - TableChart.PAD_X;
18380
+ const previous = this._text('‹ previous', right - 70, top, { textAnchor: 'end', fill: view.page > 0 ? '#2b5fd9' : '#bbb', fontSize: '11px' });
18381
+ const next = this._text('next ›', right, top, { textAnchor: 'end', fill: view.page < view.pageCount() - 1 ? '#2b5fd9' : '#bbb', fontSize: '11px' });
18382
+ this._on(interactive, [previous], () => view.goToPage(view.page - 1), 'Previous page');
18383
+ this._on(interactive, [next], () => view.goToPage(view.page + 1), 'Next page');
18384
+ }
18385
+ }
18386
+
18387
+ _text(text, x, top, attrs) {
18388
+ return this.renderer.text(text, x, top + TableChart.ROW_H / 2, { verticalAlign: 'middle', fontSize: '12px', ...attrs });
18389
+ }
18390
+
18391
+ /** Wires a click to each element that can take one (SVG); a pointer cursor and a tooltip say so. */
18392
+ _on(interactive, elements, handler, title) {
18393
+ if (!interactive) return;
18394
+ for (const el of elements) {
18395
+ if (typeof el?.addEventListener !== 'function') continue;
18396
+ el.addEventListener('click', (event) => { event.stopPropagation?.(); handler(event); });
18397
+ if (el.style) el.style.cursor = 'pointer';
18398
+ if (title && typeof el.setAttribute === 'function' && el.ownerDocument) {
18399
+ const t = el.ownerDocument.createElementNS('http://www.w3.org/2000/svg', 'title');
18400
+ t.textContent = title;
18401
+ el.appendChild(t);
18402
+ }
18403
+ }
18404
+ }
18405
+ }
18406
+
17672
18407
  /**
17673
18408
  * RadarChart — one polygon per series across N shared axes, each axis scaled
17674
18409
  * independently by its own max value across all series.
@@ -53374,6 +54109,80 @@ ${theirs}` : theirs;
53374
54109
  this._renderChart(new FunnelChart(this.renderer, data, options));
53375
54110
  }
53376
54111
 
54112
+ /**
54113
+ * Renders rows as a table — a header of column names, a row per record, numeric columns
54114
+ * right-aligned, values shown exactly. Drawn with the renderer's primitives, so it works under
54115
+ * SVG and canvas. ChartChooser offers it for any result, last.
54116
+ * @param {Array<object>} data one object per row
54117
+ * @param {object} [options]
54118
+ * @param {Array<string|{key:string, label?:string, align?:'start'|'end'}>} [options.columns] every key of the first row when absent
54119
+ * @param {number} [options.maxRows] rows beyond it are counted, not drawn
54120
+ * @param {string} [options.nullText] what a null or missing value shows ('—')
54121
+ * @param {string} [options.title]
54122
+ */
54123
+ tableChart(data, options = {}) {
54124
+ if (!this.renderer) return;
54125
+ this._chart3D = false;
54126
+ this._chartState = { type: 'table', data, options };
54127
+ this._renderChart(new TableChart(this.renderer, data, options));
54128
+ }
54129
+
54130
+ /**
54131
+ * Shows result rows as an interactive table — sort, filter, hide columns, page, copy, through
54132
+ * menus on its cells, rows, columns and the table itself — whose table menu can show what it
54133
+ * holds as any chart type ChartChooser says fits ("Show as"); a chart drawn that way has a
54134
+ * "◂ Table" link back to the table as it was left. One output for a result, table or chart.
54135
+ *
54136
+ * The container's height follows what is drawn (the table's rows, or `chartHeight` for a chart),
54137
+ * so the host gives the container a width only. Interaction needs the SVG renderer; on canvas
54138
+ * the table is drawn without it.
54139
+ * @param {Array<object>} rows
54140
+ * @param {object} [options]
54141
+ * @param {Array<{name, kind?, measure?}>} [options.columns] hints (ChartChooser's)
54142
+ * @param {boolean} [options.complete] false when the rows are only part of the answer
54143
+ * @param {number} [options.pageSize] rows per page (50)
54144
+ * @param {object} [options.menus] the host's own items: { cell, row, column, table } → items
54145
+ * @param {string} [options.title]
54146
+ * @param {number} [options.chartHeight] a chart's height (360)
54147
+ * @param {boolean} [options.fitHeight] size the container to what is drawn (true)
54148
+ * @returns {TableView|null} the table's state, for the host to read or change
54149
+ */
54150
+ resultView(rows, options = {}) {
54151
+ if (!this.renderer) return null;
54152
+ const view = new TableView(rows, { ...options, onChange: () => this._drawResultTable(view, options) });
54153
+ this._drawResultTable(view, options);
54154
+ return view;
54155
+ }
54156
+
54157
+ _drawResultTable(view, options) {
54158
+ this._fitResultHeight(TableViewChart.heightFor(view, options), options);
54159
+ this._chart3D = false;
54160
+ this._chartState = { type: 'table', data: view.rows, options };
54161
+ this._renderChart(new TableViewChart(this.renderer, view, {
54162
+ ...options,
54163
+ onShowAs: (choice) => this._drawResultChart(view, choice, options),
54164
+ }));
54165
+ }
54166
+
54167
+ _drawResultChart(view, choice, options) {
54168
+ this._fitResultHeight(options.chartHeight ?? 360, options);
54169
+ this.renderChartType(choice.key, choice.data, { title: options.title ?? choice.reason });
54170
+ // The way back, drawn over the chart: the same table, as it was left.
54171
+ if (!this.renderer.supportsSceneGraph) return;
54172
+ const back = this.renderer.text('◂ Table', 8, 14, { fill: '#2b5fd9', fontSize: '12px', verticalAlign: 'middle' });
54173
+ back?.addEventListener?.('click', () => this._drawResultTable(view, options));
54174
+ if (back?.style) back.style.cursor = 'pointer';
54175
+ }
54176
+
54177
+ _fitResultHeight(height, options) {
54178
+ if (options.fitHeight === false || !this.container?.style) return;
54179
+ // min-height as well: in a flex layout (a notebook, a workbench pane) a height alone is
54180
+ // shrunk to fit, and the table drawn into the shrunk box lost its last rows.
54181
+ this.container.style.height = `${height}px`;
54182
+ this.container.style.minHeight = `${height}px`;
54183
+ this.fitToContainer();
54184
+ }
54185
+
53377
54186
  /**
53378
54187
  * Renders a waterfall chart — running-total bars, each floating from the
53379
54188
  * previous cumulative value to the new one (a "delta" bar), except
@@ -58192,6 +59001,7 @@ th { color: #555; font-weight: 500; }
58192
59001
  exports.CanvasTemplateMenu = CanvasTemplateMenu;
58193
59002
  exports.CanvasView = CanvasView;
58194
59003
  exports.CatalogDialog = CatalogDialog;
59004
+ exports.ChartChooser = ChartChooser;
58195
59005
  exports.ChartPart = ChartPart;
58196
59006
  exports.CheckboxTreeSelector = CheckboxTreeSelector;
58197
59007
  exports.CircleMarker = CircleMarker;
@@ -58406,6 +59216,9 @@ th { color: #555; font-weight: 500; }
58406
59216
  exports.TREE_LAYERS = TREE_LAYERS;
58407
59217
  exports.TREE_MODE_CATALOG = TREE_MODE_CATALOG;
58408
59218
  exports.TREE_SETTINGS_PROPERTIES = TREE_SETTINGS_PROPERTIES;
59219
+ exports.TableChart = TableChart;
59220
+ exports.TableView = TableView;
59221
+ exports.TableViewChart = TableViewChart;
58409
59222
  exports.TabsNode = TabsNode;
58410
59223
  exports.Template = Template;
58411
59224
  exports.TemplateCatalog = TemplateCatalog;