@gramlot/gramlot 0.3.20 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/dist/components/chat/__init__.py +13 -0
  2. package/dist/components/chat/assets/collection.js +9 -0
  3. package/dist/components/chat/assets/index.js +3 -0
  4. package/dist/components/chat/commands.json +7 -0
  5. package/dist/components/chat/grammar.json +48 -0
  6. package/dist/components/editors/__init__.py +2 -2
  7. package/dist/components/editors/assets/collection.js +26 -120912
  8. package/dist/components/editors/assets/index.js +2 -1
  9. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  10. package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
  11. package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
  12. package/dist/components/editors/assets/modules/code-mirror-engine-RWQTR5G5.js +92 -0
  13. package/dist/components/editors/assets/modules/jodit-engine-MTSA4GZ3.js +1853 -0
  14. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  15. package/dist/components/editors/assets/modules/prose-mirror-engine-GMZPJPNN.js +24 -0
  16. package/dist/components/grid/__init__.py +14 -0
  17. package/dist/components/grid/assets/collection.js +262 -0
  18. package/dist/components/grid/assets/index.js +3 -0
  19. package/dist/components/grid/commands.json +7 -0
  20. package/dist/components/grid/grammar.json +770 -0
  21. package/dist/components/grouplets/__init__.py +13 -0
  22. package/dist/components/grouplets/assets/collection.js +185 -0
  23. package/dist/components/grouplets/assets/index.js +3 -0
  24. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  25. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  26. package/dist/components/grouplets/commands.json +7 -0
  27. package/dist/components/grouplets/grammar.json +355 -0
  28. package/dist/components/inputs/__init__.py +1 -1
  29. package/dist/components/inputs/assets/collection.js +65 -24511
  30. package/dist/components/inputs/assets/index.js +2 -1
  31. package/dist/components/inputs/grammar.json +278 -6
  32. package/dist/components/layout/__init__.py +1 -1
  33. package/dist/components/layout/assets/collection.js +68 -26732
  34. package/dist/components/layout/assets/index.js +2 -1
  35. package/dist/components/layout/grammar.json +39 -0
  36. package/dist/components/selection_trial/__init__.py +13 -0
  37. package/dist/components/selection_trial/assets/collection.js +4 -0
  38. package/dist/components/selection_trial/assets/index.js +3 -0
  39. package/dist/components/selection_trial/commands.json +7 -0
  40. package/dist/components/selection_trial/grammar.json +587 -0
  41. package/dist/components/tree/__init__.py +1 -1
  42. package/dist/components/tree/assets/collection.js +27 -24612
  43. package/dist/components/tree/assets/index.js +2 -1
  44. package/dist/components/tree/grammar.json +341 -1
  45. package/dist/components/typst/__init__.py +2 -2
  46. package/dist/components/typst/assets/collection.js +12 -4
  47. package/dist/components/typst/assets/index.js +2 -1
  48. package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
  49. package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
  50. package/dist/components/uploads/__init__.py +13 -0
  51. package/dist/components/uploads/assets/collection.js +67 -0
  52. package/dist/components/uploads/assets/index.js +3 -0
  53. package/dist/components/uploads/commands.json +7 -0
  54. package/dist/components/uploads/grammar.json +789 -0
  55. package/dist/gramlot-markdown.js +16 -0
  56. package/dist/gramlot.js +6861 -1395
  57. package/dist/gramlot.min.js +1595 -46
  58. package/dist/runtime-notices.json +28 -0
  59. package/package.json +10 -3
  60. package/src/binding/grid-struct.js +63 -0
  61. package/src/binding/installation.js +5 -2
  62. package/src/binding/providers.js +4 -1
  63. package/src/binding/remote-resolver.js +1 -8
  64. package/src/binding/runtime.js +90 -6
  65. package/src/binding/validation-context.js +40 -0
  66. package/src/browser-camera-provider.d.ts +8 -0
  67. package/src/browser-camera-provider.js +104 -0
  68. package/src/builder/gramlot-builder.d.ts +5 -0
  69. package/src/builder/gramlot-builder.js +16 -0
  70. package/src/builder/source.js +34 -0
  71. package/src/chat.d.ts +12 -0
  72. package/src/chat.js +198 -0
  73. package/src/collection-artifact.js +1 -1
  74. package/src/components/attachment-manager.js +160 -0
  75. package/src/components/bases.js +19 -6
  76. package/src/components/border-container.js +86 -8
  77. package/src/components/buttons.js +11 -1
  78. package/src/components/chat.js +28 -0
  79. package/src/components/choice-editor.js +106 -38
  80. package/src/components/database-choices.js +133 -9
  81. package/src/components/editing-status-styles.js +26 -0
  82. package/src/components/editing-status.js +115 -0
  83. package/src/components/field-state.js +42 -54
  84. package/src/components/grid-cell-editor.js +181 -0
  85. package/src/components/grid-grammar.json +258 -0
  86. package/src/components/grid-header-interaction.js +196 -0
  87. package/src/components/grid-row-interaction.js +184 -0
  88. package/src/components/grid-row-layout.js +96 -0
  89. package/src/components/grid-rows.js +28 -0
  90. package/src/components/grid-search-box.js +142 -0
  91. package/src/components/grid-search-styles.js +42 -0
  92. package/src/components/grid-search.js +37 -0
  93. package/src/components/grid-structure.js +85 -0
  94. package/src/components/grid-styles.js +201 -0
  95. package/src/components/grid.js +666 -0
  96. package/src/components/grouplet-card.js +445 -0
  97. package/src/components/grouplets.js +17 -0
  98. package/src/components/html-preview.js +17 -4
  99. package/src/components/image-crop-dialog.js +272 -0
  100. package/src/components/image-crop.js +79 -0
  101. package/src/components/image-uploader.js +252 -0
  102. package/src/components/inputs.js +2 -1
  103. package/src/components/jodit-engine.js +1 -1
  104. package/src/components/markdown-document.js +2 -2
  105. package/src/components/menus.js +1 -0
  106. package/src/components/registry.js +4 -3
  107. package/src/components/screen-capture.js +43 -0
  108. package/src/components/selected-container.js +6 -2
  109. package/src/components/tray-pane.js +32 -4
  110. package/src/components/tree.js +416 -17
  111. package/src/components/typed-editor.js +23 -11
  112. package/src/components/upload-engine.js +156 -0
  113. package/src/components/uploader.js +208 -0
  114. package/src/components/uploads.js +7 -0
  115. package/src/editing-session.d.ts +25 -0
  116. package/src/editing-session.js +396 -0
  117. package/src/experiments/selection-transfer.js +78 -0
  118. package/src/experiments/selection-trial.js +64 -0
  119. package/src/experiments/window-selection.js +124 -0
  120. package/src/format.js +22 -7
  121. package/src/gramlot.d.ts +2 -0
  122. package/src/gramlot.js +2 -1
  123. package/src/handlers/device-handler.d.ts +2 -1
  124. package/src/handlers/rpc-handler.d.ts +3 -3
  125. package/src/index-page-styles.js +2 -1
  126. package/src/index.d.ts +16 -1
  127. package/src/index.js +16 -1
  128. package/src/inout.d.ts +2 -0
  129. package/src/inout.js +6 -0
  130. package/src/markdown-loader.d.ts +1 -0
  131. package/src/markdown-loader.js +4 -0
  132. package/src/markdown.d.ts +1 -0
  133. package/src/markdown.js +2 -0
  134. package/src/media-frame.js +9 -0
  135. package/src/renderer/attributes.js +7 -1
  136. package/src/renderer/gramlot-renderer.d.ts +2 -0
  137. package/src/renderer/gramlot-renderer.js +39 -3
  138. package/src/server/assets.d.ts +1 -1
  139. package/src/server/assets.js +1 -1
  140. package/src/server/gramlot-server.d.ts +10 -1
  141. package/src/server/gramlot-server.js +96 -8
  142. package/src/server/index.d.ts +2 -0
  143. package/src/server/index.js +2 -0
  144. package/src/server/page-base.js +17 -4
  145. package/src/server/page.d.ts +13 -1
  146. package/src/server/page.js +6 -0
  147. package/src/server/source-import.d.ts +2 -0
  148. package/src/server/source-import.js +31 -0
  149. package/src/server/upload.d.ts +20 -0
  150. package/src/server/upload.js +142 -0
  151. package/src/server/visual-editor.d.ts +11 -0
  152. package/src/server/visual-editor.js +149 -0
  153. package/src/source-picker.d.ts +9 -0
  154. package/src/source-picker.js +57 -0
  155. package/src/stores/bag-collection-store.js +51 -0
  156. package/src/stores/bag-collection-view.js +127 -0
  157. package/src/stores/collection-filter.js +77 -0
  158. package/src/tree-store.d.ts +24 -0
  159. package/src/tree-store.js +193 -0
  160. package/src/validation-run.js +50 -0
  161. package/src/view/button.js +8 -5
  162. package/src/view/controls.js +31 -32
  163. package/src/view/grouplet-card.js +54 -0
  164. package/src/view/html.js +29 -4
  165. package/src/view/labelbox.js +7 -3
  166. package/src/visual-editor-icons.js +10 -0
  167. package/src/visual-editor.d.ts +56 -0
  168. package/src/visual-editor.js +844 -0
  169. package/themes/gramlot-base/theme.css +127 -0
  170. package/themes/gramlot-compact/theme.css +8 -0
  171. package/themes/joanna/theme.css +8 -0
  172. package/themes/mimi/theme.css +8 -0
