@stacksjs/components 0.2.854 → 0.2.857

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/CodeEditor-jg4w7e15.stx +497 -0
  2. package/dist/ContextMenu-43g3w5tp.stx +188 -0
  3. package/dist/DataGrid-7rt7v865.stx +376 -0
  4. package/dist/GraphView-0t3t9mec.stx +320 -0
  5. package/dist/JsonTree-satc4010.stx +317 -0
  6. package/dist/PreviewFrame-erbgvzj8.stx +257 -0
  7. package/dist/SplitPane-7sqfdwqa.stx +159 -0
  8. package/dist/code-editor/editor.js +2166 -0
  9. package/dist/component-api/component-api.js +36 -0
  10. package/dist/components/CodeBlock.d.ts +12 -5
  11. package/dist/context-menu/context-menu.js +575 -0
  12. package/dist/data-grid/data-grid.js +1244 -0
  13. package/dist/graph-view/graph-view.js +1408 -0
  14. package/dist/index.d.ts +10 -0
  15. package/dist/index.js +34 -15
  16. package/dist/json-tree/json-tree.js +1121 -0
  17. package/dist/preview-frame/preview-frame.js +356 -0
  18. package/dist/split-pane/split-pane.js +364 -0
  19. package/dist/ui/code-editor/CodeEditor.d.ts +46 -0
  20. package/dist/ui/code-editor/controller.d.ts +103 -0
  21. package/dist/ui/code-editor/core/commands.d.ts +55 -0
  22. package/dist/ui/code-editor/core/completion.d.ts +40 -0
  23. package/dist/ui/code-editor/core/editor.d.ts +69 -0
  24. package/dist/ui/code-editor/core/highlight.d.ts +61 -0
  25. package/dist/ui/code-editor/core/history.d.ts +27 -0
  26. package/dist/ui/code-editor/core/index.d.ts +13 -0
  27. package/dist/ui/code-editor/core/keymap.d.ts +38 -0
  28. package/dist/ui/code-editor/core/selection.d.ts +30 -0
  29. package/dist/ui/code-editor/core/text.d.ts +64 -0
  30. package/dist/ui/code-editor/editor.d.ts +15 -0
  31. package/dist/ui/code-editor/index.d.ts +29 -0
  32. package/dist/ui/code-editor/tokenizer.d.ts +18 -0
  33. package/dist/ui/code-editor/view.d.ts +59 -0
  34. package/dist/ui/context-menu/ContextMenu.d.ts +14 -0
  35. package/dist/ui/context-menu/context-menu.d.ts +8 -0
  36. package/dist/ui/context-menu/core.d.ts +74 -0
  37. package/dist/ui/context-menu/index.d.ts +11 -0
  38. package/dist/ui/context-menu/view.d.ts +36 -0
  39. package/dist/ui/data-grid/DataGrid.d.ts +30 -0
  40. package/dist/ui/data-grid/core.d.ts +141 -0
  41. package/dist/ui/data-grid/data-grid.d.ts +9 -0
  42. package/dist/ui/data-grid/index.d.ts +20 -0
  43. package/dist/ui/data-grid/view.d.ts +56 -0
  44. package/dist/ui/graph-view/GraphView.d.ts +21 -0
  45. package/dist/ui/graph-view/core/edges.d.ts +34 -0
  46. package/dist/ui/graph-view/core/force.d.ts +10 -0
  47. package/dist/ui/graph-view/core/graph.d.ts +83 -0
  48. package/dist/ui/graph-view/core/index.d.ts +5 -0
  49. package/dist/ui/graph-view/core/layered.d.ts +24 -0
  50. package/dist/ui/graph-view/core/viewport.d.ts +34 -0
  51. package/dist/ui/graph-view/graph-view.d.ts +9 -0
  52. package/dist/ui/graph-view/index.d.ts +21 -0
  53. package/dist/ui/graph-view/view.d.ts +51 -0
  54. package/dist/ui/json-tree/JsonTree.d.ts +18 -0
  55. package/dist/ui/json-tree/core.d.ts +108 -0
  56. package/dist/ui/json-tree/index.d.ts +18 -0
  57. package/dist/ui/json-tree/json-tree.d.ts +10 -0
  58. package/dist/ui/json-tree/tinker.d.ts +84 -0
  59. package/dist/ui/json-tree/view.d.ts +59 -0
  60. package/dist/ui/preview-frame/PreviewFrame.d.ts +44 -0
  61. package/dist/ui/preview-frame/core.d.ts +81 -0
  62. package/dist/ui/preview-frame/index.d.ts +19 -0
  63. package/dist/ui/preview-frame/preview-frame.d.ts +8 -0
  64. package/dist/ui/preview-frame/view.d.ts +37 -0
  65. package/dist/ui/split-pane/SplitPane.d.ts +18 -0
  66. package/dist/ui/split-pane/core.d.ts +58 -0
  67. package/dist/ui/split-pane/index.d.ts +15 -0
  68. package/dist/ui/split-pane/split-pane.d.ts +8 -0
  69. package/dist/ui/split-pane/view.d.ts +27 -0
  70. package/dist/ui/virtual-table/index.d.ts +6 -0
  71. package/dist/utils/component-api.d.ts +4 -0
  72. package/dist/utils/highlighter.d.ts +19 -1
  73. package/dist/utils/highlighter.js +24 -7
  74. package/dist/utils/syntax-theme.d.ts +44 -0
  75. package/package.json +44 -4
  76. package/src/components/CodeBlock.stx +195 -17
  77. package/src/index.ts +10 -0
  78. package/src/ui/code-editor/CodeEditor.stx +497 -0
  79. package/src/ui/code-editor/README.md +135 -0
  80. package/src/ui/code-editor/controller.ts +517 -0
  81. package/src/ui/code-editor/core/commands.ts +381 -0
  82. package/src/ui/code-editor/core/completion.ts +212 -0
  83. package/src/ui/code-editor/core/editor.ts +319 -0
  84. package/src/ui/code-editor/core/highlight.ts +203 -0
  85. package/src/ui/code-editor/core/history.ts +190 -0
  86. package/src/ui/code-editor/core/index.ts +14 -0
  87. package/src/ui/code-editor/core/keymap.ts +125 -0
  88. package/src/ui/code-editor/core/selection.ts +104 -0
  89. package/src/ui/code-editor/core/text.ts +252 -0
  90. package/src/ui/code-editor/editor.ts +16 -0
  91. package/src/ui/code-editor/index.ts +46 -0
  92. package/src/ui/code-editor/tokenizer.ts +74 -0
  93. package/src/ui/code-editor/view.ts +1066 -0
  94. package/src/ui/context-menu/ContextMenu.stx +188 -0
  95. package/src/ui/context-menu/README.md +117 -0
  96. package/src/ui/context-menu/context-menu.ts +8 -0
  97. package/src/ui/context-menu/core.ts +250 -0
  98. package/src/ui/context-menu/index.ts +16 -0
  99. package/src/ui/context-menu/view.ts +540 -0
  100. package/src/ui/data-grid/DataGrid.stx +376 -0
  101. package/src/ui/data-grid/README.md +204 -0
  102. package/src/ui/data-grid/core.ts +813 -0
  103. package/src/ui/data-grid/data-grid.ts +9 -0
  104. package/src/ui/data-grid/index.ts +34 -0
  105. package/src/ui/data-grid/view.ts +806 -0
  106. package/src/ui/graph-view/GraphView.stx +320 -0
  107. package/src/ui/graph-view/README.md +210 -0
  108. package/src/ui/graph-view/core/edges.ts +180 -0
  109. package/src/ui/graph-view/core/force.ts +237 -0
  110. package/src/ui/graph-view/core/graph.ts +277 -0
  111. package/src/ui/graph-view/core/index.ts +5 -0
  112. package/src/ui/graph-view/core/layered.ts +256 -0
  113. package/src/ui/graph-view/core/viewport.ts +141 -0
  114. package/src/ui/graph-view/graph-view.ts +9 -0
  115. package/src/ui/graph-view/index.ts +35 -0
  116. package/src/ui/graph-view/view.ts +809 -0
  117. package/src/ui/json-tree/JsonTree.stx +317 -0
  118. package/src/ui/json-tree/README.md +193 -0
  119. package/src/ui/json-tree/core.ts +588 -0
  120. package/src/ui/json-tree/index.ts +28 -0
  121. package/src/ui/json-tree/json-tree.ts +10 -0
  122. package/src/ui/json-tree/tinker.ts +349 -0
  123. package/src/ui/json-tree/view.ts +665 -0
  124. package/src/ui/preview-frame/PreviewFrame.stx +257 -0
  125. package/src/ui/preview-frame/README.md +107 -0
  126. package/src/ui/preview-frame/core.ts +195 -0
  127. package/src/ui/preview-frame/index.ts +31 -0
  128. package/src/ui/preview-frame/preview-frame.ts +8 -0
  129. package/src/ui/preview-frame/view.ts +336 -0
  130. package/src/ui/split-pane/README.md +87 -0
  131. package/src/ui/split-pane/SplitPane.stx +159 -0
  132. package/src/ui/split-pane/core.ts +200 -0
  133. package/src/ui/split-pane/index.ts +24 -0
  134. package/src/ui/split-pane/split-pane.ts +8 -0
  135. package/src/ui/split-pane/view.ts +305 -0
  136. package/src/ui/virtual-table/index.ts +6 -0
  137. package/src/utils/component-api.ts +72 -0
  138. package/src/utils/highlighter.ts +121 -218
  139. package/src/utils/syntax-theme.ts +144 -0
