@pretable/core 0.0.1

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/dist/index.cjs ADDED
@@ -0,0 +1,387 @@
1
+ 'use strict';
2
+
3
+ // ../layout-core/dist/autosize-columns.js
4
+ var DEFAULT_MAX_WIDTH_PX = 400;
5
+ var DEFAULT_MIN_WIDTH_PX = 60;
6
+ var DEFAULT_AVERAGE_CHAR_WIDTH = 7;
7
+ var DEFAULT_CELL_PADDING_PX = 16;
8
+ function autosizeColumns(input) {
9
+ const maxWidthPx = input.options?.maxWidthPx ?? DEFAULT_MAX_WIDTH_PX;
10
+ const minWidthPx = input.options?.minWidthPx ?? DEFAULT_MIN_WIDTH_PX;
11
+ const averageCharWidth = input.options?.averageCharWidth ?? DEFAULT_AVERAGE_CHAR_WIDTH;
12
+ const cellPaddingPx = input.options?.cellPaddingPx ?? DEFAULT_CELL_PADDING_PX;
13
+ const widths = /* @__PURE__ */ new Map();
14
+ for (const column of input.columns) {
15
+ if (column.widthPx !== void 0) {
16
+ continue;
17
+ }
18
+ let maxContentWidth = 0;
19
+ if (column.header) {
20
+ const headerWidth = Array.from(column.header).length * averageCharWidth + cellPaddingPx;
21
+ maxContentWidth = Math.max(maxContentWidth, headerWidth);
22
+ }
23
+ for (const row of input.rows) {
24
+ const rawValue = column.getValue ? column.getValue(row) : row[column.id];
25
+ const text = String(rawValue ?? "");
26
+ if (text.length === 0) {
27
+ continue;
28
+ }
29
+ const contentWidth = Array.from(text).length * averageCharWidth + cellPaddingPx;
30
+ maxContentWidth = Math.max(maxContentWidth, contentWidth);
31
+ }
32
+ const clampedWidth = Math.max(minWidthPx, Math.min(maxWidthPx, maxContentWidth));
33
+ widths.set(column.id, clampedWidth);
34
+ }
35
+ return { widths };
36
+ }
37
+
38
+ // ../grid-core/dist/derived-rows.js
39
+ function createSourceRows(options) {
40
+ return options.rows.map((row, index) => ({
41
+ id: options.getRowId?.(row, index) ?? String(index),
42
+ row,
43
+ sourceIndex: index
44
+ }));
45
+ }
46
+ function deriveVisibleRows(input) {
47
+ const resolvedFilters = resolveFilters(input.columns, input.filters);
48
+ const filtered = input.rows.filter((entry) => matchesFilters(entry.row, resolvedFilters));
49
+ const sorted = sortRows(filtered, input.columns, input.sort);
50
+ return sorted.map(({ id, row, sourceIndex }) => ({
51
+ id,
52
+ row,
53
+ sourceIndex
54
+ }));
55
+ }
56
+ function resolveFilters(columns, filters) {
57
+ const columnMap = new Map(columns.map((c) => [c.id, c]));
58
+ const resolved = [];
59
+ for (const [columnId, rawNeedle] of Object.entries(filters)) {
60
+ if (!rawNeedle) {
61
+ continue;
62
+ }
63
+ const column = columnMap.get(columnId);
64
+ if (!column) {
65
+ continue;
66
+ }
67
+ resolved.push({ column, needle: rawNeedle.toLowerCase() });
68
+ }
69
+ return resolved;
70
+ }
71
+ function matchesFilters(row, resolvedFilters) {
72
+ for (const { column, needle } of resolvedFilters) {
73
+ const haystack = String(readCellValue(row, column)).toLowerCase();
74
+ if (!haystack.includes(needle)) {
75
+ return false;
76
+ }
77
+ }
78
+ return true;
79
+ }
80
+ var collator = new Intl.Collator(void 0, {
81
+ numeric: true,
82
+ sensitivity: "base"
83
+ });
84
+ function sortRows(rows, columns, sort) {
85
+ if (!sort.columnId || !sort.direction) {
86
+ return [...rows];
87
+ }
88
+ const column = columns.find((candidate) => candidate.id === sort.columnId);
89
+ if (!column) {
90
+ return [...rows];
91
+ }
92
+ const multiplier = sort.direction === "asc" ? 1 : -1;
93
+ const rawKeys = rows.map((entry) => readCellValue(entry.row, column));
94
+ const allNumeric = rawKeys.every((v) => typeof v === "number");
95
+ if (allNumeric) {
96
+ const numKeys = rawKeys;
97
+ const indexed2 = rows.map((_, i) => i);
98
+ indexed2.sort((a, b) => {
99
+ const diff = numKeys[a] - numKeys[b];
100
+ return diff !== 0 ? diff * multiplier : rows[a].sourceIndex - rows[b].sourceIndex;
101
+ });
102
+ return indexed2.map((i) => rows[i]);
103
+ }
104
+ const strKeys = rawKeys.map((v) => String(v ?? ""));
105
+ const indexed = rows.map((_, i) => i);
106
+ indexed.sort((a, b) => {
107
+ const comparison = collator.compare(strKeys[a], strKeys[b]);
108
+ return comparison !== 0 ? comparison * multiplier : rows[a].sourceIndex - rows[b].sourceIndex;
109
+ });
110
+ return indexed.map((i) => rows[i]);
111
+ }
112
+ function readCellValue(row, column) {
113
+ return column.getValue ? column.getValue(row) : row[column.id];
114
+ }
115
+
116
+ // ../grid-core/dist/create-grid-core.js
117
+ function applyAutosize(options, autosizeOptions) {
118
+ const result = autosizeColumns({
119
+ columns: options.columns,
120
+ rows: options.rows,
121
+ options: autosizeOptions
122
+ });
123
+ if (result.widths.size === 0) {
124
+ return options;
125
+ }
126
+ const nextColumns = options.columns.map((column) => {
127
+ const computedWidth = result.widths.get(column.id);
128
+ if (computedWidth === void 0) {
129
+ return column;
130
+ }
131
+ return { ...column, widthPx: computedWidth };
132
+ });
133
+ return { ...options, columns: nextColumns };
134
+ }
135
+ function createGridCore(inputOptions) {
136
+ const listeners = /* @__PURE__ */ new Set();
137
+ let options = inputOptions.autosize ? applyAutosize(inputOptions, typeof inputOptions.autosize === "object" ? inputOptions.autosize : void 0) : inputOptions;
138
+ let sourceRows = createSourceRows(options);
139
+ const sourceRowIndex = new Map(sourceRows.map((entry) => [entry.id, entry]));
140
+ let cachedSnapshot = null;
141
+ let cachedVisibleRows = null;
142
+ let cachedDerivedSort = null;
143
+ let cachedDerivedFilters = null;
144
+ let sort = { columnId: null, direction: null };
145
+ let filters = {};
146
+ let selection = { rowIds: [], anchorRowId: null };
147
+ let focus = { rowId: null, columnId: null };
148
+ let viewport = {
149
+ scrollTop: 0,
150
+ scrollLeft: 0,
151
+ height: 0,
152
+ width: 0
153
+ };
154
+ const store = {
155
+ get options() {
156
+ return options;
157
+ },
158
+ subscribe(listener) {
159
+ listeners.add(listener);
160
+ return () => {
161
+ listeners.delete(listener);
162
+ };
163
+ },
164
+ getSnapshot,
165
+ setSort(columnId, direction) {
166
+ if (sort.columnId === columnId && sort.direction === direction) {
167
+ return;
168
+ }
169
+ sort = { columnId, direction };
170
+ emit();
171
+ },
172
+ setFilter(columnId, value) {
173
+ const trimmed = value.trim();
174
+ const currentValue = filters[columnId];
175
+ if (trimmed) {
176
+ if (currentValue === trimmed) {
177
+ return;
178
+ }
179
+ filters = { ...filters, [columnId]: trimmed };
180
+ } else {
181
+ if (currentValue === void 0) {
182
+ return;
183
+ }
184
+ const next = { ...filters };
185
+ delete next[columnId];
186
+ filters = next;
187
+ }
188
+ emit();
189
+ },
190
+ clearFilters() {
191
+ if (Object.keys(filters).length === 0) {
192
+ return;
193
+ }
194
+ filters = {};
195
+ emit();
196
+ },
197
+ replaceFilters(nextFilters) {
198
+ const normalized = {};
199
+ for (const [columnId, value] of Object.entries(nextFilters)) {
200
+ const trimmed = value.trim();
201
+ if (trimmed) {
202
+ normalized[columnId] = trimmed;
203
+ }
204
+ }
205
+ if (filtersEqual(filters, normalized)) {
206
+ return;
207
+ }
208
+ filters = normalized;
209
+ emit();
210
+ },
211
+ selectRow(rowId) {
212
+ const currentRowId = selection.rowIds[0] ?? null;
213
+ if (currentRowId === rowId && selection.anchorRowId === rowId) {
214
+ return;
215
+ }
216
+ selection = rowId ? { rowIds: [rowId], anchorRowId: rowId } : { rowIds: [], anchorRowId: null };
217
+ emit();
218
+ },
219
+ setFocus(rowId, columnId) {
220
+ if (focus.rowId === rowId && focus.columnId === columnId) {
221
+ return;
222
+ }
223
+ focus = { rowId, columnId };
224
+ emit();
225
+ },
226
+ moveFocus(delta) {
227
+ const snapshot = getSnapshot();
228
+ const currentIndex = snapshot.visibleRows.findIndex((row) => row.id === focus.rowId);
229
+ if (snapshot.visibleRows.length === 0) {
230
+ focus = { rowId: null, columnId: focus.columnId };
231
+ emit();
232
+ return;
233
+ }
234
+ const nextIndex = currentIndex === -1 ? delta >= 0 ? 0 : snapshot.visibleRows.length - 1 : clamp(currentIndex + delta, 0, snapshot.visibleRows.length - 1);
235
+ const nextRow = snapshot.visibleRows[nextIndex];
236
+ if (!nextRow) {
237
+ return;
238
+ }
239
+ focus = { rowId: nextRow.id, columnId: focus.columnId };
240
+ emit();
241
+ },
242
+ setViewport(nextViewport) {
243
+ if (viewport.scrollTop === nextViewport.scrollTop && viewport.scrollLeft === nextViewport.scrollLeft && viewport.height === nextViewport.height && viewport.width === nextViewport.width) {
244
+ return;
245
+ }
246
+ viewport = nextViewport;
247
+ emit();
248
+ },
249
+ autosizeColumns(autosizeOptions) {
250
+ const nextOptions = applyAutosize(options, autosizeOptions);
251
+ if (nextOptions === options) {
252
+ return;
253
+ }
254
+ options = nextOptions;
255
+ emit();
256
+ },
257
+ applyTransaction(transaction) {
258
+ if (!options.getRowId) {
259
+ throw new Error("applyTransaction requires getRowId on GridCoreOptions");
260
+ }
261
+ const getRowId = options.getRowId;
262
+ if (transaction.remove) {
263
+ const removeSet = new Set(transaction.remove);
264
+ sourceRows = sourceRows.filter((entry) => {
265
+ if (removeSet.has(entry.id)) {
266
+ sourceRowIndex.delete(entry.id);
267
+ return false;
268
+ }
269
+ return true;
270
+ });
271
+ }
272
+ if (transaction.update) {
273
+ for (const patch of transaction.update) {
274
+ const id = getRowId(patch, -1);
275
+ const existing = sourceRowIndex.get(id);
276
+ if (!existing) {
277
+ continue;
278
+ }
279
+ const merged = { ...existing.row, ...patch };
280
+ const updated = {
281
+ id: existing.id,
282
+ row: merged,
283
+ sourceIndex: existing.sourceIndex
284
+ };
285
+ const arrayIndex = sourceRows.indexOf(existing);
286
+ if (arrayIndex !== -1) {
287
+ sourceRows[arrayIndex] = updated;
288
+ }
289
+ sourceRowIndex.set(id, updated);
290
+ }
291
+ }
292
+ if (transaction.add) {
293
+ for (const row of transaction.add) {
294
+ const id = getRowId(row, sourceRows.length);
295
+ const entry = {
296
+ id,
297
+ row,
298
+ sourceIndex: sourceRows.length
299
+ };
300
+ sourceRows.push(entry);
301
+ sourceRowIndex.set(id, entry);
302
+ }
303
+ }
304
+ cachedVisibleRows = null;
305
+ emit();
306
+ }
307
+ };
308
+ return store;
309
+ function getSnapshot() {
310
+ if (cachedSnapshot) {
311
+ return cachedSnapshot;
312
+ }
313
+ const visibleRows = cachedVisibleRows !== null && cachedDerivedSort === sort && cachedDerivedFilters === filters ? cachedVisibleRows : deriveVisibleRows({
314
+ columns: options.columns,
315
+ filters,
316
+ rows: sourceRows,
317
+ sort
318
+ });
319
+ cachedVisibleRows = visibleRows;
320
+ cachedDerivedSort = sort;
321
+ cachedDerivedFilters = filters;
322
+ cachedSnapshot = {
323
+ viewport,
324
+ sort,
325
+ filters: { ...filters },
326
+ selection: {
327
+ rowIds: [...selection.rowIds],
328
+ anchorRowId: selection.anchorRowId
329
+ },
330
+ focus,
331
+ totalRowCount: sourceRows.length,
332
+ visibleRows,
333
+ visibleRange: {
334
+ start: 0,
335
+ end: visibleRows.length
336
+ }
337
+ };
338
+ return cachedSnapshot;
339
+ }
340
+ function emit() {
341
+ cachedSnapshot = null;
342
+ for (const listener of listeners) {
343
+ listener();
344
+ }
345
+ }
346
+ }
347
+ function clamp(value, min, max) {
348
+ return Math.max(min, Math.min(max, value));
349
+ }
350
+ function filtersEqual(a, b) {
351
+ const aKeys = Object.keys(a);
352
+ const bKeys = Object.keys(b);
353
+ if (aKeys.length !== bKeys.length) {
354
+ return false;
355
+ }
356
+ for (const key of aKeys) {
357
+ if (a[key] !== b[key]) {
358
+ return false;
359
+ }
360
+ }
361
+ return true;
362
+ }
363
+
364
+ // src/create-grid.ts
365
+ function createGrid(options) {
366
+ const gridCore = createGridCore(options);
367
+ return {
368
+ kind: "pretable-grid",
369
+ get options() {
370
+ return gridCore.options;
371
+ },
372
+ subscribe: gridCore.subscribe,
373
+ getSnapshot: gridCore.getSnapshot,
374
+ setSort: gridCore.setSort,
375
+ setFilter: gridCore.setFilter,
376
+ clearFilters: gridCore.clearFilters,
377
+ replaceFilters: gridCore.replaceFilters,
378
+ selectRow: gridCore.selectRow,
379
+ setFocus: gridCore.setFocus,
380
+ moveFocus: gridCore.moveFocus,
381
+ setViewport: gridCore.setViewport,
382
+ autosizeColumns: gridCore.autosizeColumns,
383
+ applyTransaction: gridCore.applyTransaction
384
+ };
385
+ }
386
+
387
+ exports.createGrid = createGrid;
@@ -0,0 +1,100 @@
1
+ interface LayoutSpan {
2
+ start: number;
3
+ end: number;
4
+ }
5
+ interface AutosizeOptions {
6
+ maxWidthPx?: number;
7
+ minWidthPx?: number;
8
+ averageCharWidth?: number;
9
+ cellPaddingPx?: number;
10
+ }
11
+
12
+ type GridCoreRow = Record<string, unknown>;
13
+ type GridCoreSortDirection = "asc" | "desc" | null;
14
+ interface GridCoreColumn<TRow extends GridCoreRow = GridCoreRow> {
15
+ id: string;
16
+ header?: string;
17
+ wrap?: boolean;
18
+ widthPx?: number;
19
+ pinned?: "left";
20
+ sortable?: boolean;
21
+ filterable?: boolean;
22
+ getValue?: (row: TRow) => unknown;
23
+ }
24
+ interface GridCoreOptions<TRow extends GridCoreRow = GridCoreRow> {
25
+ columns: GridCoreColumn<TRow>[];
26
+ rows: TRow[];
27
+ getRowId?: (row: TRow, index: number) => string;
28
+ autosize?: boolean | AutosizeOptions;
29
+ }
30
+ interface GridCoreSortState {
31
+ columnId: string | null;
32
+ direction: GridCoreSortDirection;
33
+ }
34
+ interface GridCoreSelectionState {
35
+ rowIds: string[];
36
+ anchorRowId: string | null;
37
+ }
38
+ interface GridCoreFocusState {
39
+ rowId: string | null;
40
+ columnId: string | null;
41
+ }
42
+ interface GridCoreViewportState {
43
+ scrollTop: number;
44
+ scrollLeft: number;
45
+ height: number;
46
+ width: number;
47
+ }
48
+ interface GridCoreTransaction<TRow extends GridCoreRow = GridCoreRow> {
49
+ add?: TRow[];
50
+ update?: Partial<TRow>[];
51
+ remove?: string[];
52
+ }
53
+ interface GridCoreRowModel<TRow extends GridCoreRow = GridCoreRow> {
54
+ id: string;
55
+ row: TRow;
56
+ sourceIndex: number;
57
+ }
58
+ interface GridCoreSnapshot<TRow extends GridCoreRow = GridCoreRow> {
59
+ viewport: GridCoreViewportState;
60
+ sort: GridCoreSortState;
61
+ filters: Record<string, string>;
62
+ selection: GridCoreSelectionState;
63
+ focus: GridCoreFocusState;
64
+ totalRowCount: number;
65
+ visibleRows: GridCoreRowModel<TRow>[];
66
+ visibleRange: LayoutSpan;
67
+ }
68
+ interface GridCoreStore<TRow extends GridCoreRow = GridCoreRow> {
69
+ options: GridCoreOptions<TRow>;
70
+ subscribe(listener: () => void): () => void;
71
+ getSnapshot(): GridCoreSnapshot<TRow>;
72
+ setSort(columnId: string | null, direction: GridCoreSortDirection): void;
73
+ setFilter(columnId: string, value: string): void;
74
+ clearFilters(): void;
75
+ replaceFilters(nextFilters: Record<string, string>): void;
76
+ selectRow(rowId: string | null): void;
77
+ setFocus(rowId: string | null, columnId: string | null): void;
78
+ moveFocus(delta: number): void;
79
+ setViewport(viewport: GridCoreViewportState): void;
80
+ autosizeColumns(autosizeOptions?: AutosizeOptions): void;
81
+ applyTransaction(transaction: GridCoreTransaction<TRow>): void;
82
+ }
83
+
84
+ type PretableRow = Record<string, unknown>;
85
+
86
+ type PretableColumn<TRow extends PretableRow = PretableRow> = GridCoreColumn<TRow>;
87
+ type PretableGridOptions<TRow extends PretableRow = PretableRow> = GridCoreOptions<TRow>;
88
+ type PretableTransaction<TRow extends PretableRow = PretableRow> = GridCoreTransaction<TRow>;
89
+ interface PretableGrid<TRow extends PretableRow = PretableRow> extends Omit<GridCoreStore<TRow>, "options"> {
90
+ kind: "pretable-grid";
91
+ options: PretableGridOptions<TRow>;
92
+ getSnapshot(): GridCoreSnapshot<TRow>;
93
+ setSort(columnId: string | null, direction: GridCoreSortDirection): void;
94
+ autosizeColumns(options?: AutosizeOptions): void;
95
+ applyTransaction(transaction: PretableTransaction<TRow>): void;
96
+ }
97
+
98
+ declare function createGrid<TRow extends Record<string, unknown>>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
99
+
100
+ export { type AutosizeOptions, type PretableColumn, type GridCoreFocusState as PretableFocusState, type PretableGrid, type PretableGridOptions, type GridCoreSnapshot as PretableGridSnapshot, type PretableRow, type GridCoreSelectionState as PretableSelectionState, type GridCoreSortDirection as PretableSortDirection, type GridCoreSortState as PretableSortState, type PretableTransaction, type GridCoreViewportState as PretableViewportState, type GridCoreRowModel as PretableVisibleRow, createGrid };
@@ -0,0 +1,100 @@
1
+ interface LayoutSpan {
2
+ start: number;
3
+ end: number;
4
+ }
5
+ interface AutosizeOptions {
6
+ maxWidthPx?: number;
7
+ minWidthPx?: number;
8
+ averageCharWidth?: number;
9
+ cellPaddingPx?: number;
10
+ }
11
+
12
+ type GridCoreRow = Record<string, unknown>;
13
+ type GridCoreSortDirection = "asc" | "desc" | null;
14
+ interface GridCoreColumn<TRow extends GridCoreRow = GridCoreRow> {
15
+ id: string;
16
+ header?: string;
17
+ wrap?: boolean;
18
+ widthPx?: number;
19
+ pinned?: "left";
20
+ sortable?: boolean;
21
+ filterable?: boolean;
22
+ getValue?: (row: TRow) => unknown;
23
+ }
24
+ interface GridCoreOptions<TRow extends GridCoreRow = GridCoreRow> {
25
+ columns: GridCoreColumn<TRow>[];
26
+ rows: TRow[];
27
+ getRowId?: (row: TRow, index: number) => string;
28
+ autosize?: boolean | AutosizeOptions;
29
+ }
30
+ interface GridCoreSortState {
31
+ columnId: string | null;
32
+ direction: GridCoreSortDirection;
33
+ }
34
+ interface GridCoreSelectionState {
35
+ rowIds: string[];
36
+ anchorRowId: string | null;
37
+ }
38
+ interface GridCoreFocusState {
39
+ rowId: string | null;
40
+ columnId: string | null;
41
+ }
42
+ interface GridCoreViewportState {
43
+ scrollTop: number;
44
+ scrollLeft: number;
45
+ height: number;
46
+ width: number;
47
+ }
48
+ interface GridCoreTransaction<TRow extends GridCoreRow = GridCoreRow> {
49
+ add?: TRow[];
50
+ update?: Partial<TRow>[];
51
+ remove?: string[];
52
+ }
53
+ interface GridCoreRowModel<TRow extends GridCoreRow = GridCoreRow> {
54
+ id: string;
55
+ row: TRow;
56
+ sourceIndex: number;
57
+ }
58
+ interface GridCoreSnapshot<TRow extends GridCoreRow = GridCoreRow> {
59
+ viewport: GridCoreViewportState;
60
+ sort: GridCoreSortState;
61
+ filters: Record<string, string>;
62
+ selection: GridCoreSelectionState;
63
+ focus: GridCoreFocusState;
64
+ totalRowCount: number;
65
+ visibleRows: GridCoreRowModel<TRow>[];
66
+ visibleRange: LayoutSpan;
67
+ }
68
+ interface GridCoreStore<TRow extends GridCoreRow = GridCoreRow> {
69
+ options: GridCoreOptions<TRow>;
70
+ subscribe(listener: () => void): () => void;
71
+ getSnapshot(): GridCoreSnapshot<TRow>;
72
+ setSort(columnId: string | null, direction: GridCoreSortDirection): void;
73
+ setFilter(columnId: string, value: string): void;
74
+ clearFilters(): void;
75
+ replaceFilters(nextFilters: Record<string, string>): void;
76
+ selectRow(rowId: string | null): void;
77
+ setFocus(rowId: string | null, columnId: string | null): void;
78
+ moveFocus(delta: number): void;
79
+ setViewport(viewport: GridCoreViewportState): void;
80
+ autosizeColumns(autosizeOptions?: AutosizeOptions): void;
81
+ applyTransaction(transaction: GridCoreTransaction<TRow>): void;
82
+ }
83
+
84
+ type PretableRow = Record<string, unknown>;
85
+
86
+ type PretableColumn<TRow extends PretableRow = PretableRow> = GridCoreColumn<TRow>;
87
+ type PretableGridOptions<TRow extends PretableRow = PretableRow> = GridCoreOptions<TRow>;
88
+ type PretableTransaction<TRow extends PretableRow = PretableRow> = GridCoreTransaction<TRow>;
89
+ interface PretableGrid<TRow extends PretableRow = PretableRow> extends Omit<GridCoreStore<TRow>, "options"> {
90
+ kind: "pretable-grid";
91
+ options: PretableGridOptions<TRow>;
92
+ getSnapshot(): GridCoreSnapshot<TRow>;
93
+ setSort(columnId: string | null, direction: GridCoreSortDirection): void;
94
+ autosizeColumns(options?: AutosizeOptions): void;
95
+ applyTransaction(transaction: PretableTransaction<TRow>): void;
96
+ }
97
+
98
+ declare function createGrid<TRow extends Record<string, unknown>>(options: PretableGridOptions<TRow>): PretableGrid<TRow>;
99
+
100
+ export { type AutosizeOptions, type PretableColumn, type GridCoreFocusState as PretableFocusState, type PretableGrid, type PretableGridOptions, type GridCoreSnapshot as PretableGridSnapshot, type PretableRow, type GridCoreSelectionState as PretableSelectionState, type GridCoreSortDirection as PretableSortDirection, type GridCoreSortState as PretableSortState, type PretableTransaction, type GridCoreViewportState as PretableViewportState, type GridCoreRowModel as PretableVisibleRow, createGrid };
package/dist/index.mjs ADDED
@@ -0,0 +1,385 @@
1
+ // ../layout-core/dist/autosize-columns.js
2
+ var DEFAULT_MAX_WIDTH_PX = 400;
3
+ var DEFAULT_MIN_WIDTH_PX = 60;
4
+ var DEFAULT_AVERAGE_CHAR_WIDTH = 7;
5
+ var DEFAULT_CELL_PADDING_PX = 16;
6
+ function autosizeColumns(input) {
7
+ const maxWidthPx = input.options?.maxWidthPx ?? DEFAULT_MAX_WIDTH_PX;
8
+ const minWidthPx = input.options?.minWidthPx ?? DEFAULT_MIN_WIDTH_PX;
9
+ const averageCharWidth = input.options?.averageCharWidth ?? DEFAULT_AVERAGE_CHAR_WIDTH;
10
+ const cellPaddingPx = input.options?.cellPaddingPx ?? DEFAULT_CELL_PADDING_PX;
11
+ const widths = /* @__PURE__ */ new Map();
12
+ for (const column of input.columns) {
13
+ if (column.widthPx !== void 0) {
14
+ continue;
15
+ }
16
+ let maxContentWidth = 0;
17
+ if (column.header) {
18
+ const headerWidth = Array.from(column.header).length * averageCharWidth + cellPaddingPx;
19
+ maxContentWidth = Math.max(maxContentWidth, headerWidth);
20
+ }
21
+ for (const row of input.rows) {
22
+ const rawValue = column.getValue ? column.getValue(row) : row[column.id];
23
+ const text = String(rawValue ?? "");
24
+ if (text.length === 0) {
25
+ continue;
26
+ }
27
+ const contentWidth = Array.from(text).length * averageCharWidth + cellPaddingPx;
28
+ maxContentWidth = Math.max(maxContentWidth, contentWidth);
29
+ }
30
+ const clampedWidth = Math.max(minWidthPx, Math.min(maxWidthPx, maxContentWidth));
31
+ widths.set(column.id, clampedWidth);
32
+ }
33
+ return { widths };
34
+ }
35
+
36
+ // ../grid-core/dist/derived-rows.js
37
+ function createSourceRows(options) {
38
+ return options.rows.map((row, index) => ({
39
+ id: options.getRowId?.(row, index) ?? String(index),
40
+ row,
41
+ sourceIndex: index
42
+ }));
43
+ }
44
+ function deriveVisibleRows(input) {
45
+ const resolvedFilters = resolveFilters(input.columns, input.filters);
46
+ const filtered = input.rows.filter((entry) => matchesFilters(entry.row, resolvedFilters));
47
+ const sorted = sortRows(filtered, input.columns, input.sort);
48
+ return sorted.map(({ id, row, sourceIndex }) => ({
49
+ id,
50
+ row,
51
+ sourceIndex
52
+ }));
53
+ }
54
+ function resolveFilters(columns, filters) {
55
+ const columnMap = new Map(columns.map((c) => [c.id, c]));
56
+ const resolved = [];
57
+ for (const [columnId, rawNeedle] of Object.entries(filters)) {
58
+ if (!rawNeedle) {
59
+ continue;
60
+ }
61
+ const column = columnMap.get(columnId);
62
+ if (!column) {
63
+ continue;
64
+ }
65
+ resolved.push({ column, needle: rawNeedle.toLowerCase() });
66
+ }
67
+ return resolved;
68
+ }
69
+ function matchesFilters(row, resolvedFilters) {
70
+ for (const { column, needle } of resolvedFilters) {
71
+ const haystack = String(readCellValue(row, column)).toLowerCase();
72
+ if (!haystack.includes(needle)) {
73
+ return false;
74
+ }
75
+ }
76
+ return true;
77
+ }
78
+ var collator = new Intl.Collator(void 0, {
79
+ numeric: true,
80
+ sensitivity: "base"
81
+ });
82
+ function sortRows(rows, columns, sort) {
83
+ if (!sort.columnId || !sort.direction) {
84
+ return [...rows];
85
+ }
86
+ const column = columns.find((candidate) => candidate.id === sort.columnId);
87
+ if (!column) {
88
+ return [...rows];
89
+ }
90
+ const multiplier = sort.direction === "asc" ? 1 : -1;
91
+ const rawKeys = rows.map((entry) => readCellValue(entry.row, column));
92
+ const allNumeric = rawKeys.every((v) => typeof v === "number");
93
+ if (allNumeric) {
94
+ const numKeys = rawKeys;
95
+ const indexed2 = rows.map((_, i) => i);
96
+ indexed2.sort((a, b) => {
97
+ const diff = numKeys[a] - numKeys[b];
98
+ return diff !== 0 ? diff * multiplier : rows[a].sourceIndex - rows[b].sourceIndex;
99
+ });
100
+ return indexed2.map((i) => rows[i]);
101
+ }
102
+ const strKeys = rawKeys.map((v) => String(v ?? ""));
103
+ const indexed = rows.map((_, i) => i);
104
+ indexed.sort((a, b) => {
105
+ const comparison = collator.compare(strKeys[a], strKeys[b]);
106
+ return comparison !== 0 ? comparison * multiplier : rows[a].sourceIndex - rows[b].sourceIndex;
107
+ });
108
+ return indexed.map((i) => rows[i]);
109
+ }
110
+ function readCellValue(row, column) {
111
+ return column.getValue ? column.getValue(row) : row[column.id];
112
+ }
113
+
114
+ // ../grid-core/dist/create-grid-core.js
115
+ function applyAutosize(options, autosizeOptions) {
116
+ const result = autosizeColumns({
117
+ columns: options.columns,
118
+ rows: options.rows,
119
+ options: autosizeOptions
120
+ });
121
+ if (result.widths.size === 0) {
122
+ return options;
123
+ }
124
+ const nextColumns = options.columns.map((column) => {
125
+ const computedWidth = result.widths.get(column.id);
126
+ if (computedWidth === void 0) {
127
+ return column;
128
+ }
129
+ return { ...column, widthPx: computedWidth };
130
+ });
131
+ return { ...options, columns: nextColumns };
132
+ }
133
+ function createGridCore(inputOptions) {
134
+ const listeners = /* @__PURE__ */ new Set();
135
+ let options = inputOptions.autosize ? applyAutosize(inputOptions, typeof inputOptions.autosize === "object" ? inputOptions.autosize : void 0) : inputOptions;
136
+ let sourceRows = createSourceRows(options);
137
+ const sourceRowIndex = new Map(sourceRows.map((entry) => [entry.id, entry]));
138
+ let cachedSnapshot = null;
139
+ let cachedVisibleRows = null;
140
+ let cachedDerivedSort = null;
141
+ let cachedDerivedFilters = null;
142
+ let sort = { columnId: null, direction: null };
143
+ let filters = {};
144
+ let selection = { rowIds: [], anchorRowId: null };
145
+ let focus = { rowId: null, columnId: null };
146
+ let viewport = {
147
+ scrollTop: 0,
148
+ scrollLeft: 0,
149
+ height: 0,
150
+ width: 0
151
+ };
152
+ const store = {
153
+ get options() {
154
+ return options;
155
+ },
156
+ subscribe(listener) {
157
+ listeners.add(listener);
158
+ return () => {
159
+ listeners.delete(listener);
160
+ };
161
+ },
162
+ getSnapshot,
163
+ setSort(columnId, direction) {
164
+ if (sort.columnId === columnId && sort.direction === direction) {
165
+ return;
166
+ }
167
+ sort = { columnId, direction };
168
+ emit();
169
+ },
170
+ setFilter(columnId, value) {
171
+ const trimmed = value.trim();
172
+ const currentValue = filters[columnId];
173
+ if (trimmed) {
174
+ if (currentValue === trimmed) {
175
+ return;
176
+ }
177
+ filters = { ...filters, [columnId]: trimmed };
178
+ } else {
179
+ if (currentValue === void 0) {
180
+ return;
181
+ }
182
+ const next = { ...filters };
183
+ delete next[columnId];
184
+ filters = next;
185
+ }
186
+ emit();
187
+ },
188
+ clearFilters() {
189
+ if (Object.keys(filters).length === 0) {
190
+ return;
191
+ }
192
+ filters = {};
193
+ emit();
194
+ },
195
+ replaceFilters(nextFilters) {
196
+ const normalized = {};
197
+ for (const [columnId, value] of Object.entries(nextFilters)) {
198
+ const trimmed = value.trim();
199
+ if (trimmed) {
200
+ normalized[columnId] = trimmed;
201
+ }
202
+ }
203
+ if (filtersEqual(filters, normalized)) {
204
+ return;
205
+ }
206
+ filters = normalized;
207
+ emit();
208
+ },
209
+ selectRow(rowId) {
210
+ const currentRowId = selection.rowIds[0] ?? null;
211
+ if (currentRowId === rowId && selection.anchorRowId === rowId) {
212
+ return;
213
+ }
214
+ selection = rowId ? { rowIds: [rowId], anchorRowId: rowId } : { rowIds: [], anchorRowId: null };
215
+ emit();
216
+ },
217
+ setFocus(rowId, columnId) {
218
+ if (focus.rowId === rowId && focus.columnId === columnId) {
219
+ return;
220
+ }
221
+ focus = { rowId, columnId };
222
+ emit();
223
+ },
224
+ moveFocus(delta) {
225
+ const snapshot = getSnapshot();
226
+ const currentIndex = snapshot.visibleRows.findIndex((row) => row.id === focus.rowId);
227
+ if (snapshot.visibleRows.length === 0) {
228
+ focus = { rowId: null, columnId: focus.columnId };
229
+ emit();
230
+ return;
231
+ }
232
+ const nextIndex = currentIndex === -1 ? delta >= 0 ? 0 : snapshot.visibleRows.length - 1 : clamp(currentIndex + delta, 0, snapshot.visibleRows.length - 1);
233
+ const nextRow = snapshot.visibleRows[nextIndex];
234
+ if (!nextRow) {
235
+ return;
236
+ }
237
+ focus = { rowId: nextRow.id, columnId: focus.columnId };
238
+ emit();
239
+ },
240
+ setViewport(nextViewport) {
241
+ if (viewport.scrollTop === nextViewport.scrollTop && viewport.scrollLeft === nextViewport.scrollLeft && viewport.height === nextViewport.height && viewport.width === nextViewport.width) {
242
+ return;
243
+ }
244
+ viewport = nextViewport;
245
+ emit();
246
+ },
247
+ autosizeColumns(autosizeOptions) {
248
+ const nextOptions = applyAutosize(options, autosizeOptions);
249
+ if (nextOptions === options) {
250
+ return;
251
+ }
252
+ options = nextOptions;
253
+ emit();
254
+ },
255
+ applyTransaction(transaction) {
256
+ if (!options.getRowId) {
257
+ throw new Error("applyTransaction requires getRowId on GridCoreOptions");
258
+ }
259
+ const getRowId = options.getRowId;
260
+ if (transaction.remove) {
261
+ const removeSet = new Set(transaction.remove);
262
+ sourceRows = sourceRows.filter((entry) => {
263
+ if (removeSet.has(entry.id)) {
264
+ sourceRowIndex.delete(entry.id);
265
+ return false;
266
+ }
267
+ return true;
268
+ });
269
+ }
270
+ if (transaction.update) {
271
+ for (const patch of transaction.update) {
272
+ const id = getRowId(patch, -1);
273
+ const existing = sourceRowIndex.get(id);
274
+ if (!existing) {
275
+ continue;
276
+ }
277
+ const merged = { ...existing.row, ...patch };
278
+ const updated = {
279
+ id: existing.id,
280
+ row: merged,
281
+ sourceIndex: existing.sourceIndex
282
+ };
283
+ const arrayIndex = sourceRows.indexOf(existing);
284
+ if (arrayIndex !== -1) {
285
+ sourceRows[arrayIndex] = updated;
286
+ }
287
+ sourceRowIndex.set(id, updated);
288
+ }
289
+ }
290
+ if (transaction.add) {
291
+ for (const row of transaction.add) {
292
+ const id = getRowId(row, sourceRows.length);
293
+ const entry = {
294
+ id,
295
+ row,
296
+ sourceIndex: sourceRows.length
297
+ };
298
+ sourceRows.push(entry);
299
+ sourceRowIndex.set(id, entry);
300
+ }
301
+ }
302
+ cachedVisibleRows = null;
303
+ emit();
304
+ }
305
+ };
306
+ return store;
307
+ function getSnapshot() {
308
+ if (cachedSnapshot) {
309
+ return cachedSnapshot;
310
+ }
311
+ const visibleRows = cachedVisibleRows !== null && cachedDerivedSort === sort && cachedDerivedFilters === filters ? cachedVisibleRows : deriveVisibleRows({
312
+ columns: options.columns,
313
+ filters,
314
+ rows: sourceRows,
315
+ sort
316
+ });
317
+ cachedVisibleRows = visibleRows;
318
+ cachedDerivedSort = sort;
319
+ cachedDerivedFilters = filters;
320
+ cachedSnapshot = {
321
+ viewport,
322
+ sort,
323
+ filters: { ...filters },
324
+ selection: {
325
+ rowIds: [...selection.rowIds],
326
+ anchorRowId: selection.anchorRowId
327
+ },
328
+ focus,
329
+ totalRowCount: sourceRows.length,
330
+ visibleRows,
331
+ visibleRange: {
332
+ start: 0,
333
+ end: visibleRows.length
334
+ }
335
+ };
336
+ return cachedSnapshot;
337
+ }
338
+ function emit() {
339
+ cachedSnapshot = null;
340
+ for (const listener of listeners) {
341
+ listener();
342
+ }
343
+ }
344
+ }
345
+ function clamp(value, min, max) {
346
+ return Math.max(min, Math.min(max, value));
347
+ }
348
+ function filtersEqual(a, b) {
349
+ const aKeys = Object.keys(a);
350
+ const bKeys = Object.keys(b);
351
+ if (aKeys.length !== bKeys.length) {
352
+ return false;
353
+ }
354
+ for (const key of aKeys) {
355
+ if (a[key] !== b[key]) {
356
+ return false;
357
+ }
358
+ }
359
+ return true;
360
+ }
361
+
362
+ // src/create-grid.ts
363
+ function createGrid(options) {
364
+ const gridCore = createGridCore(options);
365
+ return {
366
+ kind: "pretable-grid",
367
+ get options() {
368
+ return gridCore.options;
369
+ },
370
+ subscribe: gridCore.subscribe,
371
+ getSnapshot: gridCore.getSnapshot,
372
+ setSort: gridCore.setSort,
373
+ setFilter: gridCore.setFilter,
374
+ clearFilters: gridCore.clearFilters,
375
+ replaceFilters: gridCore.replaceFilters,
376
+ selectRow: gridCore.selectRow,
377
+ setFocus: gridCore.setFocus,
378
+ moveFocus: gridCore.moveFocus,
379
+ setViewport: gridCore.setViewport,
380
+ autosizeColumns: gridCore.autosizeColumns,
381
+ applyTransaction: gridCore.applyTransaction
382
+ };
383
+ }
384
+
385
+ export { createGrid };
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@pretable/core",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "files": [
6
+ "dist"
7
+ ],
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.mjs",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "default": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "sideEffects": false,
25
+ "devDependencies": {
26
+ "@pretable-internal/grid-core": "0.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "pnpm --filter @pretable-internal/grid-core build && tsup",
30
+ "lint": "eslint src --ext .ts",
31
+ "lint:packaging": "publint --strict && attw --pack",
32
+ "test": "pnpm --filter @pretable-internal/grid-core build && vitest run",
33
+ "typecheck": "pnpm --filter @pretable-internal/grid-core build && tsc -p tsconfig.json --noEmit"
34
+ }
35
+ }