@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.
- package/LICENSE +19 -0
- package/README.md +19 -0
- package/dist/DataTable.d.ts +159 -0
- package/dist/DataTable.js +2724 -0
- package/dist/DataTableToolbar.d.ts +28 -0
- package/dist/DataTableToolbar.js +132 -0
- package/dist/FilterBar.d.ts +24 -0
- package/dist/FilterBar.js +681 -0
- package/dist/QueryBuilder.d.ts +11 -0
- package/dist/QueryBuilder.js +693 -0
- package/dist/cell-edit.d.ts +50 -0
- package/dist/cell-edit.js +178 -0
- package/dist/client-state.d.ts +28 -0
- package/dist/client-state.js +57 -0
- package/dist/client-view.d.ts +31 -0
- package/dist/client-view.js +30 -0
- package/dist/column-layout.d.ts +10 -0
- package/dist/column-layout.js +34 -0
- package/dist/columns.d.ts +108 -0
- package/dist/columns.js +217 -0
- package/dist/core.d.ts +54 -0
- package/dist/core.js +28 -0
- package/dist/export.d.ts +14 -0
- package/dist/export.js +27 -0
- package/dist/facets.d.ts +15 -0
- package/dist/facets.js +41 -0
- package/dist/filter-bar-state.d.ts +22 -0
- package/dist/filter-bar-state.js +128 -0
- package/dist/filter-client.d.ts +9 -0
- package/dist/filter-client.js +69 -0
- package/dist/filter.d.ts +64 -0
- package/dist/filter.js +132 -0
- package/dist/grouping.d.ts +37 -0
- package/dist/grouping.js +126 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +31 -0
- package/dist/messages.d.ts +115 -0
- package/dist/messages.js +121 -0
- package/dist/pagination.d.ts +36 -0
- package/dist/pagination.js +102 -0
- package/dist/query-builder-state.d.ts +28 -0
- package/dist/query-builder-state.js +128 -0
- package/dist/requests.d.ts +26 -0
- package/dist/requests.js +106 -0
- package/dist/row-hierarchy.d.ts +32 -0
- package/dist/row-hierarchy.js +170 -0
- package/dist/row-identity.d.ts +11 -0
- package/dist/row-identity.js +36 -0
- package/dist/saved-views.d.ts +52 -0
- package/dist/saved-views.js +153 -0
- package/dist/search-controller.d.ts +22 -0
- package/dist/search-controller.js +75 -0
- package/dist/search.d.ts +28 -0
- package/dist/search.js +111 -0
- package/dist/selection-client.d.ts +9 -0
- package/dist/selection-client.js +14 -0
- package/dist/selection.d.ts +25 -0
- package/dist/selection.js +60 -0
- package/dist/server-export.d.ts +27 -0
- package/dist/server-export.js +105 -0
- package/dist/sorting.d.ts +17 -0
- package/dist/sorting.js +58 -0
- package/dist/table-state-changes.d.ts +27 -0
- package/dist/table-state-changes.js +67 -0
- package/dist/table-state.d.ts +20 -0
- package/dist/table-state.js +77 -0
- package/dist/text-normalization.d.ts +2 -0
- package/dist/text-normalization.js +12 -0
- package/dist/url-state.d.ts +39 -0
- package/dist/url-state.js +75 -0
- package/package.json +66 -0
- package/src/DataTable.tsx +2322 -0
- package/src/DataTableToolbar.tsx +69 -0
- package/src/FilterBar.tsx +396 -0
- package/src/QueryBuilder.tsx +274 -0
- package/src/cell-edit.ts +187 -0
- package/src/client-state.ts +52 -0
- package/src/client-view.ts +61 -0
- package/src/column-layout.ts +47 -0
- package/src/columns.ts +271 -0
- package/src/core.ts +54 -0
- package/src/export.ts +39 -0
- package/src/facets.ts +46 -0
- package/src/filter-bar-state.ts +118 -0
- package/src/filter-client.ts +79 -0
- package/src/filter.ts +113 -0
- package/src/grouping.ts +185 -0
- package/src/index.ts +7 -0
- package/src/messages.ts +29 -0
- package/src/pagination.ts +81 -0
- package/src/query-builder-state.ts +105 -0
- package/src/requests.ts +85 -0
- package/src/row-hierarchy.ts +280 -0
- package/src/row-identity.ts +39 -0
- package/src/saved-views.ts +143 -0
- package/src/search-controller.ts +61 -0
- package/src/search.ts +137 -0
- package/src/selection-client.ts +23 -0
- package/src/selection.ts +62 -0
- package/src/server-export.ts +89 -0
- package/src/sorting.ts +63 -0
- package/src/styles.css +197 -0
- package/src/table-state-changes.ts +51 -0
- package/src/table-state.ts +72 -0
- package/src/text-normalization.ts +14 -0
- package/src/url-state.ts +62 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
export type HierarchyLoadOutcome = "changed" | "loaded" | "failed" | "superseded" | "busy" | "unchanged" | "disposed";
|
|
2
|
+
|
|
3
|
+
export interface RowHierarchyOptions<Row extends object> {
|
|
4
|
+
readonly getRowId: (row: Row) => string;
|
|
5
|
+
/** Return known children synchronously. Undefined means children are not loaded. */
|
|
6
|
+
readonly getChildren?: (row: Row) => readonly Row[] | undefined;
|
|
7
|
+
/** Marks an unloaded row as a parent. Defaults true for every unloaded row when loadChildren exists. */
|
|
8
|
+
readonly canLoadChildren?: (row: Row) => boolean;
|
|
9
|
+
readonly loadChildren?: (row: Row, signal: AbortSignal) => Promise<readonly Row[]>;
|
|
10
|
+
readonly defaultExpanded?: boolean | readonly string[] | ((row: Row) => boolean);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface HierarchyRow<Row extends object> {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly row: Row;
|
|
16
|
+
readonly parentId: string | null;
|
|
17
|
+
readonly depth: number;
|
|
18
|
+
readonly position: number;
|
|
19
|
+
readonly setSize: number;
|
|
20
|
+
readonly canExpand: boolean;
|
|
21
|
+
readonly expanded: boolean;
|
|
22
|
+
readonly unloaded: boolean;
|
|
23
|
+
readonly pending: boolean;
|
|
24
|
+
readonly error: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface NodeDescriptor<Row extends object> {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly row: Row;
|
|
30
|
+
readonly parentId: string | null;
|
|
31
|
+
readonly depth: number;
|
|
32
|
+
readonly position: number;
|
|
33
|
+
readonly setSize: number;
|
|
34
|
+
readonly children: readonly string[] | undefined;
|
|
35
|
+
readonly loadable: boolean;
|
|
36
|
+
readonly staticChildren: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface NodeState<Row extends object> extends NodeDescriptor<Row> {
|
|
40
|
+
expanded: boolean;
|
|
41
|
+
pending: boolean;
|
|
42
|
+
error: unknown;
|
|
43
|
+
token: number;
|
|
44
|
+
controller: AbortController | undefined;
|
|
45
|
+
loaded: readonly Row[] | undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface BuiltHierarchy<Row extends object> {
|
|
49
|
+
readonly roots: readonly Row[];
|
|
50
|
+
readonly rootIds: readonly string[];
|
|
51
|
+
readonly descriptors: ReadonlyMap<string, NodeDescriptor<Row>>;
|
|
52
|
+
readonly objectIds: readonly { readonly row: Row; readonly id: string }[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function validatedRows<Row extends object>(value: readonly Row[], label: string): readonly Row[] {
|
|
56
|
+
if (!Array.isArray(value)) throw new Error(`${label} must be an array`);
|
|
57
|
+
const rows: Row[] = [];
|
|
58
|
+
for (let index = 0; index < value.length; index++) {
|
|
59
|
+
if (!Object.hasOwn(value, index) || typeof value[index] !== "object" || value[index] === null) throw new Error(`${label}[${index}] must be an object`);
|
|
60
|
+
rows.push(value[index]!);
|
|
61
|
+
}
|
|
62
|
+
return Object.freeze(rows);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Owns expansion and independent child-load lifecycles without mutating application rows. */
|
|
66
|
+
export function createRowHierarchy<Row extends object>(options: RowHierarchyOptions<Row>) {
|
|
67
|
+
if (typeof options.getRowId !== "function") throw new Error("Row hierarchy requires getRowId");
|
|
68
|
+
if (options.getChildren !== undefined && typeof options.getChildren !== "function") throw new Error("getChildren must be a function");
|
|
69
|
+
if (options.canLoadChildren !== undefined && typeof options.canLoadChildren !== "function") throw new Error("canLoadChildren must be a function");
|
|
70
|
+
if (options.loadChildren !== undefined && typeof options.loadChildren !== "function") throw new Error("loadChildren must be a function");
|
|
71
|
+
const defaultValue = options.defaultExpanded;
|
|
72
|
+
const defaultList = typeof defaultValue === "object" ? defaultValue : undefined;
|
|
73
|
+
const defaultIds = defaultList ? new Set<string>() : undefined;
|
|
74
|
+
if (defaultList && defaultIds) {
|
|
75
|
+
for (const id of defaultList) {
|
|
76
|
+
if (typeof id !== "string" || !id.trim() || defaultIds.has(id)) throw new Error("defaultExpanded IDs must be unique nonempty strings");
|
|
77
|
+
defaultIds.add(id);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
let roots: readonly Row[] = Object.freeze([]);
|
|
81
|
+
let rootIds: readonly string[] = Object.freeze([]);
|
|
82
|
+
const states = new Map<string, NodeState<Row>>();
|
|
83
|
+
const objectIds = new WeakMap<object, string>();
|
|
84
|
+
let disposed = false;
|
|
85
|
+
|
|
86
|
+
function isDefaultExpanded(row: Row, id: string): boolean {
|
|
87
|
+
if (defaultIds) return defaultIds.has(id);
|
|
88
|
+
if (typeof options.defaultExpanded === "function") return options.defaultExpanded(row);
|
|
89
|
+
return options.defaultExpanded === true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function build(nextRoots: readonly Row[], loadedOverride?: ReadonlyMap<string, readonly Row[]>): BuiltHierarchy<Row> {
|
|
93
|
+
const acceptedRoots = validatedRows(nextRoots, "Hierarchy roots");
|
|
94
|
+
const descriptors = new Map<string, NodeDescriptor<Row>>();
|
|
95
|
+
const seen = new Set<string>();
|
|
96
|
+
const nextObjectIds: { readonly row: Row; readonly id: string }[] = [];
|
|
97
|
+
const ancestors = new Set<Row>();
|
|
98
|
+
function visit(rows: readonly Row[], parentId: string | null, depth: number): readonly string[] {
|
|
99
|
+
const ids: string[] = [];
|
|
100
|
+
for (let index = 0; index < rows.length; index++) {
|
|
101
|
+
const row = rows[index]!;
|
|
102
|
+
if (ancestors.has(row)) throw new Error("Row hierarchy contains an object cycle");
|
|
103
|
+
const id = options.getRowId(row);
|
|
104
|
+
if (typeof id !== "string" || !id.trim() || id.trim() !== id) throw new Error(`Hierarchy row at depth ${depth} position ${index + 1} has an invalid ID`);
|
|
105
|
+
if (seen.has(id)) throw new Error(`Duplicate hierarchy row ID: ${id}`);
|
|
106
|
+
seen.add(id);
|
|
107
|
+
const remembered = objectIds.get(row);
|
|
108
|
+
if (remembered !== undefined && remembered !== id) throw new Error(`Hierarchy row identity changed from ${remembered} to ${id}`);
|
|
109
|
+
nextObjectIds.push({ row, id });
|
|
110
|
+
ancestors.add(row);
|
|
111
|
+
const staticValue = options.getChildren?.(row);
|
|
112
|
+
const hasStaticChildren = staticValue !== undefined;
|
|
113
|
+
const childRows = hasStaticChildren
|
|
114
|
+
? validatedRows(staticValue, `Children of ${id}`)
|
|
115
|
+
: loadedOverride?.get(id) ?? states.get(id)?.loaded;
|
|
116
|
+
const acceptedChildren = childRows === undefined ? undefined : validatedRows(childRows, `Children of ${id}`);
|
|
117
|
+
const childIds = acceptedChildren === undefined ? undefined : visit(acceptedChildren, id, depth + 1);
|
|
118
|
+
ancestors.delete(row);
|
|
119
|
+
const loadable = !hasStaticChildren && childIds === undefined && Boolean(options.loadChildren && (options.canLoadChildren?.(row) ?? true));
|
|
120
|
+
descriptors.set(id, Object.freeze({ id, row, parentId, depth, position: index + 1, setSize: rows.length, children: childIds, loadable, staticChildren: hasStaticChildren }));
|
|
121
|
+
ids.push(id);
|
|
122
|
+
}
|
|
123
|
+
return Object.freeze(ids);
|
|
124
|
+
}
|
|
125
|
+
const nextRootIds = visit(acceptedRoots, null, 1);
|
|
126
|
+
return { roots: acceptedRoots, rootIds: nextRootIds, descriptors, objectIds: Object.freeze(nextObjectIds) };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function apply(built: BuiltHierarchy<Row>, loadedOverride?: ReadonlyMap<string, readonly Row[]>): void {
|
|
130
|
+
const retained = new Set(built.descriptors.keys());
|
|
131
|
+
for (const [id, state] of states) {
|
|
132
|
+
if (retained.has(id)) continue;
|
|
133
|
+
state.token++;
|
|
134
|
+
state.controller?.abort();
|
|
135
|
+
states.delete(id);
|
|
136
|
+
}
|
|
137
|
+
for (const descriptor of built.descriptors.values()) {
|
|
138
|
+
const existing = states.get(descriptor.id);
|
|
139
|
+
if (existing) {
|
|
140
|
+
Object.assign(existing, descriptor);
|
|
141
|
+
if (descriptor.staticChildren) existing.loaded = undefined;
|
|
142
|
+
else if (loadedOverride?.has(descriptor.id)) existing.loaded = loadedOverride.get(descriptor.id);
|
|
143
|
+
} else {
|
|
144
|
+
states.set(descriptor.id, {
|
|
145
|
+
...descriptor,
|
|
146
|
+
expanded: isDefaultExpanded(descriptor.row, descriptor.id),
|
|
147
|
+
pending: false,
|
|
148
|
+
error: null,
|
|
149
|
+
token: 0,
|
|
150
|
+
controller: undefined,
|
|
151
|
+
loaded: loadedOverride?.get(descriptor.id),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const entry of built.objectIds) objectIds.set(entry.row, entry.id);
|
|
156
|
+
roots = built.roots;
|
|
157
|
+
rootIds = built.rootIds;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function updateRoots(nextRoots: readonly Row[]): void {
|
|
161
|
+
if (disposed) return;
|
|
162
|
+
apply(build(nextRoots));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function snapshot(): readonly HierarchyRow<Row>[] {
|
|
166
|
+
const visible: HierarchyRow<Row>[] = [];
|
|
167
|
+
function append(ids: readonly string[]): void {
|
|
168
|
+
for (const id of ids) {
|
|
169
|
+
const state = states.get(id);
|
|
170
|
+
if (!state) continue;
|
|
171
|
+
const canExpand = Boolean(state.children?.length) || state.loadable || state.pending || state.error !== null;
|
|
172
|
+
visible.push(Object.freeze({
|
|
173
|
+
id: state.id,
|
|
174
|
+
row: state.row,
|
|
175
|
+
parentId: state.parentId,
|
|
176
|
+
depth: state.depth,
|
|
177
|
+
position: state.position,
|
|
178
|
+
setSize: state.setSize,
|
|
179
|
+
canExpand,
|
|
180
|
+
expanded: canExpand && state.expanded,
|
|
181
|
+
unloaded: state.children === undefined && state.loadable,
|
|
182
|
+
pending: state.pending,
|
|
183
|
+
error: state.error,
|
|
184
|
+
}));
|
|
185
|
+
if (state.expanded && state.children) append(state.children);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
append(rootIds);
|
|
189
|
+
return Object.freeze(visible);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function load(id: string): Promise<HierarchyLoadOutcome> {
|
|
193
|
+
if (disposed) return "disposed";
|
|
194
|
+
const state = states.get(id);
|
|
195
|
+
const adapter = options.loadChildren;
|
|
196
|
+
if (!state || !state.loadable || !adapter) return "unchanged";
|
|
197
|
+
if (state.pending) return "busy";
|
|
198
|
+
const token = ++state.token;
|
|
199
|
+
const controller = new AbortController();
|
|
200
|
+
state.controller = controller;
|
|
201
|
+
state.pending = true;
|
|
202
|
+
state.error = null;
|
|
203
|
+
const row = state.row;
|
|
204
|
+
try {
|
|
205
|
+
const children = validatedRows(await adapter(row, controller.signal), `Loaded children of ${id}`);
|
|
206
|
+
if (disposed) return "disposed";
|
|
207
|
+
const current = states.get(id);
|
|
208
|
+
if (!current || current.token !== token) return "superseded";
|
|
209
|
+
const overrides = new Map<string, readonly Row[]>([[id, children]]);
|
|
210
|
+
const built = build(roots, overrides);
|
|
211
|
+
current.loaded = children;
|
|
212
|
+
apply(built, overrides);
|
|
213
|
+
const accepted = states.get(id);
|
|
214
|
+
if (accepted) {
|
|
215
|
+
accepted.pending = false;
|
|
216
|
+
accepted.error = null;
|
|
217
|
+
accepted.controller = undefined;
|
|
218
|
+
}
|
|
219
|
+
return "loaded";
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (disposed) return "disposed";
|
|
222
|
+
const current = states.get(id);
|
|
223
|
+
if (!current || current.token !== token) return "superseded";
|
|
224
|
+
current.pending = false;
|
|
225
|
+
current.error = error;
|
|
226
|
+
current.controller = undefined;
|
|
227
|
+
return "failed";
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function setExpanded(id: string, expanded: boolean): Promise<HierarchyLoadOutcome> {
|
|
232
|
+
if (disposed) return Promise.resolve("disposed");
|
|
233
|
+
const state = states.get(id);
|
|
234
|
+
if (!state) return Promise.resolve("unchanged");
|
|
235
|
+
const canExpand = Boolean(state.children?.length) || state.loadable || state.pending || state.error !== null;
|
|
236
|
+
if (!canExpand) return Promise.resolve("unchanged");
|
|
237
|
+
if (!expanded) {
|
|
238
|
+
if (!state.expanded && !state.pending) return Promise.resolve("unchanged");
|
|
239
|
+
state.expanded = false;
|
|
240
|
+
if (state.pending) {
|
|
241
|
+
state.token++;
|
|
242
|
+
state.pending = false;
|
|
243
|
+
const controller = state.controller;
|
|
244
|
+
state.controller = undefined;
|
|
245
|
+
controller?.abort();
|
|
246
|
+
}
|
|
247
|
+
return Promise.resolve("changed");
|
|
248
|
+
}
|
|
249
|
+
state.expanded = true;
|
|
250
|
+
if (state.children !== undefined) return Promise.resolve("changed");
|
|
251
|
+
return load(id);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function retry(id: string): Promise<HierarchyLoadOutcome> {
|
|
255
|
+
if (disposed) return Promise.resolve("disposed");
|
|
256
|
+
const state = states.get(id);
|
|
257
|
+
if (!state || state.error === null) return Promise.resolve("unchanged");
|
|
258
|
+
state.expanded = true;
|
|
259
|
+
return load(id);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function reset(): void {
|
|
263
|
+
for (const state of states.values()) {
|
|
264
|
+
state.token++;
|
|
265
|
+
state.controller?.abort();
|
|
266
|
+
}
|
|
267
|
+
states.clear();
|
|
268
|
+
roots = Object.freeze([]);
|
|
269
|
+
rootIds = Object.freeze([]);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
updateRoots,
|
|
274
|
+
getSnapshot: snapshot,
|
|
275
|
+
setExpanded,
|
|
276
|
+
retry,
|
|
277
|
+
reset,
|
|
278
|
+
dispose(): void { disposed = true; reset(); },
|
|
279
|
+
};
|
|
280
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export interface IdentifiedRow<Row extends object> {
|
|
2
|
+
readonly id: string;
|
|
3
|
+
readonly row: Row;
|
|
4
|
+
readonly index: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** Validate IDs once per resolution and detect changes for reused row objects. */
|
|
8
|
+
export function createRowIdentity<Row extends object>(getRowId: (row: Row) => string) {
|
|
9
|
+
if (typeof getRowId !== "function") throw new Error("getRowId must be a function");
|
|
10
|
+
let known = new WeakMap<Row, string>();
|
|
11
|
+
function resolveIds(rows: readonly Row[]): readonly string[] {
|
|
12
|
+
if (!Array.isArray(rows)) throw new Error("Table rows must be an array");
|
|
13
|
+
const ids = new Set<string>();
|
|
14
|
+
const result: string[] = [];
|
|
15
|
+
let index = 0;
|
|
16
|
+
for (const row of rows) {
|
|
17
|
+
if (typeof row !== "object" || row === null) throw new Error(`rows[${index}] must be an object`);
|
|
18
|
+
const id = getRowId(row);
|
|
19
|
+
if (typeof id !== "string" || !id || id.trim() !== id) throw new Error(`rows[${index}] has an invalid stable ID`);
|
|
20
|
+
if (ids.has(id)) throw new Error(`rows[${index}] duplicates row ID ${id}`);
|
|
21
|
+
const prior = known.get(row);
|
|
22
|
+
if (prior !== undefined && prior !== id) throw new Error(`rows[${index}] changed stable ID from ${prior} to ${id}`);
|
|
23
|
+
ids.add(id);
|
|
24
|
+
known.set(row, id);
|
|
25
|
+
result.push(id);
|
|
26
|
+
index++;
|
|
27
|
+
}
|
|
28
|
+
return Object.freeze(result);
|
|
29
|
+
}
|
|
30
|
+
function resolve(rows: readonly Row[]): readonly IdentifiedRow<Row>[] {
|
|
31
|
+
const ids = resolveIds(rows);
|
|
32
|
+
return Object.freeze(rows.map((row, index) => Object.freeze({ id: ids[index]!, row, index })));
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
resolve,
|
|
36
|
+
resolveIds,
|
|
37
|
+
clear(): void { known = new WeakMap<Row, string>(); },
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { deserializeState, serializeState } from "./table-state.ts";
|
|
2
|
+
import type { TableState, TableStateSchema } from "./table-state.ts";
|
|
3
|
+
|
|
4
|
+
export interface SavedViewRecord { readonly id: string; readonly name: string; readonly state: string }
|
|
5
|
+
export interface SavedViewSave { readonly id: string | null; readonly name: string; readonly state: string }
|
|
6
|
+
export interface SavedViewsAdapter {
|
|
7
|
+
readonly list: (signal: AbortSignal) => Promise<readonly SavedViewRecord[]>;
|
|
8
|
+
readonly save: (view: SavedViewSave, signal: AbortSignal) => Promise<SavedViewRecord>;
|
|
9
|
+
readonly delete: (id: string, signal: AbortSignal) => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export type SavedViewOperation =
|
|
12
|
+
| { readonly kind: "list" }
|
|
13
|
+
| { readonly kind: "save"; readonly view: SavedViewSave }
|
|
14
|
+
| { readonly kind: "delete"; readonly id: string };
|
|
15
|
+
export interface SavedViewsSnapshot {
|
|
16
|
+
readonly accepted: readonly SavedViewRecord[] | null;
|
|
17
|
+
readonly pending: SavedViewOperation | null;
|
|
18
|
+
readonly failed: SavedViewOperation | null;
|
|
19
|
+
readonly error: unknown;
|
|
20
|
+
}
|
|
21
|
+
export type SavedViewOutcome = "accepted" | "failed" | "superseded" | "disposed";
|
|
22
|
+
export type SavedViewRestore =
|
|
23
|
+
| { readonly kind: "accepted"; readonly state: TableState }
|
|
24
|
+
| { readonly kind: "missing" }
|
|
25
|
+
| { readonly kind: "invalid"; readonly error: unknown };
|
|
26
|
+
|
|
27
|
+
function text(value: unknown, label: string): string {
|
|
28
|
+
if (typeof value !== "string" || !value || value.trim() !== value) throw new Error(`${label} must be a nonempty trimmed string`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
function record(value: SavedViewRecord, label: string): SavedViewRecord {
|
|
32
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
33
|
+
const keys = Object.keys(value);
|
|
34
|
+
if (keys.length !== 3 || !keys.includes("id") || !keys.includes("name") || !keys.includes("state")) throw new Error(`${label} must contain exactly id, name, and state`);
|
|
35
|
+
const id = text(value.id, `${label}.id`);
|
|
36
|
+
const name = text(value.name, `${label}.name`);
|
|
37
|
+
if (typeof value.state !== "string" || !value.state) throw new Error(`${label}.state must be a nonempty serialized string`);
|
|
38
|
+
return Object.freeze({ id, name, state: value.state });
|
|
39
|
+
}
|
|
40
|
+
function records(value: readonly SavedViewRecord[]): readonly SavedViewRecord[] {
|
|
41
|
+
if (!Array.isArray(value)) throw new Error("Saved view list must be an array");
|
|
42
|
+
const result: SavedViewRecord[] = [];
|
|
43
|
+
const ids = new Set<string>();
|
|
44
|
+
let index = 0;
|
|
45
|
+
for (const item of value) {
|
|
46
|
+
const next = record(item, `views[${index}]`);
|
|
47
|
+
if (ids.has(next.id)) throw new Error(`views[${index}] duplicates ID ${next.id}`);
|
|
48
|
+
ids.add(next.id);
|
|
49
|
+
result.push(next);
|
|
50
|
+
index++;
|
|
51
|
+
}
|
|
52
|
+
return Object.freeze(result);
|
|
53
|
+
}
|
|
54
|
+
function operation(value: SavedViewOperation): SavedViewOperation {
|
|
55
|
+
if (value.kind === "save") return Object.freeze({ kind: "save", view: Object.freeze({ ...value.view }) });
|
|
56
|
+
return Object.freeze({ ...value });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Async saved-view ownership. Persistence and authorization stay in the app adapter. */
|
|
60
|
+
export function createSavedViews(adapter: SavedViewsAdapter, schema: TableStateSchema) {
|
|
61
|
+
let snapshot: SavedViewsSnapshot = Object.freeze({ accepted: null, pending: null, failed: null, error: null });
|
|
62
|
+
let sequence = 0n;
|
|
63
|
+
let controller: AbortController | undefined;
|
|
64
|
+
let disposed = false;
|
|
65
|
+
let clearing = false;
|
|
66
|
+
async function run(source: SavedViewOperation): Promise<SavedViewOutcome> {
|
|
67
|
+
if (disposed) return "disposed";
|
|
68
|
+
if (clearing) return "superseded";
|
|
69
|
+
const requested = operation(source);
|
|
70
|
+
const token = ++sequence;
|
|
71
|
+
const prior = controller;
|
|
72
|
+
controller = undefined;
|
|
73
|
+
prior?.abort();
|
|
74
|
+
if (disposed) return "disposed";
|
|
75
|
+
if (token !== sequence) return "superseded";
|
|
76
|
+
const current = new AbortController();
|
|
77
|
+
controller = current;
|
|
78
|
+
snapshot = Object.freeze({ ...snapshot, pending: requested, failed: null, error: null });
|
|
79
|
+
try {
|
|
80
|
+
if (requested.kind === "list") {
|
|
81
|
+
const listed = records(await adapter.list(current.signal));
|
|
82
|
+
if (disposed) return "disposed";
|
|
83
|
+
if (token !== sequence) return "superseded";
|
|
84
|
+
snapshot = Object.freeze({ accepted: listed, pending: null, failed: null, error: null });
|
|
85
|
+
return "accepted";
|
|
86
|
+
}
|
|
87
|
+
if (requested.kind === "save") {
|
|
88
|
+
const saved = record(await adapter.save(requested.view, current.signal), "saved view");
|
|
89
|
+
if (disposed) return "disposed";
|
|
90
|
+
if (token !== sequence) return "superseded";
|
|
91
|
+
if (requested.view.id !== null && requested.view.id !== saved.id) throw new Error("Saved view adapter changed the requested ID");
|
|
92
|
+
deserializeState(saved.state, schema);
|
|
93
|
+
const existing = snapshot.accepted ?? [];
|
|
94
|
+
const index = existing.findIndex(view => view.id === saved.id);
|
|
95
|
+
const accepted = index < 0 ? [...existing, saved] : existing.map(view => view.id === saved.id ? saved : view);
|
|
96
|
+
snapshot = Object.freeze({ accepted: Object.freeze(accepted), pending: null, failed: null, error: null });
|
|
97
|
+
return "accepted";
|
|
98
|
+
}
|
|
99
|
+
await adapter.delete(requested.id, current.signal);
|
|
100
|
+
if (disposed) return "disposed";
|
|
101
|
+
if (token !== sequence) return "superseded";
|
|
102
|
+
snapshot = Object.freeze({ accepted: snapshot.accepted ? Object.freeze(snapshot.accepted.filter(view => view.id !== requested.id)) : null, pending: null, failed: null, error: null });
|
|
103
|
+
return "accepted";
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (disposed) return "disposed";
|
|
106
|
+
if (token !== sequence) return "superseded";
|
|
107
|
+
snapshot = Object.freeze({ ...snapshot, pending: null, failed: requested, error });
|
|
108
|
+
return "failed";
|
|
109
|
+
} finally { if (token === sequence) controller = undefined; }
|
|
110
|
+
}
|
|
111
|
+
function save(name: string, state: TableState, id: string | null = null): Promise<SavedViewOutcome> {
|
|
112
|
+
const view = Object.freeze({ id: id === null ? null : text(id, "Saved view ID"), name: text(name, "Saved view name"), state: serializeState(state, schema) });
|
|
113
|
+
return run({ kind: "save", view });
|
|
114
|
+
}
|
|
115
|
+
function restore(id: string): SavedViewRestore {
|
|
116
|
+
try {
|
|
117
|
+
const checked = text(id, "Saved view ID");
|
|
118
|
+
const view = snapshot.accepted?.find(candidate => candidate.id === checked);
|
|
119
|
+
if (!view) return Object.freeze({ kind: "missing" });
|
|
120
|
+
return Object.freeze({ kind: "accepted", state: deserializeState(view.state, schema) });
|
|
121
|
+
} catch (error) { return Object.freeze({ kind: "invalid", error }); }
|
|
122
|
+
}
|
|
123
|
+
function clear(): void {
|
|
124
|
+
if (clearing) return;
|
|
125
|
+
clearing = true;
|
|
126
|
+
sequence++;
|
|
127
|
+
const prior = controller;
|
|
128
|
+
controller = undefined;
|
|
129
|
+
snapshot = Object.freeze({ accepted: null, pending: null, failed: null, error: null });
|
|
130
|
+
try { prior?.abort(); }
|
|
131
|
+
finally { clearing = false; }
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
getSnapshot: (): SavedViewsSnapshot => snapshot,
|
|
135
|
+
list: (): Promise<SavedViewOutcome> => run({ kind: "list" }),
|
|
136
|
+
save,
|
|
137
|
+
delete: (id: string): Promise<SavedViewOutcome> => run({ kind: "delete", id: text(id, "Saved view ID") }),
|
|
138
|
+
restore,
|
|
139
|
+
retry: (): Promise<SavedViewOutcome> => snapshot.failed ? run(snapshot.failed) : Promise.resolve(disposed ? "disposed" : "failed"),
|
|
140
|
+
clear,
|
|
141
|
+
dispose(): void { disposed = true; clear(); },
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export interface SearchSnapshot<Result> {
|
|
2
|
+
readonly accepted: { readonly query: string; readonly result: Result } | null;
|
|
3
|
+
readonly requested: string | null;
|
|
4
|
+
readonly pending: boolean;
|
|
5
|
+
readonly error: unknown;
|
|
6
|
+
}
|
|
7
|
+
export type SearchOutcome = "accepted" | "failed" | "superseded" | "cleared" | "disposed";
|
|
8
|
+
export interface InitialSearchResult<Result> {
|
|
9
|
+
readonly query: string;
|
|
10
|
+
readonly result: Result;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Owns trailing scheduling, not a data cache. Evaluate against the current complete client dataset. */
|
|
14
|
+
export function createDebouncedSearch<Result>(evaluate: (query: string) => Result, delay = 120, initial?: InitialSearchResult<Result>) {
|
|
15
|
+
if (!Number.isSafeInteger(delay) || delay < 0 || delay > 2147483647) throw new Error("Search delay must be a nonnegative timer-safe integer");
|
|
16
|
+
if (initial && typeof initial.query !== "string") throw new Error("Initial search query must be a string");
|
|
17
|
+
let snapshot: SearchSnapshot<Result> = { accepted: initial ? { query: initial.query, result: initial.result } : null, requested: null, pending: false, error: null };
|
|
18
|
+
let sequence = 0n;
|
|
19
|
+
let disposed = false;
|
|
20
|
+
let task: { timer: ReturnType<typeof setTimeout>; finish: (outcome: SearchOutcome) => void } | undefined;
|
|
21
|
+
function cancel(outcome: SearchOutcome) {
|
|
22
|
+
sequence++;
|
|
23
|
+
const previous = task;
|
|
24
|
+
task = undefined;
|
|
25
|
+
if (previous) { clearTimeout(previous.timer); previous.finish(outcome); }
|
|
26
|
+
}
|
|
27
|
+
function request(query: string): Promise<SearchOutcome> {
|
|
28
|
+
if (disposed) return Promise.resolve("disposed");
|
|
29
|
+
cancel("superseded");
|
|
30
|
+
const token = sequence;
|
|
31
|
+
snapshot = { ...snapshot, requested: query, pending: true, error: null };
|
|
32
|
+
return new Promise(resolve => {
|
|
33
|
+
const timer = setTimeout(() => {
|
|
34
|
+
try {
|
|
35
|
+
const result = evaluate(query);
|
|
36
|
+
if (token !== sequence || disposed) return;
|
|
37
|
+
snapshot = { accepted: { query, result }, requested: null, pending: false, error: null };
|
|
38
|
+
task = undefined;
|
|
39
|
+
resolve("accepted");
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (token !== sequence || disposed) return;
|
|
42
|
+
snapshot = { ...snapshot, pending: false, error };
|
|
43
|
+
task = undefined;
|
|
44
|
+
resolve("failed");
|
|
45
|
+
}
|
|
46
|
+
}, delay);
|
|
47
|
+
task = { timer, finish: resolve };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function clear() {
|
|
51
|
+
cancel(disposed ? "disposed" : "cleared");
|
|
52
|
+
snapshot = { accepted: null, requested: null, pending: false, error: null };
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
getSnapshot: () => snapshot,
|
|
56
|
+
request,
|
|
57
|
+
retry: () => snapshot.requested !== null ? request(snapshot.requested) : Promise.resolve<SearchOutcome>(disposed ? "disposed" : "failed"),
|
|
58
|
+
clear,
|
|
59
|
+
dispose: () => { disposed = true; clear(); },
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/search.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { createTextNormalizer } from "./text-normalization.ts";
|
|
2
|
+
|
|
3
|
+
export interface SearchEvaluation<Row> {
|
|
4
|
+
readonly locale: string;
|
|
5
|
+
readonly columns: readonly string[];
|
|
6
|
+
readonly getValue: (row: Row, column: string) => unknown;
|
|
7
|
+
/** Enables the portable leading-apostrophe literal-phrase syntax. */
|
|
8
|
+
readonly exactMatch?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface SearchMatch<Row> {
|
|
11
|
+
readonly row: Row;
|
|
12
|
+
/** Lower is better. Equal ranks preserve source order. */
|
|
13
|
+
readonly rank: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type SearchMode = "ranked" | "exact";
|
|
17
|
+
|
|
18
|
+
export interface SearchQuery {
|
|
19
|
+
readonly mode: SearchMode;
|
|
20
|
+
readonly value: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface PreparedSearch {
|
|
24
|
+
readonly columns: readonly string[];
|
|
25
|
+
readonly mode: SearchMode;
|
|
26
|
+
readonly terms: readonly string[];
|
|
27
|
+
readonly normalize: (value: string) => string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface IndexedSearchMatch<Row> extends SearchMatch<Row> {
|
|
31
|
+
readonly index: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function rankText(text: string, query: string): number | null {
|
|
35
|
+
if (text === query) return 0;
|
|
36
|
+
if (text.startsWith(query)) return 1;
|
|
37
|
+
if (text.includes(query)) return 2;
|
|
38
|
+
let position = 0;
|
|
39
|
+
for (const character of query) {
|
|
40
|
+
const found = text.indexOf(character, position);
|
|
41
|
+
if (found < 0) return null;
|
|
42
|
+
position = found + character.length;
|
|
43
|
+
}
|
|
44
|
+
return 3;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Parse DataTable's serializable search syntax. A leading apostrophe selects a
|
|
49
|
+
* literal contiguous phrase; two leading apostrophes escape a literal apostrophe.
|
|
50
|
+
*/
|
|
51
|
+
export function parseSearchQuery(query: string, exactMatch = false): SearchQuery {
|
|
52
|
+
const value = query.trim();
|
|
53
|
+
if (!exactMatch || !value.startsWith("'")) return Object.freeze({ mode: "ranked", value });
|
|
54
|
+
if (value.startsWith("''")) return Object.freeze({ mode: "ranked", value: value.slice(1) });
|
|
55
|
+
return Object.freeze({ mode: "exact", value: value.slice(1).trim() });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Encode a match mode without adding a second field to persisted TableState. */
|
|
59
|
+
export function formatSearchQuery(value: string, mode: SearchMode): string {
|
|
60
|
+
const query = value.trim();
|
|
61
|
+
if (mode === "exact") return `'${query}`;
|
|
62
|
+
return query.startsWith("'") ? `'${query}` : query;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function prepareSearch<Row>(query: string, options: SearchEvaluation<Row>): PreparedSearch {
|
|
66
|
+
const locale = Intl.getCanonicalLocales(options.locale)[0];
|
|
67
|
+
if (!locale) throw new Error("Search requires an explicit locale");
|
|
68
|
+
const columns = [...options.columns];
|
|
69
|
+
if (columns.some(column => typeof column !== "string" || !column.trim()) || new Set(columns).size !== columns.length) throw new Error("Search columns must be unique nonempty IDs");
|
|
70
|
+
const normalize = createTextNormalizer(locale);
|
|
71
|
+
const parsed = parseSearchQuery(query, options.exactMatch ?? false);
|
|
72
|
+
const normalized = normalize(parsed.value);
|
|
73
|
+
const terms = parsed.mode === "exact" ? (normalized ? [normalized] : []) : [...new Set(normalized.split(/\s+/u).filter(Boolean))];
|
|
74
|
+
return Object.freeze({ columns: Object.freeze(columns), mode: parsed.mode, terms: Object.freeze(terms), normalize });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function evaluateSearch<Row>(rows: readonly Row[], prepared: PreparedSearch, options: SearchEvaluation<Row>): readonly IndexedSearchMatch<Row>[] {
|
|
78
|
+
const onlyTerm = prepared.terms.length === 1 ? prepared.terms[0] : undefined;
|
|
79
|
+
const matches: IndexedSearchMatch<Row>[] = [];
|
|
80
|
+
for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
|
|
81
|
+
const row = rows[rowIndex];
|
|
82
|
+
if (row === undefined) throw new Error(`Missing search row at index ${rowIndex}`);
|
|
83
|
+
if (onlyTerm !== undefined) {
|
|
84
|
+
let rank: number | null = null;
|
|
85
|
+
for (const column of prepared.columns) {
|
|
86
|
+
const value = options.getValue(row, column);
|
|
87
|
+
const text = typeof value === "string" ? prepared.normalize(value) : typeof value === "number" && Number.isFinite(value) ? String(value) : null;
|
|
88
|
+
if (text === null) continue;
|
|
89
|
+
const score = prepared.mode === "exact" ? (text.includes(onlyTerm) ? 0 : null) : rankText(text, onlyTerm);
|
|
90
|
+
if (score !== null && (rank === null || score < rank)) rank = score;
|
|
91
|
+
if (rank === 0) break;
|
|
92
|
+
}
|
|
93
|
+
if (rank !== null) matches.push({ row, rank, index: rowIndex });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const best: Array<number | null> = Array.from({ length: prepared.terms.length }, () => null);
|
|
97
|
+
for (const column of prepared.columns) {
|
|
98
|
+
const value = options.getValue(row, column);
|
|
99
|
+
const text = typeof value === "string" ? prepared.normalize(value) : typeof value === "number" && Number.isFinite(value) ? String(value) : null;
|
|
100
|
+
if (text === null) continue;
|
|
101
|
+
let complete = true;
|
|
102
|
+
for (let termIndex = 0; termIndex < prepared.terms.length; termIndex++) {
|
|
103
|
+
const current = best[termIndex] ?? null;
|
|
104
|
+
if (current === 0) continue;
|
|
105
|
+
const term = prepared.terms[termIndex];
|
|
106
|
+
if (term === undefined) continue;
|
|
107
|
+
const score = rankText(text, term);
|
|
108
|
+
if (score !== null && (current === null || score < current)) best[termIndex] = score;
|
|
109
|
+
if (best[termIndex] !== 0) complete = false;
|
|
110
|
+
}
|
|
111
|
+
if (complete) break;
|
|
112
|
+
}
|
|
113
|
+
let rank = 0;
|
|
114
|
+
let missing = false;
|
|
115
|
+
for (const score of best) {
|
|
116
|
+
if (score === null) { missing = true; break; }
|
|
117
|
+
rank += score;
|
|
118
|
+
}
|
|
119
|
+
if (!missing) matches.push({ row, rank, index: rowIndex });
|
|
120
|
+
}
|
|
121
|
+
matches.sort((left, right) => left.rank - right.rank || left.index - right.index);
|
|
122
|
+
return matches;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** AND ranked query terms across configured columns, or one literal phrase within a single column when enabled. */
|
|
126
|
+
export function searchClientRows<Row>(rows: readonly Row[], query: string, options: SearchEvaluation<Row>): readonly SearchMatch<Row>[] {
|
|
127
|
+
const prepared = prepareSearch(query, options);
|
|
128
|
+
if (prepared.terms.length === 0) return rows.map(row => ({ row, rank: 0 }));
|
|
129
|
+
return evaluateSearch(rows, prepared, options).map(({ row, rank }) => ({ row, rank }));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Package-internal row-only path avoids allocating public match records for an inactive query. */
|
|
133
|
+
export function searchClientRowValues<Row>(rows: readonly Row[], query: string, options: SearchEvaluation<Row>): readonly Row[] {
|
|
134
|
+
const prepared = prepareSearch(query, options);
|
|
135
|
+
if (prepared.terms.length === 0) return rows;
|
|
136
|
+
return evaluateSearch(rows, prepared, options).map(match => match.row);
|
|
137
|
+
}
|