@stacksjs/components 0.2.855 → 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 (100) hide show
  1. package/dist/ContextMenu-43g3w5tp.stx +188 -0
  2. package/dist/DataGrid-7rt7v865.stx +376 -0
  3. package/dist/GraphView-0t3t9mec.stx +320 -0
  4. package/dist/JsonTree-satc4010.stx +317 -0
  5. package/dist/PreviewFrame-erbgvzj8.stx +257 -0
  6. package/dist/SplitPane-7sqfdwqa.stx +159 -0
  7. package/dist/component-api/component-api.js +36 -0
  8. package/dist/context-menu/context-menu.js +575 -0
  9. package/dist/data-grid/data-grid.js +1244 -0
  10. package/dist/graph-view/graph-view.js +1408 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.js +22 -20
  13. package/dist/json-tree/json-tree.js +1121 -0
  14. package/dist/preview-frame/preview-frame.js +356 -0
  15. package/dist/split-pane/split-pane.js +364 -0
  16. package/dist/ui/context-menu/ContextMenu.d.ts +14 -0
  17. package/dist/ui/context-menu/context-menu.d.ts +8 -0
  18. package/dist/ui/context-menu/core.d.ts +74 -0
  19. package/dist/ui/context-menu/index.d.ts +11 -0
  20. package/dist/ui/context-menu/view.d.ts +36 -0
  21. package/dist/ui/data-grid/DataGrid.d.ts +30 -0
  22. package/dist/ui/data-grid/core.d.ts +141 -0
  23. package/dist/ui/data-grid/data-grid.d.ts +9 -0
  24. package/dist/ui/data-grid/index.d.ts +20 -0
  25. package/dist/ui/data-grid/view.d.ts +56 -0
  26. package/dist/ui/graph-view/GraphView.d.ts +21 -0
  27. package/dist/ui/graph-view/core/edges.d.ts +34 -0
  28. package/dist/ui/graph-view/core/force.d.ts +10 -0
  29. package/dist/ui/graph-view/core/graph.d.ts +83 -0
  30. package/dist/ui/graph-view/core/index.d.ts +5 -0
  31. package/dist/ui/graph-view/core/layered.d.ts +24 -0
  32. package/dist/ui/graph-view/core/viewport.d.ts +34 -0
  33. package/dist/ui/graph-view/graph-view.d.ts +9 -0
  34. package/dist/ui/graph-view/index.d.ts +21 -0
  35. package/dist/ui/graph-view/view.d.ts +51 -0
  36. package/dist/ui/json-tree/JsonTree.d.ts +18 -0
  37. package/dist/ui/json-tree/core.d.ts +108 -0
  38. package/dist/ui/json-tree/index.d.ts +18 -0
  39. package/dist/ui/json-tree/json-tree.d.ts +10 -0
  40. package/dist/ui/json-tree/tinker.d.ts +84 -0
  41. package/dist/ui/json-tree/view.d.ts +59 -0
  42. package/dist/ui/preview-frame/PreviewFrame.d.ts +44 -0
  43. package/dist/ui/preview-frame/core.d.ts +81 -0
  44. package/dist/ui/preview-frame/index.d.ts +19 -0
  45. package/dist/ui/preview-frame/preview-frame.d.ts +8 -0
  46. package/dist/ui/preview-frame/view.d.ts +37 -0
  47. package/dist/ui/split-pane/SplitPane.d.ts +18 -0
  48. package/dist/ui/split-pane/core.d.ts +58 -0
  49. package/dist/ui/split-pane/index.d.ts +15 -0
  50. package/dist/ui/split-pane/split-pane.d.ts +8 -0
  51. package/dist/ui/split-pane/view.d.ts +27 -0
  52. package/dist/ui/virtual-table/index.d.ts +6 -0
  53. package/dist/utils/component-api.d.ts +4 -0
  54. package/package.json +38 -3
  55. package/src/index.ts +8 -0
  56. package/src/ui/code-editor/README.md +2 -1
  57. package/src/ui/context-menu/ContextMenu.stx +188 -0
  58. package/src/ui/context-menu/README.md +117 -0
  59. package/src/ui/context-menu/context-menu.ts +8 -0
  60. package/src/ui/context-menu/core.ts +250 -0
  61. package/src/ui/context-menu/index.ts +16 -0
  62. package/src/ui/context-menu/view.ts +540 -0
  63. package/src/ui/data-grid/DataGrid.stx +376 -0
  64. package/src/ui/data-grid/README.md +204 -0
  65. package/src/ui/data-grid/core.ts +813 -0
  66. package/src/ui/data-grid/data-grid.ts +9 -0
  67. package/src/ui/data-grid/index.ts +34 -0
  68. package/src/ui/data-grid/view.ts +806 -0
  69. package/src/ui/graph-view/GraphView.stx +320 -0
  70. package/src/ui/graph-view/README.md +210 -0
  71. package/src/ui/graph-view/core/edges.ts +180 -0
  72. package/src/ui/graph-view/core/force.ts +237 -0
  73. package/src/ui/graph-view/core/graph.ts +277 -0
  74. package/src/ui/graph-view/core/index.ts +5 -0
  75. package/src/ui/graph-view/core/layered.ts +256 -0
  76. package/src/ui/graph-view/core/viewport.ts +141 -0
  77. package/src/ui/graph-view/graph-view.ts +9 -0
  78. package/src/ui/graph-view/index.ts +35 -0
  79. package/src/ui/graph-view/view.ts +809 -0
  80. package/src/ui/json-tree/JsonTree.stx +317 -0
  81. package/src/ui/json-tree/README.md +193 -0
  82. package/src/ui/json-tree/core.ts +588 -0
  83. package/src/ui/json-tree/index.ts +28 -0
  84. package/src/ui/json-tree/json-tree.ts +10 -0
  85. package/src/ui/json-tree/tinker.ts +349 -0
  86. package/src/ui/json-tree/view.ts +665 -0
  87. package/src/ui/preview-frame/PreviewFrame.stx +257 -0
  88. package/src/ui/preview-frame/README.md +107 -0
  89. package/src/ui/preview-frame/core.ts +195 -0
  90. package/src/ui/preview-frame/index.ts +31 -0
  91. package/src/ui/preview-frame/preview-frame.ts +8 -0
  92. package/src/ui/preview-frame/view.ts +336 -0
  93. package/src/ui/split-pane/README.md +87 -0
  94. package/src/ui/split-pane/SplitPane.stx +159 -0
  95. package/src/ui/split-pane/core.ts +200 -0
  96. package/src/ui/split-pane/index.ts +24 -0
  97. package/src/ui/split-pane/split-pane.ts +8 -0
  98. package/src/ui/split-pane/view.ts +305 -0
  99. package/src/ui/virtual-table/index.ts +6 -0
  100. package/src/utils/component-api.ts +72 -0
