@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
package/src/filter.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
export type FilterColumn =
|
|
2
|
+
| { readonly id: string; readonly type: "text" }
|
|
3
|
+
| { readonly id: string; readonly type: "number" }
|
|
4
|
+
| { readonly id: string; readonly type: "date" }
|
|
5
|
+
| { readonly id: string; readonly type: "enum"; readonly options: readonly string[] };
|
|
6
|
+
export type FilterNode =
|
|
7
|
+
| { readonly kind: "and"; readonly children: readonly FilterNode[] }
|
|
8
|
+
| { readonly kind: "or"; readonly children: readonly FilterNode[] }
|
|
9
|
+
| { readonly kind: "not"; readonly child: FilterNode }
|
|
10
|
+
| { readonly kind: "empty"; readonly column: string }
|
|
11
|
+
| { readonly kind: "text"; readonly column: string; readonly operator: "eq" | "contains" | "startsWith" | "endsWith"; readonly value: string; readonly caseSensitive: boolean }
|
|
12
|
+
| { readonly kind: "number"; readonly column: string; readonly operator: "eq" | "lt" | "lte" | "gt" | "gte"; readonly value: number }
|
|
13
|
+
| { readonly kind: "number"; readonly column: string; readonly operator: "between"; readonly min: number; readonly max: number }
|
|
14
|
+
| { readonly kind: "date"; readonly column: string; readonly operator: "eq" | "lt" | "lte" | "gt" | "gte"; readonly value: number }
|
|
15
|
+
| { readonly kind: "date"; readonly column: string; readonly operator: "between"; readonly min: number; readonly max: number }
|
|
16
|
+
| { readonly kind: "enum"; readonly column: string; readonly operator: "in"; readonly values: readonly string[] };
|
|
17
|
+
|
|
18
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function fail(path: string, message: string): never { throw new Error(`Invalid filter at ${path}: ${message}`); }
|
|
22
|
+
function keys(value: Record<string, unknown>, allowed: readonly string[], path: string): void {
|
|
23
|
+
for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(path, `unknown field ${key}`);
|
|
24
|
+
}
|
|
25
|
+
function numeric(value: unknown, path: string, date: boolean): number {
|
|
26
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fail(path, "expected a finite number");
|
|
27
|
+
if (date && Math.abs(value) > 8.64e15) return fail(path, "timestamp is outside the supported epoch-millisecond range");
|
|
28
|
+
return value === 0 ? 0 : value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Copy and validate the complete AST against the available filter columns before using it. */
|
|
32
|
+
export function parseFilter(value: unknown, columns: readonly FilterColumn[]): FilterNode {
|
|
33
|
+
const schema = new Map<string, FilterColumn>();
|
|
34
|
+
for (const column of columns) {
|
|
35
|
+
if (typeof column.id !== "string" || !column.id.trim() || schema.has(column.id)) throw new Error(`Invalid or duplicate filter column: ${column.id}`);
|
|
36
|
+
if (column.type === "enum") {
|
|
37
|
+
if (!Array.isArray(column.options)) throw new Error(`Invalid enum options for filter column: ${column.id}`);
|
|
38
|
+
for (const option of column.options) if (typeof option !== "string") throw new Error(`Invalid enum options for filter column: ${column.id}`);
|
|
39
|
+
}
|
|
40
|
+
schema.set(column.id, column);
|
|
41
|
+
}
|
|
42
|
+
let count = 0;
|
|
43
|
+
function visit(input: unknown, path: string, depth: number): FilterNode {
|
|
44
|
+
if (++count > 4096 || depth >= 64) return fail(path, "filter exceeds 4096 nodes or 64 levels");
|
|
45
|
+
if (!record(input)) return fail(path, "expected a node object");
|
|
46
|
+
const kind = input.kind;
|
|
47
|
+
if (kind === "and" || kind === "or") {
|
|
48
|
+
keys(input, ["kind", "children"], path);
|
|
49
|
+
if (!Array.isArray(input.children)) return fail(path, "group children must be an array");
|
|
50
|
+
if (input.children.length > 4096) return fail(path, "filter exceeds 4096 nodes");
|
|
51
|
+
return Object.freeze({ kind, children: Object.freeze(Array.from(input.children, (child, index) => visit(child, `${path}.children[${index}]`, depth + 1))) });
|
|
52
|
+
}
|
|
53
|
+
if (kind === "not") {
|
|
54
|
+
keys(input, ["kind", "child"], path);
|
|
55
|
+
return Object.freeze({ kind, child: visit(input.child, `${path}.child`, depth + 1) });
|
|
56
|
+
}
|
|
57
|
+
if (typeof input.column !== "string" || !schema.has(input.column)) return fail(path, "unknown or missing column");
|
|
58
|
+
const column = input.column;
|
|
59
|
+
if (kind === "empty") { keys(input, ["kind", "column"], path); return Object.freeze({ kind, column }); }
|
|
60
|
+
if (kind !== schema.get(column)?.type) return fail(path, `node type does not match column ${column}`);
|
|
61
|
+
const operator = input.operator;
|
|
62
|
+
if (kind === "text") {
|
|
63
|
+
keys(input, ["kind", "column", "operator", "value", "caseSensitive"], path);
|
|
64
|
+
if (operator !== "eq" && operator !== "contains" && operator !== "startsWith" && operator !== "endsWith") return fail(path, "unsupported text operator");
|
|
65
|
+
if (typeof input.value !== "string") return fail(path, "text value must be a string");
|
|
66
|
+
if (input.caseSensitive !== undefined && typeof input.caseSensitive !== "boolean") return fail(path, "caseSensitive must be boolean");
|
|
67
|
+
return Object.freeze({ kind, column, operator, value: input.value, caseSensitive: input.caseSensitive ?? false });
|
|
68
|
+
}
|
|
69
|
+
if (kind === "number" || kind === "date") {
|
|
70
|
+
if (operator === "between") {
|
|
71
|
+
keys(input, ["kind", "column", "operator", "min", "max"], path);
|
|
72
|
+
const min = numeric(input.min, `${path}.min`, kind === "date");
|
|
73
|
+
const max = numeric(input.max, `${path}.max`, kind === "date");
|
|
74
|
+
if (min > max) return fail(path, "range minimum exceeds maximum");
|
|
75
|
+
return Object.freeze({ kind, column, operator, min, max });
|
|
76
|
+
}
|
|
77
|
+
keys(input, ["kind", "column", "operator", "value"], path);
|
|
78
|
+
if (operator !== "eq" && operator !== "lt" && operator !== "lte" && operator !== "gt" && operator !== "gte") return fail(path, "unsupported numeric/date operator");
|
|
79
|
+
return Object.freeze({ kind, column, operator, value: numeric(input.value, `${path}.value`, kind === "date") });
|
|
80
|
+
}
|
|
81
|
+
if (kind === "enum") {
|
|
82
|
+
keys(input, ["kind", "column", "operator", "values"], path);
|
|
83
|
+
const definition = schema.get(column);
|
|
84
|
+
if (operator !== "in" || !Array.isArray(input.values) || definition?.type !== "enum") return fail(path, "enum requires an in operator and values array");
|
|
85
|
+
const options = new Set(definition.options);
|
|
86
|
+
const values: string[] = [];
|
|
87
|
+
for (const option of input.values) {
|
|
88
|
+
if (typeof option !== "string" || !options.has(option)) return fail(path, "unknown enum option");
|
|
89
|
+
if (!values.includes(option)) values.push(option);
|
|
90
|
+
}
|
|
91
|
+
return Object.freeze({ kind, column, operator, values: Object.freeze(values) });
|
|
92
|
+
}
|
|
93
|
+
return fail(path, "unknown node kind");
|
|
94
|
+
}
|
|
95
|
+
return visit(value, "$", 0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function serializeFilter(filter: FilterNode, columns: readonly FilterColumn[]): string {
|
|
99
|
+
const result = JSON.stringify({ version: 1, filter: parseFilter(filter, columns) });
|
|
100
|
+
if (result.length > 262144) throw new Error("Serialized filter exceeds 262144 characters");
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function deserializeFilter(serialized: string, columns: readonly FilterColumn[]): FilterNode {
|
|
105
|
+
if (serialized.length > 262144) throw new Error("Serialized filter exceeds 262144 characters");
|
|
106
|
+
let envelope: unknown;
|
|
107
|
+
try { envelope = JSON.parse(serialized); }
|
|
108
|
+
catch { throw new Error("Invalid filter JSON"); }
|
|
109
|
+
if (!record(envelope)) return fail("$", "expected versioned envelope");
|
|
110
|
+
keys(envelope, ["version", "filter"], "$");
|
|
111
|
+
if (envelope.version !== 1) return fail("$", "unsupported filter version");
|
|
112
|
+
return parseFilter(envelope.filter, columns);
|
|
113
|
+
}
|
package/src/grouping.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { ColumnAggregate, ColumnValue } from "./columns.ts";
|
|
2
|
+
|
|
3
|
+
export interface GroupAggregateColumn<Row extends object> {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly aggregate: ColumnAggregate;
|
|
6
|
+
readonly getValue: (row: Row) => ColumnValue;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface GroupAggregateValue {
|
|
10
|
+
readonly column: string;
|
|
11
|
+
readonly value: number | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ClientRowGroup<Row extends object> {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
readonly value: ColumnValue;
|
|
17
|
+
readonly rows: readonly Row[];
|
|
18
|
+
/** Full matching leaf count. Equals rows.length for client groups. */
|
|
19
|
+
readonly count: number;
|
|
20
|
+
readonly aggregates: readonly GroupAggregateValue[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ServerRowGroup {
|
|
24
|
+
readonly value: ColumnValue;
|
|
25
|
+
readonly rowIds: readonly string[];
|
|
26
|
+
readonly count: number;
|
|
27
|
+
readonly aggregates: readonly GroupAggregateValue[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ClientGroupingOptions<Row extends object> {
|
|
31
|
+
readonly column: string;
|
|
32
|
+
readonly getValue: (row: Row) => ColumnValue;
|
|
33
|
+
readonly aggregates?: readonly GroupAggregateColumn<Row>[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function validateValue(value: unknown, label: string): ColumnValue {
|
|
37
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
38
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
39
|
+
throw new Error(`${label} must be a string, finite number, boolean, or null`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function groupKey(value: ColumnValue): string {
|
|
43
|
+
if (value === null) return "null";
|
|
44
|
+
return `${typeof value}:${JSON.stringify(value)}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function aggregateRows<Row extends object>(rows: readonly Row[], column: GroupAggregateColumn<Row>): GroupAggregateValue {
|
|
48
|
+
let count = 0;
|
|
49
|
+
let total = 0;
|
|
50
|
+
let minimum = Number.POSITIVE_INFINITY;
|
|
51
|
+
let maximum = Number.NEGATIVE_INFINITY;
|
|
52
|
+
for (let index = 0; index < rows.length; index++) {
|
|
53
|
+
const value = validateValue(column.getValue(rows[index]!), `Aggregate ${column.id} row ${index}`);
|
|
54
|
+
if (value === null) continue;
|
|
55
|
+
count++;
|
|
56
|
+
if (column.aggregate === "count") continue;
|
|
57
|
+
if (typeof value !== "number") throw new Error(`Aggregate ${column.id} ${column.aggregate} requires numeric values`);
|
|
58
|
+
total += value;
|
|
59
|
+
minimum = Math.min(minimum, value);
|
|
60
|
+
maximum = Math.max(maximum, value);
|
|
61
|
+
}
|
|
62
|
+
const value = column.aggregate === "count" ? count
|
|
63
|
+
: count === 0 ? null
|
|
64
|
+
: column.aggregate === "sum" ? total
|
|
65
|
+
: column.aggregate === "average" ? total / count
|
|
66
|
+
: column.aggregate === "min" ? minimum
|
|
67
|
+
: maximum;
|
|
68
|
+
return Object.freeze({ column: column.id, value });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Group a complete accepted client view in first-seen order and calculate leaf aggregates. */
|
|
72
|
+
export function groupClientRows<Row extends object>(rows: readonly Row[], options: ClientGroupingOptions<Row>): readonly ClientRowGroup<Row>[] {
|
|
73
|
+
if (!Array.isArray(rows)) throw new Error("Grouped rows must be an array");
|
|
74
|
+
if (typeof options.column !== "string" || !options.column.trim()) throw new Error("Grouping column must be a nonempty string");
|
|
75
|
+
if (typeof options.getValue !== "function") throw new Error("Grouping requires a value accessor");
|
|
76
|
+
const aggregateColumns = options.aggregates ?? [];
|
|
77
|
+
const aggregateIds = new Set<string>();
|
|
78
|
+
for (const column of aggregateColumns) {
|
|
79
|
+
if (!column || typeof column !== "object" || typeof column.id !== "string" || !column.id.trim() || aggregateIds.has(column.id)) throw new Error("Aggregate columns require unique nonempty IDs");
|
|
80
|
+
if (column.aggregate !== "sum" && column.aggregate !== "average" && column.aggregate !== "min" && column.aggregate !== "max" && column.aggregate !== "count") throw new Error(`Aggregate ${column.id} has an invalid operation`);
|
|
81
|
+
if (typeof column.getValue !== "function") throw new Error(`Aggregate ${column.id} requires a value accessor`);
|
|
82
|
+
aggregateIds.add(column.id);
|
|
83
|
+
}
|
|
84
|
+
const grouped = new Map<ColumnValue, Row[]>();
|
|
85
|
+
for (let index = 0; index < rows.length; index++) {
|
|
86
|
+
if (!Object.hasOwn(rows, index) || typeof rows[index] !== "object" || rows[index] === null) throw new Error(`Grouped row ${index} must be an object`);
|
|
87
|
+
const row = rows[index]!;
|
|
88
|
+
const value = validateValue(options.getValue(row), `Grouping value at row ${index}`);
|
|
89
|
+
const group = grouped.get(value);
|
|
90
|
+
if (group) group.push(row);
|
|
91
|
+
else grouped.set(value, [row]);
|
|
92
|
+
}
|
|
93
|
+
return Object.freeze([...grouped].map(([value, groupRows]) => {
|
|
94
|
+
const acceptedRows = Object.freeze([...groupRows]);
|
|
95
|
+
return Object.freeze({
|
|
96
|
+
id: `group:${options.column}:${groupKey(value)}`,
|
|
97
|
+
value,
|
|
98
|
+
rows: acceptedRows,
|
|
99
|
+
count: acceptedRows.length,
|
|
100
|
+
aggregates: Object.freeze(aggregateColumns.map(column => aggregateRows(acceptedRows, column))),
|
|
101
|
+
});
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
106
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Validate delegated groups against one accepted server page without recomputing full-query totals locally. */
|
|
110
|
+
export function normalizeServerGroups<Row extends object>(rows: readonly Row[], groups: unknown, options: {
|
|
111
|
+
readonly column: string;
|
|
112
|
+
readonly aggregateColumns: readonly string[];
|
|
113
|
+
readonly getRowId: (row: Row) => string;
|
|
114
|
+
}): readonly ClientRowGroup<Row>[] {
|
|
115
|
+
const acceptedRows = validatedRowsForServer(rows);
|
|
116
|
+
if (!Array.isArray(groups)) throw new Error("Server grouping requires a groups array");
|
|
117
|
+
const groupValues: readonly unknown[] = groups;
|
|
118
|
+
const expectedAggregates = new Set<string>();
|
|
119
|
+
for (const id of options.aggregateColumns) {
|
|
120
|
+
if (typeof id !== "string" || !id.trim() || expectedAggregates.has(id)) throw new Error("Server aggregate columns must be unique nonempty IDs");
|
|
121
|
+
expectedAggregates.add(id);
|
|
122
|
+
}
|
|
123
|
+
const rowById = new Map<string, Row>();
|
|
124
|
+
const acceptedOrder: string[] = [];
|
|
125
|
+
for (let index = 0; index < acceptedRows.length; index++) {
|
|
126
|
+
const row = acceptedRows[index]!;
|
|
127
|
+
const id = options.getRowId(row);
|
|
128
|
+
if (typeof id !== "string" || !id.trim() || rowById.has(id)) throw new Error(`Server grouped row ${index} has an invalid or duplicate ID`);
|
|
129
|
+
rowById.set(id, row);
|
|
130
|
+
acceptedOrder.push(id);
|
|
131
|
+
}
|
|
132
|
+
const seenRows = new Set<string>();
|
|
133
|
+
const seenGroups = new Set<string>();
|
|
134
|
+
const flattenedOrder: string[] = [];
|
|
135
|
+
const result: ClientRowGroup<Row>[] = [];
|
|
136
|
+
for (let index = 0; index < groupValues.length; index++) {
|
|
137
|
+
const candidate = groupValues[index];
|
|
138
|
+
if (!Object.hasOwn(groupValues, index) || !record(candidate)) throw new Error(`Server group ${index} must be an object`);
|
|
139
|
+
const group = candidate;
|
|
140
|
+
for (const field of Object.keys(group)) if (field !== "value" && field !== "rowIds" && field !== "count" && field !== "aggregates") throw new Error(`Server group ${index} has unknown field ${field}`);
|
|
141
|
+
for (const field of ["value", "rowIds", "count", "aggregates"]) if (!Object.hasOwn(group, field)) throw new Error(`Server group ${index} is missing ${field}`);
|
|
142
|
+
const value = validateValue(group.value, `Server group ${index} value`);
|
|
143
|
+
const id = `group:${options.column}:${groupKey(value)}`;
|
|
144
|
+
if (seenGroups.has(id)) throw new Error(`Duplicate server group value at index ${index}`);
|
|
145
|
+
seenGroups.add(id);
|
|
146
|
+
if (!Array.isArray(group.rowIds) || group.rowIds.length === 0) throw new Error(`Server group ${index} rowIds must be a nonempty array`);
|
|
147
|
+
const rowIds: readonly unknown[] = group.rowIds;
|
|
148
|
+
const groupRows: Row[] = [];
|
|
149
|
+
for (const rowId of rowIds) {
|
|
150
|
+
if (typeof rowId !== "string" || !rowId.trim() || seenRows.has(rowId)) throw new Error(`Server group ${index} has an invalid or duplicate row ID`);
|
|
151
|
+
const row = rowById.get(rowId);
|
|
152
|
+
if (!row) throw new Error(`Server group ${index} references an unavailable page row: ${rowId}`);
|
|
153
|
+
seenRows.add(rowId);
|
|
154
|
+
flattenedOrder.push(rowId);
|
|
155
|
+
groupRows.push(row);
|
|
156
|
+
}
|
|
157
|
+
if (typeof group.count !== "number" || !Number.isSafeInteger(group.count) || group.count < groupRows.length) throw new Error(`Server group ${index} count must cover its accepted page rows`);
|
|
158
|
+
if (!Array.isArray(group.aggregates)) throw new Error(`Server group ${index} aggregates must be an array`);
|
|
159
|
+
const aggregateValues: readonly unknown[] = group.aggregates;
|
|
160
|
+
const aggregates: GroupAggregateValue[] = [];
|
|
161
|
+
const seenAggregates = new Set<string>();
|
|
162
|
+
for (let aggregateIndex = 0; aggregateIndex < aggregateValues.length; aggregateIndex++) {
|
|
163
|
+
const aggregate = aggregateValues[aggregateIndex];
|
|
164
|
+
if (!record(aggregate) || Object.keys(aggregate).some(field => field !== "column" && field !== "value") || !Object.hasOwn(aggregate, "column") || !Object.hasOwn(aggregate, "value")) throw new Error(`Server group ${index} aggregate ${aggregateIndex} is invalid`);
|
|
165
|
+
if (typeof aggregate.column !== "string" || !expectedAggregates.has(aggregate.column) || seenAggregates.has(aggregate.column)) throw new Error(`Server group ${index} has an unknown or duplicate aggregate column`);
|
|
166
|
+
if (aggregate.value !== null && (typeof aggregate.value !== "number" || !Number.isFinite(aggregate.value))) throw new Error(`Server group ${index} aggregate ${aggregate.column} must be finite or null`);
|
|
167
|
+
seenAggregates.add(aggregate.column);
|
|
168
|
+
aggregates.push(Object.freeze({ column: aggregate.column, value: aggregate.value }));
|
|
169
|
+
}
|
|
170
|
+
if (seenAggregates.size !== expectedAggregates.size) throw new Error(`Server group ${index} must provide every configured aggregate`);
|
|
171
|
+
result.push(Object.freeze({ id, value, rows: Object.freeze(groupRows), count: group.count, aggregates: Object.freeze(aggregates) }));
|
|
172
|
+
}
|
|
173
|
+
if (flattenedOrder.length !== acceptedOrder.length || flattenedOrder.some((id, index) => id !== acceptedOrder[index])) throw new Error("Server groups must cover every accepted page row once in server order");
|
|
174
|
+
return Object.freeze(result);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function validatedRowsForServer<Row extends object>(rows: readonly Row[]): readonly Row[] {
|
|
178
|
+
if (!Array.isArray(rows)) throw new Error("Server grouped rows must be an array");
|
|
179
|
+
const result: Row[] = [];
|
|
180
|
+
for (let index = 0; index < rows.length; index++) {
|
|
181
|
+
if (!Object.hasOwn(rows, index) || typeof rows[index] !== "object" || rows[index] === null) throw new Error(`Server grouped row ${index} must be an object`);
|
|
182
|
+
result.push(rows[index]!);
|
|
183
|
+
}
|
|
184
|
+
return Object.freeze(result);
|
|
185
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from "./core.ts";
|
|
2
|
+
export { DataTable } from "./DataTable.tsx";
|
|
3
|
+
export type { DataTableProps, DataTableResult, DataTableInitialState, DataTableSelectionOptions, DataTableGroupingOptions, DataTableHierarchyOptions, DataTableExportFormat, DataTableExportOptions, DataTableCellCommitRequest, DataTableAction, DataTableActionContext, DataTableMobileLayoutOptions, DataTableVariant, DataTableDensity, DataTableSearchOptions, DataTableFilterBarOptions, ClientDataTableProps, ServerDataTableProps } from "./DataTable.tsx";
|
|
4
|
+
export { FilterBar } from "./FilterBar.tsx";
|
|
5
|
+
export type { FilterBarProps, FilterDateEditor, FilterDateEditorProps } from "./FilterBar.tsx";
|
|
6
|
+
export { QueryBuilder } from "./QueryBuilder.tsx";
|
|
7
|
+
export type { QueryBuilderProps } from "./QueryBuilder.tsx";
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export const englishTableMessages = Object.freeze({
|
|
2
|
+
loading: "Loading", refreshing: "Refreshing, showing existing results", noResults: "No results", retry: "Retry", retryFailed: "Retry failed. Try again.", serverError: "Something went wrong",
|
|
3
|
+
searchTable: "Search {caption}", searchMatchMode: "Search match mode", searchRanked: "Smart", searchExact: "Exact", tableShortcuts: "Tables", tableControls: "{caption} table controls", resultCountOne: "{count} result", resultCount: "{count} results",
|
|
4
|
+
previousResults: "Previous results", clearFilters: "Clear filters", clearSearchAndFilters: "Clear search and filters", selectAll: "Select all matching", selectPage: "Select this page", selectRow: "Select row {id}", clearSelection: "Clear selection", selectionActions: "Selection actions", selectedCount: "{count} selected",
|
|
5
|
+
cardView: "{caption}, card view", rowActions: "Actions for row {id}",
|
|
6
|
+
sort: "Sort", sortColumn: "Sort by {column}", sortedAscending: "ascending", sortedDescending: "descending", notSorted: "not sorted", sortPriority: "priority {position} of {count}",
|
|
7
|
+
export: "Export", exportCSV: "Export CSV", exportJSON: "Export JSON", preparingExport: "Preparing export", exportFailed: "Export failed", retryExport: "Retry export", downloadLastExport: "Download last export",
|
|
8
|
+
filters: "Filters", filterAdd: "+ Filter", filterColumns: "Filter columns", filterSearchColumns: "Search filter columns", filterEdit: "Edit filter", filterRemove: "Remove filter", filterApply: "Apply filter",
|
|
9
|
+
filterOperator: "Operator", filterValue: "Value", filterMinimum: "Minimum", filterMaximum: "Maximum", filterDate: "Date", filterStartDate: "Start date", filterEndDate: "End date", filterValues: "Values",
|
|
10
|
+
filterCaseSensitive: "Case sensitive", filterNegated: "Exclude matches", filterInheritedNegation: "This condition is also inside an excluded group.", filterInvalid: "Enter a valid filter value.",
|
|
11
|
+
filterEquals: "is", filterContains: "contains", filterStartsWith: "starts with", filterEndsWith: "ends with", filterLessThan: "is less than", filterAtMost: "is at most", filterGreaterThan: "is greater than", filterAtLeast: "is at least", filterBetween: "is between", filterIsEmpty: "is empty", filterIsAnyOf: "is any of",
|
|
12
|
+
filterSummary: "{column} {operator} {value}", filterNot: "Not: {filter}", filterInheritedNot: "Excluded group: {filter}",
|
|
13
|
+
queryBuilder: "Query builder", queryGroup: "Query group", queryRule: "Query rule", queryMatch: "Match", queryMatchAll: "All rules", queryMatchAny: "Any rule",
|
|
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
|
+
groupMissing: "No value", loadingChildren: "Loading children",
|
|
16
|
+
columns: "Columns", showColumn: "Show column", moveColumnStart: "Move toward start", moveColumnEnd: "Move toward end",
|
|
17
|
+
pinColumn: "Pin column", pinNone: "Not pinned", pinStart: "Pin to start", pinEnd: "Pin to end",
|
|
18
|
+
autoFitColumn: "Auto-fit width", resetColumnWidth: "Reset width", reorderColumn: "Drag to reorder {column}", resizeColumn: "Resize {column}", columnWidthPixels: "{width} pixels",
|
|
19
|
+
editCell: "Edit {column} for row {id}", cellValueRequired: "A value is required", cellValueInvalid: "Enter a valid value", noValue: "No value",
|
|
20
|
+
cellUpdateFailed: "Cell update failed", cellUpdateFailedDescription: "The committed value was restored and your draft was retained.", cellConflict: "This value changed on the server to {value}. Review your draft or press Escape to discard it.",
|
|
21
|
+
expand: "Expand", collapse: "Collapse",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export type TableMessages = Readonly<Record<keyof typeof englishTableMessages, string>>;
|
|
25
|
+
|
|
26
|
+
/** Layer provider overrides over the table package's tree-shakeable English defaults. */
|
|
27
|
+
export function resolveTableMessages(messages: Partial<TableMessages>): TableMessages {
|
|
28
|
+
return Object.freeze({ ...englishTableMessages, ...messages });
|
|
29
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export interface PageState { readonly pageIndex: number; readonly pageSize: number }
|
|
2
|
+
export type TablePagination = false | PageState;
|
|
3
|
+
export interface PageRange extends PageState { readonly pageCount: number; readonly start: number; readonly end: number }
|
|
4
|
+
export interface PageResult<Row> { readonly rows: readonly Row[]; readonly total: number }
|
|
5
|
+
export type ServerPageAssessment<Row> =
|
|
6
|
+
| { readonly kind: "accepted"; readonly pagination: TablePagination; readonly result: PageResult<Row> }
|
|
7
|
+
| { readonly kind: "refetch"; readonly pagination: PageState; readonly total: number };
|
|
8
|
+
|
|
9
|
+
function nonnegativeInteger(value: unknown, name: string): asserts value is number {
|
|
10
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a nonnegative safe integer`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function parsePagination(value: unknown): TablePagination {
|
|
14
|
+
if (value === false) return false;
|
|
15
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || !("pageIndex" in value) || !("pageSize" in value)) throw new Error("pagination must be false or { pageIndex, pageSize }");
|
|
16
|
+
if (Object.keys(value).some(key => key !== "pageIndex" && key !== "pageSize")) throw new Error("pagination contains unknown fields");
|
|
17
|
+
nonnegativeInteger(value.pageIndex, "pageIndex");
|
|
18
|
+
nonnegativeInteger(value.pageSize, "pageSize");
|
|
19
|
+
if (value.pageSize === 0) throw new Error("pageSize must be positive");
|
|
20
|
+
return Object.freeze({ pageIndex: value.pageIndex, pageSize: value.pageSize });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function resolvePagination(mode: "client" | "server", value?: TablePagination): TablePagination {
|
|
24
|
+
if (mode !== "client" && mode !== "server") throw new Error("Table mode must be client or server");
|
|
25
|
+
if (value === undefined) {
|
|
26
|
+
if (mode === "server") throw new Error("Server mode requires explicit pagination, including explicit false for complete results");
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
return parsePagination(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Filter and sort changes reset the requested page, not accepted rows. */
|
|
33
|
+
export function resetPagination(value: TablePagination): TablePagination {
|
|
34
|
+
const parsed = parsePagination(value);
|
|
35
|
+
return parsed === false ? false : Object.freeze({ ...parsed, pageIndex: 0 });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resizePagination(value: PageState, pageSize: number): PageState {
|
|
39
|
+
if (parsePagination(value) === false) throw new Error("Page-size changes require paginated state");
|
|
40
|
+
nonnegativeInteger(pageSize, "pageSize");
|
|
41
|
+
if (pageSize === 0) throw new Error("pageSize must be positive");
|
|
42
|
+
return Object.freeze({ pageIndex: 0, pageSize });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Clamp before multiplying so even extreme valid requested indices cannot overflow the offset. */
|
|
46
|
+
export function getPageRange(value: PageState, total: number): PageRange {
|
|
47
|
+
const parsed = parsePagination(value);
|
|
48
|
+
if (parsed === false) throw new Error("Page ranges require paginated state");
|
|
49
|
+
nonnegativeInteger(total, "total");
|
|
50
|
+
const pageCount = Math.ceil(total / parsed.pageSize);
|
|
51
|
+
const pageIndex = Math.min(parsed.pageIndex, Math.max(0, pageCount - 1));
|
|
52
|
+
const start = pageIndex * parsed.pageSize;
|
|
53
|
+
const end = start + Math.min(parsed.pageSize, total - start);
|
|
54
|
+
return Object.freeze({ pageIndex, pageSize: parsed.pageSize, pageCount, start, end });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Call after transforming the complete client dataset, never on an individual server page. */
|
|
58
|
+
export function paginateClientRows<Row>(rows: readonly Row[], value: TablePagination = false): PageResult<Row> & { readonly pagination: TablePagination } {
|
|
59
|
+
const parsed = parsePagination(value);
|
|
60
|
+
if (parsed === false) return { rows, total: rows.length, pagination: false };
|
|
61
|
+
const range = getPageRange(parsed, rows.length);
|
|
62
|
+
return { rows: rows.slice(range.start, range.end), total: rows.length, pagination: Object.freeze({ pageIndex: range.pageIndex, pageSize: range.pageSize }) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Validate a single response; never fetch, concatenate pages, or publish an invalid result. */
|
|
66
|
+
export function assessServerPage<Row>(value: TablePagination, result: PageResult<Row>): ServerPageAssessment<Row> {
|
|
67
|
+
const parsed = parsePagination(value);
|
|
68
|
+
nonnegativeInteger(result.total, "total");
|
|
69
|
+
if (!Array.isArray(result.rows)) throw new Error("Server rows must be an array");
|
|
70
|
+
if (parsed === false) {
|
|
71
|
+
if (result.rows.length !== result.total) throw new Error("Non-paginated server results must be complete: rows.length must equal total");
|
|
72
|
+
return { kind: "accepted", pagination: false, result };
|
|
73
|
+
}
|
|
74
|
+
const range = getPageRange(parsed, result.total);
|
|
75
|
+
if (range.pageIndex !== parsed.pageIndex && result.total > 0) {
|
|
76
|
+
if (result.rows.length) throw new Error("Out-of-range server page must not contain rows");
|
|
77
|
+
return { kind: "refetch", pagination: Object.freeze({ pageIndex: range.pageIndex, pageSize: range.pageSize }), total: result.total };
|
|
78
|
+
}
|
|
79
|
+
if (result.rows.length !== range.end - range.start) throw new Error("Server page row count does not match the requested page and total");
|
|
80
|
+
return { kind: "accepted", pagination: Object.freeze({ pageIndex: range.pageIndex, pageSize: range.pageSize }), result };
|
|
81
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { FilterColumn, FilterNode } from "./filter.ts";
|
|
2
|
+
import { parseFilter } from "./filter.ts";
|
|
3
|
+
|
|
4
|
+
export type QueryBuilderColumn =
|
|
5
|
+
| { readonly id: string; readonly label: string; readonly type: "text" }
|
|
6
|
+
| { readonly id: string; readonly label: string; readonly type: "number" }
|
|
7
|
+
| { readonly id: string; readonly label: string; readonly type: "date" }
|
|
8
|
+
| { readonly id: string; readonly label: string; readonly type: "enum"; readonly options: readonly string[] };
|
|
9
|
+
|
|
10
|
+
export type QueryBuilderPath = readonly number[];
|
|
11
|
+
|
|
12
|
+
export function queryBuilderFilterColumns(columns: readonly QueryBuilderColumn[]): readonly FilterColumn[] {
|
|
13
|
+
const ids = new Set<string>();
|
|
14
|
+
return Object.freeze(columns.map(column => {
|
|
15
|
+
if (!column.id.trim() || !column.label.trim() || ids.has(column.id)) throw new Error("QueryBuilder columns require unique nonempty IDs and labels");
|
|
16
|
+
ids.add(column.id);
|
|
17
|
+
if (column.type === "enum") {
|
|
18
|
+
const options = [...new Set(column.options)];
|
|
19
|
+
if (options.length === 0 || options.length !== column.options.length || options.some(option => !option.trim())) throw new Error(`QueryBuilder enum column ${JSON.stringify(column.id)} requires unique nonempty options`);
|
|
20
|
+
return Object.freeze({ id: column.id, type: "enum", options: Object.freeze(options) });
|
|
21
|
+
}
|
|
22
|
+
return Object.freeze({ id: column.id, type: column.type });
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function defaultQueryRule(column: QueryBuilderColumn): FilterNode {
|
|
27
|
+
if (column.type === "text") return Object.freeze({ kind: "text", column: column.id, operator: "contains", value: "", caseSensitive: false });
|
|
28
|
+
if (column.type === "number") return Object.freeze({ kind: "number", column: column.id, operator: "eq", value: 0 });
|
|
29
|
+
if (column.type === "date") return Object.freeze({ kind: "date", column: column.id, operator: "eq", value: Date.UTC(2000, 0, 1) });
|
|
30
|
+
const value = column.options[0];
|
|
31
|
+
if (!value) throw new Error(`QueryBuilder enum column ${JSON.stringify(column.id)} requires an option`);
|
|
32
|
+
return Object.freeze({ kind: "enum", column: column.id, operator: "in", values: Object.freeze([value]) });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function visit(node: FilterNode, path: QueryBuilderPath, replace: (node: FilterNode) => FilterNode): FilterNode {
|
|
36
|
+
if (path.length === 0) return replace(node);
|
|
37
|
+
const [index, ...rest] = path;
|
|
38
|
+
if (index === undefined || !Number.isSafeInteger(index) || index < 0) throw new Error("QueryBuilder path segments must be nonnegative integers");
|
|
39
|
+
if (node.kind === "and" || node.kind === "or") {
|
|
40
|
+
if (index >= node.children.length) throw new Error("QueryBuilder path is outside the filter tree");
|
|
41
|
+
return Object.freeze({ ...node, children: Object.freeze(node.children.map((child, childIndex) => childIndex === index ? visit(child, rest, replace) : child)) });
|
|
42
|
+
}
|
|
43
|
+
if (node.kind === "not" && index === 0) return Object.freeze({ kind: "not", child: visit(node.child, rest, replace) });
|
|
44
|
+
throw new Error("QueryBuilder path is outside the filter tree");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function queryNodeAt(filter: FilterNode, path: QueryBuilderPath): FilterNode {
|
|
48
|
+
let node = filter;
|
|
49
|
+
for (const index of path) {
|
|
50
|
+
if (!Number.isSafeInteger(index) || index < 0) throw new Error("QueryBuilder path segments must be nonnegative integers");
|
|
51
|
+
if (node.kind === "and" || node.kind === "or") {
|
|
52
|
+
const child = node.children[index];
|
|
53
|
+
if (!child) throw new Error("QueryBuilder path is outside the filter tree");
|
|
54
|
+
node = child;
|
|
55
|
+
} else if (node.kind === "not" && index === 0) node = node.child;
|
|
56
|
+
else throw new Error("QueryBuilder path is outside the filter tree");
|
|
57
|
+
}
|
|
58
|
+
return node;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function replaceQueryNode(filter: FilterNode, path: QueryBuilderPath, replacement: FilterNode, columns: readonly FilterColumn[]): FilterNode {
|
|
62
|
+
return parseFilter(visit(filter, path, () => replacement), columns);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function appendQueryChild(filter: FilterNode, path: QueryBuilderPath, child: FilterNode, columns: readonly FilterColumn[]): FilterNode {
|
|
66
|
+
return parseFilter(visit(filter, path, node => {
|
|
67
|
+
if (node.kind !== "and" && node.kind !== "or") throw new Error("QueryBuilder can add children only to a group");
|
|
68
|
+
return Object.freeze({ ...node, children: Object.freeze([...node.children, child]) });
|
|
69
|
+
}), columns);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function removeQueryNode(filter: FilterNode, path: QueryBuilderPath, columns: readonly FilterColumn[]): FilterNode {
|
|
73
|
+
if (path.length === 0) throw new Error("QueryBuilder cannot remove its root node");
|
|
74
|
+
const parentPath = path.slice(0, -1);
|
|
75
|
+
const index = path.at(-1);
|
|
76
|
+
if (index === undefined) throw new Error("QueryBuilder path is incomplete");
|
|
77
|
+
return parseFilter(visit(filter, parentPath, parent => {
|
|
78
|
+
if (parent.kind !== "and" && parent.kind !== "or") throw new Error("QueryBuilder can remove only group children");
|
|
79
|
+
if (!parent.children[index]) throw new Error("QueryBuilder path is outside the filter tree");
|
|
80
|
+
return Object.freeze({ ...parent, children: Object.freeze(parent.children.filter((_child, childIndex) => childIndex !== index)) });
|
|
81
|
+
}), columns);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function moveQueryNode(filter: FilterNode, path: QueryBuilderPath, offset: -1 | 1, columns: readonly FilterColumn[]): FilterNode {
|
|
85
|
+
if (path.length === 0) throw new Error("QueryBuilder cannot move its root node");
|
|
86
|
+
const parentPath = path.slice(0, -1);
|
|
87
|
+
const index = path.at(-1);
|
|
88
|
+
if (index === undefined) throw new Error("QueryBuilder path is incomplete");
|
|
89
|
+
return parseFilter(visit(filter, parentPath, parent => {
|
|
90
|
+
if (parent.kind !== "and" && parent.kind !== "or") throw new Error("QueryBuilder can move only group children");
|
|
91
|
+
const destination = index + offset;
|
|
92
|
+
if (!parent.children[index] || destination < 0 || destination >= parent.children.length) return parent;
|
|
93
|
+
const children = [...parent.children];
|
|
94
|
+
const current = children[index];
|
|
95
|
+
const adjacent = children[destination];
|
|
96
|
+
if (!current || !adjacent) return parent;
|
|
97
|
+
children[index] = adjacent;
|
|
98
|
+
children[destination] = current;
|
|
99
|
+
return Object.freeze({ ...parent, children: Object.freeze(children) });
|
|
100
|
+
}), columns);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function toggleQueryNegation(filter: FilterNode, path: QueryBuilderPath, columns: readonly FilterColumn[]): FilterNode {
|
|
104
|
+
return parseFilter(visit(filter, path, node => node.kind === "not" ? node.child : Object.freeze({ kind: "not", child: node })), columns);
|
|
105
|
+
}
|
package/src/requests.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { assessServerPage, resolvePagination } from "./pagination.ts";
|
|
2
|
+
import type { PageResult, TablePagination } from "./pagination.ts";
|
|
3
|
+
|
|
4
|
+
export interface TableRequestState { readonly pagination: TablePagination }
|
|
5
|
+
export interface TableRequestSnapshot<State, Result> {
|
|
6
|
+
readonly accepted: { readonly state: State; readonly result: Result } | null;
|
|
7
|
+
readonly requested: State | null;
|
|
8
|
+
readonly pending: boolean;
|
|
9
|
+
readonly error: unknown;
|
|
10
|
+
}
|
|
11
|
+
export type TableRequestOutcome = "accepted" | "failed" | "superseded" | "disposed";
|
|
12
|
+
export interface InitialTableResult<State, Result> { readonly state: State; readonly result: Result }
|
|
13
|
+
|
|
14
|
+
/** Framework-neutral request ownership. Read snapshots before/after awaiting request in the UI adapter. */
|
|
15
|
+
export function createTableRequests<State extends TableRequestState, Result extends PageResult<unknown>>(
|
|
16
|
+
onStateChange: (state: State, signal: AbortSignal) => Promise<Result>,
|
|
17
|
+
initial?: InitialTableResult<State, Result>,
|
|
18
|
+
) {
|
|
19
|
+
let snapshot: TableRequestSnapshot<State, Result> = { accepted: null, requested: null, pending: false, error: null };
|
|
20
|
+
if (initial) {
|
|
21
|
+
const state = structuredClone(initial.state);
|
|
22
|
+
resolvePagination("server", state.pagination);
|
|
23
|
+
const assessment = assessServerPage(state.pagination, initial.result);
|
|
24
|
+
if (assessment.kind !== "accepted") throw new Error("Initial table results must describe a valid accepted page, not a page requiring refetch");
|
|
25
|
+
snapshot = { accepted: { state: { ...state, pagination: assessment.pagination }, result: initial.result }, requested: null, pending: false, error: null };
|
|
26
|
+
}
|
|
27
|
+
let sequence = 0n;
|
|
28
|
+
let controller: AbortController | undefined;
|
|
29
|
+
let disposed = false;
|
|
30
|
+
let clearing = false;
|
|
31
|
+
|
|
32
|
+
async function request(value: State): Promise<TableRequestOutcome> {
|
|
33
|
+
if (disposed) return "disposed";
|
|
34
|
+
if (clearing) return "superseded";
|
|
35
|
+
const token = ++sequence;
|
|
36
|
+
controller?.abort();
|
|
37
|
+
if (disposed) return "disposed";
|
|
38
|
+
if (token !== sequence) return "superseded";
|
|
39
|
+
const current = new AbortController();
|
|
40
|
+
controller = current;
|
|
41
|
+
snapshot = { ...snapshot, requested: null, pending: true, error: null };
|
|
42
|
+
try {
|
|
43
|
+
// Separate transport state from both the caller and the publicly readable snapshot.
|
|
44
|
+
let state: State = structuredClone(value);
|
|
45
|
+
resolvePagination("server", state.pagination);
|
|
46
|
+
snapshot = { ...snapshot, requested: structuredClone(state), pending: true, error: null };
|
|
47
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
48
|
+
const result = await onStateChange(structuredClone(state), current.signal);
|
|
49
|
+
if (disposed) return "disposed";
|
|
50
|
+
if (token !== sequence) return "superseded";
|
|
51
|
+
const assessment = assessServerPage(state.pagination, result);
|
|
52
|
+
state = { ...state, pagination: assessment.pagination };
|
|
53
|
+
if (assessment.kind === "accepted") {
|
|
54
|
+
snapshot = { accepted: { state, result }, requested: null, pending: false, error: null };
|
|
55
|
+
return "accepted";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw new Error("Server page kept moving during clamping; retry the latest query");
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (disposed) return "disposed";
|
|
61
|
+
if (token !== sequence) return "superseded";
|
|
62
|
+
snapshot = { ...snapshot, pending: false, error };
|
|
63
|
+
return "failed";
|
|
64
|
+
} finally { if (token === sequence) controller = undefined; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function clear(): void {
|
|
68
|
+
if (clearing) return;
|
|
69
|
+
clearing = true;
|
|
70
|
+
sequence++;
|
|
71
|
+
const previous = controller;
|
|
72
|
+
controller = undefined;
|
|
73
|
+
snapshot = { accepted: null, requested: null, pending: false, error: null };
|
|
74
|
+
try { previous?.abort(); }
|
|
75
|
+
finally { clearing = false; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
getSnapshot: (): TableRequestSnapshot<State, Result> => snapshot,
|
|
80
|
+
request,
|
|
81
|
+
retry: (): Promise<TableRequestOutcome> => snapshot.requested ? request(snapshot.requested) : Promise.resolve(disposed ? "disposed" : "failed"),
|
|
82
|
+
clear,
|
|
83
|
+
dispose: (): void => { disposed = true; clear(); },
|
|
84
|
+
};
|
|
85
|
+
}
|