@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,813 @@
1
+ /**
2
+ * The model of a data grid. No DOM.
3
+ *
4
+ * A grid is a list of rows somebody else owns, a list of columns, and a view:
5
+ * the source indices of the rows that pass the filter, in sorted order. The
6
+ * rows are never copied or reordered, so a hundred thousand of them cost one
7
+ * `Uint32Array` to show, and selection (kept as source indices) survives a
8
+ * sort or a filter.
9
+ *
10
+ * Everything that is slow to work out per row is worked out once and kept:
11
+ * the text a filter searches, and a number per cell to sort by. A second
12
+ * filter is then a plain `includes` over strings, and a second sort compares
13
+ * numbers whatever the column holds.
14
+ */
15
+
16
+ export type GridColumnType = 'string' | 'number' | 'date' | 'boolean' | 'json'
17
+ export type GridAlign = 'left' | 'right' | 'center'
18
+ export type SortDirection = 'asc' | 'desc'
19
+
20
+ export interface GridColumn<Row = any> {
21
+ /** The property of a row this column shows, or the index for a row that is an array. */
22
+ key: string
23
+ label?: string
24
+ /** Left out, it is worked out from the first rows. */
25
+ type?: GridColumnType
26
+ /** Pixels. Left out, the column fits its header and the first rows. */
27
+ width?: number
28
+ minWidth?: number
29
+ maxWidth?: number
30
+ /** Left out, numbers go right and everything else left. */
31
+ align?: GridAlign
32
+ sortable?: boolean
33
+ /** Reads the cell from a row when it is not simply `row[key]`. */
34
+ accessor?: (row: Row) => unknown
35
+ }
36
+
37
+ export interface ResolvedColumn<Row = any> extends GridColumn<Row> {
38
+ label: string
39
+ type: GridColumnType
40
+ width: number
41
+ minWidth: number
42
+ maxWidth: number
43
+ align: GridAlign
44
+ sortable: boolean
45
+ }
46
+
47
+ export interface GridSort {
48
+ key: string
49
+ direction: SortDirection
50
+ }
51
+
52
+ export interface GridCell {
53
+ /** A view index, or -1 for the header row. */
54
+ row: number
55
+ column: number
56
+ }
57
+
58
+ export interface GridRange {
59
+ /** The first index in the range. */
60
+ start: number
61
+ /** One past the last. */
62
+ end: number
63
+ }
64
+
65
+ export interface GridModelOptions {
66
+ /** The width of one character of cell text, in pixels, for fitting a column. */
67
+ charWidth?: number
68
+ /** Pixels of padding inside a cell, both sides together. */
69
+ cellPadding?: number
70
+ }
71
+
72
+ export const DEFAULT_MIN_WIDTH = 48
73
+ export const DEFAULT_MAX_WIDTH = 2000
74
+ /** A column fitted to its content stops here, however long a value is. */
75
+ export const FIT_MAX_WIDTH = 420
76
+ /** JSON shown in a cell is cut here. The whole value is still what is copied. */
77
+ export const JSON_PREVIEW_LENGTH = 160
78
+
79
+ const NUMERIC = /^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i
80
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/
81
+
82
+ /** JSON for anything, including the values JSON itself refuses. */
83
+ function stringify(value: unknown, indent?: number): string {
84
+ const seen = new WeakSet<object>()
85
+ const text = JSON.stringify(value, (_key, entry) => {
86
+ if (typeof entry === 'bigint')
87
+ return entry.toString()
88
+ if (typeof entry === 'object' && entry !== null) {
89
+ if (seen.has(entry))
90
+ return '[Circular]'
91
+ seen.add(entry)
92
+ }
93
+ return entry
94
+ }, indent)
95
+ return text === undefined ? 'null' : text
96
+ }
97
+
98
+ /** The cell a column shows for a row. */
99
+ export function cellValue<Row>(row: Row, column: GridColumn<Row>): unknown {
100
+ if (column.accessor)
101
+ return column.accessor(row)
102
+ return row == null ? undefined : (row as Record<string, unknown>)[column.key]
103
+ }
104
+
105
+ /**
106
+ * What kind of column a list of values makes.
107
+ *
108
+ * Nulls say nothing and are skipped. A column is a number column only when
109
+ * every value is a number or reads as one: a single `n/a` among the figures
110
+ * makes it text, because sorting it as numbers would have to put that
111
+ * somewhere it does not belong.
112
+ */
113
+ export function inferType(values: readonly unknown[]): GridColumnType {
114
+ let seen = 0
115
+ let numbers = 0
116
+ let dates = 0
117
+ let booleans = 0
118
+ let objects = 0
119
+
120
+ for (const value of values) {
121
+ if (value === null || value === undefined || value === '')
122
+ continue
123
+ seen++
124
+ if (typeof value === 'number' || typeof value === 'bigint')
125
+ numbers++
126
+ else if (typeof value === 'boolean')
127
+ booleans++
128
+ else if (value instanceof Date)
129
+ dates++
130
+ else if (typeof value === 'object')
131
+ objects++
132
+ else if (typeof value === 'string') {
133
+ const text = value.trim()
134
+ if (NUMERIC.test(text))
135
+ numbers++
136
+ else if (ISO_DATE.test(text) && !Number.isNaN(Date.parse(text)))
137
+ dates++
138
+ }
139
+ }
140
+
141
+ if (seen === 0)
142
+ return 'string'
143
+ if (numbers === seen)
144
+ return 'number'
145
+ if (dates === seen)
146
+ return 'date'
147
+ if (booleans === seen)
148
+ return 'boolean'
149
+ if (objects === seen)
150
+ return 'json'
151
+ return 'string'
152
+ }
153
+
154
+ /**
155
+ * Columns for rows nobody described: every key of the first `sample` rows, in
156
+ * the order first seen. Rows that are arrays get a column per position.
157
+ */
158
+ export function inferColumns<Row>(rows: readonly Row[], sample = 200): GridColumn<Row>[] {
159
+ const keys: string[] = []
160
+ const known = new Set<string>()
161
+ const limit = Math.min(rows.length, sample)
162
+
163
+ for (let index = 0; index < limit; index++) {
164
+ const row = rows[index]
165
+ if (row === null || typeof row !== 'object')
166
+ continue
167
+ if (Array.isArray(row)) {
168
+ for (let position = 0; position < row.length; position++) {
169
+ const key = String(position)
170
+ if (!known.has(key)) {
171
+ known.add(key)
172
+ keys.push(key)
173
+ }
174
+ }
175
+ continue
176
+ }
177
+ for (const key in row) {
178
+ if (!known.has(key)) {
179
+ known.add(key)
180
+ keys.push(key)
181
+ }
182
+ }
183
+ }
184
+
185
+ // Positions arrive in order from one array, but a longer array later on must
186
+ // not put column 5 before column 3.
187
+ if (keys.length > 0 && keys.every(key => /^\d+$/.test(key)))
188
+ keys.sort((a, b) => Number(a) - Number(b))
189
+
190
+ return keys.map(key => ({ key }))
191
+ }
192
+
193
+ /** Whether a cell is empty, and which kind of empty. */
194
+ export function cellKind(value: unknown): 'null' | 'undefined' | 'value' {
195
+ if (value === null)
196
+ return 'null'
197
+ return value === undefined ? 'undefined' : 'value'
198
+ }
199
+
200
+ /**
201
+ * The text of a cell.
202
+ *
203
+ * A number is shown as it is, digit for digit: a grid of results is for
204
+ * reading values, and grouping or rounding would show something other than
205
+ * what is there. Lining the digits up is the stylesheet's job.
206
+ */
207
+ export function formatCell(value: unknown, type: GridColumnType = 'string'): string {
208
+ if (value === null)
209
+ return 'null'
210
+ if (value === undefined)
211
+ return 'undefined'
212
+ if (typeof value === 'string')
213
+ return value
214
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
215
+ return String(value)
216
+ if (value instanceof Date)
217
+ return Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString()
218
+ if (typeof value === 'object' || type === 'json') {
219
+ const text = stringify(value)
220
+ return text.length > JSON_PREVIEW_LENGTH ? `${text.slice(0, JSON_PREVIEW_LENGTH)}...` : text
221
+ }
222
+ return String(value)
223
+ }
224
+
225
+ /** A cell as JSON, the way it is copied. */
226
+ export function cellJson(value: unknown): string {
227
+ return stringify(value)
228
+ }
229
+
230
+ /** A row as an object of its columns. */
231
+ export function projectRow<Row>(row: Row, columns: readonly GridColumn<Row>[]): Record<string, unknown> {
232
+ const out: Record<string, unknown> = {}
233
+ for (const column of columns) {
234
+ const value = cellValue(row, column)
235
+ out[column.key] = value === undefined ? null : value
236
+ }
237
+ return out
238
+ }
239
+
240
+ /** A row as JSON, the way it is copied: its columns, indented. */
241
+ export function rowJson<Row>(row: Row, columns: readonly GridColumn<Row>[]): string {
242
+ return stringify(projectRow(row, columns), 2)
243
+ }
244
+
245
+ /** Rows as a JSON array of objects, one property per column. */
246
+ export function toJson<Row>(rows: readonly Row[], columns: readonly GridColumn<Row>[]): string {
247
+ return stringify(rows.map(row => projectRow(row, columns)), 2)
248
+ }
249
+
250
+ function csvField(value: unknown): string {
251
+ if (value === null || value === undefined)
252
+ return ''
253
+ let text: string
254
+ if (typeof value === 'string')
255
+ text = value
256
+ else if (value instanceof Date)
257
+ text = Number.isNaN(value.getTime()) ? '' : value.toISOString()
258
+ else if (typeof value === 'object')
259
+ text = stringify(value)
260
+ else
261
+ text = String(value)
262
+
263
+ // RFC 4180: a field with a quote, a comma or a line break is quoted, and a
264
+ // quote inside it is doubled. Edge spaces are quoted too, or a reader that
265
+ // trims fields would change the value.
266
+ if (/[",\r\n]/.test(text) || text !== text.trim())
267
+ return `"${text.replace(/"/g, '""')}"`
268
+ return text
269
+ }
270
+
271
+ /** Rows as CSV: a header row, CRLF line ends, RFC 4180 quoting. */
272
+ export function toCsv<Row>(rows: readonly Row[], columns: readonly GridColumn<Row>[]): string {
273
+ const lines: string[] = Array.from({ length: rows.length + 1 })
274
+ lines[0] = columns.map(column => csvField(column.label ?? column.key)).join(',')
275
+
276
+ const count = columns.length
277
+ for (let index = 0; index < rows.length; index++) {
278
+ const row = rows[index]
279
+ let line = ''
280
+ for (let position = 0; position < count; position++) {
281
+ if (position > 0)
282
+ line += ','
283
+ line += csvField(cellValue(row, columns[position]))
284
+ }
285
+ lines[index + 1] = line
286
+ }
287
+ return `${lines.join('\r\n')}\r\n`
288
+ }
289
+
290
+ /** The rows (or columns) that intersect a viewport, widened by `overscan`. */
291
+ export function rowRange(scroll: number, viewport: number, rowHeight: number, count: number, overscan = 0): GridRange {
292
+ if (count <= 0 || rowHeight <= 0)
293
+ return { start: 0, end: 0 }
294
+ const first = Math.floor(Math.max(0, scroll) / rowHeight)
295
+ const last = Math.ceil((Math.max(0, scroll) + Math.max(0, viewport)) / rowHeight)
296
+ const start = Math.min(count, Math.max(0, first - overscan))
297
+ return { start, end: Math.max(start, Math.min(count, last + overscan)) }
298
+ }
299
+
300
+ /**
301
+ * Where a key takes the active cell.
302
+ *
303
+ * Row -1 is the header, so the header is part of the grid a keyboard can
304
+ * reach: up from the first row lands on it, and down leaves it.
305
+ */
306
+ export function moveCell(cell: GridCell, key: string, bounds: { rows: number, columns: number, page: number, mod?: boolean }): GridCell {
307
+ const lastRow = bounds.rows - 1
308
+ const lastColumn = Math.max(0, bounds.columns - 1)
309
+ const page = Math.max(1, bounds.page)
310
+ let { row, column } = cell
311
+
312
+ switch (key) {
313
+ case 'ArrowUp': row = Math.max(-1, row - 1); break
314
+ case 'ArrowDown': row = Math.min(lastRow, row + 1); break
315
+ case 'ArrowLeft': column -= 1; break
316
+ case 'ArrowRight': column += 1; break
317
+ case 'PageUp': row = row <= 0 ? row : Math.max(0, row - page); break
318
+ case 'PageDown': row = Math.min(lastRow, Math.max(0, row) + (row < 0 ? 0 : page)); break
319
+ case 'Home':
320
+ column = 0
321
+ if (bounds.mod)
322
+ row = Math.min(0, lastRow)
323
+ break
324
+ case 'End':
325
+ column = lastColumn
326
+ if (bounds.mod)
327
+ row = lastRow
328
+ break
329
+ default: return cell
330
+ }
331
+
332
+ return { row: Math.max(-1, Math.min(lastRow, row)), column: Math.max(0, Math.min(lastColumn, column)) }
333
+ }
334
+
335
+ /** The next sort after a click on a column: ascending, descending, then none. */
336
+ export function cycleSort(sort: readonly GridSort[], key: string, additive = false): GridSort[] {
337
+ const current = sort.find(entry => entry.key === key)
338
+ const next: GridSort | null = !current
339
+ ? { key, direction: 'asc' }
340
+ : current.direction === 'asc' ? { key, direction: 'desc' } : null
341
+
342
+ if (!additive)
343
+ return next ? [next] : []
344
+ if (!current)
345
+ return [...sort, next!]
346
+ return next
347
+ ? sort.map(entry => (entry.key === key ? next : entry))
348
+ : sort.filter(entry => entry.key !== key)
349
+ }
350
+
351
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
352
+
353
+ export class GridModel<Row = any> {
354
+ rows: readonly Row[] = []
355
+ columns: ResolvedColumn<Row>[] = []
356
+ /** Source indices of the rows on show, in the order shown. */
357
+ view: Uint32Array = new Uint32Array(0)
358
+ sort: GridSort[] = []
359
+ filter = ''
360
+ /** Selected rows, as source indices. */
361
+ readonly selected: Set<number> = new Set()
362
+
363
+ private given: GridColumn<Row>[] | null = null
364
+ private filtered: Uint32Array = new Uint32Array(0)
365
+ private searchText: string[] | null = null
366
+ private readonly sortKeys: Map<string, Float64Array> = new Map()
367
+ private offsets: Float64Array = new Float64Array(1)
368
+ private anchor = -1
369
+ private readonly charWidth: number
370
+ private readonly cellPadding: number
371
+
372
+ constructor(rows: readonly Row[] = [], columns: readonly GridColumn<Row>[] | null = null, options: GridModelOptions = {}) {
373
+ this.charWidth = options.charWidth ?? 7.25
374
+ this.cellPadding = options.cellPadding ?? 24
375
+ this.given = columns && columns.length > 0 ? [...columns] : null
376
+ this.setRows(rows)
377
+ }
378
+
379
+ /** How many rows are on show. */
380
+ get count(): number {
381
+ return this.view.length
382
+ }
383
+
384
+ get totalWidth(): number {
385
+ return this.offsets[this.columns.length]
386
+ }
387
+
388
+ setRows(rows: readonly Row[] | null | undefined): void {
389
+ this.rows = Array.isArray(rows) ? rows : []
390
+ this.selected.clear()
391
+ this.anchor = -1
392
+ this.forget()
393
+ this.resolveColumns()
394
+ this.refilter()
395
+ }
396
+
397
+ /** Describe the columns, or pass null to have them worked out from the rows. */
398
+ setColumns(columns: readonly GridColumn<Row>[] | null | undefined): void {
399
+ this.given = columns && columns.length > 0 ? [...columns] : null
400
+ this.forget()
401
+ this.resolveColumns()
402
+ this.sort = this.sort.filter(entry => this.columns.some(column => column.key === entry.key))
403
+ this.refilter()
404
+ }
405
+
406
+ /**
407
+ * Show only the rows that hold every word of `text`, in any column, whatever
408
+ * the case. Returns how many are left.
409
+ */
410
+ setFilter(text: string | null | undefined): number {
411
+ this.filter = text == null ? '' : String(text)
412
+ this.refilter()
413
+ return this.count
414
+ }
415
+
416
+ setSort(sort: readonly GridSort[] | null | undefined): void {
417
+ this.sort = (sort ?? []).filter(entry => entry && (entry.direction === 'asc' || entry.direction === 'desc') && this.columns.some(column => column.key === entry.key))
418
+ this.resort()
419
+ }
420
+
421
+ /** What a click on a header does. Returns the new sort. */
422
+ toggleSort(key: string, additive = false): GridSort[] {
423
+ const column = this.columns.find(entry => entry.key === key)
424
+ if (!column || !column.sortable)
425
+ return this.sort
426
+ this.sort = cycleSort(this.sort, key, additive)
427
+ this.resort()
428
+ return this.sort
429
+ }
430
+
431
+ /** How a column is sorted, and where it comes in a sort over several. */
432
+ sortOf(key: string): { direction: SortDirection, priority: number } | null {
433
+ const index = this.sort.findIndex(entry => entry.key === key)
434
+ return index < 0 ? null : { direction: this.sort[index].direction, priority: index + 1 }
435
+ }
436
+
437
+ rowAt(viewIndex: number): Row | undefined {
438
+ return viewIndex >= 0 && viewIndex < this.view.length ? this.rows[this.view[viewIndex]] : undefined
439
+ }
440
+
441
+ valueAt(viewIndex: number, columnIndex: number): unknown {
442
+ const column = this.columns[columnIndex]
443
+ const row = this.rowAt(viewIndex)
444
+ return column && row !== undefined ? cellValue(row, column) : undefined
445
+ }
446
+
447
+ /** The rows on show, in order. */
448
+ viewRows(): Row[] {
449
+ const out: Row[] = Array.from({ length: this.view.length })
450
+ for (let index = 0; index < out.length; index++)
451
+ out[index] = this.rows[this.view[index]]
452
+ return out
453
+ }
454
+
455
+ toCsv(): string {
456
+ return toCsv(this.viewRows(), this.columns)
457
+ }
458
+
459
+ toJson(): string {
460
+ return toJson(this.viewRows(), this.columns)
461
+ }
462
+
463
+ // Selection
464
+
465
+ /**
466
+ * Select the row at a view index. `replace` leaves it the only one, `toggle`
467
+ * flips it, `range` selects from the last row picked to this one as shown.
468
+ */
469
+ select(viewIndex: number, mode: 'replace' | 'toggle' | 'range' = 'replace'): void {
470
+ if (viewIndex < 0 || viewIndex >= this.view.length)
471
+ return
472
+ const source = this.view[viewIndex]
473
+
474
+ if (mode === 'range' && this.anchor >= 0) {
475
+ const from = Math.min(this.anchor, viewIndex)
476
+ const to = Math.max(this.anchor, viewIndex)
477
+ this.selected.clear()
478
+ for (let index = from; index <= to && index < this.view.length; index++)
479
+ this.selected.add(this.view[index])
480
+ return
481
+ }
482
+
483
+ if (mode === 'toggle') {
484
+ if (this.selected.has(source))
485
+ this.selected.delete(source)
486
+ else
487
+ this.selected.add(source)
488
+ }
489
+ else {
490
+ this.selected.clear()
491
+ this.selected.add(source)
492
+ }
493
+ this.anchor = viewIndex
494
+ }
495
+
496
+ /** Select every row on show. */
497
+ selectAll(): void {
498
+ this.selected.clear()
499
+ for (let index = 0; index < this.view.length; index++)
500
+ this.selected.add(this.view[index])
501
+ }
502
+
503
+ clearSelection(): void {
504
+ this.selected.clear()
505
+ this.anchor = -1
506
+ }
507
+
508
+ isSelected(viewIndex: number): boolean {
509
+ return viewIndex >= 0 && viewIndex < this.view.length && this.selected.has(this.view[viewIndex])
510
+ }
511
+
512
+ /** Selected source indices, in source order. */
513
+ selectedIndices(): number[] {
514
+ return [...this.selected].sort((a, b) => a - b)
515
+ }
516
+
517
+ selectedRows(): Row[] {
518
+ return this.selectedIndices().map(index => this.rows[index])
519
+ }
520
+
521
+ // Geometry
522
+
523
+ /** Where a column starts, in pixels from the left. `columns.length` gives the total. */
524
+ offsetOf(columnIndex: number): number {
525
+ return this.offsets[Math.max(0, Math.min(this.columns.length, columnIndex))]
526
+ }
527
+
528
+ /** The column under a horizontal position, clamped to the first and last. */
529
+ columnAt(x: number): number {
530
+ const count = this.columns.length
531
+ if (count === 0)
532
+ return -1
533
+ let low = 0
534
+ let high = count - 1
535
+ while (low < high) {
536
+ const middle = (low + high + 1) >> 1
537
+ if (this.offsets[middle] <= x)
538
+ low = middle
539
+ else
540
+ high = middle - 1
541
+ }
542
+ return low
543
+ }
544
+
545
+ /** The columns that intersect a viewport, widened by `overscan` columns. */
546
+ columnRange(scrollLeft: number, viewportWidth: number, overscan = 0): GridRange {
547
+ const count = this.columns.length
548
+ if (count === 0)
549
+ return { start: 0, end: 0 }
550
+ const first = this.columnAt(Math.max(0, scrollLeft))
551
+ const last = this.columnAt(Math.max(0, scrollLeft) + Math.max(0, viewportWidth))
552
+ return { start: Math.max(0, first - overscan), end: Math.min(count, last + 1 + overscan) }
553
+ }
554
+
555
+ /** Set a column's width, inside its limits. Returns the width it got. */
556
+ resizeColumn(columnIndex: number, width: number): number {
557
+ const column = this.columns[columnIndex]
558
+ if (!column)
559
+ return 0
560
+ column.width = Math.round(Math.max(column.minWidth, Math.min(column.maxWidth, width)))
561
+ this.measure()
562
+ return column.width
563
+ }
564
+
565
+ /**
566
+ * The width that fits a column's header and the rows sampled from the top of
567
+ * the view. Counted in characters, not measured: laying text out to size a
568
+ * column would cost more than drawing the grid.
569
+ */
570
+ autoWidth(columnIndex: number, sample = 200): number {
571
+ const column = this.columns[columnIndex]
572
+ if (!column)
573
+ return 0
574
+ // Room in the header for the sort mark beside the label.
575
+ let longest = column.label.length + 3
576
+ const limit = Math.min(this.view.length, sample)
577
+ for (let index = 0; index < limit; index++) {
578
+ const length = formatCell(cellValue(this.rows[this.view[index]], column), column.type).length
579
+ if (length > longest)
580
+ longest = length
581
+ }
582
+ const width = Math.ceil(longest * this.charWidth + this.cellPadding)
583
+ return Math.max(column.minWidth, Math.min(column.maxWidth, FIT_MAX_WIDTH, width))
584
+ }
585
+
586
+ private forget(): void {
587
+ this.searchText = null
588
+ this.sortKeys.clear()
589
+ }
590
+
591
+ private resolveColumns(): void {
592
+ const source = this.given ?? inferColumns(this.rows)
593
+ const sample = Math.min(this.rows.length, 200)
594
+ // Until the view exists, a column is fitted against the rows as they come.
595
+ const previous = this.view
596
+ this.view = new Uint32Array(sample)
597
+ for (let index = 0; index < sample; index++)
598
+ this.view[index] = index
599
+
600
+ this.columns = source.map((column) => {
601
+ let type = column.type
602
+ if (!type) {
603
+ const values: unknown[] = []
604
+ for (let index = 0; index < sample; index++)
605
+ values.push(cellValue(this.rows[index], column))
606
+ type = inferType(values)
607
+ }
608
+ return {
609
+ ...column,
610
+ label: column.label ?? column.key,
611
+ type,
612
+ width: column.width ?? 0,
613
+ minWidth: column.minWidth ?? DEFAULT_MIN_WIDTH,
614
+ maxWidth: column.maxWidth ?? DEFAULT_MAX_WIDTH,
615
+ align: column.align ?? (type === 'number' ? 'right' : 'left'),
616
+ sortable: column.sortable !== false,
617
+ }
618
+ })
619
+ this.columns.forEach((column, index) => {
620
+ if (!column.width)
621
+ column.width = this.autoWidth(index)
622
+ column.width = Math.max(column.minWidth, Math.min(column.maxWidth, column.width))
623
+ })
624
+
625
+ this.view = previous
626
+ this.measure()
627
+ }
628
+
629
+ private measure(): void {
630
+ const offsets = new Float64Array(this.columns.length + 1)
631
+ for (let index = 0; index < this.columns.length; index++)
632
+ offsets[index + 1] = offsets[index] + this.columns[index].width
633
+ this.offsets = offsets
634
+ }
635
+
636
+ /** The text of each row a filter looks through, lower case, made once. */
637
+ private searchable(): string[] {
638
+ if (this.searchText)
639
+ return this.searchText
640
+ const rows = this.rows
641
+ const columns = this.columns
642
+ const text: string[] = Array.from({ length: rows.length })
643
+ for (let index = 0; index < rows.length; index++) {
644
+ const row = rows[index]
645
+ let line = ''
646
+ for (let position = 0; position < columns.length; position++) {
647
+ const value = cellValue(row, columns[position])
648
+ if (value === null || value === undefined)
649
+ continue
650
+ // A separator no value holds, so a term cannot match across two cells.
651
+ line += typeof value === 'string' ? value : formatCell(value, columns[position].type)
652
+ line += '\u0001'
653
+ }
654
+ text[index] = line.toLowerCase()
655
+ }
656
+ this.searchText = text
657
+ return text
658
+ }
659
+
660
+ private refilter(): void {
661
+ const total = this.rows.length
662
+ const terms = this.filter.toLowerCase().split(/\s+/).filter(Boolean)
663
+
664
+ if (terms.length === 0) {
665
+ const all = new Uint32Array(total)
666
+ for (let index = 0; index < total; index++)
667
+ all[index] = index
668
+ this.filtered = all
669
+ }
670
+ else {
671
+ const text = this.searchable()
672
+ const kept = new Uint32Array(total)
673
+ let count = 0
674
+ const single = terms.length === 1 ? terms[0] : null
675
+ for (let index = 0; index < total; index++) {
676
+ const line = text[index]
677
+ if (single !== null) {
678
+ if (line.includes(single))
679
+ kept[count++] = index
680
+ continue
681
+ }
682
+ let every = true
683
+ for (let term = 0; term < terms.length; term++) {
684
+ if (!line.includes(terms[term])) {
685
+ every = false
686
+ break
687
+ }
688
+ }
689
+ if (every)
690
+ kept[count++] = index
691
+ }
692
+ this.filtered = kept.slice(0, count)
693
+ }
694
+ this.anchor = -1
695
+ this.resort()
696
+ }
697
+
698
+ /**
699
+ * One number per row to sort a column by, whatever the column holds, with
700
+ * NaN for an empty cell. Text is ranked once with the collator, so a sort
701
+ * never calls it per comparison.
702
+ */
703
+ private keysFor(column: ResolvedColumn<Row>): Float64Array {
704
+ const cached = this.sortKeys.get(column.key)
705
+ if (cached)
706
+ return cached
707
+
708
+ const rows = this.rows
709
+ const keys = new Float64Array(rows.length)
710
+
711
+ if (column.type === 'number' || column.type === 'date' || column.type === 'boolean') {
712
+ for (let index = 0; index < rows.length; index++) {
713
+ const value = cellValue(rows[index], column)
714
+ let key = Number.NaN
715
+ if (value === null || value === undefined || value === '')
716
+ key = Number.NaN
717
+ else if (typeof value === 'number')
718
+ key = value
719
+ else if (typeof value === 'boolean')
720
+ key = value ? 1 : 0
721
+ else if (value instanceof Date)
722
+ key = value.getTime()
723
+ else if (column.type === 'date')
724
+ key = Date.parse(String(value))
725
+ else if (column.type === 'boolean')
726
+ key = String(value).toLowerCase() === 'true' ? 1 : 0
727
+ else
728
+ key = Number(value)
729
+ keys[index] = key
730
+ }
731
+ }
732
+ else {
733
+ const texts: Array<string | null> = Array.from({ length: rows.length })
734
+ const distinct = new Map<string, number>()
735
+ for (let index = 0; index < rows.length; index++) {
736
+ const value = cellValue(rows[index], column)
737
+ if (value === null || value === undefined) {
738
+ texts[index] = null
739
+ continue
740
+ }
741
+ const text = typeof value === 'string' ? value : formatCell(value, column.type)
742
+ texts[index] = text
743
+ if (!distinct.has(text))
744
+ distinct.set(text, 0)
745
+ }
746
+ const ordered = [...distinct.keys()].sort(collator.compare)
747
+ // Values the collator calls equal (`a` and `A`) share a rank, so they
748
+ // keep their source order instead of being split by an arbitrary one.
749
+ let rank = 0
750
+ for (let index = 0; index < ordered.length; index++) {
751
+ if (index > 0 && collator.compare(ordered[index - 1], ordered[index]) !== 0)
752
+ rank++
753
+ distinct.set(ordered[index], rank)
754
+ }
755
+ for (let index = 0; index < rows.length; index++) {
756
+ const text = texts[index]
757
+ keys[index] = text === null ? Number.NaN : distinct.get(text)!
758
+ }
759
+ }
760
+
761
+ this.sortKeys.set(column.key, keys)
762
+ return keys
763
+ }
764
+
765
+ private resort(): void {
766
+ const specs: Array<{ keys: Float64Array, sign: number }> = []
767
+ for (const entry of this.sort) {
768
+ const column = this.columns.find(candidate => candidate.key === entry.key)
769
+ if (column)
770
+ specs.push({ keys: this.keysFor(column), sign: entry.direction === 'desc' ? -1 : 1 })
771
+ }
772
+
773
+ const view = this.filtered.slice()
774
+ if (specs.length === 1) {
775
+ const { keys, sign } = specs[0]
776
+ // Empty cells last whichever way the column runs, and the source order
777
+ // between equals, which is what makes the sort stable.
778
+ view.sort((a, b) => {
779
+ const x = keys[a]
780
+ const y = keys[b]
781
+ if (x < y)
782
+ return -sign
783
+ if (x > y)
784
+ return sign
785
+ if (x === y)
786
+ return a - b
787
+ const xEmpty = x !== x
788
+ const yEmpty = y !== y
789
+ return xEmpty === yEmpty ? a - b : (xEmpty ? 1 : -1)
790
+ })
791
+ }
792
+ else if (specs.length > 1) {
793
+ view.sort((a, b) => {
794
+ for (let index = 0; index < specs.length; index++) {
795
+ const x = specs[index].keys[a]
796
+ const y = specs[index].keys[b]
797
+ if (x < y)
798
+ return -specs[index].sign
799
+ if (x > y)
800
+ return specs[index].sign
801
+ if (x === y)
802
+ continue
803
+ const xEmpty = x !== x
804
+ const yEmpty = y !== y
805
+ if (xEmpty !== yEmpty)
806
+ return xEmpty ? 1 : -1
807
+ }
808
+ return a - b
809
+ })
810
+ }
811
+ this.view = view
812
+ }
813
+ }