@gramlot/gramlot 0.3.9 → 0.3.15

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 (95) hide show
  1. package/dist/components/editors/__init__.py +13 -0
  2. package/dist/components/{editors.js → editors/assets/collection.js} +354 -418
  3. package/dist/components/editors/assets/index.js +2 -0
  4. package/dist/components/editors/commands.json +7 -0
  5. package/dist/components/editors/grammar.json +7045 -0
  6. package/dist/components/inputs/__init__.py +13 -0
  7. package/dist/components/{inputs.js → inputs/assets/collection.js} +291 -200
  8. package/dist/components/inputs/assets/index.js +2 -0
  9. package/dist/components/inputs/commands.json +7 -0
  10. package/dist/components/inputs/grammar.json +42881 -0
  11. package/dist/components/layout/__init__.py +13 -0
  12. package/dist/components/layout/assets/collection.js +25737 -0
  13. package/dist/components/layout/assets/index.js +2 -0
  14. package/dist/components/layout/commands.json +7 -0
  15. package/dist/components/layout/grammar.json +1798 -0
  16. package/dist/components/tree/__init__.py +13 -0
  17. package/dist/components/{tree.js → tree/assets/collection.js} +62 -175
  18. package/dist/components/tree/assets/index.js +2 -0
  19. package/dist/components/tree/commands.json +7 -0
  20. package/dist/components/tree/grammar.json +339 -0
  21. package/dist/components/typst/__init__.py +13 -0
  22. package/dist/components/typst/assets/collection.js +4 -0
  23. package/dist/components/typst/assets/index.js +2 -0
  24. package/dist/components/typst/commands.json +7 -0
  25. package/dist/components/typst/grammar.json +81 -0
  26. package/dist/gramlot.js +2525 -905
  27. package/dist/gramlot.min.js +109 -28
  28. package/dist/runtime-notices.json +0 -196
  29. package/package.json +1 -1
  30. package/src/binding/ask-dialog.js +1 -1
  31. package/src/binding/installation.js +5 -6
  32. package/src/binding/remote.js +9 -2
  33. package/src/binding/runtime.js +12 -5
  34. package/src/bootstrap.d.ts +1 -1
  35. package/src/bootstrap.js +52 -30
  36. package/src/builder/binding.json +25 -0
  37. package/src/builder/gramlot-builder.js +16 -3
  38. package/src/builder/source.js +41 -4
  39. package/src/collection-artifact.d.ts +11 -0
  40. package/src/collection-artifact.js +57 -0
  41. package/src/commands.d.ts +9 -0
  42. package/src/commands.js +36 -0
  43. package/src/components/bases.js +1 -1
  44. package/src/components/border-container.js +33 -2
  45. package/src/components/buttons.js +84 -161
  46. package/src/components/choice-editor.js +31 -10
  47. package/src/components/database-choices.js +110 -0
  48. package/src/components/inputs.js +15 -2
  49. package/src/components/layout.js +5 -3
  50. package/src/components/menus.js +346 -0
  51. package/src/components/popup.js +15 -2
  52. package/src/components/registry.js +18 -3
  53. package/src/components/toolbar-overflow.js +181 -0
  54. package/src/components/tree.js +14 -4
  55. package/src/components/validation.js +1 -1
  56. package/src/components/windows.js +284 -0
  57. package/src/gramlot.d.ts +2 -0
  58. package/src/gramlot.js +4 -2
  59. package/src/handlers/rpc-handler.d.ts +6 -1
  60. package/src/handlers/rpc-handler.js +7 -2
  61. package/src/handlers/source-handler.d.ts +2 -1
  62. package/src/handlers/source-handler.js +10 -1
  63. package/src/index-page-styles.js +1 -1
  64. package/src/index-theme.js +1 -1
  65. package/src/index.d.ts +5 -0
  66. package/src/index.js +5 -0
  67. package/src/renderer/attributes.js +11 -2
  68. package/src/renderer/gramlot-html-renderer.js +1 -0
  69. package/src/renderer/gramlot-renderer.js +13 -3
  70. package/src/server/assets.js +2 -2
  71. package/src/server/gramlot-file-server.d.ts +2 -0
  72. package/src/server/gramlot-file-server.js +45 -1
  73. package/src/server/gramlot-server.d.ts +20 -2
  74. package/src/server/gramlot-server.js +86 -6
  75. package/src/server/page-base.js +1 -0
  76. package/src/server/page.d.ts +3 -0
  77. package/src/view/button.js +47 -3
  78. package/src/view/controls.js +8 -0
  79. package/src/view/html.js +8 -0
  80. package/src/view/menu-command.js +45 -0
  81. package/src/view/menu.js +87 -0
  82. package/themes/gramlot-compact/README.md +19 -0
  83. package/themes/gramlot-compact/theme.css +138 -45
  84. package/themes/joanna/README.md +19 -0
  85. package/themes/joanna/theme.css +134 -78
  86. package/themes/mela/theme.css +184 -0
  87. package/themes/mimi/README.md +19 -0
  88. package/themes/mimi/theme.css +133 -77
  89. package/themes/palettes/README.md +3 -0
  90. package/themes/palettes/compact.css +86 -0
  91. package/themes/palettes/joanna.css +86 -0
  92. package/themes/palettes/mimi.css +86 -0
  93. package/tools/gramlot-tools-inspector.js +3 -3
  94. package/dist/components/layout.js +0 -1402
  95. package/dist/components/typst.js +0 -4
