@gramlot/gramlot 0.3.26 → 0.3.30

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 (213) hide show
  1. package/assets/icons/chart.svg +1 -0
  2. package/dist/components/audio/__init__.py +13 -0
  3. package/dist/components/audio/assets/collection.js +3 -0
  4. package/dist/components/audio/assets/index.js +3 -0
  5. package/dist/components/audio/commands.json +7 -0
  6. package/dist/components/audio/grammar.json +335 -0
  7. package/dist/components/charts/__init__.py +13 -0
  8. package/dist/components/charts/assets/collection.js +47 -0
  9. package/dist/components/charts/assets/files/55ea01207028f76d844678511f29fc800f8a1e67a8a0fe80470128677847ad32-echarts-gl.txt +29 -0
  10. package/dist/components/charts/assets/files/63727832aaf62004a2b249c933e327f3c90caf49e41a72f4bf436edf632cbda8-vega.txt +27 -0
  11. package/dist/components/charts/assets/files/8c45d9eaf50c2f72dd9c7ab9ef440788ba58a3538484b5c51c1f17d5128752e7-plotly.txt +21 -0
  12. package/dist/components/charts/assets/files/8f989229699b4fe2f1a0432d0e9edc338a8a911e250e2d1b01ecd770a5f5b1bd-uplot.txt +21 -0
  13. package/dist/components/charts/assets/files/c8fa058cba98f7f288b5d8fa4116f441d6dacb25b96da859e518c973fff41d0c-claygl.txt +23 -0
  14. package/dist/components/charts/assets/index.js +3 -0
  15. package/dist/components/charts/assets/modules/chunk-2CCTLZE7.js +76 -0
  16. package/dist/components/charts/assets/modules/chunk-RMRBEYTI.js +1 -0
  17. package/dist/components/charts/assets/modules/echarts-gl-CXVTZA6G.js +4409 -0
  18. package/dist/components/charts/assets/modules/plotly.min-4LB7HE7P.js +3596 -0
  19. package/dist/components/charts/assets/modules/uPlot.esm-5JJNHHRF.js +3 -0
  20. package/dist/components/charts/assets/modules/uPlot.min-N3E3FA74.js +1 -0
  21. package/dist/components/charts/assets/modules/vega.module-2QCOVQ3A.js +13 -0
  22. package/dist/components/charts/commands.json +7 -0
  23. package/dist/components/charts/grammar.json +1113 -0
  24. package/dist/components/chat/__init__.py +1 -1
  25. package/dist/components/chat/assets/collection.js +3 -3
  26. package/dist/components/chat/assets/index.js +1 -1
  27. package/dist/components/drawing/__init__.py +15 -0
  28. package/dist/components/drawing/assets/collection.js +28 -0
  29. package/dist/components/drawing/assets/index.js +3 -0
  30. package/dist/components/drawing/commands.json +7 -0
  31. package/dist/components/drawing/grammar.json +110 -0
  32. package/dist/components/editors/__init__.py +2 -2
  33. package/dist/components/editors/assets/collection.js +18 -18
  34. package/dist/components/editors/assets/index.js +1 -1
  35. package/dist/components/editors/assets/modules/{prose-mirror-engine-GMZPJPNN.js → prose-mirror-engine-DQEAEIMV.js} +2 -2
  36. package/dist/components/editors/grammar.json +150 -0
  37. package/dist/components/grid/__init__.py +1 -1
  38. package/dist/components/grid/assets/collection.js +63 -33
  39. package/dist/components/grid/assets/index.js +1 -1
  40. package/dist/components/grid/grammar.json +279 -0
  41. package/dist/components/grouplets/__init__.py +1 -1
  42. package/dist/components/grouplets/assets/collection.js +3 -3
  43. package/dist/components/grouplets/assets/index.js +1 -1
  44. package/dist/components/inputs/__init__.py +3 -2
  45. package/dist/components/inputs/assets/collection.js +38 -23
  46. package/dist/components/inputs/assets/index.js +1 -1
  47. package/dist/components/inputs/grammar.json +1533 -321
  48. package/dist/components/layout/__init__.py +1 -1
  49. package/dist/components/layout/assets/collection.js +27 -23
  50. package/dist/components/layout/assets/index.js +1 -1
  51. package/dist/components/layout/grammar.json +85 -0
  52. package/dist/components/selection_trial/__init__.py +1 -1
  53. package/dist/components/selection_trial/assets/collection.js +3 -3
  54. package/dist/components/selection_trial/assets/index.js +1 -1
  55. package/dist/components/tree/__init__.py +1 -1
  56. package/dist/components/tree/assets/collection.js +12 -12
  57. package/dist/components/tree/assets/index.js +1 -1
  58. package/dist/components/tree/grammar.json +126 -0
  59. package/dist/components/typst/__init__.py +1 -1
  60. package/dist/components/typst/assets/collection.js +3 -3
  61. package/dist/components/typst/assets/index.js +1 -1
  62. package/dist/components/uploads/__init__.py +1 -1
  63. package/dist/components/uploads/assets/collection.js +9 -9
  64. package/dist/components/uploads/assets/index.js +1 -1
  65. package/dist/components/vizabi/__init__.py +13 -0
  66. package/dist/components/vizabi/assets/collection.js +22 -0
  67. package/dist/components/vizabi/assets/index.js +3 -0
  68. package/dist/components/vizabi/commands.json +7 -0
  69. package/dist/components/vizabi/grammar.json +128 -0
  70. package/dist/gramlot.js +1190 -256
  71. package/dist/gramlot.min.js +85 -52
  72. package/dist/standard-collections.js +2 -0
  73. package/package.json +12 -4
  74. package/src/binding/grid-struct.js +2 -2
  75. package/src/binding/runtime.js +10 -0
  76. package/src/binding/validation-context.js +2 -1
  77. package/src/bootstrap.js +1 -1
  78. package/src/builder/gramlot-builder.d.ts +15 -2
  79. package/src/builder/gramlot-builder.js +22 -3
  80. package/src/builder/source.js +24 -1
  81. package/src/components/audio-analysis-session.js +65 -0
  82. package/src/components/audio.js +44 -0
  83. package/src/components/bases.js +11 -7
  84. package/src/components/border-container.js +6 -3
  85. package/src/components/buttons.js +47 -3
  86. package/src/components/chart-bar3d-options.js +30 -0
  87. package/src/components/chart-controls.js +83 -0
  88. package/src/components/chart-data-view.js +52 -0
  89. package/src/components/chart-data.js +42 -0
  90. package/src/components/chart-domains.js +46 -0
  91. package/src/components/chart-engines/echarts-options.js +50 -0
  92. package/src/components/chart-engines/echarts.js +82 -0
  93. package/src/components/chart-engines/index.js +22 -0
  94. package/src/components/chart-engines/plotly-map.js +34 -0
  95. package/src/components/chart-engines/plotly-spatial.js +35 -0
  96. package/src/components/chart-engines/plotly.js +138 -0
  97. package/src/components/chart-engines/uplot.js +57 -0
  98. package/src/components/chart-engines/vega.js +101 -0
  99. package/src/components/chart-fields.js +110 -0
  100. package/src/components/chart-geographic-options.js +47 -0
  101. package/src/components/chart-geojson.js +60 -0
  102. package/src/components/chart-geometry.js +11 -0
  103. package/src/components/chart-map-anchors.js +24 -0
  104. package/src/components/chart-map-bar3d-options.js +41 -0
  105. package/src/components/chart-map-data.js +25 -0
  106. package/src/components/chart-map-labels.js +8 -0
  107. package/src/components/chart-map-options.js +20 -0
  108. package/src/components/chart-pane.js +91 -0
  109. package/src/components/chart-renderer.js +58 -0
  110. package/src/components/chart-sample-view.js +32 -0
  111. package/src/components/chart-spatial-options.js +40 -0
  112. package/src/components/chart-time.js +84 -0
  113. package/src/components/chart-timeline.js +70 -0
  114. package/src/components/chart-types/area.js +2 -0
  115. package/src/components/chart-types/bar.js +2 -0
  116. package/src/components/chart-types/bar3D.js +2 -0
  117. package/src/components/chart-types/donut.js +2 -0
  118. package/src/components/chart-types/horizontalBar.js +2 -0
  119. package/src/components/chart-types/index.js +26 -0
  120. package/src/components/chart-types/line.js +2 -0
  121. package/src/components/chart-types/line3D.js +2 -0
  122. package/src/components/chart-types/lines3D.js +2 -0
  123. package/src/components/chart-types/map.js +2 -0
  124. package/src/components/chart-types/map3D.js +2 -0
  125. package/src/components/chart-types/mapBar3D.js +2 -0
  126. package/src/components/chart-types/pie.js +2 -0
  127. package/src/components/chart-types/polygons3D.js +2 -0
  128. package/src/components/chart-types/scatter.js +2 -0
  129. package/src/components/chart-types/scatter3D.js +2 -0
  130. package/src/components/chart-types/stackedArea.js +2 -0
  131. package/src/components/chart-types/stackedBar.js +2 -0
  132. package/src/components/chart-types/surface.js +2 -0
  133. package/src/components/charts.js +152 -0
  134. package/src/components/check-box-text-editor.js +88 -0
  135. package/src/components/check-box-text.js +193 -0
  136. package/src/components/check-box-tree.js +62 -0
  137. package/src/components/choice-editor.js +35 -18
  138. package/src/components/choice-field-styles.js +14 -0
  139. package/src/components/choices.js +5 -0
  140. package/src/components/database-choices.js +9 -6
  141. package/src/components/drawing.js +199 -0
  142. package/src/components/field-state.js +8 -1
  143. package/src/components/grid-cell-editor.js +83 -19
  144. package/src/components/grid-check-sets.js +98 -0
  145. package/src/components/grid-column-filters.js +198 -0
  146. package/src/components/grid-grammar.json +65 -0
  147. package/src/components/grid-header-interaction.js +3 -1
  148. package/src/components/grid-rows.js +2 -2
  149. package/src/components/grid-search-box.js +38 -22
  150. package/src/components/grid-search-styles.js +13 -14
  151. package/src/components/grid-search.js +8 -1
  152. package/src/components/grid-structure.js +13 -2
  153. package/src/components/grid-styles.js +34 -2
  154. package/src/components/grid.js +67 -10
  155. package/src/components/image-uploader.js +2 -2
  156. package/src/components/inputs.js +21 -12
  157. package/src/components/labelbox.js +5 -1
  158. package/src/components/licenses/claygl.txt +23 -0
  159. package/src/components/licenses/echarts-gl.txt +29 -0
  160. package/src/components/licenses/plotly.txt +21 -0
  161. package/src/components/licenses/uplot.txt +21 -0
  162. package/src/components/licenses/vega.txt +27 -0
  163. package/src/components/menus.js +19 -11
  164. package/src/components/parameters.js +6 -2
  165. package/src/components/toolbar-overflow.js +12 -8
  166. package/src/components/tree.js +31 -8
  167. package/src/components/typed-editor.js +18 -7
  168. package/src/components/validation.js +1 -1
  169. package/src/components/vizabi-session.js +66 -0
  170. package/src/components/vizabi.js +66 -0
  171. package/src/components/window-surface.js +20 -9
  172. package/src/components/windows.js +1 -1
  173. package/src/editing-session.d.ts +1 -0
  174. package/src/editing-session.js +113 -15
  175. package/src/editor-values.js +57 -0
  176. package/src/gramlot.d.ts +2 -0
  177. package/src/gramlot.js +9 -4
  178. package/src/handlers/device-handler.js +32 -32
  179. package/src/handlers/source-handler.d.ts +2 -2
  180. package/src/ide-documents.js +19 -3
  181. package/src/ide-runtime.d.ts +1 -0
  182. package/src/ide-runtime.js +45 -31
  183. package/src/index.d.ts +2 -1
  184. package/src/renderer/drag-drop.js +1 -0
  185. package/src/renderer/gramlot-renderer.d.ts +3 -0
  186. package/src/renderer/gramlot-renderer.js +16 -4
  187. package/src/server/assets.d.ts +3 -0
  188. package/src/server/assets.js +9 -0
  189. package/src/server/gramlot-server.d.ts +1 -1
  190. package/src/server/gramlot-server.js +2 -1
  191. package/src/server/index.d.ts +1 -1
  192. package/src/server/index.js +1 -1
  193. package/src/server/source-import.d.ts +1 -1
  194. package/src/server/source-import.js +5 -1
  195. package/src/server/visual-editor.d.ts +1 -1
  196. package/src/server/visual-editor.js +44 -34
  197. package/src/source-picker.d.ts +1 -1
  198. package/src/source-picker.js +1 -2
  199. package/src/stores/bag-collection-view.js +79 -17
  200. package/src/stores/collection-filter.js +2 -1
  201. package/src/stores/column-filter.js +49 -0
  202. package/src/stores/id-set.js +10 -0
  203. package/src/view/controls.js +8 -0
  204. package/src/view/html.js +10 -1
  205. package/src/view/label-menu.js +61 -0
  206. package/src/view/labelbox.js +15 -2
  207. package/src/visual-editor-canvas.js +29 -0
  208. package/src/visual-editor-catalogue.js +34 -0
  209. package/src/visual-editor.d.ts +5 -0
  210. package/src/visual-editor.js +244 -26
  211. package/themes/gramlot-base/theme.css +84 -36
  212. package/tools/gramlot-tools-inspector.js +170 -506
  213. package/tools/inspector-agent.js +1 -1
