@gemologic/sheen-table 0.1.0 → 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 };
@@ -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",
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",
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",
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. */
@@ -1128,13 +1131,50 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1128
1131
  return Object.freeze({ definition, state, updateState, variable: `--sheen-table-column-${index}`, sortDescriptionId: createUniqueId() });
1129
1132
  });
1130
1133
  const columnRecordById = new Map(columnRecords.map(column => [column.definition.id, column]));
1131
- 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
+ };
1132
1172
  const visibleDefinitions = createMemo(() => {
1133
1173
  const ordered = orderedColumnStates();
1134
1174
  for (const state of ordered) columnRecordById.get(state.id)?.updateState(state);
1135
1175
  return ordered.flatMap(state => {
1136
1176
  const record = columnRecordById.get(state.id);
1137
- return record && state.visible ? [record] : [];
1177
+ return record && state.visible && !summarizedIds().has(state.id) ? [record] : [];
1138
1178
  });
1139
1179
  });
1140
1180
  type CellEditController = ReturnType<typeof createCellEdit<ColumnValue, string>>;
@@ -1356,7 +1396,10 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1356
1396
  const column = columnRecordById.get(columnState.id);
1357
1397
  if (!column) throw new Error(`Missing table column: ${columnState.id}`);
1358
1398
  const items: readonly MenuItem[] = [
1359
- { 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
+ } },
1360
1403
  { kind: "action", id: "move-start", label: labels.moveColumnStart, disabled: !canMoveColumn(state, columnState.id, "toward-start"), onSelect: () => moveLayoutColumn(columnState.id, "toward-start") },
1361
1404
  { kind: "action", id: "move-end", label: labels.moveColumnEnd, disabled: !canMoveColumn(state, columnState.id, "toward-end"), onSelect: () => moveLayoutColumn(columnState.id, "toward-end") },
1362
1405
  { kind: "radio", id: "pin", label: labels.pinColumn, value: columnState.pin === false ? "none" : columnState.pin, onValueChange: value => {
@@ -1569,7 +1612,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1569
1612
  const rowHeight = props.rowHeight ?? "var(--sheen-table-row-h)";
1570
1613
  if (typeof rowHeight !== "string" || rowHeight.trim() === "") throw new Error("rowHeight must be a nonempty CSS length");
1571
1614
  const effectiveDensity = (): DataTableDensity => density() ?? theme.state().density;
1572
- const estimatedRowHeight = (): number => props.estimatedRowHeight ?? (effectiveDensity() === "compact" ? 28 : effectiveDensity() === "spacious" ? 42 : 34);
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);
1573
1618
  let measuredDensity = effectiveDensity();
1574
1619
  let measuredRowHeight = estimatedRowHeight();
1575
1620
  if (!Number.isFinite(measuredRowHeight) || measuredRowHeight <= 0) throw new Error("estimatedRowHeight must be a positive finite number");
@@ -1757,6 +1802,16 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
1757
1802
  let anchorFrame: number | undefined;
1758
1803
  function captureScrollAnchor(): void {
1759
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
+ }
1760
1815
  const bounds = viewport.getBoundingClientRect();
1761
1816
  const visibleTop = viewport.querySelector("thead")?.getBoundingClientRect().bottom ?? bounds.top;
1762
1817
  const row = [...viewport.querySelectorAll<HTMLTableRowElement>("tbody tr[data-row-key]")].find(candidate => candidate.getBoundingClientRect().bottom > visibleTop);
@@ -2045,8 +2100,13 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2045
2100
  </span>;
2046
2101
  }
2047
2102
  function DataCellContent(cellProps: { readonly row: DisplayDataRow<Row>; readonly column: (typeof columnRecords)[number]; readonly first: boolean; readonly edit: CellEditRecord | undefined }): JSX.Element {
2048
- const value = () => cellProps.column.definition.accessor?.(cellProps.row.row.value()) ?? null;
2049
- 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);
2050
2110
  if (!treePresentation || !cellProps.first) return <>{content()}</>;
