@gemologic/sheen-table 0.1.0-rc.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.
Files changed (106) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +19 -0
  3. package/dist/DataTable.d.ts +159 -0
  4. package/dist/DataTable.js +2724 -0
  5. package/dist/DataTableToolbar.d.ts +28 -0
  6. package/dist/DataTableToolbar.js +132 -0
  7. package/dist/FilterBar.d.ts +24 -0
  8. package/dist/FilterBar.js +681 -0
  9. package/dist/QueryBuilder.d.ts +11 -0
  10. package/dist/QueryBuilder.js +693 -0
  11. package/dist/cell-edit.d.ts +50 -0
  12. package/dist/cell-edit.js +178 -0
  13. package/dist/client-state.d.ts +28 -0
  14. package/dist/client-state.js +57 -0
  15. package/dist/client-view.d.ts +31 -0
  16. package/dist/client-view.js +30 -0
  17. package/dist/column-layout.d.ts +10 -0
  18. package/dist/column-layout.js +34 -0
  19. package/dist/columns.d.ts +108 -0
  20. package/dist/columns.js +217 -0
  21. package/dist/core.d.ts +54 -0
  22. package/dist/core.js +28 -0
  23. package/dist/export.d.ts +14 -0
  24. package/dist/export.js +27 -0
  25. package/dist/facets.d.ts +15 -0
  26. package/dist/facets.js +41 -0
  27. package/dist/filter-bar-state.d.ts +22 -0
  28. package/dist/filter-bar-state.js +128 -0
  29. package/dist/filter-client.d.ts +9 -0
  30. package/dist/filter-client.js +69 -0
  31. package/dist/filter.d.ts +64 -0
  32. package/dist/filter.js +132 -0
  33. package/dist/grouping.d.ts +37 -0
  34. package/dist/grouping.js +126 -0
  35. package/dist/index.d.ts +7 -0
  36. package/dist/index.js +31 -0
  37. package/dist/messages.d.ts +115 -0
  38. package/dist/messages.js +121 -0
  39. package/dist/pagination.d.ts +36 -0
  40. package/dist/pagination.js +102 -0
  41. package/dist/query-builder-state.d.ts +28 -0
  42. package/dist/query-builder-state.js +128 -0
  43. package/dist/requests.d.ts +26 -0
  44. package/dist/requests.js +106 -0
  45. package/dist/row-hierarchy.d.ts +32 -0
  46. package/dist/row-hierarchy.js +170 -0
  47. package/dist/row-identity.d.ts +11 -0
  48. package/dist/row-identity.js +36 -0
  49. package/dist/saved-views.d.ts +52 -0
  50. package/dist/saved-views.js +153 -0
  51. package/dist/search-controller.d.ts +22 -0
  52. package/dist/search-controller.js +75 -0
  53. package/dist/search.d.ts +28 -0
  54. package/dist/search.js +111 -0
  55. package/dist/selection-client.d.ts +9 -0
  56. package/dist/selection-client.js +14 -0
  57. package/dist/selection.d.ts +25 -0
  58. package/dist/selection.js +60 -0
  59. package/dist/server-export.d.ts +27 -0
  60. package/dist/server-export.js +105 -0
  61. package/dist/sorting.d.ts +17 -0
  62. package/dist/sorting.js +58 -0
  63. package/dist/table-state-changes.d.ts +27 -0
  64. package/dist/table-state-changes.js +67 -0
  65. package/dist/table-state.d.ts +20 -0
  66. package/dist/table-state.js +77 -0
  67. package/dist/text-normalization.d.ts +2 -0
  68. package/dist/text-normalization.js +12 -0
  69. package/dist/url-state.d.ts +39 -0
  70. package/dist/url-state.js +75 -0
  71. package/package.json +66 -0
  72. package/src/DataTable.tsx +2322 -0
  73. package/src/DataTableToolbar.tsx +69 -0
  74. package/src/FilterBar.tsx +396 -0
  75. package/src/QueryBuilder.tsx +274 -0
  76. package/src/cell-edit.ts +187 -0
  77. package/src/client-state.ts +52 -0
  78. package/src/client-view.ts +61 -0
  79. package/src/column-layout.ts +47 -0
  80. package/src/columns.ts +271 -0
  81. package/src/core.ts +54 -0
  82. package/src/export.ts +39 -0
  83. package/src/facets.ts +46 -0
  84. package/src/filter-bar-state.ts +118 -0
  85. package/src/filter-client.ts +79 -0
  86. package/src/filter.ts +113 -0
  87. package/src/grouping.ts +185 -0
  88. package/src/index.ts +7 -0
  89. package/src/messages.ts +29 -0
  90. package/src/pagination.ts +81 -0
  91. package/src/query-builder-state.ts +105 -0
  92. package/src/requests.ts +85 -0
  93. package/src/row-hierarchy.ts +280 -0
  94. package/src/row-identity.ts +39 -0
  95. package/src/saved-views.ts +143 -0
  96. package/src/search-controller.ts +61 -0
  97. package/src/search.ts +137 -0
  98. package/src/selection-client.ts +23 -0
  99. package/src/selection.ts +62 -0
  100. package/src/server-export.ts +89 -0
  101. package/src/sorting.ts +63 -0
  102. package/src/styles.css +197 -0
  103. package/src/table-state-changes.ts +51 -0
  104. package/src/table-state.ts +72 -0
  105. package/src/text-normalization.ts +14 -0
  106. package/src/url-state.ts +62 -0
