@gramlot/gramlot 0.3.24 → 0.3.26

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 (131) hide show
  1. package/dist/components/editors/__init__.py +2 -2
  2. package/dist/components/editors/assets/collection.js +20 -19
  3. package/dist/components/editors/assets/index.js +1 -1
  4. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  5. package/dist/components/editors/assets/modules/{code-mirror-engine-QX4A5FVO.js → code-mirror-engine-RWQTR5G5.js} +29 -29
  6. package/dist/components/editors/assets/modules/{jodit-engine-MMSPIWM7.js → jodit-engine-MTSA4GZ3.js} +292 -292
  7. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  8. package/dist/components/editors/assets/modules/{prose-mirror-engine-IXTRTG6B.js → prose-mirror-engine-GMZPJPNN.js} +13 -13
  9. package/dist/components/grid/__init__.py +3 -2
  10. package/dist/components/grid/assets/collection.js +68 -17
  11. package/dist/components/grid/assets/index.js +1 -1
  12. package/dist/components/grid/grammar.json +57 -1
  13. package/dist/components/grouplets/__init__.py +2 -2
  14. package/dist/components/grouplets/assets/collection.js +3 -20
  15. package/dist/components/grouplets/assets/index.js +1 -1
  16. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  17. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  18. package/dist/components/inputs/__init__.py +1 -1
  19. package/dist/components/inputs/assets/collection.js +59 -34
  20. package/dist/components/inputs/assets/index.js +1 -1
  21. package/dist/components/inputs/grammar.json +64 -0
  22. package/dist/components/layout/__init__.py +1 -1
  23. package/dist/components/layout/assets/collection.js +67 -57
  24. package/dist/components/layout/assets/index.js +1 -1
  25. package/dist/components/layout/grammar.json +35 -0
  26. package/dist/components/selection_trial/__init__.py +1 -1
  27. package/dist/components/selection_trial/assets/collection.js +3 -3
  28. package/dist/components/selection_trial/assets/index.js +1 -1
  29. package/dist/components/selection_trial/grammar.json +35 -0
  30. package/dist/components/tree/__init__.py +1 -1
  31. package/dist/components/tree/assets/collection.js +26 -23
  32. package/dist/components/tree/assets/index.js +1 -1
  33. package/dist/components/tree/grammar.json +341 -1
  34. package/dist/components/uploads/__init__.py +13 -0
  35. package/dist/components/uploads/assets/collection.js +67 -0
  36. package/dist/components/uploads/assets/index.js +3 -0
  37. package/dist/components/uploads/commands.json +7 -0
  38. package/dist/components/uploads/grammar.json +789 -0
  39. package/dist/{components/editors/assets/modules/chunk-OCFLP2K4.js → gramlot-markdown.js} +12 -12
  40. package/dist/gramlot.js +4910 -566
  41. package/dist/gramlot.min.js +1587 -43
  42. package/dist/runtime-notices.json +28 -0
  43. package/package.json +4 -2
  44. package/src/binding/grid-struct.js +1 -1
  45. package/src/binding/providers.js +4 -1
  46. package/src/binding/remote-resolver.js +1 -8
  47. package/src/binding/runtime.js +40 -1
  48. package/src/binding/validation-context.js +40 -0
  49. package/src/browser-camera-provider.d.ts +8 -0
  50. package/src/browser-camera-provider.js +104 -0
  51. package/src/builder/source.js +13 -2
  52. package/src/components/attachment-manager.js +160 -0
  53. package/src/components/bases.js +17 -6
  54. package/src/components/border-container.js +86 -8
  55. package/src/components/buttons.js +11 -1
  56. package/src/components/choice-editor.js +20 -7
  57. package/src/components/database-choices.js +4 -2
  58. package/src/components/editing-status-styles.js +26 -0
  59. package/src/components/editing-status.js +115 -0
  60. package/src/components/field-state.js +37 -58
  61. package/src/components/grid-cell-editor.js +181 -0
  62. package/src/components/grid-grammar.json +21 -0
  63. package/src/components/grid-structure.js +2 -1
  64. package/src/components/grid-styles.js +51 -1
  65. package/src/components/grid.js +87 -10
  66. package/src/components/grouplet-card.js +11 -3
  67. package/src/components/html-preview.js +17 -4
  68. package/src/components/image-crop-dialog.js +272 -0
  69. package/src/components/image-crop.js +79 -0
  70. package/src/components/image-uploader.js +252 -0
  71. package/src/components/inputs.js +2 -1
  72. package/src/components/jodit-engine.js +1 -1
  73. package/src/components/markdown-document.js +2 -2
  74. package/src/components/screen-capture.js +43 -0
  75. package/src/components/selected-container.js +6 -2
  76. package/src/components/tree.js +416 -17
  77. package/src/components/typed-editor.js +19 -9
  78. package/src/components/upload-engine.js +156 -0
  79. package/src/components/uploader.js +208 -0
  80. package/src/components/uploads.js +7 -0
  81. package/src/editing-session.d.ts +25 -0
  82. package/src/editing-session.js +396 -0
  83. package/src/experiments/selection-trial.js +18 -2
  84. package/src/format.js +22 -7
  85. package/src/gramlot.d.ts +2 -0
  86. package/src/gramlot.js +2 -1
  87. package/src/handlers/device-handler.d.ts +2 -1
  88. package/src/handlers/rpc-handler.d.ts +3 -3
  89. package/src/index-page-styles.js +1 -0
  90. package/src/index.d.ts +13 -0
  91. package/src/index.js +13 -0
  92. package/src/inout.d.ts +2 -0
  93. package/src/inout.js +6 -0
  94. package/src/markdown-loader.d.ts +1 -0
  95. package/src/markdown-loader.js +4 -0
  96. package/src/markdown.d.ts +1 -0
  97. package/src/markdown.js +2 -0
  98. package/src/media-frame.js +9 -0
  99. package/src/renderer/attributes.js +7 -1
  100. package/src/renderer/gramlot-renderer.d.ts +2 -0
  101. package/src/renderer/gramlot-renderer.js +31 -2
  102. package/src/server/assets.d.ts +1 -1
  103. package/src/server/assets.js +1 -1
  104. package/src/server/gramlot-server.d.ts +8 -1
  105. package/src/server/gramlot-server.js +83 -7
  106. package/src/server/index.d.ts +2 -0
  107. package/src/server/index.js +2 -0
  108. package/src/server/page-base.js +17 -4
  109. package/src/server/page.d.ts +13 -1
  110. package/src/server/page.js +6 -0
  111. package/src/server/source-import.d.ts +2 -0
  112. package/src/server/source-import.js +31 -0
  113. package/src/server/upload.d.ts +20 -0
  114. package/src/server/upload.js +142 -0
  115. package/src/server/visual-editor.d.ts +11 -0
  116. package/src/server/visual-editor.js +149 -0
  117. package/src/source-picker.d.ts +9 -0
  118. package/src/source-picker.js +57 -0
  119. package/src/tree-store.d.ts +24 -0
  120. package/src/tree-store.js +193 -0
  121. package/src/validation-run.js +50 -0
  122. package/src/view/button.js +8 -5
  123. package/src/view/controls.js +9 -42
  124. package/src/view/html.js +10 -2
  125. package/src/visual-editor-icons.js +10 -0
  126. package/src/visual-editor.d.ts +56 -0
  127. package/src/visual-editor.js +844 -0
  128. package/themes/gramlot-base/theme.css +99 -0
  129. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +0 -3
  130. package/src/form-state.d.ts +0 -20
  131. package/src/form-state.js +0 -198