2051
2111
  return <div class="sheen-data-table-tree-cell" style={{ "--sheen-table-depth": Math.max(0, cellProps.row.depth - 1) }}>
2052
2112
  <Show when={cellProps.row.canExpand} fallback={<span class="sheen-data-table-expander-space" aria-hidden="true" />}>
@@ -2119,7 +2179,7 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2119
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>
2120
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>
2121
2181
  <DataTableToolbar label={messages().tableControls.replace("{caption}", props.caption)} result={resultCount()} resultPrevious={previous() ? messages().previousResults : undefined} actions={toolbarActions()}
2122
- query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) ? <>
2182
+ query={searchOptions || (props.filterBar !== false && schema.filterColumns.length > 0) || columnSummaries().length > 0 ? <>
2123
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}
2124
2184
  onValueChange={updateSearchDraft} onCompositionStart={startSearchComposition} onCompositionEnd={event => finishSearchComposition(event.currentTarget.value)} />
2125
2185
  <Show when={searchOptions?.exactMatch}><DropdownMenu class="sheen-data-table-search-mode-menu" trigger={<span>{searchMode() === "exact" ? messages().searchExact : messages().searchRanked}</span>}
@@ -2127,6 +2187,9 @@ export function DataTable<Row extends object>(props: DataTableProps<Row>): JSX.E
2127
2187
  </div></Show>
2128
2188
  <Show when={props.filterBar !== false && schema.filterColumns.length > 0}><FilterBar columns={props.columns} value={acceptedState().filter} facets={result().facets} disabled={pending()} onChange={requestFilter}
2129
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>
2130
2193
  </> : undefined}
2131
2194
  status={<Show when={exportPending()}><span class="sheen-data-table-export-status" role="status">{messages().preparingExport}</span></Show>} />
2132
2195
  <div class="sheen-data-table-frame">
@@ -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
+ }
package/src/messages.ts CHANGED
@@ -14,6 +14,7 @@ export const englishTableMessages = Object.freeze({
14
14
  queryColumn: "Column", queryAddRule: "Add rule", queryAddGroup: "Add group", queryNegate: "Exclude", queryRemoveNegation: "Include", queryRemove: "Remove", queryMoveBefore: "Move before", queryMoveAfter: "Move after", queryChanged: "Query updated",
15
15
  groupMissing: "No value", loadingChildren: "Loading children",
16
16
  columns: "Columns", showColumn: "Show column", moveColumnStart: "Move toward start", moveColumnEnd: "Move toward end",
17
+ constrainedColumns: "Fields fixed by the accepted filter", constrainedColumn: "{column}: {value} · {count} matching results", restoreColumn: "Restore {column} column",
17
18
  pinColumn: "Pin column", pinNone: "Not pinned", pinStart: "Pin to start", pinEnd: "Pin to end",
18
19
  autoFitColumn: "Auto-fit width", resetColumnWidth: "Reset width", reorderColumn: "Drag to reorder {column}", resizeColumn: "Resize {column}", columnWidthPixels: "{width} pixels",
19
20
  editCell: "Edit {column} for row {id}", cellValueRequired: "A value is required", cellValueInvalid: "Enter a valid value", noValue: "No value",
package/src/styles.css CHANGED
@@ -5,6 +5,8 @@
5
5
  .sheen-data-table[data-variant="framed"] { --sheen-data-table-frame-border: 1px solid var(--sheen-color-border); --sheen-data-table-frame-radius: var(--sheen-surface-radius); --sheen-data-table-viewport-height: var(--sheen-data-table-initial-viewport-height); }
6
6
  .sheen-data-table-toolbar { container: sheen-table-toolbar / inline-size; display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--sheen-space-inline-sm); min-block-size: var(--sheen-control-h-md); padding: var(--sheen-space-block-xs) var(--sheen-space-inline-sm); background: var(--sheen-color-bg-raised); border-block-end: 1px solid var(--sheen-color-border); }
7
7
  .sheen-data-table-toolbar-query { display: flex; flex: 1 1 32rem; flex-wrap: wrap; align-items: center; gap: var(--sheen-space-inline-sm); min-inline-size: 0; }
8
+ .sheen-data-table-constraints { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sheen-space-inline-sm); }
9
+ .sheen-data-table-constraint { display: inline-flex; flex-wrap: wrap; align-items: center; gap: var(--sheen-space-inline-xs); padding-inline-start: var(--sheen-space-inline-sm); border: 1px solid var(--sheen-color-border); border-radius: var(--sheen-control-radius); background: var(--sheen-color-bg-subtle); color: var(--sheen-color-fg-muted); font-size: var(--sheen-text-ui-sm-size); overflow-wrap: anywhere; }
8
10
  .sheen-data-table-search-field { display: flex; flex: 1 1 18rem; align-items: stretch; min-inline-size: 12rem; max-inline-size: 28rem; }