package/src/bootstrap.js CHANGED
@@ -34,52 +34,74 @@ export class PageBootstrap {
34
34
  const {config, resources, document} = this;
35
35
  const window = document.defaultView;
36
36
  if (resources.serverAdapter !== undefined) this.serverAdapter = await this.loadServerAdapter(resources.serverAdapter);
37
- for (const url of resources.css) {
38
- const link = document.createElement('link');
39
- link.rel = 'stylesheet';
40
- link.href = url;
41
- document.head.append(link);
42
- }
43
- let closed = false;
37
+ let closed = false, resolveClosed, app;
38
+ const styleCleanup = [];
39
+ const closing = new Promise(resolve => { resolveClosed = resolve; });
44
40
  const pagehide = event => {
45
41
  if (event.persisted || closed) return;
46
42
  closed = true;
47
43
  this.closePage();
44
+ resolveClosed(null);
48
45
  };
49
46
  window.addEventListener('pagehide', pagehide);
50
- let entries, collections;
51
47
  try {
52
- // A relative module URL is resolved against the document, as in HTML (D8).
53
- const settled = await Promise.allSettled(resources.js.map(({url}) => import(new URL(url, document.baseURI).href)));
54
- if (closed) return null;
55
- entries = resources.js.map(({url, group}, index) => {
56
- const outcome = settled[index];
57
- if (outcome.status === 'rejected') {
58
- throw new Error(`${url}: import failed: ${outcome.reason?.message ?? outcome.reason}`, {cause: outcome.reason});
48
+ const styles = resources.css.map(url => new Promise((resolve, reject) => {
49
+ const link = document.createElement('link');
50
+ link.rel = 'stylesheet'; link.href = url;
51
+ const cleanup = () => { link.removeEventListener('load', loaded); link.removeEventListener('error', failed); };
52
+ styleCleanup.push(cleanup);
53
+ const loaded = () => { cleanup(); resolve(); };
54
+ const failed = () => { cleanup(); reject(new Error(`${url}: stylesheet load failed`)); };
55
+ link.addEventListener('load', loaded); link.addEventListener('error', failed);
56
+ document.head.append(link);
57
+ }));
58
+ const logic = resources.js.map(async ({url, group}) => {
59
+ try {
60
+ const module = await import(new URL(url, document.baseURI).href);
61
+ return {logicClass:module.Logic, group, resource:url};
62
+ } catch(error) { throw new Error(`${url}: import failed: ${error.message}`, {cause:error}); }
63
+ });
64
+ const names = new Set();
65
+ const collectionImports = (resources.collections ?? []).map(async record => {
66
+ if (!record || typeof record !== 'object' || Object.keys(record).sort().join(',') !== 'buildId,name,url' ||
67
+ typeof record.name !== 'string' || typeof record.url !== 'string' ||
68
+ typeof record.buildId !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(record.buildId) || names.has(record.name)) {
69
+ throw new TypeError('Invalid or duplicate collection bootstrap record');
70
+ }
71
+ names.add(record.name);
72
+ const {name,url,buildId} = record;
73
+ let module;
74
+ try { module = await import(new URL(url, document.baseURI).href); }
75
+ catch(error) { throw new Error(`${name}: collection import failed: ${error.message}`, {cause:error}); }
76
+ if (module.default?.name !== name || module.buildId !== buildId) {
77
+ throw new Error(`${name}: collection identity mismatch; expected ${buildId}, received ${module.buildId}`);
59
78
  }
60
- return {logicClass: outcome.value.Logic, group, resource: url};
79
+ return module.default;
61
80
  });
62
- LogicRegistry.check(entries);
63
- collections = await Promise.all((resources.collections ?? []).map(async url => {
64
- try { return (await import(new URL(url, document.baseURI).href)).default; }
65
- catch (error) { throw new Error(`${url}: collection import failed: ${error.message}`, {cause: error}); }
66
- }));
81
+ const result = await Promise.race([Promise.all([
82
+ Promise.all(styles), Promise.all(logic), Promise.all(collectionImports)]), closing]);
67
83
  if (closed) return null;
84
+ const [,entries,collections] = result;
85
+ LogicRegistry.check(entries);
86
+ // Verify the complete graph before activating any component or command.
68
87
  for (const collection of collections) collection.register(window);
69
- } catch (error) {
70
- this.closePage();
88
+ app = new Gramlot({...config, document, serverAdapter:this.serverAdapter,
89
+ collections:[...(config.collections ?? []), ...collections.map(c=>c.toDocument())]});
90
+ window.removeEventListener('pagehide', pagehide);
91
+ for (const collection of collections) collection.registerCommands(app);
92
+ for (const {logicClass,group,resource} of entries) app.src.logicRegistry.register(logicClass,{group,resource});
93
+ window.gramlot = app;
94
+ await app.start();
95
+ return app;
96
+ } catch(error) {
97
+ if (app) app.dispose();
98
+ else if (!closed) this.closePage();
71
99
  throw error;
72
100
  } finally {
101
+ for (const cleanup of styleCleanup) cleanup();
73
102
  window.removeEventListener('pagehide', pagehide);
74
103
  }
75
- const app = new Gramlot({...config, document, serverAdapter: this.serverAdapter,
76
- collections: [...(config.collections ?? []), ...collections.map(collection => collection.toDocument())]});
77
- for (const {logicClass, group, resource} of entries) app.src.logicRegistry.register(logicClass, {group, resource});
78
- window.gramlot = app;
79
- await app.start();
80
- return app;
81
104
  }
82
-
83
105
  /**
84
106
  * The ServerAdapter the server names in `resources.serverAdapter`: an instance of the default export of the
85
107
  * module `url`, which imports the core through the import map and so shares the runtime already loaded. A
@@ -411,6 +411,31 @@
411
411
  "_meta": {
412
412
  "render_tag": "button"
413
413
  }
414
+ },
415
+ "html_dialog": {
416
+ "doc": "Native HTML dialog, distinct from the layout window component.",
417
+ "sub_tags": "a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",
418
+ "parent_tags": null,
419
+ "inherits_from": null,
420
+ "ns": null,
421
+ "attributes": {
422
+ "parameters": [
423
+ {
424
+ "name": "kwargs",
425
+ "kind": "var_keyword",
426
+ "role": "attribute",
427
+ "annotation": null,
428
+ "has_default": false
429
+ }
430
+ ],
431
+ "accepts_var_keyword": true,
432
+ "accepts_var_positional": false
433
+ },
434
+ "node_label": null,
435
+ "collection_key": null,
436
+ "_meta": {
437
+ "render_tag": "dialog"
438
+ }
414
439
  }
415
440
  }
416
441
  }
@@ -154,12 +154,25 @@ export class GramlotBuilder extends HtmlBuilder {
154
154
 
155
155
  /** Builder's element call from the Proxy on a Source Bag. */
156
156
  bagCall(bag, tag, value, attrs) {
157
- return super.bagCall(bag, this.#authoredTag(tag), value, attrs);
157
+ tag = this.#authoredTag(tag);
158
+ [value, attrs] = this.menuArguments(tag, value, attrs);
159
+ return super.bagCall(bag, tag, value, attrs);
158
160
  }
159
161
 
160
162
  /** Builder's element call from the Proxy on a Source node. */
161
163
  commandOnNode(node, tag, value, attrs) {
162
- return super.commandOnNode(node, this.#authoredTag(tag), value, attrs);
164
+ tag = this.#authoredTag(tag);
165
+ [value, attrs] = this.menuArguments(tag, value, attrs);
166
+ return super.commandOnNode(node, tag, value, attrs);
167
+ }
168
+
169
+ menuArguments(tag, value, attrs = {}) {
170
+ if (tag === 'menu' && value == null) return [new GramlotBuilderBag(null, this), attrs];
171
+ if (tag === 'menuline' && value != null && value !== '-') {
172
+ if (Object.hasOwn(attrs, 'command')) throw new TypeError('menuline command must be declared once');
173
+ return [null, {...attrs, command: value}];
174
+ }
175
+ return [value, attrs];
163
176
  }
164
177
 
165
178
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
@@ -191,7 +204,7 @@ export class GramlotBuilder extends HtmlBuilder {
191
204
  /** Both button declarations occupy the native button slot in HTML content models. */
192
205
  _validateChildren(parentTag, info, tags, includeMinimum) {
193
206
  return super._validateChildren(parentTag, info,
194
- tags.map(tag => tag === 'html_button' ? 'button' : tag), includeMinimum);
207
+ tags.map(tag => tag === 'html_button' ? 'button' : tag === 'html_dialog' ? 'dialog' : tag), includeMinimum);
195
208
  }
196
209
 
197
210
  /** Custom elements are outside the native HTML child catalogue, as components are. */
@@ -177,6 +177,34 @@ function isExpression(value) {
177
177
  * setRelativeData too, with the Gramlot reset rules.
178
178
  */
179
179
  export class GramlotBuilderBagNode extends SourceBagNode {
180
+ get frame() {
181
+ if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('frame accessor requires a window');
182
+ const children = this.value instanceof SourceBag ? this.value.getNodes() : [];
183
+ if (children.length) {
184
+ if (children.length !== 1 || children[0].nodeTag !== 'framePane') throw new TypeError('A window requires exactly one framePane');
185
+ return this.builder.wrapSource(children[0]);
186
+ }
187
+ return this.builder.wrapSource(this.builder.commandOnNode(this, 'framePane', null, {node_label:'frame'}));
188
+ }
189
+ requestClose(reason = 'application') {
190
+ if (!['dialog','floatingPane'].includes(this.nodeTag)) throw new TypeError('requestClose requires a window');
191
+ return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(reason);
192
+ }
193
+ get top() { return this.frameRegion('top'); }
194
+ get bottom() { return this.frameRegion('bottom'); }
195
+ get left() { return this.frameRegion('left'); }
196
+ get right() { return this.frameRegion('right'); }
197
+ get center() { return this.frameRegion('center'); }
198
+ frameRegion(region) {
199
+ if (this.nodeTag !== 'framePane') throw new TypeError('Region accessors require framePane');
200
+ const existing = this.value instanceof SourceBag
201
+ ? this.value.getNodes().find(child => child.getAttr('region') === region) : null;
202
+ if (existing) return this.builder.wrapSource(existing);
203
+ const attrs = {region, node_label: region};
204
+ if (region !== 'center') Object.assign(attrs, {display: 'flex', flex_direction: ['top', 'bottom'].includes(region) ? 'column' : 'row'});
205
+ return this.builder.wrapSource(this.builder.commandOnNode(this, 'contentPane', null, attrs));
206
+ }
207
+
180
208
  // Attributes ending in `_path` whose pointer symbol was already reported.
181
209
  #reportedPathPointers = new Set();
182
210
  // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
@@ -193,7 +221,8 @@ export class GramlotBuilderBagNode extends SourceBagNode {
193
221
  * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
194
222
  * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
195
223
  * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
196
- * every `==` attribute (canonical name) and a `==` node value (`''`).
224
+ * every `==` attribute (canonical name) and a `==` node value (`''`). Script elements also retain
225
+ * their literal executable text and URLs here for the live renderer's activation check.
197
226
  */
198
227
  codeAttributes() {
199
228
  const own = [...(CODE_ATTRIBUTES[this.nodeTag] ?? []),
@@ -214,8 +243,12 @@ export class GramlotBuilderBagNode extends SourceBagNode {
214
243
  }
215
244
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
216
245
  if (isExpression(value)) items.push([name, value]);
246
+ if (this.nodeTag === 'script' && typeof value === 'string') {
247
+ const prefix = this.builder.constructor.dialectPrefixes.find(prefix => name.startsWith(prefix)) ?? '';
248
+ if (['src', 'href', 'xlink:href', 'xlink_href', '_text'].includes(name.slice(prefix.length).toLowerCase())) items.push([name, value]);
249
+ }
217
250
  }
218
- if (isExpression(this.staticValue)) items.push(['', this.staticValue]);
251
+ if (isExpression(this.staticValue) || this.nodeTag === 'script' && typeof this.staticValue === 'string') items.push(['', this.staticValue]);
219
252
  return items;
220
253
  }
221
254
 
@@ -274,14 +307,14 @@ export class GramlotBuilderBagNode extends SourceBagNode {
274
307
 
275
308
  /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
276
309
  publish(topic, payload = {}) {
277
- return this.builder.binding.subscriptions.publishNode(this, topic, payload);
310
+ return this.rootBuilder.binding.subscriptions.publishNode(this, topic, payload);
278
311
  }
279
312
 
280
313
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
281
314
  pointers() {
282
315
  const datapath = this.getAttr('datapath');
283
316
  const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : new Set();
284
- const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer))
317
+ const result = super.pointers().filter(([name, pointer]) => !(this.nodeTag === 'menuline' && ['caption','icon','tooltip','command'].includes(name)) && !dependencies.has(name) && !this.#isPathAttribute(name, pointer))
285
318
  .map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
286
319
  for (const name of dependencies) {
287
320
  const value = this.getAttr(name);
@@ -298,6 +331,10 @@ export class GramlotBuilderBagNode extends SourceBagNode {
298
331
  runtimeToEvaluate() {
299
332
  const items = super.runtimeToEvaluate();
300
333
  for (const [name, value] of items) {
334
+ if (this.nodeTag === 'menuline' && ['caption','icon','tooltip','command'].includes(name)) {
335
+ items.set(name, new BagCbResolver(() => value));
336
+ continue;
337
+ }
301
338
  if (!this.pointerType(value)) continue;
302
339
  if (pointerTransform(value)) {
303
340
  if (typeof name !== 'string') throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
@@ -0,0 +1,11 @@
1
+ export interface CollectionArtifactMetadata {
2
+ name: string;
3
+ grammar: string;
4
+ commands: string;
5
+ module: string;
6
+ css: string[];
7
+ dependencies: string[];
8
+ files: string[];
9
+ }
10
+ export declare function collectionBuildId(metadata: CollectionArtifactMetadata, files: Map<string, Uint8Array>): Promise<string>;
11
+ export declare function verifyCollectionArtifact(metadata: CollectionArtifactMetadata & {buildId: string}, files: Map<string, Uint8Array>): Promise<void>;
@@ -0,0 +1,57 @@
1
+ /** Portable prepared-artifact integrity; hosts provide bytes, never filesystem paths. */
2
+ const encoder = new TextEncoder();
3
+ const wrapper = id => `export {default} from "./collection.js";\nexport const buildId = "${id}";\n`;
4
+ const pathValid = value => typeof value === 'string' && value.length > 0 &&
5
+ !/[\\\x00-\x1f:?#%]/.test(value) && !value.split('/').some(part => !part || part === '.' || part === '..');
6
+ function validate(metadata, files) {
7
+ if (!metadata || typeof metadata.name !== 'string' || !metadata.name ||
8
+ !['grammar', 'commands', 'module'].every(key => pathValid(metadata[key])) ||
9
+ !Array.isArray(metadata.css) || !metadata.css.every(pathValid) ||
10
+ !Array.isArray(metadata.dependencies) || !metadata.dependencies.every(name => typeof name === 'string' && name.length > 0) ||
11
+ !Array.isArray(metadata.files) || !metadata.files.every(pathValid) ||
12
+ new Set(metadata.files).size !== metadata.files.length || !(files instanceof Map) ||
13
+ files.size !== metadata.files.length || metadata.files.some(path => !(files.get(path) instanceof Uint8Array)) ||
14
+ [metadata.grammar, metadata.commands, metadata.module, ...metadata.css].some(path => !files.has(path))) {
15
+ throw new TypeError('Invalid collection artifact metadata or file inventory');
16
+ }
17
+ }
18
+ /** Compute the version-1 framed fingerprint, normalizing only the fixed wrapper identity. */
19
+ export async function collectionBuildId(metadata, files) {
20
+ validate(metadata, files);
21
+ const chunks = [encoder.encode('gramlot-build-v1\0')];
22
+ const record = (tag, value) => {
23
+ const bytes = typeof value === 'string' ? encoder.encode(value) : value;
24
+ chunks.push(encoder.encode(`${tag}\0${bytes.length}\0`), bytes);
25
+ };
26
+ for (const key of ['name', 'grammar', 'commands', 'module']) record(key, metadata[key]);
27
+ for (const value of metadata.css) record('css', value);
28
+ for (const value of metadata.dependencies) record('dependency', value);
29
+ const compare = (a, b) => {
30
+ const left = encoder.encode(a), right = encoder.encode(b);
31
+ for (let i = 0; i < Math.min(left.length, right.length); i++) if (left[i] !== right[i]) return left[i] - right[i];
32
+ return left.length - right.length;
33
+ };
34
+ for (const path of [...metadata.files].sort(compare)) {
35
+ record('path', path);
36
+ record('content', path === metadata.module ? wrapper('__GRAMLOT_BUILD_ID__') : files.get(path));
37
+ }
38
+ const input = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
39
+ let offset = 0;
40
+ for (const chunk of chunks) { input.set(chunk, offset); offset += chunk.length; }
41
+ const hash = await crypto.subtle.digest('SHA-256', input);
42
+ return 'sha256:' + [...new Uint8Array(hash)].map(value => value.toString(16).padStart(2, '0')).join('');
43
+ }
44
+ /** Reject a changed wrapper, missing/extra file, or any content/metadata fingerprint mismatch. */
45
+ export async function verifyCollectionArtifact(metadata, files) {
46
+ validate(metadata, files);
47
+ if (typeof metadata.buildId !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(metadata.buildId)) {
48
+ throw new TypeError('Invalid collection buildId');
49
+ }
50
+ const expected = encoder.encode(wrapper(metadata.buildId)), actual = files.get(metadata.module);
51
+ if (actual.length !== expected.length || actual.some((byte, index) => byte !== expected[index])) {
52
+ throw new Error('Invalid collection wrapper');
53
+ }
54
+ if (await collectionBuildId(metadata, files) !== metadata.buildId) {
55
+ throw new Error(`Collection fingerprint mismatch: ${metadata.name}`);
56
+ }
57
+ }
@@ -0,0 +1,9 @@
1
+ /** Command metadata authored by a collection and isolated per page instance. */
2
+ export interface CommandDefinition {label:string; publish:string; icon?:string; iconSrc?:string; tooltip?:string;}
3
+ export interface CommandGroupMetadata {author?:string; description?:string;}
4
+ export class CommandRegistry {
5
+ registerGroup(namespace:string, metadata?:CommandGroupMetadata): Readonly<{register(name:string,definition:CommandDefinition):void}>;
6
+ get(command:string): Readonly<CommandDefinition> | undefined;
7
+ toDocument(): {document_format:{name:'gramlot_commands';version:'1.0'};
8
+ groups:Record<string,CommandGroupMetadata & {commands:Record<string,CommandDefinition>}>};
9
+ }
@@ -0,0 +1,36 @@
1
+ /** Page-local command definitions shared by collection preparation and activation. */
2
+ export class CommandRegistry {
3
+ #groups = new Map();
4
+ registerGroup(namespace, metadata = {}) {
5
+ if (typeof namespace !== 'string' || !namespace || namespace.includes(':')) {
6
+ throw new TypeError('Extension command namespace must be nonempty and unqualified');
7
+ }
8
+ if (this.#groups.has(namespace)) throw new Error(`Duplicate command namespace: ${namespace}`);
9
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata) || Object.keys(metadata).some(key => !['author', 'description'].includes(key)) ||
10
+ Object.values(metadata).some(value => typeof value !== 'string')) {
11
+ throw new TypeError(`Invalid command group metadata: ${namespace}`);
12
+ }
13
+ const commands = new Map();
14
+ this.#groups.set(namespace, {metadata: {...metadata}, commands});
15
+ return Object.freeze({register(name, definition) {
16
+ if (typeof name !== 'string' || !name || name.includes(':')) throw new TypeError('Invalid command name');
17
+ if (commands.has(name)) throw new Error(`Duplicate command: ${namespace}:${name}`);
18
+ if (!definition || typeof definition !== 'object' || Array.isArray(definition) ||
19
+ !Object.hasOwn(definition, 'label') || !Object.hasOwn(definition, 'publish') ||
20
+ Object.keys(definition).some(key => !['label', 'publish', 'icon', 'iconSrc', 'tooltip'].includes(key)) ||
21
+ Object.values(definition).some(value => typeof value !== 'string')) {
22
+ throw new TypeError(`Invalid command definition: ${namespace}:${name}`);
23
+ }
24
+ commands.set(name, Object.freeze({...definition}));
25
+ }});
26
+ }
27
+ get(command) {
28
+ const separator = command.indexOf(':');
29
+ return this.#groups.get(command.slice(0, separator))?.commands.get(command.slice(separator + 1));
30
+ }
31
+ toDocument() {
32
+ return {document_format: {name: 'gramlot_commands', version: '1.0'},
33
+ groups: Object.fromEntries([...this.#groups].map(([name, {metadata, commands}]) =>
34
+ [name, {...metadata, commands: Object.fromEntries(commands)}]))};
35
+ }
36
+ }
@@ -11,7 +11,7 @@ export function controlElement(HTMLElement) {
11
11
  style.textContent = `:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
12
12
  input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
13
13
  input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
14
- appearance:none;box-sizing:border-box;border:1px solid var(--gramlot-border-control,#7a8798);
14
+ appearance:none;box-sizing:border-box;width:100%;border:1px solid var(--gramlot-border-control,#7a8798);
15
15
  border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);
16
16
  min-height:var(--gramlot-field-height,28px);padding:var(--gramlot-field-padding,.25em .5em);font-size:var(--gramlot-field-font-size,1em);line-height:var(--gramlot-field-line-height,inherit)}
17
17
  input:read-only:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea:read-only{
@@ -1,6 +1,7 @@
1
1
  /** Parent-owned regions. Layout changes never move or recreate slotted content. */
2
2
  import {defineComponent} from './registry.js';
3
3
  import {Container} from './container.js';
4
+ import createDOMPurify from 'dompurify';
4
5
 
5
6
  const SIDES = ['top', 'bottom', 'left', 'right'];
6
7
  const REGIONS = [...SIDES, 'center'];
@@ -75,6 +76,23 @@ export const ContentPane = defineComponent({
75
76
  style.textContent = ':host{min-height:0;overflow:auto}.control-box{height:100%;min-height:0}';
76
77
  this.shadowRoot.append(style);
77
78
  }
79
+ projectAttributes(attrs) {
80
+ const rest = super.projectAttributes(attrs);
81
+ // Source flex styles belong to the slot's layout container as well as
82
+ // the host; the shadow wrapper must not turn region children into blocks.
83
+ const authored = this.ownerDocument.createElement('div').style;
84
+ authored.cssText = rest.style ?? '';
85
+ const flex = authored.display === 'flex' || authored.display === 'inline-flex';
86
+ this.controlBox.style.display = flex ? 'flex' : '';
87
+ this.controlBox.style.flex = flex ? '1 1 auto' : '';
88
+ const properties = ['flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-content', 'gap', 'row-gap', 'column-gap'];
89
+ for (const name of properties) this.controlBox.style.removeProperty(name);
90
+ if (flex) for (let index = 0; index < authored.length; index++) {
91
+ const name = authored.item(index);
92
+ if (properties.includes(name)) this.controlBox.style.setProperty(name, authored.getPropertyValue(name));
93
+ }
94
+ return rest;
95
+ }
78
96
  }
79
97
  });
80
98
 
@@ -92,17 +110,19 @@ export const BorderContainer = defineComponent({
92
110
  static projectChild(element, attrs, context) {
93
111
  const {rest, config} = projectBorderChild(element, attrs, context);
94
112
  BorderContainer.#borderRegions.set(element, config);
95
- if (element.parentElement?.constructor.gramlotComponent?.name === 'borderContainer') element.parentElement.projectRegion(element);
113
+ if (['borderContainer', 'framePane'].includes(element.parentElement?.constructor.gramlotComponent?.name)) element.parentElement.projectRegion(element);
96
114
  return rest;
97
115
  }
98
116
  #regions = new Map();
99
117
  #observer;
100
118
  #contentObserver;
101
119
  #drag;
120
+ #sanitizer;
102
121
  constructor() {
103
122
  super();
104
123
  this.control.replaceChildren();
105
124
  const doc = this.ownerDocument;
125
+ this.#sanitizer = createDOMPurify(doc.defaultView);
106
126
  this.#contentObserver = new doc.defaultView.ResizeObserver(entries => {
107
127
  for (const {target} of entries) {
108
128
  const region = target.closest('.region');
@@ -309,7 +329,10 @@ export const BorderContainer = defineComponent({
309
329
  state.separator.classList.add('separator'); state.drawer.classList.add('drawer');
310
330
  state.drawer.classList.toggle('drawer-reveal', config.minimize);
311
331
  state.drawer.classList.toggle('drawer-rotated', !horizontal(side));
312
- state.drawerLabel.innerHTML = config.label ?? '';
332
+ state.drawerLabel.replaceChildren(this.#sanitizer.sanitize(config.label ?? '', {
333
+ USE_PROFILES: {html: true}, FORBID_TAGS: ['style', 'form', 'input', 'button', 'select', 'textarea'],
334
+ RETURN_DOM_FRAGMENT: true,
335
+ }));
313
336
  state.drawerIcon.textContent = config.icon ?? '';
314
337
  state.drawerIcon.hidden = !config.icon;
315
338
  state.drawer.toggleAttribute('data-icon', !!config.icon);
@@ -436,3 +459,11 @@ export const BorderContainer = defineComponent({
436
459
  }
437
460
  }
438
461
  });
462
+
463
+
464
+ /** Five-region command frame; the existing border engine owns layout. */
465
+ export const FramePane = defineComponent({
466
+ name: 'framePane', tag: 'gramlot-frame-pane', base: BorderContainer.base,
467
+ parameters: BorderContainer.parameters, childParameters: BorderContainer.childParameters,
468
+ subTags: 'contentPane', implementation: BorderContainer.implementation
469
+ });