@spfx-fast/sharepoint-ui 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/QUICKSTART.md +13 -128
  2. package/README.md +19 -26
  3. package/components.json +240 -5834
  4. package/dist/accordion.d.ts +11 -0
  5. package/dist/accordion.js +4 -0
  6. package/dist/alert.d.ts +3 -0
  7. package/dist/alert.js +4 -0
  8. package/dist/attachment-list.d.ts +15 -0
  9. package/dist/attachment-list.js +14 -0
  10. package/dist/avatar-group.d.ts +12 -0
  11. package/dist/avatar-group.js +7 -0
  12. package/dist/avatar.d.ts +6 -0
  13. package/dist/avatar.js +5 -0
  14. package/dist/badge.d.ts +3 -0
  15. package/dist/badge.js +4 -0
  16. package/dist/breadcrumb.d.ts +10 -0
  17. package/dist/breadcrumb.js +9 -0
  18. package/dist/button-group.d.ts +6 -0
  19. package/dist/button-group.js +4 -0
  20. package/dist/button.d.ts +3 -0
  21. package/dist/button.js +4 -0
  22. package/dist/card.d.ts +3 -0
  23. package/dist/card.js +4 -0
  24. package/dist/carousel.d.ts +11 -0
  25. package/dist/carousel.js +6 -0
  26. package/dist/checkbox.d.ts +3 -0
  27. package/dist/checkbox.js +4 -0
  28. package/dist/combobox.d.ts +9 -0
  29. package/dist/combobox.js +6 -0
  30. package/dist/command-bar.d.ts +6 -0
  31. package/dist/command-bar.js +4 -0
  32. package/dist/copy-button.d.ts +7 -0
  33. package/dist/copy-button.js +19 -0
  34. package/dist/data-grid.d.ts +25 -0
  35. package/dist/data-grid.js +39 -0
  36. package/dist/date-range-picker.d.ts +12 -0
  37. package/dist/date-range-picker.js +4 -0
  38. package/dist/dialog.d.ts +9 -0
  39. package/dist/dialog.js +21 -0
  40. package/dist/divider.d.ts +3 -0
  41. package/dist/divider.js +4 -0
  42. package/dist/drawer.d.ts +6 -0
  43. package/dist/drawer.js +5 -0
  44. package/dist/empty-state.d.ts +7 -0
  45. package/dist/empty-state.js +5 -0
  46. package/dist/field.d.ts +15 -0
  47. package/dist/field.js +11 -0
  48. package/dist/file-dropzone.d.ts +15 -0
  49. package/dist/file-dropzone.js +21 -0
  50. package/dist/filter-bar.d.ts +9 -0
  51. package/dist/filter-bar.js +9 -0
  52. package/dist/image.d.ts +5 -0
  53. package/dist/image.js +4 -0
  54. package/dist/index.d.ts +68 -78
  55. package/dist/index.js +60 -68
  56. package/dist/input.d.ts +3 -0
  57. package/dist/input.js +4 -0
  58. package/dist/label.d.ts +3 -0
  59. package/dist/label.js +4 -0
  60. package/dist/link.d.ts +3 -0
  61. package/dist/link.js +9 -0
  62. package/dist/list-view.d.ts +29 -0
  63. package/dist/list-view.js +14 -0
  64. package/dist/list.d.ts +6 -0
  65. package/dist/list.js +5 -0
  66. package/dist/lookup-picker.d.ts +12 -0
  67. package/dist/lookup-picker.js +4 -0
  68. package/dist/menu.d.ts +6 -0
  69. package/dist/menu.js +4 -0
  70. package/dist/nav.d.ts +12 -0
  71. package/dist/nav.js +4 -0
  72. package/dist/pagination.d.ts +11 -0
  73. package/dist/pagination.js +5 -0
  74. package/dist/person-picker.d.ts +13 -0
  75. package/dist/person-picker.js +4 -0
  76. package/dist/persona.d.ts +7 -0
  77. package/dist/persona.js +5 -0
  78. package/dist/popover.d.ts +6 -0
  79. package/dist/popover.js +4 -0
  80. package/dist/progress-bar.d.ts +5 -0
  81. package/dist/progress-bar.js +5 -0
  82. package/dist/radio-group.d.ts +6 -0
  83. package/dist/radio-group.js +4 -0
  84. package/dist/radio.d.ts +3 -0
  85. package/dist/radio.js +4 -0
  86. package/dist/rating.d.ts +8 -0
  87. package/dist/rating.js +5 -0
  88. package/dist/react.d.ts +1 -4715
  89. package/dist/react.js +1 -7097
  90. package/dist/select.d.ts +3 -0
  91. package/dist/select.js +4 -0
  92. package/dist/sharepoint-field.d.ts +18 -0
  93. package/dist/sharepoint-field.js +54 -0
  94. package/dist/skeleton.d.ts +6 -0
  95. package/dist/skeleton.js +9 -0
  96. package/dist/spinner.d.ts +5 -0
  97. package/dist/spinner.js +4 -0
  98. package/dist/swatch-picker.d.ts +17 -0
  99. package/dist/swatch-picker.js +11 -0
  100. package/dist/switch.d.ts +3 -0
  101. package/dist/switch.js +4 -0
  102. package/dist/table.d.ts +6 -0
  103. package/dist/table.js +4 -0
  104. package/dist/tabs.d.ts +14 -0
  105. package/dist/tabs.js +30 -0
  106. package/dist/tag-group.d.ts +6 -0
  107. package/dist/tag-group.js +4 -0
  108. package/dist/tag-picker.d.ts +12 -0
  109. package/dist/tag-picker.js +4 -0
  110. package/dist/tag.d.ts +7 -0
  111. package/dist/tag.js +5 -0
  112. package/dist/text.d.ts +5 -0
  113. package/dist/text.js +4 -0
  114. package/dist/textarea.d.ts +3 -0
  115. package/dist/textarea.js +4 -0
  116. package/dist/theme.d.ts +15 -175
  117. package/dist/theme.js +36 -239
  118. package/dist/toast.d.ts +9 -0
  119. package/dist/toast.js +12 -0
  120. package/dist/tree.d.ts +13 -0
  121. package/dist/tree.js +9 -0
  122. package/dist/view-card.d.ts +8 -0
  123. package/dist/view-card.js +4 -0
  124. package/dist/view-switcher.d.ts +13 -0
  125. package/dist/view-switcher.js +7 -0
  126. package/dist/virtual-list.d.ts +11 -0
  127. package/dist/virtual-list.js +25 -0
  128. package/measurements.json +365 -0
  129. package/package.json +14 -46
  130. package/src/theme.css +125 -0
  131. package/AGENTS.md +0 -231
  132. package/dist/appearance.d.ts +0 -6
  133. package/dist/appearance.js +0 -217
  134. package/dist/elements/accordion.d.ts +0 -9
  135. package/dist/elements/accordion.js +0 -338
  136. package/dist/elements/alert.d.ts +0 -2
  137. package/dist/elements/alert.js +0 -86
  138. package/dist/elements/avatar-group-primitives.d.ts +0 -3
  139. package/dist/elements/avatar-group-primitives.js +0 -189
  140. package/dist/elements/avatar-group.d.ts +0 -2
  141. package/dist/elements/avatar-group.js +0 -110
  142. package/dist/elements/avatar.d.ts +0 -4
  143. package/dist/elements/avatar.js +0 -251
  144. package/dist/elements/badge.d.ts +0 -8
  145. package/dist/elements/badge.js +0 -182
  146. package/dist/elements/breadcrumb.d.ts +0 -4
  147. package/dist/elements/breadcrumb.js +0 -233
  148. package/dist/elements/button-group.d.ts +0 -1
  149. package/dist/elements/button-group.js +0 -20
  150. package/dist/elements/button-variants.d.ts +0 -6
  151. package/dist/elements/button-variants.js +0 -339
  152. package/dist/elements/button.d.ts +0 -5
  153. package/dist/elements/button.js +0 -233
  154. package/dist/elements/card-primitives.d.ts +0 -3
  155. package/dist/elements/card-primitives.js +0 -83
  156. package/dist/elements/card.d.ts +0 -5
  157. package/dist/elements/card.js +0 -213
  158. package/dist/elements/carousel.d.ts +0 -92
  159. package/dist/elements/carousel.js +0 -1115
  160. package/dist/elements/color-picker.d.ts +0 -24
  161. package/dist/elements/color-picker.js +0 -1004
  162. package/dist/elements/combobox.d.ts +0 -1
  163. package/dist/elements/combobox.js +0 -1012
  164. package/dist/elements/data-grid-model.d.ts +0 -120
  165. package/dist/elements/data-grid-model.js +0 -294
  166. package/dist/elements/data-grid.d.ts +0 -30
  167. package/dist/elements/data-grid.js +0 -1576
  168. package/dist/elements/date-picker.d.ts +0 -1
  169. package/dist/elements/date-picker.js +0 -486
  170. package/dist/elements/dialog.d.ts +0 -23
  171. package/dist/elements/dialog.js +0 -409
  172. package/dist/elements/divider.d.ts +0 -2
  173. package/dist/elements/divider.js +0 -66
  174. package/dist/elements/drawer.d.ts +0 -3
  175. package/dist/elements/drawer.js +0 -308
  176. package/dist/elements/field-composition.d.ts +0 -26
  177. package/dist/elements/field-composition.js +0 -133
  178. package/dist/elements/field.d.ts +0 -1
  179. package/dist/elements/field.js +0 -67
  180. package/dist/elements/file-upload.d.ts +0 -6
  181. package/dist/elements/file-upload.js +0 -211
  182. package/dist/elements/floating-position.d.ts +0 -36
  183. package/dist/elements/floating-position.js +0 -92
  184. package/dist/elements/image.d.ts +0 -28
  185. package/dist/elements/image.js +0 -38
  186. package/dist/elements/info.d.ts +0 -9
  187. package/dist/elements/info.js +0 -102
  188. package/dist/elements/input.d.ts +0 -5
  189. package/dist/elements/input.js +0 -255
  190. package/dist/elements/label.d.ts +0 -15
  191. package/dist/elements/label.js +0 -56
  192. package/dist/elements/link.d.ts +0 -1
  193. package/dist/elements/link.js +0 -92
  194. package/dist/elements/list.d.ts +0 -19
  195. package/dist/elements/list.js +0 -297
  196. package/dist/elements/menu.d.ts +0 -33
  197. package/dist/elements/menu.js +0 -1103
  198. package/dist/elements/message-bar.d.ts +0 -10
  199. package/dist/elements/message-bar.js +0 -327
  200. package/dist/elements/nav.d.ts +0 -32
  201. package/dist/elements/nav.js +0 -794
  202. package/dist/elements/overflow.d.ts +0 -10
  203. package/dist/elements/overflow.js +0 -218
  204. package/dist/elements/persona.d.ts +0 -3
  205. package/dist/elements/persona.js +0 -125
  206. package/dist/elements/popover.d.ts +0 -77
  207. package/dist/elements/popover.js +0 -840
  208. package/dist/elements/progress-bar.d.ts +0 -4
  209. package/dist/elements/progress-bar.js +0 -82
  210. package/dist/elements/radio-group.d.ts +0 -1
  211. package/dist/elements/radio-group.js +0 -303
  212. package/dist/elements/rating-display.d.ts +0 -2
  213. package/dist/elements/rating-display.js +0 -125
  214. package/dist/elements/rating.d.ts +0 -2
  215. package/dist/elements/rating.js +0 -206
  216. package/dist/elements/rich-text-editor.d.ts +0 -32
  217. package/dist/elements/rich-text-editor.js +0 -1367
  218. package/dist/elements/search.d.ts +0 -3
  219. package/dist/elements/search.js +0 -200
  220. package/dist/elements/select.d.ts +0 -6
  221. package/dist/elements/select.js +0 -291
  222. package/dist/elements/shared.d.ts +0 -22
  223. package/dist/elements/shared.js +0 -409
  224. package/dist/elements/sharepoint-field-basic-controls.d.ts +0 -1
  225. package/dist/elements/sharepoint-field-basic-controls.js +0 -14
  226. package/dist/elements/sharepoint-fields.d.ts +0 -29
  227. package/dist/elements/sharepoint-fields.js +0 -460
  228. package/dist/elements/skeleton.d.ts +0 -6
  229. package/dist/elements/skeleton.js +0 -91
  230. package/dist/elements/slider.d.ts +0 -1
  231. package/dist/elements/slider.js +0 -248
  232. package/dist/elements/spin-button.d.ts +0 -7
  233. package/dist/elements/spin-button.js +0 -499
  234. package/dist/elements/spinner.d.ts +0 -4
  235. package/dist/elements/spinner.js +0 -124
  236. package/dist/elements/swatch-picker.d.ts +0 -5
  237. package/dist/elements/swatch-picker.js +0 -363
  238. package/dist/elements/table.d.ts +0 -21
  239. package/dist/elements/table.js +0 -261
  240. package/dist/elements/tabs.d.ts +0 -1
  241. package/dist/elements/tabs.js +0 -276
  242. package/dist/elements/tag-picker.d.ts +0 -29
  243. package/dist/elements/tag-picker.js +0 -715
  244. package/dist/elements/tags.d.ts +0 -21
  245. package/dist/elements/tags.js +0 -421
  246. package/dist/elements/teaching-popover.d.ts +0 -32
  247. package/dist/elements/teaching-popover.js +0 -412
  248. package/dist/elements/text.d.ts +0 -9
  249. package/dist/elements/text.js +0 -75
  250. package/dist/elements/textarea.d.ts +0 -1
  251. package/dist/elements/textarea.js +0 -182
  252. package/dist/elements/toast.d.ts +0 -25
  253. package/dist/elements/toast.js +0 -337
  254. package/dist/elements/toaster.d.ts +0 -6
  255. package/dist/elements/toaster.js +0 -357
  256. package/dist/elements/toggle.d.ts +0 -2
  257. package/dist/elements/toggle.js +0 -246
  258. package/dist/elements/toolbar.d.ts +0 -12
  259. package/dist/elements/toolbar.js +0 -381
  260. package/dist/elements/tooltip.d.ts +0 -76
  261. package/dist/elements/tooltip.js +0 -527
  262. package/dist/elements/tree-model.d.ts +0 -19
  263. package/dist/elements/tree-model.js +0 -34
  264. package/dist/elements/tree.d.ts +0 -5
  265. package/dist/elements/tree.js +0 -273
  266. package/dist/elements/view-card.d.ts +0 -2
  267. package/dist/elements/view-card.js +0 -78
  268. package/dist/elements/virtual-list.d.ts +0 -41
  269. package/dist/elements/virtual-list.js +0 -369
  270. package/dist/elements.d.ts +0 -73
  271. package/dist/elements.js +0 -210
  272. package/dist/sharepoint-fields.d.ts +0 -135
  273. package/dist/sharepoint-fields.js +0 -402
  274. package/dist/virtualizer-hooks.d.ts +0 -80
  275. package/dist/virtualizer-hooks.js +0 -253
  276. package/scripts/generate-token-index.mjs +0 -43
  277. package/scripts/sync-component-catalog-signatures.mjs +0 -55
  278. package/scripts/validate-component-catalog.mjs +0 -44
  279. package/skills/sharepoint-ui/SKILL.md +0 -12
  280. package/skills/sharepoint-ui/references/choosing-components.md +0 -20
  281. package/skills/sharepoint-ui/references/sharepoint-patterns.md +0 -17
  282. package/tokens.json +0 -3777
