@gramlot/gramlot 0.3.19 → 0.3.24

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 (102) hide show
  1. package/dist/components/chat/__init__.py +13 -0
  2. package/dist/components/chat/assets/collection.js +9 -0
  3. package/dist/components/chat/assets/index.js +3 -0
  4. package/dist/components/chat/commands.json +7 -0
  5. package/dist/components/chat/grammar.json +48 -0
  6. package/dist/components/editors/__init__.py +2 -2
  7. package/dist/components/editors/assets/collection.js +22 -120909
  8. package/dist/components/editors/assets/index.js +2 -1
  9. package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
  10. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +3 -0
  11. package/dist/components/editors/assets/modules/chunk-OCFLP2K4.js +16 -0
  12. package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
  13. package/dist/components/editors/assets/modules/code-mirror-engine-QX4A5FVO.js +92 -0
  14. package/dist/components/editors/assets/modules/jodit-engine-MMSPIWM7.js +1853 -0
  15. package/dist/components/editors/assets/modules/prose-mirror-engine-IXTRTG6B.js +24 -0
  16. package/dist/components/grid/__init__.py +13 -0
  17. package/dist/components/grid/assets/collection.js +211 -0
  18. package/dist/components/grid/assets/index.js +3 -0
  19. package/dist/components/grid/commands.json +7 -0
  20. package/dist/components/grid/grammar.json +714 -0
  21. package/dist/components/grouplets/__init__.py +13 -0
  22. package/dist/components/grouplets/assets/collection.js +202 -0
  23. package/dist/components/grouplets/assets/index.js +3 -0
  24. package/dist/components/grouplets/commands.json +7 -0
  25. package/dist/components/grouplets/grammar.json +355 -0
  26. package/dist/components/inputs/__init__.py +1 -1
  27. package/dist/components/inputs/assets/collection.js +32 -24503
  28. package/dist/components/inputs/assets/index.js +2 -1
  29. package/dist/components/inputs/grammar.json +214 -6
  30. package/dist/components/layout/__init__.py +1 -1
  31. package/dist/components/layout/assets/collection.js +27 -26701
  32. package/dist/components/layout/assets/index.js +2 -1
  33. package/dist/components/layout/grammar.json +4 -0
  34. package/dist/components/selection_trial/__init__.py +13 -0
  35. package/dist/components/selection_trial/assets/collection.js +4 -0
  36. package/dist/components/selection_trial/assets/index.js +3 -0
  37. package/dist/components/selection_trial/commands.json +7 -0
  38. package/dist/components/selection_trial/grammar.json +552 -0
  39. package/dist/components/tree/__init__.py +1 -1
  40. package/dist/components/tree/assets/collection.js +24 -24612
  41. package/dist/components/tree/assets/index.js +2 -1
  42. package/dist/components/typst/__init__.py +2 -2
  43. package/dist/components/typst/assets/collection.js +12 -4
  44. package/dist/components/typst/assets/index.js +2 -1
  45. package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
  46. package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
  47. package/dist/gramlot.js +2749 -1627
  48. package/dist/gramlot.min.js +46 -41
  49. package/package.json +7 -2
  50. package/src/binding/grid-struct.js +63 -0
  51. package/src/binding/installation.js +5 -2
  52. package/src/binding/runtime.js +51 -6
  53. package/src/builder/gramlot-builder.d.ts +5 -0
  54. package/src/builder/gramlot-builder.js +16 -0
  55. package/src/builder/source.js +23 -0
  56. package/src/chat.d.ts +12 -0
  57. package/src/chat.js +198 -0
  58. package/src/collection-artifact.js +1 -1
  59. package/src/components/bases.js +2 -0
  60. package/src/components/chat.js +28 -0
  61. package/src/components/choice-editor.js +89 -34
  62. package/src/components/database-choices.js +131 -9
  63. package/src/components/field-state.js +10 -1
  64. package/src/components/grid-grammar.json +237 -0
  65. package/src/components/grid-header-interaction.js +196 -0
  66. package/src/components/grid-row-interaction.js +184 -0
  67. package/src/components/grid-row-layout.js +96 -0
  68. package/src/components/grid-rows.js +28 -0
  69. package/src/components/grid-search-box.js +142 -0
  70. package/src/components/grid-search-styles.js +42 -0
  71. package/src/components/grid-search.js +37 -0
  72. package/src/components/grid-structure.js +84 -0
  73. package/src/components/grid-styles.js +151 -0
  74. package/src/components/grid.js +589 -0
  75. package/src/components/grouplet-card.js +437 -0
  76. package/src/components/grouplets.js +17 -0
  77. package/src/components/menus.js +1 -0
  78. package/src/components/registry.js +4 -3
  79. package/src/components/tray-pane.js +32 -4
  80. package/src/components/typed-editor.js +4 -2
  81. package/src/experiments/selection-transfer.js +78 -0
  82. package/src/experiments/selection-trial.js +48 -0
  83. package/src/experiments/window-selection.js +124 -0
  84. package/src/form-state.d.ts +20 -0
  85. package/src/form-state.js +198 -0
  86. package/src/index-page-styles.js +1 -1
  87. package/src/index.d.ts +3 -1
  88. package/src/index.js +3 -1
  89. package/src/renderer/gramlot-renderer.js +8 -1
  90. package/src/server/gramlot-server.d.ts +2 -0
  91. package/src/server/gramlot-server.js +13 -1
  92. package/src/stores/bag-collection-store.js +51 -0
  93. package/src/stores/bag-collection-view.js +127 -0
  94. package/src/stores/collection-filter.js +77 -0
  95. package/src/view/controls.js +33 -1
  96. package/src/view/grouplet-card.js +54 -0
  97. package/src/view/html.js +20 -3
  98. package/src/view/labelbox.js +7 -3
  99. package/themes/gramlot-base/theme.css +28 -0
  100. package/themes/gramlot-compact/theme.css +8 -0
  101. package/themes/joanna/theme.css +8 -0
  102. package/themes/mimi/theme.css +8 -0