@@ -0,0 +1,274 @@
1
+ import { Button, CheckboxGroup, Input, NumberField, Select, Switch, cn, useTheme } from "@gemologic/sheen";
2
+ import { Index, Match, Show, Switch as MatchSwitch, createMemo, createSignal, splitProps } from "solid-js";
3
+ import type { JSX } from "solid-js";
4
+ import type { FilterColumn, FilterNode } from "./filter.ts";
5
+ import { parseFilter } from "./filter.ts";
6
+ import { resolveTableMessages } from "./messages.ts";
7
+ import type { TableMessages } from "./messages.ts";
8
+ import {
9
+ appendQueryChild,
10
+ defaultQueryRule,
11
+ moveQueryNode,
12
+ queryBuilderFilterColumns,
13
+ removeQueryNode,
14
+ replaceQueryNode,
15
+ toggleQueryNegation,
16
+ } from "./query-builder-state.ts";
17
+ import type { QueryBuilderColumn, QueryBuilderPath } from "./query-builder-state.ts";
18
+
19
+ export interface QueryBuilderProps extends Omit<JSX.HTMLAttributes<HTMLElement>, "children" | "onChange"> {
20
+ readonly columns: readonly QueryBuilderColumn[];
21
+ readonly value: FilterNode;
22
+ readonly onChange: (filter: FilterNode) => void;
23
+ readonly label?: string;
24
+ readonly disabled?: boolean;
25
+ }
26
+
27
+ interface NodeEditorProps {
28
+ readonly node: FilterNode;
29
+ readonly path: QueryBuilderPath;
30
+ readonly columns: readonly QueryBuilderColumn[];
31
+ readonly schema: readonly FilterColumn[];
32
+ readonly disabled: boolean;
33
+ readonly structural: boolean;
34
+ readonly index: number;
35
+ readonly siblingCount: number;
36
+ readonly messages: TableMessages;
37
+ readonly publish: (filter: FilterNode, announcement: string) => void;
38
+ readonly root: () => FilterNode;
39
+ }
40
+
41
+ type GroupNode = Extract<FilterNode, { readonly kind: "and" | "or" }>;
42
+ type NotNode = Extract<FilterNode, { readonly kind: "not" }>;
43
+ type RuleNode = Exclude<FilterNode, { readonly kind: "and" | "or" | "not" }>;
44
+ type NumberNode = Extract<FilterNode, { readonly kind: "number" }>;
45
+ type DateNode = Extract<FilterNode, { readonly kind: "date" }>;
46
+ type TextNode = Extract<FilterNode, { readonly kind: "text" }>;
47
+ type EnumNode = Extract<FilterNode, { readonly kind: "enum" }>;
48
+ type NumberRangeNode = Extract<NumberNode, { readonly operator: "between" }>;
49
+ type NumberScalarNode = Exclude<NumberNode, { readonly operator: "between" }>;
50
+ type DateRangeNode = Extract<DateNode, { readonly operator: "between" }>;
51
+ type DateScalarNode = Exclude<DateNode, { readonly operator: "between" }>;
52
+
53
+ function textNode(node: RuleNode): TextNode {
54
+ if (node.kind !== "text") throw new Error("QueryBuilder expected a text rule");
55
+ return node;
56
+ }
57
+
58
+ function numberNode(node: RuleNode): NumberNode {
59
+ if (node.kind !== "number") throw new Error("QueryBuilder expected a number rule");
60
+ return node;
61
+ }
62
+
63
+ function dateNode(node: RuleNode): DateNode {
64
+ if (node.kind !== "date") throw new Error("QueryBuilder expected a date rule");
65
+ return node;
66
+ }
67
+
68
+ function enumNode(node: RuleNode): EnumNode {
69
+ if (node.kind !== "enum") throw new Error("QueryBuilder expected an enum rule");
70
+ return node;
71
+ }
72
+
73
+ function numberRangeNode(node: NumberNode): NumberRangeNode {
74
+ if (node.operator !== "between") throw new Error("QueryBuilder expected a number range");
75
+ return node;
76
+ }
77
+
78
+ function numberScalarNode(node: NumberNode): NumberScalarNode {
79
+ if (node.operator === "between") throw new Error("QueryBuilder expected a scalar number rule");
80
+ return node;
81
+ }
82
+
83
+ function dateRangeNode(node: DateNode): DateRangeNode {
84
+ if (node.operator !== "between") throw new Error("QueryBuilder expected a date range");
85
+ return node;
86
+ }
87
+
88
+ function dateScalarNode(node: DateNode): DateScalarNode {
89
+ if (node.operator === "between") throw new Error("QueryBuilder expected a scalar date rule");
90
+ return node;
91
+ }
92
+
93
+ function groupNode(node: FilterNode): GroupNode {
94
+ if (node.kind !== "and" && node.kind !== "or") throw new Error("QueryBuilder expected a group");
95
+ return node;
96
+ }
97
+
98
+ function notNode(node: FilterNode): NotNode {
99
+ if (node.kind !== "not") throw new Error("QueryBuilder expected a negated rule");
100
+ return node;
101
+ }
102
+
103
+ function ruleNode(node: FilterNode): RuleNode {
104
+ if (node.kind === "and" || node.kind === "or" || node.kind === "not") throw new Error("QueryBuilder expected a rule");
105
+ return node;
106
+ }
107
+
108
+ function pathKey(path: QueryBuilderPath): string {
109
+ return path.length === 0 ? "root" : path.join("-");
110
+ }
111
+
112
+ function dateInputValue(timestamp: number): string {
113
+ return new Date(timestamp).toISOString().slice(0, 10);
114
+ }
115
+
116
+ function parseDateInput(value: string): number | undefined {
117
+ if (!/^\d{4}-\d{2}-\d{2}$/u.test(value)) return undefined;
118
+ const timestamp = Date.parse(`${value}T00:00:00.000Z`);
119
+ return Number.isFinite(timestamp) && dateInputValue(timestamp) === value ? timestamp : undefined;
120
+ }
121
+
122
+ function columnById(columns: readonly QueryBuilderColumn[], id: string): QueryBuilderColumn {
123
+ const column = columns.find(candidate => candidate.id === id);
124
+ if (!column) throw new Error(`QueryBuilder cannot edit missing column ${JSON.stringify(id)}`);
125
+ return column;
126
+ }
127
+
128
+ function enumOptions(column: QueryBuilderColumn): readonly { readonly value: string; readonly label: string }[] {
129
+ return column.type === "enum" ? column.options.map(value => ({ value, label: value })) : [];
130
+ }
131
+
132
+ function operatorOptions(column: QueryBuilderColumn, messages: TableMessages): readonly { readonly value: string; readonly label: string }[] {
133
+ if (column.type === "text") return [
134
+ { value: "contains", label: messages.filterContains }, { value: "eq", label: messages.filterEquals },
135
+ { value: "startsWith", label: messages.filterStartsWith }, { value: "endsWith", label: messages.filterEndsWith },
136
+ { value: "empty", label: messages.filterIsEmpty },
137
+ ];
138
+ if (column.type === "enum") return [{ value: "in", label: messages.filterIsAnyOf }, { value: "empty", label: messages.filterIsEmpty }];
139
+ return [
140
+ { value: "eq", label: messages.filterEquals }, { value: "lt", label: messages.filterLessThan },
141
+ { value: "lte", label: messages.filterAtMost }, { value: "gt", label: messages.filterGreaterThan },
142
+ { value: "gte", label: messages.filterAtLeast }, { value: "between", label: messages.filterBetween },
143
+ { value: "empty", label: messages.filterIsEmpty },
144
+ ];
145
+ }
146
+
147
+ function operator(node: FilterNode): string {
148
+ if (node.kind === "and" || node.kind === "or" || node.kind === "not") return "";
149
+ return node.kind === "empty" ? "empty" : node.operator;
150
+ }
151
+
152
+ function changeOperator(node: FilterNode, column: QueryBuilderColumn, next: string): FilterNode {
153
+ if (next === "empty") return Object.freeze({ kind: "empty", column: column.id });
154
+ if (column.type === "text" && (next === "eq" || next === "contains" || next === "startsWith" || next === "endsWith")) {
155
+ return Object.freeze({ kind: "text", column: column.id, operator: next, value: node.kind === "text" ? node.value : "", caseSensitive: node.kind === "text" && node.caseSensitive });
156
+ }
157
+ if ((column.type === "number" || column.type === "date") && (next === "eq" || next === "lt" || next === "lte" || next === "gt" || next === "gte" || next === "between")) {
158
+ const fallback = defaultQueryRule(column);
159
+ const initial = node.kind === column.type ? (node.operator === "between" ? node.min : node.value)
160
+ : fallback.kind === column.type && fallback.operator !== "between" ? fallback.value : 0;
161
+ return next === "between" ? Object.freeze({ kind: column.type, column: column.id, operator: "between", min: initial, max: initial })
162
+ : Object.freeze({ kind: column.type, column: column.id, operator: next, value: initial });
163
+ }
164
+ if (column.type === "enum" && next === "in") {
165
+ const fallback = defaultQueryRule(column);
166
+ const values = node.kind === "enum" ? node.values : fallback.kind === "enum" ? fallback.values : [];
167
+ return Object.freeze({ kind: "enum", column: column.id, operator: "in", values });
168
+ }
169
+ throw new Error(`QueryBuilder operator ${JSON.stringify(next)} is not valid for ${column.type}`);
170
+ }
171
+
172
+ function StructuralActions(props: NodeEditorProps): JSX.Element {
173
+ if (!props.structural) return null;
174
+ const update = (next: FilterNode, announcement: string): void => props.publish(next, announcement);
175
+ return <div class="sheen-query-node-actions">
176
+ <Button size="xs" aria-label={props.messages.queryMoveBefore} disabled={props.disabled || props.index === 0}
177
+ onClick={() => update(moveQueryNode(props.root(), props.path, -1, props.schema), props.messages.queryChanged)}>{props.messages.queryMoveBefore}</Button>
178
+ <Button size="xs" aria-label={props.messages.queryMoveAfter} disabled={props.disabled || props.index >= props.siblingCount - 1}
179
+ onClick={() => update(moveQueryNode(props.root(), props.path, 1, props.schema), props.messages.queryChanged)}>{props.messages.queryMoveAfter}</Button>
180
+ <Button size="xs" disabled={props.disabled} onClick={() => update(toggleQueryNegation(props.root(), props.path, props.schema), props.messages.queryChanged)}>{props.messages.queryNegate}</Button>
181
+ <Button size="xs" tone="danger" disabled={props.disabled} onClick={() => update(removeQueryNode(props.root(), props.path, props.schema), props.messages.queryChanged)}>{props.messages.queryRemove}</Button>
182
+ </div>;
183
+ }
184
+
185
+ function GroupEditor(props: NodeEditorProps & { readonly node: GroupNode }): JSX.Element {
186
+ const replace = (node: FilterNode): void => props.publish(replaceQueryNode(props.root(), props.path, node, props.schema), props.messages.queryChanged);
187
+ const addRule = (): void => {
188
+ const first = props.columns[0];
189
+ if (!first) return;
190
+ props.publish(appendQueryChild(props.root(), props.path, defaultQueryRule(first), props.schema), props.messages.queryChanged);
191
+ };
192
+ const addGroup = (): void => props.publish(appendQueryChild(props.root(), props.path, Object.freeze({ kind: "and", children: Object.freeze([]) }), props.schema), props.messages.queryChanged);
193
+ return <fieldset class="sheen-query-group" data-query-path={pathKey(props.path)}>
194
+ <legend>{props.messages.queryGroup}</legend>
195
+ <div class="sheen-query-group-toolbar">
196
+ <Select label={props.messages.queryMatch} value={props.node.kind} disabled={props.disabled} options={[
197
+ { value: "and", label: props.messages.queryMatchAll }, { value: "or", label: props.messages.queryMatchAny },
198
+ ]} onValueChange={value => {
199
+ if (value === "and" || value === "or") replace(Object.freeze({ kind: value, children: props.node.children }));
200
+ }} />
201
+ <Button size="sm" disabled={props.disabled || props.columns.length === 0} onClick={addRule}>{props.messages.queryAddRule}</Button>
202
+ <Button size="sm" disabled={props.disabled} onClick={addGroup}>{props.messages.queryAddGroup}</Button>
203
+ <StructuralActions {...props} />
204
+ </div>
205
+ <Show when={props.node.children.length > 0} fallback={<p class="sheen-query-empty">{props.messages.noResults}</p>}>
206
+ <ol class="sheen-query-children"><Index each={props.node.children}>{(child, index) => <li>
207
+ <QueryNodeEditor {...props} node={child()} path={[...props.path, index]} structural index={index} siblingCount={props.node.children.length} />
208
+ </li>}</Index></ol>
209
+ </Show>
210
+ </fieldset>;
211
+ }
212
+
213
+ function RuleEditor(props: NodeEditorProps & { readonly node: RuleNode }): JSX.Element {
214
+ const column = createMemo(() => columnById(props.columns, props.node.column));
215
+ const replace = (node: FilterNode): void => props.publish(replaceQueryNode(props.root(), props.path, node, props.schema), props.messages.queryChanged);
216
+ const setOperator = (value: string | null): void => { if (value) replace(changeOperator(props.node, column(), value)); };
217
+ return <div class="sheen-query-rule" role="group" aria-label={`${props.messages.queryRule}: ${column().label}`} data-query-path={pathKey(props.path)}>
218
+ <div class="sheen-query-rule-fields">
219
+ <Select label={props.messages.queryColumn} value={column().id} disabled={props.disabled} options={props.columns.map(item => ({ value: item.id, label: item.label }))}
220
+ onValueChange={value => { const next = props.columns.find(item => item.id === value); if (next) replace(defaultQueryRule(next)); }} />
221
+ <Select label={props.messages.filterOperator} value={operator(props.node)} disabled={props.disabled} options={operatorOptions(column(), props.messages)} onValueChange={setOperator} />
222
+ <MatchSwitch>
223
+ <Match when={props.node.kind === "text"}><Input label={props.messages.filterValue} value={textNode(props.node).value} disabled={props.disabled} onInput={event => replace(Object.freeze({ ...textNode(props.node), value: event.currentTarget.value }))} />
224
+ <Switch label={props.messages.filterCaseSensitive} checked={textNode(props.node).caseSensitive} disabled={props.disabled} onCheckedChange={caseSensitive => replace(Object.freeze({ ...textNode(props.node), caseSensitive }))} /></Match>
225
+ <Match when={props.node.kind === "number"}><MatchSwitch>
226
+ <Match when={numberNode(props.node).operator === "between"}><NumberField label={props.messages.filterMinimum} value={numberRangeNode(numberNode(props.node)).min} disabled={props.disabled} onValueChange={min => { const current = numberRangeNode(numberNode(props.node)); if (min !== null && min <= current.max) replace(Object.freeze({ ...current, min })); }} />
227
+ <NumberField label={props.messages.filterMaximum} value={numberRangeNode(numberNode(props.node)).max} disabled={props.disabled} onValueChange={max => { const current = numberRangeNode(numberNode(props.node)); if (max !== null && max >= current.min) replace(Object.freeze({ ...current, max })); }} /></Match>
228
+ <Match when={numberNode(props.node).operator !== "between"}><NumberField label={props.messages.filterValue} value={numberScalarNode(numberNode(props.node)).value} disabled={props.disabled} onValueChange={value => { if (value !== null) replace(Object.freeze({ ...numberScalarNode(numberNode(props.node)), value })); }} /></Match>
229
+ </MatchSwitch></Match>
230
+ <Match when={props.node.kind === "date"}><MatchSwitch>
231
+ <Match when={dateNode(props.node).operator === "between"}><Input type="date" label={props.messages.filterStartDate} value={dateInputValue(dateRangeNode(dateNode(props.node)).min)} disabled={props.disabled} onInput={event => { const current = dateRangeNode(dateNode(props.node)); const min = parseDateInput(event.currentTarget.value); if (min !== undefined && min <= current.max) replace(Object.freeze({ ...current, min })); }} />
232
+ <Input type="date" label={props.messages.filterEndDate} value={dateInputValue(dateRangeNode(dateNode(props.node)).max)} disabled={props.disabled} onInput={event => { const current = dateRangeNode(dateNode(props.node)); const max = parseDateInput(event.currentTarget.value); if (max !== undefined && max >= current.min) replace(Object.freeze({ ...current, max })); }} /></Match>
233
+ <Match when={dateNode(props.node).operator !== "between"}><Input type="date" label={props.messages.filterDate} value={dateInputValue(dateScalarNode(dateNode(props.node)).value)} disabled={props.disabled} onInput={event => { const value = parseDateInput(event.currentTarget.value); if (value !== undefined) replace(Object.freeze({ ...dateScalarNode(dateNode(props.node)), value })); }} /></Match>
234
+ </MatchSwitch></Match>
235
+ <Match when={props.node.kind === "enum"}><CheckboxGroup label={props.messages.filterValues} value={enumNode(props.node).values} disabled={props.disabled} options={enumOptions(column())}
236
+ onValueChange={values => { if (values.length > 0) replace(Object.freeze({ ...enumNode(props.node), values: Object.freeze([...values]) })); }} /></Match>
237
+ </MatchSwitch>
238
+ </div>
239
+ <StructuralActions {...props} />
240
+ </div>;
241
+ }
242
+
243
+ function QueryNodeEditor(props: NodeEditorProps): JSX.Element {
244
+ return <MatchSwitch>
245
+ <Match when={props.node.kind === "not"}><section class="sheen-query-not" aria-label={props.messages.queryNegate} data-query-path={pathKey(props.path)}>
246
+ <div class="sheen-query-not-toolbar"><strong>{props.messages.queryNegate}</strong>
247
+ <Button size="xs" disabled={props.disabled} onClick={() => props.publish(toggleQueryNegation(props.root(), props.path, props.schema), props.messages.queryChanged)}>{props.messages.queryRemoveNegation}</Button>
248
+ <StructuralActions {...props} />
249
+ </div>
250
+ <QueryNodeEditor {...props} node={notNode(props.node).child} path={[...props.path, 0]} structural={false} index={0} siblingCount={1} />
251
+ </section></Match>
252
+ <Match when={props.node.kind === "and" || props.node.kind === "or"}><GroupEditor {...props} node={groupNode(props.node)} /></Match>
253
+ <Match when={props.node.kind !== "and" && props.node.kind !== "or" && props.node.kind !== "not"}><RuleEditor {...props} node={ruleNode(props.node)} /></Match>
254
+ </MatchSwitch>;
255
+ }
256
+
257
+ export function QueryBuilder(props: QueryBuilderProps): JSX.Element {
258
+ const [local, rest] = splitProps(props, ["columns", "value", "onChange", "label", "disabled", "class", "ref"]);
259
+ const theme = useTheme();
260
+ const [announcement, setAnnouncement] = createSignal("");
261
+ const messages = createMemo(() => resolveTableMessages(theme.messages()));
262
+ const schema = createMemo(() => queryBuilderFilterColumns(local.columns));
263
+ const value = createMemo(() => parseFilter(local.value, schema()));
264
+ const publish = (filter: FilterNode, message: string): void => {
265
+ local.onChange(parseFilter(filter, schema()));
266
+ setAnnouncement("");
267
+ queueMicrotask(() => setAnnouncement(message));
268
+ };
269
+ return <section {...rest} ref={local.ref} class={cn("sheen-query-builder", local.class)} aria-label={local.label ?? messages().queryBuilder} data-disabled={local.disabled || undefined}>
270
+ <QueryNodeEditor node={value()} path={[]} columns={local.columns} schema={schema()} disabled={local.disabled ?? false} structural={false} index={0} siblingCount={1}
271
+ messages={messages()} publish={publish} root={value} />
272
+ <div class="sheen-query-announcement" role="status" aria-live="polite">{announcement()}</div>
273
+ </section>;
274
+ }
@@ -0,0 +1,187 @@
1
+ export type CellEditValue = string | number | boolean | null;
2
+
3
+ export interface CellCommitRequest<Value extends CellEditValue> {
4
+ readonly commitId: bigint;
5
+ readonly value: Value;
6
+ readonly previous: Value;
7
+ }
8
+ export type CellCommitResult<Value extends CellEditValue, Conflict> =
9
+ | { readonly kind: "accepted"; readonly value: Value }
10
+ | { readonly kind: "conflict"; readonly current: Value; readonly detail: Conflict };
11
+ export type CellCommitAttempt<Value extends CellEditValue> = CellCommitRequest<Value>;
12
+ export interface CellEditConflict<Value extends CellEditValue, Conflict> {
13
+ readonly commitId: bigint;
14
+ readonly attempted: Value;
15
+ readonly current: Value;
16
+ readonly detail: Conflict;
17
+ }
18
+ export interface CellEditSnapshot<Value extends CellEditValue, Conflict> {
19
+ readonly committed: Value;
20
+ readonly draft: { readonly value: Value } | null;
21
+ readonly editing: boolean;
22
+ readonly pending: boolean;
23
+ readonly invalid: string | null;
24
+ readonly stale: boolean;
25
+ readonly error: unknown;
26
+ readonly attempt: CellCommitAttempt<Value> | null;
27
+ readonly conflict: CellEditConflict<Value, Conflict> | null;
28
+ }
29
+ export type CellCommitOutcome = "accepted" | "conflict" | "invalid" | "failed" | "busy" | "superseded" | "changed" | "inactive" | "disposed";
30
+ export interface CellEditOptions<Value extends CellEditValue> {
31
+ readonly validate?: (value: Value) => string | null;
32
+ readonly equals?: (left: Value, right: Value) => boolean;
33
+ }
34
+
35
+ function assertValue(value: unknown): asserts value is CellEditValue {
36
+ if (value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new Error("Cell edit values must be strings, finite numbers, booleans, or null");
37
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("Cell edit numbers must be finite");
38
+ }
39
+
40
+ /** Framework-neutral single-cell ownership. UIs publish snapshots around awaited methods. */
41
+ export function createCellEdit<Value extends CellEditValue, Conflict = unknown>(
42
+ initial: Value,
43
+ onCellCommit: (request: CellCommitRequest<Value>, signal: AbortSignal) => Promise<CellCommitResult<Value, Conflict>>,
44
+ options: CellEditOptions<Value> = {},
45
+ ) {
46
+ assertValue(initial);
47
+ const equals = options.equals ?? ((left: Value, right: Value) => Object.is(left, right));
48
+ let snapshot: CellEditSnapshot<Value, Conflict> = Object.freeze({ committed: initial, draft: null, editing: false, pending: false, invalid: null, stale: false, error: null, attempt: null, conflict: null });
49
+ let editBase: { readonly value: Value } | null = null;
50
+ let draftRevision = 0n;
51
+ let sequence = 0n;
52
+ let nextCommitId = 0n;
53
+ let retryRevision: bigint | null = null;
54
+ let pendingRevision: bigint | null = null;
55
+ let controller: AbortController | undefined;
56
+ let disposed = false;
57
+ let clearing = false;
58
+
59
+ const draft = (value: Value) => Object.freeze({ value });
60
+ const attempt = (commitId: bigint, value: Value, previous: Value) => Object.freeze({ commitId, value, previous });
61
+ function publish(value: CellEditSnapshot<Value, Conflict>): void { snapshot = Object.freeze(value); }
62
+
63
+ function begin(): boolean {
64
+ if (disposed || clearing || snapshot.editing) return false;
65
+ editBase = draft(snapshot.committed);
66
+ draftRevision++;
67
+ retryRevision = null;
68
+ publish({ ...snapshot, draft: draft(snapshot.committed), editing: true, invalid: null, stale: false, error: null, attempt: null, conflict: null });
69
+ return true;
70
+ }
71
+
72
+ function setDraft(value: Value): void {
73
+ assertValue(value);
74
+ if (disposed || clearing || !snapshot.editing) throw new Error("Cell is not available for editing");
75
+ draftRevision++;
76
+ publish({ ...snapshot, draft: draft(value), invalid: null });
77
+ }
78
+
79
+ async function commit(): Promise<CellCommitOutcome> {
80
+ if (disposed) return "disposed";
81
+ if (clearing) return "superseded";
82
+ const candidate = snapshot.draft;
83
+ if (!snapshot.editing || !candidate) return "inactive";
84
+ const candidateRevision = draftRevision;
85
+ if (snapshot.pending && pendingRevision === candidateRevision) return "busy";
86
+ const token = ++sequence;
87
+ const previousController = controller;
88
+ controller = undefined;
89
+ previousController?.abort();
90
+ if (disposed) return "disposed";
91
+ if (token !== sequence) return "superseded";
92
+ let validation: string | null;
93
+ try { validation = options.validate?.(candidate.value) ?? null; }
94
+ catch (error) {
95
+ retryRevision = null;
96
+ pendingRevision = null;
97
+ publish({ ...snapshot, pending: false, error, attempt: null });
98
+ return "failed";
99
+ }
100
+ if (validation !== null) {
101
+ if (typeof validation !== "string" || !validation.trim()) throw new Error("Cell validation messages must be nonempty strings");
102
+ retryRevision = null;
103
+ pendingRevision = null;
104
+ publish({ ...snapshot, pending: false, invalid: validation, error: null, attempt: null });
105
+ return "invalid";
106
+ }
107
+ const commitId = ++nextCommitId;
108
+ const captured = attempt(commitId, candidate.value, snapshot.committed);
109
+ const current = new AbortController();
110
+ controller = current;
111
+ retryRevision = null;
112
+ pendingRevision = candidateRevision;
113
+ publish({ ...snapshot, pending: true, invalid: null, error: null, attempt: captured, conflict: null });
114
+ try {
115
+ const result = await onCellCommit(captured, current.signal);
116
+ if (disposed) return "disposed";
117
+ if (token !== sequence) return "superseded";
118
+ assertValue(result.kind === "accepted" ? result.value : result.current);
119
+ if (result.kind === "conflict") {
120
+ pendingRevision = null;
121
+ retryRevision = candidateRevision;
122
+ publish({ ...snapshot, committed: result.current, pending: false, stale: true, error: null, conflict: Object.freeze({ commitId, attempted: candidate.value, current: result.current, detail: result.detail }) });
123
+ return "conflict";
124
+ }
125
+ const changed = draftRevision !== candidateRevision;
126
+ retryRevision = null;
127
+ pendingRevision = null;
128
+ editBase = changed ? editBase : null;
129
+ publish({ ...snapshot, committed: result.value, draft: changed ? snapshot.draft : null, editing: changed, pending: false, invalid: null, stale: changed, error: null, attempt: null, conflict: null });
130
+ return "accepted";
131
+ } catch (error) {
132
+ if (disposed) return "disposed";
133
+ if (token !== sequence) return "superseded";
134
+ retryRevision = candidateRevision;
135
+ pendingRevision = null;
136
+ publish({ ...snapshot, pending: false, error });
137
+ return "failed";
138
+ } finally {
139
+ if (token === sequence) controller = undefined;
140
+ }
141
+ }
142
+
143
+ function retry(): Promise<CellCommitOutcome> {
144
+ if (disposed) return Promise.resolve("disposed");
145
+ if (retryRevision === null || !snapshot.attempt) return Promise.resolve("inactive");
146
+ if (retryRevision !== draftRevision) return Promise.resolve("changed");
147
+ return commit();
148
+ }
149
+
150
+ function acceptRefetch(value: Value): boolean {
151
+ assertValue(value);
152
+ if (disposed || clearing) return false;
153
+ if (!snapshot.editing) {
154
+ editBase = null;
155
+ publish({ ...snapshot, committed: value, stale: false });
156
+ return true;
157
+ }
158
+ const stale = editBase !== null && !equals(editBase.value, value);
159
+ publish({ ...snapshot, committed: value, stale: snapshot.stale || stale });
160
+ return true;
161
+ }
162
+
163
+ function discard(): void {
164
+ if (clearing) return;
165
+ clearing = true;
166
+ sequence++;
167
+ const previousController = controller;
168
+ controller = undefined;
169
+ retryRevision = null;
170
+ pendingRevision = null;
171
+ editBase = null;
172
+ publish({ ...snapshot, draft: null, editing: false, pending: false, invalid: null, stale: false, error: null, attempt: null, conflict: null });
173
+ try { previousController?.abort(); }
174
+ finally { clearing = false; }
175
+ }
176
+
177
+ return {
178
+ getSnapshot: (): CellEditSnapshot<Value, Conflict> => snapshot,
179
+ begin,
180
+ setDraft,
181
+ commit,
182
+ retry,
183
+ acceptRefetch,
184
+ discard,
185
+ dispose(): void { disposed = true; discard(); },
186
+ };
187
+ }
@@ -0,0 +1,52 @@
1
+ import type { ClientViewState } from "./client-view.ts";
2
+ import { parseFilter } from "./filter.ts";
3
+ import type { FilterColumn, FilterNode } from "./filter.ts";
4
+ import { parsePagination, resetPagination, resizePagination } from "./pagination.ts";
5
+ import type { TablePagination } from "./pagination.ts";
6
+ import { parseSorting } from "./sorting.ts";
7
+ import type { SortColumn, SortState } from "./sorting.ts";
8
+
9
+ export interface ClientStateSchema {
10
+ readonly filterColumns: readonly FilterColumn[];
11
+ readonly sortColumns: readonly SortColumn[];
12
+ }
13
+ export type ClientStateChange =
14
+ | { readonly kind: "search"; readonly value: string }
15
+ | { readonly kind: "filter"; readonly value: FilterNode }
16
+ | { readonly kind: "sorting"; readonly value: SortState }
17
+ | { readonly kind: "pagination"; readonly value: TablePagination }
18
+ | { readonly kind: "pageSize"; readonly value: number };
19
+
20
+ /** Query-state fragment only; column layout, selection, and saved-view envelopes are separate. */
21
+ export function parseClientViewState(value: unknown, schema: ClientStateSchema): ClientViewState {
22
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid client state: expected an object");
23
+ if (Object.keys(value).some(key => !["search", "filter", "sorting", "pagination"].includes(key))) throw new Error("Invalid client state: unknown field");
24
+ if (!("search" in value) || typeof value.search !== "string") throw new Error("Invalid client state: search must be a string");
25
+ if (!("filter" in value) || !("sorting" in value) || !("pagination" in value)) throw new Error("Invalid client state: missing query field");
26
+ return Object.freeze({
27
+ search: value.search,
28
+ filter: parseFilter(value.filter, schema.filterColumns),
29
+ sorting: parseSorting(value.sorting, schema.sortColumns),
30
+ pagination: parsePagination(value.pagination),
31
+ });
32
+ }
33
+
34
+ /** Changes requested state only. Accepted rows/state remain owned by the result controller. */
35
+ export function changeClientViewState(state: ClientViewState, change: ClientStateChange, schema: ClientStateSchema): ClientViewState {
36
+ const current = parseClientViewState(state, schema);
37
+ switch (change.kind) {
38
+ case "search": return parseClientViewState({ ...current, search: change.value, pagination: resetPagination(current.pagination) }, schema);
39
+ case "filter": return parseClientViewState({ ...current, filter: change.value, pagination: resetPagination(current.pagination) }, schema);
40
+ case "sorting": return parseClientViewState({ ...current, sorting: change.value, pagination: resetPagination(current.pagination) }, schema);
41
+ case "pagination": {
42
+ const pagination = parsePagination(change.value);
43
+ const resized = pagination !== false && current.pagination !== false && pagination.pageSize !== current.pagination.pageSize;
44
+ return parseClientViewState({ ...current, pagination: resized ? resetPagination(pagination) : pagination }, schema);
45
+ }
46
+ case "pageSize": {
47
+ if (current.pagination === false) throw new Error("Page-size changes require pagination to be enabled");
48
+ return parseClientViewState({ ...current, pagination: resizePagination(current.pagination, change.value) }, schema);
49
+ }
50
+ default: throw new Error("Unknown client state change");
51
+ }
52
+ }
@@ -0,0 +1,61 @@
1
+ import { countClientFacets } from "./facets.ts";
2
+ import type { ColumnFacet } from "./facets.ts";
3
+ import { filterClientRows } from "./filter-client.ts";
4
+ import type { FilterColumn, FilterNode } from "./filter.ts";
5
+ import { paginateClientRows, parsePagination } from "./pagination.ts";
6
+ import type { TablePagination } from "./pagination.ts";
7
+ import { searchClientRowValues } from "./search.ts";
8
+ import { sortClientRows } from "./sorting.ts";
9
+ import { removeFilterColumnConditions } from "./filter-bar-state.ts";
10
+ import type { SortColumn, SortState } from "./sorting.ts";
11
+
12
+ export interface ClientViewState {
13
+ readonly search: string;
14
+ readonly filter: FilterNode;
15
+ readonly sorting: SortState;
16
+ readonly pagination: TablePagination;
17
+ }
18
+ export interface ClientViewOptions<Row> {
19
+ readonly locale: string;
20
+ readonly searchColumns: readonly string[];
21
+ /** Enables the leading-apostrophe exact-match syntax for global search. */
22
+ readonly exactMatch?: boolean;
23
+ readonly filterColumns: readonly FilterColumn[];
24
+ readonly sortColumns: readonly SortColumn[];
25
+ readonly getValue: (row: Row, column: string) => unknown;
26
+ /** Optional search-only projection. Filters and sorting continue to use getValue. */
27
+ readonly getSearchValue?: (row: Row, column: string) => unknown;
28
+ }
29
+ export interface ClientView<Row> {
30
+ /** Complete transformed view for export and continuous rendering, never just a page. */
31
+ readonly view: readonly Row[];
32
+ readonly rows: readonly Row[];
33
+ readonly total: number;
34
+ readonly pagination: TablePagination;
35
+ readonly facets: readonly ColumnFacet[];
36
+ }
37
+
38
+ /** Search -> filter -> facets -> explicit sort -> page. No network, cache, or state mutation. */
39
+ export function createClientView<Row>(rows: readonly Row[], state: ClientViewState, options: ClientViewOptions<Row>): ClientView<Row> {
40
+ const pagination = parsePagination(state.pagination);
41
+ const searched = searchClientRowValues(rows, state.search, {
42
+ locale: options.locale,
43
+ columns: options.searchColumns,
44
+ getValue: options.getSearchValue ?? options.getValue,
45
+ exactMatch: options.exactMatch ?? false,
46
+ });
47
+ const filtered = filterClientRows(searched, state.filter, options.filterColumns, options);
48
+ const facetGroups = new Map<FilterNode, FilterColumn[]>();
49
+ for (const column of options.filterColumns) {
50
+ if (column.type !== "enum") continue;
51
+ const filter = removeFilterColumnConditions(state.filter, column.id);
52
+ const columns = facetGroups.get(filter);
53
+ if (columns) columns.push(column);
54
+ else facetGroups.set(filter, [column]);
55
+ }
56
+ const facets = Object.freeze([...facetGroups].flatMap(([filter, columns]) =>
57
+ countClientFacets(filterClientRows(searched, filter, options.filterColumns, options), columns, options)));
58
+ const view = sortClientRows(filtered, state.sorting, options.sortColumns, options);
59
+ const page = paginateClientRows(view, pagination);
60
+ return { view, rows: page.rows, total: page.total, pagination: page.pagination, facets };
61
+ }
@@ -0,0 +1,47 @@
1
+ import type { ColumnState } from "./table-state.ts";
2
+
3
+ export type ColumnMoveDirection = "toward-start" | "toward-end";
4
+ export type ColumnDropPlacement = "before" | "after";
5
+
6
+ /** Resolve logical pin regions while retaining the user's order inside each region. */
7
+ export function orderColumnStates(columns: readonly ColumnState[]): readonly ColumnState[] {
8
+ return [
9
+ ...columns.filter(column => column.pin === "start"),
10
+ ...columns.filter(column => column.pin === false),
11
+ ...columns.filter(column => column.pin === "end"),
12
+ ];
13
+ }
14
+
15
+ /** Reorder one column relative to another without allowing a drag to change pin regions. */
16
+ export function placeColumn(columns: readonly ColumnState[], sourceId: string, targetId: string, placement: ColumnDropPlacement): readonly ColumnState[] {
17
+ if (sourceId === targetId) return columns;
18
+ const source = columns.find(column => column.id === sourceId);
19
+ const target = columns.find(column => column.id === targetId);
20
+ if (!source || !target) throw new Error("Cannot reorder an unknown table column");
21
+ if (source.pin !== target.pin) throw new Error("Cannot reorder columns across pin regions");
22
+ const reordered = columns.filter(column => column.id !== sourceId);
23
+ const targetIndex = reordered.findIndex(column => column.id === targetId);
24
+ reordered.splice(targetIndex + (placement === "after" ? 1 : 0), 0, source);
25
+ return reordered;
26
+ }
27
+
28
+ /** Keyboard/menu equivalent for a one-position logical drag. */
29
+ export function moveColumn(columns: readonly ColumnState[], id: string, direction: ColumnMoveDirection): readonly ColumnState[] {
30
+ const ordered = orderColumnStates(columns);
31
+ const index = ordered.findIndex(column => column.id === id);
32
+ if (index < 0) throw new Error(`Cannot move unknown table column: ${id}`);
33
+ const source = ordered[index];
34
+ if (!source) throw new Error(`Cannot move unknown table column: ${id}`);
35
+ const step = direction === "toward-start" ? -1 : 1;
36
+ let candidate = index + step;
37
+ while (candidate >= 0 && candidate < ordered.length) {
38
+ const target = ordered[candidate];
39
+ if (target?.pin === source.pin) return placeColumn(columns, id, target.id, direction === "toward-start" ? "before" : "after");
40
+ candidate += step;
41
+ }
42
+ return columns;
43
+ }
44
+
45
+ export function canMoveColumn(columns: readonly ColumnState[], id: string, direction: ColumnMoveDirection): boolean {
46
+ return moveColumn(columns, id, direction) !== columns;
47
+ }