@@ -1,1576 +0,0 @@
1
- import { base } from "./shared.js";
2
- import { VariableSizeIndex } from "./virtual-list.js";
3
- import { clampDataGridColumnWidth, clampDataGridRowHeight, dataGridColumnVar, filterDataGridItems, fitDataGridColumnWidths, formatDataGridClipboard, getDataGridCellValue, getDataGridColumnSizing, getDataGridColumnWindow, groupDataGridItems, parseDataGridClipboard, parseDataGridClipboardValue, parseDataGridInputValue, sortDataGridItems, toDataGridInputValue, writeDataGridClipboardText, getDataGridDataSourceRow } from "./data-grid-model.js";
4
- let nextGridId = 0;
5
- /** Accessible, virtualized grid engine for non-React and React consumers. */
6
- export function defineDataGrid() {
7
- if (customElements.get("spui-data-grid"))
8
- return;
9
- class SpuiDataGrid extends HTMLElement {
10
- static observedAttributes = ["aria-label", "label", "focus-mode", "selection-mode", "selection-appearance", "subtle-selection", "auto-fit-columns", "container-width-offset", "row-height", "overscan", "virtualize-columns", "select-label", "select-all-label", "empty-label", "no-results-label", "loading-label", "load-error-label", "edit-error-label", "filterable", "filter-label", "sort-priority-label", "resizable-columns", "resize-label", "reorderable-columns", "reorder-label", "reorder-hint-label", "group-by", "empty-group-label", "expand-group-label", "collapse-group-label", "row-label", "edit-hint", "selection-copied-label", "copy-failed-label", "paste-one-label", "paste-many-label", "paste-failed-label"];
11
- data = [];
12
- source;
13
- sourceUnsubscribe;
14
- sourceRequest;
15
- clipboardController;
16
- completedSourceRange = "";
17
- sortedData = [];
18
- definitions = [];
19
- renderer;
20
- keyOf;
21
- rowHeightGetter;
22
- heightRows;
23
- heightEstimate = 0;
24
- heightGetterAtIndex;
25
- rowSizes = new VariableSizeIndex();
26
- selected = new Set();
27
- sourceAllSelected = false;
28
- sourceAllSelectedScope;
29
- sourceExcludedKeys = new Set();
30
- currentSort;
31
- currentSorts = [];
32
- currentFilterValue = "";
33
- currentColumnWidths = {};
34
- fittedColumnWidths = {};
35
- sizingOptions = {};
36
- currentColumnOrder = [];
37
- draggedColumnId;
38
- resizing;
39
- rows = new Map();
40
- pool = [];
41
- viewport;
42
- filterBar;
43
- filterInput;
44
- header;
45
- body;
46
- reorderStatus;
47
- frame = 0;
48
- resizeObserver;
49
- columnWindowChanged = false;
50
- activeCell = { row: 0, column: 0 };
51
- pendingBoundaryFocus;
52
- get focusMode() { const value = this.getAttribute("focus-mode"); return value === "none" || value === "row_unstable" || value === "composite" ? value : "cell"; }
53
- set focusMode(value) { if (value === "cell")
54
- this.removeAttribute("focus-mode");
55
- else
56
- this.setAttribute("focus-mode", value); }
57
- get selectionAppearance() { const value = this.getAttribute("selection-appearance"); return value === "neutral" || value === "none" ? value : "brand"; }
58
- set selectionAppearance(value) { if (value === "brand")
59
- this.removeAttribute("selection-appearance");
60
- else
61
- this.setAttribute("selection-appearance", value); }
62
- get subtleSelection() { return this.hasAttribute("subtle-selection"); }
63
- set subtleSelection(value) { this.toggleAttribute("subtle-selection", value); }
64
- get columnSizingOptions() { return this.sizingOptions; }
65
- set columnSizingOptions(value) { this.sizingOptions = value && typeof value === "object" ? value : {}; this.initializeColumnWidths(); this.applyColumnWidthVariables(); this.renderHeader(); this.paint(true); }
66
- get autoFitColumns() { return this.getAttribute("auto-fit-columns") !== "false"; }
67
- set autoFitColumns(value) { if (value)
68
- this.removeAttribute("auto-fit-columns");
69
- else
70
- this.setAttribute("auto-fit-columns", "false"); }
71
- get containerWidthOffset() { const value = Number(this.getAttribute("container-width-offset")); return Number.isFinite(value) ? value : 0; }
72
- set containerWidthOffset(value) { if (Number.isFinite(value) && value !== 0)
73
- this.setAttribute("container-width-offset", String(value));
74
- else
75
- this.removeAttribute("container-width-offset"); }
76
- columnWindow = { start: 0, end: 16 };
77
- collapsedGroups = new Set();
78
- cachedDisplayRows;
79
- cachedSortedData;
80
- failedSourceRange = "";
81
- cachedGroupBy = "";
82
- cachedColumnIds = "";
83
- cachedCollapsedGroups;
84
- selectionName = `spui-grid-selection-${++nextGridId}`;
85
- editedValues = new Map();
86
- editingCell;
87
- editCallback;
88
- editErrorCallback;
89
- cellsEditCallback;
90
- dataSourceGroupToggleCallback;
91
- dataSourceSelectionCallback;
92
- editValidator;
93
- suppressEditorBlurCommit = false;
94
- get sourceSelectableCount() {
95
- const count = this.source?.selectableCount ?? this.source?.length ?? 0;
96
- return Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
97
- }
98
- get items() { return this.data; }
99
- set items(value) { this.clipboardController?.abort(); this.clipboardController = undefined; this.data = Array.isArray(value) ? value : []; this.source = undefined; this.sourceAllSelected = false; this.sourceAllSelectedScope = undefined; this.sourceExcludedKeys.clear(); this.sourceUnsubscribe?.(); this.sourceUnsubscribe = undefined; this.sourceRequest?.controller.abort(); this.sourceRequest = undefined; this.completedSourceRange = ""; this.failedSourceRange = ""; this.editedValues.clear(); this.editingCell = undefined; this.recomputeSort(); this.cachedDisplayRows = undefined; this.paint(true); }
100
- get dataSource() { return this.source; }
101
- set dataSource(value) {
102
- if (value === this.source) {
103
- this.refreshDataSource();
104
- return;
105
- }
106
- this.clipboardController?.abort();
107
- this.clipboardController = undefined;
108
- this.sourceRequest?.controller.abort();
109
- this.sourceRequest = undefined;
110
- this.sourceUnsubscribe?.();
111
- this.sourceUnsubscribe = undefined;
112
- this.source = value;
113
- this.completedSourceRange = "";
114
- this.failedSourceRange = "";
115
- this.cachedDisplayRows = undefined;
116
- this.recomputeSort();
117
- this.observeDataSource();
118
- if (this.reorderStatus)
119
- this.reorderStatus.textContent = "";
120
- this.paint(true);
121
- }
122
- get columns() { return this.definitions; }
123
- set columns(value) { this.definitions = Array.isArray(value) ? value.filter(column => column?.id && column.label) : []; this.currentColumnOrder = this.normalizeColumnOrder(this.currentColumnOrder); this.recomputeSort(); this.renderHeader(); this.initializeColumnWidths(); this.paint(true); }
124
- get renderCell() { return this.renderer; }
125
- set renderCell(value) { this.renderer = value; this.paint(true); }
126
- get itemKey() { return this.keyOf; }
127
- set itemKey(value) { this.keyOf = value; this.paint(true); }
128
- get getRowHeight() { return this.rowHeightGetter; }
129
- set getRowHeight(value) { this.rowHeightGetter = value; this.heightRows = undefined; this.paint(true); }
130
- get selectedKeys() { return this.sourceAllSelected ? [] : [...this.selected]; }
131
- set selectedKeys(value) { this.sourceAllSelected = false; this.sourceAllSelectedScope = undefined; this.sourceExcludedKeys.clear(); this.selected = new Set((value ?? []).map(String)); this.paint(true); }
132
- get selectionModel() { return this.sourceAllSelected ? { mode: "all", excludedKeys: [...this.sourceExcludedKeys], ...(this.sourceAllSelectedScope === undefined ? {} : { scopeKey: this.sourceAllSelectedScope }) } : { mode: "explicit", keys: [...this.selected] }; }
133
- set selectionModel(value) {
134
- if (value?.mode === "all") {
135
- this.sourceAllSelected = true;
136
- this.sourceAllSelectedScope = value.scopeKey;
137
- this.sourceExcludedKeys = new Set(value.excludedKeys.map(String));
138
- this.selected.clear();
139
- }
140
- else {
141
- this.sourceAllSelected = false;
142
- this.sourceAllSelectedScope = undefined;
143
- this.sourceExcludedKeys.clear();
144
- this.selected = new Set((value?.mode === "explicit" ? value.keys : []).map(String));
145
- }
146
- this.paint(true);
147
- }
148
- get sort() { return this.currentSort; }
149
- set sort(value) { this.currentSort = value; this.currentSorts = value ? [value] : []; this.recomputeSort(); this.renderHeader(); this.paint(true); }
150
- get sorts() { return this.currentSorts.map(entry => ({ ...entry })); }
151
- set sorts(value) { this.currentSorts = this.normalizeSorts(value); this.currentSort = this.currentSorts[0]; this.recomputeSort(); this.renderHeader(); this.paint(true); }
152
- get filterValue() { return this.currentFilterValue; }
153
- set filterValue(value) {
154
- const next = String(value ?? "");
155
- if (next === this.currentFilterValue)
156
- return;
157
- this.currentFilterValue = next;
158
- if (this.filterInput && this.filterInput.value !== next)
159
- this.filterInput.value = next;
160
- this.recomputeSort();
161
- this.paint(true);
162
- this.dispatchEvent(new CustomEvent("spui-filter-change", { detail: { filterValue: next }, bubbles: true, composed: true }));
163
- }
164
- get filterable() { return this.hasAttribute("filterable"); }
165
- set filterable(value) { this.toggleAttribute("filterable", Boolean(value)); }
166
- get columnOrder() { return [...this.orderedDefinitions.map(column => column.id)]; }
167
- set columnOrder(value) { this.currentColumnOrder = this.normalizeColumnOrder(value); this.renderHeader(); this.paint(true); }
168
- get resizableColumns() { return this.hasAttribute("resizable-columns"); }
169
- set resizableColumns(value) { this.toggleAttribute("resizable-columns", Boolean(value)); }
170
- get reorderableColumns() { return this.hasAttribute("reorderable-columns"); }
171
- set reorderableColumns(value) { this.toggleAttribute("reorderable-columns", Boolean(value)); }
172
- get virtualizeColumns() { const value = this.getAttribute("virtualize-columns"); return value === null ? this.orderedDefinitions.length > 16 : value !== "false"; }
173
- set virtualizeColumns(value) { this.setAttribute("virtualize-columns", String(Boolean(value))); }
174
- get columnWidths() { return this.currentColumnWidths; }
175
- set columnWidths(value) {
176
- this.currentColumnWidths = Object.fromEntries(Object.entries(value ?? {}).filter(([, width]) => Number.isFinite(width) && width > 0).map(([id, width]) => { const column = this.definitions.find(candidate => candidate.id === id); return [id, column ? clampDataGridColumnWidth(column, width, this.sizingOptions[id]) : Math.round(width)]; }));
177
- this.initializeColumnWidths();
178
- this.applyColumnWidthVariables();
179
- this.renderHeader();
180
- this.paint(true);
181
- }
182
- get groupBy() { return this.getAttribute("group-by") || ""; }
183
- set groupBy(value) { if (value)
184
- this.setAttribute("group-by", value);
185
- else
186
- this.removeAttribute("group-by"); }
187
- get collapsedGroupKeys() { return [...this.collapsedGroups]; }
188
- set collapsedGroupKeys(value) { this.collapsedGroups = new Set(value ?? []); this.paint(true); }
189
- get onCellEdit() { return this.editCallback; }
190
- set onCellEdit(value) { this.editCallback = value; }
191
- get onCellEditError() { return this.editErrorCallback; }
192
- set onCellEditError(value) { this.editErrorCallback = value; }
193
- get validateCellEdit() { return this.editValidator; }
194
- set validateCellEdit(value) { this.editValidator = value; }
195
- get onCellsEdit() { return this.cellsEditCallback; }
196
- set onCellsEdit(value) { this.cellsEditCallback = value; }
197
- get onDataSourceGroupToggle() { return this.dataSourceGroupToggleCallback; }
198
- set onDataSourceGroupToggle(value) { this.dataSourceGroupToggleCallback = value; }
199
- get onDataSourceSelectionChange() { return this.dataSourceSelectionCallback; }
200
- set onDataSourceSelectionChange(value) { this.dataSourceSelectionCallback = value; }
201
- refreshDataSource() { this.completedSourceRange = ""; this.failedSourceRange = ""; this.sourceRequest?.controller.abort(); this.sourceRequest = undefined; this.cachedDisplayRows = undefined; this.paint(true); }
202
- connectedCallback() {
203
- if (!this.shadowRoot)
204
- this.render();
205
- this.recomputeSort();
206
- this.resizeObserver ??= new ResizeObserver(() => { this.initializeColumnWidths(); this.paint(this.updateColumnWindow()); });
207
- if (this.viewport)
208
- this.resizeObserver.observe(this.viewport);
209
- this.observeDataSource();
210
- this.renderHeader();
211
- this.initializeColumnWidths();
212
- this.paint(true);
213
- }
214
- disconnectedCallback() { cancelAnimationFrame(this.frame); this.frame = 0; this.resizeObserver?.disconnect(); this.sourceRequest?.controller.abort(); this.sourceRequest = undefined; this.clipboardController?.abort(); this.clipboardController = undefined; this.sourceUnsubscribe?.(); this.sourceUnsubscribe = undefined; }
215
- attributeChangedCallback() { this.renderFilter(); this.renderHeader(); this.initializeColumnWidths(); this.paint(true); }
216
- localizedMessage(attribute, fallback, values = {}) {
217
- return Object.entries(values).reduce((message, [key, value]) => message.replaceAll(`{${key}}`, value), this.getAttribute(attribute) ?? fallback);
218
- }
219
- render() {
220
- const shadow = this.attachShadow({ mode: "open" });
221
- const style = document.createElement("style");
222
- style.textContent = `${base}:host{display:block;min-width:0}.viewport{box-sizing:border-box;position:relative;overflow:auto;height:var(--spui-data-grid-height,400px);overscroll-behavior:contain;border:1px solid var(--spui-data-grid-border,var(--spui-ui-stroke,var(--spui-semantic-body-divider,#d1d1d1)));border-radius:var(--spui-data-grid-radius,var(--spui-control-radius,6px));background:var(--spui-data-grid-background,var(--spui-base-surface,var(--spui-ui-surface,#fff)));outline:none}.viewport:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:2px}.header{position:sticky;top:0;z-index:2;background:var(--spui-data-grid-header-background,var(--spui-base-canvas,var(--spui-ui-canvas,#f5f5f5)));color:var(--spui-ui-text,var(--spui-semantic-body-text,#323130));box-shadow:0 1px 0 var(--spui-ui-stroke,#d1d1d1)}.row{box-sizing:border-box;display:grid;align-items:center;min-width:100%;border-block-end:1px solid var(--spui-ui-stroke,var(--spui-semantic-body-divider,#edebe9));background:var(--spui-data-grid-row-background,var(--spui-base-surface,var(--spui-ui-surface,#fff)));color:var(--spui-ui-text,var(--spui-semantic-body-text,#323130))}.data-row{position:absolute;inset-inline:0;top:0}.row:hover{background:var(--spui-data-grid-row-hover,var(--spui-ui-surface-hover,#f5f5f5))}.cell{box-sizing:border-box;display:flex;align-items:center;min-width:0;height:100%;padding-inline:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.header-cell{position:relative;font-weight:600}.resize-handle{position:absolute;z-index:1;inset-block:0;inset-inline-end:0;width:10px;display:flex;align-items:center;justify-content:center;touch-action:none;cursor:col-resize;outline:none}.resize-handle::after{content:"";width:1px;height:60%;background:transparent}.resize-handle:hover::after,.resize-handle:focus-visible::after{background:var(--spui-focus-ring,var(--spui-ui-accent,#0078d4))}.resize-handle:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:-2px}.header-cell button{display:flex;align-items:center;gap:6px;width:100%;height:100%;padding:0;border:0;background:transparent;color:inherit;font:inherit;text-align:start;cursor:pointer}.header-cell button:focus-visible,.cell:focus-visible,input:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:-2px}.selection-cell{justify-content:center;padding-inline:8px}.sort-indicator{color:var(--spui-ui-accent,var(--colorBrandForeground1,#0078d4))}.empty{padding:24px;color:var(--spui-ui-muted,var(--spui-semantic-body-subtext,#616161));text-align:center}@media(forced-colors:active){.viewport{border-color:CanvasText}.header{background:Canvas;color:CanvasText}.row{background:Canvas;color:CanvasText;border-color:CanvasText}.sort-indicator{color:LinkText}.resize-handle:focus-visible{outline-color:Highlight}.resize-handle::after{background:CanvasText}}`;
223
- style.textContent += ".body{position:relative;display:block}.reorder-handle{flex:none;width:24px;height:28px;margin-inline-end:4px;padding:0;border:0;border-radius:var(--spui-control-radius,4px);background:transparent;color:var(--spui-ui-muted,var(--spui-semantic-body-subtext,#616161));font:inherit;cursor:grab}.header-cell .reorder-handle{width:24px;height:28px}.header-cell .reorder-handle+button{flex:1;min-width:0;width:auto}.reorder-handle:hover{background:var(--spui-ui-surface-hover,var(--spui-ui-canvas,#f5f5f5));color:var(--spui-ui-text,inherit)}.reorder-handle:active{cursor:grabbing}.reorder-status{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}";
224
- style.textContent += ".group-row{background:var(--spui-data-grid-header-background,var(--spui-base-canvas,var(--spui-ui-canvas,#f5f5f5)));font-weight:600}.group-cell{grid-column:1/-1!important;padding-inline:8px}.group-cell button{display:flex;align-items:center;gap:8px;width:100%;height:100%;padding-inline:4px;border:0;background:transparent;color:inherit;font:inherit;text-align:start;cursor:pointer}.group-cell button:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:-2px}.group-cell button span{margin-inline-start:auto;color:var(--spui-ui-muted,var(--spui-semantic-body-subtext,#616161));font-variant-numeric:tabular-nums}";
225
- style.textContent += ".filter-bar{margin-block-end:8px}.filter-bar[hidden]{display:none}.filter-bar input{box-sizing:border-box;width:min(100%,360px);min-height:36px;padding:6px 10px;border:1px solid var(--spui-ui-stroke,var(--spui-semantic-body-divider,#d1d1d1));border-radius:var(--spui-control-radius,4px);background:var(--spui-base-surface,var(--spui-ui-surface,#fff));color:var(--spui-ui-text,var(--spui-semantic-body-text,#242424));font:inherit}.filter-bar input:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:2px}.cell-editor{box-sizing:border-box;width:100%;min-width:0;min-height:30px;padding:3px 6px;border:1px solid var(--spui-ui-accent,#78716c);border-radius:var(--spui-control-radius,4px);background:var(--spui-base-surface,var(--spui-ui-surface,#fff));color:var(--spui-ui-text,var(--spui-semantic-body-text,#242424));font:inherit}.cell-editor:focus-visible{outline:2px solid var(--spui-focus-ring,var(--spui-ui-accent,#0078d4));outline-offset:1px}.cell-editor[aria-invalid=true]{border-color:var(--spui-semantic-danger,#d13438)}.edit-error{position:absolute;z-index:3;margin-block-start:32px;padding:4px 8px;border:1px solid var(--spui-semantic-danger,#d13438);border-radius:4px;background:var(--spui-base-surface,#fff);color:var(--spui-semantic-danger,#d13438);font-size:12px}";
226
- style.textContent += ".viewport[data-selection-appearance=brand] .data-row[aria-selected=true]{background:color-mix(in srgb,var(--spui-ui-accent,#0078d4) 14%,var(--spui-base-surface,var(--spui-ui-surface,#fff)))}.viewport[data-selection-appearance=neutral] .data-row[aria-selected=true]{background:color-mix(in srgb,var(--spui-ui-text,#323130) 6%,var(--spui-base-surface,var(--spui-ui-surface,#fff)))}.viewport[data-subtle-selection=true] .data-row .selection-cell input{opacity:0;transition:opacity var(--spui-motion-duration-fast,120ms) var(--spui-motion-easing-standard,cubic-bezier(.2,0,0,1))}.viewport[data-subtle-selection=true] .data-row:hover .selection-cell input,.viewport[data-subtle-selection=true] .data-row:focus-within .selection-cell input{opacity:1}@media(prefers-reduced-motion:reduce){.selection-cell input{transition:none}}@media(forced-colors:active){.viewport .data-row[aria-selected=true]{outline:1px solid Highlight}.viewport[data-selection-appearance=brand] .data-row[aria-selected=true],.viewport[data-selection-appearance=neutral] .data-row[aria-selected=true]{background:Canvas;color:CanvasText}}";
227
- style.textContent += ".data-row[aria-selected]{cursor:pointer}";
228
- this.filterBar = document.createElement("div");
229
- this.filterBar.className = "filter-bar";
230
- this.filterBar.setAttribute("role", "search");
231
- this.filterBar.part.add("filter");
232
- this.filterInput = document.createElement("input");
233
- this.filterInput.type = "search";
234
- this.filterInput.dataset.testid = "spui-data-grid-filter";
235
- this.filterInput.addEventListener("input", () => { this.filterValue = this.filterInput.value; });
236
- this.filterBar.append(this.filterInput);
237
- this.viewport = document.createElement("div");
238
- this.viewport.className = "viewport";
239
- this.viewport.part.add("viewport");
240
- this.viewport.setAttribute("role", "grid");
241
- this.viewport.tabIndex = 0;
242
- this.viewport.addEventListener("scroll", () => {
243
- this.columnWindowChanged ||= this.updateColumnWindow();
244
- if (!this.frame)
245
- this.frame = requestAnimationFrame(() => { this.frame = 0; const force = this.columnWindowChanged; this.columnWindowChanged = false; this.paint(force); });
246
- }, { passive: true });
247
- this.viewport.addEventListener("click", event => this.onGridClick(event));
248
- this.viewport.addEventListener("dblclick", event => this.onResizeDoubleClick(event));
249
- this.viewport.addEventListener("pointerdown", event => this.onResizeStart(event));
250
- this.viewport.addEventListener("pointermove", event => this.onResizeMove(event));
251
- this.viewport.addEventListener("pointerup", event => this.onResizeEnd(event));
252
- this.viewport.addEventListener("pointercancel", event => this.onResizeEnd(event, true));
253
- this.viewport.addEventListener("dragstart", event => this.onColumnDragStart(event));
254
- this.viewport.addEventListener("dragover", event => this.onColumnDragOver(event));
255
- this.viewport.addEventListener("drop", event => this.onColumnDrop(event));
256
- this.viewport.addEventListener("dragend", () => { this.draggedColumnId = undefined; });
257
- this.viewport.addEventListener("keydown", event => this.onGridKeyDown(event));
258
- this.viewport.addEventListener("copy", event => this.onGridCopy(event));
259
- this.viewport.addEventListener("paste", event => { void this.onGridPaste(event); });
260
- this.header = document.createElement("div");
261
- this.header.className = "header";
262
- this.header.setAttribute("role", "rowgroup");
263
- this.header.part.add("header");
264
- this.body = document.createElement("div");
265
- this.body.className = "body";
266
- this.body.setAttribute("role", "rowgroup");
267
- this.body.part.add("body");
268
- this.reorderStatus = document.createElement("div");
269
- this.reorderStatus.className = "reorder-status";
270
- this.reorderStatus.setAttribute("role", "status");
271
- this.reorderStatus.setAttribute("aria-live", "polite");
272
- this.reorderStatus.part.add("reorder-status");
273
- this.viewport.append(this.header, this.body, this.reorderStatus);
274
- shadow.append(style, this.filterBar, this.viewport);
275
- this.renderFilter();
276
- }
277
- renderFilter() {
278
- if (!this.filterBar || !this.filterInput)
279
- return;
280
- this.filterBar.hidden = !this.filterable;
281
- this.filterInput.setAttribute("aria-label", this.getAttribute("filter-label") || "Search rows");
282
- if (this.filterInput.value !== this.currentFilterValue)
283
- this.filterInput.value = this.currentFilterValue;
284
- }
285
- recomputeSort() {
286
- if (this.source) {
287
- this.sortedData = [];
288
- this.cachedDisplayRows = undefined;
289
- this.cachedSortedData = this.sortedData;
290
- return;
291
- }
292
- const locale = this.lang || document.documentElement.lang;
293
- const filtered = filterDataGridItems(this.data, this.definitions, this.currentFilterValue, locale);
294
- this.sortedData = sortDataGridItems(filtered, this.definitions, this.currentSorts, locale);
295
- }
296
- normalizeSorts(value) {
297
- const seen = new Set();
298
- return (value ?? []).filter(entry => {
299
- if (!entry?.columnId || seen.has(entry.columnId) || !this.definitions.some(column => column.id === entry.columnId && column.sortable !== false))
300
- return false;
301
- seen.add(entry.columnId);
302
- return entry.direction === "ascending" || entry.direction === "descending";
303
- }).map(entry => ({ ...entry }));
304
- }
305
- visibleItems() { return this.sortedData; }
306
- sourceSelectionActive() { return this.sourceAllSelected && (this.sourceAllSelectedScope === undefined || this.sourceAllSelectedScope === this.source?.selectionScopeKey); }
307
- isRowSelected(key) { return this.source && this.sourceSelectionActive() ? !this.sourceExcludedKeys.has(key) : this.selected.has(key); }
308
- selectedLoadedItems() {
309
- if (this.source)
310
- return [...this.rows.values()].flatMap(row => row.spuiItem !== undefined && this.isRowSelected(row.spuiKey || "") ? [row.spuiItem] : []);
311
- return this.sortedData.filter((item, index) => this.selected.has(this.rowKey(item, index)));
312
- }
313
- emitSelectionChange() {
314
- const detail = { selectedKeys: this.selectedKeys, selectionModel: this.selectionModel, selectedItems: this.selectedLoadedItems() };
315
- this.dataSourceSelectionCallback?.(detail.selectionModel, detail.selectedItems);
316
- this.dispatchEvent(new CustomEvent("spui-selection-change", { detail, bubbles: true, composed: true }));
317
- }
318
- displayRows() {
319
- if (this.source) {
320
- const length = Number.isFinite(this.source.length) ? Math.max(0, Math.floor(this.source.length)) : 0;
321
- if (!this.cachedDisplayRows || this.cachedDisplayRows.length !== length)
322
- this.cachedDisplayRows = new Array(length);
323
- return this.cachedDisplayRows;
324
- }
325
- const columnIds = this.orderedDefinitions.map(column => column.id).join("\u001f");
326
- const locale = this.lang || document.documentElement.lang;
327
- const groupSignature = `${this.groupBy}\u001f${this.getAttribute("empty-group-label") || "No value"}\u001f${locale}`;
328
- if (this.cachedDisplayRows && this.cachedSortedData === this.sortedData && this.cachedGroupBy === groupSignature && this.cachedColumnIds === columnIds && this.cachedCollapsedGroups === this.collapsedGroups)
329
- return this.cachedDisplayRows;
330
- const groups = groupDataGridItems(this.sortedData, this.orderedDefinitions, this.groupBy, locale, this.getAttribute("empty-group-label") || "No value");
331
- this.cachedDisplayRows = groups ? groups.flatMap(group => [{ kind: "group", group }, ...(this.collapsedGroups.has(group.key) ? [] : group.items.map((item, offset) => ({ kind: "item", item, itemIndex: group.indices[offset] })))]) : this.sortedData.map((item, itemIndex) => ({ kind: "item", item, itemIndex }));
332
- this.cachedSortedData = this.sortedData;
333
- this.cachedGroupBy = groupSignature;
334
- this.cachedColumnIds = columnIds;
335
- this.cachedCollapsedGroups = this.collapsedGroups;
336
- return this.cachedDisplayRows;
337
- }
338
- observeDataSource() {
339
- if (!this.source || this.sourceUnsubscribe)
340
- return;
341
- this.sourceUnsubscribe = this.source.subscribe?.(() => {
342
- this.completedSourceRange = "";
343
- this.failedSourceRange = "";
344
- this.cachedDisplayRows = undefined;
345
- this.paint(true);
346
- });
347
- }
348
- requestDataRange(start, end) {
349
- const source = this.source;
350
- if (!source || start >= end)
351
- return;
352
- let missingRange = false;
353
- for (let index = start; index < end; index++)
354
- if (getDataGridDataSourceRow(source, index) === undefined) {
355
- missingRange = true;
356
- break;
357
- }
358
- if (!missingRange)
359
- return;
360
- const key = `${start}:${end}`;
361
- if (this.failedSourceRange === key || this.completedSourceRange === key || this.sourceRequest?.key === key)
362
- return;
363
- this.sourceRequest?.controller.abort();
364
- const request = { key, controller: new AbortController() };
365
- this.sourceRequest = request;
366
- this.viewport?.setAttribute("aria-busy", "true");
367
- Promise.resolve().then(() => source.loadRange(start, end, request.controller.signal)).then(() => {
368
- if (this.sourceRequest !== request || request.controller.signal.aborted)
369
- return;
370
- let missing = false;
371
- for (let index = start; index < end; index++)
372
- if (getDataGridDataSourceRow(source, index) === undefined) {
373
- missing = true;
374
- break;
375
- }
376
- this.sourceRequest = undefined;
377
- if (missing) {
378
- this.failedSourceRange = key;
379
- const error = new Error("loadRange resolved before every requested row was available");
380
- if (this.reorderStatus)
381
- this.reorderStatus.textContent = this.localizedMessage("load-error-label", "Data could not be loaded.");
382
- this.viewport?.setAttribute("aria-busy", "false");
383
- this.dispatchEvent(new CustomEvent("spui-data-load-error", { detail: { error, start, end }, bubbles: true, composed: true }));
384
- return;
385
- }
386
- this.completedSourceRange = key;
387
- this.failedSourceRange = "";
388
- if (this.reorderStatus)
389
- this.reorderStatus.textContent = "";
390
- this.cachedDisplayRows = undefined;
391
- this.paint(true);
392
- }, error => {
393
- if (this.sourceRequest !== request || request.controller.signal.aborted)
394
- return;
395
- this.sourceRequest = undefined;
396
- this.failedSourceRange = key;
397
- if (this.reorderStatus)
398
- this.reorderStatus.textContent = this.localizedMessage("load-error-label", "Data could not be loaded.");
399
- this.viewport?.setAttribute("aria-busy", "false");
400
- this.dispatchEvent(new CustomEvent("spui-data-load-error", { detail: { error, start, end }, bubbles: true, composed: true }));
401
- });
402
- }
403
- indexRowSizes(rows, estimate) {
404
- if (this.heightRows !== rows || this.heightEstimate !== estimate || this.heightGetterAtIndex !== this.rowHeightGetter) {
405
- if (this.source)
406
- this.rowSizes.reset(rows.length, estimate);
407
- else {
408
- const sizes = rows.map(row => row?.kind === "item" ? clampDataGridRowHeight(this.rowHeightGetter?.(row.item, row.itemIndex), estimate) : estimate);
409
- this.rowSizes.reset(rows.length, estimate, sizes);
410
- }
411
- this.heightRows = rows;
412
- this.heightEstimate = estimate;
413
- this.heightGetterAtIndex = this.rowHeightGetter;
414
- }
415
- return this.rowSizes;
416
- }
417
- rowKey(item, index) { return String(this.keyOf?.(item, index) ?? item?.id ?? item?.Id ?? index); }
418
- selectionMode() { const value = this.getAttribute("selection-mode"); return value === "single" ? "single" : value === "multiple" || value === "multiselect" ? "multiple" : "none"; }
419
- get orderedDefinitions() {
420
- if (!this.currentColumnOrder.length)
421
- return this.definitions;
422
- const byId = new Map(this.definitions.map(column => [column.id, column]));
423
- const orderedIds = new Set(this.currentColumnOrder);
424
- return [...this.currentColumnOrder.flatMap(id => { const column = byId.get(id); return column ? [column] : []; }), ...this.definitions.filter(column => !orderedIds.has(column.id))];
425
- }
426
- updateColumnWindow() {
427
- const next = this.virtualizeColumns && this.viewport && this.header
428
- ? getDataGridColumnWindow([...this.header.querySelectorAll("[data-column-index]")], this.viewport)
429
- : { start: 0, end: this.orderedDefinitions.length };
430
- if (next.start === this.columnWindow.start && next.end === this.columnWindow.end)
431
- return false;
432
- this.columnWindow = next;
433
- return true;
434
- }
435
- normalizeColumnOrder(value) {
436
- const known = new Set(this.definitions.map(column => column.id));
437
- return [...new Set(value ?? [])].filter(id => known.has(id)).concat(this.definitions.filter(column => !value?.includes(column.id)).map(column => column.id));
438
- }
439
- templateColumns() {
440
- return [...(this.selectionMode() === "none" ? [] : ["44px"]), ...this.orderedDefinitions.map((column, index) => {
441
- const sizing = getDataGridColumnSizing(column, this.sizingOptions);
442
- const configured = this.sizingOptions[column.id];
443
- const hasInitialWidth = configured?.defaultWidth !== undefined || configured?.idealWidth !== undefined;
444
- const isAutoFitLast = this.resizableColumns && this.autoFitColumns && index === this.orderedDefinitions.length - 1 && this.currentColumnWidths[column.id] === undefined;
445
- const fallback = isAutoFitLast ? `minmax(${sizing.minWidth}px, 1fr)` : hasInitialWidth ? `${sizing.defaultWidth}px` : column.width || "minmax(120px, 1fr)";
446
- return `var(${dataGridColumnVar(column.id)}, ${fallback})`;
447
- })].join(" ") || "minmax(0, 1fr)";
448
- }
449
- renderHeader() {
450
- if (!this.header || !this.viewport)
451
- return;
452
- this.header.replaceChildren();
453
- const row = document.createElement("div");
454
- row.className = "row header-row";
455
- row.setAttribute("role", "row");
456
- row.setAttribute("aria-rowindex", "1");
457
- row.style.gridTemplateColumns = this.templateColumns();
458
- if (this.selectionMode() !== "none") {
459
- const cell = document.createElement("div");
460
- cell.className = "cell header-cell selection-cell";
461
- cell.setAttribute("role", "columnheader");
462
- if (this.selectionMode() === "multiple") {
463
- const checkbox = document.createElement("input");
464
- checkbox.type = "checkbox";
465
- checkbox.dataset.selectAll = "";
466
- checkbox.setAttribute("aria-label", this.getAttribute("select-all-label") || "Select all rows");
467
- cell.append(checkbox);
468
- }
469
- row.append(cell);
470
- }
471
- this.orderedDefinitions.forEach((column, index) => {
472
- const cell = document.createElement("div");
473
- cell.className = "cell header-cell";
474
- cell.setAttribute("role", "columnheader");
475
- cell.dataset.columnId = column.id;
476
- cell.dataset.columnIndex = String(index);
477
- cell.setAttribute("aria-colindex", String(index + (this.selectionMode() === "none" ? 1 : 2)));
478
- if (this.reorderableColumns) {
479
- const grip = document.createElement("button");
480
- grip.type = "button";
481
- grip.className = "reorder-handle";
482
- grip.dataset.reorderColumn = column.id;
483
- grip.draggable = true;
484
- grip.setAttribute("aria-label", `${this.getAttribute("reorder-label") || "Reorder column"} ${column.label}`);
485
- grip.title = this.localizedMessage("reorder-hint-label", "Reorder {column}; use Alt+Shift+Arrow keys", { column: column.label });
486
- grip.textContent = "⠿";
487
- cell.append(grip);
488
- }
489
- if (column.sortable !== false) {
490
- const button = document.createElement("button");
491
- button.type = "button";
492
- button.dataset.sortColumn = column.id;
493
- button.append(document.createTextNode(column.label));
494
- const sortIndex = this.currentSorts.findIndex(entry => entry.columnId === column.id);
495
- if (sortIndex === 0) {
496
- cell.setAttribute("aria-sort", this.currentSorts[0].direction);
497
- const indicator = document.createElement("span");
498
- indicator.className = "sort-indicator";
499
- indicator.setAttribute("aria-hidden", "true");
500
- indicator.textContent = `${sortIndex + 1}${this.currentSorts[0].direction === "ascending" ? "▲" : "▼"}`;
501
- button.append(indicator);
502
- }
503
- else {
504
- cell.setAttribute("aria-sort", "none");
505
- if (sortIndex > 0) {
506
- const indicator = document.createElement("span");
507
- indicator.className = "sort-indicator";
508
- indicator.setAttribute("aria-hidden", "true");
509
- indicator.textContent = `${sortIndex + 1}${this.currentSorts[sortIndex].direction === "ascending" ? "▲" : "▼"}`;
510
- button.append(indicator);
511
- }
512
- }
513
- if (sortIndex >= 0)
514
- button.setAttribute("aria-label", `${column.label}, ${(this.getAttribute("sort-priority-label") || "Sort priority {priority}").replace("{priority}", String(sortIndex + 1))}`);
515
- cell.append(button);
516
- }
517
- else {
518
- const label = document.createElement("span");
519
- label.textContent = column.label;
520
- cell.append(label);
521
- }
522
- if (this.resizableColumns && column.resizable !== false) {
523
- cell.style.position = "relative";
524
- const separator = document.createElement("div");
525
- separator.className = "resize-handle";
526
- separator.dataset.resizeColumn = column.id;
527
- separator.setAttribute("role", "separator");
528
- separator.setAttribute("aria-orientation", "vertical");
529
- separator.tabIndex = 0;
530
- separator.setAttribute("aria-label", `${this.getAttribute("resize-label") || "Resize column"} ${column.label}`);
531
- separator.setAttribute("aria-valuemin", String(getDataGridColumnSizing(column, this.sizingOptions).minWidth));
532
- separator.setAttribute("aria-valuemax", String(column.maxWidth ?? 1600));
533
- separator.setAttribute("aria-valuenow", String(this.currentColumnWidths[column.id] ?? Math.round(cell.getBoundingClientRect().width)));
534
- cell.append(separator);
535
- }
536
- row.append(cell);
537
- });
538
- this.header.append(row);
539
- this.updateColumnWindow();
540
- this.header.querySelectorAll("[data-resize-column]").forEach(handle => {
541
- const id = handle.dataset.resizeColumn;
542
- if (this.currentColumnWidths[id] === undefined)
543
- handle.setAttribute("aria-valuenow", String(Math.round(handle.parentElement.getBoundingClientRect().width)));
544
- });
545
- this.viewport.setAttribute("aria-label", this.getAttribute("label") || this.getAttribute("aria-label") || "Data grid");
546
- this.viewport.setAttribute("aria-colcount", String(this.orderedDefinitions.length + (this.selectionMode() === "none" ? 0 : 1)));
547
- }
548
- paint(force = false) {
549
- if (!this.isConnected || !this.viewport || !this.body)
550
- return;
551
- const activeEditor = this.shadowRoot?.activeElement instanceof HTMLInputElement && this.shadowRoot.activeElement.classList.contains("cell-editor") ? this.shadowRoot.activeElement : undefined;
552
- const selection = activeEditor ? [activeEditor.selectionStart, activeEditor.selectionEnd] : undefined;
553
- this.suppressEditorBlurCommit = Boolean(activeEditor);
554
- const items = this.visibleItems();
555
- const displayRows = this.displayRows();
556
- const rowHeight = this.positiveNumber(this.getAttribute("row-height"), 40);
557
- const rowSizes = this.indexRowSizes(displayRows, rowHeight);
558
- const overscanValue = Number(this.getAttribute("overscan"));
559
- const overscan = Number.isFinite(overscanValue) ? Math.max(0, Math.min(50, Math.floor(overscanValue))) : 4;
560
- const headerHeight = this.header?.offsetHeight || rowHeight;
561
- const scrollTop = Math.max(0, this.viewport.scrollTop - headerHeight);
562
- const viewportEnd = scrollTop + Math.max(0, this.viewport.clientHeight - headerHeight);
563
- const first = Math.max(0, rowSizes.indexAt(scrollTop) - overscan);
564
- const last = Math.min(displayRows.length, rowSizes.indexAt(viewportEnd) + overscan + 1);
565
- const itemCount = this.source ? Math.max(0, Math.floor(this.source.length)) : items.length;
566
- if (this.source)
567
- this.requestDataRange(first, last);
568
- this.viewport.setAttribute("aria-rowcount", String(displayRows.length + 1));
569
- this.viewport.setAttribute("data-item-count", String(itemCount));
570
- this.viewport.setAttribute("aria-busy", String(Boolean(this.sourceRequest)));
571
- this.viewport.tabIndex = itemCount ? -1 : 0;
572
- this.viewport.dataset.selectionAppearance = this.selectionAppearance;
573
- this.viewport.dataset.subtleSelection = String(this.subtleSelection);
574
- const orderedColumns = this.orderedDefinitions;
575
- const visibleColumns = this.virtualizeColumns ? orderedColumns.slice(this.columnWindow.start, this.columnWindow.end) : orderedColumns;
576
- const columnTemplate = this.templateColumns();
577
- for (const [index, row] of this.rows)
578
- if (index < first || index >= last) {
579
- row.remove();
580
- this.rows.delete(index);
581
- this.pool.push(row);
582
- }
583
- const fragment = document.createDocumentFragment();
584
- if (!itemCount) {
585
- const empty = document.createElement("div");
586
- empty.className = "empty";
587
- empty.setAttribute("role", "row");
588
- empty.textContent = this.currentFilterValue.trim() ? this.getAttribute("no-results-label") || "No results" : this.getAttribute("empty-label") || "No items";
589
- fragment.append(empty);
590
- }
591
- else {
592
- const spacer = document.createElement("div");
593
- spacer.setAttribute("role", "presentation");
594
- spacer.setAttribute("aria-hidden", "true");
595
- spacer.style.height = "0px";
596
- fragment.append(spacer);
597
- for (let index = first; index < last; index++) {
598
- let display = displayRows[index];
599
- if (this.source) {
600
- const sourceRow = getDataGridDataSourceRow(this.source, index);
601
- display = sourceRow?.kind === "group"
602
- ? { kind: "group", group: { key: sourceRow.key, label: sourceRow.label, value: undefined, items: [], indices: [] }, sourceGroup: { count: sourceRow.count, expanded: sourceRow.expanded } }
603
- : sourceRow?.kind === "item" ? { kind: "item", item: sourceRow.item, itemIndex: sourceRow.itemIndex ?? index, rowKey: sourceRow.rowId === undefined ? undefined : String(sourceRow.rowId) } : undefined;
604
- displayRows[index] = display;
605
- }
606
- const item = display?.kind === "item" ? display.item : undefined;
607
- const itemIndex = display?.kind === "item" ? display.itemIndex : -1;
608
- const key = display?.kind === "item" ? display.rowKey ?? this.rowKey(item, itemIndex) : display?.kind === "group" ? display.group.key : `loading-${index}`;
609
- let row = this.rows.get(index);
610
- if (!row) {
611
- row = (this.pool.pop() ?? Object.assign(document.createElement("div"), { className: "row data-row" }));
612
- row.setAttribute("role", "row");
613
- this.rows.set(index, row);
614
- }
615
- const typeChanged = row.spuiType !== (display?.kind ?? "loading");
616
- row.dataset.rowIndex = String(index);
617
- row.dataset.rowKey = key;
618
- row.spuiType = display?.kind ?? "loading";
619
- row.setAttribute("aria-rowindex", String(index + 2));
620
- row.tabIndex = display?.kind === "item" && (this.focusMode === "row_unstable" || this.focusMode === "composite") && index === this.activeCell.row ? 0 : -1;
621
- const selected = display?.kind === "item" && this.isRowSelected(key);
622
- if (this.selectionMode() !== "none")
623
- row.setAttribute("aria-selected", String(selected));
624
- else
625
- row.removeAttribute("aria-selected");
626
- row.style.height = `${rowSizes.size(index)}px`;
627
- row.style.gridTemplateColumns = columnTemplate;
628
- row.style.transform = `translateY(${rowSizes.offset(index)}px)`;
629
- if (display?.kind === "group") {
630
- row.dataset.groupKey = key;
631
- const collapsed = display.sourceGroup ? !display.sourceGroup.expanded : this.collapsedGroups.has(key);
632
- if (force || typeChanged || row.spuiKey !== key) {
633
- row.replaceChildren();
634
- row.removeAttribute("aria-selected");
635
- row.classList.add("group-row");
636
- const cell = document.createElement("div");
637
- cell.className = "cell group-cell";
638
- cell.setAttribute("role", "rowheader");
639
- cell.setAttribute("aria-colspan", String(orderedColumns.length + (this.selectionMode() === "none" ? 0 : 1)));
640
- cell.style.gridColumn = "1 / -1";
641
- const groupCount = display.sourceGroup?.count ?? display.group.items.length;
642
- const button = document.createElement("button");
643
- button.type = "button";
644
- button.dataset.groupToggle = key;
645
- button.setAttribute("aria-expanded", String(!collapsed));
646
- button.setAttribute("aria-label", `${collapsed ? this.getAttribute("expand-group-label") || "Expand group" : this.getAttribute("collapse-group-label") || "Collapse group"} ${display.group.label}, ${groupCount}`);
647
- button.append(document.createTextNode(`${collapsed ? "›" : "⌄"} ${display.group.label} `));
648
- const count = document.createElement("span");
649
- count.textContent = String(groupCount);
650
- button.append(count);
651
- cell.append(button);
652
- row.append(cell);
653
- row.spuiItem = undefined;
654
- row.spuiKey = key;
655
- }
656
- fragment.append(row);
657
- continue;
658
- }
659
- if (!display) {
660
- row.removeAttribute("aria-selected");
661
- row.setAttribute("aria-busy", "true");
662
- row.setAttribute("aria-label", `${this.getAttribute("loading-label") || "Loading row"} ${index + 1}`);
663
- row.classList.add("loading-row");
664
- if (force || typeChanged || row.spuiKey !== key) {
665
- row.replaceChildren();
666
- const loadingCell = document.createElement("div");
667
- loadingCell.className = "cell";
668
- loadingCell.setAttribute("role", "gridcell");
669
- loadingCell.setAttribute("aria-colspan", String(orderedColumns.length + (this.selectionMode() === "none" ? 0 : 1)));
670
- loadingCell.style.gridColumn = "1 / -1";
671
- const loadingText = document.createElement("span");
672
- loadingText.textContent = this.getAttribute("loading-label") || "Loading…";
673
- loadingCell.append(loadingText);
674
- row.append(loadingCell);
675
- row.spuiItem = undefined;
676
- row.spuiKey = key;
677
- }
678
- fragment.append(row);
679
- continue;
680
- }
681
- row.removeAttribute("aria-busy");
682
- row.removeAttribute("aria-label");
683
- row.classList.remove("loading-row");
684
- delete row.dataset.groupKey;
685
- row.classList.remove("group-row");
686
- if (force || typeChanged || row.spuiItem !== item || row.spuiKey !== key) {
687
- row.replaceChildren();
688
- if (this.selectionMode() !== "none") {
689
- const cell = document.createElement("div");
690
- cell.className = "cell selection-cell";
691
- cell.setAttribute("role", "gridcell");
692
- cell.setAttribute("aria-colindex", "1");
693
- cell.dataset.colIndex = "-1";
694
- const checkbox = document.createElement("input");
695
- checkbox.type = this.selectionMode() === "single" ? "radio" : "checkbox";
696
- if (checkbox.type === "radio")
697
- checkbox.name = this.selectionName;
698
- checkbox.checked = selected;
699
- checkbox.dataset.rowSelect = key;
700
- checkbox.setAttribute("aria-label", `${this.getAttribute("select-label") || "Select row"} ${itemIndex + 1}`);
701
- cell.append(checkbox);
702
- row.append(cell);
703
- }
704
- visibleColumns.forEach((column, visibleIndex) => {
705
- const columnIndex = this.virtualizeColumns ? this.columnWindow.start + visibleIndex : visibleIndex;
706
- const cell = document.createElement("div");
707
- cell.className = "cell";
708
- cell.setAttribute("role", "gridcell");
709
- cell.setAttribute("aria-colindex", String(columnIndex + (this.selectionMode() === "none" ? 1 : 2)));
710
- cell.dataset.colIndex = String(columnIndex);
711
- cell.dataset.colId = column.id;
712
- cell.tabIndex = (this.focusMode === "cell" || this.focusMode === "composite") && this.activeCell.row === index && this.activeCell.column === columnIndex ? 0 : -1;
713
- cell.style.gridColumn = String(columnIndex + (this.selectionMode() === "none" ? 1 : 2));
714
- cell.dataset.rowId = key;
715
- const isEditing = this.editingCell?.rowId === key && this.editingCell.columnId === column.id && column.editable === true;
716
- if (isEditing) {
717
- const input = document.createElement("input");
718
- input.type = column.editType || "text";
719
- input.className = "cell-editor";
720
- input.dataset.testid = "spui-data-grid-editor";
721
- input.value = this.editingCell.draft;
722
- input.disabled = Boolean(this.editingCell.saving);
723
- input.setAttribute("aria-label", `${column.label}, ${this.getAttribute("row-label") || "row"} ${itemIndex + 1}`);
724
- input.setAttribute("aria-invalid", String(Boolean(this.editingCell.error)));
725
- if (this.editingCell.error) {
726
- const errorId = `spui-grid-edit-error-${CSS.escape(key)}-${CSS.escape(column.id)}`;
727
- input.setAttribute("aria-describedby", errorId);
728
- const error = document.createElement("span");
729
- error.id = errorId;
730
- error.className = "edit-error";
731
- error.setAttribute("role", "alert");
732
- error.textContent = this.editingCell.error;
733
- cell.append(error);
734
- }
735
- input.addEventListener("input", () => { if (this.editingCell)
736
- this.editingCell.draft = input.value; });
737
- input.addEventListener("keydown", event => { event.stopPropagation(); if (event.key === "Escape") {
738
- event.preventDefault();
739
- this.cancelCellEdit(key, column.id);
740
- }
741
- else if (event.key === "Enter") {
742
- event.preventDefault();
743
- void this.commitCellEdit(key, column, item, input.value);
744
- } });
745
- input.addEventListener("blur", () => { if (!this.suppressEditorBlurCommit && this.editingCell?.rowId === key && this.editingCell.columnId === column.id && !this.editingCell.saving)
746
- void this.commitCellEdit(key, column, item, input.value); });
747
- cell.append(input);
748
- }
749
- else {
750
- const editKey = this.editKey(key, column.id);
751
- const result = this.editedValues.has(editKey) ? this.editedValues.get(editKey) : this.renderer?.(item, column, itemIndex) ?? getDataGridCellValue(item, column) ?? "";
752
- if (result instanceof Node)
753
- cell.append(result);
754
- else
755
- cell.textContent = String(result ?? "");
756
- if (column.editable) {
757
- cell.title = this.getAttribute("edit-hint") || "Press Enter or F2 to edit";
758
- cell.setAttribute("aria-keyshortcuts", "Enter F2");
759
- }
760
- }
761
- row.append(cell);
762
- });
763
- row.spuiItem = item;
764
- row.spuiKey = key;
765
- row.spuiType = "item";
766
- }
767
- else if (this.selectionMode() !== "none") {
768
- const checkbox = row.querySelector("[data-row-select]");
769
- if (checkbox)
770
- checkbox.checked = selected;
771
- }
772
- row.querySelectorAll("[data-col-index]").forEach(cell => { cell.tabIndex = (this.focusMode === "cell" || this.focusMode === "composite") && this.activeCell.row === index && this.activeCell.column === Number(cell.dataset.colIndex) ? 0 : -1; });
773
- fragment.append(row);
774
- }
775
- }
776
- const bottom = document.createElement("div");
777
- bottom.setAttribute("role", "presentation");
778
- bottom.setAttribute("aria-hidden", "true");
779
- bottom.style.height = `${rowSizes.totalSize}px`;
780
- fragment.append(bottom);
781
- this.body.replaceChildren(fragment);
782
- this.suppressEditorBlurCommit = false;
783
- const pendingBoundary = this.pendingBoundaryFocus;
784
- if (pendingBoundary) {
785
- const row = this.rows.get(pendingBoundary.row);
786
- if (row && row.getAttribute("aria-busy") !== "true") {
787
- const cell = row.querySelector(`[role="gridcell"][data-col-index="${pendingBoundary.column}"]`);
788
- if (cell && !pendingBoundary.scheduled) {
789
- pendingBoundary.scheduled = true;
790
- requestAnimationFrame(() => requestAnimationFrame(() => {
791
- if (this.pendingBoundaryFocus !== pendingBoundary)
792
- return;
793
- const currentRow = this.rows.get(pendingBoundary.row);
794
- const currentCell = currentRow?.querySelector(`[role="gridcell"][data-col-index="${pendingBoundary.column}"]`);
795
- if (!currentRow || !currentCell || currentRow.getAttribute("aria-busy") === "true") {
796
- pendingBoundary.scheduled = false;
797
- return;
798
- }
799
- const target = this.focusMode === "row_unstable" ? currentRow : currentCell.querySelector("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href]") ?? currentCell;
800
- target.focus();
801
- pendingBoundary.attempts++;
802
- const active = this.shadowRoot?.activeElement;
803
- if (active && currentRow.contains(active))
804
- this.pendingBoundaryFocus = undefined;
805
- else if (pendingBoundary.attempts >= 3)
806
- this.pendingBoundaryFocus = undefined;
807
- else {
808
- pendingBoundary.scheduled = false;
809
- this.paint();
810
- }
811
- }));
812
- }
813
- }
814
- }
815
- if (activeEditor) {
816
- const currentEditor = activeEditor.isConnected ? activeEditor : this.rows.get(this.activeCell.row)?.querySelector(".cell-editor");
817
- if (currentEditor) {
818
- currentEditor.focus();
819
- if (selection && selection[0] !== null && selection[1] !== null)
820
- currentEditor.setSelectionRange(selection[0] ?? currentEditor.value.length, selection[1] ?? currentEditor.value.length);
821
- }
822
- }
823
- const selectAll = this.header?.querySelector("[data-select-all]");
824
- if (selectAll && force) {
825
- if (this.source) {
826
- const hasRows = this.sourceSelectableCount > 0;
827
- selectAll.disabled = !hasRows;
828
- const activeAll = this.sourceSelectionActive();
829
- const partial = activeAll ? this.sourceExcludedKeys.size > 0 : !this.sourceAllSelected && this.selected.size > 0;
830
- selectAll.checked = hasRows && activeAll && !partial;
831
- selectAll.indeterminate = hasRows && partial;
832
- }
833
- else {
834
- selectAll.disabled = items.length === 0;
835
- const selectedCount = items.reduce((count, item, index) => count + Number(this.selected.has(this.rowKey(item, index))), 0);
836
- selectAll.checked = items.length > 0 && selectedCount === items.length;
837
- selectAll.indeterminate = selectedCount > 0 && selectedCount < items.length;
838
- }
839
- }
840
- }
841
- onGridClick(event) {
842
- const target = event.target;
843
- const groupToggle = target.closest("button[data-group-toggle]");
844
- if (groupToggle) {
845
- const key = groupToggle.dataset.groupToggle;
846
- const rowIndex = Number(groupToggle.closest("[data-row-index]")?.dataset.rowIndex);
847
- const display = this.displayRows()[rowIndex];
848
- if (this.source && display?.kind === "group" && display.sourceGroup) {
849
- const expanded = !display.sourceGroup.expanded;
850
- this.dataSourceGroupToggleCallback?.(key, expanded);
851
- this.dispatchEvent(new CustomEvent("spui-data-source-group-toggle", { detail: { groupKey: key, expanded }, bubbles: true, composed: true }));
852
- requestAnimationFrame(() => this.viewport?.querySelector(`[data-group-toggle="${CSS.escape(key)}"]`)?.focus());
853
- return;
854
- }
855
- const next = new Set(this.collapsedGroups);
856
- if (next.has(key))
857
- next.delete(key);
858
- else
859
- next.add(key);
860
- this.collapsedGroups = next;
861
- this.paint(true);
862
- this.dispatchEvent(new CustomEvent("spui-group-state-change", { detail: { collapsedGroupKeys: this.collapsedGroupKeys }, bubbles: true, composed: true }));
863
- requestAnimationFrame(() => this.viewport?.querySelector(`[data-group-toggle="${CSS.escape(key)}"]`)?.focus());
864
- return;
865
- }
866
- const sortButton = target.closest("button[data-sort-column]");
867
- if (sortButton) {
868
- const columnId = sortButton.dataset.sortColumn;
869
- const next = [...this.currentSorts];
870
- const index = next.findIndex(entry => entry.columnId === columnId);
871
- const additive = event.shiftKey;
872
- if (!additive) {
873
- const direction = index === 0 && next[0].direction === "ascending" ? "descending" : "ascending";
874
- this.currentSorts = index === 0 && next[0].direction === "descending" ? [] : [{ columnId, direction }];
875
- }
876
- else if (index < 0)
877
- next.push({ columnId, direction: "ascending" });
878
- else if (next[index].direction === "ascending")
879
- next[index] = { columnId, direction: "descending" };
880
- else
881
- next.splice(index, 1);
882
- if (additive)
883
- this.currentSorts = next;
884
- this.currentSort = this.currentSorts[0];
885
- this.recomputeSort();
886
- this.renderHeader();
887
- this.paint(true);
888
- this.header?.querySelector(`[data-sort-column="${CSS.escape(columnId)}"]`)?.focus();
889
- this.dispatchEvent(new CustomEvent("spui-sort-change", { detail: { sort: this.currentSort, sorts: this.sorts }, bubbles: true, composed: true }));
890
- return;
891
- }
892
- const row = target.closest(".data-row[data-row-index]");
893
- if (row && this.selectionMode() !== "none") {
894
- this.toggleRowSelection(row.dataset.rowKey || "");
895
- return;
896
- }
897
- const checkbox = target.closest("input[data-select-all],input[data-row-select]");
898
- if (!checkbox)
899
- return;
900
- const items = this.visibleItems();
901
- if (checkbox.hasAttribute("data-select-all")) {
902
- if (this.source) {
903
- this.sourceAllSelected = checkbox.checked && this.sourceSelectableCount > 0;
904
- this.sourceAllSelectedScope = this.sourceAllSelected ? this.source?.selectionScopeKey : undefined;
905
- this.sourceExcludedKeys.clear();
906
- this.selected.clear();
907
- }
908
- else {
909
- const allKeys = items.map((item, index) => this.rowKey(item, index));
910
- this.selected = checkbox.checked ? new Set(allKeys) : new Set();
911
- }
912
- }
913
- else {
914
- const key = checkbox.dataset.rowSelect;
915
- if (!key)
916
- return;
917
- if (this.source && this.sourceSelectionActive()) {
918
- if (checkbox.checked)
919
- this.sourceExcludedKeys.delete(key);
920
- else
921
- this.sourceExcludedKeys.add(key);
922
- }
923
- else {
924
- if (this.source && this.sourceAllSelected) {
925
- this.sourceAllSelected = false;
926
- this.sourceAllSelectedScope = undefined;
927
- this.sourceExcludedKeys.clear();
928
- }
929
- if (this.selectionMode() === "single")
930
- this.selected.clear();
931
- if (checkbox.checked)
932
- this.selected.add(key);
933
- else
934
- this.selected.delete(key);
935
- }
936
- }
937
- this.paint(true);
938
- this.emitSelectionChange();
939
- }
940
- toggleRowSelection(key) {
941
- if (!key || this.selectionMode() === "none")
942
- return;
943
- const selected = this.isRowSelected(key);
944
- if (this.source && this.sourceSelectionActive()) {
945
- if (selected)
946
- this.sourceExcludedKeys.add(key);
947
- else
948
- this.sourceExcludedKeys.delete(key);
949
- }
950
- else if (this.source && this.sourceAllSelected) {
951
- this.sourceAllSelected = false;
952
- this.sourceAllSelectedScope = undefined;
953
- this.sourceExcludedKeys.clear();
954
- this.selected.add(key);
955
- }
956
- else if (this.selectionMode() === "single") {
957
- if (selected)
958
- this.selected.delete(key);
959
- else {
960
- this.selected.clear();
961
- this.selected.add(key);
962
- }
963
- }
964
- else if (selected)
965
- this.selected.delete(key);
966
- else
967
- this.selected.add(key);
968
- this.paint(true);
969
- this.emitSelectionChange();
970
- }
971
- editKey(rowId, columnId) { return JSON.stringify([rowId, columnId]); }
972
- beginCellEdit(cell) {
973
- if (!cell || !this.viewport)
974
- return;
975
- const rowIndex = Number(cell.closest("[data-row-index]")?.dataset.rowIndex);
976
- const columnIndex = Number(cell.dataset.colIndex);
977
- const display = this.displayRows()[rowIndex];
978
- const column = this.orderedDefinitions[columnIndex];
979
- if (!display || display.kind !== "item" || !column?.editable)
980
- return;
981
- const rowId = display.rowKey ?? this.rowKey(display.item, display.itemIndex);
982
- const key = this.editKey(rowId, column.id);
983
- const current = this.editedValues.has(key) ? this.editedValues.get(key) : getDataGridCellValue(display.item, column);
984
- this.activeCell = { row: rowIndex, column: columnIndex };
985
- this.editingCell = { rowId, columnId: column.id, draft: toDataGridInputValue(current, column.editType) };
986
- this.paint(true);
987
- requestAnimationFrame(() => this.rows.get(rowIndex)?.querySelector(".cell-editor")?.focus());
988
- }
989
- cancelCellEdit(rowId, columnId) {
990
- const editing = this.editingCell;
991
- if (!editing || editing.rowId !== rowId || editing.columnId !== columnId || editing.saving)
992
- return;
993
- this.editingCell = undefined;
994
- this.paint(true);
995
- requestAnimationFrame(() => this.viewport?.querySelector(`[data-row-id="${CSS.escape(rowId)}"][data-col-index="${this.orderedDefinitions.findIndex(column => column.id === columnId)}"]`)?.focus());
996
- }
997
- async commitCellEdit(rowId, column, item, draft) {
998
- const editing = this.editingCell;
999
- if (!editing || editing.rowId !== rowId || editing.columnId !== column.id || editing.saving)
1000
- return;
1001
- const value = parseDataGridInputValue(draft, column.editType);
1002
- const edit = { item, rowId, columnId: column.id, previousValue: getDataGridCellValue(item, column), value };
1003
- let error;
1004
- try {
1005
- error = this.editValidator?.(edit);
1006
- }
1007
- catch (reason) {
1008
- error = reason instanceof Error ? reason.message : String(reason);
1009
- }
1010
- if (error) {
1011
- editing.draft = draft;
1012
- editing.error = error;
1013
- this.showEditError(editing);
1014
- return;
1015
- }
1016
- editing.saving = true;
1017
- const input = this.rows.get(this.activeCell.row)?.querySelector(".cell-editor");
1018
- if (input) {
1019
- input.disabled = true;
1020
- input.setAttribute("aria-busy", "true");
1021
- }
1022
- try {
1023
- await this.editCallback?.(edit);
1024
- this.editedValues.set(this.editKey(rowId, column.id), value);
1025
- this.editingCell = undefined;
1026
- this.dispatchEvent(new CustomEvent("spui-cell-edit", { detail: edit, bubbles: true, composed: true }));
1027
- const columnIndex = this.orderedDefinitions.findIndex(candidate => candidate.id === column.id);
1028
- this.paint(true);
1029
- requestAnimationFrame(() => this.viewport?.querySelector(`[data-row-id="${CSS.escape(rowId)}"][data-col-index="${columnIndex}"]`)?.focus());
1030
- }
1031
- catch (reason) {
1032
- editing.saving = false;
1033
- const message = reason instanceof Error ? reason.message : String(reason || "The value could not be saved.");
1034
- editing.error = this.getAttribute("edit-error-label") || "The value could not be saved.";
1035
- if (input) {
1036
- input.disabled = false;
1037
- input.removeAttribute("aria-busy");
1038
- }
1039
- this.editErrorCallback?.({ item: edit.item, rowId: edit.rowId, columnId: edit.columnId, previousValue: edit.previousValue, value: edit.value, error: message });
1040
- this.dispatchEvent(new CustomEvent("spui-cell-edit-error", { detail: { item: edit.item, rowId: edit.rowId, columnId: edit.columnId, previousValue: edit.previousValue, value: edit.value, error: message }, bubbles: true, composed: true }));
1041
- this.showEditError(editing);
1042
- }
1043
- }
1044
- showEditError(editing) {
1045
- const cell = this.viewport?.querySelector(`[data-row-id="${CSS.escape(editing.rowId)}"][data-col-index="${this.orderedDefinitions.findIndex(column => column.id === editing.columnId)}"]`);
1046
- const input = cell?.querySelector(".cell-editor");
1047
- if (!cell || !input)
1048
- return;
1049
- cell.style.position = "relative";
1050
- const errorId = `spui-grid-edit-error-${CSS.escape(editing.rowId)}-${CSS.escape(editing.columnId)}`;
1051
- input.setAttribute("aria-invalid", "true");
1052
- input.setAttribute("aria-describedby", errorId);
1053
- let error = cell.querySelector(".edit-error");
1054
- if (!error) {
1055
- error = document.createElement("span");
1056
- error.id = errorId;
1057
- error.className = "edit-error";
1058
- error.setAttribute("role", "alert");
1059
- cell.append(error);
1060
- }
1061
- error.textContent = editing.error || this.getAttribute("edit-error-label") || "The value could not be saved.";
1062
- requestAnimationFrame(() => input.focus());
1063
- }
1064
- currentEditValue(item, rowId, column) {
1065
- const key = this.editKey(rowId, column.id);
1066
- return this.editedValues.has(key) ? this.editedValues.get(key) : getDataGridCellValue(item, column);
1067
- }
1068
- onGridCopy(event) {
1069
- if (!event.clipboardData || event.target.closest(".cell-editor"))
1070
- return;
1071
- const selectedItems = (this.source ? [...this.rows.entries()].flatMap(([index, row]) => row.spuiItem === undefined ? [] : [{ item: row.spuiItem, index, key: row.spuiKey || this.rowKey(row.spuiItem, index) }]) : this.sortedData.map((item, index) => ({ item, index, key: this.rowKey(item, index) }))).filter(({ key }) => this.isRowSelected(key));
1072
- const cell = event.target.closest("[role=gridcell][data-col-index]");
1073
- let values;
1074
- if (selectedItems.length) {
1075
- values = selectedItems.map(({ item, key }) => {
1076
- const rowId = key;
1077
- return this.orderedDefinitions.map(column => this.currentEditValue(item, rowId, column));
1078
- });
1079
- }
1080
- else if (cell) {
1081
- const rowIndex = Number(cell.closest("[data-row-index]")?.dataset.rowIndex);
1082
- const sourceRow = this.source ? getDataGridDataSourceRow(this.source, rowIndex) : undefined;
1083
- const display = this.source ? sourceRow?.kind === "item" ? { kind: "item", item: sourceRow.item, itemIndex: sourceRow.itemIndex ?? rowIndex, rowKey: sourceRow.rowId === undefined ? undefined : String(sourceRow.rowId) } : undefined : this.displayRows()[rowIndex];
1084
- const column = this.orderedDefinitions[Number(cell.dataset.colIndex)];
1085
- if (!display || display.kind !== "item" || !column)
1086
- return;
1087
- values = [[this.currentEditValue(display.item, display.rowKey ?? this.rowKey(display.item, display.itemIndex), column)]];
1088
- }
1089
- else
1090
- return;
1091
- event.preventDefault();
1092
- event.clipboardData.setData("text/plain", formatDataGridClipboard(values));
1093
- }
1094
- copySourceSelection() {
1095
- const source = this.source;
1096
- if (!source?.copySelection)
1097
- return;
1098
- const selectionScopeKey = source.selectionScopeKey;
1099
- const controller = new AbortController();
1100
- this.clipboardController?.abort();
1101
- this.clipboardController = controller;
1102
- const text = Promise.resolve().then(() => source.copySelection(this.selectionModel, this.orderedDefinitions.map(({ id, label }) => ({ id, label })), controller.signal)).then(value => {
1103
- if (controller.signal.aborted || this.source !== source)
1104
- throw new DOMException("Clipboard operation cancelled", "AbortError");
1105
- if (source.selectionScopeKey !== selectionScopeKey)
1106
- throw new Error("The data query changed before copying completed.");
1107
- if (value.length > 1_000_000)
1108
- throw new Error("Copy is limited to 1,000,000 characters.");
1109
- return value;
1110
- });
1111
- void writeDataGridClipboardText(text).then(() => {
1112
- if (this.clipboardController === controller && this.reorderStatus)
1113
- this.reorderStatus.textContent = this.localizedMessage("selection-copied-label", "Selection copied.");
1114
- }, reason => {
1115
- if (controller.signal.aborted)
1116
- return;
1117
- const message = reason instanceof Error ? reason.message : String(reason);
1118
- if (this.reorderStatus)
1119
- this.reorderStatus.textContent = this.localizedMessage("copy-failed-label", "Copy failed.");
1120
- this.dispatchEvent(new CustomEvent("spui-clipboard-error", { detail: { operation: "copy", message }, bubbles: true, composed: true }));
1121
- });
1122
- }
1123
- async onGridPaste(event) {
1124
- if (event.target.closest(".cell-editor"))
1125
- return;
1126
- const cell = event.target.closest("[role=gridcell][data-col-index]");
1127
- const text = event.clipboardData?.getData("text/plain");
1128
- if (!cell || text === undefined || !this.viewport)
1129
- return;
1130
- event.preventDefault();
1131
- const edits = [];
1132
- try {
1133
- const matrix = parseDataGridClipboard(text);
1134
- const cellCount = matrix.reduce((total, row) => total + row.length, 0);
1135
- if (cellCount > 1000)
1136
- throw new Error("Paste is limited to 1,000 cells at a time.");
1137
- const startRow = Number(cell.closest("[data-row-index]")?.dataset.rowIndex);
1138
- const startColumn = Number(cell.dataset.colIndex);
1139
- if (startColumn < 0)
1140
- throw new Error("Paste into a data cell, not the row selection control.");
1141
- const source = this.source;
1142
- const selectionScopeKey = source?.selectionScopeKey;
1143
- const controller = new AbortController();
1144
- this.clipboardController?.abort();
1145
- this.clipboardController = controller;
1146
- if (source) {
1147
- const endRow = startRow + matrix.length;
1148
- if (startRow < 0 || endRow > source.length)
1149
- throw new Error("The pasted data extends past the last row.");
1150
- let missing = false;
1151
- for (let index = startRow; index < endRow; index++)
1152
- if (getDataGridDataSourceRow(source, index) === undefined) {
1153
- missing = true;
1154
- break;
1155
- }
1156
- if (missing)
1157
- await source.loadRange(startRow, endRow, controller.signal);
1158
- if (controller.signal.aborted)
1159
- return;
1160
- if (this.source !== source || source.selectionScopeKey !== selectionScopeKey)
1161
- throw new Error("The data query changed before paste completed.");
1162
- for (let index = startRow; index < endRow; index++)
1163
- if (getDataGridDataSourceRow(source, index) === undefined)
1164
- throw new Error("The data source did not provide every destination row.");
1165
- this.completedSourceRange = "";
1166
- this.cachedDisplayRows = undefined;
1167
- this.paint(true);
1168
- }
1169
- const rows = this.source
1170
- ? Array.from({ length: matrix.length }, (_, offset) => { const sourceRow = getDataGridDataSourceRow(this.source, startRow + offset); return sourceRow?.kind === "item" ? { kind: "item", item: sourceRow.item, itemIndex: sourceRow.itemIndex ?? startRow + offset, rowKey: sourceRow.rowId === undefined ? undefined : String(sourceRow.rowId) } : undefined; })
1171
- : this.displayRows().slice(startRow).filter((row) => row?.kind === "item");
1172
- for (let rowOffset = 0; rowOffset < matrix.length; rowOffset++) {
1173
- const target = rows[rowOffset];
1174
- if (!target || target.kind !== "item")
1175
- throw new Error(this.source ? "Load the destination rows before pasting." : "The pasted data extends past the last row.");
1176
- const rowId = target.rowKey ?? this.rowKey(target.item, target.itemIndex);
1177
- for (let columnOffset = 0; columnOffset < matrix[rowOffset].length; columnOffset++) {
1178
- const column = this.orderedDefinitions[startColumn + columnOffset];
1179
- if (!column)
1180
- throw new Error("The pasted data extends past the last column.");
1181
- if (!column.editable)
1182
- throw new Error(`${column.label} cannot be edited.`);
1183
- const value = parseDataGridClipboardValue(matrix[rowOffset][columnOffset], column.editType);
1184
- const edit = { item: target.item, rowId, columnId: column.id, previousValue: this.currentEditValue(target.item, rowId, column), value };
1185
- const validation = this.editValidator?.(edit);
1186
- if (validation)
1187
- throw new Error(validation);
1188
- edits.push(edit);
1189
- }
1190
- }
1191
- if (edits.length > 1) {
1192
- if (!this.cellsEditCallback)
1193
- throw new Error("Provide onCellsEdit to persist a multi-cell paste atomically.");
1194
- await this.cellsEditCallback(edits);
1195
- for (const edit of edits)
1196
- this.editedValues.set(this.editKey(edit.rowId, edit.columnId), edit.value);
1197
- this.dispatchEvent(new CustomEvent("spui-cells-edit", { detail: { edits }, bubbles: true, composed: true }));
1198
- }
1199
- else if (edits.length === 1) {
1200
- const edit = edits[0];
1201
- await this.editCallback?.(edit);
1202
- this.editedValues.set(this.editKey(edit.rowId, edit.columnId), edit.value);
1203
- this.dispatchEvent(new CustomEvent("spui-cell-edit", { detail: edit, bubbles: true, composed: true }));
1204
- }
1205
- if (this.reorderStatus)
1206
- this.reorderStatus.textContent = this.localizedMessage(edits.length === 1 ? "paste-one-label" : "paste-many-label", edits.length === 1 ? "Pasted {count} cell." : "Pasted {count} cells.", { count: String(edits.length) });
1207
- this.paint(true);
1208
- }
1209
- catch (reason) {
1210
- if (this.clipboardController?.signal.aborted)
1211
- return;
1212
- const message = reason instanceof Error ? reason.message : String(reason);
1213
- if (this.reorderStatus)
1214
- this.reorderStatus.textContent = this.localizedMessage("paste-failed-label", "Paste failed.");
1215
- this.dispatchEvent(new CustomEvent("spui-cells-edit-error", { detail: { message, edits }, bubbles: true, composed: true }));
1216
- }
1217
- }
1218
- onGridKeyDown(event) {
1219
- if (event.ctrlKey && (event.key === "Home" || event.key === "End")) {
1220
- event.preventDefault();
1221
- if (event.key === "Home") {
1222
- const first = this.header?.querySelector(".header-row input:not([disabled]),.header-row button:not([disabled]),.header-row [tabindex='0']");
1223
- first?.focus();
1224
- return;
1225
- }
1226
- const rows = this.displayRows();
1227
- if (!rows.length || !this.orderedDefinitions.length || !this.viewport)
1228
- return;
1229
- let rowIndex = rows.length - 1;
1230
- if (!this.source)
1231
- while (rowIndex >= 0 && rows[rowIndex]?.kind !== "item")
1232
- rowIndex--;
1233
- if (rowIndex < 0)
1234
- return;
1235
- const columnIndex = this.orderedDefinitions.length - 1;
1236
- this.activeCell = { row: rowIndex, column: columnIndex };
1237
- this.pendingBoundaryFocus = { row: rowIndex, column: columnIndex, attempts: 0, scheduled: false };
1238
- if (this.virtualizeColumns && columnIndex >= this.columnWindow.end) {
1239
- this.columnWindow = { start: Math.max(0, columnIndex - 8), end: columnIndex + 1 };
1240
- this.viewport.scrollLeft = this.viewport.scrollWidth;
1241
- this.columnWindowChanged = true;
1242
- }
1243
- const sizes = this.indexRowSizes(rows, this.positiveNumber(this.getAttribute("row-height"), 40));
1244
- this.viewport.scrollTop = (this.header?.offsetHeight || 40) + sizes.offset(rowIndex);
1245
- this.paint(true);
1246
- return;
1247
- }
1248
- if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c" && !(event.target.closest(".cell-editor"))) {
1249
- const selection = this.selectionModel;
1250
- if (this.source?.copySelection && (this.sourceSelectionActive() || selection.mode === "explicit" && selection.keys.length > 0)) {
1251
- event.preventDefault();
1252
- this.copySourceSelection();
1253
- return;
1254
- }
1255
- }
1256
- const reorderHandle = event.target.closest("[data-reorder-column]");
1257
- if (reorderHandle && this.reorderableColumns && event.altKey && event.shiftKey && ["ArrowLeft", "ArrowRight"].includes(event.key)) {
1258
- const columns = this.orderedDefinitions;
1259
- const currentIndex = columns.findIndex(column => column.id === reorderHandle.dataset.reorderColumn);
1260
- const rtl = getComputedStyle(this).direction === "rtl";
1261
- const nextIndex = currentIndex + (event.key === "ArrowRight" ? 1 : -1) * (rtl ? -1 : 1);
1262
- if (currentIndex >= 0 && nextIndex >= 0 && nextIndex < columns.length) {
1263
- event.preventDefault();
1264
- this.moveColumn(columns[currentIndex].id, columns[nextIndex].id, nextIndex > currentIndex);
1265
- requestAnimationFrame(() => this.header?.querySelector(`[data-reorder-column="${CSS.escape(columns[currentIndex].id)}"]`)?.focus());
1266
- }
1267
- return;
1268
- }
1269
- const handle = event.target.closest("[data-resize-column]");
1270
- if (handle) {
1271
- this.onResizeKeyDown(event, handle);
1272
- return;
1273
- }
1274
- const selectionRow = event.target.closest(".data-row[data-row-index]");
1275
- if (event.key === " " && selectionRow && this.selectionMode() !== "none" && !event.target.closest("button,input,select,textarea,a,[contenteditable=true]")) {
1276
- event.preventDefault();
1277
- this.toggleRowSelection(selectionRow.dataset.rowKey || "");
1278
- return;
1279
- }
1280
- const focusMode = this.focusMode;
1281
- if (focusMode === "none")
1282
- return;
1283
- const rowElement = event.target.closest("[role=row][data-row-index]");
1284
- if (rowElement && (focusMode === "row_unstable" || focusMode === "composite") && event.target === rowElement) {
1285
- if (focusMode === "composite" && event.key === "ArrowRight") {
1286
- const firstFocusable = rowElement.querySelector('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href],[tabindex="0"][role="gridcell"]');
1287
- if (firstFocusable) {
1288
- event.preventDefault();
1289
- firstFocusable.focus();
1290
- }
1291
- return;
1292
- }
1293
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
1294
- const rows = this.displayRows();
1295
- let next = Number(rowElement.dataset.rowIndex) + (event.key === "ArrowDown" ? 1 : -1);
1296
- while (!this.source && next >= 0 && next < rows.length && rows[next]?.kind !== "item")
1297
- next += event.key === "ArrowDown" ? 1 : -1;
1298
- if (next >= 0 && next < rows.length) {
1299
- event.preventDefault();
1300
- this.activeCell = { ...this.activeCell, row: next };
1301
- this.viewport?.scrollTo({ top: this.indexRowSizes(rows, this.positiveNumber(this.getAttribute("row-height"), 40)).offset(next), behavior: "auto" });
1302
- this.paint();
1303
- requestAnimationFrame(() => this.rows.get(next)?.focus());
1304
- }
1305
- return;
1306
- }
1307
- }
1308
- const cell = event.target.closest("[role=gridcell][data-col-index]");
1309
- if (!cell || !this.viewport)
1310
- return;
1311
- if (focusMode === "composite") {
1312
- if (event.key === "ArrowLeft") {
1313
- const row = cell.closest("[role=row][data-row-index]");
1314
- if (row) {
1315
- event.preventDefault();
1316
- row.focus();
1317
- }
1318
- }
1319
- else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
1320
- const row = Number(cell.closest("[data-row-index]")?.dataset.rowIndex);
1321
- const rows = this.displayRows();
1322
- let next = row + (event.key === "ArrowDown" ? 1 : -1);
1323
- while (!this.source && next >= 0 && next < rows.length && rows[next]?.kind !== "item")
1324
- next += event.key === "ArrowDown" ? 1 : -1;
1325
- if (next >= 0 && next < rows.length) {
1326
- event.preventDefault();
1327
- this.activeCell = { ...this.activeCell, row: next };
1328
- this.viewport.scrollTo({ top: this.indexRowSizes(rows, this.positiveNumber(this.getAttribute("row-height"), 40)).offset(next), behavior: "auto" });
1329
- this.paint();
1330
- requestAnimationFrame(() => this.rows.get(next)?.focus());
1331
- }
1332
- }
1333
- return;
1334
- }
1335
- if ((event.key === "Enter" || event.key === "F2") && cell.dataset.colIndex !== "-1") {
1336
- event.preventDefault();
1337
- this.beginCellEdit(cell);
1338
- return;
1339
- }
1340
- const row = Number(cell.closest("[data-row-index]")?.dataset.rowIndex);
1341
- const column = Number(cell.dataset.colIndex);
1342
- let nextRow = row, nextColumn = column;
1343
- const displayRows = this.displayRows();
1344
- if (event.key === "ArrowDown") {
1345
- let next = nextRow + 1;
1346
- while (!this.source && next < displayRows.length && displayRows[next]?.kind !== "item")
1347
- next++;
1348
- if (next < displayRows.length)
1349
- nextRow = next;
1350
- }
1351
- else if (event.key === "ArrowUp") {
1352
- let next = nextRow - 1;
1353
- while (!this.source && next >= 0 && displayRows[next]?.kind !== "item")
1354
- next--;
1355
- if (next >= 0)
1356
- nextRow = next;
1357
- }
1358
- else if (event.key === "ArrowRight")
1359
- nextColumn++;
1360
- else if (event.key === "ArrowLeft")
1361
- nextColumn--;
1362
- else if (event.key === "Home")
1363
- nextColumn = 0;
1364
- else if (event.key === "End")
1365
- nextColumn = this.definitions.length - 1;
1366
- else
1367
- return;
1368
- event.preventDefault();
1369
- nextRow = Math.max(0, Math.min(displayRows.length - 1, nextRow));
1370
- nextColumn = Math.max(0, Math.min(this.definitions.length - 1, nextColumn));
1371
- this.activeCell = { row: nextRow, column: nextColumn };
1372
- const rowHeight = this.positiveNumber(this.getAttribute("row-height"), 40);
1373
- const rowSizes = this.indexRowSizes(displayRows, rowHeight);
1374
- const headerHeight = this.header?.offsetHeight || rowHeight;
1375
- const rowTop = headerHeight + rowSizes.offset(nextRow);
1376
- const rowBottom = rowTop + rowSizes.size(nextRow);
1377
- if (rowTop < this.viewport.scrollTop + headerHeight)
1378
- this.viewport.scrollTop = rowSizes.offset(nextRow);
1379
- else if (rowBottom > this.viewport.scrollTop + this.viewport.clientHeight)
1380
- this.viewport.scrollTop = rowSizes.offset(nextRow) + rowSizes.size(nextRow) - Math.max(0, this.viewport.clientHeight - headerHeight);
1381
- this.header?.querySelector(`[data-column-index="${nextColumn}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
1382
- this.paint(this.updateColumnWindow());
1383
- requestAnimationFrame(() => requestAnimationFrame(() => this.viewport?.querySelector(`.data-row[data-row-index="${nextRow}"] [data-col-index="${nextColumn}"]`)?.focus()));
1384
- }
1385
- onColumnDragStart(event) {
1386
- const handle = event.target.closest("[data-reorder-column]");
1387
- if (!this.reorderableColumns || !handle)
1388
- return;
1389
- this.draggedColumnId = handle.dataset.reorderColumn;
1390
- if (event.dataTransfer) {
1391
- event.dataTransfer.effectAllowed = "move";
1392
- event.dataTransfer.setData("text/plain", this.draggedColumnId ?? "");
1393
- }
1394
- }
1395
- onColumnDragOver(event) {
1396
- if (this.reorderableColumns && this.draggedColumnId && event.target.closest("[data-column-id]"))
1397
- event.preventDefault();
1398
- }
1399
- onColumnDrop(event) {
1400
- if (!this.reorderableColumns || !this.draggedColumnId)
1401
- return;
1402
- const target = event.target.closest("[data-column-id]");
1403
- if (!target)
1404
- return;
1405
- event.preventDefault();
1406
- const bounds = target.getBoundingClientRect();
1407
- const after = getComputedStyle(this).direction === "rtl" ? event.clientX < bounds.left + bounds.width / 2 : event.clientX > bounds.left + bounds.width / 2;
1408
- this.moveColumn(this.draggedColumnId, target.dataset.columnId ?? "", after);
1409
- this.draggedColumnId = undefined;
1410
- }
1411
- moveColumn(fromId, toId, after = false) {
1412
- const next = this.orderedDefinitions.map(column => column.id);
1413
- if (fromId === toId || !next.includes(fromId) || !next.includes(toId))
1414
- return;
1415
- next.splice(next.indexOf(fromId), 1);
1416
- const targetIndex = next.indexOf(toId);
1417
- next.splice(targetIndex + Number(after), 0, fromId);
1418
- if (next.every((id, index) => id === this.orderedDefinitions[index].id))
1419
- return;
1420
- this.currentColumnOrder = next;
1421
- this.renderHeader();
1422
- this.paint(true);
1423
- const moved = this.definitions.find(column => column.id === fromId);
1424
- if (this.reorderStatus)
1425
- this.reorderStatus.textContent = `${moved.label}, ${next.indexOf(fromId) + 1} of ${next.length}`;
1426
- this.dispatchEvent(new CustomEvent("spui-column-order-change", { detail: { columnIds: next }, bubbles: true, composed: true }));
1427
- }
1428
- onResizeStart(event) {
1429
- const handle = event.target.closest("[data-resize-column]");
1430
- const column = this.definitions.find(candidate => candidate.id === handle?.dataset.resizeColumn);
1431
- if (!handle || !column || event.button !== 0)
1432
- return;
1433
- event.preventDefault();
1434
- const width = this.currentColumnWidths[column.id] ?? handle.parentElement.getBoundingClientRect().width;
1435
- this.resizing = { column, handle, startX: event.clientX, startWidth: width, direction: getComputedStyle(this).direction === "rtl" ? -1 : 1, pointerId: event.pointerId };
1436
- this.setAttribute("data-resizing", "");
1437
- handle.setPointerCapture(event.pointerId);
1438
- }
1439
- onResizeDoubleClick(event) {
1440
- const handle = event.target.closest("[data-resize-column]");
1441
- const column = this.definitions.find(candidate => candidate.id === handle?.dataset.resizeColumn);
1442
- if (!handle) {
1443
- this.beginCellEdit(event.target.closest("[role=gridcell][data-col-index]"));
1444
- return;
1445
- }
1446
- if (!column || column.resizable === false)
1447
- return;
1448
- event.preventDefault();
1449
- const header = this.header?.querySelector(`[data-column-id="${CSS.escape(column.id)}"] button`);
1450
- const cells = [...(this.body?.querySelectorAll(`[data-col-index="${this.orderedDefinitions.indexOf(column)}"]`) ?? [])];
1451
- const padding = getDataGridColumnSizing(column, this.sizingOptions).padding;
1452
- const measure = (element, extra) => { const range = document.createRange(); range.selectNodeContents(element); return range.getBoundingClientRect().width + padding + extra; };
1453
- const headerWidth = header ? measure(header, 18) : 0;
1454
- const contentWidth = Math.max(headerWidth, ...cells.map(cell => measure(cell, 10)));
1455
- const width = clampDataGridColumnWidth(column, contentWidth, this.sizingOptions[column.id]);
1456
- this.currentColumnWidths = { ...this.currentColumnWidths, [column.id]: width };
1457
- this.initializeColumnWidths();
1458
- this.applyColumnWidthVariables();
1459
- this.renderHeader();
1460
- this.paint(true);
1461
- this.header?.querySelector(`[data-resize-column="${CSS.escape(column.id)}"]`)?.focus();
1462
- this.dispatchEvent(new CustomEvent("spui-column-resize", { detail: { columnId: column.id, width, autoFit: true }, bubbles: true, composed: true }));
1463
- }
1464
- onResizeMove(event) {
1465
- const resize = this.resizing;
1466
- if (!resize || event.pointerId !== resize.pointerId)
1467
- return;
1468
- const width = clampDataGridColumnWidth(resize.column, resize.startWidth + (event.clientX - resize.startX) * resize.direction, this.sizingOptions[resize.column.id]);
1469
- this.style.setProperty(dataGridColumnVar(resize.column.id), `${width}px`);
1470
- resize.handle.setAttribute("aria-valuenow", String(width));
1471
- }
1472
- onResizeEnd(event, cancelled = false) {
1473
- const resize = this.resizing;
1474
- if (!resize || event.pointerId !== resize.pointerId)
1475
- return;
1476
- const width = cancelled ? resize.startWidth : Number(resize.handle.getAttribute("aria-valuenow")) || resize.startWidth;
1477
- if (cancelled)
1478
- this.style.setProperty(dataGridColumnVar(resize.column.id), `${resize.startWidth}px`);
1479
- this.resizing = undefined;
1480
- this.removeAttribute("data-resizing");
1481
- this.currentColumnWidths = { ...this.currentColumnWidths, [resize.column.id]: width };
1482
- this.initializeColumnWidths();
1483
- this.applyColumnWidthVariables();
1484
- resize.handle.setAttribute("aria-valuenow", String(width));
1485
- if (!cancelled)
1486
- this.dispatchEvent(new CustomEvent("spui-column-resize", { detail: { columnId: resize.column.id, width }, bubbles: true, composed: true }));
1487
- }
1488
- onResizeKeyDown(event, handle) {
1489
- const column = this.definitions.find(candidate => candidate.id === handle.dataset.resizeColumn);
1490
- if (!column)
1491
- return;
1492
- const current = this.currentColumnWidths[column.id] ?? Math.round(handle.parentElement.getBoundingClientRect().width);
1493
- const direction = getComputedStyle(this).direction === "rtl" ? -1 : 1;
1494
- const step = event.shiftKey ? 32 : 10;
1495
- let width;
1496
- if (event.key === "ArrowRight")
1497
- width = current + step * direction;
1498
- else if (event.key === "ArrowLeft")
1499
- width = current - step * direction;
1500
- else if (event.key === "Home")
1501
- width = column.minWidth ?? 48;
1502
- else if (event.key === "End")
1503
- width = column.maxWidth ?? 1600;
1504
- else
1505
- return;
1506
- event.preventDefault();
1507
- const nextWidth = clampDataGridColumnWidth(column, width, this.sizingOptions[column.id]);
1508
- this.currentColumnWidths = { ...this.currentColumnWidths, [column.id]: nextWidth };
1509
- this.initializeColumnWidths();
1510
- this.applyColumnWidthVariables();
1511
- handle.setAttribute("aria-valuenow", String(nextWidth));
1512
- handle.focus();
1513
- this.dispatchEvent(new CustomEvent("spui-column-resize", { detail: { columnId: column.id, width: this.currentColumnWidths[column.id] }, bubbles: true, composed: true }));
1514
- }
1515
- applyColumnWidthVariables() {
1516
- const widths = { ...this.fittedColumnWidths, ...this.currentColumnWidths };
1517
- for (const column of this.definitions) {
1518
- const width = widths[column.id];
1519
- if (Number.isFinite(width))
1520
- this.style.setProperty(dataGridColumnVar(column.id), `${width}px`);
1521
- else
1522
- this.style.removeProperty(dataGridColumnVar(column.id));
1523
- }
1524
- this.header?.querySelectorAll("[data-resize-column]").forEach(handle => {
1525
- const id = handle.dataset.resizeColumn;
1526
- if (this.currentColumnWidths[id] === undefined && widths[id] !== undefined)
1527
- handle.setAttribute("aria-valuenow", String(widths[id]));
1528
- });
1529
- }
1530
- initializeColumnWidths() {
1531
- if (!this.header)
1532
- return;
1533
- if (this.resizableColumns && this.autoFitColumns && this.viewport) {
1534
- this.fittedColumnWidths = fitDataGridColumnWidths(this.orderedDefinitions, this.viewport.clientWidth - this.containerWidthOffset, this.sizingOptions, this.currentColumnWidths, this.selectionMode() === "none" ? 0 : 44);
1535
- this.applyColumnWidthVariables();
1536
- return;
1537
- }
1538
- this.fittedColumnWidths = {};
1539
- if (!this.resizableColumns) {
1540
- this.applyColumnWidthVariables();
1541
- return;
1542
- }
1543
- let changed = false;
1544
- for (const column of this.definitions) {
1545
- if (this.currentColumnWidths[column.id] !== undefined)
1546
- continue;
1547
- const configured = this.sizingOptions[column.id];
1548
- const hasInitialWidth = configured?.defaultWidth !== undefined || configured?.idealWidth !== undefined;
1549
- const isAutoFitLast = this.resizableColumns && this.autoFitColumns && this.orderedDefinitions.at(-1)?.id === column.id;
1550
- if (isAutoFitLast)
1551
- continue;
1552
- if (!hasInitialWidth && column.minWidth === undefined && column.maxWidth === undefined && configured?.minWidth === undefined)
1553
- continue;
1554
- if (hasInitialWidth) {
1555
- this.currentColumnWidths = { ...this.currentColumnWidths, [column.id]: getDataGridColumnSizing(column, this.sizingOptions).defaultWidth };
1556
- changed = true;
1557
- continue;
1558
- }
1559
- const cell = this.header.querySelector(`[data-column-id="${CSS.escape(column.id)}"]`);
1560
- if (!cell || cell.getBoundingClientRect().width <= 0)
1561
- continue;
1562
- const width = clampDataGridColumnWidth(column, cell.getBoundingClientRect().width, configured);
1563
- if (Math.abs(width - cell.getBoundingClientRect().width) >= 1) {
1564
- this.currentColumnWidths = { ...this.currentColumnWidths, [column.id]: width };
1565
- changed = true;
1566
- }
1567
- }
1568
- if (changed) {
1569
- this.applyColumnWidthVariables();
1570
- this.renderHeader();
1571
- }
1572
- }
1573
- positiveNumber(value, fallback) { const number = Number(value); return Number.isFinite(number) && number > 0 ? number : fallback; }
1574
- }
1575
- customElements.define("spui-data-grid", SpuiDataGrid);
1576
- }