@gramlot/gramlot 0.3.26 → 0.3.27

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 (71) hide show
  1. package/dist/components/chat/__init__.py +1 -1
  2. package/dist/components/chat/assets/collection.js +3 -3
  3. package/dist/components/chat/assets/index.js +1 -1
  4. package/dist/components/editors/__init__.py +1 -1
  5. package/dist/components/editors/assets/collection.js +16 -16
  6. package/dist/components/editors/assets/index.js +1 -1
  7. package/dist/components/grid/__init__.py +1 -1
  8. package/dist/components/grid/assets/collection.js +28 -19
  9. package/dist/components/grid/assets/index.js +1 -1
  10. package/dist/components/grid/grammar.json +21 -0
  11. package/dist/components/grouplets/__init__.py +1 -1
  12. package/dist/components/grouplets/assets/collection.js +2 -2
  13. package/dist/components/grouplets/assets/index.js +1 -1
  14. package/dist/components/inputs/__init__.py +1 -1
  15. package/dist/components/inputs/assets/collection.js +21 -21
  16. package/dist/components/inputs/assets/index.js +1 -1
  17. package/dist/components/layout/__init__.py +1 -1
  18. package/dist/components/layout/assets/collection.js +15 -15
  19. package/dist/components/layout/assets/index.js +1 -1
  20. package/dist/components/selection_trial/__init__.py +1 -1
  21. package/dist/components/selection_trial/assets/collection.js +3 -3
  22. package/dist/components/selection_trial/assets/index.js +1 -1
  23. package/dist/components/tree/__init__.py +1 -1
  24. package/dist/components/tree/assets/collection.js +11 -11
  25. package/dist/components/tree/assets/index.js +1 -1
  26. package/dist/components/typst/__init__.py +1 -1
  27. package/dist/components/typst/assets/collection.js +3 -3
  28. package/dist/components/typst/assets/index.js +1 -1
  29. package/dist/components/uploads/__init__.py +1 -1
  30. package/dist/components/uploads/assets/collection.js +8 -8
  31. package/dist/components/uploads/assets/index.js +1 -1
  32. package/dist/gramlot.js +624 -86
  33. package/dist/gramlot.min.js +47 -46
  34. package/package.json +1 -1
  35. package/src/binding/grid-struct.js +1 -1
  36. package/src/binding/validation-context.js +2 -1
  37. package/src/components/bases.js +5 -3
  38. package/src/components/choice-editor.js +28 -13
  39. package/src/components/database-choices.js +9 -6
  40. package/src/components/field-state.js +8 -1
  41. package/src/components/grid-cell-editor.js +83 -19
  42. package/src/components/grid-grammar.json +21 -0
  43. package/src/components/grid-structure.js +4 -1
  44. package/src/components/grid-styles.js +11 -2
  45. package/src/components/grid.js +16 -1
  46. package/src/components/inputs.js +2 -2
  47. package/src/components/parameters.js +6 -2
  48. package/src/components/tree.js +1 -0
  49. package/src/components/typed-editor.js +4 -4
  50. package/src/components/validation.js +1 -1
  51. package/src/editing-session.d.ts +1 -0
  52. package/src/editing-session.js +113 -15
  53. package/src/editor-values.js +57 -0
  54. package/src/gramlot.d.ts +1 -0
  55. package/src/gramlot.js +7 -4
  56. package/src/index.d.ts +1 -1
  57. package/src/renderer/gramlot-renderer.d.ts +1 -0
  58. package/src/renderer/gramlot-renderer.js +11 -0
  59. package/src/server/source-import.d.ts +1 -1
  60. package/src/server/source-import.js +5 -1
  61. package/src/server/visual-editor.d.ts +1 -1
  62. package/src/server/visual-editor.js +30 -20
  63. package/src/source-picker.d.ts +1 -1
  64. package/src/source-picker.js +1 -2
  65. package/src/visual-editor-canvas.js +29 -0
  66. package/src/visual-editor-catalogue.js +34 -0
  67. package/src/visual-editor.d.ts +5 -0
  68. package/src/visual-editor.js +244 -26
  69. package/themes/gramlot-base/theme.css +78 -36
  70. package/tools/gramlot-tools-inspector.js +1 -1
  71. package/tools/inspector-agent.js +1 -1