@@ -0,0 +1,844 @@
1
+ import {SourcePicker} from './source-picker.js';
2
+ import {appearanceStyles, paletteStyles} from './index-page-styles.js';
3
+ import {toolIcons} from './visual-editor-icons.js';
4
+ import {Bag} from '@genrojs/bag';
5
+ import {chatRender, chatSend, chatCompleted, chatReset, chatResize, chatPickAttachments, chatRenderAttachments, chatRemoveAttachment} from './chat.js';
6
+
7
+ export function visualEditorScope(node) {
8
+ for (let scope = node; scope; scope = scope.parentNode) {
9
+ if (scope.getAttr('visualEditorId')) return scope;
10
+ }
11
+ throw new Error('Operation requires a VisualEditor Source ancestor');
12
+ }
13
+ function sourceRoot(node) { return visualEditorScope(node).fullpath.split('.').slice(1).join('.') + '.layout.center.design'; }
14
+ function editorData(node) { return visualEditorScope(node).absDatapath('.'); }
15
+ function editorField(node, name) {
16
+ return node.rootBuilder.binding.nodeIds.get(visualEditorScope(node).getAttr('visualEditorId') + name);
17
+ }
18
+ // Catalogue taxonomy: the schema remains authoritative for the available tags.
19
+ const catalogueSections = [
20
+ ['html.structure', 'Structure', 'main header footer nav section article aside div address search'],
21
+ ['html.text', 'Text and headings', 'h1 h2 h3 h4 h5 h6 hgroup p span a b strong i em small s u mark abbr cite code pre blockquote q br wbr hr time data dfn kbd samp var bdi bdo ruby rt rp sub sup ins del_'],
22
+ ['html.lists', 'Lists', 'ul ol li dl dt dd'],
23
+ ['html.forms', 'Forms', 'form input textarea select selectedcontent option optgroup datalist label fieldset legend output progress meter html_button'],
24
+ ['html.tables', 'Tables', 'table caption colgroup col thead tbody tfoot tr th td'],
25
+ ['html.media', 'Media and embedded content', 'img picture source audio video track canvas iframe embed object param map area'],
26
+ ['html.interaction', 'Disclosure and menus', 'details summary html_dialog html_menu'],
27
+ ['html.document', 'Document and metadata', 'html head body title base meta link style script noscript template slot'],
28
+ ['components.layout.containers', 'Containers', 'borderContainer contentPane framePane stackContainer tabContainer'],
29
+ ['components.layout.windows', 'Windows', 'dialog floatingPane'],
30
+ ['components.layout.composition', 'Composition', 'formlet groupBox trayPane transformPane'],
31
+ ['components.inputs.text', 'Text', 'textbox textBoxArea passwordbox'],
32
+ ['components.inputs.choices', 'Choices', 'checkbox radioButton radioButtonText checkBoxText filteringSelect comboBox callbackSelect dbSelect dbComboBox'],
33
+ ['components.inputs.numbers', 'Numbers and colors', 'numberTextBox horizontalSlider verticalSlider colorpicker'],
34
+ ['components.inputs.dates', 'Dates and times', 'dateTextBox timeTextBox dateCalendar'],
35
+ ['components.commands', 'Buttons and menus', 'button toggleButton dropDownButton menu menuline spacer'],
36
+ ['components.data', 'Trees and grids', 'tree grid searchBox'],
37
+ ['components.editors', 'Editors and previews', 'codeMirror htmlEditor htmlPreview markdownEditor markdownPreview typstPreview']
38
+ ];
39
+ const sectionTitles = {html:'HTML', components:'Gramlot', 'components.layout':'Layout', 'components.inputs':'Inputs'};
40
+ const styleParameters = Object.fromEntries(['class','style','width','height','padding','margin','color','background']
41
+ .map(name => [name, {dtype:'T', nullable:true}]));
42
+ // These prefixes belong to the renderer's existing Labelbox attribute contract.
43
+ const labelboxParameters = Object.fromEntries(['lbl_', 'box_'].flatMap(prefix =>
44
+ Object.entries(styleParameters).map(([name, spec]) => [prefix + name, spec])));
45
+ const parameterThemes = [
46
+ ['general', 'General'], ['behaviour', 'Behaviour'], ['validation', 'Validation'],
47
+ ['styles', 'Styles'], ['container', 'Container']
48
+ ];
49
+ const editableTypes = ['T','B','L','R','N','D','H'];
50
+ function parameterTheme(name, parentFields) {
51
+ if (/^(lbl|box)(_|$)/.test(name)) return 'general';
52
+ if (parentFields.has(name)) return 'container';
53
+ if (name.startsWith('validate_')) return 'validation';
54
+ if (Object.hasOwn(styleParameters, name) || /^(icon|tab)/.test(name) ||
55
+ ['design','labelPosition','switch_color','orientation'].includes(name)) return 'styles';
56
+ if (/^(on[A-Z]|get[A-Z]|drag|drop)/.test(name) ||
57
+ ['action','command','disabled','readonly','live','beforeClose','open','collapsed','closable','movable','resizable','collapsible','maximizable','maximized','persist','autoCollapse','openOnClick'].includes(name)) return 'behaviour';
58
+ return 'general';
59
+ }
60
+
61
+ const specifications = (node, tag, current = null) => {
62
+ const info = node.builder.schema[tag];
63
+ if (!info) throw new Error(`Unknown widget: ${tag}`);
64
+ const component = info._meta?.gramlot_component;
65
+ const textContent = (!current || !(current.getValue(true) instanceof current.builder.source.constructor)) &&
66
+ (!component || (component.command && !Object.hasOwn(component.parameters, 'caption')));
67
+ return {...(textContent ? {_text:{dtype:'T', nullable:true}} : {}), ...styleParameters, ...(component?.labelbox ? labelboxParameters : {}), ...(component?.parameters ?? {}),
68
+ ...(node._getMeta('gramlot_component')?.childParameters ?? {})};
69
+ };
70
+
71
+ // Editor-local view resources; selection itself remains in the Data Bag.
72
+ const canvasSelections = new WeakMap();
73
+
74
+ export class VisualEditorLogic {
75
+ chatRender(node, params) { return chatRender(this.page, node, params); }
76
+ chatCompleted(node, params) {
77
+ chatCompleted(this.page, node, params);
78
+ if (node.GET(`${editorData(node)}.assistant.active`)) node.SET('.pending', true);
79
+ }
80
+ chatReset(node) { return chatReset(this.page, node); }
81
+ chatResize(node) { return chatResize(this.page, node); }
82
+ chatPickAttachments(node) { return chatPickAttachments(this.page, node); }
83
+ chatRenderAttachments(node, params) { return chatRenderAttachments(this.page, node, params); }
84
+ chatRemoveAttachment(node) { return chatRemoveAttachment(this.page, node); }
85
+ chatSend(node) {
86
+ if (node.GET('.pending') || !node.GET('.conversation.ready') || !node.GET('.draft')?.trim()) return;
87
+ const editor = visualEditorScope(node);
88
+ const mode = editor.GET('.editingMode');
89
+ const wire = node.builder.source.getNode(sourceRoot(node)).value.toTytx();
90
+ const content = mode === 'code' ? editor.GET('.codeDocument.content') : wire;
91
+ if (mode === 'code' && !editor.GET('.codeDocument.writable')) { node.SET('.error', 'Page code editing is disabled by the host'); return; }
92
+ const run = (editor.GET('.assistantRun.run') ?? 0) + 1;
93
+ const schema = {commonParameters:styleParameters, labelboxParameters, widgets:{}};
94
+ for (const [tag, info] of Object.entries(node.builder.schema)) {
95
+ if (info._meta?.data_element || info._meta?.subbuilder || info._meta?.container) continue;
96
+ const component = info._meta?.gramlot_component;
97
+ schema.widgets[tag] = {parameters:component?.parameters ?? {}, labelbox:!!component?.labelbox,
98
+ childParameters:component?.childParameters ?? {}};
99
+ }
100
+ editor.SET('.assistantRun', new Bag({run, mode, next:0, expected:content, blocked:false}));
101
+ editor.SET('.assistantStatus', 'Waiting for editing instructions…');
102
+ editor.SET('.assistant.context', new Bag({run, mode, language:editor.GET('.codeDocument.language') ?? null, codeWritable:editor.GET('.codeDocument.writable') === true, code:mode === 'code' ? content : null, source:wire, selected:editor.GET('.selection'), schema:JSON.stringify(schema)}));
103
+ return chatSend(this.page, node);
104
+ }
105
+ assistantState(node, {active}) {
106
+ if (active === false) {
107
+ node.SET(`${editorData(node)}.chat.pending`, false);
108
+ const editor = visualEditorScope(node);
109
+ if (editor.GET('.assistantRun.next') === 0) editor.SET('.assistantStatus', '');
110
+ }
111
+ }
112
+ assistantApply(node, {operations}) {
113
+ if (!(operations instanceof Bag)) return;
114
+ const editor = visualEditorScope(node);
115
+ for (const entry of operations.getNodes()) {
116
+ if (entry.attr.run !== editor.GET('.assistantRun.run') || entry.attr.index < editor.GET('.assistantRun.next')) continue;
117
+ const page = node.builder.source.getNode(sourceRoot(node)).value;
118
+ const mode = editor.GET('.assistantRun.mode');
119
+ const before = mode === 'code' ? editor.GET('.codeDocument.content') : page.toTytx();
120
+ let applied = false, stop = false, error = '';
121
+ try {
122
+ if (editor.GET('.assistantRun.blocked')) {
123
+ stop = true;
124
+ throw new Error('The document was replaced during editing');
125
+ }
126
+ if (entry.attr.index !== editor.GET('.assistantRun.next')) {
127
+ stop = true;
128
+ throw new Error('Editing sequence is incomplete');
129
+ }
130
+ if (before !== editor.GET('.assistantRun.expected')) {
131
+ stop = true;
132
+ throw new Error('Source changed during the request. Remaining edits stopped; send a new instruction.');
133
+ }
134
+ const operation = JSON.parse(entry.value);
135
+ if (mode === 'code') {
136
+ if (operation.operation !== 'replace_code' || typeof operation.content !== 'string') throw new Error('Expected a Page code draft operation');
137
+ if (!editor.GET('.codeDocument.writable') || editor.GET('.codeDocument.busy')) throw new Error('Page code draft is not editable now');
138
+ editor.SET('.codeDocument.content', operation.content);
139
+ editor.SET('.codeDocument.status', 'AI draft · Save to apply');
140
+ editor.SET('.codeOpen', true);
141
+ } else this.applySourceEdit(editor, operation);
142
+ applied = true;
143
+ editor.SET('.assistantRun.expected', mode === 'code' ? editor.GET('.codeDocument.content') : page.toTytx());
144
+ editor.SET('.assistantStatus', `Applied ${entry.attr.index + 1}: ${mode === 'code' ? 'Page code draft' : operation.operation + ' ' + operation.path}`);
145
+ } catch (caught) {
146
+ error = caught.message;
147
+ if ((mode === 'code' ? editor.GET('.codeDocument.content') : page.toTytx()) !== before) stop = true;
148
+ editor.SET('.assistantRun.blocked', stop);
149
+ editor.SET('.assistantStatus', `${stop ? 'Editing stopped' : 'Rejected'}: ${error}`);
150
+ }
151
+ editor.SET('.assistantRun.next', entry.attr.index + 1);
152
+ editor.SET('.assistant.ack', new Bag({run:entry.attr.run, index:entry.attr.index,
153
+ applied, stop, error, mode, code:mode === 'code' ? editor.GET('.codeDocument.content') : null, source:page.toTytx(), selected:editor.GET('.selection')}));
154
+ }
155
+ }
156
+ applySourceEdit(node, operation) {
157
+ const {operation:action, path, parent:parentPath, tag, label, attributes = {}, text} = operation;
158
+ const validPath = value => typeof value === 'string' && /^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(value);
159
+ if (!validPath(path) || (action === 'move' && !validPath(parentPath))) throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(path)}`);
160
+ if (!['insert','update','remove','move'].includes(action)) throw new Error('Unknown Source editing operation');
161
+ if (['remove','move'].includes(action) && path === 'pageRoot') throw new Error('The page root is protected');
162
+ if (action === 'insert' && (typeof label !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(label))) throw new Error('Choose an explicit node label');
163
+ if (!attributes || typeof attributes !== 'object' || Array.isArray(attributes)) throw new Error('Expected scalar attributes');
164
+ for (const [name, value] of Object.entries(attributes)) {
165
+ if (name.startsWith('_') || /^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(name) ||
166
+ ['constructor','prototype'].includes(name) || (value !== null && typeof value === 'object') ||
167
+ (typeof value === 'string' && (value.startsWith('==') || value.includes(':='))))
168
+ throw new Error(`Unsupported generated attribute: ${name}`);
169
+ }
170
+ if (text !== undefined && typeof text !== 'string') throw new Error('Text must be literal text');
171
+ const design = node.builder.source.getNode(sourceRoot(node)), app = node.rootBuilder.binding.gramlot;
172
+ const candidate = app.src.prepareSource(design.value.toTytx(), design.builder);
173
+ const target = candidate.getNode(path);
174
+ if (!target) throw new Error('The Source target no longer exists');
175
+ let changed = target;
176
+ if (action === 'insert') {
177
+ if (!node.builder.schema[tag] || ['script','style','iframe','object','embed'].includes(tag) ||
178
+ node.builder.schema[tag]._meta?.data_element) throw new Error('Choose a visual widget from the catalogue');
179
+ if (target.value instanceof candidate.constructor && target.value.getNode(label)) throw new Error('This node label is already in use');
180
+ changed = target.builder.commandOnNode(target, tag, text ?? null, {...attributes, node_label:label});
181
+ } else if (action === 'update') {
182
+ if (text !== undefined && target.value instanceof candidate.constructor) throw new Error('Text cannot replace a populated container');
183
+ const attrs = {...target.getAttr()};
184
+ for (const [name, value] of Object.entries(attributes)) {
185
+ if (value === null) delete attrs[name]; else attrs[name] = value;
186
+ }
187
+ target.setAttr(attrs, true, false, false);
188
+ if (text !== undefined) target.setValue(text);
189
+ } else if (action === 'remove') target.parentBag.popNode(target.label);
190
+ else {
191
+ if (Object.keys(attributes).length || text !== undefined) throw new Error('Move and property edits must be separate operations');
192
+ if (parentPath === path || parentPath.startsWith(path + '.')) throw new Error('Cannot move a node into itself');
193
+ const parent = candidate.getNode(parentPath);
194
+ if (!parent) throw new Error('The destination no longer exists');
195
+ if (parent.value instanceof candidate.constructor && parent.value.getNode(target.label)) throw new Error('The destination already contains this label');
196
+ changed = this.appendBranch(parent, target, target.label);
197
+ }
198
+ const validateChildren = parent => {
199
+ if (!(parent.value instanceof candidate.constructor)) return;
200
+ parent.builder.validateChildren(parent.nodeTag, parent.value.getNodes().map(child => child.nodeTag));
201
+ for (const child of parent.value.getNodes()) {
202
+ for (const [name, spec] of Object.entries(specifications(parent, child.nodeTag, child)))
203
+ this.validateParameter(parent, child, name, spec, child.getAttr(name));
204
+ validateChildren(child);
205
+ }
206
+ };
207
+ candidate.getNodes().forEach(validateChildren);
208
+ app.src.renderer.validateCandidate(candidate, {replacingNode:design});
209
+ const current = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
210
+ let selected = path;
211
+ if (action === 'insert') {
212
+ this.appendBranch(current, changed, label);
213
+ selected = `${path}.${label}`;
214
+ } else if (action === 'update') {
215
+ current.setAttr({...changed.getAttr()}, true, false, false);
216
+ if (text !== undefined) current.setValue(text);
217
+ } else if (action === 'remove') {
218
+ selected = path.slice(0, path.lastIndexOf('.'));
219
+ current.parentBag.popNode(current.label);
220
+ } else {
221
+ this.applyDrop(node, {item:node.builder.source.getNode(`${sourceRoot(node)}.${parentPath}`),
222
+ path:parentPath, dropValues:{'app/source':{path}}});
223
+ selected = `${parentPath}.${current.label}`;
224
+ }
225
+ node.SET('.sourceSearch', '');
226
+ node.SET('.selection', selected);
227
+ }
228
+
229
+ initializeCanvasSelection(node) {
230
+ const renderer = node.rootBuilder.binding.renderer;
231
+ const design = node.builder.source.getNode(sourceRoot(node));
232
+ const picker = new SourcePicker({renderer, root:design, onSelect:selected => {
233
+ node.SET('.sourceSearch', '');
234
+ node.SET('.selection', selected.fullpath.slice(design.fullpath.length + 1));
235
+ }});
236
+ canvasSelections.set(design, picker);
237
+ renderer.onDispose(design.parentNode, () => canvasSelections.delete(design));
238
+ this.highlightSelection(node);
239
+ }
240
+ highlightSelection(node) {
241
+ const design = node.builder.source.getNode(sourceRoot(node));
242
+ const path = node.GET('.selection');
243
+ canvasSelections.get(design)?.select(path ? design.staticValue.getNode(path) : null);
244
+ }
245
+
246
+ clipboardShortcut(node, event) {
247
+ if (event.defaultPrevented || event.repeat || node.GET('.clipboardOpen') || node.GET('.insertionOpen') || node.GET('.uploadOpen')) return;
248
+ if (event.composedPath().some(element => element.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(element.tagName))) return;
249
+ const key = event.key.toLowerCase();
250
+ const action = key === 'f8' ? 'cutBranch' : key === 'f9' ? 'pasteBranch' : null;
251
+ if (!action || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
252
+ event.preventDefault();
253
+ this[action](node);
254
+ }
255
+ clipboardModifiers(node, event) {
256
+ node.SET('.clipboardDropEffect', event.altKey ? 'copy' : 'move');
257
+ }
258
+ cutBranch(node) { this.beginClipboard(node, node.GET('.selection'), false); }
259
+ copyBranch(node) { this.beginClipboard(node, node.GET('.selection'), true); }
260
+ dropClipboard(node, {dropValues, dropEffect}) {
261
+ this.beginClipboard(node, dropValues['app/source'].path, dropEffect === 'copy');
262
+ }
263
+ prepareClipboard(node, {path, dragValues}) {
264
+ node.SET('.sourceDropEffect', 'copy');
265
+ dragValues['app/clipboard'] = {path};
266
+ }
267
+ branchSnapshot(node, path) {
268
+ const design = node.builder.source.getNode(sourceRoot(node));
269
+ const source = node.rootBuilder.binding.gramlot.src.prepareSource(design.getValue(true).toTytx(), design.builder);
270
+ const branch = source.getNode(path);
271
+ if (!branch) throw new Error('The Source branch no longer exists');
272
+ const check = current => {
273
+ if (current.resolver) throw new Error('Resolver-backed branches cannot be stored in this trial');
274
+ if (current.value instanceof node.builder.source.constructor) current.value.getNodes().forEach(check);
275
+ };
276
+ check(branch);
277
+ const result = new node.builder.source.constructor(null, branch.builder);
278
+ branch.parentBag.popNode(branch.label);
279
+ result.setItem(branch.label, branch.getValue(true), {...branch.getAttr()}, '>', false, false,
280
+ 'editor', false, true, null, branch.nodeTag);
281
+ return result.toTytx();
282
+ }
283
+ beginClipboard(node, path, copy) {
284
+ node.SET('.error', '');
285
+ try {
286
+ if (!path || path === 'pageRoot') throw new Error('Choose a branch below the page root');
287
+ const branch = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
288
+ if (!branch) throw new Error('The Source branch no longer exists');
289
+ const wire = this.branchSnapshot(node, path);
290
+ node.SET('.clipboardDraft', new Bag({path, copy, name:branch.label, wire,
291
+ parentTag:branch.parentNode.nodeTag}));
292
+ node.SET('.clipboardOpen', true);
293
+ } catch (error) { node.SET('.error', error.message); }
294
+ }
295
+ saveClipboard(node) {
296
+ node.SET('.error', '');
297
+ try {
298
+ const name = node.GET('.clipboardDraft.name')?.trim();
299
+ if (!name) throw new Error('Choose a name for the branch');
300
+ const path = node.GET('.clipboardDraft.path');
301
+ const wire = node.GET('.clipboardDraft.wire');
302
+ const copy = node.GET('.clipboardDraft.copy');
303
+ const branch = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
304
+ if (!copy && (!branch || this.branchSnapshot(node, path) !== wire))
305
+ throw new Error('The branch changed; select it again before cutting');
306
+ const shelf = node.GET('.clipboard');
307
+ let index = 1;
308
+ while (shelf.getNode(`branch_${index}`)) index++;
309
+ const key = `branch_${index}`;
310
+ // Store the complete snapshot before removing any live Source.
311
+ shelf.setItem(key, wire, {name, parentTag:node.GET('.clipboardDraft.parentTag')});
312
+ node.SET('.clipboardSelection', key);
313
+ node.SET('.clipboardVisible', true);
314
+ if (!copy) {
315
+ node.SET('.selection', path.slice(0, path.lastIndexOf('.')));
316
+ branch.parentBag.popNode(branch.label);
317
+ }
318
+ node.SET('.clipboardOpen', false);
319
+ node.SET('.fileStatus', `${copy ? 'Copied' : 'Cut'}: ${name}`);
320
+ } catch (error) { node.SET('.error', error.message); }
321
+ }
322
+ pasteBranch(node) {
323
+ node.SET('.error', '');
324
+ try { this.beginPaste(node, node.GET('.clipboardSelection'), node.GET('.selection')); }
325
+ catch (error) { node.SET('.error', error.message); }
326
+ }
327
+ beginPaste(node, key, path) {
328
+ const saved = key ? node.GET('.clipboard').getNode(key) : null;
329
+ if (!saved) throw new Error('Choose a saved branch in the clipboard');
330
+ const parent = path ? node.builder.source.getNode(`${sourceRoot(node)}.${path}`) : null;
331
+ if (!parent) throw new Error('Choose a destination in the Source tree');
332
+ const source = node.rootBuilder.binding.gramlot.src.prepareSource(saved.getValue(true), parent.builder);
333
+ const branch = source.getNodes()[0];
334
+ parent.builder.validateParent(branch.nodeTag, parent.nodeTag);
335
+ const body = parent.getValue(true);
336
+ parent.builder.validateChildren(parent.nodeTag, [...(body instanceof node.builder.source.constructor
337
+ ? body.getNodes().map(child => child.nodeTag) : []), branch.nodeTag]);
338
+ const attrs = {...branch.getAttr()};
339
+ const own = parent.builder.schema[branch.nodeTag]._meta?.gramlot_component?.parameters ?? {};
340
+ const previous = parent.builder.schema[saved.getAttr('parentTag')]?._meta?.gramlot_component?.childParameters ?? {};
341
+ for (const name of Object.keys(previous)) if (!(name in own)) delete attrs[name];
342
+ branch.setAttr(attrs, true, false, false);
343
+ node.SET('.insertion', new Bag({parentPath:path, tag:branch.nodeTag, clipboard:source.toTytx()}));
344
+ const entries = specifications(parent, branch.nodeTag);
345
+ const required = Object.entries(entries).filter(([name, spec]) => spec.required &&
346
+ (attrs[name] == null || attrs[name] === '' || spec.unique));
347
+ if (!required.length) { this.finishPaste(node); return; }
348
+ const fields = editorField(node, 'InsertFields');
349
+ fields.getValue(true).clear();
350
+ const root = node.builder.wrapSource(fields);
351
+ root.p(`Paste ${saved.getAttr('name')} into ${parent.label} [${parent.nodeTag}]`, {class:'visual-editor-hint'});
352
+ const form = root.formlet({columns:2, gap:'8px 10px', lbl_position:'TL', box_c_width:'100%', align_items:'start'});
353
+ for (const [name, spec] of required) this.parameterField(node, form, branch.nodeTag, name, spec, 'insertion', spec.default);
354
+ node.SET('.insertionOpen', true);
355
+ }
356
+ appendBranch(parent, branch, label) {
357
+ const Source = parent.builder.source.constructor;
358
+ let body = parent.getValue(true);
359
+ if (!(body instanceof Source)) {
360
+ const previous = body;
361
+ body = new Source(null, parent.builder);
362
+ parent.builder.promoteNodeValue(parent, previous, body);
363
+ }
364
+ branch.parentBag.popNode(branch.label);
365
+ body.setItem(label, branch.getValue(true), {...branch.getAttr()}, '>', false, false,
366
+ 'editor', false, true, null, branch.nodeTag);
367
+ return body.getNode(label);
368
+ }
369
+ finishPaste(node) {
370
+ const path = node.GET('.insertion.parentPath');
371
+ const parent = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
372
+ if (!parent) throw new Error('The destination no longer exists');
373
+ const app = node.rootBuilder.binding.gramlot;
374
+ const source = app.src.prepareSource(node.GET('.insertion.clipboard'), parent.builder);
375
+ const branch = source.getNodes()[0];
376
+ const attrs = {...branch.getAttr()};
377
+ for (const [name, spec] of Object.entries(specifications(parent, branch.nodeTag))) {
378
+ if (!spec.required) continue;
379
+ const type = node.GET(`.insertion.types.${name}`);
380
+ const value = node.GET(`.insertion.parameters.${name}${spec.enum ? '' : type ? '.' + type : ''}`);
381
+ if (value != null) attrs[name] = value;
382
+ this.validateParameter(parent, null, name, spec, attrs[name]);
383
+ }
384
+ branch.setAttr(attrs, true, false, false);
385
+ const body = parent.getValue(true);
386
+ let label = branch.label, index = 1;
387
+ while (body instanceof node.builder.source.constructor && body.getNode(label)) label = `${branch.label}_${index++}`;
388
+ // Validate the prospective page, including duplicate IDs, before touching the live branch.
389
+ const design = node.builder.source.getNode(sourceRoot(node));
390
+ const candidate = app.src.prepareSource(design.getValue(true).toTytx(), design.builder);
391
+ const candidateParent = candidate.getNode(path);
392
+ candidateParent.builder.validateParent(branch.nodeTag, candidateParent.nodeTag);
393
+ const children = candidateParent.getValue(true);
394
+ candidateParent.builder.validateChildren(candidateParent.nodeTag, [...(children instanceof node.builder.source.constructor
395
+ ? children.getNodes().map(child => child.nodeTag) : []), branch.nodeTag]);
396
+ const inserted = this.appendBranch(candidateParent, branch, label);
397
+ app.src.renderer.validateCandidate(candidate, {replacingNode:design});
398
+ this.appendBranch(parent, inserted, label);
399
+ node.SET('.insertionOpen', false);
400
+ node.SET('.sourceSearch', '');
401
+ node.SET('.selection', `${path}.${label}`);
402
+ node.SET('.fileStatus', 'Branch pasted');
403
+ }
404
+
405
+ openCode(node) {
406
+ const editor = visualEditorScope(node);
407
+ editor.SET('.codeOpen', true);
408
+ editor.SET('.editingMode', 'code');
409
+ }
410
+ async codeSave(node) {
411
+ const editor = visualEditorScope(node), doc = editor.GET('.codeDocument');
412
+ if (doc.getItem('busy') || !doc.getItem('writable')) return;
413
+ const content = doc.getItem('content'), revision = doc.getItem('revision');
414
+ let saved = false;
415
+ if (content === doc.getItem('saved')) return;
416
+ const request = new AbortController();
417
+ const release = this.page.src.renderer.onDispose(editor, () => request.abort());
418
+ doc.setItem('busy', true); doc.setItem('status', 'Saving Page code…');
419
+ const design = editor.value.getNode('layout.center.design'), source = design.value.toTytx();
420
+ try {
421
+ const result = await this.page.rpc.call('data', 'editor_document_save', {
422
+ key:editor.getAttr('codeDocumentKey'), content, revision
423
+ }, {signal:request.signal});
424
+ if (request.signal.aborted) return;
425
+ doc.setItem('revision', result.revision); doc.setItem('saved', content); saved = true;
426
+ doc.setItem('status', 'Page code saved');
427
+ if (source !== design.value.toTytx()) {
428
+ doc.setItem('status', 'Page code saved; Source changed meanwhile. Use Preview saved to replace it.');
429
+ } else await this.codeLoadPreview(editor, request);
430
+ } catch (error) {
431
+ if (!request.signal.aborted) doc.setItem('status', `${saved ? 'Page code saved; preview failed' : 'Save failed'}: ${error.message}`);
432
+ } finally {
433
+ release();
434
+ if (!request.signal.aborted) doc.setItem('busy', false);
435
+ }
436
+ }
437
+ async codePreview(node) {
438
+ const editor = visualEditorScope(node), doc = editor.GET('.codeDocument');
439
+ if (doc.getItem('busy')) return;
440
+ const request = new AbortController();
441
+ const release = this.page.src.renderer.onDispose(editor, () => request.abort());
442
+ doc.setItem('busy', true);
443
+ try { await this.codeLoadPreview(editor, request); }
444
+ catch (error) { if (!request.signal.aborted) doc.setItem('status', `Preview failed: ${error.message}`); }
445
+ finally { release(); if (!request.signal.aborted) doc.setItem('busy', false); }
446
+ }
447
+ async codeLoadPreview(editor, request) {
448
+ const doc = editor.GET('.codeDocument'), design = editor.value.getNode('layout.center.design');
449
+ const before = design.value.toTytx();
450
+ const wire = await this.page.rpc.call('source', 'editor_document_preview', {
451
+ key:editor.getAttr('codeDocumentKey'), revision:doc.getItem('revision'), data_root:editor.GET('.dataRoot')
452
+ }, {signal:request.signal});
453
+ if (request.signal.aborted) return;
454
+ if (design.value.toTytx() !== before) throw new Error('Source changed while preparing preview; it was retained');
455
+ const candidate = this.page.src.prepareSource(wire, design.builder);
456
+ this.page.src.renderer.validateCandidate(candidate, {replacingNode:design});
457
+ if (editor.GET('.assistantRun')) editor.SET('.assistantRun.blocked', true);
458
+ editor.SET('.selection', null);
459
+ design.setValue(candidate, true, {_text:null}, true);
460
+ editor.SET('.selection', 'pageRoot');
461
+ doc.setItem('status', doc.getItem('content') === doc.getItem('saved') ? 'Saved Page code · preview updated' : 'Preview updated from saved page code; newer draft retained');
462
+ }
463
+ newPage(node) {
464
+ if (node.GET('.assistantRun')) node.SET('.assistantRun.blocked', true);
465
+ node.SET('.selection', null);
466
+ node.SET('.insertionOpen', false);
467
+ node.SET('.error', '');
468
+ const design = node.builder.source.getNode(sourceRoot(node));
469
+ design.getValue(true).clear();
470
+ const dataRoot = node.GET('.dataRoot');
471
+ if (dataRoot) node.SET(dataRoot, new Bag());
472
+ else for (const entry of node.rootBuilder.data.getNodes()) {
473
+ if (entry.label !== '__editor') node.rootBuilder.data.popNode(entry.label);
474
+ }
475
+ node.builder.wrapSource(design).div({node_label:'pageRoot', ...(dataRoot ? {datapath:dataRoot} : {})});
476
+ node.SET('.filename', 'page.grmlt');
477
+ node.SET('.fileStatus', '');
478
+ node.SET('.sourceSearch', '');
479
+ node.SET('.dataSearch', '');
480
+ node.SET('.selection', 'pageRoot');
481
+ }
482
+ async copySource(node) {
483
+ node.SET('.fileStatus', '');
484
+ try {
485
+ const page = node.builder.source.getNode(sourceRoot(node)).getValue(true);
486
+ await node.rootBuilder.binding.gramlot.utl.inout.copyText(page.toTytx());
487
+ node.SET('.fileStatus', 'Source copied');
488
+ } catch (error) { node.SET('.fileStatus', `Copy failed: ${error.message}`); }
489
+ }
490
+ downloadPage(node) {
491
+ const page = node.builder.source.getNode(sourceRoot(node)).getValue(true);
492
+ node.rootBuilder.binding.gramlot.utl.inout.saveText(page.toTytx(), node.GET('.filename'), 'application/json');
493
+ }
494
+
495
+ openUpload(node) { node.SET('.uploadOpen', true); }
496
+ sourceUploaded(node, {item, result}) {
497
+ try {
498
+ const app = node.rootBuilder.binding.gramlot;
499
+ const target = node.builder.source.getNode(sourceRoot(node));
500
+ const source = app.src.prepareSource(result, target.builder);
501
+ const roots = source.getNodes();
502
+ if (roots.length !== 1 || roots[0].label !== 'pageRoot') throw new Error('Expected one pageRoot Source');
503
+ app.src.renderer.validateCandidate(source, {replacingNode:target});
504
+ if (node.GET('.assistantRun')) node.SET('.assistantRun.blocked', true);
505
+ target.setValue(source, true, {_text:null}, true);
506
+ node.SET('.filename', item.value.getItem('name'));
507
+ node.SET('.selection', 'pageRoot');
508
+ node.SET('.fileStatus', 'Source opened');
509
+ node.SET('.uploadOpen', false);
510
+ } catch (error) {
511
+ node.SET('.fileStatus', `Open failed: ${error.message}`);
512
+ throw error;
513
+ }
514
+ }
515
+ toggleNavigation(node) { node.SET('.navigationOpen', node.GET('.navigationOpen') === 'close' ? true : 'close'); }
516
+ openCatalogue(node) { node.SET(`${editorData(node)}.catalogueOpen`, true); }
517
+ openProperties(node) { this.showProperties(node, {path:node.GET('.selection')}); }
518
+ sourceLabel(node, {item}) { return {text:`${item.label} [${item.nodeTag}]`}; }
519
+ dropNode(node, event) {
520
+ node.SET('.error', '');
521
+ try { this.applyDrop(node, event); }
522
+ catch (error) { node.SET('.error', error.message); }
523
+ }
524
+ insertWidget(node) {
525
+ node.SET('.error', '');
526
+ try { this.applyInsert(node); }
527
+ catch (error) { node.SET('.error', error.message); }
528
+ }
529
+ initializeEditorAppearance(node) {
530
+ const editor = visualEditorScope(node);
531
+ const document = node.rootBuilder.binding.renderer.destination.ownerDocument;
532
+ editor.SET('.appearanceProfile', 'compact');
533
+ editor.SET('.appearancePalette', 'joanna');
534
+ editor.SET('.appearanceMode', document.documentElement.getAttribute('data-theme') || 'dark');
535
+ }
536
+ applyEditorAppearance(node, {profile, palette, mode}) {
537
+ if (!profile || !palette || !mode) return;
538
+ if (!Object.hasOwn(appearanceStyles, profile) || !Object.hasOwn(paletteStyles, palette) || !['light','dark'].includes(mode))
539
+ throw new Error('Choose a declared theme, palette and color mode');
540
+ const editor = visualEditorScope(node);
541
+ editor.SET('.appearanceCss', appearanceStyles[profile] + '\n' + paletteStyles[palette]);
542
+ node.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute('data-theme', mode);
543
+ }
544
+ initializeEditor(node, {dataRoot}) {
545
+ node.SET('.editingMode', 'source');
546
+ node.SET('.clipboard', new Bag());
547
+ node.SET('.clipboardVisible', false);
548
+ node.SET('.clipboardDropEffect', 'move');
549
+ node.SET('.sourceDropEffect', 'move');
550
+ node.SET('.dataRoot', dataRoot);
551
+ node.SET('.filename', 'page.grmlt');
552
+ node.SET('.fileStatus', '');
553
+ node.SET('.selection', 'pageRoot');
554
+ if (dataRoot) {
555
+ if (node.GET(dataRoot) == null) node.SET(dataRoot, new Bag());
556
+ } else {
557
+ // Existing parent-path syntax gives the canvas the actual Data root.
558
+ // This context belongs to the editor, outside the exported page Source.
559
+ const context = editorData(node);
560
+ const parents = context.split('.').map(() => '#parent').join('.');
561
+ node.builder.source.getNode(sourceRoot(node)).setAttr({datapath:`${context}.${parents}`});
562
+ }
563
+ const catalogue = new Bag();
564
+ const groups = new Map([['', catalogue]]);
565
+ const ensureGroup = (path, caption) => {
566
+ if (groups.has(path)) return groups.get(path);
567
+ const segments = path.split('.'), label = segments.pop(), parentPath = segments.join('.');
568
+ const parent = ensureGroup(parentPath, sectionTitles[parentPath]);
569
+ const bag = new Bag();
570
+ parent.setItem(label, bag, {caption});
571
+ groups.set(path, bag);
572
+ return bag;
573
+ };
574
+ for (const [path, caption, tags] of catalogueSections) {
575
+ if (tags.split(' ').some(tag => node.builder.schema[tag])) ensureGroup(path, caption);
576
+ }
577
+ for (const [tag, info] of Object.entries(node.builder.schema).sort(([a], [b]) => a.localeCompare(b))) {
578
+ if (info._meta?.data_element || info._meta?.subbuilder || info._meta?.container) continue;
579
+ const root = info._meta?.gramlot_component ? 'components' : 'html';
580
+ const section = catalogueSections.find(([path, , tags]) => path.startsWith(root + '.') && tags.split(' ').includes(tag));
581
+ const path = section ? section[0] : `${root}.other`;
582
+ ensureGroup(path, section ? section[1] : 'Other elements').setItem(tag, null, {caption:tag, tag});
583
+ }
584
+ node.SET('.catalogue', catalogue);
585
+ }
586
+ prepareWidget(node, {item, dragValues}) {
587
+ node.SET('.sourceDropEffect', 'copy');
588
+ if (!item.attr.tag) return false;
589
+ dragValues['app/widget'] = {tag:item.attr.tag};
590
+ }
591
+ prepareSource(node, {path, dragValues}) {
592
+ node.SET('.sourceDropEffect', 'move');
593
+ dragValues['app/source'] = {path};
594
+ }
595
+ applyDrop(node, {item, path, dropValues}) {
596
+ if (dropValues['app/clipboard']) {
597
+ this.beginPaste(node, dropValues['app/clipboard'].path, path);
598
+ return;
599
+ }
600
+ if (dropValues['app/source']) {
601
+ const sourcePath = `${sourceRoot(node)}.${dropValues['app/source'].path}`;
602
+ const targetPath = `${sourceRoot(node)}.${path}`;
603
+ const moving = node.builder.source.getNode(sourcePath);
604
+ if (!moving || sourcePath === `${sourceRoot(node)}.pageRoot`) throw new Error('The page root cannot be moved');
605
+ if (moving.resolver) throw new Error('Resolver-backed Source nodes cannot be moved in this trial');
606
+ if (sourcePath === targetPath || targetPath.startsWith(sourcePath + '.')) throw new Error('A node cannot be moved into itself');
607
+ const parent = item, origin = moving.parentBag, Source = node.builder.source.constructor;
608
+ if (moving.builder !== parent.builder) throw new Error('Nodes cannot cross builder dialects');
609
+ const body = parent.getValue(true);
610
+ const children = body instanceof Source ? body.getNodes().filter(child => child !== moving) : [];
611
+ if (body instanceof Source && body !== origin && body.getNode(moving.label)) throw new Error('The target already contains this label');
612
+ const childSpecs = parent._getMeta('gramlot_component')?.childParameters ?? {};
613
+ for (const [name, spec] of Object.entries(childSpecs)) {
614
+ const value = moving.getAttr(name);
615
+ if (spec.required && value == null) throw new Error(`The moved node requires ${name}`);
616
+ if (spec.enum && value != null && !spec.enum.includes(value)) throw new Error(`Invalid ${name}`);
617
+ if (spec.unique && value != null && children.some(child => child.getAttr(name) === value)) throw new Error(`${name} is already in use`);
618
+ }
619
+ parent.builder.validateParent(moving.nodeTag, parent.nodeTag);
620
+ parent.builder.validateChildren(parent.nodeTag, [...children.map(child => child.nodeTag), moving.nodeTag]);
621
+ if (body === origin) origin.move(origin.getNodes().indexOf(moving), children.length);
622
+ else {
623
+ const destination = body instanceof Source ? body : new Source(null, parent.builder);
624
+ if (!(body instanceof Source)) parent.builder.promoteNodeValue(parent, body, destination);
625
+ const saved = {label:moving.label, tag:moving.nodeTag, value:moving.getValue(true), attrs:{...moving.getAttr()}};
626
+ origin.popNode(saved.label);
627
+ destination.setItem(saved.label, saved.value, saved.attrs, destination.getNodes().length,
628
+ false, false, 'editor', false, true, null, saved.tag);
629
+ }
630
+ node.SET('.selection', `${path}.${moving.label}`);
631
+ return;
632
+ }
633
+ const tag = dropValues['app/widget'].tag;
634
+ item.builder.validateParent(tag, item.nodeTag);
635
+ const body = item.getValue(true);
636
+ item.builder.validateChildren(item.nodeTag, [...(body instanceof node.builder.source.constructor ? body.getNodes().map(child => child.nodeTag) : []), tag]);
637
+ const entries = specifications(item, tag);
638
+ const required = Object.entries(entries).filter(([, spec]) => spec.required);
639
+ node.SET('.insertion', new Bag());
640
+ node.SET('.insertion.parentPath', path);
641
+ node.SET('.insertion.tag', tag);
642
+ if (!required.length) { this.applyInsert(node); return; }
643
+ const fields = editorField(node, 'InsertFields');
644
+ fields.getValue(true).clear();
645
+ const root = node.builder.wrapSource(fields);
646
+ root.p(`Insert ${tag} into ${item.label} [${item.nodeTag}]`, {class:'visual-editor-hint'});
647
+ const form = root.formlet({columns:2, gap:'8px 10px', lbl_position:'TL', box_c_width:'100%', align_items:'start'});
648
+ for (const [name, spec] of required) this.parameterField(node, form, tag, name, spec, 'insertion', spec.default);
649
+ node.SET('.insertionOpen', true);
650
+ }
651
+ showProperties(node, {path}) {
652
+ const fields = editorField(node, 'EditorFields');
653
+ fields.getValue(true).clear();
654
+ node.SET('.propertyError', '');
655
+ node.SET('.properties', new Bag());
656
+ if (!path) { node.SET('.propertiesOpen', false); return; }
657
+ const current = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
658
+ if (!current) { node.SET('.propertiesOpen', false); return; }
659
+ const parent = current.parentNode;
660
+ const entries = specifications(parent, current.nodeTag, current);
661
+ node.SET('.properties.path', path);
662
+ node.SET('.propertiesTitle', `${current.label} [${current.nodeTag}]`);
663
+ node.SET('.propertiesHeight', `${Math.min(340, 120 + Math.ceil(Object.keys(entries).filter(name => parameterTheme(name, new Set()) === 'general').length / 2) * 48)}px`);
664
+ const root = node.builder.wrapSource(fields);
665
+ if (path !== 'pageRoot') root.p(path, {class:'visual-editor-destination'});
666
+ const parentFields = new Set(Object.keys(parent._getMeta('gramlot_component')?.childParameters ?? {}));
667
+ const groups = new Map(parameterThemes.map(([key]) => [key, []]));
668
+ for (const entry of Object.entries(entries)) groups.get(parameterTheme(entry[0], parentFields)).push(entry);
669
+ node.SET('.parameterTab', parameterThemes.find(([key]) => groups.get(key).length)[0]);
670
+ const tabs = root.tabContainer({selectedPage:`^${editorData(node)}.parameterTab`, class:'visual-parameter-tabs',
671
+ tabMode:'underline', height:'100%', min_height:0, flex:1});
672
+ for (const [key, title] of parameterThemes) {
673
+ if (!groups.get(key).length) continue;
674
+ const panel = tabs.contentPane({pageName:key, title, overflow:'auto', padding:'10px', min_height:0});
675
+ if (key === 'container') panel.p(`Child parameters of ${parent.nodeTag}`, {class:'visual-editor-hint'});
676
+ if (key === 'behaviour' && Object.hasOwn(entries, 'action')) panel.p('action: use a named Logic method, for example openCatalogue.', {class:'visual-editor-hint'});
677
+ if (key === 'behaviour' && current.nodeTag === 'borderContainer') panel.p('persist remembers splitter sizes and requires a stable container id.', {class:'visual-editor-hint'});
678
+ const form = panel.formlet({columns:2, gap:'8px 10px', lbl_position:'TL', box_c_width:'100%', align_items:'start'});
679
+ if (key === 'general' && current._getMeta('gramlot_component')?.labelbox) {
680
+ this.labelboxFields(node, form, current, entries);
681
+ }
682
+ let advanced;
683
+ const fieldOrder = ([, spec]) => {
684
+ const types = Array.isArray(spec.dtype) ? spec.dtype : [spec.dtype];
685
+ if (!spec.enum && !types.some(type => editableTypes.includes(type))) return 2;
686
+ return spec.dtype === 'B' ? 1 : 0;
687
+ };
688
+ for (const [name, spec] of [...groups.get(key)].sort((a, b) => fieldOrder(a) - fieldOrder(b))) {
689
+ if (current._getMeta('gramlot_component')?.labelbox && /^(lbl|box)(_|$)/.test(name)) continue;
690
+ let target = form;
691
+ if (key === 'validation' && /(_if|_error|_warning|_iswarning)$/.test(name)) {
692
+ if (!advanced) {
693
+ const details = panel.details({class:'visual-validation-advanced'});
694
+ details.summary('Conditions and messages');
695
+ advanced = details.formlet({columns:2, gap:'8px 10px', lbl_position:'TL', box_c_width:'100%', align_items:'start'});
696
+ }
697
+ target = advanced;
698
+ }
699
+ const value = name === '_text' ? current.getValue(true) : current.getAttr(name);
700
+ this.parameterField(node, target, current.nodeTag, name, spec, 'properties', value ?? spec.default);
701
+ }
702
+ }
703
+ node.SET('.propertiesOpen', true);
704
+ }
705
+ toggleLabelboxAttributes(node, {prefix}) {
706
+ node.SET(`.properties.${prefix}Hidden`, !node.GET(`.properties.${prefix}Hidden`));
707
+ }
708
+ labelboxFields(node, form, current, entries) {
709
+ for (const prefix of ['lbl', 'box']) {
710
+ const title = prefix === 'lbl' ? 'Label' : 'Box';
711
+ const section = form.div({class:'visual-labelbox-section', grid_column:'1 / -1'});
712
+ const heading = section.div({class:'visual-labelbox-heading'});
713
+ if (prefix === 'lbl') this.parameterField(node, heading, current.nodeTag, 'lbl', entries.lbl,
714
+ 'properties', current.getAttr('lbl'));
715
+ else heading.span(title, {class:'visual-labelbox-title'});
716
+ heading.button({iconSrc:toolIcons.properties, title:`Edit ${title.toLowerCase()} attributes`,
717
+ 'aria-label':`Edit ${title.toLowerCase()} attributes`, class:'button--quiet',
718
+ action:'toggleLabelboxAttributes', prefix});
719
+ const choices = Object.entries(entries).filter(([name]) => name.startsWith(prefix + '_'));
720
+ node.SET(`.properties.${prefix}Hidden`, true);
721
+ node.SET(`.properties.${prefix}Attribute`, '');
722
+ const row = section.div({class:'visual-labelbox-attribute', hidden:`^${editorData(node)}.properties.${prefix}Hidden`});
723
+ const select = row.select({'aria-label':`${title} attribute`, value:`^${editorData(node)}.properties.${prefix}Attribute`});
724
+ select.option('Which attribute?', {value:''});
725
+ for (const [name] of choices) select.option(name.slice(prefix.length + 1), {value:name});
726
+ row.div({node_label:'attributeValue'}).span('');
727
+ row.dataController({func:'renderLabelboxAttribute', _init:true,
728
+ parameterName:`^${editorData(node)}.properties.${prefix}Attribute`, editingPath:node.GET('.properties.path')});
729
+ }
730
+ }
731
+ renderLabelboxAttribute(node, {parameterName, editingPath}) {
732
+ const target = node.parentBag.getNode('attributeValue');
733
+ target.getValue(true).clear();
734
+ if (!parameterName || editingPath !== node.GET('.selection')) return;
735
+ const current = node.builder.source.getNode(`${sourceRoot(node)}.${editingPath}`);
736
+ const spec = specifications(current.parentNode, current.nodeTag, current)[parameterName];
737
+ this.parameterField(node, node.builder.wrapSource(target), current.nodeTag, parameterName, spec,
738
+ 'properties', current.getAttr(parameterName) ?? spec.default, true);
739
+ }
740
+ parameterField(node, form, tag, name, spec, scope, value, compact = false) {
741
+ const label = name === 'lbl' ? 'Label' : name === '_text' && node.builder.schema[tag]._meta?.gramlot_component?.command ? 'caption' : name === '_text' ? 'Text' : name;
742
+ const parameterPath = `${editorData(node)}.${scope}.parameters.${name}`;
743
+ if (spec.enum) {
744
+ node.SET(parameterPath, value ?? '');
745
+ const select = form.select({lbl:compact ? null : label, lbl_position:'TL', value:`^${parameterPath}`, 'aria-label':name});
746
+ select.option('', {value:''});
747
+ for (const option of spec.enum) select.option(String(option), {value:option});
748
+ if (scope === 'properties') form.dataController({func:'changeProperty', value:`^${parameterPath}`,
749
+ _userChanges:true, parameterName:name, editingPath:node.GET('.properties.path')});
750
+ return;
751
+ }
752
+ const types = Array.isArray(spec.dtype) ? spec.dtype : spec.dtype ? [spec.dtype] : [];
753
+ const supported = types.filter(type => editableTypes.includes(type));
754
+ if (!supported.length) { form.p(`${label}: no editor is available for this declared type`, {class:'visual-editor-hint', grid_column:'1 / -1'}); return; }
755
+ let type = '';
756
+ if (value == null) type = supported.length === 1 ? supported[0] : '';
757
+ else if (typeof value === 'boolean' && supported.includes('B')) type = 'B';
758
+ else if (typeof value === 'string' && supported.includes('T')) type = 'T';
759
+ else if (typeof value === 'number') type = supported.find(code => ['L','R','N'].includes(code)) ?? '';
760
+ else if (value instanceof Date) type = supported.find(code => ['D','H'].includes(code)) ?? '';
761
+ else if (supported.length === 1 && supported[0] === 'N') type = 'N';
762
+ if (value != null && !type) { form.p(`${label}: the current value is not editable with these scalar types`, {class:'visual-editor-hint', grid_column:'1 / -1'}); return; }
763
+ node.SET(`${editorData(node)}.${scope}.types.${name}`, type);
764
+ for (const code of supported) node.SET(`${parameterPath}.${code}`, code === type ? value ?? null : null);
765
+ const wide = !compact && (types.length > 1 || /^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(name));
766
+ const row = form.div({class:'visual-parameter-field', grid_column:wide ? '1 / -1' : 'auto',
767
+ grid_template_columns:types.length > 1 ? 'minmax(100px, 1fr) minmax(0, 2fr)' : 'minmax(0, 1fr)', align_items:'start'});
768
+ if (types.length > 1) {
769
+ const choice = row.select({lbl:`${label} type`, lbl_position:'TL', value:`^${editorData(node)}.${scope}.types.${name}`, 'aria-label':`${name} type`});
770
+ choice.option('Not set', {value:''});
771
+ for (const code of types) choice.option(editableTypes.includes(code) ? code : `${code} (unavailable)`, {value:code, disabled:!editableTypes.includes(code)});
772
+ if (scope === 'properties') row.dataController({func:'changePropertyType', type:`^${editorData(node)}.${scope}.types.${name}`,
773
+ _userChanges:true, parameterName:name, editingPath:node.GET('.properties.path')});
774
+ }
775
+ row.div({node_label:'input'}).span('');
776
+ row.dataController({func:'renderParameterInput', _init:true, type:`^${editorData(node)}.${scope}.types.${name}`,
777
+ parameterName:name, parameterLabel:label, scope, compact, multiple:types.length > 1});
778
+ }
779
+ renderParameterInput(node, {type, parameterName, parameterLabel, scope, multiple, compact}) {
780
+ const target = node.parentBag.getNode('input');
781
+ target.getValue(true).clear();
782
+ if (!type) return;
783
+ const parent = node.builder.wrapSource(target);
784
+ const label = multiple ? `${parameterLabel} (${type})` : parameterLabel;
785
+ const binding = `^${editorData(node)}.${scope}.parameters.${parameterName}.${type}`;
786
+ const attrs = {lbl:compact ? null : label, lbl_position:'TL', value:binding, 'aria-label':label};
787
+ if (type === 'B') parent.checkbox(attrs);
788
+ else if (['L','R','N'].includes(type)) parent.numberTextBox({...attrs, dtype:type});
789
+ else if (type === 'D') parent.dateTextBox(attrs);
790
+ else if (type === 'H') parent.timeTextBox(attrs);
791
+ else if (type === 'T' && /^(lbl|box)_color$/.test(parameterName)) parent.colorpicker(attrs);
792
+ else if (type === 'T') parent.textbox(attrs);
793
+ else throw new Error(`No parameter editor for ${type}`);
794
+ if (scope === 'properties') parent.dataController({func:'changeProperty', value:binding, _userChanges:true,
795
+ parameterName, editingPath:node.GET('.properties.path')});
796
+ }
797
+ changePropertyType(node, {type, parameterName, editingPath}) {
798
+ this.changeProperty(node, {parameterName, editingPath, value:type ? node.GET(`.properties.parameters.${parameterName}.${type}`) : null});
799
+ }
800
+ changeProperty(node, {value, parameterName, editingPath}) {
801
+ if (editingPath !== node.GET('.selection')) return;
802
+ node.SET('.propertyError', '');
803
+ try {
804
+ const current = node.builder.source.getNode(`${sourceRoot(node)}.${editingPath}`);
805
+ if (!current) throw new Error('The selected Source node no longer exists');
806
+ const specs = specifications(current.parentNode, current.nodeTag, current);
807
+ const spec = specs[parameterName];
808
+ if (!spec) throw new Error(`Unknown parameter: ${parameterName}`);
809
+ this.validateParameter(current.parentNode, current, parameterName, spec, value);
810
+ if (parameterName === '_text') current.setValue(value ?? '');
811
+ else {
812
+ const attrs = {...current.getAttr()};
813
+ if (value == null || value === '') delete attrs[parameterName];
814
+ else attrs[parameterName] = value;
815
+ current.setAttr(attrs, true, false, false);
816
+ }
817
+ } catch (error) { node.SET('.propertyError', error.message); }
818
+ }
819
+ validateParameter(parent, current, name, spec, value) {
820
+ const empty = value == null || value === '';
821
+ if (spec.required && empty) throw new Error(`Choose ${name}`);
822
+ if (!empty && spec.enum && !spec.enum.includes(value)) throw new Error(`Invalid ${name}`);
823
+ const children = parent.getValue(true);
824
+ if (!empty && spec.unique && children instanceof parent.builder.source.constructor &&
825
+ children.getNodes().some(child => child !== current && child.getAttr(name) === value)) throw new Error(`${name} is already in use`);
826
+ }
827
+ applyInsert(node) {
828
+ if (node.GET('.insertion.clipboard')) { this.finishPaste(node); return; }
829
+ const path = node.GET('.insertion.parentPath');
830
+ const parent = node.builder.source.getNode(`${sourceRoot(node)}.${path}`);
831
+ if (!parent) throw new Error('The target Source node is no longer available');
832
+ const tag = node.GET('.insertion.tag');
833
+ const attrs = {};
834
+ for (const [name, spec] of Object.entries(specifications(parent, tag)).filter(([, spec]) => spec.required)) {
835
+ const type = node.GET(`.insertion.types.${name}`);
836
+ const value = node.GET(`.insertion.parameters.${name}${spec.enum ? '' : type ? '.' + type : ''}`);
837
+ this.validateParameter(parent, null, name, spec, value);
838
+ attrs[name] = value;
839
+ }
840
+ const created = parent.builder.commandOnNode(parent, tag, null, attrs);
841
+ node.SET('.insertionOpen', false);
842
+ node.SET('.selection', `${path}.${created.label}`);
843
+ }
844
+ }