@gramlot/gramlot 0.3.27 → 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 (194) 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 +51 -30
  39. package/dist/components/grid/assets/index.js +1 -1
  40. package/dist/components/grid/grammar.json +258 -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 +11 -11
  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 +2 -2
  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 +8 -8
  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 +572 -176
  71. package/dist/gramlot.min.js +85 -53
  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/bootstrap.js +1 -1
  77. package/src/builder/gramlot-builder.d.ts +15 -2
  78. package/src/builder/gramlot-builder.js +22 -3
  79. package/src/builder/source.js +24 -1
  80. package/src/components/audio-analysis-session.js +65 -0
  81. package/src/components/audio.js +44 -0
  82. package/src/components/bases.js +6 -4
  83. package/src/components/border-container.js +6 -3
  84. package/src/components/buttons.js +47 -3
  85. package/src/components/chart-bar3d-options.js +30 -0
  86. package/src/components/chart-controls.js +83 -0
  87. package/src/components/chart-data-view.js +52 -0
  88. package/src/components/chart-data.js +42 -0
  89. package/src/components/chart-domains.js +46 -0
  90. package/src/components/chart-engines/echarts-options.js +50 -0
  91. package/src/components/chart-engines/echarts.js +82 -0
  92. package/src/components/chart-engines/index.js +22 -0
  93. package/src/components/chart-engines/plotly-map.js +34 -0
  94. package/src/components/chart-engines/plotly-spatial.js +35 -0
  95. package/src/components/chart-engines/plotly.js +138 -0
  96. package/src/components/chart-engines/uplot.js +57 -0
  97. package/src/components/chart-engines/vega.js +101 -0
  98. package/src/components/chart-fields.js +110 -0
  99. package/src/components/chart-geographic-options.js +47 -0
  100. package/src/components/chart-geojson.js +60 -0
  101. package/src/components/chart-geometry.js +11 -0
  102. package/src/components/chart-map-anchors.js +24 -0
  103. package/src/components/chart-map-bar3d-options.js +41 -0
  104. package/src/components/chart-map-data.js +25 -0
  105. package/src/components/chart-map-labels.js +8 -0
  106. package/src/components/chart-map-options.js +20 -0
  107. package/src/components/chart-pane.js +91 -0
  108. package/src/components/chart-renderer.js +58 -0
  109. package/src/components/chart-sample-view.js +32 -0
  110. package/src/components/chart-spatial-options.js +40 -0
  111. package/src/components/chart-time.js +84 -0
  112. package/src/components/chart-timeline.js +70 -0
  113. package/src/components/chart-types/area.js +2 -0
  114. package/src/components/chart-types/bar.js +2 -0
  115. package/src/components/chart-types/bar3D.js +2 -0
  116. package/src/components/chart-types/donut.js +2 -0
  117. package/src/components/chart-types/horizontalBar.js +2 -0
  118. package/src/components/chart-types/index.js +26 -0
  119. package/src/components/chart-types/line.js +2 -0
  120. package/src/components/chart-types/line3D.js +2 -0
  121. package/src/components/chart-types/lines3D.js +2 -0
  122. package/src/components/chart-types/map.js +2 -0
  123. package/src/components/chart-types/map3D.js +2 -0
  124. package/src/components/chart-types/mapBar3D.js +2 -0
  125. package/src/components/chart-types/pie.js +2 -0
  126. package/src/components/chart-types/polygons3D.js +2 -0
  127. package/src/components/chart-types/scatter.js +2 -0
  128. package/src/components/chart-types/scatter3D.js +2 -0
  129. package/src/components/chart-types/stackedArea.js +2 -0
  130. package/src/components/chart-types/stackedBar.js +2 -0
  131. package/src/components/chart-types/surface.js +2 -0
  132. package/src/components/charts.js +152 -0
  133. package/src/components/check-box-text-editor.js +88 -0
  134. package/src/components/check-box-text.js +193 -0
  135. package/src/components/check-box-tree.js +62 -0
  136. package/src/components/choice-editor.js +7 -5
  137. package/src/components/choice-field-styles.js +14 -0
  138. package/src/components/choices.js +5 -0
  139. package/src/components/drawing.js +199 -0
  140. package/src/components/grid-check-sets.js +98 -0
  141. package/src/components/grid-column-filters.js +198 -0
  142. package/src/components/grid-grammar.json +44 -0
  143. package/src/components/grid-header-interaction.js +3 -1
  144. package/src/components/grid-rows.js +2 -2
  145. package/src/components/grid-search-box.js +38 -22
  146. package/src/components/grid-search-styles.js +13 -14
  147. package/src/components/grid-search.js +8 -1
  148. package/src/components/grid-structure.js +10 -2
  149. package/src/components/grid-styles.js +23 -0
  150. package/src/components/grid.js +52 -10
  151. package/src/components/image-uploader.js +2 -2
  152. package/src/components/inputs.js +19 -10
  153. package/src/components/labelbox.js +5 -1
  154. package/src/components/licenses/claygl.txt +23 -0
  155. package/src/components/licenses/echarts-gl.txt +29 -0
  156. package/src/components/licenses/plotly.txt +21 -0
  157. package/src/components/licenses/uplot.txt +21 -0
  158. package/src/components/licenses/vega.txt +27 -0
  159. package/src/components/menus.js +19 -11
  160. package/src/components/toolbar-overflow.js +12 -8
  161. package/src/components/tree.js +30 -8
  162. package/src/components/typed-editor.js +14 -3
  163. package/src/components/vizabi-session.js +66 -0
  164. package/src/components/vizabi.js +66 -0
  165. package/src/components/window-surface.js +20 -9
  166. package/src/components/windows.js +1 -1
  167. package/src/gramlot.d.ts +1 -0
  168. package/src/gramlot.js +2 -0
  169. package/src/handlers/device-handler.js +32 -32
  170. package/src/handlers/source-handler.d.ts +2 -2
  171. package/src/ide-documents.js +19 -3
  172. package/src/ide-runtime.d.ts +1 -0
  173. package/src/ide-runtime.js +45 -31
  174. package/src/index.d.ts +1 -0
  175. package/src/renderer/drag-drop.js +1 -0
  176. package/src/renderer/gramlot-renderer.d.ts +2 -0
  177. package/src/renderer/gramlot-renderer.js +5 -4
  178. package/src/server/assets.d.ts +3 -0
  179. package/src/server/assets.js +9 -0
  180. package/src/server/gramlot-server.d.ts +1 -1
  181. package/src/server/gramlot-server.js +2 -1
  182. package/src/server/index.d.ts +1 -1
  183. package/src/server/index.js +1 -1
  184. package/src/server/visual-editor.js +17 -17
  185. package/src/stores/bag-collection-view.js +79 -17
  186. package/src/stores/collection-filter.js +2 -1
  187. package/src/stores/column-filter.js +49 -0
  188. package/src/stores/id-set.js +10 -0
  189. package/src/view/controls.js +8 -0
  190. package/src/view/html.js +10 -1
  191. package/src/view/label-menu.js +61 -0
  192. package/src/view/labelbox.js +15 -2
  193. package/themes/gramlot-base/theme.css +6 -0
  194. package/tools/gramlot-tools-inspector.js +169 -505