@@ -0,0 +1,589 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+ import {SVG_NS} from '../renderer/attributes.js';
3
+ import {defineComponent, ComponentCollection} from './registry.js';
4
+ import {Container} from './container.js';
5
+ import {parseSort} from '../stores/bag-collection-view.js';
6
+ import {GridRows} from './grid-rows.js';
7
+ import {GridStructure} from './grid-structure.js';
8
+ import {GridHeaderInteraction} from './grid-header-interaction.js';
9
+ import {GridRowLayout} from './grid-row-layout.js';
10
+ import {GridRowInteraction} from './grid-row-interaction.js';
11
+ import {gridStyles} from './grid-styles.js';
12
+ import {gridSearch} from './grid-search.js';
13
+ import {SearchBox} from './grid-search-box.js';
14
+ import structureGrammar from './grid-grammar.json' with {type: 'json'};
15
+
16
+ /** First grid: explicit Bag row representation and a separately observable Data struct. */
17
+ export const Grid = defineComponent({
18
+ name: 'grid', tag: 'gramlot-grid', base: Container, bagStore: true, bagStruct: true, sourceContext: true, subTags: 'struct',
19
+ parameters: {windowInfo: {dtype:'X', nullable:true, default:null, binding:'read'},
20
+ viewport: {dtype:'X', nullable:true, default:null, binding:'write'},
21
+ sortRequest: {dtype:'T', default:'', binding:'write'},
22
+ storepath: {dtype: 'T'}, structpath: {dtype: 'T'}, rowMode: {dtype: 'T'},
23
+ rowHeaders: {dtype:'B', default:false, binding:'read'},
24
+ rowResize: {dtype:'B', default:false, binding:'read'},
25
+ selfDragRows: {dtype:'B', default:false, binding:'read'},
26
+ sortedBy: {dtype:'T', default:'', binding:'read'},
27
+ filter: {annotation:{kind:'type',module:'builtins',name:'dict'}, nullable:true, default:null, binding:'read'}},
28
+ implementation: Base => class extends Base {
29
+ #store;
30
+ #windowRevision;
31
+ #windowRequest;
32
+ #context;
33
+ #structure;
34
+ #structBag;
35
+ #structureDirty = true;
36
+ #signature;
37
+ #rows = new Map();
38
+ #head;
39
+ #body;
40
+ #headerTable;
41
+ #bodyTable;
42
+ #headerViewport;
43
+ #bodyViewport;
44
+ #resizeObserver;
45
+ #layoutFrame = null;
46
+ #headerRows = 1;
47
+ #rowHeaders = false;
48
+ #interaction;
49
+ #rowInteraction;
50
+ #rowLayout;
51
+ #collectionView;
52
+ #requestedSort;
53
+ #requestedFilter;
54
+ #unsubscribeStore;
55
+ #refreshTimer = null;
56
+ #pendingFull = false;
57
+ #pendingRows = new Set();
58
+ #visibleNodes = [];
59
+ #windowStart = -1;
60
+ #windowEnd = -1;
61
+ #topSpace;
62
+ #bottomSpace;
63
+ #geometryKey;
64
+ #endPinned = false;
65
+ #adjustedScroll = null;
66
+ #viewportKey = event => {
67
+ if (event.target !== this.#bodyViewport || !['Home', 'End'].includes(event.key) || !this.#structure) return;
68
+ event.preventDefault();
69
+ this.#endPinned = event.key === 'End';
70
+ this.#scrollTo(this.#endPinned ? Math.max(0, this.#rowLayout.totalHeight - this.#bodyViewport.clientHeight) : 0);
71
+ this.#scheduleLayout();
72
+ };
73
+ #syncScroll = () => {
74
+ const viewport = this.#bodyViewport;
75
+ if (viewport.scrollTop !== this.#adjustedScroll) {
76
+ this.#endPinned = viewport.scrollTop > 0 && viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop <= 1;
77
+ }
78
+ this.#adjustedScroll = null;
79
+ this.#headerViewport.scrollLeft = this.#bodyViewport.scrollLeft;
80
+ this.#scheduleLayout();
81
+ };
82
+ constructor() {
83
+ super();
84
+ const doc = this.ownerDocument;
85
+ const style = doc.createElement('style');
86
+ style.textContent = gridStyles;
87
+ // Two layout tables expose one logical read-only table, with explicit row groups.
88
+ // The header is outside the only user-scrollable viewport.
89
+ this.control.setAttribute('role', 'table');
90
+ this.control.setAttribute('aria-label', 'Grid');
91
+ this.control.setAttribute('part', 'table');
92
+ const headerFrame = doc.createElement('div');
93
+ headerFrame.className = 'header-frame'; headerFrame.setAttribute('part', 'header');
94
+ this.#headerViewport = doc.createElement('div');
95
+ this.#headerViewport.className = 'header-viewport';
96
+ this.#headerViewport.setAttribute('part', 'header-viewport');
97
+ this.#bodyViewport = doc.createElement('div');
98
+ this.#bodyViewport.className = 'body-viewport';
99
+ this.#bodyViewport.setAttribute('part', 'body-viewport');
100
+ this.#bodyViewport.tabIndex = 0;
101
+ this.#bodyViewport.setAttribute('role', 'rowgroup');
102
+ this.#headerTable = doc.createElement('table');
103
+ this.#bodyTable = doc.createElement('table');
104
+ for (const table of [this.#headerTable, this.#bodyTable]) table.setAttribute('role', 'presentation');
105
+ this.#head = doc.createElement('thead'); this.#head.setAttribute('role', 'rowgroup');
106
+ this.#body = doc.createElement('tbody'); this.#body.setAttribute('role', 'presentation');
107
+ this.#headerTable.append(this.#head); this.#bodyTable.append(this.#body);
108
+ this.#headerViewport.append(this.#headerTable); headerFrame.append(this.#headerViewport);
109
+ this.#topSpace = doc.createElement('div');
110
+ this.#bottomSpace = doc.createElement('div');
111
+ for (const space of [this.#topSpace, this.#bottomSpace]) {
112
+ space.className = 'row-space'; space.setAttribute('aria-hidden', 'true');
113
+ }
114
+ this.#bodyViewport.append(this.#topSpace, this.#bodyTable, this.#bottomSpace);
115
+ this.control.replaceChildren(headerFrame, this.#bodyViewport); this.shadowRoot.append(style);
116
+ this.#interaction = new GridHeaderInteraction(this.#head, this.control, () => this.#structure, (field, multiple) => this.#sort(field, multiple),
117
+ () => this.#rowLayout, () => this.#scheduleLayout());
118
+ this.#rowInteraction = new GridRowInteraction(this.#body, this.control, () => this.#rowLayout, row => {
119
+ for (const [node, element] of this.#rows) if (element === row) return node;
120
+ return null;
121
+ }, () => this.#collectionView, () => this.parameters.selfDragRows, () => this.#scheduleLayout());
122
+ this.#resizeObserver = new doc.defaultView.ResizeObserver(() => this.#scheduleLayout());
123
+ }
124
+ connectedCallback() {
125
+ this.#observeStore();
126
+ if (this.#collectionView) this.#invalidate({full:true, rows:[]});
127
+ this.#interaction.connect();
128
+ this.#rowInteraction.connect();
129
+ this.#bodyViewport.addEventListener('scroll', this.#syncScroll, {passive: true});
130
+ this.#bodyViewport.addEventListener('keydown', this.#viewportKey);
131
+ this.#resizeObserver.observe(this.#bodyViewport);
132
+ this.#resizeObserver.observe(this.#bodyTable);
133
+ this.#scheduleLayout();
134
+ }
135
+ disconnectedCallback() {
136
+ this.#cancelRefresh();
137
+ this.#collectionView?.disconnect();
138
+ this.#unsubscribeStore?.(); this.#unsubscribeStore = null;
139
+ this.#interaction.disconnect();
140
+ this.#rowInteraction.disconnect();
141
+ this.#bodyViewport.removeEventListener('scroll', this.#syncScroll);
142
+ this.#bodyViewport.removeEventListener('keydown', this.#viewportKey);
143
+ this.#resizeObserver.disconnect();
144
+ if (this.#layoutFrame !== null) this.ownerDocument.defaultView.cancelAnimationFrame(this.#layoutFrame);
145
+ this.#layoutFrame = null;
146
+ }
147
+ #scheduleLayout() {
148
+ if (!this.isConnected || this.#layoutFrame !== null) return;
149
+ this.#layoutFrame = this.ownerDocument.defaultView.requestAnimationFrame(() => {
150
+ this.#layoutFrame = null;
151
+ const gutter = this.#bodyViewport.offsetWidth - this.#bodyViewport.clientWidth;
152
+ const width = `${gutter}px`;
153
+ if (this.control.style.getPropertyValue('--grid-scrollbar-width') !== width) {
154
+ this.control.style.setProperty('--grid-scrollbar-width', width);
155
+ }
156
+ this.#sizeRowHeader();
157
+ for (const header of this.#head.querySelectorAll('th[scope=col]')) {
158
+ header.querySelector('.column-resize').setAttribute('aria-valuenow', String(Math.round(header.getBoundingClientRect().width)));
159
+ }
160
+ for (const row of this.#rows.values()) {
161
+ const handle = row.querySelector('.row-height-handle');
162
+ if (handle) handle.setAttribute('aria-valuenow', String(Math.round(row.getBoundingClientRect().height)));
163
+ }
164
+ this.#headerViewport.scrollLeft = this.#bodyViewport.scrollLeft;
165
+ if (!this.#structure) return;
166
+ try { this.#layoutWindow(); }
167
+ catch (error) { this.#context.reportError(error, 'Grid viewport'); }
168
+ });
169
+ }
170
+ #sizeRowHeader() {
171
+ if (!this.#rowHeaders) return;
172
+ const probe = this.#head.querySelector('.row-number-measure');
173
+ probe.textContent = String(Math.max(1, this.#rowLayout.count));
174
+ const minimum = Math.ceil(probe.getBoundingClientRect().width);
175
+ this.control.style.setProperty('--grid-row-header-min-width', `${minimum}px`);
176
+ if (this.#rowLayout.headerWidth === null) this.control.style.removeProperty('--grid-row-header-width');
177
+ else this.control.style.setProperty('--grid-row-header-width', `${this.#rowLayout.headerWidth}px`);
178
+ const handle = this.#head.querySelector('.row-heading .column-resize');
179
+ handle.setAttribute('aria-valuemin', String(Math.max(40, minimum)));
180
+ }
181
+ #layoutWindow() {
182
+ const viewport = this.#bodyViewport;
183
+ const anchor = this.#rowLayout.indexAt(viewport.scrollTop);
184
+ const within = viewport.scrollTop - this.#rowLayout.offset(anchor);
185
+ let changed = false;
186
+ const first = this.#rows.values().next().value;
187
+ if (first) {
188
+ const style = this.ownerDocument.defaultView.getComputedStyle(first.querySelector('td'));
189
+ const key = JSON.stringify([this.#bodyTable.getBoundingClientRect().width,
190
+ style.font, style.lineHeight, style.padding, style.getPropertyValue('--gramlot-grid-row-height')]);
191
+ if (key !== this.#geometryKey) {
192
+ this.#rowLayout.resetMeasurements(); this.#geometryKey = key; changed = true;
193
+ }
194
+ }
195
+ for (const [node, row] of this.#rows) {
196
+ changed = this.#rowLayout.measure(node, row.getBoundingClientRect().height) || changed;
197
+ }
198
+ if (changed && this.#visibleNodes.length) {
199
+ // Keep the same visible row while estimated heights become exact.
200
+ const top = this.#rowLayout.offset(anchor) + within;
201
+ this.#setSpaces();
202
+ this.#scrollTo(this.#endPinned ? Math.max(0, this.#rowLayout.totalHeight - viewport.clientHeight) : top);
203
+ }
204
+ if (!this.#rowInteraction.resizing) this.#renderWindow();
205
+ }
206
+ #setSpaces() {
207
+ const start = Math.max(0, this.#windowStart), end = Math.max(start, this.#windowEnd);
208
+ this.#topSpace.style.height = `${this.#rowLayout.offset(start)}px`;
209
+ this.#bottomSpace.style.height = `${Math.max(0, this.#rowLayout.totalHeight - this.#rowLayout.offset(end))}px`;
210
+ }
211
+ #scrollTo(top) {
212
+ if (this.#bodyViewport.scrollTop === top) return;
213
+ this.#bodyViewport.scrollTop = top;
214
+ // A layout correction emits a scroll event too. Do not mistake it
215
+ // for a user leaving the bottom while new rows are being measured.
216
+ this.#adjustedScroll = this.#bodyViewport.scrollTop;
217
+ }
218
+ #renderWindow(force = false) {
219
+ const viewport = this.#bodyViewport;
220
+ const maximum = Math.max(0, this.#rowLayout.totalHeight - viewport.clientHeight);
221
+ const top = this.#endPinned ? maximum : Math.min(viewport.scrollTop, maximum);
222
+ let {start, end} = this.#rowLayout.window(top, viewport.clientHeight);
223
+ const info = this.#windowInfo();
224
+ if (info) {
225
+ const loadedEnd = info.start + this.#visibleNodes.length;
226
+ if (start < info.start || end > loadedEnd) {
227
+ const count = Math.max(200, end - start);
228
+ const requestedStart = Math.max(0, Math.min(Math.max(0, info.total - count), start));
229
+ const key = JSON.stringify([info.revision, requestedStart, count]);
230
+ if (key !== this.#windowRequest) {
231
+ this.#windowRequest = key;
232
+ this.#context.writeParameter('viewport', {start:requestedStart, count});
233
+ }
234
+ this.control.setAttribute('aria-busy', 'true');
235
+ } else {
236
+ this.#windowRequest = null;
237
+ this.control.removeAttribute('aria-busy');
238
+ }
239
+ start = Math.max(start, info.start);
240
+ end = Math.max(start, Math.min(end, loadedEnd));
241
+ }
242
+ if (force || start !== this.#windowStart || end !== this.#windowEnd) {
243
+ const rows = new GridRows(this.#collectionView, this.#context.format)
244
+ .read(this.#structure.columns, this.#visibleNodes.slice(start-(info?.start ?? 0), end-(info?.start ?? 0)));
245
+ this.#renderRows(rows, this.#structure.columns, start);
246
+ this.#windowStart = start; this.#windowEnd = end;
247
+ this.#scheduleLayout();
248
+ }
249
+ this.#setSpaces();
250
+ this.#scrollTo(top);
251
+ }
252
+ #windowInfo() {
253
+ const value = this.parameters.windowInfo;
254
+ if (value === null) return null;
255
+ if (!(value instanceof Bag)) throw new TypeError('Grid windowInfo requires a Bag');
256
+ return Object.fromEntries(['start', 'total', 'revision', 'sortedBy'].map(key => [key, value.getItem(key)]));
257
+ }
258
+ setSourceContext(context) {
259
+ this.#context = context;
260
+ const node = context.sourceNode;
261
+ if (!Object.hasOwn(node, 'gridRowLayout')) {
262
+ Object.defineProperty(node, 'gridRowLayout', {value:new GridRowLayout(), configurable:true});
263
+ }
264
+ this.#rowLayout = node.gridRowLayout;
265
+ }
266
+ setStoreBag(bag) {
267
+ if (!(bag instanceof Bag)) throw new TypeError('grid storepath must resolve to a Bag');
268
+ this.#store = bag;
269
+ this.#rowLayout.bindStore(bag);
270
+ }
271
+ setStructBag(bag) { this.#structBag = bag; this.#structureDirty = true; }
272
+ projectAttributes(attrs, adapt) {
273
+ const rest = super.projectAttributes(attrs, adapt);
274
+ const store = this.#context.collectionView(this.#store, this.parameters.rowMode);
275
+ if (this.#collectionView !== store) {
276
+ this.#cancelRefresh();
277
+ this.#unsubscribeStore?.(); this.#unsubscribeStore = null;
278
+ this.#collectionView = store;
279
+ this.#observeStore();
280
+ }
281
+ if (!this.#windowInfo() && this.#requestedSort !== this.parameters.sortedBy) {
282
+ this.#collectionView.sort(this.parameters.sortedBy);
283
+ this.#requestedSort = this.parameters.sortedBy;
284
+ }
285
+ const filter = this.parameters.filter;
286
+ const signature = JSON.stringify(filter);
287
+ if (!this.#windowInfo() && this.#requestedFilter !== signature) {
288
+ this.#collectionView.applyFilter(filter === null ? null : {locale:this.#context.locale,timeZone:this.#context.timeZone,...filter});
289
+ this.#requestedFilter = signature;
290
+ }
291
+ this.#invalidate({full:true, rows:[]});
292
+ return rest;
293
+ }
294
+ #observeStore() {
295
+ if (this.isConnected && this.#collectionView && !this.#unsubscribeStore) {
296
+ this.#collectionView.connect();
297
+ this.#unsubscribeStore = this.#collectionView.subscribe(change => this.#invalidate(change));
298
+ }
299
+ }
300
+ #cancelRefresh() {
301
+ if (this.#refreshTimer !== null) this.ownerDocument.defaultView.clearTimeout(this.#refreshTimer);
302
+ this.#refreshTimer = null;
303
+ this.#pendingFull = false;
304
+ this.#pendingRows.clear();
305
+ }
306
+ #invalidate({full, rows}) {
307
+ this.#pendingFull ||= full;
308
+ if (this.#pendingFull) this.#pendingRows.clear();
309
+ else for (const node of rows) this.#pendingRows.add(node);
310
+ if (!this.isConnected || this.#refreshTimer !== null) return;
311
+ this.#refreshTimer = this.ownerDocument.defaultView.setTimeout(() => {
312
+ const full = this.#pendingFull, nodes = [...this.#pendingRows];
313
+ this.#refreshTimer = null;
314
+ this.#pendingFull = false;
315
+ this.#pendingRows.clear();
316
+ try {
317
+ if (full) this.#project();
318
+ else this.#projectRows(nodes);
319
+ } catch (error) {
320
+ // Keep the last valid DOM. A later change retries a complete pull;
321
+ // there is no automatic retry loop and no exception in Data delivery.
322
+ this.#pendingFull = true;
323
+ this.#context.reportError(error, 'Grid refresh');
324
+ }
325
+ }, 0);
326
+ }
327
+ #projectRows(nodes) {
328
+ for (const node of nodes) this.#rowLayout.forget(node);
329
+ const rows = new GridRows(this.#collectionView, this.#context.format).read(this.#structure.columns, nodes.filter(node => this.#rows.has(node)));
330
+ this.#rowInteraction.cancel();
331
+ for (const {node, cells} of rows) this.#renderCells(this.#rows.get(node), cells);
332
+ this.#scheduleLayout();
333
+ }
334
+ #project() {
335
+ const model = this.#structureDirty ? new GridStructure(this.#structBag) : this.#structure;
336
+ const nodes = this.#collectionView.getRows();
337
+ this.#rowInteraction.cancel(); this.#rowInteraction.cancelDrag();
338
+ this.#rowLayout.retain(this.#store.getNodes());
339
+ if (this.#structureDirty) this.#rowLayout.resetMeasurements();
340
+ const info = this.#windowInfo();
341
+ this.#rowLayout.setWindow(info);
342
+ this.#rowLayout.setRows(nodes);
343
+ this.#visibleNodes = nodes;
344
+ if (info && this.#windowRevision !== info.revision) {
345
+ this.#endPinned = false;
346
+ this.#scrollTo(0);
347
+ this.#windowRequest = null;
348
+ }
349
+ this.#windowRevision = info?.revision;
350
+ this.#structure = model;
351
+ this.#structureDirty = false;
352
+ gridSearch(this.#context.sourceNode).update(this.#collectionView, model.columns);
353
+ const rowHeaders = this.parameters.rowHeaders || this.parameters.rowResize;
354
+ const signature = JSON.stringify([model.groups, rowHeaders]);
355
+ this.#rowHeaders = rowHeaders;
356
+ if (signature !== this.#signature) {
357
+ this.#renderHeader(model);
358
+ this.#signature = signature;
359
+ }
360
+ this.#renderSort();
361
+ this.#renderWindow(true);
362
+ this.control.setAttribute('aria-colcount', String(model.columns.length + Number(this.#rowHeaders)));
363
+ this.control.setAttribute('aria-rowcount', String(this.#headerRows + Math.max(this.#rowLayout.count, 1)));
364
+ this.#scheduleLayout();
365
+ }
366
+ #sort(field, multiple) {
367
+ try {
368
+ const criteria = this.#windowInfo() ? parseSort(this.#windowInfo().sortedBy) : this.#collectionView.criteria;
369
+ const current = criteria.find(item => item.field === field);
370
+ const direction = current?.direction === 'a' ? 'd' : 'a';
371
+ const next = multiple ? criteria.filter(item => item.field !== field) : [];
372
+ if (multiple && current) next.splice(criteria.indexOf(current), 0, {field, direction});
373
+ else next.push({field, direction});
374
+ const sortedBy = next.map(item => `${item.field}:${item.direction}`).join(',');
375
+ if (this.#windowInfo()) this.#context.writeParameter('sortRequest', sortedBy);
376
+ else this.#collectionView.sort(sortedBy);
377
+ } catch (error) { this.#context.reportError(error, 'Grid sort'); }
378
+ }
379
+ #renderSort() {
380
+ const criteria = this.#windowInfo() ? parseSort(this.#windowInfo().sortedBy) : this.#collectionView.criteria;
381
+ this.#sizeRowHeader();
382
+ for (const header of this.#head.querySelectorAll('th[scope=col]')) {
383
+ const index = criteria.findIndex(item => item.field === header.dataset.field);
384
+ header.removeAttribute('aria-sort');
385
+ if (index < 0) {
386
+ delete header.dataset.sortDirection; delete header.dataset.sortPriority;
387
+ header.removeAttribute('aria-label');
388
+ } else {
389
+ const direction = criteria[index].direction === 'a' ? 'ascending' : 'descending';
390
+ header.dataset.sortDirection = direction; header.dataset.sortPriority = String(index + 1);
391
+ if (index === 0) header.setAttribute('aria-sort', direction);
392
+ header.setAttribute('aria-label', `${header.textContent}, sort ${index + 1}, ${direction}`);
393
+ }
394
+ }
395
+ }
396
+ #renderHeader(model) {
397
+ this.#interaction.cancel();
398
+ const focused = this.shadowRoot.activeElement;
399
+ const focusedField = focused?.closest('th[data-field]')?.dataset.field;
400
+ const resizeFocused = focused?.classList.contains('column-resize');
401
+ const doc = this.ownerDocument, grouped = model.groups.some(group => group.name !== null);
402
+ this.#headerRows = grouped ? 2 : 1;
403
+ const top = doc.createElement('tr'), bottom = doc.createElement('tr');
404
+ for (const [index, row] of [top, bottom].entries()) {
405
+ row.setAttribute('role', 'row'); row.setAttribute('aria-rowindex', String(index + 1));
406
+ }
407
+ const header = (text, span, rowSpan, scope, index, align = 'start') => {
408
+ const cell = doc.createElement('th'); cell.textContent = text;
409
+ cell.colSpan = span; cell.rowSpan = rowSpan; cell.scope = scope;
410
+ cell.setAttribute('role', 'columnheader'); cell.setAttribute('part', scope === 'colgroup' ? 'group-header' : 'column-header');
411
+ cell.setAttribute('aria-colindex', String(index + 1 + Number(this.#rowHeaders)));
412
+ cell.setAttribute('aria-colspan', String(span)); cell.setAttribute('aria-rowspan', String(rowSpan));
413
+ cell.style.textAlign = align;
414
+ if (scope === 'col') {
415
+ const caption = doc.createElement('span');
416
+ caption.className = 'column-caption'; caption.textContent = text; cell.replaceChildren(caption);
417
+ const column = model.columns[index];
418
+ cell.dataset.field = column.field;
419
+ cell.draggable = true; cell.tabIndex = 0;
420
+ cell.title = 'Click: ascending / descending · Shift-click: add or reverse this column without changing the others · Numbers show sort priority · Drag to reorder';
421
+ const indicator = doc.createElementNS(SVG_NS, 'svg');
422
+ indicator.classList.add('sort-indicator'); indicator.setAttribute('viewBox', '0 0 16 16');
423
+ indicator.setAttribute('aria-hidden', 'true');
424
+ const arrow = doc.createElementNS(SVG_NS, 'path');
425
+ arrow.setAttribute('d', 'M4 10L8 6L12 10'); indicator.append(arrow); cell.append(indicator);
426
+ const handle = doc.createElement('span');
427
+ handle.className = 'column-resize'; handle.tabIndex = 0;
428
+ handle.setAttribute('role', 'separator');
429
+ handle.setAttribute('aria-orientation', 'vertical');
430
+ handle.setAttribute('aria-valuemin', '40');
431
+ handle.setAttribute('aria-label', `Resize ${column.name}`);
432
+ handle.title = 'Drag to resize · Arrow keys adjust width';
433
+ cell.append(handle);
434
+ }
435
+ return cell;
436
+ };
437
+ if (this.#rowHeaders) {
438
+ const corner = doc.createElement('th');
439
+ corner.textContent = '#'; corner.scope = 'col'; corner.className = 'row-heading';
440
+ corner.rowSpan = this.#headerRows;
441
+ corner.setAttribute('role', 'columnheader');
442
+ corner.setAttribute('aria-colindex', '1');
443
+ corner.setAttribute('aria-rowspan', String(this.#headerRows));
444
+ corner.setAttribute('part', 'row-header');
445
+ const probe = doc.createElement('span');
446
+ probe.className = 'row-number-measure'; probe.setAttribute('aria-hidden', 'true');
447
+ const handle = doc.createElement('span');
448
+ handle.className = 'column-resize'; handle.tabIndex = 0;
449
+ handle.setAttribute('role', 'separator'); handle.setAttribute('aria-orientation', 'vertical');
450
+ handle.setAttribute('aria-label', 'Resize row numbers');
451
+ handle.title = 'Drag to resize · Arrow keys adjust width';
452
+ corner.append(probe, handle); top.append(corner);
453
+ }
454
+ let index = 0;
455
+ for (const group of model.groups) {
456
+ if (grouped && group.name !== null) {
457
+ const band = header(group.name, group.columns.length, 1, 'colgroup', index, 'center');
458
+ band.style.background = group.background ?? '';
459
+ band.style.color = group.color ?? '';
460
+ top.append(band);
461
+ for (const col of group.columns) bottom.append(header(col.name, 1, 1, 'col', index++, col.align));
462
+ } else for (const col of group.columns) {
463
+ if (grouped) {
464
+ const spacer = doc.createElement('td');
465
+ spacer.className = 'group-spacer'; spacer.setAttribute('aria-hidden', 'true');
466
+ top.append(spacer);
467
+ }
468
+ (grouped ? bottom : top).append(header(col.name, 1, 1, 'col', index++, col.align));
469
+ }
470
+ }
471
+ this.#head.replaceChildren(top, ...(grouped ? [bottom] : []));
472
+ if (focusedField) this.#head.querySelector(`th[data-field="${focusedField}"]${resizeFocused ? ' .column-resize' : ''}`)?.focus({preventScroll:true});
473
+ const widths = model.columns.map(column => column.width ?? 'var(--gramlot-grid-column-width, 10rem)');
474
+ if (this.#rowHeaders) widths.unshift('max(var(--grid-row-header-min-width, 0px), var(--grid-row-header-width, var(--gramlot-grid-row-header-width, 44px)))');
475
+ this.control.style.setProperty('--grid-columns-width', `calc(${widths.join(' + ')})`);
476
+ // Identical colgroups and table constraints keep one CSS sizing policy for both areas.
477
+ for (const table of [this.#headerTable, this.#bodyTable]) {
478
+ for (const group of table.querySelectorAll(':scope > colgroup')) group.remove();
479
+ table.prepend(...model.groups.map(group => {
480
+ const element = doc.createElement('colgroup');
481
+ for (const column of group.columns) {
482
+ const col = doc.createElement('col');
483
+ col.style.width = column.width ?? 'var(--gramlot-grid-column-width, 10rem)';
484
+ element.append(col);
485
+ }
486
+ return element;
487
+ }));
488
+ if (this.#rowHeaders) {
489
+ const group = doc.createElement('colgroup'), col = doc.createElement('col');
490
+ col.style.width = 'max(var(--grid-row-header-min-width, 0px), var(--grid-row-header-width, var(--gramlot-grid-row-header-width, 44px)))';
491
+ group.append(col); table.prepend(group);
492
+ }
493
+ }
494
+ }
495
+ #renderRows(rows, columns, start) {
496
+ this.#rowInteraction.cancel();
497
+
498
+ const keep = new Set(); let previous = null;
499
+ this.#body.querySelector('.empty')?.parentElement.remove();
500
+ for (const {node, cells} of rows) {
501
+ let tr = this.#rows.get(node);
502
+ if (!tr) {
503
+ tr = this.ownerDocument.createElement('tr'); tr.setAttribute('part', 'row');
504
+ tr.setAttribute('role', 'row');
505
+ tr.dataset.row = node.label;
506
+ this.#rows.set(node, tr);
507
+ }
508
+ tr.classList.toggle('alternate', (start + keep.size) % 2 === 1);
509
+ tr.draggable = this.parameters.selfDragRows;
510
+ let heading = tr.querySelector('th[scope=row]');
511
+ if (this.#rowHeaders) {
512
+ if (!heading) {
513
+ heading = this.ownerDocument.createElement('th');
514
+ heading.scope = 'row'; heading.className = 'row-heading';
515
+ heading.setAttribute('role', 'rowheader'); heading.setAttribute('part', 'row-header');
516
+ heading.setAttribute('aria-colindex', '1');
517
+ const caption = this.ownerDocument.createElement('span');
518
+ caption.className = 'row-number'; heading.append(caption); tr.prepend(heading);
519
+ }
520
+ heading.querySelector('.row-number').textContent = String(start + keep.size + 1);
521
+ let handle = heading.querySelector('.row-height-handle');
522
+ if (this.parameters.rowResize) {
523
+ if (!handle) {
524
+ handle = this.ownerDocument.createElement('span');
525
+ handle.className = 'row-height-handle'; handle.tabIndex = 0;
526
+ handle.setAttribute('role', 'separator');
527
+ handle.setAttribute('aria-orientation', 'horizontal');
528
+ handle.title = 'Drag to resize row · Double-click or Home resets · Arrow keys adjust height';
529
+ heading.append(handle);
530
+ }
531
+ handle.setAttribute('aria-label', `Resize row ${start + keep.size + 1}`);
532
+ } else handle?.remove();
533
+ } else heading?.remove();
534
+ const offset = Number(this.#rowHeaders);
535
+ const existing = new Map([...tr.querySelectorAll('td[data-field]')].map(td => [td.dataset.field, td]));
536
+ for (const [index, column] of columns.entries()) {
537
+ let td = existing.get(column.field);
538
+ if (!td) {
539
+ td = this.ownerDocument.createElement('td'); td.setAttribute('part', 'cell');
540
+ td.dataset.field = column.field; td.setAttribute('role', 'cell');
541
+ }
542
+ td.style.textAlign = column.align;
543
+ td.style.whiteSpace = column.white_space ?? '';
544
+ td.style.overflowWrap = column.white_space === 'pre-wrap' || column.white_space === 'normal' ? 'anywhere' : '';
545
+ td.setAttribute('aria-colindex', String(index + 1 + offset));
546
+ td.classList.toggle('numeric', ['L', 'R', 'N'].includes(column.dtype));
547
+ if (tr.cells[index + offset] !== td) tr.insertBefore(td, tr.cells[index + offset] ?? null);
548
+ existing.delete(column.field);
549
+ }
550
+ for (const td of existing.values()) td.remove();
551
+ tr.setAttribute('aria-rowindex', String(this.#headerRows + start + keep.size + 1));
552
+ this.#renderCells(tr, cells);
553
+ const next = previous ? previous.nextSibling : this.#body.firstChild;
554
+ if (next !== tr) this.#body.insertBefore(tr, next);
555
+ this.#rowInteraction.project(tr, node);
556
+ previous = tr; keep.add(node);
557
+ }
558
+ for (const [node, tr] of this.#rows) if (!keep.has(node)) { tr.remove(); this.#rows.delete(node); }
559
+ if (!rows.length) {
560
+ const tr = this.ownerDocument.createElement('tr'), td = this.ownerDocument.createElement('td');
561
+ tr.setAttribute('role', 'row'); tr.setAttribute('aria-rowindex', String(this.#headerRows + 1));
562
+ td.setAttribute('role', 'cell'); td.setAttribute('aria-colspan', String(columns.length + Number(this.#rowHeaders)));
563
+ td.className = 'empty'; td.colSpan = columns.length + Number(this.#rowHeaders); td.textContent = 'No rows'; tr.append(td); this.#body.append(tr);
564
+ }
565
+ }
566
+ #renderCells(row, cells) {
567
+ const offset = Number(this.#rowHeaders);
568
+ cells.forEach((text, index) => {
569
+ if (row.cells[index + offset].textContent !== text) row.cells[index + offset].textContent = text;
570
+ });
571
+ }
572
+ }
573
+ });
574
+
575
+ class GridCollection extends ComponentCollection {
576
+ toDocument() {
577
+ const document = super.toDocument();
578
+ const parameters = document.elements.grid.attributes.parameters;
579
+ for (const name of ['storepath', 'rowMode']) {
580
+ const parameter = parameters.find(item => item.name === name);
581
+ parameter.has_default = false; delete parameter.default;
582
+ if (name === 'rowMode') parameter.annotation = {kind: 'annotated', base: {kind: 'dtype', dtype: 'T'},
583
+ metadata: [{kind: 'regex', pattern: '^(values|attributes)$', flags: 0}]};
584
+ }
585
+ Object.assign(document.elements, structuredClone(structureGrammar.elements));
586
+ return document;
587
+ }
588
+ }
589
+ export default new GridCollection({name: 'grid', components: [Grid, SearchBox]});