@gemologic/sheen-table 0.1.0-rc.2 → 0.2.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.
@@ -17,7 +17,7 @@ function s(s, c, l) {
17
17
  let t = n(c.filter, e.id), r = p.get(t);
18
18
  r ? r.push(e) : p.set(t, [e]);
19
19
  }
20
- let m = Object.freeze([...p].flatMap(([e, t]) => a(r(d, e, l.filterColumns, l), t, l))), h = i(f, c.sorting, l.sortColumns, l), g = e(h, u);
20
+ let m = Object.freeze([...p].flatMap(([e, t]) => a(e === c.filter ? f : r(d, e, l.filterColumns, l), t, l))), h = i(f, c.sorting, l.sortColumns, l), g = e(h, u);
21
21
  return {
22
22
  view: h,
23
23
  rows: g.rows,
package/dist/columns.d.ts CHANGED
@@ -34,6 +34,8 @@ export interface UnsafeTanStackColumnOptions {
34
34
  readonly [option: string]: unknown;
35
35
  }
36
36
  interface ColumnBase<Row extends object> {
37
+ /** Extra row fields used by a custom cell, including its event handlers. Omit to depend on the whole row. */
38
+ readonly cellDependencies?: readonly (keyof Row & string)[];
37
39
  readonly id: string;
38
40
  readonly header: string;
39
41
  readonly footer?: string | ((rows: readonly Row[]) => JSX.Element);
@@ -76,6 +78,7 @@ interface ResolvedColumn<Row extends object> {
76
78
  readonly header: string;
77
79
  readonly accessor: ((row: Row) => ColumnValue) | null;
78
80
  readonly cell: ((value: ColumnValue, row: Row) => JSX.Element) | null;
81
+ readonly cellDependencies: readonly (keyof Row & string)[] | null;
79
82
  readonly footer: string | ((rows: readonly Row[]) => JSX.Element) | null;
80
83
  readonly width: ColumnWidth;
81
84
  readonly minWidth: number | null;
package/dist/columns.js CHANGED
@@ -12,6 +12,7 @@ var e = Symbol("inspect-sheen-columns"), t = class {
12
12
  "header",
13
13
  "accessor",
14
14
  "cell",
15
+ "cellDependencies",
15
16
  "footer",
16
17
  "width",
17
18
  "minWidth",
@@ -155,47 +156,51 @@ function p(e) {
155
156
  if (y !== null && typeof y != "function") throw Error(`${e}.accessor must be a function`);
156
157
  let b = u(y, `${e}.accessor`), x = v.cell;
157
158
  if (x !== null && typeof x != "function") throw Error(`${e}.cell must be a function`);
159
+ let S = g.cellDependencies;
160
+ if (S !== void 0 && (x === null || _.editor !== void 0 || !Array.isArray(S) || S.some((e) => typeof e != "string" || !e.trim()) || new Set(S).size !== S.length)) throw Error(`${e}.cellDependencies requires unique nonempty row keys and a noneditable custom cell`);
161
+ let C = S === void 0 ? null : Object.freeze([...S]);
158
162
  if (b === null && x === null) throw Error(`${e} must define an accessor or display cell`);
159
163
  if (b === null && (_.filter !== void 0 || _.sort !== void 0 || _.aggregate !== void 0 || _.search !== void 0)) throw Error(`${e} display columns cannot search, filter, sort, or aggregate`);
160
164
  if (_.footer !== void 0 && typeof _.footer != "string" && typeof _.footer != "function") throw Error(`${e}.footer must be a string or function`);
161
- let S = a(_.minWidth, `${e}.minWidth`), C = a(_.maxWidth, `${e}.maxWidth`);
162
- if (S !== null && C !== null && S > C) throw Error(`${e}.minWidth cannot exceed maxWidth`);
163
- let w = _.width ?? "fill";
164
- if (w !== "fill" && w !== "content" && (typeof w != "number" || !Number.isFinite(w) || w <= 0)) throw Error(`${e}.width is invalid`);
165
- if (typeof w == "number" && (S !== null && w < S || C !== null && w > C)) throw Error(`${e}.width must be within its bounds`);
165
+ let w = a(_.minWidth, `${e}.minWidth`), T = a(_.maxWidth, `${e}.maxWidth`);
166
+ if (w !== null && T !== null && w > T) throw Error(`${e}.minWidth cannot exceed maxWidth`);
167
+ let E = _.width ?? "fill";
168
+ if (E !== "fill" && E !== "content" && (typeof E != "number" || !Number.isFinite(E) || E <= 0)) throw Error(`${e}.width is invalid`);
169
+ if (typeof E == "number" && (w !== null && E < w || T !== null && E > T)) throw Error(`${e}.width must be within its bounds`);
166
170
  if (_.numeric !== void 0 && typeof _.numeric != "boolean") throw Error(`${e}.numeric must be boolean`);
167
- let T = _.numeric ?? !1, E = _.align ?? (T ? "end" : "start");
168
- if (E !== "start" && E !== "center" && E !== "end") throw Error(`${e}.align is invalid`);
169
- let D = _.pin ?? !1;
170
- if (D !== !1 && D !== "start" && D !== "end") throw Error(`${e}.pin is invalid`);
171
- if (D !== !1 && typeof w != "number") throw Error(`${e}.width must be numeric when initially pinned`);
171
+ let D = _.numeric ?? !1, O = _.align ?? (D ? "end" : "start");
172
+ if (O !== "start" && O !== "center" && O !== "end") throw Error(`${e}.align is invalid`);
173
+ let k = _.pin ?? !1;
174
+ if (k !== !1 && k !== "start" && k !== "end") throw Error(`${e}.pin is invalid`);
175
+ if (k !== !1 && typeof E != "number") throw Error(`${e}.width must be numeric when initially pinned`);
172
176
  if (_.visible !== void 0 && typeof _.visible != "boolean") throw Error(`${e}.visible must be boolean`);
173
177
  if (_.sensitive !== void 0 && typeof _.sensitive != "boolean") throw Error(`${e}.sensitive must be boolean`);
174
- let O = _.visible ?? !0, k = _.sensitive ?? !1, A = d(g.search, b, O, k, `${e}.search`), j = l(g.editor, b !== null, `${e}.editor`), M = o(_.filter, _.id, `${e}.filter`), N = c(_.filter, `${e}.filter`), P = s(_.sort, b !== null, M, T, _.id, `${e}.sort`), F = _.aggregate ?? null;
175
- if (F !== null && F !== "sum" && F !== "average" && F !== "min" && F !== "max" && F !== "count") throw Error(`${e}.aggregate is invalid`);
176
- if (F !== null && F !== "count" && !T && M?.type !== "number") throw Error(`${e}.${F} requires a numeric column`);
177
- let I = null;
178
- _.__unsafe_tanstack !== void 0 && (r(_.__unsafe_tanstack, `${e}.__unsafe_tanstack`), I = Object.freeze({ ..._.__unsafe_tanstack })), m.push(Object.freeze({
178
+ let A = _.visible ?? !0, j = _.sensitive ?? !1, M = d(g.search, b, A, j, `${e}.search`), N = l(g.editor, b !== null, `${e}.editor`), P = o(_.filter, _.id, `${e}.filter`), F = c(_.filter, `${e}.filter`), I = s(_.sort, b !== null, P, D, _.id, `${e}.sort`), L = _.aggregate ?? null;
179
+ if (L !== null && L !== "sum" && L !== "average" && L !== "min" && L !== "max" && L !== "count") throw Error(`${e}.aggregate is invalid`);
180
+ if (L !== null && L !== "count" && !D && P?.type !== "number") throw Error(`${e}.${L} requires a numeric column`);
181
+ let R = null;
182
+ _.__unsafe_tanstack !== void 0 && (r(_.__unsafe_tanstack, `${e}.__unsafe_tanstack`), R = Object.freeze({ ..._.__unsafe_tanstack })), m.push(Object.freeze({
179
183
  id: _.id,
180
184
  header: _.header,
181
185
  accessor: b,
182
186
  cell: x,
187
+ cellDependencies: C,
183
188
  footer: v.footer,
184
- width: w,
185
- minWidth: S,
186
- maxWidth: C,
187
- align: E,
188
- numeric: T,
189
- pin: D,
190
- visible: O,
191
- search: A,
192
- sensitive: k,
193
- editor: j,
194
- filter: M,
195
- faceted: N,
196
- sort: P,
197
- aggregate: F,
198
- unsafeTanStack: I
189
+ width: E,
190
+ minWidth: w,
191
+ maxWidth: T,
192
+ align: O,
193
+ numeric: D,
194
+ pin: k,
195
+ visible: A,
196
+ search: M,
197
+ sensitive: j,
198
+ editor: N,
199
+ filter: P,
200
+ faceted: F,
201
+ sort: I,
202
+ aggregate: L,
203
+ unsafeTanStack: R
199
204
  })), h++;
200
205
  }
201
206
  return new t(Object.freeze(m));
@@ -0,0 +1,11 @@
1
+ import type { FilterNode } from "./filter.ts";
2
+ import type { ColumnState } from "./table-state.ts";
3
+ export interface ConstrainedColumn {
4
+ readonly column: string;
5
+ readonly kind: "text" | "enum" | "number" | "date";
6
+ readonly value: string | number;
7
+ }
8
+ /** Infer only exact values required by the accepted predicate, never by sampled rows or facets. */
9
+ export declare function constrainedColumnValues(filter: FilterNode): ReadonlyMap<string, ConstrainedColumn>;
10
+ /** A temporary presentation projection. Saved visibility, order, widths, and pins remain untouched. */
11
+ export declare function summarizedColumns(columns: readonly ColumnState[], constraints: ReadonlyMap<string, ConstrainedColumn>, eligible: ReadonlySet<string>, restored: ReadonlySet<string>): readonly ConstrainedColumn[];
@@ -0,0 +1,49 @@
1
+ //#region src/constrained-columns.ts
2
+ function e(e, t) {
3
+ return t !== void 0 && e.kind === t.kind && e.value === t.value;
4
+ }
5
+ function t(n) {
6
+ if (n.kind === "and") {
7
+ let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
8
+ for (let a of n.children) for (let [n, o] of t(a)) {
9
+ if (i.has(n)) continue;
10
+ let t = r.get(n);
11
+ t && !e(t, o) ? (r.delete(n), i.add(n)) : r.set(n, o);
12
+ }
13
+ return r;
14
+ }
15
+ if (n.kind === "or") {
16
+ let r = n.children[0], i = new Map(r ? t(r) : []);
17
+ for (let r of n.children.slice(1)) {
18
+ let n = t(r);
19
+ for (let [t, r] of i) e(r, n.get(t)) || i.delete(t);
20
+ }
21
+ return i;
22
+ }
23
+ if (n.kind === "enum" && n.values.length === 1) {
24
+ let e = n.values[0];
25
+ if (e !== void 0) return /* @__PURE__ */ new Map([[n.column, {
26
+ column: n.column,
27
+ kind: n.kind,
28
+ value: e
29
+ }]]);
30
+ }
31
+ return (n.kind === "number" || n.kind === "date") && n.operator === "eq" ? /* @__PURE__ */ new Map([[n.column, {
32
+ column: n.column,
33
+ kind: n.kind,
34
+ value: n.value
35
+ }]]) : n.kind === "text" && n.operator === "eq" && n.caseSensitive ? /* @__PURE__ */ new Map([[n.column, {
36
+ column: n.column,
37
+ kind: n.kind,
38
+ value: n.value.normalize("NFC")
39
+ }]]) : /* @__PURE__ */ new Map();
40
+ }
41
+ function n(e, t, n, r) {
42
+ let i = e.filter((e) => e.visible), a = i.flatMap((e) => {
43
+ let r = t.get(e.id);
44
+ return r && n.has(e.id) ? [r] : [];
45
+ });
46
+ return a.filter((e) => !r.has(e.column) && (a.length !== i.length || e.column !== i[0]?.id));
47
+ }
48
+ //#endregion
49
+ export { t as constrainedColumnValues, n as summarizedColumns };
package/dist/facets.js CHANGED
@@ -18,14 +18,16 @@ function e(e, t, n) {
18
18
  for (let t = 0; t < e.length; t++) {
19
19
  let r = e[t];
20
20
  if (r === void 0) throw Error(`Missing facet row at index ${t}`);
21
- for (let e of i) {
22
- let i = n.getValue(r, e.column);
23
- if (i == null) {
24
- e.missing++;
21
+ for (let e = 0; e < i.length; e++) {
22
+ let a = i[e];
23
+ if (!a) throw Error(`Missing facet column at index ${e}`);
24
+ let o = n.getValue(r, a.column);
25
+ if (o == null) {
26
+ a.missing++;
25
27
  continue;
26
28
  }
27
- if (typeof i != "string" || !e.counts.has(i)) throw Error(`Invalid enum value for facet ${e.column} at row ${t}`);
28
- e.counts.set(i, (e.counts.get(i) ?? 0) + 1);
29
+ if (typeof o != "string" || !a.counts.has(o)) throw Error(`Invalid enum value for facet ${a.column} at row ${t}`);
30
+ a.counts.set(o, (a.counts.get(o) ?? 0) + 1);
29
31
  }
30
32
  }
31
33
  return Object.freeze(i.map((e) => Object.freeze({
@@ -91,6 +91,9 @@ export declare const englishTableMessages: Readonly<{
91
91
  showColumn: "Show column";
92
92
  moveColumnStart: "Move toward start";
93
93
  moveColumnEnd: "Move toward end";
94
+ constrainedColumns: "Fields fixed by the accepted filter";
95
+ constrainedColumn: "{column}: {value} · {count} matching results";
96
+ restoreColumn: "Restore {column} column";
94
97
  pinColumn: "Pin column";
95
98
  pinNone: "Not pinned";
96
99
  pinStart: "Pin to start";
package/dist/messages.js CHANGED
@@ -92,6 +92,9 @@ var e = Object.freeze({
92
92
  showColumn: "Show column",
93
93
  moveColumnStart: "Move toward start",
94
94
  moveColumnEnd: "Move toward end",
95
+ constrainedColumns: "Fields fixed by the accepted filter",
96
+ constrainedColumn: "{column}: {value} · {count} matching results",
97
+ restoreColumn: "Restore {column} column",
95
98
  pinColumn: "Pin column",
96
99
  pinNone: "Not pinned",
97
100
  pinStart: "Pin to start",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemologic/sheen-table",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.2.0",
4
4
  "description": "Compact accessible data tables and query-building components for Sheen SolidJS applications.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -49,14 +49,14 @@
49
49
  "./styles.css": "./src/styles.css"
50
50
  },
51
51
  "peerDependencies": {
52
- "@gemologic/sheen": "0.1.0-rc.2",
52
+ "@gemologic/sheen": "0.2.0",
53
53
  "solid-js": "1.9.15"
54
54
  },
55
55
  "dependencies": {
56
56
  "@tanstack/solid-virtual": "3.13.37"
57
57
  },
58
58
  "devDependencies": {
59
- "@gemologic/sheen": "0.1.0-rc.2",
59
+ "@gemologic/sheen": "0.2.0",
60
60
  "solid-js": "1.9.15",
61
61
  "vite-plugin-solid": "2.11.14"
62
62
  },
package/src/DataTable.tsx CHANGED
@@ -6,6 +6,7 @@ import { For, Index, Show, createEffect, createMemo, createSignal, createUniqueI
6
6
  import type { Accessor, JSX } from "solid-js";
7
7
  import { changeTableState } from "./table-state-changes.ts";
8
8
  import { canMoveColumn, moveColumn, orderColumnStates, placeColumn } from "./column-layout.ts";
9
+ import { constrainedColumnValues, summarizedColumns } from "./constrained-columns.ts";
9
10
  import type { ColumnDropPlacement, ColumnMoveDirection } from "./column-layout.ts";
10
11
  import { columnStateSchema, readColumnDefinitions } from "./columns.ts";
11
12
  import type { ColumnEditor, ColumnValue, SheenColumns } from "./columns.ts";
@@ -177,6 +178,8 @@ interface DataTableBaseProps<Row extends object> {
177
178
  readonly filterBar?: boolean | DataTableFilterBarOptions;
178
179
  /** Show the keyboard-accessible visibility, order, pin, and sizing menu. */
179
180
  readonly columnControls?: boolean;
181
+ /** Opt-in fields summarized only when the accepted filter fixes their value. Does not rewrite saved visibility. */
182
+ readonly summarizeColumns?: readonly string[];
180
183
  /** Client exports are enabled by default. False hides them; options customize format and filename. */
181
184
  readonly export?: false | DataTableExportOptions;
182
185
  /** Commits values from columns that declare an editor. Required when any editor is present. */
@@ -230,8 +233,8 @@ interface DisplayDataRow<Row extends object> {
230
233
  readonly row: StableRow<Row>;
231
234
  readonly parentId: string | null;
232
235
  readonly depth: number;
233
- position: number;
234
- setSize: number;
236
+ readonly position: number;
237
+ readonly setSize: number;
235
238
  readonly canExpand: boolean;
236
239
  readonly expanded: boolean;
237
240
  readonly unloaded: boolean;
@@ -883,12 +886,8 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
883
886
  }
884
887
  function flatDisplayRow(row: StableRow<Row>, index: number, setSize: number): DisplayDataRow<Row> {
885
888
  const existing = flatDisplayCache.get(row.id);
886
- if (existing) {
887
- existing.position = index + 1;
888
- existing.setSize = setSize;
889
- return existing;
890
- }
891
- const created: DisplayDataRow<Row> = { kind: "data", key: `row:${row.id}`, row, parentId: null, depth: 1, position: index + 1, setSize, canExpand: false, expanded: false, unloaded: false, pending: false, error: null };
889
+ if (existing && existing.row === row && existing.position === index + 1 && existing.setSize === setSize) return existing;
890
+ const created: DisplayDataRow<Row> = Object.freeze({ kind: "data", key: `row:${row.id}`, row, parentId: null, depth: 1, position: index + 1, setSize, canExpand: false, expanded: false, unloaded: false, pending: false, error: null });
892
891
  flatDisplayCache.set(row.id, created);
893
892
  return created;
894
893
  }
@@ -1132,13 +1131,50 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1132
1131
  return Object.freeze({ definition, state, updateState, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1133
1132
  });
1134
1133
  const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1135
- const orderedColumnStates = createMemo(() => orderColumnStates(acceptedState().columns));
1134
+ const acceptedColumns = createMemo(() => acceptedState().columns);
1135
+ const orderedColumnStates = createMemo(() => orderColumnStates(acceptedColumns()));
1136
+ const summaryEligible = createMemo(() => {
1137
+ const ids = props.summarizeColumns ?? [];
1138
+ const unique = new Set<string>();
1139
+ for (const id of ids) {
1140
+ const definition = columnRecordById.get(id)?.definition;
1141
+ if (!definition?.accessor || !definition.filter || definition.editor || definition.sensitive || unique.has(id)) throw new Error("DataTable summarizeColumns requires unique, filterable, noneditable, nonsensitive accessor IDs");
1142
+ unique.add(id);
1143
+ }
1144
+ return unique;
1145
+ });
1146
+ const [restoredSummaries, setRestoredSummaries] = createSignal<ReadonlySet<string>>(new Set());
1147
+ const columnSummaries = createMemo(() => summaryEligible().size === 0 ? [] : summarizedColumns(orderedColumnStates(), constrainedColumnValues(acceptedState().filter), summaryEligible(), restoredSummaries()));
1148
+ const summarizedIds = createMemo(() => new Set(columnSummaries().map(item => item.column)), undefined, {
1149
+ equals: (previous, next) => previous.size === next.size && [...previous].every(id => next.has(id)),
1150
+ });
1151
+ const summaryLabel = (id: string): string => {
1152
+ const summary = columnSummaries().find(item => item.column === id);
1153
+ const definition = columnRecordById.get(id)?.definition;
1154
+ if (!summary || !definition) return "";
1155
+ const locale = theme.state().locale;
1156
+ const value = typeof summary.value === "number"
1157
+ ? summary.kind === "date" ? new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" }).format(summary.value) : new Intl.NumberFormat(locale).format(summary.value)
1158
+ : summary.value;
1159
+ return messages().constrainedColumn.replace(/\{(column|value|count)\}/gu, (_match: string, key: string) => key === "column" ? definition.header : key === "value" ? value : new Intl.NumberFormat(locale).format(result().total));
1160
+ };
1161
+ const restoreSummary = (id: string): void => {
1162
+ setRestoredSummaries(previous => new Set([...previous, id]));
1163
+ queueMicrotask(() => {
1164
+ const header = tableElement?.querySelector<HTMLElement>(`th[data-column="${CSS.escape(id)}"]`);
1165
+ if (header && header.getClientRects().length > 0) {
1166
+ const sort = header.querySelector<HTMLButtonElement>(".sheen-data-table-sort");
1167
+ if (sort) sort.focus({ preventScroll: true });
1168
+ else { header.tabIndex = -1; header.focus({ preventScroll: true }); }
1169
+ } else if (root) { root.tabIndex = -1; root.focus({ preventScroll: true }); }
1170
+ });
1171
+ };
1136
1172
  const visibleDefinitions = createMemo(() => {
1137
1173
  const ordered = orderedColumnStates();
1138
1174
  for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1139
1175
  return ordered.flatMap(state => {
1140
1176
  const record = columnRecordById.get(state.id);
1141
- return record && state.visible ? [record] : [];
1177
+ return record && state.visible && !summarizedIds().has(state.id) ? [record] : [];
1142
1178
  });
1143
1179
  });
1144
1180
  type CellEditController = ReturnType<typeof createCellEdit<ColumnValue, string>>;
@@ -1360,7 +1396,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1360
1396
  const column = columnRecordById.get(columnState.id);
1361
1397
  if (!column) throw new Error(`Missing table column: ${columnState.id}`);
1362
1398
  const items: readonly MenuItem[] = [
1363
- { kind: "checkbox", id: "visible", label: labels.showColumn, checked: columnState.visible, disabled: columnState.visible && visibleCount === 1, onCheckedChange: visible => changeLayout({ kind: "columnVisibility", column: columnState.id, visible }) },
1399
+ { kind: "checkbox", id: "visible", label: labels.showColumn, checked: columnState.visible && !summarizedIds().has(columnState.id), disabled: columnState.visible && visibleCount === 1, onCheckedChange: visible => {
1400
+ if (visible) setRestoredSummaries(previous => new Set([...previous, columnState.id]));
1401
+ changeLayout({ kind: "columnVisibility", column: columnState.id, visible });
1402
+ } },
1364
1403
  { kind: "action", id: "move-start", label: labels.moveColumnStart, disabled: !canMoveColumn(state, columnState.id, "toward-start"), onSelect: () => moveLayoutColumn(columnState.id, "toward-start") },
1365
1404
  { kind: "action", id: "move-end", label: labels.moveColumnEnd, disabled: !canMoveColumn(state, columnState.id, "toward-end"), onSelect: () => moveLayoutColumn(columnState.id, "toward-end") },
1366
1405
  { kind: "radio", id: "pin", label: labels.pinColumn, value: columnState.pin === false ? "none" : columnState.pin, onValueChange: value => {
@@ -1573,14 +1612,18 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1573
1612
  const rowHeight = props.rowHeight ?? "var(--sheen-table-row-h)";
1574
1613
  if (typeof rowHeight !== "string" || rowHeight.trim() === "") throw new Error("rowHeight must be a nonempty CSS length");
1575
1614
  const effectiveDensity = (): DataTableDensity => density() ?? theme.state().density;
1576
- const estimatedRowHeight = (): number => props.estimatedRowHeight ?? (effectiveDensity() === "compact" ? 28 : effectiveDensity() === "spacious" ? 42 : 34);
1577
- if (!Number.isFinite(estimatedRowHeight()) || estimatedRowHeight() <= 0) throw new Error("estimatedRowHeight must be a positive finite number");
1615
+ const estimatedRowHeight = (): number => props.estimatedRowHeight ?? (theme.state().theme === "studio"
1616
+ ? effectiveDensity() === "compact" ? 36 : effectiveDensity() === "spacious" ? 48 : 40
1617
+ : effectiveDensity() === "compact" ? 28 : effectiveDensity() === "spacious" ? 42 : 34);
1618
+ let measuredDensity = effectiveDensity();
1619
+ let measuredRowHeight = estimatedRowHeight();
1620
+ if (!Number.isFinite(measuredRowHeight) || measuredRowHeight <= 0) throw new Error("estimatedRowHeight must be a positive finite number");
1578
1621
  const initialViewportHeight = props.initialViewportHeight ?? 400;
1579
1622
  if (!Number.isFinite(initialViewportHeight) || initialViewportHeight <= 0) throw new Error("initialViewportHeight must be a positive finite number");
1580
1623
  const virtualizer = createVirtualizer<HTMLDivElement, HTMLTableRowElement>({
1581
1624
  get count() { return rowCount(); },
1582
1625
  getScrollElement: () => viewport ?? null,
1583
- estimateSize: estimatedRowHeight,
1626
+ estimateSize: () => measuredRowHeight,
1584
1627
  getItemKey: index => props.variableRowHeight ? rowAt(index)?.key ?? index : index,
1585
1628
  initialRect: { width: 1024, height: initialViewportHeight },
1586
1629
  overscan: 8,
@@ -1597,31 +1640,36 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1597
1640
  for (const element of viewport?.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]") ?? []) virtualizer.measureElement(element);
1598
1641
  }
1599
1642
  });
1600
- let measuredDensity = effectiveDensity();
1601
1643
  createEffect(() => {
1602
1644
  const currentDensity = effectiveDensity();
1603
- if (virtualizerMounted && currentDensity !== measuredDensity) virtualizer.measure();
1645
+ const height = estimatedRowHeight();
1646
+ if (!Number.isFinite(height) || height <= 0) throw new Error("estimatedRowHeight must be a positive finite number");
1647
+ const changed = height !== measuredRowHeight || currentDensity !== measuredDensity;
1648
+ measuredRowHeight = height;
1604
1649
  measuredDensity = currentDensity;
1650
+ if (virtualizerMounted && changed) virtualizer.measure();
1605
1651
  });
1606
1652
  const renderedRowCache = new Map<string, RenderedRow<Row>>();
1607
1653
  const renderedRows = createMemo<readonly RenderedRow<Row>[]>(() => {
1608
1654
  const retained = new Set<string>();
1609
- const rows = virtualizer.getVirtualItems().flatMap(item => {
1655
+ const rows: RenderedRow<Row>[] = [];
1656
+ for (const item of virtualizer.getVirtualItems()) {
1610
1657
  const row = rowAt(item.index);
1611
- if (!row) return [];
1658
+ if (!row) continue;
1612
1659
  retained.add(row.key);
1613
1660
  const existing = renderedRowCache.get(row.key);
1614
1661
  if (existing) {
1615
1662
  existing.updateRow(row);
1616
1663
  existing.updateItem(item);
1617
- return [existing];
1664
+ rows.push(existing);
1665
+ continue;
1618
1666
  }
1619
- const [currentRow, setCurrentRow] = createSignal(row, { equals: false });
1620
- const [currentItem, setCurrentItem] = createSignal(item, { equals: false });
1667
+ const [currentRow, setCurrentRow] = createSignal(row);
1668
+ const [currentItem, setCurrentItem] = createSignal(item);
1621
1669
  const rendered = Object.freeze({ key: row.key, row: currentRow, updateRow: (next: DisplayRow<Row>): void => { setCurrentRow(next); }, item: currentItem, updateItem: (next: VirtualItem): void => { setCurrentItem(next); } });
1622
1670
  renderedRowCache.set(row.key, rendered);
1623
- return [rendered];
1624
- });
1671
+ rows.push(rendered);
1672
+ }
1625
1673
  for (const id of renderedRowCache.keys()) if (!retained.has(id)) renderedRowCache.delete(id);
1626
1674
  return rows;
1627
1675
  });
@@ -1754,6 +1802,16 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1754
1802
  let anchorFrame: number | undefined;
1755
1803
  function captureScrollAnchor(): void {
1756
1804
  if (!viewport) return;
1805
+ if (!props.variableRowHeight && props.estimatedRowHeight === undefined) {
1806
+ // Fixed rows use the virtualizer's coordinates. The sticky header and
1807
+ // body's normal-flow header offset cancel at the visible row boundary.
1808
+ // Avoid querying and measuring every overscan row on each scroll frame.
1809
+ const top = viewport.scrollTop;
1810
+ const item = virtualizer.getVirtualItems().find(candidate => candidate.end > top);
1811
+ const row = item ? rowAt(item.index) : undefined;
1812
+ if (item && row) scrollAnchor = { id: row.key, offset: top - item.start };
1813
+ return;
1814
+ }
1757
1815
  const bounds = viewport.getBoundingClientRect();
1758
1816
  const visibleTop = viewport.querySelector("thead")?.getBoundingClientRect().bottom ?? bounds.top;
1759
1817
  const row = [...viewport.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]")].find(candidate => candidate.getBoundingClientRect().bottom > visibleTop);
@@ -2042,8 +2100,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2042
2100
  </span>;
2043
2101
  }
2044
2102
  function DataCellContent(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly first: boolean; readonly edit: CellEditRecord | undefined }): JSX.Element {
2045
- const value = () => cellProps.column.definition.accessor?.(cellProps.row.row.value()) ?? null;
2046
- const content = () => cellProps.edit ? <EditableCellValue row={cellProps.row} column={cellProps.column} record={cellProps.edit} /> : cellProps.column.definition.cell?.(value(), cellProps.row.row.value()) ?? defaultCell(value());
2103
+ const definition = cellProps.column.definition;
2104
+ const input = createMemo(() => {
2105
+ const row = cellProps.row.row.value();
2106
+ return { row, value: definition.accessor?.(row) ?? null };
2107
+ }, undefined, { equals: (previous, next) => Object.is(previous.value, next.value) && (definition.cell === null
2108
+ || (definition.cellDependencies === null ? previous.row === next.row : definition.cellDependencies.every(key => Object.is(previous.row[key], next.row[key])))) });
2109
+ const content = () => cellProps.edit ? <EditableCellValue row={cellProps.row} column={cellProps.column} record={cellProps.edit} /> : definition.cell?.(input().value, input().row) ?? defaultCell(input().value);
2047
2110
  if (!treePresentation || !cellProps.first) return <>{content()}</>;
2048
2111
  return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, cellProps.row.depth - 1) }}>
2049
2112
  <Show when={cellProps.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
@@ -2116,7 +2179,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2116
2179
  <Show when={acceptedAvailable() ? error() : null}>{value => <div class="sheen-data-table-error" role="alert"><span>{errorMessage(value())}</span><Button onClick={retry}>{messages().retry}</Button></div>}</Show>
2117
2180
  <Show when={exportError()}><div class="sheen-data-table-error" role="alert"><span>{messages().exportFailed}</span><Show when={serverExports}><Button onClick={retryExport}>{messages().retryExport}</Button></Show></div></Show>
2118
2181
  <DataTableToolbar label={messages().tableControls.replace("{caption}", props.caption)} result={resultCount()} resultPrevious={previous() ? messages().previousResults : undefined} actions={toolbarActions()}
2119
- query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) ? <>
2182
+ query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) || columnSummaries().length > 0 ? <>
2120
2183
  <Show when={searchOptions}><div class="sheen-data-table-search-field" data-search-mode={searchMode()}><SearchInput class="sheen-data-table-search" label={searchLabel()} placeholder={searchPlaceholder()} value={searchDraft()} shortcut={searchShortcut()} aria-busy={busy() || undefined}
2121
2184
  onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2122
2185
  <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
@@ -2124,6 +2187,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2124
2187
  </div></Show>
2125
2188
  <Show when={props.filterBar !== false && schema.filterColumns.length > 0}><FilterBar columns={props.columns} value={acceptedState().filter} facets={result().facets} disabled={pending()} onChange={requestFilter}
2126
2189
  {...(typeof props.filterBar === "object" && props.filterBar.dateEditor ? { dateEditor: props.filterBar.dateEditor } : {})} /></Show>
2190
+ <Show when={columnSummaries().length > 0}><div class="sheen-data-table-constraints" role="group" aria-label={messages().constrainedColumns}>
2191
+ <For each={columnSummaries().map(item => item.column)}>{id => <span class="sheen-data-table-constraint"><span>{summaryLabel(id)}</span><Button size="sm" variant="ghost" aria-label={messages().restoreColumn.replaceAll("{column}", columnRecordById.get(id)?.definition.header ?? id)} onClick={() => restoreSummary(id)}>{messages().showColumn}</Button></span>}</For>
2192
+ </div></Show>
2127
2193
  </> : undefined}
2128
2194
  status={<Show when={exportPending()}><span class="sheen-data-table-export-status" role="status">{messages().preparingExport}</span></Show>} />
2129
2195
  <div class="sheen-data-table-frame">
@@ -2188,7 +2254,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2188
2254
  <tbody style={{ height: `${virtualizer.getTotalSize()}px` }}>
2189
2255
  <For each={renderedRows()}>{current => {
2190
2256
  const row = () => current.row();
2191
- const dataRow = () => displayDataRow(row());
2257
+ const dataRow = treePresentation ? () => displayDataRow(row()) : createMemo(() => displayDataRow(row()), undefined, {
2258
+ equals: (previous, next) => previous?.row === next?.row,
2259
+ });
2192
2260
  const groupRow = () => displayGroupRow(row());
2193
2261
  const labelColumn = () => {
2194
2262
  const visible = visibleDefinitions();
@@ -2202,10 +2270,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2202
2270
  </Show>
2203
2271
  </Show>
2204
2272
  <For each={visibleDefinitions()}>{column => {
2205
- const edit = createMemo(() => {
2273
+ const edit = column.definition.editor ? createMemo(() => {
2206
2274
  const value = dataRow();
2207
2275
  return value ? cellEditRecord(value.row, column) : undefined;
2208
- });
2276
+ }) : () => undefined;
2209
2277
  const state = () => editSnapshot(edit());
2210
2278
  const invalid = () => {
2211
2279
  const currentState = state();
@@ -54,7 +54,7 @@ export function createClientView<Row>(rows: readonly Row[], state: ClientViewSta
54
54
  else facetGroups.set(filter, [column]);
55
55
  }
56
56
  const facets = Object.freeze([...facetGroups].flatMap(([filter, columns]) =>
57
- countClientFacets(filterClientRows(searched, filter, options.filterColumns, options), columns, options)));
57
+ countClientFacets(filter === state.filter ? filtered : filterClientRows(searched, filter, options.filterColumns, options), columns, options)));
58
58
  const view = sortClientRows(filtered, state.sorting, options.sortColumns, options);
59
59
  const page = paginateClientRows(view, pagination);
60
60
  return { view, rows: page.rows, total: page.total, pagination: page.pagination, facets };
package/src/columns.ts CHANGED
@@ -25,6 +25,8 @@ export type ColumnFilter =
25
25
  export interface UnsafeTanStackColumnOptions { readonly [option: string]: unknown }
26
26
 
27
27
  interface ColumnBase<Row extends object> {
28
+ /** Extra row fields used by a custom cell, including its event handlers. Omit to depend on the whole row. */
29
+ readonly cellDependencies?: readonly (keyof Row & string)[];
28
30
  readonly id: string;
29
31
  readonly header: string;
30
32
  readonly footer?: string | ((rows: readonly Row[]) => JSX.Element);
@@ -68,6 +70,7 @@ interface ResolvedColumn<Row extends object> {
68
70
  readonly header: string;
69
71
  readonly accessor: ((row: Row) => ColumnValue) | null;
70
72
  readonly cell: ((value: ColumnValue, row: Row) => JSX.Element) | null;
73
+ readonly cellDependencies: readonly (keyof Row & string)[] | null;
71
74
  readonly footer: string | ((rows: readonly Row[]) => JSX.Element) | null;
72
75
  readonly width: ColumnWidth;
73
76
  readonly minWidth: number | null;
@@ -103,7 +106,7 @@ class DefinedColumns<Row extends object> implements SheenColumns<Row> {
103
106
  [inspectColumns](): readonly ResolvedColumn<Row>[] { return this.#definitions; }
104
107
  }
105
108
 
106
- const baseKeys = new Set(["id", "header", "accessor", "cell", "footer", "width", "minWidth", "maxWidth", "align", "numeric", "pin", "visible", "search", "sensitive", "editor", "filter", "sort", "aggregate", "__unsafe_tanstack"]);
109
+ const baseKeys = new Set(["id", "header", "accessor", "cell", "cellDependencies", "footer", "width", "minWidth", "maxWidth", "align", "numeric", "pin", "visible", "search", "sensitive", "editor", "filter", "sort", "aggregate", "__unsafe_tanstack"]);
107
110
  function assertRecord(value: unknown, label: string): asserts value is Record<string, unknown> {
108
111
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be an object`);
109
112
  const prototype = Object.getPrototypeOf(value);
@@ -214,6 +217,12 @@ export function defineColumns<Row extends object>(values: readonly SheenColumnIn
214
217
  const accessor = checkedAccessor(sourceAccessor, `${label}.accessor`);
215
218
  const cell = functions.cell;
216
219
  if (cell !== null && typeof cell !== "function") throw new Error(`${label}.cell must be a function`);
220
+ const dependencies = typedValue.cellDependencies;
221
+ if (dependencies !== undefined && (cell === null || input.editor !== undefined || !Array.isArray(dependencies)
222
+ || dependencies.some(key => typeof key !== "string" || !key.trim()) || new Set(dependencies).size !== dependencies.length)) {
223
+ throw new Error(`${label}.cellDependencies requires unique nonempty row keys and a noneditable custom cell`);
224
+ }
225
+ const cellDependencies = dependencies === undefined ? null : Object.freeze([...dependencies]);
217
226
  if (accessor === null && cell === null) throw new Error(`${label} must define an accessor or display cell`);
218
227
  if (accessor === null && (input.filter !== undefined || input.sort !== undefined || input.aggregate !== undefined || input.search !== undefined)) throw new Error(`${label} display columns cannot search, filter, sort, or aggregate`);
219
228
  if (input.footer !== undefined && typeof input.footer !== "string" && typeof input.footer !== "function") throw new Error(`${label}.footer must be a string or function`);
@@ -247,7 +256,7 @@ export function defineColumns<Row extends object>(values: readonly SheenColumnIn
247
256
  assertRecord(input.__unsafe_tanstack, `${label}.__unsafe_tanstack`);
248
257
  unsafeTanStack = Object.freeze({ ...input.__unsafe_tanstack });
249
258
  }
250
- definitions.push(Object.freeze({ id: input.id, header: input.header, accessor, cell, footer: functions.footer, width, minWidth, maxWidth, align, numeric, pin, visible, search, sensitive, editor, filter, faceted, sort, aggregate, unsafeTanStack }));
259
+ definitions.push(Object.freeze({ id: input.id, header: input.header, accessor, cell, cellDependencies, footer: functions.footer, width, minWidth, maxWidth, align, numeric, pin, visible, search, sensitive, editor, filter, faceted, sort, aggregate, unsafeTanStack }));
251
260
  index++;
252
261
  }
253
262
  return new DefinedColumns(Object.freeze(definitions));
@@ -0,0 +1,60 @@
1
+ import type { FilterNode } from "./filter.ts";
2
+ import type { ColumnState } from "./table-state.ts";
3
+
4
+ export interface ConstrainedColumn {
5
+ readonly column: string;
6
+ readonly kind: "text" | "enum" | "number" | "date";
7
+ readonly value: string | number;
8
+ }
9
+
10
+ function equal(left: ConstrainedColumn, right: ConstrainedColumn | undefined): boolean {
11
+ return right !== undefined && left.kind === right.kind && left.value === right.value;
12
+ }
13
+
14
+ /** Infer only exact values required by the accepted predicate, never by sampled rows or facets. */
15
+ export function constrainedColumnValues(filter: FilterNode): ReadonlyMap<string, ConstrainedColumn> {
16
+ if (filter.kind === "and") {
17
+ const values = new Map<string, ConstrainedColumn>();
18
+ const conflicts = new Set<string>();
19
+ for (const child of filter.children) {
20
+ for (const [column, value] of constrainedColumnValues(child)) {
21
+ if (conflicts.has(column)) continue;
22
+ const previous = values.get(column);
23
+ if (previous && !equal(previous, value)) { values.delete(column); conflicts.add(column); }
24
+ else values.set(column, value);
25
+ }
26
+ }
27
+ return values;
28
+ }
29
+ if (filter.kind === "or") {
30
+ const first = filter.children[0];
31
+ const common = new Map(first ? constrainedColumnValues(first) : []);
32
+ for (const child of filter.children.slice(1)) {
33
+ const values = constrainedColumnValues(child);
34
+ for (const [column, value] of common) if (!equal(value, values.get(column))) common.delete(column);
35
+ }
36
+ return common;
37
+ }
38
+ if (filter.kind === "enum" && filter.values.length === 1) {
39
+ const value = filter.values[0];
40
+ if (value !== undefined) return new Map([[filter.column, { column: filter.column, kind: filter.kind, value }]]);
41
+ }
42
+ if ((filter.kind === "number" || filter.kind === "date") && filter.operator === "eq") {
43
+ return new Map([[filter.column, { column: filter.column, kind: filter.kind, value: filter.value }]]);
44
+ }
45
+ if (filter.kind === "text" && filter.operator === "eq" && filter.caseSensitive) {
46
+ return new Map([[filter.column, { column: filter.column, kind: filter.kind, value: filter.value.normalize("NFC") }]]);
47
+ }
48
+ return new Map();
49
+ }
50
+
51
+ /** A temporary presentation projection. Saved visibility, order, widths, and pins remain untouched. */
52
+ export function summarizedColumns(columns: readonly ColumnState[], constraints: ReadonlyMap<string, ConstrainedColumn>, eligible: ReadonlySet<string>, restored: ReadonlySet<string>): readonly ConstrainedColumn[] {
53
+ const visible = columns.filter(column => column.visible);
54
+ const summaries = visible.flatMap(column => {
55
+ const constraint = constraints.get(column.id);
56
+ return constraint && eligible.has(column.id) ? [constraint] : [];
57
+ });
58
+ // Retain the first logical column when every visible field is constrained.
59
+ return summaries.filter(summary => !restored.has(summary.column) && (summaries.length !== visible.length || summary.column !== visible[0]?.id));
60
+ }