@@ -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());
@@ -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
+ }
@@ -0,0 +1,199 @@
1
+ import {Bag, sourceTarget} from '@gramlot/gramlot';
2
+ import inputs from './inputs.js';
3
+ import layout from './layout.js';
4
+ import {defineCollection, defineComponent} from './registry.js';
5
+ import {Container} from './container.js';
6
+ import {randomId} from '../random-id.js';
7
+
8
+ import {SVG_NS} from '../renderer/attributes.js';
9
+
10
+ /** An editable image annotation layer whose durable state is a Data Bag. */
11
+ export const DrawingPane = defineComponent({
12
+ name:'drawingPane', tag:'gramlot-drawing-pane', base:Container, sourceContext:true, subTags:'*',
13
+ parameters:{image:{dtype:'T',nullable:true,default:null,binding:'read'},
14
+ annotations:{dtype:'X',binding:'read'}},
15
+ implementation:Base => class extends Base {
16
+ #svg; #image; #editor; #editing; #state; #statePath; #stateSubscription = `drawing-state-${randomId()}`; #syncing = false; #built = false; #lastColor; #lastSize; #bag; #subscription = `drawing-${randomId()}`;
17
+ #tool='select'; #selected=null; #gesture=null; #dimensions=[1000,1000]; #url=null; #events;
18
+ constructor() {
19
+ super();
20
+ const d=this.ownerDocument;
21
+ const style=d.createElement('style');
22
+ style.textContent=`:host{display:block;height:100%;min-height:0}.control-box{height:100%;display:flex;flex-direction:row;min-height:0;position:relative}
23
+ slot{display:contents} ::slotted(gramlot-menu){flex:0 0 56px;box-sizing:border-box;padding:6px;background:var(--gramlot-surface,Canvas);border-right:1px solid var(--gramlot-border-control,#a8b2bf);overflow:hidden}
24
+ .canvas{display:block;flex:1;width:0;height:100%;min-width:0;min-height:0;background:var(--gramlot-surface-subtle,#eee);touch-action:none;user-select:none}
25
+ .text-editor{position:absolute;z-index:2;min-width:120px;padding:2px 4px;border:1px solid #3977bc;border-radius:3px;background:white;color:#222;box-shadow:0 2px 8px #0003}
26
+ .text-editor[hidden]{display:none}.shape{cursor:pointer}.selected{stroke:#1683ff}.selected [data-text-hit]{stroke:#3977bc;stroke-width:1;stroke-dasharray:4 3}`;
27
+ this.shadowRoot.append(style);this.control.replaceChildren();
28
+ this.#editor=d.createElement('input');this.#editor.type='text';this.#editor.className='text-editor';this.#editor.hidden=true;this.#editor.setAttribute('aria-label','Annotation text');
29
+ this.#svg=d.createElementNS(SVG_NS,'svg');this.#svg.setAttribute('role','img');this.#svg.setAttribute('aria-label','Annotated image');
30
+ this.#svg.setAttribute('class','canvas');
31
+ this.#svg.setAttribute('viewBox','0 0 1000 1000');this.#svg.setAttribute('preserveAspectRatio','xMidYMid meet');
32
+ this.controlBox.append(d.createElement('slot'),this.#svg,this.#editor);
33
+ this.#image=d.createElement('img');
34
+ }
35
+ setSourceContext(context) { this.context=context; }
36
+ projectAttributes(attrs,adapt) {
37
+ const rest=super.projectAttributes(attrs,adapt);
38
+ if(this.isConnected)this.#connect();
39
+ return rest;
40
+ }
41
+ connectedCallback() {
42
+ this.#events=new this.ownerDocument.defaultView.AbortController();const options={signal:this.#events.signal};
43
+ this.#makeToolbar();
44
+ if(!this.isConnected)return;
45
+ this.#state.subscribe(this.#stateSubscription,{any:()=>this.#stateChanged()});
46
+ this.#svg.addEventListener('pointerdown',e=>this.#down(e),options);
47
+ this.#svg.addEventListener('pointermove',e=>this.#move(e),options);
48
+ this.#svg.addEventListener('pointerup',e=>this.#up(e),options);
49
+ this.#svg.addEventListener('pointercancel',()=>{this.#gesture=null;this.#render();},options);
50
+ this.#svg.addEventListener('dblclick',e=>{const id=e.target.closest('[data-id]')?.dataset.id;if(id&&this.#bag.getItem(id)?.getItem('type')==='text'){this.#gesture=null;this.#editText(id);e.preventDefault();}},options);
51
+ this.#editor.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();this.#finishText(true);}else if(e.key==='Escape'){e.preventDefault();this.#finishText(false);}},options);
52
+ this.#editor.addEventListener('blur',()=>this.#finishText(true),options);
53
+ this.#connect();
54
+ }
55
+ disconnectedCallback() {this.#finishText(false);this.#events?.abort();this.#events=null;this.#state?.unsubscribe(this.#stateSubscription,{any:true});this.#bag?.unsubscribe(this.#subscription,{any:true});this.#bag=null;this.#image.onload=null;this.#image.onerror=null;this.#url=null;this.#gesture=null;}
56
+ #connect() {
57
+ const bag=this.parameters.annotations;
58
+ if(!(bag instanceof Bag))throw new TypeError('drawingPane annotations requires a Data Bag');
59
+ if(bag!==this.#bag){this.#bag?.unsubscribe(this.#subscription,{any:true});this.#bag=bag;bag.subscribe(this.#subscription,{any:()=>this.#render()});this.#selected=null;}
60
+ const url=this.parameters.image;
61
+ if(url!==this.#url){
62
+ this.#url=url;this.#gesture=null;
63
+ if(!url){this.#dimensions=[1000,1000];this.#render();}
64
+ else {
65
+ this.#dimensions=null;this.#render();
66
+ this.#image.onload=()=>{if(this.#url!==url)return;this.#dimensions=[this.#image.naturalWidth,this.#image.naturalHeight];this.#render();};
67
+ this.#image.onerror=()=>{if(this.#url===url){this.#dimensions=null;this.context.reportError(new Error('Cannot load image'),'Drawing image');this.#render();}};
68
+ this.#image.src=url;
69
+ }
70
+ }
71
+ this.#render();
72
+ }
73
+ #makeToolbar(){
74
+ if(this.#built)return;
75
+ const node=this.context.sourceNode,builder=node.rootBuilder;
76
+ const existing=node.value?.getNode('bar');
77
+ if(existing){this.#state=node.drawingState;this.#statePath=node.drawingStatePath;existing.drawingController=this;this.#built=true;this.#tool=this.#state.getItem('tool');this.#lastColor=this.#state.getItem('color');this.#lastSize=this.#state.getItem('size');return;}
78
+ this.#statePath=`_gramlot.drawing.${randomId()}`;
79
+ this.#state=new Bag({tool:'select',color:'#dd2222',size:3});
80
+ node.setRelativeData(this.#statePath,this.#state);
81
+ Object.defineProperty(node,'drawingState',{value:this.#state,configurable:true});
82
+ Object.defineProperty(node,'drawingStatePath',{value:this.#statePath,configurable:true});
83
+ this.#lastColor=this.#state.getItem('color');this.#lastSize=this.#state.getItem('size');
84
+ const fragment=new builder.source.constructor(null,builder),root=builder.wrapSource(fragment);
85
+ const bar=root.menu({node_label:'bar',presentation:'bar',orientation:'vertical',labelPosition:'tooltip',iconSize:20,aria_label:'Image annotations'});
86
+ Object.defineProperty(sourceTarget(bar),'drawingController',{value:this,configurable:true,writable:true});
87
+ const paths={select:'M5 3l13 11-6 .5-3 5z',freehand:'M4 20l3.5-.7L19 7.8 16.2 5 4.7 16.5z M14.7 6.5l2.8 2.8',arrow:'M4 19L19 4 M12 4h7v7',circle:'M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0z',text:'M4 5h16 M12 5v14 M8 19h8',delete:'M4 7h16 M9 7V4h6v3 M7 7l1 13h8l1-13 M10 10v7 M14 10v7'};
88
+ const icon=key=>'data:image/svg+xml,'+encodeURIComponent(`<svg xmlns="${SVG_NS}" viewBox="0 0 24 24" fill="none" stroke="#7e93ad" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="${paths[key]}"/></svg>`);
89
+ for(const [tool,label] of [['select','Select'],['freehand','Draw'],['arrow','Arrow'],['circle','Circle'],['text','Text']]){
90
+ bar.menuline({caption:label,tooltip:label,iconSrc:icon(tool),checked:`^${this.#statePath}.tool:={} === '${tool}'`,action:`this.parentBag.parentNode.drawingController.setTool('${tool}')`});
91
+ }
92
+ bar.contentPane({height:'1px',margin:'6px 4px',background:'var(--gramlot-border-control,#a8b2bf)'});
93
+ const circleIcon=color=>'data:image/svg+xml,'+encodeURIComponent(`<svg xmlns="${SVG_NS}" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="${color}" stroke="#8793a3" stroke-width="1.5"/></svg>`);
94
+ const colorMenu=bar.menuline({caption:'Color',tooltip:'Color',iconSrc:`^${this.#statePath}.color:='data:image/svg+xml,' + encodeURIComponent('<svg xmlns="${SVG_NS}" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="' + {} + '" stroke="#8793a3" stroke-width="1.5"/></svg>')`}).menu({aria_label:'Annotation colors'});
95
+ for(const [color,label] of [['#dd2222','Red'],['#e6a700','Yellow'],['#16834a','Green'],['#1677d2','Blue'],['#ffffff','White'],['#202733','Black']]){
96
+ colorMenu.menuline({caption:label,iconSrc:circleIcon(color),checked:`^${this.#statePath}.color:={} === '${color}'`,
97
+ action:`this.SET('${this.#statePath}.color', '${color}');`});
98
+ }
99
+ colorMenu.contentPane({padding:'8px'}).colorpicker({value:`^${this.#statePath}.color`,lbl:'Custom color',aria_label:'Color',width:'140px'});
100
+ const strokeIcon=size=>'data:image/svg+xml,'+encodeURIComponent(`<svg xmlns="${SVG_NS}" viewBox="0 0 24 24"><path d="M4 12h16" stroke="#7e93ad" stroke-width="${size}" stroke-linecap="round"/></svg>`);
101
+ const sizeMenu=bar.menuline({caption:'Pen size',tooltip:'Pen size',iconSrc:`^${this.#statePath}.size:='data:image/svg+xml,' + encodeURIComponent('<svg xmlns="${SVG_NS}" viewBox="0 0 24 24"><path d="M4 12h16" stroke="#7e93ad" stroke-width="' + Math.min({}, 12) + '" stroke-linecap="round"/></svg>')`}).menu({aria_label:'Pen size'});
102
+ for(const size of [1,3,5,7,12,20])sizeMenu.menuline({caption:`${size} px`,iconSrc:strokeIcon(Math.min(size,12)),checked:`^${this.#statePath}.size:={} === ${size}`,action:`this.SET('${this.#statePath}.size', ${size});`});
103
+ sizeMenu.contentPane({padding:'8px'}).numberTextBox({value:`^${this.#statePath}.size`,lbl:'Custom size',aria_label:'Pen size',dtype:'L',min:1,max:20,width:'140px'});
104
+ bar.contentPane({flex:'1',min_height:'12px'});
105
+ bar.menuline({caption:'Delete',tooltip:'Delete',iconSrc:icon('delete'),action:'this.parentBag.parentNode.drawingController.deleteSelection()'});
106
+ const app=builder.binding.gramlot,source=app.src.prepareSource(fragment);
107
+ app.src.renderer.validateCandidate(source);this.#built=true;node.setValue(source);
108
+ }
109
+ setTool(tool){this.#finishText(true);this.#gesture=null;this.#state.setItem('tool',tool);}
110
+ deleteSelection(){if(this.#selected){this.#bag.popNode(this.#selected);this.#selected=null;this.#render();}}
111
+ #stateChanged(){
112
+ const tool=this.#state.getItem('tool');this.#tool=tool;
113
+ const color=this.#state.getItem('color'),size=this.#state.getItem('size');
114
+ const changed=color!==this.#lastColor||size!==this.#lastSize;this.#lastColor=color;this.#lastSize=size;
115
+ if(changed&&!this.#syncing)this.#styleSelection();
116
+ this.#render();
117
+ }
118
+ #point(event){
119
+ const matrix=this.#svg.getScreenCTM();if(!matrix)return null;
120
+ const p=this.#svg.createSVGPoint();p.x=event.clientX;p.y=event.clientY;const q=p.matrixTransform(matrix.inverse());
121
+ return {x:Math.max(0,Math.min(this.#dimensions[0],q.x)),y:Math.max(0,Math.min(this.#dimensions[1],q.y))};
122
+ }
123
+ #down(event){
124
+ if(event.button!==0||!this.#dimensions)return;const point=this.#point(event);if(!point)return;
125
+ const id=event.target.closest('[data-id]')?.getAttribute('data-id');
126
+ if(this.#tool==='select'){
127
+ this.#selected=id||null;
128
+ if(id){const value=this.#bag.getItem(id);if(!(value instanceof Bag))throw new TypeError('Annotation must be a Bag');const row=this.#read(value);this.#syncing=true;try{this.#state.setItem('color',row.color);this.#state.setItem('size',row.width);}finally{this.#syncing=false;}this.#gesture={id,start:point,original:row};}
129
+ }else if(this.#tool==='text'){
130
+ const value=id?this.#bag.getItem(id):null;
131
+ this.#editText(value instanceof Bag&&value.getItem('type')==='text'?id:null,point);
132
+ }else {this.#selected=null;this.#gesture={start:point,current:point,points:[point]};}
133
+ if(this.#gesture)this.#svg.setPointerCapture(event.pointerId);this.#render();event.preventDefault();
134
+ }
135
+ #move(event){if(!this.#gesture||!this.#dimensions)return;const point=this.#point(event);if(!point)return;this.#gesture.current=point;if(this.#tool==='freehand')this.#gesture.points.push(point);this.#render();}
136
+ #up(event){
137
+ if(!this.#gesture)return;this.#move(event);const gesture=this.#gesture;this.#gesture=null;
138
+ if(gesture.id){const delta={x:gesture.current.x-gesture.start.x,y:gesture.current.y-gesture.start.y};const row=this.#translate(gesture.original,delta);this.#bag.setItem(gesture.id,new Bag(row));}
139
+ else {const {start,current,points}=gesture;let row;
140
+ if(this.#tool==='arrow')row={type:'arrow',x:start.x,y:start.y,x2:current.x,y2:current.y};
141
+ else if(this.#tool==='circle')row={type:'circle',x:start.x,y:start.y,radius:Math.hypot(current.x-start.x,current.y-start.y)};
142
+ else if(this.#tool==='freehand')row={type:'freehand',points};
143
+ if(row)this.#insert({...row,color:this.#state.getItem('color'),width:this.#penSize()});
144
+ }
145
+ if(this.#svg.hasPointerCapture(event.pointerId))this.#svg.releasePointerCapture(event.pointerId);this.#render();
146
+ }
147
+ #insert(row){const id=`item_${randomId()}`;this.#bag.setItem(id,new Bag(row));this.#selected=id;}
148
+ #penSize(){const value=this.#state.getItem('size');return Number.isFinite(value)?Math.max(1,Math.min(20,value)):3;}
149
+ #styleSelection(){if(!this.#selected)return;const value=this.#bag.getItem(this.#selected);if(!(value instanceof Bag))return;const row=this.#read(value);row.color=this.#state.getItem('color');row.width=this.#penSize();this.#bag.setItem(this.#selected,new Bag(row));}
150
+ #editText(id,point){
151
+ this.#finishText(true);const row=id?this.#read(this.#bag.getItem(id)):{type:'text',...point,text:'',color:this.#state.getItem('color'),width:this.#penSize()};
152
+ this.#selected=id;this.#editing={id,row};this.#editor.value=row.text;this.#editor.hidden=false;
153
+ const svgPoint=this.#svg.createSVGPoint();svgPoint.x=row.x;svgPoint.y=row.y;const matrix=this.#svg.getScreenCTM();if(!matrix){this.#finishText(false);return;}
154
+ const position=svgPoint.matrixTransform(matrix),box=this.controlBox.getBoundingClientRect();
155
+ const fontSize=Math.max(14,Math.max(14,12+row.width*2)*matrix.a);
156
+ this.#editor.style.left=`${position.x-box.left}px`;this.#editor.style.top=`${position.y-box.top-fontSize}px`;
157
+ this.#editor.style.fontSize=`${fontSize}px`;this.#editor.focus();this.#editor.select();
158
+ }
159
+ #finishText(commit){
160
+ if(!this.#editing)return;const {id,row}=this.#editing;this.#editing=null;const text=this.#editor.value.trim();this.#editor.hidden=true;
161
+ if(commit&&text){row.text=text;if(id)this.#bag.setItem(id,new Bag(row));else this.#insert(row);}
162
+ if(commit)this.#state.setItem('tool','select');
163
+ this.#render();
164
+ }
165
+ #read(row){
166
+ const result=Object.fromEntries(row.getNodes().map(node=>[node.label,node.getValue()]));
167
+ if(result.type==='freehand')result.points=result.points.getNodes().map(node=>({x:node.getValue().getItem('x'),y:node.getValue().getItem('y')}));
168
+ return result;
169
+ }
170
+ #translate(row,delta){const result={...row};if(row.type==='freehand')result.points=row.points.map(p=>({x:p.x+delta.x,y:p.y+delta.y}));else {result.x+=delta.x;result.y+=delta.y;if(row.type==='arrow'){result.x2+=delta.x;result.y2+=delta.y;}}return result;}
171
+ #element(tag,attrs){const el=this.ownerDocument.createElementNS(SVG_NS,tag);for(const [k,v] of Object.entries(attrs))el.setAttribute(k,String(v));return el;}
172
+ #shape(row,id){
173
+ const g=this.#element('g',{'data-id':id,class:`shape${id===this.#selected?' selected':''}`,fill:'none',stroke:row.color,'stroke-width':row.width,'stroke-linecap':'round','stroke-linejoin':'round'});
174
+ if(row.type==='circle')g.append(this.#element('circle',{cx:row.x,cy:row.y,r:row.radius}));
175
+ if(row.type==='arrow'){
176
+ g.append(this.#element('line',{x1:row.x,y1:row.y,x2:row.x2,y2:row.y2}));
177
+ const angle=Math.atan2(row.y2-row.y,row.x2-row.x),size=Math.max(12,row.width*5);
178
+ const x1=row.x2-size*Math.cos(angle-0.45),y1=row.y2-size*Math.sin(angle-0.45),x2=row.x2-size*Math.cos(angle+0.45),y2=row.y2-size*Math.sin(angle+0.45);
179
+ g.append(this.#element('polyline',{points:`${x1},${y1} ${row.x2},${row.y2} ${x2},${y2}`}));
180
+ }
181
+ if(row.type==='freehand')g.append(this.#element('polyline',{points:row.points.map(p=>`${p.x},${p.y}`).join(' ')}));
182
+ if(row.type==='text'){const hit=this.#element('rect',{'data-text-hit':'',fill:'transparent',stroke:'none','pointer-events':'all'});const t=this.#element('text',{x:row.x,y:row.y,fill:row.color,stroke:'none','font-size':Math.max(14,12+row.width*2)});t.textContent=row.text;g.append(hit,t);}
183
+ return g;
184
+ }
185
+ #render(){
186
+ if(!this.#svg||!this.#bag)return;this.#svg.replaceChildren();if(!this.#dimensions)return;
187
+ const [width,height]=this.#dimensions;this.#svg.setAttribute('viewBox',`0 0 ${width} ${height}`);
188
+ if(this.#url)this.#svg.append(this.#element('image',{href:this.#url,x:0,y:0,width,height,'pointer-events':'none'}));
189
+ for(const node of this.#bag.getNodes()){
190
+ const value=node.getValue();if(!(value instanceof Bag))throw new TypeError('Annotation must be a Bag');let row=this.#read(value);
191
+ if(this.#gesture?.id===node.label&&this.#gesture.current)row=this.#translate(this.#gesture.original,{x:this.#gesture.current.x-this.#gesture.start.x,y:this.#gesture.current.y-this.#gesture.start.y});
192
+ const shape=this.#shape(row,node.label);this.#svg.append(shape);
193
+ if(row.type==='text'){const bounds=shape.querySelector('text').getBBox(),hit=shape.querySelector('[data-text-hit]');for(const name of ['x','y','width','height'])hit.setAttribute(name,bounds[name]);}
194
+ }
195
+ const g=this.#gesture;if(g&&!g.id&&g.current){let row;if(this.#tool==='arrow')row={type:'arrow',x:g.start.x,y:g.start.y,x2:g.current.x,y2:g.current.y};if(this.#tool==='circle')row={type:'circle',x:g.start.x,y:g.start.y,radius:Math.hypot(g.current.x-g.start.x,g.current.y-g.start.y)};if(this.#tool==='freehand')row={type:'freehand',points:g.points};if(row)this.#svg.append(this.#shape({...row,color:this.#state.getItem('color'),width:this.#penSize()},''));}
196
+ }
197
+ }
198
+ });
199
+ export default defineCollection({name:'drawing',dependencies:[inputs,layout],components:[DrawingPane]});
@@ -0,0 +1,98 @@
1
+ import {containsId, requireId, requireIdSet} from '../stores/id-set.js';
2
+
3
+ function singleId(id) {
4
+ if (typeof id === 'number' && Number.isFinite(id)) return id;
5
+ return requireId(id);
6
+ }
7
+
8
+ /** External membership columns. Data IDs and membership strings are authoritative; DOM checks are projections. */
9
+ export class GridCheckSets {
10
+ #registrations = [];
11
+ #connected = false;
12
+ constructor(source, body, columns, rowFor, read, selection, view) {
13
+ this.source = source; this.body = body; this.columns = columns;
14
+ this.rowFor = rowFor; this.read = read; this.selection = selection; this.view = view;
15
+ }
16
+ path(column) { return this.source.absDatapath(column.checked.slice(1)); }
17
+ value(column) {
18
+ const value = this.source.getRelativeData(column.checked.slice(1));
19
+ if (column.check === 'single') return value == null || value === '' ? value : singleId(value);
20
+ return requireIdSet(value);
21
+ }
22
+ id(row, column) {
23
+ const id = this.read(row,column.checkedField);
24
+ if (column.check === 'single') return singleId(id);
25
+ return requireId(id);
26
+ }
27
+ contains(column, value, id) { return column.check === 'single' ? value === id : containsId(value,id); }
28
+ filter() {
29
+ const selected = this.selection();
30
+ const sets = selected === '' ? null : selected.split(',').map(field => {
31
+ const column = this.columns().find(column => column.field === field && column.check === 'multiple');
32
+ if (!column) throw new TypeError(`Unknown external check column: ${field}`);
33
+ return {field:column.checkedField,value:this.value(column)};
34
+ });
35
+ this.view().applySetFilter(sets);
36
+ }
37
+ project(content, row, column) {
38
+ const id = this.id(row,column), value = this.value(column);
39
+ let input = content.querySelector('input.grid-set-check');
40
+ if (!input) {
41
+ input = content.ownerDocument.createElement('input');
42
+ input.className = 'grid-set-check'; content.replaceChildren(input);
43
+ }
44
+ input.type = column.check === 'single' ? 'radio' : 'checkbox';
45
+ if (column.check === 'single') input.name = column.field;
46
+ else input.removeAttribute('name');
47
+ input.setAttribute('aria-label', `${column.title ?? column.name}: ${id}`);
48
+ input.checked = this.contains(column,value,id);
49
+ }
50
+ refresh = () => {
51
+ this.filter();
52
+ for (const input of this.body.querySelectorAll('input.grid-set-check')) {
53
+ const cell = input.closest('td[data-field]');
54
+ const column = this.columns().find(c => c.field === cell.dataset.field);
55
+ const row = this.rowFor(cell.parentElement);
56
+ if (column?.check && row) this.project(input.parentElement,row,column);
57
+ }
58
+ };
59
+ change = event => {
60
+ const input = event.target;
61
+ if (!input.matches('input.grid-set-check')) return;
62
+ const cell = input.closest('td[data-field]');
63
+ const column = this.columns().find(c => c.field === cell.dataset.field);
64
+ const row = this.rowFor(cell.parentElement);
65
+ const id = this.id(row,column), value = this.value(column);
66
+ const present = this.contains(column,value,id);
67
+ if (input.checked === present) return;
68
+ if (column.check === 'single') {
69
+ if (input.checked) this.source.setRelativeData(column.checked.slice(1),id);
70
+ else this.project(input.parentElement,row,column);
71
+ return;
72
+ }
73
+ const next = input.checked ? (value ? value + ',' + id : id)
74
+ : (',' + value + ',').replace(',' + id + ',', ',').slice(1,-1);
75
+ this.source.setRelativeData(column.checked.slice(1),next);
76
+ };
77
+ configure() {
78
+ for (const registration of this.#registrations) registration.close();
79
+ this.#registrations = [];
80
+ if (!this.#connected) return;
81
+ this.filter();
82
+ for (const column of this.columns().filter(column => column.check)) {
83
+ this.#registrations.push(this.source.rootBuilder.binding.router.register({
84
+ path:this.path(column), recipient:{receive:this.refresh}
85
+ }));
86
+ }
87
+ }
88
+ connect() {
89
+ if (this.#connected) return;
90
+ this.#connected = true;
91
+ this.body.addEventListener('change',this.change);
92
+ }
93
+ disconnect() {
94
+ this.body.removeEventListener('change',this.change);
95
+ this.#connected = false;
96
+ this.configure();
97
+ }
98
+ }