@@ -28,6 +28,11 @@ export class EditingSession {
28
28
  this.retainedFields = new Map();
29
29
  this.listeners = new Set();
30
30
  this.navigators = new Set();
31
+ this.validationSources = new Set();
32
+ this.validationDependencies = new Map();
33
+ this.validationRevision = 0;
34
+ this.validatedRevision = -1;
35
+ this.fullValidation = null;
31
36
  if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
32
37
  this.registers.setItem('baseline', copy(this.data));
33
38
  for (const name of ['changes', 'errors', 'pending', 'drafts']) this.registers.setItem(name, new Bag());
@@ -113,7 +118,7 @@ export class EditingSession {
113
118
  }
114
119
  get status() {
115
120
  const dirty = this.registers.getItem('changes').length > 0;
116
- const pending = this.registers.getItem('pending').length > 0;
121
+ const pending = this.fullValidation !== null || this.registers.getItem('pending').length > 0;
117
122
  const invalid = this.registers.getItem('errors').length > 0;
118
123
  const incomplete = this.registers.getItem('drafts').length > 0;
119
124
  return {dirty, pending, valid:!invalid && !incomplete, canSave:dirty && !invalid && !incomplete && !pending,
@@ -122,15 +127,8 @@ export class EditingSession {
122
127
  register(adapter) {
123
128
  const node = adapter.node;
124
129
  this.fields.set(node, adapter);
125
- let field = this.validations.get(node);
126
- if (!field) {
127
- field = {node, binding:adapter.binding, context:validationContext(adapter.binding), run:new ValidationRun(),
128
- execute:adapter.element.validationExecutor, checkValue:adapter.element.validationValueCheck(), path:fieldPath(node), rules:null, value:undefined, target:null, result:null, selection:adapter.element.validationSelection()};
129
- this.validations.set(node,field);
130
- adapter.binding.editingSession = this;
131
- field.release = adapter.binding.track(() => this.forgetField(node));
132
- this.refreshField(node);
133
- }
130
+ const field = this.registerField(node,adapter.element.constructor);
131
+ field.selection = adapter.element.validationSelection();
134
132
  this.schedule(() => {
135
133
  if (this.fields.get(node) !== adapter) return;
136
134
  const draft = this.registers.getItem('drafts').getNode(key(node));
@@ -142,6 +140,96 @@ export class EditingSession {
142
140
  });
143
141
  return () => { this.fields.delete(node); };
144
142
  }
143
+ /** A real Source declaration can validate without an element or ControlAdapter. */
144
+ registerField(node, component, schedule = true) {
145
+ let field = this.validations.get(node);
146
+ if (field) return field;
147
+ if (!component.validationExecutor) throw new TypeError('Grid editors require shared input validation.');
148
+ const binding = this.runtime.bindingFor(node), context = validationContext(binding);
149
+ field = {node,binding,context,component,run:new ValidationRun(),
150
+ execute:component.validationExecutor,checkValue:component.validationValueCheck(context),
151
+ path:fieldPath(node),rules:null,value:undefined,target:null,result:null,selection:null};
152
+ this.validations.set(node,field);
153
+ binding.editingSession = this;
154
+ field.release = binding.track(() => this.forgetField(node));
155
+ this.refreshField(node,schedule);
156
+ return field;
157
+ }
158
+ registerValidationSource(fields) {
159
+ this.validationSources.add(fields);
160
+ this.invalidateValidation();
161
+ return () => { this.validationSources.delete(fields); this.invalidateValidation(); };
162
+ }
163
+ invalidateValidation() {
164
+ this.validationRevision++;
165
+ if (this.fullValidation) for (const node of this.fullValidation.active) this.cancelValidation(node);
166
+ }
167
+ trackValidationDependency(absolute) {
168
+ if (absolute === null || this.validationDependencies.has(absolute)) return;
169
+ const [path,attr = null] = absolute.split('?',2);
170
+ this.validationDependencies.set(absolute,this.runtime.router.register({path,attr,subtree:true,
171
+ recipient:{receive:() => this.invalidateValidation()}}));
172
+ }
173
+ clearValidationDependencies() {
174
+ for (const registration of this.validationDependencies.values()) registration.close();
175
+ this.validationDependencies.clear();
176
+ }
177
+ /** Validate the complete declared scope. Bounded work keeps remote checks and UI responsive. */
178
+ validate() {
179
+ if (this.disposed) return Promise.resolve(false);
180
+ if (this.fullValidation) return this.fullValidation.promise;
181
+ for (const adapter of this.fields.values()) if (Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
182
+ this.clearValidationDependencies();
183
+ const pass = {revision:this.validationRevision,promise:null,active:new Set(),failed:false,complete:true};
184
+ this.fullValidation = pass;
185
+ this.notify();
186
+ const fields = this.validationFields();
187
+ const current = () => !this.disposed && !pass.failed && pass.revision === this.validationRevision;
188
+ const seen = new WeakSet();
189
+ const worker = async () => {
190
+ let count = 0;
191
+ while (current()) {
192
+ const next = fields.next();
193
+ if (next.done) return;
194
+ const {node,release} = next.value;
195
+ try {
196
+ if (seen.has(node)) continue;
197
+ seen.add(node);
198
+ for (const [name,pointer] of node.pointers()) if (name !== 'value') {
199
+ this.trackValidationDependency((name === 'datapath' ? node.parentNode : node).absDatapath(pointer));
200
+ }
201
+ pass.active.add(node);
202
+ const outcome = await this.validateField(node);
203
+ if (!outcome?.ok) pass.complete = false;
204
+ } finally { pass.active.delete(node); release(); }
205
+ if (++count % 20 === 0) await new Promise(resolve => setTimeout(resolve,0));
206
+ }
207
+ };
208
+ pass.promise = Promise.resolve().then(async () => {
209
+ const outcomes = await Promise.allSettled(Array.from({length:8},() => worker().catch(error => {
210
+ pass.failed = true;
211
+ for (const node of pass.active) this.cancelValidation(node);
212
+ throw error;
213
+ })));
214
+ const failure = outcomes.find(outcome => outcome.status === 'rejected');
215
+ if (failure) throw failure.reason;
216
+ if (!current()) return false;
217
+ // fullValidation itself is pending until finally; inspect field registers here.
218
+ const valid = pass.complete && this.status.valid && this.registers.getItem('pending').length === 0;
219
+ if (valid) this.validatedRevision = this.validationRevision;
220
+ return valid;
221
+ }).finally(() => {
222
+ fields.return();
223
+ this.fullValidation = null;
224
+ this.notify();
225
+ });
226
+ return pass.promise;
227
+ }
228
+ *validationFields() {
229
+ const existing = [...this.validations.keys()];
230
+ for (const fields of this.validationSources) yield* fields();
231
+ for (const node of existing) if (this.validations.has(node)) yield {node,release:() => {}};
232
+ }
145
233
  forgetField(node) {
146
234
  const field = this.validations.get(node);
147
235
  if (!field) return;
@@ -162,16 +250,18 @@ export class EditingSession {
162
250
  delete node.formDraft;
163
251
  this.notify();
164
252
  }
165
- refreshField(node) {
253
+ refreshField(node, schedule = true) {
166
254
  const field = this.validations.get(node);
167
255
  if (!field || this.disposed || this.writing) return;
168
256
  const [, attrs] = node.rootBuilder.runtimeValues(node);
169
- const resolved = this.runtime.renderer.evaluateExpressions(node,attrs);
257
+ const resolved = field.component.validationParameters(this.runtime.renderer.evaluateExpressions(node,attrs));
170
258
  const rules = Object.fromEntries(Object.entries(resolved).filter(([name]) => name.startsWith('validate_')));
259
+ const configuration = toTytx(Object.fromEntries(Object.entries(resolved).filter(([name]) => name !== 'value')));
171
260
  const path = fieldPath(node), target = this.runtime.gramlot.data.getNode(path.split('?')[0]);
172
261
  const value = node.getRelativeData(node.getAttr('value'));
173
262
  const dataChanged = field.path !== path || field.target !== target || !same(field.value,value);
174
- if (!dataChanged && same(field.rules,rules)) return;
263
+ if (!dataChanged && field.configuration === configuration) return;
264
+ if (field.rules !== null) this.invalidateValidation();
175
265
  this.cancelValidation(node);
176
266
  if (field.path !== path) {
177
267
  for (const name of ['errors','pending','drafts']) {
@@ -179,9 +269,10 @@ export class EditingSession {
179
269
  if (bag.getNode(encoded(field.path))) bag.popNode(encoded(field.path));
180
270
  }
181
271
  }
182
- Object.assign(field,{path,target,value,rules,result:null});
272
+ Object.assign(field,{path,target,value,rules,configuration,result:null,
273
+ selection:field.component.validationSelection(resolved,field.context)});
183
274
  if (dataChanged) this.clearDraft(node);
184
- this.scheduleField(node);
275
+ if (schedule) this.scheduleField(node);
185
276
  }
186
277
  cancelValidation(node) {
187
278
  this.validations.get(node)?.run.cancel();
@@ -201,6 +292,7 @@ export class EditingSession {
201
292
  for (const other of this.validations.keys()) if (other !== node) this.refreshField(other);
202
293
  }
203
294
  validateCandidate(node,value,selection) {
295
+ this.invalidateValidation();
204
296
  this.cancelValidation(node);
205
297
  this.writeCandidate(node,value);
206
298
  const field = this.validations.get(node);
@@ -261,6 +353,7 @@ export class EditingSession {
261
353
  this.notify();
262
354
  }
263
355
  draft(node, text) {
356
+ this.invalidateValidation();
264
357
  this.cancelValidation(node);
265
358
  node.formDraft = text;
266
359
  this.set('drafts',node,text);
@@ -296,6 +389,7 @@ export class EditingSession {
296
389
  if (this.disposed) return;
297
390
  this.updateChanges(change.path);
298
391
  if (this.writing) return;
392
+ this.invalidateValidation();
299
393
  for (const node of this.validations.keys()) this.refreshField(node);
300
394
  }
301
395
 
@@ -358,6 +452,7 @@ export class EditingSession {
358
452
  if (Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
359
453
  }
360
454
  if (!this.status.valid || this.status.pending) return false;
455
+ if (this.validationSources.size && this.validatedRevision !== this.validationRevision) return false;
361
456
  this.registers.setItem('baseline',copy(this.data));
362
457
  this.updateChanges();
363
458
  return true;
@@ -370,6 +465,7 @@ export class EditingSession {
370
465
  }
371
466
  restore() {
372
467
  if (this.disposed) return;
468
+ this.invalidateValidation();
373
469
  for (const node of this.validations.keys()) this.cancelValidation(node);
374
470
  for (const adapter of this.fields.values()) {
375
471
  adapter.element.cancelValidation();
@@ -392,5 +488,7 @@ export class EditingSession {
392
488
  this.retainedFields.clear();
393
489
  this.listeners.clear();
394
490
  this.navigators.clear();
491
+ this.validationSources.clear();
492
+ this.clearValidationDependencies();
395
493
  }
396
494
  }
@@ -0,0 +1,57 @@
1
+ /** Scalar editor contract. Containers and unsupported objects remain inspectable. */
2
+ export const editorTypes = ['string', 'number', 'integer', 'boolean', 'date', 'time', 'datetime', 'null'];
3
+
4
+ export function scalarType(value) {
5
+ if (value === null) return 'null';
6
+ if (['string', 'boolean'].includes(typeof value)) return typeof value;
7
+ if (typeof value === 'number' && Number.isFinite(value)) return Number.isSafeInteger(value) ? 'integer' : 'number';
8
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
9
+ const iso = value.toISOString();
10
+ return iso.slice(0, 10) === '1970-01-01' ? 'time' : iso.endsWith('T00:00:00.000Z') ? 'date' : 'datetime';
11
+ }
12
+ return null;
13
+ }
14
+
15
+ export function scalarText(value, type) {
16
+ if (type === 'null') return '';
17
+ if (value instanceof Date) {
18
+ const iso = value.toISOString();
19
+ return type === 'date' ? iso.slice(0, 10) : type === 'time' ? iso.slice(11, 23) : iso;
20
+ }
21
+ return String(value);
22
+ }
23
+
24
+ export function parseScalar(type, text) {
25
+ if (type === 'string') return text;
26
+ if (type === 'null') return null;
27
+ if (type === 'boolean' && ['true', 'false'].includes(text)) return text === 'true';
28
+ if (type === 'number' || type === 'integer') {
29
+ if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text.trim())) {
30
+ const value = Number(text);
31
+ if (Number.isFinite(value) && (type !== 'integer' || Number.isSafeInteger(value))) return value;
32
+ }
33
+ }
34
+ if (['date', 'time', 'datetime'].includes(type)) {
35
+ const pattern = type === 'date' ? /^\d{4}-\d{2}-\d{2}$/
36
+ : type === 'time' ? /^\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/
37
+ : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/;
38
+ if (pattern.test(text)) {
39
+ const input = type === 'date' ? `${text}T00:00:00Z` : type === 'time' ? `1970-01-01T${text}Z` : text;
40
+ const date = new Date(input);
41
+ if (Number.isFinite(date.getTime())) {
42
+ // Reject Date's normalization of invalid calendar dates and 24:00.
43
+ const iso = date.toISOString();
44
+ const supplied = input.replace(/Z$/, '').split(/[T:.]/);
45
+ const actual = iso.replace(/Z$/, '').split(/[T:.]/);
46
+ if (supplied.every((part, index) => index === 4 ? Number(part.padEnd(3, '0')) === Number(actual[index]) : part === actual[index])) return date;
47
+ }
48
+ }
49
+ }
50
+ throw new Error(`Invalid ${type} value: ${text || '(empty)'}`);
51
+ }
52
+
53
+ /** Read the portable component contract from a real Source node. */
54
+ export function readParameterEnums(node) {
55
+ return Object.fromEntries(Object.entries(node._getMeta('gramlot_component')?.parameters ?? {})
56
+ .filter(([, spec]) => spec.enum).map(([name, spec]) => [name, spec.enum]));
57
+ }
package/src/gramlot.d.ts CHANGED
@@ -117,6 +117,7 @@ export class Gramlot {
117
117
  publish(topic: {topic: string; server: true; pageId?: string}, payload?: Record<string, unknown>): Promise<'ok'>;
118
118
  publish(topic: Publication, payload?: Record<string, unknown>): void | Promise<'ok'>;
119
119
  /** Subscribe to a local page topic, synchronously in registration order. */
120
+ registerDocument(document:Document):void;
120
121
  subscribe(topic: string, callback: (payload: Record<string, unknown>, metadata: {pageId?: string}) => unknown): SubscriptionHandle;
121
122
  /** Remove a registration; repeating removal of an owned handle is harmless. */
122
123
  unsubscribe(registration: SubscriptionHandle): void;
package/src/gramlot.js CHANGED
@@ -28,14 +28,13 @@ import {formatValue} from './format.js';
28
28
  */
29
29
  export class Gramlot {
30
30
  #mobileEnvironment;
31
+ #collections;
31
32
  constructor({pageId, uploadUrl = null, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
32
33
  element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = [],
33
34
  locale = null, timeZone = null, devices = [], serverAdapter = new ServerAdapter(), nameSyntax = null,
34
35
  websocketUrl = null} = {}) {
35
- buttons.register(document.defaultView);
36
- for (const collection of collections) {
37
- if (collection instanceof ComponentCollection) collection.register(document.defaultView);
38
- }
36
+ this.#collections = [buttons, ...collections.filter(collection => collection instanceof ComponentCollection)];
37
+ this.registerDocument(document);
39
38
  this.commands = new CommandRegistry();
40
39
  this.pageId = pageId;
41
40
  this.uploadUrl = uploadUrl;
@@ -68,6 +67,10 @@ export class Gramlot {
68
67
  }
69
68
  }
70
69
  publish(topic, payload = {}) { return this._subscriptions.publish(topic, payload); }
70
+ /** Register this page's activated collections in an additional rendering realm. */
71
+ registerDocument(document) {
72
+ for (const collection of this.#collections) collection.register(document.defaultView);
73
+ }
71
74
  subscribe(topic, callback) { return this._subscriptions.subscribe(topic, callback); }
72
75
  unsubscribe(registration) { this._subscriptions.unsubscribe(registration); }
73
76
  format(value, options) { return formatValue(value, options, {locale: this.locale, timeZone: this.timeZone}); }
package/src/index.d.ts CHANGED
@@ -52,7 +52,7 @@ export {collectionBuildId, verifyCollectionArtifact} from './collection-artifact
52
52
 
53
53
  export {DeviceHandler} from './handlers/device-handler.js';
54
54
  export {BrowserCameraProvider} from './browser-camera-provider.js';
55
- export type {DeviceProvider, DeviceClipboard, DeviceName, DeviceAudio, DeviceAudioSession, DeviceNetwork, DeviceLifecycleEvent, DeviceHapticStyle, AppInfo, DeviceLocation, DevicePhoto, DeviceBarcode, DeviceBiometrics, DeviceNotificationRequest, DeviceNotificationSchedule, DeviceNotificationEvent, DevicePushRegistration, DevicePushEvent, DeviceShortcutRequest, DeviceLinkRequest} from './handlers/device-handler.js';
55
+ export type {DeviceDatabase, DeviceOrientation, DeviceMotionEvent, DeviceProvider, DeviceClipboard, DeviceName, DeviceAudio, DeviceAudioSession, DeviceNetwork, DeviceLifecycleEvent, DeviceHapticStyle, AppInfo, DeviceLocation, DevicePhoto, DeviceBarcode, DeviceBiometrics, DeviceNotificationRequest, DeviceNotificationSchedule, DeviceNotificationEvent, DevicePushRegistration, DevicePushEvent, DeviceShortcutRequest, DeviceLinkRequest} from './handlers/device-handler.js';
56
56
 
57
57
  export {MobileEnvironment} from './mobile-environment.js';
58
58
 
@@ -88,6 +88,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
88
88
  end?: DomNode;
89
89
  };
90
90
  /** Set the container of a render record and of its children. */
91
+ mountDestination(node:SourceBagNode, destination:DomElement):unknown;
91
92
  assignContainer(record: unknown, container: DomNode): void;
92
93
  /** Apply a Source update event to the DOM of a node. */
93
94
  update(node: SourceBagNode, event: string): void;
@@ -524,6 +524,17 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
524
524
  throw errors.length === 1 ? error : new AggregateError(errors, 'Source build and cleanup failed');
525
525
  }
526
526
 
527
+ /** Mount the same Source and bindings in a new document's element realm. */
528
+ mountDestination(node, destination) {
529
+ const record = this.records.get(node);
530
+ if (!record?.presentation || destination?.nodeType !== 1)
531
+ throw new TypeError('mountDestination requires a mounted element and an HTML destination');
532
+ if (record.presentation.contains(destination)) throw new Error('Destination cannot be inside the moved presentation');
533
+ const parent = record.parent;
534
+ this.remove(node);
535
+ return this.buildNode(node, destination, null, parent);
536
+ }
537
+
527
538
  assignContainer(record, container) {
528
539
  record.container = container;
529
540
  const childContainer = record.element ?? container;
@@ -1,2 +1,2 @@
1
1
  import {UploadTarget} from './upload.js';
2
- export class SourceImport extends UploadTarget { constructor(); }
2
+ export class SourceImport extends UploadTarget { constructor(options?:{catalogue?:"html"|string[]}); }
@@ -1,9 +1,12 @@
1
+ import {validateCatalogue, validateCatalogueSource} from '../visual-editor-catalogue.js';
1
2
  import {fromTytx} from '@genrojs/tytx';
2
3
  import {SourceBag} from '@genrojs/builders';
3
4
  import {UploadTarget} from './upload.js';
4
5
  export class SourceImport extends UploadTarget {
5
- constructor() {
6
+ constructor({catalogue = null} = {}) {
6
7
  super({maxBytes:5 * 1024 * 1024});
8
+ validateCatalogue(catalogue);
9
+ this.catalogue = catalogue;
7
10
  this.decoder = new TextDecoder('utf-8', {fatal:true});
8
11
  this.parts = [];
9
12
  this.outcome = {state:'pending'};
@@ -17,6 +20,7 @@ export class SourceImport extends UploadTarget {
17
20
  if (!(source instanceof SourceBag) || source.length !== 1 || source.getNodes()[0].label !== 'pageRoot') {
18
21
  throw new TypeError('Expected one pageRoot Source');
19
22
  }
23
+ validateCatalogueSource(this.catalogue, source);
20
24
  this.outcome = {state:'completed', result:wire};
21
25
  return this.outcome;
22
26
  }
@@ -1,7 +1,7 @@
1
1
  import type {SourceBagNode} from '@genrojs/builders';
2
2
  export interface PageCodeDocument {language:'python'|'javascript'; key:string; path:string; content:string; revision:string; writable:boolean;}
3
3
  export class VisualEditor {
4
- constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; [attribute:string]:unknown});
4
+ constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; catalogue?:"html"|string[]; fileCommands?:boolean; canvasCss?:string[]; [attribute:string]:unknown});
5
5
  pane:SourceBagNode;
6
6
  frame:SourceBagNode;
7
7
  toolbar:SourceBagNode;
@@ -1,17 +1,24 @@
1
+ import {validateCatalogue} from '../visual-editor-catalogue.js';
1
2
  import {Bag} from '@genrojs/bag';
2
3
  import {sourceTarget} from '@genrojs/builders';
3
4
  import {toolIcons} from '../visual-editor-icons.js';
4
5
 
5
6
  export class VisualEditor {
6
- constructor(root, {datapath = '__editor', dataRoot = '', editorId = 'visual', uploadOperation = 'import_source', codeDocument = null, ...attributes} = {}) {
7
+ constructor(root, {datapath = '__editor', dataRoot = '', editorId = 'visual', uploadOperation = 'import_source', codeDocument = null, catalogue = null, fileCommands = true, canvasCss = null, ...attributes} = {}) {
7
8
  if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(editorId)) throw new Error('editorId must be a literal identifier');
8
9
  if (!dataRoot && datapath !== '__editor' && !datapath.startsWith('__editor.')) throw new Error('Root Data editing requires an __editor datapath');
10
+ validateCatalogue(catalogue);
11
+ if (canvasCss != null && (!Array.isArray(canvasCss) || canvasCss.some(text => typeof text !== 'string')))
12
+ throw new TypeError('canvasCss must be a list of CSS texts');
9
13
  this.dataRoot = dataRoot;
10
14
  const pane = this.pane = root.main({node_label:editorId, datapath, visualEditorId:editorId, ...attributes, nodeId:`${editorId}Editor`, class:`visual-editor-shell ${attributes.class ?? ''}`, overflow:'hidden', tabindex:0, connect_onkeydown:'clipboardShortcut'});
15
+ pane.dataSetter({destination_path:'.catalogueScope', value:catalogue});
16
+ pane.dataSetter({destination_path:'.canvasCss', value:canvasCss});
11
17
  pane.dataSetter({destination_path:'.uploadQueue', value:new Bag()});
12
18
  pane.dataController({func:'initializeEditor', dataRoot:this.dataRoot, _init:true});
13
19
  pane.dataController({func:'showProperties', path:'^.selection', _init:true});
14
20
  pane.dataController({func:'initializeCanvasSelection', _onBuilt:true});
21
+ pane.dataController({func:'initializeDocument', _onBuilt:true});
15
22
  pane.dataController({func:'highlightSelection', path:'^.selection', _init:true});
16
23
  pane.style('^.appearanceCss');
17
24
  pane.dataController({func:'initializeEditorAppearance', _onBuilt:true});
@@ -20,14 +27,16 @@ export class VisualEditor {
20
27
  this.toolButton(rail.menuline({group:true, overflowable:false}), 'Source / Data', 'toggleNavigation', toolIcons.navigation);
21
28
  this.toolButton(rail.menuline({group:true, overflowable:false}), 'Catalogue', 'openCatalogue', toolIcons.catalogue);
22
29
  this.toolButton(rail.menuline({group:true, overflowable:false}), 'Properties', 'openProperties', toolIcons.properties);
23
- this.toolButton(rail.menuline({group:true, overflowable:false}), 'Clipboard', "this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))", toolIcons.paste);
30
+ this.toolButton(rail.menuline({group:true, overflowable:false}), 'Clipboard', "this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))", toolIcons.paste,
31
+ {dropTarget:true, dropTypes:'app/source', dropTags:`${editorId}Source`, dropEffect:'^.clipboardDropEffect',
32
+ connect_ondragover:'clipboardModifiers', connect_ondrop:'clipboardModifiers', onDrop:'dropClipboard'});
24
33
  rail.spacer({flex:1});
25
34
  this.toolButton(rail.menuline({group:true, overflowable:false}), 'Appearance', "this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))", toolIcons.appearance);
26
35
  const layoutRoot = pane.framePane({node_label:'layout', height:'100%', id:`${editorId}-editor-frame`, class:'visual-editor-layout'});
27
- layoutRoot.top.setAttr({height:'38px'});
36
+ layoutRoot.top.setAttr({height:'30px'});
28
37
  const toolbar = layoutRoot.top.menu({presentation:'bar', aria_label:'Editor tools', class:'visual-editor-toolbar'});
29
38
  toolbar.menuline({group:true, overflowable:false}).span('Source editor', {class:'visual-editor-brand'});
30
- const files = toolbar.menuline({group:true, overflowable:false, gap:'4px'});
39
+ const files = toolbar.menuline({group:true, overflowable:false, gap:'4px', hidden:!fileCommands});
31
40
  for (const [caption,action,icon] of [['New','newPage','new'],['Open','openUpload','open'],['Download','downloadPage','download'],['Copy Source','copySource','copy']])
32
41
  this.toolButton(files,caption,action,toolIcons[icon],{id:`${editorId}-${icon}`});
33
42
  toolbar.menuline({group:true, overflowable:false}).span({class:'visual-toolbar-divider', aria_hidden:'true'});
@@ -36,10 +45,11 @@ export class VisualEditor {
36
45
  this.toolButton(edit,'Copy branch','copyBranch',toolIcons.copy);
37
46
  this.toolButton(edit,'Paste branch','pasteBranch',toolIcons.paste,{title:'Paste branch (F9)'});
38
47
  toolbar.spacer({flex:1});
48
+ toolbar.menuline({group:true, overflowable:false, hidden:'^.modified:=!{}'}).span('Unsaved changes', {role:'status', class:'visual-editor-hint'});
39
49
  toolbar.menuline({group:true, overflowable:false}).span('^.fileStatus', {role:'status', class:'visual-editor-file-status'});
40
50
  toolbar.menuline({group:true, overflowable:false}).span('^.filename', {class:'visual-editor-filename'});
41
51
  const left = layoutRoot.left;
42
- left.setAttr({width:'min(260px, 34vw)', splitter:true,
52
+ left.setAttr({width:'min(240px, 34vw)', splitter:true,
43
53
  drawer:'^.navigationOpen', default_drawer:true, drawer_label:'Source / Data',
44
54
  drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",
45
55
  display:'flex', flex_direction:'column', min_height:0, class:'visual-editor-sidebar'});
@@ -69,36 +79,36 @@ export class VisualEditor {
69
79
  center.setAttr({overflow:'auto', class:'visual-editor-workspace'});
70
80
  const design = center.div({node_label:'design', class:'visual-editor-canvas'});
71
81
  design.div({node_label:'pageRoot', ...(this.dataRoot ? {datapath:this.dataRoot} : {})});
72
- const window = pane.floatingPane({title:'Widget catalogue', open:'^.catalogueOpen', default_open:false, width:'320px', height:'480px', movable:true, resizable:true});
82
+ const window = pane.floatingPane({title:'Widget catalogue', open:'^.catalogueOpen', default_open:false, width:'280px', height:'400px', class:'visual-editor-popup', movable:true, resizable:true});
73
83
  this.search(window.frame.top, 'catalogueSearch', 'Search widgets');
74
84
  window.frame.center.tree({storepath:'.catalogue', hideValues:true, labelAttribute:'caption', searchText:'^.catalogueSearch',
75
85
  draggable:true, dragTags:'widget', effectAllowed:'all', onDrag:'prepareWidget', id:`${editorId}-widget-tree`});
76
- const properties = sidebar.contentPane({region:'bottom', height:'^.propertiesHeight', default_height:'240px', minSize:140, splitter:true,
86
+ const properties = sidebar.contentPane({region:'bottom', height:'^.propertiesHeight', default_height:'200px', minSize:140, splitter:true,
77
87
  title:'^.propertiesTitle', detachable:true, hidden:'^.propertiesOpen:=!{}',
78
88
  display:'flex', flex_direction:'column', overflow:'hidden', min_height:0});
79
89
  properties.div({nodeId:`${editorId}EditorFields`, class:'visual-editor-fields', display:'flex', flex_direction:'column', flex:1, min_height:0}).span('');
80
- properties.p('^.propertyError', {role:'alert', class:'visual-editor-hint', margin:'8px'});
81
- const uploader = pane.dialog({title:'Open Source', open:'^.uploadOpen', width:'480px', height:'300px', movable:true, resizable:true});
90
+ properties.p('^.propertyError', {role:'alert', class:'visual-editor-hint', margin:'3px'});
91
+ const uploader = pane.dialog({class:'visual-editor-popup', title:'Open Source', open:'^.uploadOpen', width:'480px', height:'300px', movable:true, resizable:true});
82
92
  uploader.frame.center.uploader({operation:uploadOperation, storepath:'.uploadQueue', accept:'.grmlt',
83
93
  multiple:false, autoUpload:true, onComplete:'sourceUploaded', id:`${editorId}-uploader`});
84
- const naming = pane.dialog({title:'Save branch to clipboard', open:'^.clipboardOpen', width:'380px', height:'210px'});
94
+ const naming = pane.dialog({class:'visual-editor-popup', title:'Save branch to clipboard', open:'^.clipboardOpen', width:'380px', height:'210px'});
85
95
  naming.frame.center.textbox({value:'^.clipboardDraft.name', lbl:'Name', margin:'12px'});
86
96
  naming.frame.center.p('^.error', {role:'alert', margin:'12px'});
87
- const namingBar = naming.frame.bottom.menu({presentation:'bar', aria_label:'Clipboard commands', padding:'8px 12px'});
97
+ const namingBar = naming.frame.bottom.menu({presentation:'bar', aria_label:'Clipboard commands', padding:'3px 6px'});
88
98
  namingBar.spacer({flex:1});
89
99
  const namingButtons = namingBar.menuline({group:true, overflowable:false, gap:'8px'});
90
100
  namingButtons.button('Cancel', {action:"this.SET('.clipboardOpen', false)"});
91
101
  namingButtons.button('Save branch', {action:'saveClipboard'});
92
- const dialog = pane.dialog({title:'Required parameters', open:'^.insertionOpen', width:'400px', height:'280px', movable:true, resizable:true});
93
- dialog.frame.center.div({nodeId:`${editorId}InsertFields`, class:'visual-editor-fields', padding:'12px'}).span('');
102
+ const dialog = pane.dialog({class:'visual-editor-popup', title:'Required parameters', open:'^.insertionOpen', width:'400px', height:'280px', movable:true, resizable:true});
103
+ dialog.frame.center.div({nodeId:`${editorId}InsertFields`, class:'visual-editor-fields', padding:'6px'}).span('');
94
104
  dialog.frame.center.p('^.error', {role:'alert'});
95
- const bar = dialog.frame.bottom.menu({presentation:'bar', aria_label:'Insertion commands', padding:'8px 12px', border_top:'1px solid var(--gramlot-border)'});
105
+ const bar = dialog.frame.bottom.menu({presentation:'bar', aria_label:'Insertion commands', padding:'3px 6px', border_top:'1px solid var(--gramlot-border)'});
96
106
  bar.spacer({flex:1});
97
107
  const buttons = bar.menuline({group:true, overflowable:false, gap:'8px'});
98
108
  buttons.button('Cancel', {action:"this.SET('.insertionOpen', false)"});
99
109
  buttons.button('Insert', {action:'insertWidget'});
100
- const settings = pane.floatingPane({title:'Appearance', open:'^.appearanceOpen', default_open:false, width:'280px', height:'260px', movable:true, resizable:true});
101
- const form = settings.frame.center.formlet({columns:1, lbl_position:'TL', gap:'10px', padding:'12px'});
110
+ const settings = pane.floatingPane({class:'visual-editor-popup', title:'Appearance', open:'^.appearanceOpen', default_open:false, width:'280px', height:'260px', movable:true, resizable:true});
111
+ const form = settings.frame.center.formlet({columns:1, lbl_position:'TL', gap:'4px', padding:'6px'});
102
112
  form.filteringSelect({validate_notnull:true, lbl:'Theme', value:'^.appearanceProfile', values:'base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela'});
103
113
  form.filteringSelect({validate_notnull:true, lbl:'Colors', value:'^.appearancePalette', values:'default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue'});
104
114
  form.filteringSelect({validate_notnull:true, lbl:'Mode', value:'^.appearanceMode', values:'light:Light,dark:Dark'});
@@ -120,16 +130,16 @@ export class VisualEditor {
120
130
  const opener = frame === this.frame ? this.toolbar : frame.top.menu({presentation:'bar', aria_label:'Code drawer'});
121
131
  opener.menuline({group:true, overflowable:false}).button('Code', {action:'openCode', class:'button--quiet'});
122
132
  const drawer = frame.right;
123
- drawer.setAttr({datapath:anchor, title:'Page code', detachable:true, width:'60%', minSize:240, splitter:true,
133
+ drawer.setAttr({class:'visual-editor-code', datapath:anchor, title:'Page code', detachable:true, width:'60%', minSize:240, splitter:true,
124
134
  drawer:'^.codeOpen', default_drawer:'close', drawer_label:'Code', drawer_minimize:false,
125
135
  drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')", min_height:0, overflow:'hidden'});
126
136
  const code = drawer.framePane({height:'100%', width:'100%', min_width:0, flex:1});
127
- code.top.setAttr({height:'32px'}); code.bottom.setAttr({height:'58px'});
137
+ code.top.setAttr({height:'26px'}); code.bottom.setAttr({height:'48px'});
128
138
  code.center.setAttr({display:'flex', flex_direction:'column', min_height:0, overflow:'hidden'});
129
- code.top.div(document.path, {padding:'8px 12px', font_size:'12px', overflow:'hidden', text_overflow:'ellipsis', white_space:'nowrap'});
139
+ code.top.div(document.path, {padding:'3px 6px', font_size:'12px', overflow:'hidden', text_overflow:'ellipsis', white_space:'nowrap'});
130
140
  code.center.codeMirror({value:'^.codeDocument.content', language:document.language, live:true, readonly:'^.codeDocument.writable:=!{}', height:'100%', box_height:'100%', box_c_height:'100%', box_min_height:0, box_c_min_height:0, fontSize:13, flex:1, min_height:0});
131
141
  code.bottom.div('^.codeDocument.status', {role:'status', font_size:'12px', padding:'4px 10px'});
132
- const bar = code.bottom.menu({presentation:'bar', aria_label:'Page code commands', padding:'6px 10px'});
142
+ const bar = code.bottom.menu({presentation:'bar', aria_label:'Page code commands', padding:'3px 6px'});
133
143
  bar.spacer({flex:1});
134
144
  const commands = bar.menuline({group:true, overflowable:false, gap:'6px'});
135
145
  commands.button('Close', {action:"this.SET('.codeOpen', 'close')"});
@@ -3,7 +3,7 @@ import type {GramlotRenderer} from './renderer/gramlot-renderer.js';
3
3
 
4
4
  /** Reusable, lifecycle-bound selection of rendered Source nodes in an editor preview. */
5
5
  export class SourcePicker {
6
- constructor(options: {renderer: GramlotRenderer; root: SourceBagNode; onSelect: (node: SourceBagNode) => void});
6
+ constructor(options: {renderer: GramlotRenderer; root: SourceBagNode; canvas?:Element; onSelect: (node: SourceBagNode) => void});
7
7
  select(node: SourceBagNode | null): void;
8
8
  dispose(): void;
9
9
  }
@@ -2,9 +2,8 @@
2
2
  export class SourcePicker {
3
3
  #renderer; #root; #canvas; #onSelect; #observer; #selectedPath = null;
4
4
  #highlighted = null; #release = null; #disposed = false;
5
- constructor({renderer, root, onSelect}) {
5
+ constructor({renderer, root, onSelect, canvas = renderer.records.get(root.parentNode)?.presentation}) {
6
6
  if (!root?.parentNode || typeof onSelect !== 'function') throw new TypeError('SourcePicker requires a mounted Source root and onSelect');
7
- const canvas = renderer.records.get(root.parentNode)?.presentation;
8
7
  if (!canvas || canvas.nodeType !== 1) throw new TypeError('SourcePicker requires a mounted preview');
9
8
  this.#renderer = renderer; this.#root = root; this.#canvas = canvas; this.#onSelect = onSelect;
10
9
  canvas.addEventListener('pointerdown', this, true);
@@ -0,0 +1,29 @@
1
+ /** An editor-owned document destination for the same live Source and renderer. */
2
+ export class VisualEditorCanvas {
3
+ constructor({app, editor, design}) {
4
+ this.renderer = app.src.renderer;
5
+ this.design = design;
6
+ const presentation = this.renderer.records.get(design).presentation;
7
+ this.frame = presentation.ownerDocument.createElement('iframe');
8
+ this.frame.title = 'Page canvas';
9
+ this.frame.className = 'visual-editor-canvas-frame';
10
+ this.frame.style.cssText = 'display:block;width:100%;height:100%;min-height:240px;border:0;background:white';
11
+ presentation.before(this.frame);
12
+ const document = this.frame.contentDocument;
13
+ app.registerDocument(document);
14
+ const base = document.createElement('style');
15
+ base.textContent = 'html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}';
16
+ this.styles = document.createElement('style');
17
+ const selection = document.createElement('style');
18
+ selection.textContent = '.gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}';
19
+ document.head.append(base, this.styles, selection);
20
+ this.body = document.body;
21
+ this.renderer.mountDestination(design, this.body);
22
+ this.release = this.renderer.onDispose(editor, () => this.dispose());
23
+ }
24
+ setCss(texts) { this.styles.textContent = texts.join('\n'); }
25
+ dispose() {
26
+ this.release?.(); this.release = null;
27
+ this.frame.remove();
28
+ }
29
+ }
@@ -0,0 +1,34 @@
1
+ import {HtmlBuilder, SourceBag} from '@genrojs/builders';
2
+
3
+ const htmlTags = new Set(Object.entries(new HtmlBuilder().schema)
4
+ .filter(([, info]) => !info._meta?.data_element && !info._meta?.subbuilder && !info._meta?.container)
5
+ .map(([tag]) => tag));
6
+
7
+ export function validateCatalogue(catalogue) {
8
+ if (catalogue == null || catalogue === 'html') return;
9
+ if (!Array.isArray(catalogue) || catalogue.some(tag => typeof tag !== 'string' || !tag || tag.trim() !== tag))
10
+ throw new TypeError('catalogue must be "html" or a list of tag names');
11
+ if (!catalogue.includes('div')) throw new Error('catalogue must include div for pageRoot');
12
+ }
13
+
14
+ export function catalogueAllows(catalogue, tag, meta = {}) {
15
+ if (catalogue == null) return true;
16
+ if (Array.isArray(catalogue)) return catalogue.includes(tag);
17
+ return !meta.gramlot_component && !meta.data_element && !meta.subbuilder && !meta.container
18
+ && htmlTags.has(meta.render_tag ?? tag);
19
+ }
20
+
21
+ export function validateCatalogueSource(catalogue, source) {
22
+ if (catalogue == null) return;
23
+ const visit = (bag, prefix) => {
24
+ for (const node of bag.getNodes()) {
25
+ const path = prefix ? `${prefix}.${node.label}` : node.label;
26
+ if (!catalogueAllows(catalogue, node.nodeTag, node.getAttr('_meta') ?? {}))
27
+ throw new Error(`Tag ${node.nodeTag} is outside the editor catalogue at ${path}`);
28
+ if (node.resolver) throw new Error(`Catalogue scope requires materialized Source at ${path}`);
29
+ const value = node.getValue(true);
30
+ if (value instanceof SourceBag) visit(value, path);
31
+ }
32
+ };
33
+ visit(source, '');
34
+ }
@@ -1,6 +1,11 @@
1
1
  import type {SourceBagNode} from '@genrojs/builders';
2
2
  export function visualEditorScope(node:SourceBagNode):SourceBagNode;
3
3
  export class VisualEditorLogic {
4
+ setCanvasCss(node:SourceBagNode, texts:string[]):void;
5
+ loadSource(node:SourceBagNode, document:{source:string; filename:string}):void;
6
+ currentSource(node:SourceBagNode):string;
7
+ markSaved(node:SourceBagNode):void;
8
+ initializeDocument(node:SourceBagNode):void;
4
9
  chatRender(node:SourceBagNode, ...args:unknown[]):unknown;
5
10
  chatCompleted(node:SourceBagNode, ...args:unknown[]):unknown;
6
11
  chatReset(node:SourceBagNode, ...args:unknown[]):unknown;