@@ -0,0 +1,806 @@
1
+ /**
2
+ * A data grid in the DOM.
3
+ *
4
+ * One scroll container holds everything: a header that sticks to its top, and
5
+ * a body as tall as every row put together. Only the rows and columns that
6
+ * cross the viewport are elements. A row that scrolls out is handed to the
7
+ * row that scrolls in, so scrolling makes no elements and drops none, and a
8
+ * hundred thousand rows cost what forty do.
9
+ *
10
+ * Focus stays on the container. The active cell is named with
11
+ * `aria-activedescendant`, because the cell a screen reader is on has to keep
12
+ * existing while the elements under it are recycled.
13
+ */
14
+ import type { GridCell, GridColumn, GridRange, GridSort, ResolvedColumn } from './core'
15
+ import { cellJson, cellKind, cellValue, formatCell, GridModel, moveCell, rowJson, rowRange } from './core'
16
+
17
+ export interface DataGridOptions<Row = any> {
18
+ rows?: readonly Row[]
19
+ columns?: readonly GridColumn<Row>[] | null
20
+ /** Pixels. Default 28. */
21
+ rowHeight?: number
22
+ /** Pixels. Default 32. */
23
+ headerHeight?: number
24
+ /** Rows drawn past each edge of the viewport. Default 6. */
25
+ overscan?: number
26
+ /** Columns drawn past each edge. Default 2. */
27
+ columnOverscan?: number
28
+ selectable?: boolean
29
+ /** The filter to start with. */
30
+ filter?: string
31
+ /** The name of a downloaded file, without its extension. */
32
+ fileName?: string
33
+ /** Suppress the browser's own menu on a right click, for a host that shows one. */
34
+ contextMenu?: boolean
35
+ /** Pixels Alt+arrow resizes a column by. Default 16. */
36
+ resizeStep?: number
37
+ }
38
+
39
+ export interface GridCellDetail<Row = any> {
40
+ row: Row | undefined
41
+ /** The row's place in the view. -1 on the header. */
42
+ rowIndex: number
43
+ column: ResolvedColumn<Row> | undefined
44
+ value: unknown
45
+ }
46
+
47
+ export interface DataGridCallbacks<Row = any> {
48
+ onSort?: (sort: GridSort[]) => void
49
+ onFilter?: (detail: { text: string, count: number }) => void
50
+ onSelect?: (detail: { rows: Row[], indices: number[] }) => void
51
+ onCell?: (detail: GridCellDetail<Row>) => void
52
+ onActivate?: (detail: { row: Row, rowIndex: number }) => void
53
+ onCopy?: (detail: { what: 'cell' | 'row', text: string }) => void
54
+ onExport?: (detail: { format: 'csv' | 'json', text: string, rows: number }) => void
55
+ onContext?: (detail: GridCellDetail<Row> & { x: number, y: number }) => void
56
+ }
57
+
58
+ interface RowSlot {
59
+ el: HTMLElement
60
+ /** The view index it is showing, or -1 while it waits in the pool. */
61
+ index: number
62
+ cells: HTMLElement[]
63
+ }
64
+
65
+ type Inert = HTMLElement & { __stx_inert_content?: boolean }
66
+ type CellElement = HTMLElement & { __dgColumn?: number }
67
+ type RowElement = HTMLElement & { __dgRow?: number }
68
+
69
+ const FILTER_DELAY = 120
70
+ const numberFormat = new Intl.NumberFormat('en-US')
71
+
72
+ function part(root: HTMLElement, name: string): HTMLElement | null {
73
+ return root.querySelector<HTMLElement>(`[data-dg="${name}"]`)
74
+ }
75
+
76
+ /** Put text on the clipboard, by the old route where the new one is refused. */
77
+ function writeClipboard(text: string): void {
78
+ const fallback = (): void => {
79
+ const field = document.createElement('textarea')
80
+ field.value = text
81
+ field.setAttribute('aria-hidden', 'true')
82
+ field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none'
83
+ document.body.appendChild(field)
84
+ const active = document.activeElement as HTMLElement | null
85
+ field.select()
86
+ try {
87
+ document.execCommand('copy')
88
+ }
89
+ catch {}
90
+ field.remove()
91
+ active?.focus({ preventScroll: true })
92
+ }
93
+
94
+ if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function')
95
+ navigator.clipboard.writeText(text).catch(fallback)
96
+ else
97
+ fallback()
98
+ }
99
+
100
+ export class DataGridView<Row = any> {
101
+ readonly model: GridModel<Row>
102
+
103
+ private readonly scroller: HTMLElement
104
+ private readonly content: HTMLElement
105
+ private readonly header: HTMLElement
106
+ private readonly body: HTMLElement
107
+ private readonly status: HTMLElement | null
108
+ private readonly filterInput: HTMLInputElement | null
109
+ private readonly prefix: string
110
+
111
+ private readonly rowHeight: number
112
+ private readonly headerHeight: number
113
+ private readonly overscan: number
114
+ private readonly columnOverscan: number
115
+ private readonly selectable: boolean
116
+ private readonly resizeStep: number
117
+ private fileName: string
118
+ private readonly contextMenu: boolean
119
+
120
+ private readonly slots: Map<number, RowSlot> = new Map()
121
+ private readonly pool: RowSlot[] = []
122
+ private headerCells: HTMLElement[] = []
123
+ private rows: GridRange = { start: 0, end: 0 }
124
+ private cols: GridRange = { start: 0, end: 0 }
125
+ /** Bumped whenever what a drawn cell shows may have changed. */
126
+ private stale = true
127
+ private active: GridCell = { row: 0, column: 0 }
128
+ private activeEl: HTMLElement | null = null
129
+ private filterTimer: ReturnType<typeof setTimeout> | null = null
130
+ private resize: { column: number, start: number, width: number, pointer: number, handle: HTMLElement } | null = null
131
+ private observer: ResizeObserver | null = null
132
+ private readonly disposers: Array<() => void> = []
133
+
134
+ constructor(private readonly root: HTMLElement, options: DataGridOptions<Row> = {}, private readonly callbacks: DataGridCallbacks<Row> = {}) {
135
+ const scroller = part(root, 'scroller')
136
+ const content = part(root, 'content')
137
+ const header = part(root, 'header')
138
+ const body = part(root, 'body')
139
+ if (!scroller || !content || !header || !body)
140
+ throw new Error('DataGridView: the root is missing its scroller, content, header or body')
141
+
142
+ this.scroller = scroller
143
+ this.content = content
144
+ this.header = header
145
+ this.body = body
146
+ this.status = part(root, 'status')
147
+ this.filterInput = part(root, 'filter') as HTMLInputElement | null
148
+ this.prefix = scroller.id || `data-grid-${Math.random().toString(36).slice(2, 8)}`
149
+
150
+ this.rowHeight = Math.max(8, options.rowHeight ?? 28)
151
+ this.headerHeight = Math.max(8, options.headerHeight ?? 32)
152
+ this.overscan = options.overscan ?? 6
153
+ this.columnOverscan = options.columnOverscan ?? 2
154
+ this.selectable = options.selectable !== false
155
+ this.resizeStep = options.resizeStep ?? 16
156
+ this.fileName = options.fileName || 'data'
157
+ this.contextMenu = Boolean(options.contextMenu)
158
+
159
+ // What the cells hold is data. A value with braces in it is text, and the
160
+ // stx runtime must never read it as an expression.
161
+ ;(this.header as Inert).__stx_inert_content = true
162
+ ;(this.body as Inert).__stx_inert_content = true
163
+
164
+ root.style.setProperty('--stx-grid-row-height', `${this.rowHeight}px`)
165
+ root.style.setProperty('--stx-grid-header-height', `${this.headerHeight}px`)
166
+
167
+ this.model = new GridModel<Row>(options.rows ?? [], options.columns ?? null)
168
+ if (options.filter) {
169
+ this.model.setFilter(options.filter)
170
+ if (this.filterInput)
171
+ this.filterInput.value = options.filter
172
+ }
173
+
174
+ this.listen(this.scroller, 'scroll', () => this.render())
175
+ this.listen(this.scroller, 'keydown', event => this.onKeyDown(event as KeyboardEvent))
176
+ this.listen(this.body, 'click', event => this.onBodyClick(event as MouseEvent))
177
+ this.listen(this.body, 'dblclick', event => this.onBodyDoubleClick(event as MouseEvent))
178
+ this.listen(this.body, 'contextmenu', event => this.onContextMenu(event as MouseEvent))
179
+ this.listen(this.header, 'click', event => this.onHeaderClick(event as MouseEvent))
180
+ this.listen(this.header, 'dblclick', event => this.onHeaderDoubleClick(event as MouseEvent))
181
+ this.listen(this.header, 'pointerdown', event => this.onResizeStart(event as PointerEvent))
182
+ this.listen(this.header, 'pointermove', event => this.onResizeMove(event as PointerEvent))
183
+ this.listen(this.header, 'pointerup', event => this.onResizeEnd(event as PointerEvent))
184
+ this.listen(this.header, 'pointercancel', event => this.onResizeEnd(event as PointerEvent))
185
+ if (this.filterInput)
186
+ this.listen(this.filterInput, 'input', () => this.onFilterInput())
187
+ const csv = part(root, 'export-csv')
188
+ const json = part(root, 'export-json')
189
+ if (csv)
190
+ this.listen(csv, 'click', () => this.download('csv'))
191
+ if (json)
192
+ this.listen(json, 'click', () => this.download('json'))
193
+
194
+ if (typeof ResizeObserver !== 'undefined') {
195
+ this.observer = new ResizeObserver(() => this.render())
196
+ this.observer.observe(this.scroller)
197
+ }
198
+
199
+ this.refresh()
200
+ root.setAttribute('data-dg-ready', '')
201
+ }
202
+
203
+ // The data
204
+
205
+ setRows(rows: readonly Row[] | null | undefined): void {
206
+ this.model.setRows(rows)
207
+ this.active = { row: Math.min(0, this.model.count - 1), column: Math.min(this.active.column, Math.max(0, this.model.columns.length - 1)) }
208
+ this.scroller.scrollTop = 0
209
+ this.refresh()
210
+ }
211
+
212
+ setColumns(columns: readonly GridColumn<Row>[] | null | undefined): void {
213
+ this.model.setColumns(columns)
214
+ this.active = { row: this.active.row, column: Math.min(this.active.column, Math.max(0, this.model.columns.length - 1)) }
215
+ this.refresh()
216
+ }
217
+
218
+ setFilter(text: string | null | undefined): void {
219
+ const next = text == null ? '' : String(text)
220
+ if (this.filterInput && this.filterInput.value !== next)
221
+ this.filterInput.value = next
222
+ this.applyFilter(next)
223
+ }
224
+
225
+ setSort(sort: readonly GridSort[] | null | undefined): void {
226
+ this.model.setSort(sort)
227
+ this.refresh()
228
+ }
229
+
230
+ setFileName(name: string): void {
231
+ this.fileName = name || 'data'
232
+ }
233
+
234
+ /** The rows on show, in order. */
235
+ getView(): Row[] {
236
+ return this.model.viewRows()
237
+ }
238
+
239
+ getSelection(): { rows: Row[], indices: number[] } {
240
+ const indices = this.model.selectedIndices()
241
+ return { rows: indices.map(index => this.model.rows[index]), indices }
242
+ }
243
+
244
+ clearSelection(): void {
245
+ this.model.clearSelection()
246
+ this.paintSelection()
247
+ this.reportSelection()
248
+ }
249
+
250
+ exportCsv(): string {
251
+ return this.model.toCsv()
252
+ }
253
+
254
+ exportJson(): string {
255
+ return this.model.toJson()
256
+ }
257
+
258
+ /** Save the rows on show as a file. Returns its text. */
259
+ download(format: 'csv' | 'json'): string {
260
+ const text = format === 'json' ? this.model.toJson() : this.model.toCsv()
261
+ const blob = new Blob([text], { type: format === 'json' ? 'application/json' : 'text/csv;charset=utf-8' })
262
+ const url = URL.createObjectURL(blob)
263
+ const link = document.createElement('a')
264
+ link.href = url
265
+ link.download = `${this.fileName}.${format}`
266
+ link.style.display = 'none'
267
+ this.root.appendChild(link)
268
+ link.click()
269
+ link.remove()
270
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
271
+ this.callbacks.onExport?.({ format, text, rows: this.model.count })
272
+ return text
273
+ }
274
+
275
+ scrollToRow(viewIndex: number): void {
276
+ const index = Math.max(0, Math.min(this.model.count - 1, viewIndex))
277
+ this.revealRow(index)
278
+ this.render()
279
+ }
280
+
281
+ focus(): void {
282
+ this.scroller.focus({ preventScroll: true })
283
+ }
284
+
285
+ /** The cell the keyboard is on. Row -1 is the header. */
286
+ getActiveCell(): GridCell {
287
+ return { ...this.active }
288
+ }
289
+
290
+ setActiveCell(row: number, column: number): void {
291
+ this.moveTo({ row, column }, false)
292
+ }
293
+
294
+ destroy(): void {
295
+ this.observer?.disconnect()
296
+ if (this.filterTimer)
297
+ clearTimeout(this.filterTimer)
298
+ for (const dispose of this.disposers) dispose()
299
+ this.header.replaceChildren()
300
+ this.body.replaceChildren()
301
+ this.slots.clear()
302
+ this.pool.length = 0
303
+ this.root.removeAttribute('data-dg-ready')
304
+ }
305
+
306
+ // Drawing
307
+
308
+ /** Everything may have changed: size the content and draw it all again. */
309
+ refresh(): void {
310
+ const model = this.model
311
+ this.content.style.width = `${model.totalWidth}px`
312
+ this.content.style.height = `${this.headerHeight + model.count * this.rowHeight}px`
313
+ this.header.style.width = `${model.totalWidth}px`
314
+ this.body.style.height = `${model.count * this.rowHeight}px`
315
+ this.scroller.setAttribute('aria-rowcount', String(model.count + 1))
316
+ this.scroller.setAttribute('aria-colcount', String(model.columns.length))
317
+ this.root.toggleAttribute('data-empty', model.count === 0)
318
+ this.stale = true
319
+ this.render()
320
+ this.paintStatus()
321
+ }
322
+
323
+ /**
324
+ * Draw what the viewport shows now. Called on every scroll, so it does only
325
+ * what moved: rows that came in are filled, rows that left are pooled, and
326
+ * the cells of a row that stayed are untouched unless the columns shifted.
327
+ */
328
+ render(): void {
329
+ const model = this.model
330
+ const scroller = this.scroller
331
+ const rows = rowRange(scroller.scrollTop, Math.max(0, scroller.clientHeight - this.headerHeight), this.rowHeight, model.count, this.overscan)
332
+ const cols = model.columnRange(scroller.scrollLeft, scroller.clientWidth, this.columnOverscan)
333
+ const columnsMoved = this.stale || cols.start !== this.cols.start || cols.end !== this.cols.end
334
+
335
+ if (!columnsMoved && rows.start === this.rows.start && rows.end === this.rows.end)
336
+ return
337
+
338
+ this.rows = rows
339
+ this.cols = cols
340
+
341
+ if (columnsMoved)
342
+ this.renderHeader()
343
+
344
+ for (const [index, slot] of this.slots) {
345
+ if (index < rows.start || index >= rows.end) {
346
+ this.slots.delete(index)
347
+ slot.index = -1
348
+ slot.el.style.display = 'none'
349
+ this.pool.push(slot)
350
+ }
351
+ }
352
+
353
+ for (let index = rows.start; index < rows.end; index++) {
354
+ let slot = this.slots.get(index)
355
+ if (slot) {
356
+ if (columnsMoved)
357
+ this.fill(slot)
358
+ continue
359
+ }
360
+ slot = this.pool.pop() ?? this.createSlot()
361
+ slot.index = index
362
+ slot.el.style.display = ''
363
+ this.slots.set(index, slot)
364
+ this.fill(slot)
365
+ }
366
+
367
+ this.stale = false
368
+ this.paintActive()
369
+ }
370
+
371
+ private createSlot(): RowSlot {
372
+ const el = document.createElement('div')
373
+ el.className = 'stx-dg-row'
374
+ el.setAttribute('role', 'row')
375
+ this.body.appendChild(el)
376
+ return { el, index: -1, cells: [] }
377
+ }
378
+
379
+ private fill(slot: RowSlot): void {
380
+ const model = this.model
381
+ const index = slot.index
382
+ const row = model.rowAt(index)
383
+ const selected = this.selectable && model.isSelected(index)
384
+ const el = slot.el as RowElement
385
+
386
+ el.__dgRow = index
387
+ el.style.transform = `translateY(${index * this.rowHeight}px)`
388
+ el.setAttribute('aria-rowindex', String(index + 2))
389
+ if (this.selectable)
390
+ el.setAttribute('aria-selected', selected ? 'true' : 'false')
391
+
392
+ const wanted = this.cols.end - this.cols.start
393
+ while (slot.cells.length < wanted) {
394
+ const cell = document.createElement('div')
395
+ cell.className = 'stx-dg-cell'
396
+ cell.setAttribute('role', 'gridcell')
397
+ cell.appendChild(document.createTextNode(''))
398
+ el.appendChild(cell)
399
+ slot.cells.push(cell)
400
+ }
401
+ while (slot.cells.length > wanted)
402
+ slot.cells.pop()!.remove()
403
+
404
+ for (let position = 0; position < wanted; position++) {
405
+ const columnIndex = this.cols.start + position
406
+ const column = model.columns[columnIndex]
407
+ const cell = slot.cells[position] as CellElement
408
+ const value = row === undefined ? undefined : cellValue(row, column)
409
+ const kind = cellKind(value)
410
+
411
+ cell.__dgColumn = columnIndex
412
+ cell.id = `${this.prefix}-r${index}-c${columnIndex}`
413
+ cell.style.left = `${model.offsetOf(columnIndex)}px`
414
+ cell.style.width = `${column.width}px`
415
+ cell.setAttribute('aria-colindex', String(columnIndex + 1))
416
+ cell.setAttribute('data-type', column.type)
417
+ cell.setAttribute('data-align', column.align)
418
+ if (kind === 'value')
419
+ cell.removeAttribute('data-empty')
420
+ else
421
+ cell.setAttribute('data-empty', kind)
422
+ if (this.selectable)
423
+ cell.setAttribute('aria-selected', selected ? 'true' : 'false')
424
+ // The text node is the cell's own and is kept: only its value changes.
425
+ ;(cell.firstChild as Text).data = typeof value === 'string' ? value : formatCell(value, column.type)
426
+ }
427
+ }
428
+
429
+ private renderHeader(): void {
430
+ const model = this.model
431
+ const wanted = this.cols.end - this.cols.start
432
+
433
+ while (this.headerCells.length < wanted) {
434
+ const cell = document.createElement('div')
435
+ cell.className = 'stx-dg-head'
436
+ cell.setAttribute('role', 'columnheader')
437
+ const label = document.createElement('span')
438
+ label.className = 'stx-dg-head-label'
439
+ label.appendChild(document.createTextNode(''))
440
+ const mark = document.createElement('span')
441
+ mark.className = 'stx-dg-sort'
442
+ mark.setAttribute('aria-hidden', 'true')
443
+ mark.appendChild(document.createTextNode(''))
444
+ const handle = document.createElement('span')
445
+ handle.className = 'stx-dg-resize'
446
+ handle.setAttribute('aria-hidden', 'true')
447
+ cell.append(label, mark, handle)
448
+ this.header.appendChild(cell)
449
+ this.headerCells.push(cell)
450
+ }
451
+ while (this.headerCells.length > wanted)
452
+ this.headerCells.pop()!.remove()
453
+
454
+ for (let position = 0; position < wanted; position++) {
455
+ const columnIndex = this.cols.start + position
456
+ const column = model.columns[columnIndex]
457
+ const cell = this.headerCells[position] as CellElement
458
+ const sorted = model.sortOf(column.key)
459
+
460
+ cell.__dgColumn = columnIndex
461
+ cell.id = `${this.prefix}-h-c${columnIndex}`
462
+ cell.style.left = `${model.offsetOf(columnIndex)}px`
463
+ cell.style.width = `${column.width}px`
464
+ cell.setAttribute('aria-colindex', String(columnIndex + 1))
465
+ cell.setAttribute('data-align', column.align)
466
+ cell.toggleAttribute('data-sortable', column.sortable)
467
+ if (column.sortable)
468
+ cell.setAttribute('aria-sort', sorted ? (sorted.direction === 'asc' ? 'ascending' : 'descending') : 'none')
469
+ else
470
+ cell.removeAttribute('aria-sort')
471
+ ;(cell.children[0].firstChild as Text).data = column.label
472
+ // An arrow, and the column's place when several are sorted by.
473
+ ;(cell.children[1].firstChild as Text).data = sorted
474
+ ? `${sorted.direction === 'asc' ? '▲' : '▼'}${model.sort.length > 1 ? sorted.priority : ''}`
475
+ : ''
476
+ }
477
+ }
478
+
479
+ private cellElement(cell: GridCell): HTMLElement | null {
480
+ if (cell.column < this.cols.start || cell.column >= this.cols.end)
481
+ return null
482
+ const position = cell.column - this.cols.start
483
+ if (cell.row < 0)
484
+ return this.headerCells[position] ?? null
485
+ return this.slots.get(cell.row)?.cells[position] ?? null
486
+ }
487
+
488
+ /** Mark the active cell, and tell assistive technology which one it is. */
489
+ private paintActive(): void {
490
+ const next = this.cellElement(this.active)
491
+ if (this.activeEl && this.activeEl !== next)
492
+ this.activeEl.removeAttribute('data-active')
493
+ this.activeEl = next
494
+ if (next) {
495
+ next.setAttribute('data-active', '')
496
+ this.scroller.setAttribute('aria-activedescendant', next.id)
497
+ }
498
+ else {
499
+ this.scroller.removeAttribute('aria-activedescendant')
500
+ }
501
+ }
502
+
503
+ private paintSelection(): void {
504
+ if (!this.selectable)
505
+ return
506
+ for (const [index, slot] of this.slots) {
507
+ const value = this.model.isSelected(index) ? 'true' : 'false'
508
+ slot.el.setAttribute('aria-selected', value)
509
+ for (const cell of slot.cells)
510
+ cell.setAttribute('aria-selected', value)
511
+ }
512
+ this.paintStatus()
513
+ }
514
+
515
+ private paintStatus(): void {
516
+ if (!this.status)
517
+ return
518
+ const model = this.model
519
+ const total = model.rows.length
520
+ let text = model.count === total
521
+ ? `${numberFormat.format(total)} ${total === 1 ? 'row' : 'rows'}`
522
+ : `${numberFormat.format(model.count)} of ${numberFormat.format(total)} rows`
523
+ if (model.selected.size > 0)
524
+ text += `, ${numberFormat.format(model.selected.size)} selected`
525
+ if (this.status.textContent !== text)
526
+ this.status.textContent = text
527
+ }
528
+
529
+ // Moving about
530
+
531
+ private revealRow(index: number): void {
532
+ const scroller = this.scroller
533
+ const top = index * this.rowHeight
534
+ const room = scroller.clientHeight - this.headerHeight
535
+ if (top < scroller.scrollTop)
536
+ scroller.scrollTop = top
537
+ else if (top + this.rowHeight > scroller.scrollTop + room)
538
+ scroller.scrollTop = top + this.rowHeight - room
539
+ }
540
+
541
+ private revealColumn(index: number): void {
542
+ const scroller = this.scroller
543
+ const left = this.model.offsetOf(index)
544
+ const right = this.model.offsetOf(index + 1)
545
+ if (left < scroller.scrollLeft)
546
+ scroller.scrollLeft = left
547
+ else if (right > scroller.scrollLeft + scroller.clientWidth)
548
+ scroller.scrollLeft = Math.min(left, right - scroller.clientWidth)
549
+ }
550
+
551
+ private detail(cell: GridCell): GridCellDetail<Row> {
552
+ return {
553
+ row: this.model.rowAt(cell.row),
554
+ rowIndex: cell.row,
555
+ column: this.model.columns[cell.column],
556
+ value: cell.row < 0 ? undefined : this.model.valueAt(cell.row, cell.column),
557
+ }
558
+ }
559
+
560
+ private moveTo(cell: GridCell, report = true): void {
561
+ const model = this.model
562
+ const next = {
563
+ row: Math.max(-1, Math.min(model.count - 1, cell.row)),
564
+ column: Math.max(0, Math.min(model.columns.length - 1, cell.column)),
565
+ }
566
+ this.active = next
567
+ if (next.row >= 0)
568
+ this.revealRow(next.row)
569
+ this.revealColumn(next.column)
570
+ this.render()
571
+ this.paintActive()
572
+ if (report)
573
+ this.callbacks.onCell?.(this.detail(next))
574
+ }
575
+
576
+ private reportSelection(): void {
577
+ this.callbacks.onSelect?.(this.getSelection())
578
+ }
579
+
580
+ private applyFilter(text: string): void {
581
+ const count = this.model.setFilter(text)
582
+ this.active = { row: Math.min(0, count - 1), column: this.active.column }
583
+ this.scroller.scrollTop = 0
584
+ this.refresh()
585
+ this.callbacks.onFilter?.({ text, count })
586
+ }
587
+
588
+ private sortBy(columnIndex: number, additive: boolean): void {
589
+ const column = this.model.columns[columnIndex]
590
+ if (!column || !column.sortable)
591
+ return
592
+ const sort = this.model.toggleSort(column.key, additive)
593
+ this.refresh()
594
+ this.callbacks.onSort?.([...sort])
595
+ }
596
+
597
+ private setColumnWidth(columnIndex: number, width: number): void {
598
+ this.model.resizeColumn(columnIndex, width)
599
+ this.content.style.width = `${this.model.totalWidth}px`
600
+ this.header.style.width = `${this.model.totalWidth}px`
601
+ this.stale = true
602
+ this.render()
603
+ }
604
+
605
+ private copy(what: 'cell' | 'row'): void {
606
+ if (this.active.row < 0)
607
+ return
608
+ const row = this.model.rowAt(this.active.row)
609
+ if (row === undefined)
610
+ return
611
+ const text = what === 'row' ? rowJson(row, this.model.columns) : cellJson(this.model.valueAt(this.active.row, this.active.column))
612
+ writeClipboard(text)
613
+ this.callbacks.onCopy?.({ what, text })
614
+ }
615
+
616
+ // Events
617
+
618
+ private listen(target: HTMLElement, type: string, handler: (event: Event) => void): void {
619
+ target.addEventListener(type, handler)
620
+ this.disposers.push(() => target.removeEventListener(type, handler))
621
+ }
622
+
623
+ private cellFrom(event: Event): GridCell | null {
624
+ const target = event.target as HTMLElement | null
625
+ const cell = target?.closest<HTMLElement>('.stx-dg-cell') as CellElement | null
626
+ const row = cell?.parentElement as RowElement | null
627
+ if (!cell || !row || cell.__dgColumn === undefined || row.__dgRow === undefined)
628
+ return null
629
+ return { row: row.__dgRow, column: cell.__dgColumn }
630
+ }
631
+
632
+ private headFrom(event: Event): { column: number, onHandle: boolean, handle: HTMLElement | null } | null {
633
+ const target = event.target as HTMLElement | null
634
+ const head = target?.closest<HTMLElement>('.stx-dg-head') as CellElement | null
635
+ if (!head || head.__dgColumn === undefined)
636
+ return null
637
+ const handle = target!.closest<HTMLElement>('.stx-dg-resize')
638
+ return { column: head.__dgColumn, onHandle: Boolean(handle), handle }
639
+ }
640
+
641
+ private onBodyClick(event: MouseEvent): void {
642
+ const cell = this.cellFrom(event)
643
+ if (!cell)
644
+ return
645
+ if (this.selectable) {
646
+ this.model.select(cell.row, event.shiftKey ? 'range' : (event.metaKey || event.ctrlKey ? 'toggle' : 'replace'))
647
+ this.paintSelection()
648
+ this.reportSelection()
649
+ }
650
+ this.moveTo(cell)
651
+ }
652
+
653
+ private onBodyDoubleClick(event: MouseEvent): void {
654
+ const cell = this.cellFrom(event)
655
+ const row = cell ? this.model.rowAt(cell.row) : undefined
656
+ if (cell && row !== undefined)
657
+ this.callbacks.onActivate?.({ row, rowIndex: cell.row })
658
+ }
659
+
660
+ private onContextMenu(event: MouseEvent): void {
661
+ const cell = this.cellFrom(event)
662
+ if (!cell)
663
+ return
664
+ if (this.contextMenu)
665
+ event.preventDefault()
666
+ this.moveTo(cell, false)
667
+ this.callbacks.onContext?.({ ...this.detail(cell), x: event.clientX, y: event.clientY })
668
+ }
669
+
670
+ private onHeaderClick(event: MouseEvent): void {
671
+ const head = this.headFrom(event)
672
+ if (!head || head.onHandle)
673
+ return
674
+ this.active = { row: -1, column: head.column }
675
+ this.sortBy(head.column, event.shiftKey)
676
+ }
677
+
678
+ private onHeaderDoubleClick(event: MouseEvent): void {
679
+ const head = this.headFrom(event)
680
+ if (head && head.onHandle)
681
+ this.setColumnWidth(head.column, this.model.autoWidth(head.column))
682
+ }
683
+
684
+ private onResizeStart(event: PointerEvent): void {
685
+ const head = this.headFrom(event)
686
+ if (!head || !head.onHandle || !head.handle || event.button !== 0)
687
+ return
688
+ event.preventDefault()
689
+ try {
690
+ head.handle.setPointerCapture(event.pointerId)
691
+ }
692
+ catch {}
693
+ this.resize = { column: head.column, start: event.clientX, width: this.model.columns[head.column].width, pointer: event.pointerId, handle: head.handle }
694
+ this.root.setAttribute('data-resizing', '')
695
+ }
696
+
697
+ private onResizeMove(event: PointerEvent): void {
698
+ const resize = this.resize
699
+ if (!resize || event.pointerId !== resize.pointer)
700
+ return
701
+ this.setColumnWidth(resize.column, resize.width + event.clientX - resize.start)
702
+ }
703
+
704
+ private onResizeEnd(event: PointerEvent): void {
705
+ const resize = this.resize
706
+ if (!resize || event.pointerId !== resize.pointer)
707
+ return
708
+ this.resize = null
709
+ this.root.removeAttribute('data-resizing')
710
+ try {
711
+ resize.handle.releasePointerCapture(event.pointerId)
712
+ }
713
+ catch {}
714
+ }
715
+
716
+ private onFilterInput(): void {
717
+ if (this.filterTimer)
718
+ clearTimeout(this.filterTimer)
719
+ // A hundred thousand rows are searched per keystroke otherwise, and only
720
+ // the last of a burst of keys is a question anyone asked.
721
+ this.filterTimer = setTimeout(() => {
722
+ this.filterTimer = null
723
+ this.applyFilter(this.filterInput ? this.filterInput.value : '')
724
+ }, FILTER_DELAY)
725
+ }
726
+
727
+ private onKeyDown(event: KeyboardEvent): void {
728
+ if (event.target !== this.scroller)
729
+ return
730
+ const model = this.model
731
+ const mod = event.metaKey || event.ctrlKey
732
+ const onHeader = this.active.row < 0
733
+ const key = event.key
734
+
735
+ if (mod && (key === 'a' || key === 'A')) {
736
+ if (!this.selectable)
737
+ return
738
+ event.preventDefault()
739
+ model.selectAll()
740
+ this.paintSelection()
741
+ this.reportSelection()
742
+ return
743
+ }
744
+
745
+ if (mod && (key === 'c' || key === 'C')) {
746
+ if (onHeader)
747
+ return
748
+ event.preventDefault()
749
+ this.copy(event.shiftKey ? 'row' : 'cell')
750
+ return
751
+ }
752
+
753
+ if (onHeader && event.altKey && (key === 'ArrowLeft' || key === 'ArrowRight')) {
754
+ event.preventDefault()
755
+ const column = model.columns[this.active.column]
756
+ if (column)
757
+ this.setColumnWidth(this.active.column, column.width + (key === 'ArrowRight' ? this.resizeStep : -this.resizeStep))
758
+ this.paintActive()
759
+ return
760
+ }
761
+
762
+ if (key === 'Enter' || key === ' ') {
763
+ event.preventDefault()
764
+ if (onHeader) {
765
+ this.sortBy(this.active.column, event.shiftKey)
766
+ return
767
+ }
768
+ if (key === ' ') {
769
+ if (!this.selectable)
770
+ return
771
+ model.select(this.active.row, 'toggle')
772
+ this.paintSelection()
773
+ this.reportSelection()
774
+ return
775
+ }
776
+ const row = model.rowAt(this.active.row)
777
+ if (row !== undefined)
778
+ this.callbacks.onActivate?.({ row, rowIndex: this.active.row })
779
+ return
780
+ }
781
+
782
+ if (key === 'Escape' && this.selectable && model.selected.size > 0) {
783
+ event.preventDefault()
784
+ this.clearSelection()
785
+ return
786
+ }
787
+
788
+ const page = Math.max(1, Math.floor((this.scroller.clientHeight - this.headerHeight) / this.rowHeight) - 1)
789
+ const next = moveCell(this.active, key, { rows: model.count, columns: model.columns.length, page, mod })
790
+ if (next === this.active)
791
+ return
792
+
793
+ event.preventDefault()
794
+ if (next.row === this.active.row && next.column === this.active.column)
795
+ return
796
+ // Shift with a move down or up the rows carries the selection along.
797
+ if (event.shiftKey && this.selectable && next.row >= 0 && next.row !== this.active.row) {
798
+ if (model.selected.size === 0 && this.active.row >= 0)
799
+ model.select(this.active.row, 'replace')
800
+ model.select(next.row, 'range')
801
+ this.paintSelection()
802
+ this.reportSelection()
803
+ }
804
+ this.moveTo(next)
805
+ }
806
+ }