@@ -0,0 +1,1244 @@
1
+ // src/ui/data-grid/core.ts
2
+ var DEFAULT_MIN_WIDTH = 48;
3
+ var DEFAULT_MAX_WIDTH = 2000;
4
+ var FIT_MAX_WIDTH = 420;
5
+ var JSON_PREVIEW_LENGTH = 160;
6
+ var NUMERIC = /^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
7
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
8
+ function stringify(value, indent) {
9
+ const seen = new WeakSet;
10
+ const text = JSON.stringify(value, (_key, entry) => {
11
+ if (typeof entry === "bigint")
12
+ return entry.toString();
13
+ if (typeof entry === "object" && entry !== null) {
14
+ if (seen.has(entry))
15
+ return "[Circular]";
16
+ seen.add(entry);
17
+ }
18
+ return entry;
19
+ }, indent);
20
+ return text === undefined ? "null" : text;
21
+ }
22
+ function cellValue(row, column) {
23
+ if (column.accessor)
24
+ return column.accessor(row);
25
+ return row == null ? undefined : row[column.key];
26
+ }
27
+ function inferType(values) {
28
+ let seen = 0;
29
+ let numbers = 0;
30
+ let dates = 0;
31
+ let booleans = 0;
32
+ let objects = 0;
33
+ for (const value of values) {
34
+ if (value === null || value === undefined || value === "")
35
+ continue;
36
+ seen++;
37
+ if (typeof value === "number" || typeof value === "bigint")
38
+ numbers++;
39
+ else if (typeof value === "boolean")
40
+ booleans++;
41
+ else if (value instanceof Date)
42
+ dates++;
43
+ else if (typeof value === "object")
44
+ objects++;
45
+ else if (typeof value === "string") {
46
+ const text = value.trim();
47
+ if (NUMERIC.test(text))
48
+ numbers++;
49
+ else if (ISO_DATE.test(text) && !Number.isNaN(Date.parse(text)))
50
+ dates++;
51
+ }
52
+ }
53
+ if (seen === 0)
54
+ return "string";
55
+ if (numbers === seen)
56
+ return "number";
57
+ if (dates === seen)
58
+ return "date";
59
+ if (booleans === seen)
60
+ return "boolean";
61
+ if (objects === seen)
62
+ return "json";
63
+ return "string";
64
+ }
65
+ function inferColumns(rows, sample = 200) {
66
+ const keys = [];
67
+ const known = new Set;
68
+ const limit = Math.min(rows.length, sample);
69
+ for (let index = 0;index < limit; index++) {
70
+ const row = rows[index];
71
+ if (row === null || typeof row !== "object")
72
+ continue;
73
+ if (Array.isArray(row)) {
74
+ for (let position = 0;position < row.length; position++) {
75
+ const key = String(position);
76
+ if (!known.has(key)) {
77
+ known.add(key);
78
+ keys.push(key);
79
+ }
80
+ }
81
+ continue;
82
+ }
83
+ for (const key in row) {
84
+ if (!known.has(key)) {
85
+ known.add(key);
86
+ keys.push(key);
87
+ }
88
+ }
89
+ }
90
+ if (keys.length > 0 && keys.every((key) => /^\d+$/.test(key)))
91
+ keys.sort((a, b) => Number(a) - Number(b));
92
+ return keys.map((key) => ({ key }));
93
+ }
94
+ function cellKind(value) {
95
+ if (value === null)
96
+ return "null";
97
+ return value === undefined ? "undefined" : "value";
98
+ }
99
+ function formatCell(value, type = "string") {
100
+ if (value === null)
101
+ return "null";
102
+ if (value === undefined)
103
+ return "undefined";
104
+ if (typeof value === "string")
105
+ return value;
106
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint")
107
+ return String(value);
108
+ if (value instanceof Date)
109
+ return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
110
+ if (typeof value === "object" || type === "json") {
111
+ const text = stringify(value);
112
+ return text.length > JSON_PREVIEW_LENGTH ? `${text.slice(0, JSON_PREVIEW_LENGTH)}...` : text;
113
+ }
114
+ return String(value);
115
+ }
116
+ function cellJson(value) {
117
+ return stringify(value);
118
+ }
119
+ function projectRow(row, columns) {
120
+ const out = {};
121
+ for (const column of columns) {
122
+ const value = cellValue(row, column);
123
+ out[column.key] = value === undefined ? null : value;
124
+ }
125
+ return out;
126
+ }
127
+ function rowJson(row, columns) {
128
+ return stringify(projectRow(row, columns), 2);
129
+ }
130
+ function toJson(rows, columns) {
131
+ return stringify(rows.map((row) => projectRow(row, columns)), 2);
132
+ }
133
+ function csvField(value) {
134
+ if (value === null || value === undefined)
135
+ return "";
136
+ let text;
137
+ if (typeof value === "string")
138
+ text = value;
139
+ else if (value instanceof Date)
140
+ text = Number.isNaN(value.getTime()) ? "" : value.toISOString();
141
+ else if (typeof value === "object")
142
+ text = stringify(value);
143
+ else
144
+ text = String(value);
145
+ if (/[",\r\n]/.test(text) || text !== text.trim())
146
+ return `"${text.replace(/"/g, '""')}"`;
147
+ return text;
148
+ }
149
+ function toCsv(rows, columns) {
150
+ const lines = Array.from({ length: rows.length + 1 });
151
+ lines[0] = columns.map((column) => csvField(column.label ?? column.key)).join(",");
152
+ const count = columns.length;
153
+ for (let index = 0;index < rows.length; index++) {
154
+ const row = rows[index];
155
+ let line = "";
156
+ for (let position = 0;position < count; position++) {
157
+ if (position > 0)
158
+ line += ",";
159
+ line += csvField(cellValue(row, columns[position]));
160
+ }
161
+ lines[index + 1] = line;
162
+ }
163
+ return `${lines.join(`\r
164
+ `)}\r
165
+ `;
166
+ }
167
+ function rowRange(scroll, viewport, rowHeight, count, overscan = 0) {
168
+ if (count <= 0 || rowHeight <= 0)
169
+ return { start: 0, end: 0 };
170
+ const first = Math.floor(Math.max(0, scroll) / rowHeight);
171
+ const last = Math.ceil((Math.max(0, scroll) + Math.max(0, viewport)) / rowHeight);
172
+ const start = Math.min(count, Math.max(0, first - overscan));
173
+ return { start, end: Math.max(start, Math.min(count, last + overscan)) };
174
+ }
175
+ function moveCell(cell, key, bounds) {
176
+ const lastRow = bounds.rows - 1;
177
+ const lastColumn = Math.max(0, bounds.columns - 1);
178
+ const page = Math.max(1, bounds.page);
179
+ let { row, column } = cell;
180
+ switch (key) {
181
+ case "ArrowUp":
182
+ row = Math.max(-1, row - 1);
183
+ break;
184
+ case "ArrowDown":
185
+ row = Math.min(lastRow, row + 1);
186
+ break;
187
+ case "ArrowLeft":
188
+ column -= 1;
189
+ break;
190
+ case "ArrowRight":
191
+ column += 1;
192
+ break;
193
+ case "PageUp":
194
+ row = row <= 0 ? row : Math.max(0, row - page);
195
+ break;
196
+ case "PageDown":
197
+ row = Math.min(lastRow, Math.max(0, row) + (row < 0 ? 0 : page));
198
+ break;
199
+ case "Home":
200
+ column = 0;
201
+ if (bounds.mod)
202
+ row = Math.min(0, lastRow);
203
+ break;
204
+ case "End":
205
+ column = lastColumn;
206
+ if (bounds.mod)
207
+ row = lastRow;
208
+ break;
209
+ default:
210
+ return cell;
211
+ }
212
+ return { row: Math.max(-1, Math.min(lastRow, row)), column: Math.max(0, Math.min(lastColumn, column)) };
213
+ }
214
+ function cycleSort(sort, key, additive = false) {
215
+ const current = sort.find((entry) => entry.key === key);
216
+ const next = !current ? { key, direction: "asc" } : current.direction === "asc" ? { key, direction: "desc" } : null;
217
+ if (!additive)
218
+ return next ? [next] : [];
219
+ if (!current)
220
+ return [...sort, next];
221
+ return next ? sort.map((entry) => entry.key === key ? next : entry) : sort.filter((entry) => entry.key !== key);
222
+ }
223
+ var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
224
+
225
+ class GridModel {
226
+ rows = [];
227
+ columns = [];
228
+ view = new Uint32Array(0);
229
+ sort = [];
230
+ filter = "";
231
+ selected = new Set;
232
+ given = null;
233
+ filtered = new Uint32Array(0);
234
+ searchText = null;
235
+ sortKeys = new Map;
236
+ offsets = new Float64Array(1);
237
+ anchor = -1;
238
+ charWidth;
239
+ cellPadding;
240
+ constructor(rows = [], columns = null, options = {}) {
241
+ this.charWidth = options.charWidth ?? 7.25;
242
+ this.cellPadding = options.cellPadding ?? 24;
243
+ this.given = columns && columns.length > 0 ? [...columns] : null;
244
+ this.setRows(rows);
245
+ }
246
+ get count() {
247
+ return this.view.length;
248
+ }
249
+ get totalWidth() {
250
+ return this.offsets[this.columns.length];
251
+ }
252
+ setRows(rows) {
253
+ this.rows = Array.isArray(rows) ? rows : [];
254
+ this.selected.clear();
255
+ this.anchor = -1;
256
+ this.forget();
257
+ this.resolveColumns();
258
+ this.refilter();
259
+ }
260
+ setColumns(columns) {
261
+ this.given = columns && columns.length > 0 ? [...columns] : null;
262
+ this.forget();
263
+ this.resolveColumns();
264
+ this.sort = this.sort.filter((entry) => this.columns.some((column) => column.key === entry.key));
265
+ this.refilter();
266
+ }
267
+ setFilter(text) {
268
+ this.filter = text == null ? "" : String(text);
269
+ this.refilter();
270
+ return this.count;
271
+ }
272
+ setSort(sort) {
273
+ this.sort = (sort ?? []).filter((entry) => entry && (entry.direction === "asc" || entry.direction === "desc") && this.columns.some((column) => column.key === entry.key));
274
+ this.resort();
275
+ }
276
+ toggleSort(key, additive = false) {
277
+ const column = this.columns.find((entry) => entry.key === key);
278
+ if (!column || !column.sortable)
279
+ return this.sort;
280
+ this.sort = cycleSort(this.sort, key, additive);
281
+ this.resort();
282
+ return this.sort;
283
+ }
284
+ sortOf(key) {
285
+ const index = this.sort.findIndex((entry) => entry.key === key);
286
+ return index < 0 ? null : { direction: this.sort[index].direction, priority: index + 1 };
287
+ }
288
+ rowAt(viewIndex) {
289
+ return viewIndex >= 0 && viewIndex < this.view.length ? this.rows[this.view[viewIndex]] : undefined;
290
+ }
291
+ valueAt(viewIndex, columnIndex) {
292
+ const column = this.columns[columnIndex];
293
+ const row = this.rowAt(viewIndex);
294
+ return column && row !== undefined ? cellValue(row, column) : undefined;
295
+ }
296
+ viewRows() {
297
+ const out = Array.from({ length: this.view.length });
298
+ for (let index = 0;index < out.length; index++)
299
+ out[index] = this.rows[this.view[index]];
300
+ return out;
301
+ }
302
+ toCsv() {
303
+ return toCsv(this.viewRows(), this.columns);
304
+ }
305
+ toJson() {
306
+ return toJson(this.viewRows(), this.columns);
307
+ }
308
+ select(viewIndex, mode = "replace") {
309
+ if (viewIndex < 0 || viewIndex >= this.view.length)
310
+ return;
311
+ const source = this.view[viewIndex];
312
+ if (mode === "range" && this.anchor >= 0) {
313
+ const from = Math.min(this.anchor, viewIndex);
314
+ const to = Math.max(this.anchor, viewIndex);
315
+ this.selected.clear();
316
+ for (let index = from;index <= to && index < this.view.length; index++)
317
+ this.selected.add(this.view[index]);
318
+ return;
319
+ }
320
+ if (mode === "toggle") {
321
+ if (this.selected.has(source))
322
+ this.selected.delete(source);
323
+ else
324
+ this.selected.add(source);
325
+ } else {
326
+ this.selected.clear();
327
+ this.selected.add(source);
328
+ }
329
+ this.anchor = viewIndex;
330
+ }
331
+ selectAll() {
332
+ this.selected.clear();
333
+ for (let index = 0;index < this.view.length; index++)
334
+ this.selected.add(this.view[index]);
335
+ }
336
+ clearSelection() {
337
+ this.selected.clear();
338
+ this.anchor = -1;
339
+ }
340
+ isSelected(viewIndex) {
341
+ return viewIndex >= 0 && viewIndex < this.view.length && this.selected.has(this.view[viewIndex]);
342
+ }
343
+ selectedIndices() {
344
+ return [...this.selected].sort((a, b) => a - b);
345
+ }
346
+ selectedRows() {
347
+ return this.selectedIndices().map((index) => this.rows[index]);
348
+ }
349
+ offsetOf(columnIndex) {
350
+ return this.offsets[Math.max(0, Math.min(this.columns.length, columnIndex))];
351
+ }
352
+ columnAt(x) {
353
+ const count = this.columns.length;
354
+ if (count === 0)
355
+ return -1;
356
+ let low = 0;
357
+ let high = count - 1;
358
+ while (low < high) {
359
+ const middle = low + high + 1 >> 1;
360
+ if (this.offsets[middle] <= x)
361
+ low = middle;
362
+ else
363
+ high = middle - 1;
364
+ }
365
+ return low;
366
+ }
367
+ columnRange(scrollLeft, viewportWidth, overscan = 0) {
368
+ const count = this.columns.length;
369
+ if (count === 0)
370
+ return { start: 0, end: 0 };
371
+ const first = this.columnAt(Math.max(0, scrollLeft));
372
+ const last = this.columnAt(Math.max(0, scrollLeft) + Math.max(0, viewportWidth));
373
+ return { start: Math.max(0, first - overscan), end: Math.min(count, last + 1 + overscan) };
374
+ }
375
+ resizeColumn(columnIndex, width) {
376
+ const column = this.columns[columnIndex];
377
+ if (!column)
378
+ return 0;
379
+ column.width = Math.round(Math.max(column.minWidth, Math.min(column.maxWidth, width)));
380
+ this.measure();
381
+ return column.width;
382
+ }
383
+ autoWidth(columnIndex, sample = 200) {
384
+ const column = this.columns[columnIndex];
385
+ if (!column)
386
+ return 0;
387
+ let longest = column.label.length + 3;
388
+ const limit = Math.min(this.view.length, sample);
389
+ for (let index = 0;index < limit; index++) {
390
+ const length = formatCell(cellValue(this.rows[this.view[index]], column), column.type).length;
391
+ if (length > longest)
392
+ longest = length;
393
+ }
394
+ const width = Math.ceil(longest * this.charWidth + this.cellPadding);
395
+ return Math.max(column.minWidth, Math.min(column.maxWidth, FIT_MAX_WIDTH, width));
396
+ }
397
+ forget() {
398
+ this.searchText = null;
399
+ this.sortKeys.clear();
400
+ }
401
+ resolveColumns() {
402
+ const source = this.given ?? inferColumns(this.rows);
403
+ const sample = Math.min(this.rows.length, 200);
404
+ const previous = this.view;
405
+ this.view = new Uint32Array(sample);
406
+ for (let index = 0;index < sample; index++)
407
+ this.view[index] = index;
408
+ this.columns = source.map((column) => {
409
+ let type = column.type;
410
+ if (!type) {
411
+ const values = [];
412
+ for (let index = 0;index < sample; index++)
413
+ values.push(cellValue(this.rows[index], column));
414
+ type = inferType(values);
415
+ }
416
+ return {
417
+ ...column,
418
+ label: column.label ?? column.key,
419
+ type,
420
+ width: column.width ?? 0,
421
+ minWidth: column.minWidth ?? DEFAULT_MIN_WIDTH,
422
+ maxWidth: column.maxWidth ?? DEFAULT_MAX_WIDTH,
423
+ align: column.align ?? (type === "number" ? "right" : "left"),
424
+ sortable: column.sortable !== false
425
+ };
426
+ });
427
+ this.columns.forEach((column, index) => {
428
+ if (!column.width)
429
+ column.width = this.autoWidth(index);
430
+ column.width = Math.max(column.minWidth, Math.min(column.maxWidth, column.width));
431
+ });
432
+ this.view = previous;
433
+ this.measure();
434
+ }
435
+ measure() {
436
+ const offsets = new Float64Array(this.columns.length + 1);
437
+ for (let index = 0;index < this.columns.length; index++)
438
+ offsets[index + 1] = offsets[index] + this.columns[index].width;
439
+ this.offsets = offsets;
440
+ }
441
+ searchable() {
442
+ if (this.searchText)
443
+ return this.searchText;
444
+ const rows = this.rows;
445
+ const columns = this.columns;
446
+ const text = Array.from({ length: rows.length });
447
+ for (let index = 0;index < rows.length; index++) {
448
+ const row = rows[index];
449
+ let line = "";
450
+ for (let position = 0;position < columns.length; position++) {
451
+ const value = cellValue(row, columns[position]);
452
+ if (value === null || value === undefined)
453
+ continue;
454
+ line += typeof value === "string" ? value : formatCell(value, columns[position].type);
455
+ line += "\x01";
456
+ }
457
+ text[index] = line.toLowerCase();
458
+ }
459
+ this.searchText = text;
460
+ return text;
461
+ }
462
+ refilter() {
463
+ const total = this.rows.length;
464
+ const terms = this.filter.toLowerCase().split(/\s+/).filter(Boolean);
465
+ if (terms.length === 0) {
466
+ const all = new Uint32Array(total);
467
+ for (let index = 0;index < total; index++)
468
+ all[index] = index;
469
+ this.filtered = all;
470
+ } else {
471
+ const text = this.searchable();
472
+ const kept = new Uint32Array(total);
473
+ let count = 0;
474
+ const single = terms.length === 1 ? terms[0] : null;
475
+ for (let index = 0;index < total; index++) {
476
+ const line = text[index];
477
+ if (single !== null) {
478
+ if (line.includes(single))
479
+ kept[count++] = index;
480
+ continue;
481
+ }
482
+ let every = true;
483
+ for (let term = 0;term < terms.length; term++) {
484
+ if (!line.includes(terms[term])) {
485
+ every = false;
486
+ break;
487
+ }
488
+ }
489
+ if (every)
490
+ kept[count++] = index;
491
+ }
492
+ this.filtered = kept.slice(0, count);
493
+ }
494
+ this.anchor = -1;
495
+ this.resort();
496
+ }
497
+ keysFor(column) {
498
+ const cached = this.sortKeys.get(column.key);
499
+ if (cached)
500
+ return cached;
501
+ const rows = this.rows;
502
+ const keys = new Float64Array(rows.length);
503
+ if (column.type === "number" || column.type === "date" || column.type === "boolean") {
504
+ for (let index = 0;index < rows.length; index++) {
505
+ const value = cellValue(rows[index], column);
506
+ let key = Number.NaN;
507
+ if (value === null || value === undefined || value === "")
508
+ key = Number.NaN;
509
+ else if (typeof value === "number")
510
+ key = value;
511
+ else if (typeof value === "boolean")
512
+ key = value ? 1 : 0;
513
+ else if (value instanceof Date)
514
+ key = value.getTime();
515
+ else if (column.type === "date")
516
+ key = Date.parse(String(value));
517
+ else if (column.type === "boolean")
518
+ key = String(value).toLowerCase() === "true" ? 1 : 0;
519
+ else
520
+ key = Number(value);
521
+ keys[index] = key;
522
+ }
523
+ } else {
524
+ const texts = Array.from({ length: rows.length });
525
+ const distinct = new Map;
526
+ for (let index = 0;index < rows.length; index++) {
527
+ const value = cellValue(rows[index], column);
528
+ if (value === null || value === undefined) {
529
+ texts[index] = null;
530
+ continue;
531
+ }
532
+ const text = typeof value === "string" ? value : formatCell(value, column.type);
533
+ texts[index] = text;
534
+ if (!distinct.has(text))
535
+ distinct.set(text, 0);
536
+ }
537
+ const ordered = [...distinct.keys()].sort(collator.compare);
538
+ let rank = 0;
539
+ for (let index = 0;index < ordered.length; index++) {
540
+ if (index > 0 && collator.compare(ordered[index - 1], ordered[index]) !== 0)
541
+ rank++;
542
+ distinct.set(ordered[index], rank);
543
+ }
544
+ for (let index = 0;index < rows.length; index++) {
545
+ const text = texts[index];
546
+ keys[index] = text === null ? Number.NaN : distinct.get(text);
547
+ }
548
+ }
549
+ this.sortKeys.set(column.key, keys);
550
+ return keys;
551
+ }
552
+ resort() {
553
+ const specs = [];
554
+ for (const entry of this.sort) {
555
+ const column = this.columns.find((candidate) => candidate.key === entry.key);
556
+ if (column)
557
+ specs.push({ keys: this.keysFor(column), sign: entry.direction === "desc" ? -1 : 1 });
558
+ }
559
+ const view = this.filtered.slice();
560
+ if (specs.length === 1) {
561
+ const { keys, sign } = specs[0];
562
+ view.sort((a, b) => {
563
+ const x = keys[a];
564
+ const y = keys[b];
565
+ if (x < y)
566
+ return -sign;
567
+ if (x > y)
568
+ return sign;
569
+ if (x === y)
570
+ return a - b;
571
+ const xEmpty = x !== x;
572
+ const yEmpty = y !== y;
573
+ return xEmpty === yEmpty ? a - b : xEmpty ? 1 : -1;
574
+ });
575
+ } else if (specs.length > 1) {
576
+ view.sort((a, b) => {
577
+ for (let index = 0;index < specs.length; index++) {
578
+ const x = specs[index].keys[a];
579
+ const y = specs[index].keys[b];
580
+ if (x < y)
581
+ return -specs[index].sign;
582
+ if (x > y)
583
+ return specs[index].sign;
584
+ if (x === y)
585
+ continue;
586
+ const xEmpty = x !== x;
587
+ const yEmpty = y !== y;
588
+ if (xEmpty !== yEmpty)
589
+ return xEmpty ? 1 : -1;
590
+ }
591
+ return a - b;
592
+ });
593
+ }
594
+ this.view = view;
595
+ }
596
+ }
597
+ // src/ui/data-grid/view.ts
598
+ var FILTER_DELAY = 120;
599
+ var numberFormat = new Intl.NumberFormat("en-US");
600
+ function part(root, name) {
601
+ return root.querySelector(`[data-dg="${name}"]`);
602
+ }
603
+ function writeClipboard(text) {
604
+ const fallback = () => {
605
+ const field = document.createElement("textarea");
606
+ field.value = text;
607
+ field.setAttribute("aria-hidden", "true");
608
+ field.style.cssText = "position:fixed;top:0;left:0;opacity:0;pointer-events:none";
609
+ document.body.appendChild(field);
610
+ const active = document.activeElement;
611
+ field.select();
612
+ try {
613
+ document.execCommand("copy");
614
+ } catch {}
615
+ field.remove();
616
+ active?.focus({ preventScroll: true });
617
+ };
618
+ if (typeof navigator !== "undefined" && navigator.clipboard && typeof navigator.clipboard.writeText === "function")
619
+ navigator.clipboard.writeText(text).catch(fallback);
620
+ else
621
+ fallback();
622
+ }
623
+
624
+ class DataGridView {
625
+ root;
626
+ callbacks;
627
+ model;
628
+ scroller;
629
+ content;
630
+ header;
631
+ body;
632
+ status;
633
+ filterInput;
634
+ prefix;
635
+ rowHeight;
636
+ headerHeight;
637
+ overscan;
638
+ columnOverscan;
639
+ selectable;
640
+ resizeStep;
641
+ fileName;
642
+ contextMenu;
643
+ slots = new Map;
644
+ pool = [];
645
+ headerCells = [];
646
+ rows = { start: 0, end: 0 };
647
+ cols = { start: 0, end: 0 };
648
+ stale = true;
649
+ active = { row: 0, column: 0 };
650
+ activeEl = null;
651
+ filterTimer = null;
652
+ resize = null;
653
+ observer = null;
654
+ disposers = [];
655
+ constructor(root, options = {}, callbacks = {}) {
656
+ this.root = root;
657
+ this.callbacks = callbacks;
658
+ const scroller = part(root, "scroller");
659
+ const content = part(root, "content");
660
+ const header = part(root, "header");
661
+ const body = part(root, "body");
662
+ if (!scroller || !content || !header || !body)
663
+ throw new Error("DataGridView: the root is missing its scroller, content, header or body");
664
+ this.scroller = scroller;
665
+ this.content = content;
666
+ this.header = header;
667
+ this.body = body;
668
+ this.status = part(root, "status");
669
+ this.filterInput = part(root, "filter");
670
+ this.prefix = scroller.id || `data-grid-${Math.random().toString(36).slice(2, 8)}`;
671
+ this.rowHeight = Math.max(8, options.rowHeight ?? 28);
672
+ this.headerHeight = Math.max(8, options.headerHeight ?? 32);
673
+ this.overscan = options.overscan ?? 6;
674
+ this.columnOverscan = options.columnOverscan ?? 2;
675
+ this.selectable = options.selectable !== false;
676
+ this.resizeStep = options.resizeStep ?? 16;
677
+ this.fileName = options.fileName || "data";
678
+ this.contextMenu = Boolean(options.contextMenu);
679
+ this.header.__stx_inert_content = true;
680
+ this.body.__stx_inert_content = true;
681
+ root.style.setProperty("--stx-grid-row-height", `${this.rowHeight}px`);
682
+ root.style.setProperty("--stx-grid-header-height", `${this.headerHeight}px`);
683
+ this.model = new GridModel(options.rows ?? [], options.columns ?? null);
684
+ if (options.filter) {
685
+ this.model.setFilter(options.filter);
686
+ if (this.filterInput)
687
+ this.filterInput.value = options.filter;
688
+ }
689
+ this.listen(this.scroller, "scroll", () => this.render());
690
+ this.listen(this.scroller, "keydown", (event) => this.onKeyDown(event));
691
+ this.listen(this.body, "click", (event) => this.onBodyClick(event));
692
+ this.listen(this.body, "dblclick", (event) => this.onBodyDoubleClick(event));
693
+ this.listen(this.body, "contextmenu", (event) => this.onContextMenu(event));
694
+ this.listen(this.header, "click", (event) => this.onHeaderClick(event));
695
+ this.listen(this.header, "dblclick", (event) => this.onHeaderDoubleClick(event));
696
+ this.listen(this.header, "pointerdown", (event) => this.onResizeStart(event));
697
+ this.listen(this.header, "pointermove", (event) => this.onResizeMove(event));
698
+ this.listen(this.header, "pointerup", (event) => this.onResizeEnd(event));
699
+ this.listen(this.header, "pointercancel", (event) => this.onResizeEnd(event));
700
+ if (this.filterInput)
701
+ this.listen(this.filterInput, "input", () => this.onFilterInput());
702
+ const csv = part(root, "export-csv");
703
+ const json = part(root, "export-json");
704
+ if (csv)
705
+ this.listen(csv, "click", () => this.download("csv"));
706
+ if (json)
707
+ this.listen(json, "click", () => this.download("json"));
708
+ if (typeof ResizeObserver !== "undefined") {
709
+ this.observer = new ResizeObserver(() => this.render());
710
+ this.observer.observe(this.scroller);
711
+ }
712
+ this.refresh();
713
+ root.setAttribute("data-dg-ready", "");
714
+ }
715
+ setRows(rows) {
716
+ this.model.setRows(rows);
717
+ this.active = { row: Math.min(0, this.model.count - 1), column: Math.min(this.active.column, Math.max(0, this.model.columns.length - 1)) };
718
+ this.scroller.scrollTop = 0;
719
+ this.refresh();
720
+ }
721
+ setColumns(columns) {
722
+ this.model.setColumns(columns);
723
+ this.active = { row: this.active.row, column: Math.min(this.active.column, Math.max(0, this.model.columns.length - 1)) };
724
+ this.refresh();
725
+ }
726
+ setFilter(text) {
727
+ const next = text == null ? "" : String(text);
728
+ if (this.filterInput && this.filterInput.value !== next)
729
+ this.filterInput.value = next;
730
+ this.applyFilter(next);
731
+ }
732
+ setSort(sort) {
733
+ this.model.setSort(sort);
734
+ this.refresh();
735
+ }
736
+ setFileName(name) {
737
+ this.fileName = name || "data";
738
+ }
739
+ getView() {
740
+ return this.model.viewRows();
741
+ }
742
+ getSelection() {
743
+ const indices = this.model.selectedIndices();
744
+ return { rows: indices.map((index) => this.model.rows[index]), indices };
745
+ }
746
+ clearSelection() {
747
+ this.model.clearSelection();
748
+ this.paintSelection();
749
+ this.reportSelection();
750
+ }
751
+ exportCsv() {
752
+ return this.model.toCsv();
753
+ }
754
+ exportJson() {
755
+ return this.model.toJson();
756
+ }
757
+ download(format) {
758
+ const text = format === "json" ? this.model.toJson() : this.model.toCsv();
759
+ const blob = new Blob([text], { type: format === "json" ? "application/json" : "text/csv;charset=utf-8" });
760
+ const url = URL.createObjectURL(blob);
761
+ const link = document.createElement("a");
762
+ link.href = url;
763
+ link.download = `${this.fileName}.${format}`;
764
+ link.style.display = "none";
765
+ this.root.appendChild(link);
766
+ link.click();
767
+ link.remove();
768
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
769
+ this.callbacks.onExport?.({ format, text, rows: this.model.count });
770
+ return text;
771
+ }
772
+ scrollToRow(viewIndex) {
773
+ const index = Math.max(0, Math.min(this.model.count - 1, viewIndex));
774
+ this.revealRow(index);
775
+ this.render();
776
+ }
777
+ focus() {
778
+ this.scroller.focus({ preventScroll: true });
779
+ }
780
+ getActiveCell() {
781
+ return { ...this.active };
782
+ }
783
+ setActiveCell(row, column) {
784
+ this.moveTo({ row, column }, false);
785
+ }
786
+ destroy() {
787
+ this.observer?.disconnect();
788
+ if (this.filterTimer)
789
+ clearTimeout(this.filterTimer);
790
+ for (const dispose of this.disposers)
791
+ dispose();
792
+ this.header.replaceChildren();
793
+ this.body.replaceChildren();
794
+ this.slots.clear();
795
+ this.pool.length = 0;
796
+ this.root.removeAttribute("data-dg-ready");
797
+ }
798
+ refresh() {
799
+ const model = this.model;
800
+ this.content.style.width = `${model.totalWidth}px`;
801
+ this.content.style.height = `${this.headerHeight + model.count * this.rowHeight}px`;
802
+ this.header.style.width = `${model.totalWidth}px`;
803
+ this.body.style.height = `${model.count * this.rowHeight}px`;
804
+ this.scroller.setAttribute("aria-rowcount", String(model.count + 1));
805
+ this.scroller.setAttribute("aria-colcount", String(model.columns.length));
806
+ this.root.toggleAttribute("data-empty", model.count === 0);
807
+ this.stale = true;
808
+ this.render();
809
+ this.paintStatus();
810
+ }
811
+ render() {
812
+ const model = this.model;
813
+ const scroller = this.scroller;
814
+ const rows = rowRange(scroller.scrollTop, Math.max(0, scroller.clientHeight - this.headerHeight), this.rowHeight, model.count, this.overscan);
815
+ const cols = model.columnRange(scroller.scrollLeft, scroller.clientWidth, this.columnOverscan);
816
+ const columnsMoved = this.stale || cols.start !== this.cols.start || cols.end !== this.cols.end;
817
+ if (!columnsMoved && rows.start === this.rows.start && rows.end === this.rows.end)
818
+ return;
819
+ this.rows = rows;
820
+ this.cols = cols;
821
+ if (columnsMoved)
822
+ this.renderHeader();
823
+ for (const [index, slot] of this.slots) {
824
+ if (index < rows.start || index >= rows.end) {
825
+ this.slots.delete(index);
826
+ slot.index = -1;
827
+ slot.el.style.display = "none";
828
+ this.pool.push(slot);
829
+ }
830
+ }
831
+ for (let index = rows.start;index < rows.end; index++) {
832
+ let slot = this.slots.get(index);
833
+ if (slot) {
834
+ if (columnsMoved)
835
+ this.fill(slot);
836
+ continue;
837
+ }
838
+ slot = this.pool.pop() ?? this.createSlot();
839
+ slot.index = index;
840
+ slot.el.style.display = "";
841
+ this.slots.set(index, slot);
842
+ this.fill(slot);
843
+ }
844
+ this.stale = false;
845
+ this.paintActive();
846
+ }
847
+ createSlot() {
848
+ const el = document.createElement("div");
849
+ el.className = "stx-dg-row";
850
+ el.setAttribute("role", "row");
851
+ this.body.appendChild(el);
852
+ return { el, index: -1, cells: [] };
853
+ }
854
+ fill(slot) {
855
+ const model = this.model;
856
+ const index = slot.index;
857
+ const row = model.rowAt(index);
858
+ const selected = this.selectable && model.isSelected(index);
859
+ const el = slot.el;
860
+ el.__dgRow = index;
861
+ el.style.transform = `translateY(${index * this.rowHeight}px)`;
862
+ el.setAttribute("aria-rowindex", String(index + 2));
863
+ if (this.selectable)
864
+ el.setAttribute("aria-selected", selected ? "true" : "false");
865
+ const wanted = this.cols.end - this.cols.start;
866
+ while (slot.cells.length < wanted) {
867
+ const cell = document.createElement("div");
868
+ cell.className = "stx-dg-cell";
869
+ cell.setAttribute("role", "gridcell");
870
+ cell.appendChild(document.createTextNode(""));
871
+ el.appendChild(cell);
872
+ slot.cells.push(cell);
873
+ }
874
+ while (slot.cells.length > wanted)
875
+ slot.cells.pop().remove();
876
+ for (let position = 0;position < wanted; position++) {
877
+ const columnIndex = this.cols.start + position;
878
+ const column = model.columns[columnIndex];
879
+ const cell = slot.cells[position];
880
+ const value = row === undefined ? undefined : cellValue(row, column);
881
+ const kind = cellKind(value);
882
+ cell.__dgColumn = columnIndex;
883
+ cell.id = `${this.prefix}-r${index}-c${columnIndex}`;
884
+ cell.style.left = `${model.offsetOf(columnIndex)}px`;
885
+ cell.style.width = `${column.width}px`;
886
+ cell.setAttribute("aria-colindex", String(columnIndex + 1));
887
+ cell.setAttribute("data-type", column.type);
888
+ cell.setAttribute("data-align", column.align);
889
+ if (kind === "value")
890
+ cell.removeAttribute("data-empty");
891
+ else
892
+ cell.setAttribute("data-empty", kind);
893
+ if (this.selectable)
894
+ cell.setAttribute("aria-selected", selected ? "true" : "false");
895
+ cell.firstChild.data = typeof value === "string" ? value : formatCell(value, column.type);
896
+ }
897
+ }
898
+ renderHeader() {
899
+ const model = this.model;
900
+ const wanted = this.cols.end - this.cols.start;
901
+ while (this.headerCells.length < wanted) {
902
+ const cell = document.createElement("div");
903
+ cell.className = "stx-dg-head";
904
+ cell.setAttribute("role", "columnheader");
905
+ const label = document.createElement("span");
906
+ label.className = "stx-dg-head-label";
907
+ label.appendChild(document.createTextNode(""));
908
+ const mark = document.createElement("span");
909
+ mark.className = "stx-dg-sort";
910
+ mark.setAttribute("aria-hidden", "true");
911
+ mark.appendChild(document.createTextNode(""));
912
+ const handle = document.createElement("span");
913
+ handle.className = "stx-dg-resize";
914
+ handle.setAttribute("aria-hidden", "true");
915
+ cell.append(label, mark, handle);
916
+ this.header.appendChild(cell);
917
+ this.headerCells.push(cell);
918
+ }
919
+ while (this.headerCells.length > wanted)
920
+ this.headerCells.pop().remove();
921
+ for (let position = 0;position < wanted; position++) {
922
+ const columnIndex = this.cols.start + position;
923
+ const column = model.columns[columnIndex];
924
+ const cell = this.headerCells[position];
925
+ const sorted = model.sortOf(column.key);
926
+ cell.__dgColumn = columnIndex;
927
+ cell.id = `${this.prefix}-h-c${columnIndex}`;
928
+ cell.style.left = `${model.offsetOf(columnIndex)}px`;
929
+ cell.style.width = `${column.width}px`;
930
+ cell.setAttribute("aria-colindex", String(columnIndex + 1));
931
+ cell.setAttribute("data-align", column.align);
932
+ cell.toggleAttribute("data-sortable", column.sortable);
933
+ if (column.sortable)
934
+ cell.setAttribute("aria-sort", sorted ? sorted.direction === "asc" ? "ascending" : "descending" : "none");
935
+ else
936
+ cell.removeAttribute("aria-sort");
937
+ cell.children[0].firstChild.data = column.label;
938
+ cell.children[1].firstChild.data = sorted ? `${sorted.direction === "asc" ? "▲" : "▼"}${model.sort.length > 1 ? sorted.priority : ""}` : "";
939
+ }
940
+ }
941
+ cellElement(cell) {
942
+ if (cell.column < this.cols.start || cell.column >= this.cols.end)
943
+ return null;
944
+ const position = cell.column - this.cols.start;
945
+ if (cell.row < 0)
946
+ return this.headerCells[position] ?? null;
947
+ return this.slots.get(cell.row)?.cells[position] ?? null;
948
+ }
949
+ paintActive() {
950
+ const next = this.cellElement(this.active);
951
+ if (this.activeEl && this.activeEl !== next)
952
+ this.activeEl.removeAttribute("data-active");
953
+ this.activeEl = next;
954
+ if (next) {
955
+ next.setAttribute("data-active", "");
956
+ this.scroller.setAttribute("aria-activedescendant", next.id);
957
+ } else {
958
+ this.scroller.removeAttribute("aria-activedescendant");
959
+ }
960
+ }
961
+ paintSelection() {
962
+ if (!this.selectable)
963
+ return;
964
+ for (const [index, slot] of this.slots) {
965
+ const value = this.model.isSelected(index) ? "true" : "false";
966
+ slot.el.setAttribute("aria-selected", value);
967
+ for (const cell of slot.cells)
968
+ cell.setAttribute("aria-selected", value);
969
+ }
970
+ this.paintStatus();
971
+ }
972
+ paintStatus() {
973
+ if (!this.status)
974
+ return;
975
+ const model = this.model;
976
+ const total = model.rows.length;
977
+ let text = model.count === total ? `${numberFormat.format(total)} ${total === 1 ? "row" : "rows"}` : `${numberFormat.format(model.count)} of ${numberFormat.format(total)} rows`;
978
+ if (model.selected.size > 0)
979
+ text += `, ${numberFormat.format(model.selected.size)} selected`;
980
+ if (this.status.textContent !== text)
981
+ this.status.textContent = text;
982
+ }
983
+ revealRow(index) {
984
+ const scroller = this.scroller;
985
+ const top = index * this.rowHeight;
986
+ const room = scroller.clientHeight - this.headerHeight;
987
+ if (top < scroller.scrollTop)
988
+ scroller.scrollTop = top;
989
+ else if (top + this.rowHeight > scroller.scrollTop + room)
990
+ scroller.scrollTop = top + this.rowHeight - room;
991
+ }
992
+ revealColumn(index) {
993
+ const scroller = this.scroller;
994
+ const left = this.model.offsetOf(index);
995
+ const right = this.model.offsetOf(index + 1);
996
+ if (left < scroller.scrollLeft)
997
+ scroller.scrollLeft = left;
998
+ else if (right > scroller.scrollLeft + scroller.clientWidth)
999
+ scroller.scrollLeft = Math.min(left, right - scroller.clientWidth);
1000
+ }
1001
+ detail(cell) {
1002
+ return {
1003
+ row: this.model.rowAt(cell.row),
1004
+ rowIndex: cell.row,
1005
+ column: this.model.columns[cell.column],
1006
+ value: cell.row < 0 ? undefined : this.model.valueAt(cell.row, cell.column)
1007
+ };
1008
+ }
1009
+ moveTo(cell, report = true) {
1010
+ const model = this.model;
1011
+ const next = {
1012
+ row: Math.max(-1, Math.min(model.count - 1, cell.row)),
1013
+ column: Math.max(0, Math.min(model.columns.length - 1, cell.column))
1014
+ };
1015
+ this.active = next;
1016
+ if (next.row >= 0)
1017
+ this.revealRow(next.row);
1018
+ this.revealColumn(next.column);
1019
+ this.render();
1020
+ this.paintActive();
1021
+ if (report)
1022
+ this.callbacks.onCell?.(this.detail(next));
1023
+ }
1024
+ reportSelection() {
1025
+ this.callbacks.onSelect?.(this.getSelection());
1026
+ }
1027
+ applyFilter(text) {
1028
+ const count = this.model.setFilter(text);
1029
+ this.active = { row: Math.min(0, count - 1), column: this.active.column };
1030
+ this.scroller.scrollTop = 0;
1031
+ this.refresh();
1032
+ this.callbacks.onFilter?.({ text, count });
1033
+ }
1034
+ sortBy(columnIndex, additive) {
1035
+ const column = this.model.columns[columnIndex];
1036
+ if (!column || !column.sortable)
1037
+ return;
1038
+ const sort = this.model.toggleSort(column.key, additive);
1039
+ this.refresh();
1040
+ this.callbacks.onSort?.([...sort]);
1041
+ }
1042
+ setColumnWidth(columnIndex, width) {
1043
+ this.model.resizeColumn(columnIndex, width);
1044
+ this.content.style.width = `${this.model.totalWidth}px`;
1045
+ this.header.style.width = `${this.model.totalWidth}px`;
1046
+ this.stale = true;
1047
+ this.render();
1048
+ }
1049
+ copy(what) {
1050
+ if (this.active.row < 0)
1051
+ return;
1052
+ const row = this.model.rowAt(this.active.row);
1053
+ if (row === undefined)
1054
+ return;
1055
+ const text = what === "row" ? rowJson(row, this.model.columns) : cellJson(this.model.valueAt(this.active.row, this.active.column));
1056
+ writeClipboard(text);
1057
+ this.callbacks.onCopy?.({ what, text });
1058
+ }
1059
+ listen(target, type, handler) {
1060
+ target.addEventListener(type, handler);
1061
+ this.disposers.push(() => target.removeEventListener(type, handler));
1062
+ }
1063
+ cellFrom(event) {
1064
+ const target = event.target;
1065
+ const cell = target?.closest(".stx-dg-cell");
1066
+ const row = cell?.parentElement;
1067
+ if (!cell || !row || cell.__dgColumn === undefined || row.__dgRow === undefined)
1068
+ return null;
1069
+ return { row: row.__dgRow, column: cell.__dgColumn };
1070
+ }
1071
+ headFrom(event) {
1072
+ const target = event.target;
1073
+ const head = target?.closest(".stx-dg-head");
1074
+ if (!head || head.__dgColumn === undefined)
1075
+ return null;
1076
+ const handle = target.closest(".stx-dg-resize");
1077
+ return { column: head.__dgColumn, onHandle: Boolean(handle), handle };
1078
+ }
1079
+ onBodyClick(event) {
1080
+ const cell = this.cellFrom(event);
1081
+ if (!cell)
1082
+ return;
1083
+ if (this.selectable) {
1084
+ this.model.select(cell.row, event.shiftKey ? "range" : event.metaKey || event.ctrlKey ? "toggle" : "replace");
1085
+ this.paintSelection();
1086
+ this.reportSelection();
1087
+ }
1088
+ this.moveTo(cell);
1089
+ }
1090
+ onBodyDoubleClick(event) {
1091
+ const cell = this.cellFrom(event);
1092
+ const row = cell ? this.model.rowAt(cell.row) : undefined;
1093
+ if (cell && row !== undefined)
1094
+ this.callbacks.onActivate?.({ row, rowIndex: cell.row });
1095
+ }
1096
+ onContextMenu(event) {
1097
+ const cell = this.cellFrom(event);
1098
+ if (!cell)
1099
+ return;
1100
+ if (this.contextMenu)
1101
+ event.preventDefault();
1102
+ this.moveTo(cell, false);
1103
+ this.callbacks.onContext?.({ ...this.detail(cell), x: event.clientX, y: event.clientY });
1104
+ }
1105
+ onHeaderClick(event) {
1106
+ const head = this.headFrom(event);
1107
+ if (!head || head.onHandle)
1108
+ return;
1109
+ this.active = { row: -1, column: head.column };
1110
+ this.sortBy(head.column, event.shiftKey);
1111
+ }
1112
+ onHeaderDoubleClick(event) {
1113
+ const head = this.headFrom(event);
1114
+ if (head && head.onHandle)
1115
+ this.setColumnWidth(head.column, this.model.autoWidth(head.column));
1116
+ }
1117
+ onResizeStart(event) {
1118
+ const head = this.headFrom(event);
1119
+ if (!head || !head.onHandle || !head.handle || event.button !== 0)
1120
+ return;
1121
+ event.preventDefault();
1122
+ try {
1123
+ head.handle.setPointerCapture(event.pointerId);
1124
+ } catch {}
1125
+ this.resize = { column: head.column, start: event.clientX, width: this.model.columns[head.column].width, pointer: event.pointerId, handle: head.handle };
1126
+ this.root.setAttribute("data-resizing", "");
1127
+ }
1128
+ onResizeMove(event) {
1129
+ const resize = this.resize;
1130
+ if (!resize || event.pointerId !== resize.pointer)
1131
+ return;
1132
+ this.setColumnWidth(resize.column, resize.width + event.clientX - resize.start);
1133
+ }
1134
+ onResizeEnd(event) {
1135
+ const resize = this.resize;
1136
+ if (!resize || event.pointerId !== resize.pointer)
1137
+ return;
1138
+ this.resize = null;
1139
+ this.root.removeAttribute("data-resizing");
1140
+ try {
1141
+ resize.handle.releasePointerCapture(event.pointerId);
1142
+ } catch {}
1143
+ }
1144
+ onFilterInput() {
1145
+ if (this.filterTimer)
1146
+ clearTimeout(this.filterTimer);
1147
+ this.filterTimer = setTimeout(() => {
1148
+ this.filterTimer = null;
1149
+ this.applyFilter(this.filterInput ? this.filterInput.value : "");
1150
+ }, FILTER_DELAY);
1151
+ }
1152
+ onKeyDown(event) {
1153
+ if (event.target !== this.scroller)
1154
+ return;
1155
+ const model = this.model;
1156
+ const mod = event.metaKey || event.ctrlKey;
1157
+ const onHeader = this.active.row < 0;
1158
+ const key = event.key;
1159
+ if (mod && (key === "a" || key === "A")) {
1160
+ if (!this.selectable)
1161
+ return;
1162
+ event.preventDefault();
1163
+ model.selectAll();
1164
+ this.paintSelection();
1165
+ this.reportSelection();
1166
+ return;
1167
+ }
1168
+ if (mod && (key === "c" || key === "C")) {
1169
+ if (onHeader)
1170
+ return;
1171
+ event.preventDefault();
1172
+ this.copy(event.shiftKey ? "row" : "cell");
1173
+ return;
1174
+ }
1175
+ if (onHeader && event.altKey && (key === "ArrowLeft" || key === "ArrowRight")) {
1176
+ event.preventDefault();
1177
+ const column = model.columns[this.active.column];
1178
+ if (column)
1179
+ this.setColumnWidth(this.active.column, column.width + (key === "ArrowRight" ? this.resizeStep : -this.resizeStep));
1180
+ this.paintActive();
1181
+ return;
1182
+ }
1183
+ if (key === "Enter" || key === " ") {
1184
+ event.preventDefault();
1185
+ if (onHeader) {
1186
+ this.sortBy(this.active.column, event.shiftKey);
1187
+ return;
1188
+ }
1189
+ if (key === " ") {
1190
+ if (!this.selectable)
1191
+ return;
1192
+ model.select(this.active.row, "toggle");
1193
+ this.paintSelection();
1194
+ this.reportSelection();
1195
+ return;
1196
+ }
1197
+ const row = model.rowAt(this.active.row);
1198
+ if (row !== undefined)
1199
+ this.callbacks.onActivate?.({ row, rowIndex: this.active.row });
1200
+ return;
1201
+ }
1202
+ if (key === "Escape" && this.selectable && model.selected.size > 0) {
1203
+ event.preventDefault();
1204
+ this.clearSelection();
1205
+ return;
1206
+ }
1207
+ const page = Math.max(1, Math.floor((this.scroller.clientHeight - this.headerHeight) / this.rowHeight) - 1);
1208
+ const next = moveCell(this.active, key, { rows: model.count, columns: model.columns.length, page, mod });
1209
+ if (next === this.active)
1210
+ return;
1211
+ event.preventDefault();
1212
+ if (next.row === this.active.row && next.column === this.active.column)
1213
+ return;
1214
+ if (event.shiftKey && this.selectable && next.row >= 0 && next.row !== this.active.row) {
1215
+ if (model.selected.size === 0 && this.active.row >= 0)
1216
+ model.select(this.active.row, "replace");
1217
+ model.select(next.row, "range");
1218
+ this.paintSelection();
1219
+ this.reportSelection();
1220
+ }
1221
+ this.moveTo(next);
1222
+ }
1223
+ }
1224
+ export {
1225
+ DEFAULT_MAX_WIDTH,
1226
+ DEFAULT_MIN_WIDTH,
1227
+ DataGridView,
1228
+ FIT_MAX_WIDTH,
1229
+ GridModel,
1230
+ JSON_PREVIEW_LENGTH,
1231
+ cellJson,
1232
+ cellKind,
1233
+ cellValue,
1234
+ cycleSort,
1235
+ formatCell,
1236
+ inferColumns,
1237
+ inferType,
1238
+ moveCell,
1239
+ projectRow,
1240
+ rowJson,
1241
+ rowRange,
1242
+ toCsv,
1243
+ toJson
1244
+ };