@@ -1,25 +1,70 @@
1
1
  /** Bag hierarchy, lazy branch expansion, captions and path selection. */
2
- import {Bag} from '@gramlot/gramlot';
3
- import createDOMPurify from 'dompurify';
2
+ import {Bag, createDOMPurify} from '@gramlot/gramlot';
4
3
  import {defineComponent, defineCollection} from './registry.js';
5
4
  import {Container} from './container.js';
6
5
  import {SVG_NS} from '../renderer/attributes.js';
7
6
 
7
+ export const RowActions = defineComponent({
8
+ name: 'rowActions', tag: 'gramlot-row-actions', base: Container,
9
+ subTags: 'button,dropDownButton', sourceContext: true, parameters: {
10
+ position: {dtype: 'T', default: 'end'},
11
+ actionState: {dtype: 'T', nullable: true, default: null},
12
+ state: {dtype: 'X', nullable: true, default: null, binding: 'read'}
13
+ },
14
+ implementation: Base => class extends Base {
15
+ #rowContext = null;
16
+ #context;
17
+ connectedCallback() { this.slot = 'row-actions'; this.hidden = true; }
18
+ setSourceContext(context) { this.#context = context; }
19
+ setRowContext(item, path) { this.#rowContext = {item, path}; this.#refresh(); }
20
+ getRowContext() { return this.#rowContext; }
21
+ clearRowContext() { this.#rowContext = null; this.hidden = true; }
22
+ projectAttributes(attrs, adapt) {
23
+ const rest = super.projectAttributes(attrs, adapt);
24
+ if (!['start', 'end'].includes(this.parameters.position)) throw new TypeError('rowActions position must be start or end');
25
+ this.#refresh();
26
+ return rest;
27
+ }
28
+ #refresh() {
29
+ if (!this.#rowContext || !this.parameters.actionState) return;
30
+ for (const action of this.children) {
31
+ const code = action.getAttribute('rowAction');
32
+ if (code === null) continue;
33
+ const presentation = this.#context.callLogic(this.parameters.actionState,
34
+ {...this.#rowContext, action: code, state: this.parameters.state});
35
+ if (!presentation || typeof presentation.hidden !== 'boolean' ||
36
+ typeof presentation.icon !== 'string' || typeof presentation.title !== 'string') {
37
+ throw new TypeError('rowActions actionState must return hidden, icon and title');
38
+ }
39
+ action.setActionPresentation(presentation);
40
+ }
41
+ }
42
+ }
43
+ });
44
+
8
45
  export const Tree = defineComponent({
9
- name: 'tree', tag: 'gramlot-tree', base: Container, sourceContext: true, bagStore: true, dragSource: true,
46
+ name: 'tree', tag: 'gramlot-tree', base: Container, subTags: 'rowActions[:1]', sourceContext: true, bagStore: true, dragSource: true,
10
47
  parameters: {
11
48
  storepath: {dtype: 'T'},
12
49
  draggable: {dtype: 'B', default: false, binding: 'read'},
13
50
  labelAttribute: {dtype: 'T', nullable: true, default: null, binding: 'read'},
51
+ internalNames: {dtype: 'B', default: false, binding: 'read'},
14
52
  hideValues: {dtype: 'B', default: false, binding: 'read'},
53
+ excludeRoot: {dtype: 'T', nullable: true, default: null, binding: 'read'},
15
54
  labelCb: {dtype: 'T', nullable: true, default: null},
16
55
  getLabel: {dtype: 'T', nullable: true, default: null},
17
56
  getLabelClass: {dtype: 'T', nullable: true, default: null},
18
57
  getIconClass: {dtype: 'T', nullable: true, default: null},
19
58
  selectedLabelClass: {dtype: 'T', default: '', binding: 'read'},
20
59
  searchText: {dtype: 'T', default: '', binding: 'read'},
60
+ favorites: {dtype: 'X', nullable: true, default: null, binding: 'read'},
61
+ favoritesLabel: {dtype: 'T', default: 'Favorites', binding: 'read'},
21
62
  autoCollapse: {dtype: 'B', default: false, binding: 'read'},
22
- selectedPath: {dtype: 'T', nullable: true, default: null, binding: 'twoWay'}
63
+ selectedPath: {dtype: 'T', nullable: true, default: null, binding: 'twoWay'},
64
+ onChecked: {dtype: ['B', 'T'], nullable: true, default: null},
65
+ checkedPaths: {dtype: 'T', nullable: true, default: null, binding: 'twoWay'},
66
+ checkedPaths_joiner: {dtype: 'T', default: ','},
67
+ checkChildren: {dtype: 'B', default: true, binding: 'read'}
23
68
  },
24
69
  implementation: Base => class extends Base {
25
70
  #store;
@@ -27,14 +72,23 @@ export const Tree = defineComponent({
27
72
  #context;
28
73
  #expanded = new Set();
29
74
  #rows = new Map();
75
+ #favoriteRows = new Map();
76
+ #favoritesOpen = false;
30
77
  #dragRows = new WeakMap();
31
78
  #presentations = new Map();
32
79
  #requestedPath;
80
+ #selectionVersion = 0;
33
81
  #selectedPath = null;
34
82
  #scheduled = false;
83
+ #checkedPaths;
84
+ #checksEnabled = false;
85
+ #pathsEnabled = false;
86
+ #checkedBags = new WeakMap();
87
+ #checkedNodes = new WeakSet();
35
88
  #loading = new Set();
36
89
  #errors = new Map();
37
90
  #searchInput = '';
91
+ #excludedRoot = null;
38
92
  #searchText = '';
39
93
  #searchTimer = null;
40
94
  #searchVersion = 0;
@@ -54,6 +108,7 @@ export const Tree = defineComponent({
54
108
  this.control.setAttribute('part', 'tree');
55
109
  const style = this.ownerDocument.createElement('style');
56
110
  style.textContent = `
111
+ :host{position:relative}
57
112
  .control-box{overflow:auto;padding:4px;min-height:32px}
58
113
  ul{list-style:none;margin:0;padding:0} ul ul{padding-inline-start:20px}
59
114
  .row{display:flex;align-items:center;min-height:var(--gramlot-tree-row-height,28px);gap:2px;border-radius:3px;cursor:default}
@@ -69,6 +124,10 @@ export const Tree = defineComponent({
69
124
  .expander svg{display:block;width:14px;height:14px;pointer-events:none}
70
125
  [aria-expanded=true]>.row>.expander svg{transform:rotate(90deg)}
71
126
  .spacer{width:max(20px,var(--gramlot-touch-target,0px));flex:none}.caption{min-width:0;overflow-wrap:anywhere}
127
+ .badge{display:inline-flex;align-items:center;justify-content:center;flex:none;min-width:18px;
128
+ height:16px;padding:0 3px;border-radius:3px;font-size:10px;line-height:1;
129
+ background:var(--gramlot-tree-badge-background,#e7eaf0);color:var(--gramlot-tree-badge-color,#394452)}
130
+ .badge[data-colored]{color:var(--gramlot-tree-colored-badge-color,white)}
72
131
  .icon{width:16px;height:16px;flex:none;background:currentColor;opacity:.7;mask:center/contain no-repeat;
73
132
  mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M5 3h9l5 5v13H5zM14 3v6h5M8 13h8M8 17h8'/%3E%3C/svg%3E")}
74
133
  .branch-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 7V4h7l3 3h8v13H3z'/%3E%3C/svg%3E")}
@@ -78,6 +137,13 @@ export const Tree = defineComponent({
78
137
  .search-status{padding:4px;color:var(--gramlot-text-secondary,#555);font-size:.9em}
79
138
  [hidden]{display:none}`;
80
139
  this.shadowRoot.append(style);
140
+ const actions = this.ownerDocument.createElement('slot');
141
+ actions.name = 'row-actions';
142
+ this.shadowRoot.append(actions);
143
+ this.addEventListener('pointerleave', () => {
144
+ const bar = this.#rowActions();
145
+ if (bar && !bar.contains(this.ownerDocument.activeElement)) bar.clearRowContext();
146
+ });
81
147
  }
82
148
  setSourceContext(context) { this.#context = context; }
83
149
  /** Read only the rendered row and its BagNode; never request a resolver value. */
@@ -103,11 +169,22 @@ export const Tree = defineComponent({
103
169
  this.#expanded.clear();
104
170
  this.#errors.clear();
105
171
  this.#requestedPath = undefined;
172
+ this.#selectionVersion++;
173
+ this.#checkedPaths = undefined;
174
+ this.#checkedBags = new WeakMap();
175
+ this.#checkedNodes = new WeakSet();
106
176
  }
107
177
  this.#schedule();
108
178
  }
109
179
  projectAttributes(attrs, adapt) {
180
+ this.#pathsEnabled = Object.hasOwn(attrs, 'checkedPaths');
181
+ this.#checksEnabled = this.#pathsEnabled || Boolean(attrs.onChecked);
110
182
  const rest = super.projectAttributes(attrs, adapt);
183
+ if (this.#excludedRoot !== this.parameters.excludeRoot) {
184
+ this.#excludedRoot = this.parameters.excludeRoot;
185
+ this.#resetSearch();
186
+ this.#searchText = this.#searchInput.toLowerCase();
187
+ }
111
188
  const text = this.parameters.searchText.trim();
112
189
  if (text !== this.#searchInput) {
113
190
  this.#resetSearch();
@@ -140,7 +217,9 @@ export const Tree = defineComponent({
140
217
  if (ancestors.has(bag)) throw new TypeError('tree requires an acyclic Bag store');
141
218
  const next = new Set(ancestors).add(bag);
142
219
  for (const node of bag.getNodes()) {
220
+ if (bag === this.#store && node.label === this.parameters.excludeRoot) continue;
143
221
  if (!current()) return;
222
+ if (node.attr.loop === true) continue;
144
223
  if (node.resolver !== null && node.resolver.expired && !this.#searchAttempted.has(node)) {
145
224
  this.#searchAttempted.add(node);
146
225
  await this.#resolve(node, true);
@@ -167,6 +246,7 @@ export const Tree = defineComponent({
167
246
  fragment.append(value.slice(cursor)); text.replaceWith(fragment);
168
247
  }
169
248
  }
249
+ retrySelection() { this.#requestedPath = undefined; this.#schedule(); }
170
250
  #schedule() {
171
251
  if (this.#scheduled) return;
172
252
  this.#scheduled = true;
@@ -177,11 +257,20 @@ export const Tree = defineComponent({
177
257
  }
178
258
  #render() {
179
259
  const focused = this.shadowRoot.activeElement?.closest('[role=treeitem]')?.dataset.path;
260
+ const focusedFavorite = this.shadowRoot.activeElement?.dataset.favoritePath;
261
+ const focusedFavoritesGroup = this.shadowRoot.activeElement?.dataset.favoritesGroup === 'true';
262
+ const loaded = [];
263
+ let checksChanged = false;
264
+ if (this.#checksEnabled && this.parameters.checkChildren &&
265
+ !(this.#pathsEnabled && this.parameters.checkedPaths !== this.#checkedPaths)) {
266
+ checksChanged = this.#syncChecked(this.#store, new Set(), loaded);
267
+ }
180
268
  const items = new Map(), seen = new Set();
181
269
  const visit = (bag, prefix, ancestors) => {
182
270
  if (seen.has(bag)) throw new TypeError('tree requires an acyclic Bag store');
183
271
  seen.add(bag);
184
272
  for (const node of bag.getNodes()) {
273
+ if (bag === this.#store && node.label === this.parameters.excludeRoot) continue;
185
274
  const path = prefix ? `${prefix}.${node.label}` : node.label;
186
275
  const value = node.staticValue; // Rendering never evaluates resolvers.
187
276
  items.set(path, {node, ancestors, children: value instanceof Bag ? value : null});
@@ -191,20 +280,63 @@ export const Tree = defineComponent({
191
280
  };
192
281
  visit(this.#store, '', []);
193
282
  if (this.#searchText && this.#searchTimer === null && !this.#searching && [...items.values()].some(({node}) =>
194
- node.resolver !== null && node.resolver.expired && !this.#searchAttempted.has(node))) {
283
+ node.attr.loop !== true && node.resolver !== null && node.resolver.expired && !this.#searchAttempted.has(node))) {
195
284
  void this.#searchBranches();
196
285
  }
286
+ const actionBar = this.#rowActions();
287
+ const actionContext = actionBar ? actionBar.getRowContext() : null;
288
+ if (actionContext) {
289
+ const favorite = actionContext.item.getAttr('favoriteEntry') === true;
290
+ const valid = favorite ? this.parameters.favorites instanceof Bag && this.parameters.favorites.getNodes().includes(actionContext.item)
291
+ : items.get(actionContext.path)?.node === actionContext.item;
292
+ if (!valid) actionBar.clearRowContext();
293
+ }
294
+ if (this.#pathsEnabled && this.parameters.checkedPaths !== this.#checkedPaths) {
295
+ const initial = this.#checkedPaths === undefined;
296
+ this.#checkedPaths = this.parameters.checkedPaths;
297
+ for (const {node} of items.values()) {
298
+ if (!initial || this.#checkedPaths !== null) node.setAttr({checked: false});
299
+ }
300
+ for (const path of (this.#checkedPaths || '').split(this.parameters.checkedPaths_joiner).filter(Boolean)) {
301
+ const item = items.get(path);
302
+ if (item) this.#check(item.node, true, false);
303
+ }
304
+ } else if (this.#pathsEnabled && loaded.length) {
305
+ const paths = (this.parameters.checkedPaths || '').split(this.parameters.checkedPaths_joiner).filter(Boolean);
306
+ for (const path of paths) {
307
+ const item = items.get(path);
308
+ if (!item || item.node.attr.checked === true || item.node.attr.checked === 'disabled:on' ||
309
+ item.node.attr.checked === 'disabled:off') continue;
310
+ let bag = item.node.parentBag;
311
+ while (bag && !loaded.includes(bag)) bag = bag.parentNode?.parentBag;
312
+ if (bag) this.#check(item.node, true, false);
313
+ }
314
+ if (checksChanged || paths.length) this.#publishChecked(true);
315
+ } else if (checksChanged) {
316
+ this.#publishChecked(true);
317
+ }
197
318
  const identities = new Set([...items.values()].map(item => item.node));
198
319
  for (const node of this.#expanded) if (!identities.has(node)) this.#expanded.delete(node);
199
320
  for (const node of this.#errors.keys()) if (!identities.has(node)) this.#errors.delete(node);
200
321
  const requested = this.parameters.selectedPath;
322
+ let reveal = null;
201
323
  if (requested !== this.#requestedPath) {
202
324
  this.#requestedPath = requested;
203
325
  this.#selectedPath = requested;
204
- for (const node of items.get(requested)?.ancestors ?? []) this.#expand(node);
326
+ const version = ++this.#selectionVersion;
327
+ const ancestors = items.get(requested)?.ancestors ?? [];
328
+ if (requested && !items.has(requested)) {
329
+ reveal = {requested, version, store: this.#store};
330
+ }
331
+ for (let index = 0; index < ancestors.length; index++) {
332
+ const node = ancestors[index];
333
+ if (this.#expanded.has(node)) continue;
334
+ this.#expand(node);
335
+ }
205
336
  }
206
337
  const selected = this.#selectedPath;
207
338
  this.#rows.clear();
339
+ this.#favoriteRows.clear();
208
340
  this.#dragRows = new WeakMap();
209
341
  this.#presentations.clear();
210
342
  const branchSync = new Map();
@@ -213,6 +345,7 @@ export const Tree = defineComponent({
213
345
  list.className = 'group'; list.setAttribute('part', 'group');
214
346
  list.setAttribute('role', 'group');
215
347
  for (const node of bag.getNodes()) {
348
+ if (bag === this.#store && node.label === this.parameters.excludeRoot) continue;
216
349
  const path = prefix ? `${prefix}.${node.label}` : node.label;
217
350
  const {children} = items.get(path);
218
351
  const scalar = children === null && !this.parameters.hideValues && (node.resolver === null || !node.resolver.expired);
@@ -230,6 +363,8 @@ export const Tree = defineComponent({
230
363
  entry.dataset.path = path;
231
364
  entry.tabIndex = -1;
232
365
  const row = this.ownerDocument.createElement('div'); row.className = 'row';
366
+ row.addEventListener('pointerenter', () => this.#showRowActions(row, node, path));
367
+ entry.addEventListener('focus', () => this.#showRowActions(row, node, path));
233
368
  row.draggable = this.parameters.draggable;
234
369
  row.setAttribute('part', `row ${branch ? 'branch-row' : 'leaf-row'}${selected === path ? ' selected-row' : ''}`);
235
370
  if (this.#errors.has(node)) row.title = String(this.#errors.get(node));
@@ -247,10 +382,12 @@ export const Tree = defineComponent({
247
382
  chevronPath.setAttribute('stroke-linecap', 'round'); chevronPath.setAttribute('stroke-linejoin', 'round');
248
383
  chevron.append(chevronPath); expander.append(chevron);
249
384
  expander.addEventListener('click', event => {
250
- event.stopPropagation(); toggle(); entry.focus();
385
+ event.stopPropagation(); entry.focus(); toggle();
251
386
  });
252
387
  } else expander.className = 'spacer';
253
388
  const caption = this.ownerDocument.createElement('span'); caption.className = 'caption';
389
+ const badge = this.ownerDocument.createElement('span'); badge.className = 'badge';
390
+ badge.setAttribute('part', 'badge');
254
391
  this.#dragRows.set(row, {item: node, path, caption});
255
392
  caption.setAttribute('part', 'caption');
256
393
  const icon = this.ownerDocument.createElement('span');
@@ -258,7 +395,22 @@ export const Tree = defineComponent({
258
395
  icon.setAttribute('aria-hidden', 'true');
259
396
  icon.setAttribute('part', `icon ${branch ? 'branch-icon' : 'leaf-icon'}`);
260
397
 
261
- row.append(expander, icon, caption); entry.append(row);
398
+ let check;
399
+ if (this.#checksEnabled) {
400
+ check = this.ownerDocument.createElement('input');
401
+ check.type = 'checkbox'; check.className = 'checkbox'; check.setAttribute('part', 'checkbox');
402
+ check.tabIndex = -1;
403
+ check.addEventListener('click', event => {
404
+ event.stopPropagation();
405
+ if (typeof this.parameters.onChecked === 'string') {
406
+ const result = this.#context.callLogic(this.parameters.onChecked, {item: node, path});
407
+ if (result instanceof Promise) throw new TypeError('tree onChecked must be synchronous');
408
+ if (result === false) { this.#schedule(); return; }
409
+ }
410
+ this.#check(node, check.checked, true);
411
+ });
412
+ }
413
+ row.append(expander, check || icon, badge, caption); entry.append(row);
262
414
  const group = branch ? (children ? build(children, path, entry) : this.ownerDocument.createElement('ul')) : null;
263
415
  if (group) { group.className = 'group'; group.setAttribute('role', 'group'); group.setAttribute('part', 'group'); }
264
416
  if (group) entry.append(group);
@@ -290,12 +442,24 @@ export const Tree = defineComponent({
290
442
  }
291
443
  const present = () => {
292
444
  const opened = this.#opened(node), selected = this.#selectedPath === path;
445
+ const value = node.attr.badge;
446
+ if (value != null && typeof value !== 'string' && typeof value !== 'number') {
447
+ throw new TypeError('tree badge must be text or a number');
448
+ }
449
+ const color = node.attr.badge_color;
450
+ if (color != null && typeof color !== 'string') throw new TypeError('tree badge_color must be text');
451
+ badge.textContent = value == null ? '' : String(value);
452
+ badge.hidden = value == null || value === '';
453
+ badge.style.backgroundColor = color ?? '';
454
+ badge.toggleAttribute('data-colored', color != null && color !== '');
293
455
  const keywords = {item: node, path, opened, selected};
294
456
  const attribute = this.parameters.labelAttribute;
295
- const label = this.parameters.getLabel !== null ? this.#call('getLabel', keywords)
457
+ const label = this.parameters.internalNames && node.getAttr('fieldpath') ? node.label
458
+ : this.parameters.getLabel !== null ? this.#call('getLabel', keywords)
296
459
  : attribute !== null ? (Object.hasOwn(node.attr, attribute) ? node.attr[attribute] : node.label)
297
460
  : this.parameters.labelCb !== null ? this.#call('labelCb', keywords) : node.label;
298
- this.#setCaption(caption, label, this.parameters.getLabel !== null || (attribute === null && this.parameters.labelCb !== null));
461
+ this.#setCaption(caption, label, !(this.parameters.internalNames && node.getAttr('fieldpath')) &&
462
+ (this.parameters.getLabel !== null || (attribute === null && this.parameters.labelCb !== null)));
299
463
  if (this.#searchText) this.#highlight(caption);
300
464
  const labelClass = this.parameters.getLabelClass !== null ? this.#call('getLabelClass', keywords)
301
465
  : node.attr[opened ? 'labelClassOpened' : 'labelClassClosed'] || node.attr.labelClass || '';
@@ -307,12 +471,20 @@ export const Tree = defineComponent({
307
471
  ...(selected ? ['selected'] : []), ...(branch ? [opened ? 'opened' : 'closed'] : []),
308
472
  ...(this.#loading.has(node) ? ['loading'] : []), ...(this.#errors.has(node) ? ['error'] : [])].join(' ');
309
473
  entry.setAttribute('part', ['node', branch ? 'branch' : 'leaf', ...nodeClasses].join(' '));
310
- const customIcon = this.parameters.getIconClass !== null;
474
+ const customIcon = !check && this.parameters.getIconClass !== null;
311
475
  const iconClasses = customIcon ? this.#classes(this.#call('getIconClass', keywords))
312
476
  : [branch ? 'branch-icon' : 'leaf-icon', ...(branch ? [opened ? 'opened-icon' : 'closed-icon'] : [])];
313
477
  icon.className = ['icon', ...iconClasses].join(' ');
314
478
  icon.setAttribute('part', ['icon', ...iconClasses].join(' '));
315
479
  icon.hidden = customIcon && iconClasses.length === 0;
480
+ if (check) {
481
+ const value = node.attr.checked;
482
+ check.checked = value === true || value === 'disabled:on';
483
+ check.indeterminate = value === -1;
484
+ entry.setAttribute('aria-checked', value === -1 ? 'mixed' : String(check.checked));
485
+ check.disabled = value === 'disabled:on' || value === 'disabled:off';
486
+ check.setAttribute('aria-label', caption.textContent);
487
+ }
316
488
  if (branch) expander.setAttribute('aria-label', `${opened ? 'Collapse' : 'Expand'} ${caption.textContent}`);
317
489
  };
318
490
  this.#presentations.set(path, present);
@@ -331,8 +503,7 @@ export const Tree = defineComponent({
331
503
  if (expanded.has(node)) {
332
504
  expanded.delete(node);
333
505
  if (this.#searchText) this.#searchClosed.add(node);
334
- }
335
- else {
506
+ } else {
336
507
  if (this.#searchText) { this.#searchClosed.delete(node); this.#searchOpen.add(node); } else this.#expand(node);
337
508
  if (node.resolver !== null) this.#resolve(node);
338
509
  }
@@ -353,7 +524,8 @@ export const Tree = defineComponent({
353
524
  if (!this.#opened(node)) toggle(); else target = group.firstElementChild;
354
525
  } else if (event.key === 'ArrowLeft') {
355
526
  if (branch && this.#opened(node)) toggle(); else target = parent;
356
- } else if (event.key === 'Enter' || event.key === ' ') this.#select(path);
527
+ } else if (event.key === ' ' && check) check.click();
528
+ else if (event.key === 'Enter' || event.key === ' ') this.#select(path);
357
529
  else return;
358
530
  event.preventDefault(); event.stopPropagation();
359
531
  if (target) { this.#tabStop(target); target.focus(); }
@@ -363,13 +535,19 @@ export const Tree = defineComponent({
363
535
  }
364
536
  return list;
365
537
  };
366
- this.control.replaceChildren(build(this.#store, '', null));
538
+ const root = build(this.#store, '', null);
539
+ if (this.parameters.favorites !== null) {
540
+ if (!(this.parameters.favorites instanceof Bag)) throw new TypeError('tree favorites must be a Bag');
541
+ if (this.parameters.favorites.length) root.prepend(this.#buildFavorites(this.parameters.favorites, selected));
542
+ }
543
+ this.control.replaceChildren(root);
367
544
  this.control.setAttribute('aria-busy', String(this.#searching));
368
545
  if (this.#searchText) {
369
546
  const visible = new Set(), matches = [];
370
547
  this.#searchOpen.clear();
371
548
  for (const [path, row] of this.#rows) {
372
549
  const caption = row.firstElementChild.querySelector('.caption'), item = items.get(path);
550
+ if (item.ancestors.some(ancestor => ancestor.attr.loop === true)) continue;
373
551
  const match = caption.textContent.toLowerCase().includes(this.#searchText);
374
552
  if (match) matches.push(caption);
375
553
  if (match || this.#errors.has(item.node) || this.#loading.has(item.node)) {
@@ -384,12 +562,233 @@ export const Tree = defineComponent({
384
562
  this.control.append(status);
385
563
  }
386
564
  this.#tabStop(focused ?? selected);
387
- if (focused) this.#rows.get(focused)?.focus();
565
+ if (focusedFavorite) this.#favoriteRows.get(focusedFavorite)?.focus();
566
+ else if (focusedFavoritesGroup) root.querySelector('[data-favorites-group]')?.focus();
567
+ else if (focused) this.#rows.get(focused)?.focus();
568
+ if (reveal) queueMicrotask(() => this.#loadSelection(reveal));
569
+ }
570
+ #buildFavorites(favorites, selected) {
571
+ const document = this.ownerDocument;
572
+ const group = document.createElement('li');
573
+ group.className = 'node branch'; group.setAttribute('role', 'treeitem');
574
+ group.dataset.favoritesGroup = 'true'; group.tabIndex = -1;
575
+ const row = document.createElement('div'); row.className = 'row';
576
+ const button = document.createElement('button'); button.type = 'button'; button.className = 'expander'; button.tabIndex = -1;
577
+ const heart = document.createElement('span'); heart.textContent = '♡'; heart.setAttribute('aria-hidden', 'true');
578
+ const title = document.createElement('span'); title.className = 'caption'; title.textContent = this.parameters.favoritesLabel;
579
+ const children = document.createElement('ul'); children.className = 'group'; children.setAttribute('role', 'group');
580
+ const sync = () => {
581
+ group.setAttribute('aria-expanded', String(this.#favoritesOpen));
582
+ button.textContent = this.#favoritesOpen ? '▾' : '▸';
583
+ button.setAttribute('aria-label', `${this.#favoritesOpen ? 'Collapse' : 'Expand'} ${this.parameters.favoritesLabel}`);
584
+ children.hidden = !this.#favoritesOpen;
585
+ };
586
+ const toggle = () => { this.#favoritesOpen = !this.#favoritesOpen; sync(); };
587
+ button.addEventListener('click', event => { event.stopPropagation(); toggle(); group.focus(); });
588
+ row.addEventListener('click', toggle);
589
+ group.addEventListener('focus', () => this.#rowActions()?.clearRowContext());
590
+ group.addEventListener('keydown', event => {
591
+ if (event.target !== group) return;
592
+ if (event.key === 'ArrowRight') { if (!this.#favoritesOpen) toggle(); else children.firstElementChild?.focus(); }
593
+ else if (event.key === 'ArrowLeft') { if (this.#favoritesOpen) toggle(); }
594
+ else if (event.key === 'Enter' || event.key === ' ') toggle();
595
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
596
+ const visible = this.#visible(), index = visible.indexOf(group);
597
+ visible[index + (event.key === 'ArrowDown' ? 1 : -1)]?.focus();
598
+ } else return;
599
+ event.preventDefault(); event.stopPropagation();
600
+ });
601
+ row.append(button, heart, title); group.append(row, children);
602
+ for (const node of favorites.getNodes()) {
603
+ const path = node.getAttr('originalPath');
604
+ const entry = document.createElement('li'); entry.className = 'node leaf'; entry.setAttribute('role', 'treeitem');
605
+ entry.dataset.favoritePath = path; entry.tabIndex = -1; entry.setAttribute('aria-selected', String(selected === path));
606
+ const favoriteRow = document.createElement('div'); favoriteRow.className = 'row';
607
+ const spacer = document.createElement('span'); spacer.className = 'spacer';
608
+ const icon = document.createElement('span'); icon.className = 'icon'; icon.setAttribute('aria-hidden', 'true');
609
+ const badge = document.createElement('span'); badge.className = 'badge'; badge.setAttribute('part', 'badge');
610
+ const badgeValue = node.getAttr('badge'); badge.textContent = badgeValue == null ? '' : String(badgeValue);
611
+ badge.hidden = badgeValue == null || badgeValue === '';
612
+ const color = node.getAttr('badge_color'); if (color) { badge.style.backgroundColor = color; badge.setAttribute('data-colored', ''); }
613
+ const caption = document.createElement('span'); caption.className = 'caption';
614
+ caption.textContent = node.getAttr(this.parameters.internalNames ? 'fieldpath' : 'fullcaption');
615
+ favoriteRow.title = node.getAttr('fieldpath');
616
+ favoriteRow.draggable = this.parameters.draggable;
617
+ this.#dragRows.set(favoriteRow, {item: node, path, caption});
618
+ favoriteRow.addEventListener('pointerenter', () => this.#showRowActions(favoriteRow, node, path));
619
+ entry.addEventListener('focus', () => this.#showRowActions(favoriteRow, node, path));
620
+ favoriteRow.addEventListener('click', () => this.#selectFavorite(path));
621
+ entry.addEventListener('keydown', event => {
622
+ if (event.target !== entry) return;
623
+ if (event.key === 'Enter' || event.key === ' ') this.#selectFavorite(path);
624
+ else if (event.key === 'ArrowLeft') group.focus();
625
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
626
+ const visible = this.#visible(), index = visible.indexOf(entry);
627
+ visible[index + (event.key === 'ArrowDown' ? 1 : -1)]?.focus();
628
+ } else return;
629
+ event.preventDefault(); event.stopPropagation();
630
+ });
631
+ favoriteRow.append(spacer, icon, badge, caption); entry.append(favoriteRow); children.append(entry);
632
+ this.#favoriteRows.set(path, entry);
633
+ }
634
+ sync();
635
+ return group;
636
+ }
637
+ #selectFavorite(path) {
638
+ if (this.parameters.selectedPath === path) this.retrySelection();
639
+ else this.#context.writeParameter('selectedPath', path);
640
+ }
641
+ async #loadSelection({requested, version, store}) {
642
+ const current = () => this.isConnected && this.#selectionVersion === version &&
643
+ this.#store === store && this.parameters.selectedPath === requested && this.#selectedPath === requested;
644
+ const parts = requested.split('.');
645
+ let bag = store;
646
+ for (const part of parts.slice(0, -1)) {
647
+ if (!current()) return;
648
+ const node = bag.getNode(part);
649
+ if (!node) return;
650
+ if (node.resolver === null && !(node.staticValue instanceof Bag)) return;
651
+ if (!current() || bag.getNode(part) !== node) return;
652
+ this.#expand(node);
653
+ this.#schedule();
654
+ if (node.resolver !== null && !(node.staticValue instanceof Bag)) await this.#resolve(node);
655
+ if (!current() || bag.getNode(part) !== node || !(node.staticValue instanceof Bag)) return;
656
+ bag = node.staticValue;
657
+ }
658
+ if (current() && bag.getNode(parts.at(-1))) this.#schedule();
659
+ }
660
+ #check(node, value, publish) {
661
+ if (node.attr.checked === 'disabled:on' || node.attr.checked === 'disabled:off') return;
662
+ const children = this.#resolutions.get(node) ?? node.getValue();
663
+ if (children instanceof Promise && !this.#resolutions.has(node)) {
664
+ this.#errors.delete(node);
665
+ const pending = children.catch(error => {
666
+ this.#errors.set(node, error);
667
+ this.#expanded.delete(node);
668
+ }).finally(() => {
669
+ if (this.#resolutions.get(node) === pending) this.#resolutions.delete(node);
670
+ this.#schedule();
671
+ });
672
+ this.#resolutions.set(node, pending);
673
+ }
674
+ if (this.parameters.checkChildren && children instanceof Bag) {
675
+ if (node.resolver !== null) this.#checkedBags.set(node, children);
676
+ this.#applyChecked(children, value);
677
+ }
678
+ node.setAttr({checked: this.parameters.checkChildren && children instanceof Bag && children.length
679
+ ? this.#checkStatus(children) : value});
680
+ if (this.parameters.checkChildren) {
681
+ for (let parent = node.parentBag.parentNode; parent && parent !== this.#store.parentNode; parent = parent.parentBag.parentNode) {
682
+ parent.setAttr({checked: this.#checkStatus(parent.staticValue)});
683
+ }
684
+ }
685
+ if (publish) this.#publishChecked();
686
+ }
687
+ #applyChecked(bag, value, onlyNew = false) {
688
+ for (const child of bag.getNodes()) {
689
+ if (onlyNew && this.#checkedNodes.has(child)) continue;
690
+ this.#checkedNodes.add(child);
691
+ if (child.attr.checked === 'disabled:on' || child.attr.checked === 'disabled:off') continue;
692
+ const children = child.staticValue;
693
+ if (children instanceof Bag && children.length) {
694
+ if (child.resolver !== null) this.#checkedBags.set(child, children);
695
+ this.#applyChecked(children, value);
696
+ child.setAttr({checked: this.#checkStatus(children)});
697
+ } else child.setAttr({checked: value});
698
+ }
699
+ }
700
+ #syncChecked(bag, ancestors = new Set(), loaded = []) {
701
+ if (ancestors.has(bag)) throw new TypeError('tree requires an acyclic Bag store');
702
+ ancestors.add(bag);
703
+ let changed = false;
704
+ for (const node of bag.getNodes()) {
705
+ this.#checkedNodes.add(node);
706
+ const children = node.staticValue;
707
+ if (!(children instanceof Bag)) continue;
708
+ let childChanged = false;
709
+ if (node.resolver !== null && this.#checkedBags.get(node) !== children) {
710
+ this.#checkedBags.set(node, children);
711
+ loaded.push(children);
712
+ if (typeof node.attr.checked === 'boolean') {
713
+ this.#applyChecked(children, node.attr.checked);
714
+ childChanged = true;
715
+ }
716
+ } else if (typeof node.attr.checked === 'boolean' && children.getNodes().some(child => !this.#checkedNodes.has(child))) {
717
+ this.#applyChecked(children, node.attr.checked, true);
718
+ loaded.push(children);
719
+ childChanged = true;
720
+ }
721
+ childChanged = this.#syncChecked(children, ancestors, loaded) || childChanged;
722
+ if (childChanged && children.length && node.attr.checked !== 'disabled:on' && node.attr.checked !== 'disabled:off') {
723
+ node.setAttr({checked: this.#checkStatus(children)});
724
+ }
725
+ changed ||= childChanged;
726
+ }
727
+ ancestors.delete(bag);
728
+ return changed;
729
+ }
730
+ #publishChecked(preservePending = false) {
731
+ const paths = [];
732
+ const visit = (bag, prefix) => {
733
+ for (const child of bag.getNodes()) {
734
+ const path = prefix ? `${prefix}.${child.label}` : child.label;
735
+ const children = child.staticValue;
736
+ if (children instanceof Bag && children.length) {
737
+ if (!this.parameters.checkChildren && child.attr.checked === true) paths.push(path);
738
+ visit(children, path);
739
+ } else if (child.attr.checked === true) paths.push(path);
740
+ }
741
+ };
742
+ visit(this.#store, '');
743
+ if (preservePending && this.#pathsEnabled) {
744
+ for (const path of (this.parameters.checkedPaths || '').split(this.parameters.checkedPaths_joiner).filter(Boolean)) {
745
+ if (!paths.includes(path) && this.#pendingCheckedPath(path)) paths.push(path);
746
+ }
747
+ }
748
+ this.#checkedPaths = paths.join(this.parameters.checkedPaths_joiner);
749
+ this.#context.writeParameter('checkedPaths', this.#checkedPaths);
750
+ this.#schedule();
751
+ }
752
+ #pendingCheckedPath(path) {
753
+ const parts = path.split('.');
754
+ let bag = this.#store;
755
+ for (let index = 0; index < parts.length; index++) {
756
+ const node = bag.getNode(parts[index]);
757
+ if (!node) return false;
758
+ if (index === parts.length - 1) return false;
759
+ if (node.resolver !== null && !(node.staticValue instanceof Bag)) return true;
760
+ if (!(node.staticValue instanceof Bag)) return false;
761
+ bag = node.staticValue;
762
+ }
763
+ return false;
764
+ }
765
+ #checkStatus(bag) {
766
+ const values = bag.getNodes().map(child => child.attr.checked === 'disabled:on' ? true
767
+ : child.attr.checked === 'disabled:off' || child.attr.checked == null ? false : child.attr.checked);
768
+ return values.every(value => value === true) ? true
769
+ : values.every(value => value === false) ? false : -1;
388
770
  }
389
771
  #classes(value) {
390
772
  if (typeof value !== 'string') throw new TypeError('Tree classes must be a string');
391
773
  return value.split(/\s+/).filter(Boolean);
392
774
  }
775
+ #rowActions() {
776
+ const bars = this.querySelectorAll(':scope > gramlot-row-actions');
777
+ if (bars.length > 1) throw new Error('tree accepts one rowActions bar');
778
+ return bars[0] ?? null;
779
+ }
780
+ #showRowActions(row, item, path) {
781
+ const bar = this.#rowActions();
782
+ if (!bar || bar.contains(this.ownerDocument.activeElement)) return;
783
+ const hostBox = this.getBoundingClientRect(), rowBox = row.getBoundingClientRect();
784
+ bar.setRowContext(item, path);
785
+ bar.style.position = 'absolute';
786
+ bar.style.top = `${rowBox.top - hostBox.top}px`;
787
+ bar.style.left = bar.parameters.position === 'start' ? `${rowBox.left - hostBox.left}px` : 'auto';
788
+ bar.style.right = bar.parameters.position === 'end' ? `${hostBox.right - rowBox.right}px` : 'auto';
789
+ bar.style.zIndex = '1';
790
+ bar.hidden = false;
791
+ }
393
792
  #call(name, keywords) {
394
793
  const result = this.#context.callLogic(this.parameters[name], keywords);
395
794
  if (name === 'labelCb' || name === 'getLabel') {
@@ -451,4 +850,4 @@ export const Tree = defineComponent({
451
850
  }
452
851
  }
453
852
  });
454
- export default defineCollection({name: 'tree', components: [Tree]});
853
+ export default defineCollection({name: 'tree', components: [Tree, RowActions]});