9
11
  .sheen-data-table-search-field .sheen-field-label { position: absolute; inline-size: 1px; block-size: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
10
12
  .sheen-data-table-search-field > .sheen-field { flex: 1 1 auto; min-inline-size: 0; }
@@ -116,7 +118,7 @@
116
118
  .sheen-data-table-editor { box-sizing: border-box; min-inline-size: 0; inline-size: 100%; block-size: calc(var(--sheen-table-row-h) - 0.35rem); padding-inline: var(--sheen-space-inline-xs); color: var(--sheen-color-fg); background: var(--sheen-color-bg-inset); border: 1px solid var(--sheen-color-border-control); border-radius: var(--sheen-control-radius); font: inherit; }
117
119
  .sheen-data-table-editor-boolean { inline-size: 1rem; block-size: 1rem; padding: 0; accent-color: var(--sheen-color-accent); }
118
120
  .sheen-data-table-editor:focus-visible { outline: var(--sheen-focus-ring-width) solid var(--sheen-color-focus-ring); outline-offset: var(--sheen-focus-ring-offset); }
119
- .sheen-data-table-edit-message { position: absolute; inset-block-start: calc(100% - 1px); inset-inline-start: var(--sheen-space-inline-sm); min-inline-size: min(16rem, calc(100vw - 2rem)); max-inline-size: 24rem; padding: var(--sheen-space-inline-xs) var(--sheen-space-inline-sm); color: var(--sheen-color-danger-fg); background: var(--sheen-color-bg-overlay); border: 1px solid var(--sheen-color-danger-border); border-radius: var(--sheen-surface-radius); box-shadow: var(--sheen-shadow-3); font-size: var(--sheen-text-ui-sm-size); line-height: var(--sheen-text-ui-sm-leading); white-space: normal; }
121
+ .sheen-data-table-edit-message { position: absolute; inset-block-start: calc(100% - 1px); inset-inline-start: var(--sheen-space-inline-sm); min-inline-size: min(16rem, calc(100vw - 2rem)); max-inline-size: 24rem; padding: var(--sheen-space-inline-xs) var(--sheen-space-inline-sm); color: var(--sheen-color-danger-fg); background: var(--sheen-color-bg-raised); border: 1px solid var(--sheen-color-danger-border); border-radius: var(--sheen-surface-radius); box-shadow: var(--sheen-elevation-overlay); font-size: var(--sheen-text-ui-sm-size); line-height: var(--sheen-text-ui-sm-leading); white-space: normal; }
120
122
  .sheen-data-table-empty { min-block-size: var(--sheen-table-row-h); }
121
123
  .sheen-data-table-empty td { grid-column: 1 / -1; block-size: auto; min-block-size: var(--sheen-table-row-h); padding: 0; overflow: visible; white-space: normal; color: var(--sheen-color-fg-muted); }
122
124
  .sheen-data-table-state { display: grid; justify-items: start; gap: var(--sheen-space-block-sm); padding: var(--sheen-space-section); color: var(--sheen-color-fg); }