@@ -0,0 +1,88 @@
1
+ /** Text projection for checkBoxText. Codes remain the field value; drafts belong to Source. */
2
+ export class CheckBoxTextEditor {
3
+ constructor(owner) {
4
+ this.owner = owner;
5
+ const doc = owner.ownerDocument;
6
+ this.input = doc.createElement('input');
7
+ this.input.type = 'text'; this.input.className = 'summary';
8
+ this.input.placeholder = 'Select options'; this.input.autocomplete = 'off';
9
+ this.input.setAttribute('aria-label', 'Selected descriptions');
10
+ this.list = doc.createElement('datalist'); this.list.id = 'description-options';
11
+ this.input.setAttribute('list', this.list.id);
12
+ this.toggle = doc.createElement('button'); this.toggle.type = 'button';
13
+ this.toggle.className = 'choice-toggle'; this.toggle.setAttribute('aria-label', 'Show options');
14
+ this.element = doc.createElement('div'); this.element.className = 'summary-row choice-field';
15
+ this.element.append(this.input, this.toggle, this.list);
16
+ this.toggle.addEventListener('click', () => owner.openChoices());
17
+ this.input.addEventListener('input', event => {
18
+ if (this.locked) return;
19
+ owner.cancelValidation();
20
+ this.state.draft = {text:this.input.value, value:owner.readControlValue()};
21
+ owner.pageContext?.formSelectionError('Confirm the edited selection.');
22
+ if (!event.isComposing) { owner.closeChoices(); this.suggest(); }
23
+ });
24
+ this.input.addEventListener('compositionend', () => this.suggest());
25
+ this.input.addEventListener('change', () => this.commit());
26
+ this.input.addEventListener('keydown', event => {
27
+ if (event.isComposing || this.locked) return;
28
+ if (event.key === 'Enter') { event.preventDefault(); this.commit(); }
29
+ if (event.key === 'Escape') { event.preventDefault(); owner.cancelValidation(); this.clear(); owner.closeChoices(); owner.updateSummary(); }
30
+ });
31
+ owner.control.addEventListener('change', event => {
32
+ if (event.target !== owner.control) this.clear();
33
+ });
34
+ }
35
+ get state() { return this.source.checkBoxTextState; }
36
+ get locked() { return this.input.disabled || this.input.readOnly || !this.owner.pageContext?.isActive(); }
37
+ attach(source) { this.source = source; source.checkBoxTextState ??= {draft:null}; }
38
+ clear() {
39
+ if (this.source) this.state.draft = null;
40
+ this.owner.pageContext?.formSelectionError('');
41
+ this.input.setCustomValidity(''); this.input.setAttribute('aria-invalid','false');
42
+ this.owner.error('');
43
+ }
44
+ project(value, caption) {
45
+ if (this.source && this.state.draft && !Object.is(this.state.draft.value, value)) this.clear();
46
+ const text = this.source && this.state.draft ? this.state.draft.text : caption ?? '';
47
+ if (this.input.value !== text) this.input.value = text;
48
+ this.toggle.disabled = this.input.disabled;
49
+ this.element.hidden = this.input.hidden;
50
+ this.suggest();
51
+ }
52
+ suggest() {
53
+ const text = this.input.value, end = text.lastIndexOf(',') + 1;
54
+ const prefix = text.slice(0,end), query = text.slice(end).trim().toLocaleLowerCase();
55
+ const options = this.owner.textOptions();
56
+ const used = new Set(prefix.split(',').map(s => s.trim().toLocaleLowerCase()));
57
+ this.list.replaceChildren(...options.filter(row => !row.disabled && !used.has(row.caption.toLocaleLowerCase()) &&
58
+ row.caption.toLocaleLowerCase().includes(query)).map(row => {
59
+ const option = this.owner.ownerDocument.createElement('option');
60
+ option.value = prefix + row.caption; option.label = row.id; return option;
61
+ }));
62
+ }
63
+ candidate() {
64
+ if (!this.source || !this.state.draft) return {value:this.owner.readControlValue()};
65
+ const text = this.state.draft.text.trim();
66
+ if (!text) return {value:null};
67
+ const rows = this.owner.textOptions(), codes = [];
68
+ const old = (this.state.draft.value || '').split(',');
69
+ for (const token of text.split(',').map(s => s.trim())) {
70
+ const matches = rows.filter(row => !row.disabled && row.caption.toLocaleLowerCase() === token.toLocaleLowerCase());
71
+ if (matches.length !== 1) {
72
+ // A missing code already present in Data may remain until options load.
73
+ if (token && old.includes(token) && !rows.some(row => row.id === token)) { codes.push(token); continue; }
74
+ return {error:matches.length > 1 ? 'Ambiguous description: choose its checkbox.' : 'Choose a description from the options.'};
75
+ }
76
+ if (!codes.includes(matches[0].id)) codes.push(matches[0].id);
77
+ }
78
+ return {value:codes.join(',') || null};
79
+ }
80
+ commit() {
81
+ if (this.locked || !this.state.draft) return;
82
+ this.owner.control.dispatchEvent(new this.owner.ownerDocument.defaultView.Event('change', {bubbles:true}));
83
+ }
84
+ reject(message) {
85
+ this.input.setCustomValidity(message); this.input.setAttribute('aria-invalid','true');
86
+ this.owner.error(message); this.owner.pageContext?.formSelectionError(message);
87
+ }
88
+ }
@@ -0,0 +1,193 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+ import {parseChoices} from './choices.js';
3
+ import {positionPopup} from './popup.js';
4
+ import {CheckBoxTree} from './check-box-tree.js';
5
+ import {CheckBoxTextEditor} from './check-box-text-editor.js';
6
+ import {choiceFieldStyles} from './choice-field-styles.js';
7
+ import {randomId} from '../random-id.js';
8
+
9
+ /** Multiple choices keep the existing group's commit and validation lifecycle. */
10
+ export function checkBoxChoices(Base) {
11
+ return class extends Base {
12
+ #store;
13
+ #text;
14
+ #sourceContext;
15
+ #tree;
16
+ #refreshScheduled = false;
17
+ #subscription = `checkbox-options-${randomId()}`;
18
+ #attrs;
19
+ #request;
20
+ #configuration;
21
+ #rows = [];
22
+ #available = true;
23
+ #opened = false;
24
+ #cleanup;
25
+ constructor() {
26
+ super();
27
+ const doc = this.ownerDocument;
28
+ this.#text = new CheckBoxTextEditor(this);
29
+ this.summary = this.#text.input; this.summary.hidden = true;
30
+ this.summary.className = 'summary';
31
+ this.summary.setAttribute('aria-haspopup', 'dialog');
32
+ this.summary.setAttribute('aria-expanded', 'false');
33
+ this.panel = doc.createElement('div'); this.panel.id = 'checkbox-options';
34
+ this.panel.setAttribute('popover', 'manual'); this.panel.setAttribute('role', 'dialog');
35
+ this.panel.setAttribute('aria-label', 'Options'); this.panel.hidden = true;
36
+ this.summary.setAttribute('aria-controls', this.panel.id);
37
+ this.optionsMessage = doc.createElement('div'); this.optionsMessage.setAttribute('role', 'status');
38
+ const style = doc.createElement('style');
39
+ style.textContent = choiceFieldStyles + `.summary{min-width:0;box-sizing:border-box;font:inherit;text-align:start;width:100%;padding:var(--gramlot-field-padding,.25em .5em);min-height:var(--gramlot-field-height,28px);border:1px solid var(--gramlot-border-control,#7a8798);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText)}
40
+ .summary:disabled{opacity:.6}.summary[aria-invalid=true]{border-color:var(--gramlot-error,#8c1d18)}
41
+ [popover]{position:fixed;inset:auto;margin:0;padding:8px;max-width:var(--gramlot-popup-available-width,100vw);max-height:min(20rem,var(--gramlot-popup-available-height,100vh));overflow:auto;border:1px solid var(--gramlot-border-control,#7a8798);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);font:inherit}
42
+ [hidden]{display:none!important}`;
43
+ this.controlBox.prepend(style, this.#text.element);
44
+ this.controlBox.append(this.panel, this.optionsMessage);
45
+ this.summary.addEventListener('click', () => this.#opened ? this.closeChoices() : this.openChoices());
46
+ this.summary.addEventListener('keydown', event => {
47
+ if (event.altKey && ['ArrowDown','ArrowUp'].includes(event.key)) { event.preventDefault(); this.openChoices(); }
48
+ });
49
+ this.panel.addEventListener('keydown', event => {
50
+ if (event.key === 'Escape') {event.preventDefault(); event.stopPropagation(); this.closeChoices(); this.summary.focus();}
51
+ });
52
+ }
53
+ setSourceContext(context) { this.#sourceContext = context; this.#text.attach(context.sourceNode); }
54
+ get choiceType() { return 'checkbox'; }
55
+ get multiple() { return true; }
56
+ choiceOptions() {
57
+ const {values, identifier, labelAttribute, dbtable, method, hierarchical} = this.parameters;
58
+ if (hierarchical) return [];
59
+ if (dbtable || method) return this.#rows;
60
+ if (typeof values === 'string') return parseChoices(values);
61
+ if (!(values instanceof Bag)) throw new TypeError('values must be text or a Bag');
62
+ const ids = new Set();
63
+ return values.getNodes().map(node => {
64
+ const read = key => node.staticValue instanceof Bag ? node.staticValue.getItem(key) : node.getAttr(key);
65
+ const id = identifier ? read(identifier) : node.label;
66
+ const caption = labelAttribute ? read(labelAttribute) : node.label;
67
+ if (typeof id !== 'string' || !id || id.includes(',') || ids.has(id) || typeof caption !== 'string') throw new TypeError('Options require unique comma-free text codes and text captions');
68
+ ids.add(id); return {id, caption};
69
+ });
70
+ }
71
+ projectAttributes(attrs, adapt) {
72
+ const current = this.readControlValue();
73
+ this.#attrs = attrs;
74
+ const rest = super.projectAttributes(attrs, adapt);
75
+ const {values, popup, disabled, readonly, dbtable, method, hierarchical} = this.parameters;
76
+ if (hierarchical && (dbtable || method)) throw new TypeError('Load hierarchical values into a Bag with dataRemote, not the flat selector service');
77
+ if (hierarchical && !this.#tree) this.#tree = new CheckBoxTree(this, this.#sourceContext);
78
+ if (!hierarchical && this.#tree) { this.#tree.dispose(); this.#tree = null; }
79
+ if ((dbtable || method) && values !== '') throw new TypeError('Remote choices and values are mutually exclusive');
80
+ const store = values instanceof Bag ? values : null;
81
+ if (store !== this.#store) {
82
+ this.#store?.unsubscribe(this.#subscription, {any:true}); this.#store = store;
83
+ store?.subscribe(this.#subscription, {any:() => {
84
+ if (!this.parameters.hierarchical) {
85
+ this.projectAttributes(this.#attrs); this.writeControlValue(this.readControlValue());
86
+ } else if (!this.#refreshScheduled) {
87
+ this.#refreshScheduled = true;
88
+ queueMicrotask(() => {
89
+ this.#refreshScheduled = false;
90
+ if (this.isConnected && this.pageContext?.isActive()) this.projectAttributes(this.#attrs);
91
+ });
92
+ }
93
+ }});
94
+ }
95
+ this.summary.hidden = !popup; this.summary.disabled = Boolean(disabled || readonly || !this.#available);
96
+ for (const input of this.control.querySelectorAll("input")) input.disabled = this.summary.disabled;
97
+ if (!popup || this.summary.disabled) this.closeChoices();
98
+ const target = popup ? this.panel : this.controlBox;
99
+ if (this.control.parentNode !== target) target.append(this.control);
100
+ this.writeControlValue(current);
101
+ const config = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
102
+ ['dbtable','method','caption_field','order_by','condition'].includes(key) || key.startsWith('condition_')));
103
+ const signature = JSON.stringify(config);
104
+ if (signature !== this.#configuration) { this.#configuration = signature; this.loadOptions(config); }
105
+ for (const key of Object.keys(rest)) if (key.startsWith('condition_')) delete rest[key];
106
+ return rest;
107
+ }
108
+ setPageContext(context) { super.setPageContext(context); this.#configuration = undefined; this.projectAttributes(this.#attrs); }
109
+ async loadOptions(config) {
110
+ this.#request?.abort(); this.#request = null;
111
+ if (!(config.dbtable || config.method)) {
112
+ this.#available = true; this.optionsMessage.textContent = '';
113
+ this.summary.disabled = Boolean(this.parameters.disabled || this.parameters.readonly);
114
+ for (const input of this.control.querySelectorAll('input')) input.disabled = this.summary.disabled;
115
+ return;
116
+ }
117
+ if (!this.pageContext) return;
118
+ const controller = new AbortController(); this.#request = controller;
119
+ this.closeChoices(); this.#available = false; this.summary.disabled = true;
120
+ for (const input of this.control.querySelectorAll('input')) input.disabled = true;
121
+ this.optionsMessage.textContent = 'Loading options…'; this.summary.setAttribute('aria-busy','true');
122
+ const {method, ...parameters} = config;
123
+ try {
124
+ for (const key of Object.keys(parameters)) if (key.startsWith('condition_')) {
125
+ const name = key.slice(10);
126
+ if (!name || name.startsWith('_') || ['limit','dbtable','condition','caption_field','order_by'].includes(name)) throw new TypeError('Invalid condition parameter');
127
+ parameters[name] = parameters[key]; delete parameters[key];
128
+ }
129
+ const result = await this.pageContext.remote(method || 'dbSelect', {...parameters, _querystring:'', limit:null}, controller.signal);
130
+ if (controller.signal.aborted || !this.pageContext.isActive()) return;
131
+ if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') throw new TypeError('Options require {rows, identifier, caption}');
132
+ const ids = new Set();
133
+ this.#rows = result.rows.map(row => {
134
+ const key = row[result.identifier], caption = row[result.caption];
135
+ if (!(typeof key === 'string' || Number.isSafeInteger(key)) || key === '' || String(key).includes(',') || typeof caption !== 'string' || ids.has(String(key))) throw new TypeError('Invalid or duplicate option');
136
+ const id = String(key); ids.add(id); return {id, caption};
137
+ });
138
+ this.#available = true;
139
+ const value = this.readControlValue(); this.projectAttributes(this.#attrs); this.writeControlValue(value);
140
+ this.optionsMessage.textContent = '';
141
+ } catch(error) {
142
+ if (!controller.signal.aborted && this.pageContext.isActive()) this.optionsMessage.textContent = error.message;
143
+ } finally { if (this.#request === controller) this.summary.setAttribute('aria-busy','false'); }
144
+ }
145
+ acceptTreeValue(value) {
146
+ this.#text.clear();
147
+ super.writeControlValue(value);
148
+ this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change', {bubbles:true}));
149
+ }
150
+ restoreFormValue(value) { this.#text.clear(); super.restoreFormValue(value); }
151
+ textOptions() { return this.#tree ? this.#tree.options() : this.choiceOptions(); }
152
+ acceptControlValue() {
153
+ const candidate = this.#text.candidate();
154
+ if (candidate.error) { this.#text.reject(candidate.error); return {ok:false}; }
155
+ this.pageContext?.formSelectionError('');
156
+ return this.validateCandidate(candidate.value, accepted => {
157
+ this.#text.clear(); this.writeControlValue(accepted);
158
+ });
159
+ }
160
+ writeControlValue(value) {
161
+ super.writeControlValue(value); this.#tree?.project(value); this.updateSummary(value);
162
+ }
163
+ updateSummary(value = this.readControlValue()) {
164
+ const labels = new Map(this.textOptions().map(row => [row.id,row.caption]));
165
+ const caption = value ? value.split(',').map(code => labels.get(code) ?? code).join(',') : null;
166
+ this.#text.project(value, caption);
167
+ this.pageContext?.selectionDisplay(caption, value);
168
+ }
169
+ openChoices() {
170
+ if (this.#opened || !this.parameters.popup || this.summary.disabled || !this.pageContext?.isActive()) return;
171
+ this.panel.hidden = false; this.panel.showPopover(); this.#opened = true;
172
+ this.summary.setAttribute('aria-expanded','true'); positionPopup(this.panel,this.summary,{matchWidth:true});
173
+ const doc = this.ownerDocument, view = doc.defaultView;
174
+ const outside = event => {if (!event.composedPath().includes(this)) this.closeChoices();};
175
+ const position = () => positionPopup(this.panel,this.summary,{matchWidth:true});
176
+ doc.addEventListener('pointerdown',outside); doc.addEventListener('focusin',outside);
177
+ view.addEventListener('resize',position); view.addEventListener('scroll',position,true);
178
+ this.#cleanup = () => {doc.removeEventListener('pointerdown',outside);doc.removeEventListener('focusin',outside);view.removeEventListener('resize',position);view.removeEventListener('scroll',position,true);};
179
+ this.summary.focus();
180
+ }
181
+ closeChoices() {
182
+ if (!this.#opened) return;
183
+ this.#cleanup(); this.#cleanup = null; this.panel.hidePopover(); this.panel.hidden = true;
184
+ this.#opened = false; this.summary.setAttribute('aria-expanded','false');
185
+ }
186
+ focus(options) { if (this.parameters.popup) this.summary.focus(options); else if (this.#tree) this.#tree.focus(); else super.focus(options); }
187
+ releaseControl() {
188
+ this.closeChoices(); this.#request?.abort(); this.#store?.unsubscribe(this.#subscription,{any:true}); this.#store = null;
189
+ this.#tree?.dispose(); this.#tree = null;
190
+ super.releaseControl();
191
+ }
192
+ };
193
+ }
@@ -0,0 +1,62 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+
3
+ /** Identity/caption projection only. The shared tree owns checks and lazy propagation. */
4
+ export class CheckBoxTree {
5
+ // Derived index from the last projection: newly loaded codes are still pending
6
+ // until that projection has supplied their paths to the shared tree.
7
+ #knownCodes = new Set();
8
+ constructor(owner, context) {
9
+ this.owner = owner;
10
+ this.element = owner.ownerDocument.createElement('gramlot-tree');
11
+ this.element.setSourceContext({...context, writeParameter:(name, paths) => {
12
+ if (name !== 'checkedPaths' || !owner.pageContext?.isActive()) return;
13
+ const rows = this.options(), byPath = new Map(rows.map(row => [row.path,row.id]));
14
+ const known = this.#knownCodes;
15
+ const selected = (paths || '').split(',').filter(Boolean).map(path => owner.parameters.identifier ? byPath.get(path) : path).filter(code => code !== undefined);
16
+ const old = (owner.readControlValue() || '').split(',').filter(Boolean);
17
+ const codes = old.filter(code => !known.has(code) || selected.includes(code));
18
+ for (const code of selected) if (!codes.includes(code)) codes.push(code);
19
+ const value = codes.join(',') || null;
20
+ if (value !== owner.readControlValue()) owner.acceptTreeValue(value);
21
+ }});
22
+ owner.control.append(this.element);
23
+ }
24
+ options() {
25
+ const {values, identifier, labelAttribute} = this.owner.parameters;
26
+ if (!(values instanceof Bag)) throw new TypeError('hierarchical checkBoxText requires a Bag in values');
27
+ const rows = [], ids = new Set(), ancestors = new Set();
28
+ const visit = (bag, prefix) => {
29
+ if (ancestors.has(bag)) throw new TypeError('Hierarchical options require an acyclic Bag');
30
+ ancestors.add(bag);
31
+ for (const node of bag.getNodes()) {
32
+ const path = prefix ? `${prefix}.${node.label}` : node.label;
33
+ const id = identifier ? node.getAttr(identifier) : path;
34
+ if (typeof id !== 'string' || !id || id.includes(',') || ids.has(id)) {
35
+ throw new TypeError('Hierarchical option identifiers must be unique comma-free text on every loaded node');
36
+ }
37
+ const caption = labelAttribute ? node.getAttr(labelAttribute) ?? node.label : node.label;
38
+ if (typeof caption !== 'string') throw new TypeError('Hierarchical captions must be text');
39
+ ids.add(id); rows.push({id, path, caption, disabled:node.attr.checked === 'disabled:on' || node.attr.checked === 'disabled:off'});
40
+ // Reading the index must never execute a resolver.
41
+ if (node.staticValue instanceof Bag) visit(node.staticValue, path);
42
+ }
43
+ ancestors.delete(bag);
44
+ };
45
+ visit(values, '');
46
+ return rows;
47
+ }
48
+ project(value) {
49
+ const p = this.owner.parameters;
50
+ const byCode = new Map(this.options().map(row => [row.id,row.path]));
51
+ this.#knownCodes = new Set(byCode.keys());
52
+ const paths = value === null ? null : (value || '').split(',').filter(Boolean)
53
+ .map(code => p.identifier ? byCode.get(code) : code).filter(Boolean).join(',');
54
+ this.element.inert = Boolean(p.disabled || p.readonly);
55
+ this.element.setAttribute('aria-disabled', String(this.element.inert));
56
+ this.element.setStoreBag(p.values);
57
+ this.element.projectAttributes({checkedPaths:paths, checkChildren:p.checkChildren,
58
+ labelAttribute:p.labelAttribute ?? null, hideValues:true});
59
+ }
60
+ focus() { this.element.shadowRoot.querySelector('[role=treeitem]')?.focus(); }
61
+ dispose() { this.element.remove(); }
62
+ }
@@ -1,5 +1,6 @@
1
1
  import {NativeControl} from './bases.js';
2
2
  import {parseChoices} from './choices.js';
3
+ import {choiceFieldStyles} from './choice-field-styles.js';
3
4
  import {positionPopup} from './popup.js';
4
5
  import {Bag} from '@gramlot/gramlot';
5
6
 
@@ -23,9 +24,9 @@ export function ChoiceEditor(HTMLElement) {
23
24
  super();
24
25
  const doc = this.ownerDocument;
25
26
  const style = doc.createElement('style');
26
- style.textContent = `.option{position:relative} #control{width:100%;padding-right:calc(var(--gramlot-choice-toggle-width,1.6em) + .2em)}
27
+ style.textContent = choiceFieldStyles + `.option{position:relative} #control{width:100%;padding-right:calc(var(--gramlot-choice-toggle-width,1.6em) + .2em)}
27
28
  #control:focus-visible{outline:1px solid var(--gramlot-border-control,#7a8798);outline-offset:-3px}
28
- .toggle{position:absolute;right:0;top:0;bottom:0;width:var(--gramlot-choice-toggle-width,1.6em);min-width:0;min-height:0;font:inherit;font-size:var(--gramlot-field-font-size,1em);padding:0;border:0;background:transparent;color:inherit}
29
+
29
30
  .choices{min-width:min(var(--gramlot-choice-popup-min-width,0px),var(--gramlot-popup-available-width,100vw));max-width:var(--gramlot-popup-available-width,100vw);position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);box-sizing:border-box;max-height:min(var(--gramlot-choice-max-height,20rem),var(--gramlot-popup-available-height,100vh));overflow:auto;
30
31
  border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);font:inherit;font-size:var(--gramlot-field-font-size,1em);line-height:1.4;box-shadow:var(--gramlot-shadow,0 3px 9px #0002)}
31
32
  .choices[hidden]{display:none} .choice{min-height:var(--gramlot-touch-target,0px);display:flex;align-items:center;padding:var(--gramlot-choice-item-padding,.25em .5em);border-radius:var(--gramlot-radius-sm,4px);cursor:pointer}
@@ -34,8 +35,9 @@ export function ChoiceEditor(HTMLElement) {
34
35
  .choice-detail{margin-inline-start:var(--gramlot-space-3,.75rem);color:var(--gramlot-text-secondary,GrayText)}
35
36
  .choice[aria-selected=true]{background:var(--gramlot-selected,Highlight);color:var(--gramlot-ink,HighlightText)}`;
36
37
  this.toggle = doc.createElement('button');
37
- this.toggle.className = 'toggle'; this.toggle.type = 'button'; this.toggle.tabIndex = -1;
38
- this.toggle.textContent = '▾'; this.toggle.setAttribute('aria-label', 'Show options');
38
+ this.toggle.className = 'toggle choice-toggle'; this.toggle.type = 'button'; this.toggle.tabIndex = -1;
39
+ this.control.parentElement.classList.add('choice-field');
40
+ this.toggle.setAttribute('aria-label', 'Show options');
39
41
  this.control.parentElement.append(this.toggle);
40
42
  this.choices = doc.createElement('div');
41
43
  this.choices.id = 'choices'; this.choices.className = 'choices'; this.choices.hidden = true;
@@ -44,7 +46,7 @@ export function ChoiceEditor(HTMLElement) {
44
46
  this.toggle.addEventListener('mousedown', event => event.preventDefault());
45
47
  this.toggle.addEventListener('click', () => {
46
48
  if (this.locked) return;
47
- this.control.focus();
49
+ this.control.focus({preventScroll: true});
48
50
  if (this.#opened) this.closeChoices(); else this.search('');
49
51
  });
50
52
  this.choices.addEventListener('mousedown', event => event.preventDefault());
@@ -82,7 +84,8 @@ export function ChoiceEditor(HTMLElement) {
82
84
  input.setAttribute('aria-controls', 'choices'); input.setAttribute('aria-expanded', 'false');
83
85
  input.autocomplete = 'off'; return input;
84
86
  }
85
- get constrained() { return true; }
87
+ static get constrained() { return true; }
88
+ get constrained() { return this.constructor.constrained; }
86
89
  get revalidateDraftOnSourceChange() { return false; }
87
90
  get autoHighlight() { return true; }
88
91
  get matchTypedChoice() { return true; }
@@ -129,21 +132,27 @@ export function ChoiceEditor(HTMLElement) {
129
132
  this.#value = value; this.#dirty = false; this.#picked = null;
130
133
  this.closeChoices({cancelLookup:true}); this.resolveValue();
131
134
  }
132
- validationValueCheck() {
135
+ static validationValueCheck() {
133
136
  const constrained = this.constrained;
134
137
  return (value, original) => {
135
138
  if (constrained && value !== original) throw new Error('Validation cannot replace a selected code; update the Data explicitly.');
136
139
  };
137
140
  }
141
+ static validationSelection(parameters,context) {
142
+ if (!this.constrained) return super.validationSelection(parameters,context);
143
+ return async (value,signal) => {
144
+ if (value == null) return true;
145
+ const rows = await this.loadChoices(parameters,context,{_id:value},signal);
146
+ return selectionResult(rows.find(row => row.id === value),value);
147
+ };
148
+ }
138
149
  validationSelection() {
139
150
  if (!this.constrained) return super.validationSelection();
140
151
  const rows = this.#rows.map(({id,error}) => ({id,error}));
141
152
  const picked = this.#picked ? {id:this.#picked.id,error:this.#picked.error} : null;
142
153
  return value => {
143
154
  const row = picked?.id === value ? picked : rows.find(row => row.id === value);
144
- if (row?.error) return {errorcode:'condition',message:row.error};
145
- if (value == null || row) return true;
146
- return {errorcode:'missing',message:'Choose a value from the list.'};
155
+ return selectionResult(row,value);
147
156
  };
148
157
  }
149
158
  acceptControlValue() {
@@ -290,19 +299,20 @@ ChoiceEditor.parameters = {...NativeControl.parameters,
290
299
 
291
300
  export function localChoices(Base) {
292
301
  return class extends Base {
293
- loadChoices(keywords) {
302
+ loadChoices(keywords) { return this.constructor.loadChoices(this.parameters,this.pageContext,keywords); }
303
+ static loadChoices(parameters,context,keywords) {
294
304
  let rows;
295
- if (this.parameters.store != null) {
296
- if (!(this.parameters.store instanceof Bag)) throw new TypeError('store must be a Bag');
297
- if (this.parameters.values) throw new TypeError('store and values are mutually exclusive');
305
+ if (parameters.store != null) {
306
+ if (!(parameters.store instanceof Bag)) throw new TypeError('store must be a Bag');
307
+ if (parameters.values) throw new TypeError('store and values are mutually exclusive');
298
308
  const ids = new Set();
299
- rows = this.parameters.store.getNodes().map(node => {
309
+ rows = parameters.store.getNodes().map(node => {
300
310
  const id = node.staticValue, caption = node.attr.caption;
301
311
  if (typeof id !== 'string' || !id || typeof caption !== 'string' || ids.has(id)) throw new TypeError('Invalid or duplicate store choice');
302
312
  ids.add(id);
303
313
  return {id, caption};
304
314
  });
305
- } else rows = parseChoices(this.parameters.values ?? '', this.parameters.separator);
315
+ } else rows = parseChoices(parameters.values ?? '', parameters.separator);
306
316
  return rows.filter(row => Object.hasOwn(keywords, '_id') ? row.id === keywords._id
307
317
  : row.caption.toLocaleLowerCase().includes(keywords._querystring.toLocaleLowerCase()));
308
318
  }
@@ -310,8 +320,9 @@ export function localChoices(Base) {
310
320
  }
311
321
  export function callbackChoices(Base) {
312
322
  return class extends Base {
313
- async loadChoices(keywords) {
314
- const result = await this.pageContext.callLogic(this.parameters.callback, keywords);
323
+ loadChoices(keywords) { return this.constructor.loadChoices(this.parameters,this.pageContext,keywords); }
324
+ static async loadChoices(parameters,context,keywords) {
325
+ const result = await context.callLogic(parameters.callback, keywords);
315
326
  if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') {
316
327
  throw new TypeError('callbackSelect requires {rows, identifier, caption}');
317
328
  }
@@ -324,3 +335,9 @@ export function callbackChoices(Base) {
324
335
  }
325
336
  };
326
337
  }
338
+
339
+ function selectionResult(row,value) {
340
+ if (row?.error) return {errorcode:'condition',message:row.error};
341
+ if (value == null || row) return true;
342
+ return {errorcode:'missing',message:'Choose a value from the list.'};
343
+ }
@@ -0,0 +1,14 @@
1
+ /** Shared field affordance: one field border, an inset transparent chevron. */
2
+ export const choiceFieldStyles = `
3
+ .choice-field{position:relative;min-width:0}
4
+ .choice-field>input{box-sizing:border-box;width:100%;padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .4em)}
5
+ .choice-field>.choice-toggle{position:absolute;inset-inline-end:1px;inset-block:1px;
6
+ width:var(--gramlot-choice-toggle-width,1.6em);min-width:0;min-height:0;
7
+ display:grid;place-items:center;padding:0;border:0;border-radius:0;
8
+ background:transparent;box-shadow:none;color:inherit;font:inherit;cursor:pointer}
9
+ .choice-toggle::after{content:'';width:.4em;height:.4em;border-inline-end:1.5px solid currentColor;
10
+ border-block-end:1.5px solid currentColor;transform:translateY(-.1em) rotate(45deg);pointer-events:none}
11
+ .choice-toggle:disabled{opacity:.5;cursor:default}
12
+ .choice-toggle:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-3px}
13
+ .choice-field>input::-webkit-calendar-picker-indicator{opacity:0}
14
+ `;
@@ -12,3 +12,8 @@ export function parseChoices(values, separator = ',') {
12
12
  return {id, caption};
13
13
  });
14
14
  }
15
+
16
+ /** Resolve the visible caption without changing the selected code. */
17
+ export function choiceCaption(choices, value, placeholder = '') {
18
+ return choices.find(choice => choice.id === value)?.caption ?? placeholder ?? '';
19
+ }
@@ -94,10 +94,7 @@ export function databaseChoices(Base) {
94
94
  for (const key of Object.keys(rest)) if (key.startsWith('condition_') || key.startsWith('selected_')) delete rest[key];
95
95
  return rest;
96
96
  }
97
- async loadChoices(keywords, signal) {
98
- const parameters = Object.fromEntries(requestParameters.filter(key => key !== 'method' && this.parameters[key] != null)
99
- .map(key => [key, this.parameters[key]]));
100
- if (parameters.weakCondition === false) delete parameters.weakCondition;
97
+ loadChoices(keywords, signal) {
101
98
  const required = new Set(Object.entries(this.#outputs).filter(([, path]) => path).map(([name]) => name.slice(9)));
102
99
  if (this.#template) {
103
100
  const walker = this.ownerDocument.createTreeWalker(this.#template, 4);
@@ -105,17 +102,23 @@ export function databaseChoices(Base) {
105
102
  for (const match of walker.currentNode.data.matchAll(/\{([A-Za-z0-9_]+)\}/g)) required.add(match[1]);
106
103
  }
107
104
  }
105
+ return this.constructor.loadChoices({...this.parameters,...this.#configuration},this.pageContext,keywords,signal,required);
106
+ }
107
+ static async loadChoices(configuration,context,keywords,signal,required = new Set()) {
108
+ const parameters = Object.fromEntries(requestParameters.filter(key => key !== 'method' && configuration[key] != null)
109
+ .map(key => [key, configuration[key]]));
110
+ if (parameters.weakCondition === false) delete parameters.weakCondition;
108
111
  if (required.size) parameters.hiddenColumns = [...new Set([
109
112
  ...(parameters.hiddenColumns ?? '').split(',').map(name => name.trim()).filter(Boolean), ...required
110
113
  ])].join(',');
111
- for (const [key, value] of Object.entries(this.#configuration)) {
114
+ for (const [key, value] of Object.entries(configuration)) {
112
115
  if (key.startsWith('condition_')) {
113
116
  const name = key.slice(10);
114
117
  if (!name || name.startsWith('_') || requestParameters.includes(name)) throw new TypeError('Invalid condition parameter.');
115
118
  parameters[name] = value;
116
119
  }
117
120
  }
118
- const result = await this.pageContext.remote(this.parameters.method, {...parameters, ...keywords}, signal);
121
+ const result = await context.remote(configuration.method, {...parameters, ...keywords}, signal);
119
122
  if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') {
120
123
  throw new TypeError('Database selectors require {rows, identifier, caption}.');
121
124
  }