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