@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
@@ -2,4 +2,4 @@
2
2
  export const THEME_READY = 'index:theme-ready';
3
3
  export const THEME_SET = 'index:theme-set';
4
4
  export const THEMES = new Set(['light', 'dark']);
5
- export const APPEARANCES = new Set(['base', 'compact', 'mimi', 'joanna']);
5
+ export const APPEARANCES = new Set(['base', 'compact', 'mimi', 'joanna', 'mela']);
package/src/index.d.ts CHANGED
@@ -42,3 +42,8 @@ export {NavigationResolver} from "./navigation-resolver.js";
42
42
 
43
43
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "./filesystem.js";
44
44
  export {IdeLogic} from "./ide-runtime.js";
45
+
46
+ export {CommandRegistry} from './commands.js';
47
+ export type {CommandDefinition,CommandGroupMetadata} from './commands.js';
48
+
49
+ export {collectionBuildId, verifyCollectionArtifact} from './collection-artifact.js';
package/src/index.js CHANGED
@@ -37,3 +37,8 @@ export {parseDateExpression} from './date-parser/index.js';
37
37
 
38
38
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "./filesystem.js";
39
39
  export {IdeLogic} from "./ide-runtime.js";
40
+
41
+ export {CommandRegistry} from './commands.js';
42
+ export * from './components/index.js';
43
+
44
+ export {collectionBuildId, verifyCollectionArtifact} from './collection-artifact.js';
@@ -28,8 +28,8 @@ const NATIVE_ATTRIBUTES = {
28
28
  // Display directives of the node text: consumed by the renderer, never written as attributes.
29
29
  const DISPLAY_ATTRIBUTES = ['format', 'mask', 'locale', 'timeZone', 'places', 'dtype'];
30
30
 
31
- // Output attributes whose `javascript:` value the browser runs as code (`action` never reaches the output).
32
- const URL_ATTRIBUTES = new Set(['href', 'src', 'formaction', 'xlink:href', 'xlink_href']);
31
+ // Output URL attributes, including the native form action authored as html_action.
32
+ const URL_ATTRIBUTES = new Set(['href', 'src', 'action', 'formaction', 'xlink:href', 'xlink_href']);
33
33
 
34
34
  /** The attributes of `attrs` that are not binding attributes. */
35
35
  export function withoutBindingAttributes(attrs) {
@@ -56,6 +56,15 @@ export function requireStyleClassAttributes(node, attrs, prefixes = []) {
56
56
  * the dialect `prefixes` (`html_`).
57
57
  */
58
58
  export function requireNoScriptAttributes(node, attrs, prefixes = []) {
59
+ if (node.nodeTag === 'script') {
60
+ const executable = [['', node.staticValue], ...sourceAttributeItems(node.getAttr()).filter(([name]) =>
61
+ ['src', 'href', 'xlink:href', 'xlink_href', '_text'].includes(name.slice((prefixes.find(prefix => name.startsWith(prefix)) ?? '').length).toLowerCase()))];
62
+ for (const [name, value] of executable) {
63
+ if (node.pointerType(value) || isExpression(value)) {
64
+ throw new Error(`script '${node.label}': '${name}' must be literal Source; script code and URLs cannot come from Data`);
65
+ }
66
+ }
67
+ }
59
68
  if (attrs.onClose != null && !node.parentNode?._getMeta('gramlot_component')?.childParameters?.onClose) {
60
69
  throw new Error('onClose is only supported on a tab/stack panel');
61
70
  }
@@ -91,6 +91,7 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
91
91
  const evaluate = (attr, expr) => (compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null);
92
92
  const attrs = {...runtimeAttrs};
93
93
  for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
94
+ if (node.nodeTag === 'menuline' && ['caption','icon','tooltip','command'].includes(name)) continue;
94
95
  if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
95
96
  }
96
97
  if (isExpression(node.value)) this.#expressionValues.set(node, evaluate('', node.value));
@@ -9,6 +9,7 @@ import {BuilderBase, SourceBag, sourceTarget} from '@genrojs/builders';
9
9
  import {HtmlElement} from '../view/html.js';
10
10
  import {ControlAdapter, RadioGroups, SelectControl} from '../view/controls.js';
11
11
  import {ButtonBinding} from '../view/button.js';
12
+ import {MenuBinding} from '../view/menu.js';
12
13
  import {NativeEventBinding} from '../view/events.js';
13
14
  import {References} from '../references.js';
14
15
  import {randomId} from '../random-id.js';
@@ -218,6 +219,11 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
218
219
  button.attach();
219
220
  record.cleanup.push(() => button.detach());
220
221
  }
222
+ if (node.nodeTag === 'menu') {
223
+ record.menu = new MenuBinding(record.binding, record.element);
224
+ record.menu.attach();
225
+ record.cleanup.push(() => record.menu.detach());
226
+ }
221
227
  this.#connectEvents(record);
222
228
  this.references?.register(node, record.element);
223
229
  for (const element of children) {
@@ -330,7 +336,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
330
336
 
331
337
  /**
332
338
  * Source event intake (§5.2): an event on a node under construction is ignored
333
- * on arrival; every other event is queued and processed in arrival order.
339
+ * on arrival, as is the deletion of a consumed dataSetter (already closed by the installer).
340
+ * Every other event is queued and processed in arrival order.
334
341
  * Semantic work runs for every event, also under freeze; structural work only
335
342
  * outside frozen branches. A failing disposer does not block the rest: the
336
343
  * closing errors of the semantic work and the cleanup errors of the removals
@@ -338,11 +345,13 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
338
345
  */
339
346
  receive(event) {
340
347
  if (this.disposed) return;
348
+ const ignored = node => this.#constructing.has(node)
349
+ || (event.evt === 'del' && node.nodeTag === 'dataSetter');
341
350
  if (Array.isArray(event.node)) {
342
- const nodes = event.node.filter(node => !this.#constructing.has(node));
351
+ const nodes = event.node.filter(node => !ignored(node));
343
352
  if (!nodes.length) return;
344
353
  event = {...event, node: nodes};
345
- } else if (this.#constructing.has(event.node)) return;
354
+ } else if (ignored(event.node)) return;
346
355
  this.pending.push(event);
347
356
  if (this.building) return;
348
357
  this.building = true;
@@ -541,6 +550,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
541
550
  this.#projectControl(record, node, attrs, change);
542
551
  record.control?.refresh();
543
552
  record.button?.refresh();
553
+ record.menu?.refresh();
544
554
  this.#connectEvents(record);
545
555
  const defaults = this.#presentationDefaults.get(node);
546
556
  if (defaults) {
@@ -20,8 +20,8 @@ export function gramlotDev() {
20
20
 
21
21
  const RUNTIME_ASSETS = ['gramlot.js', 'gramlot.min.js', 'runtime-notices.json'];
22
22
 
23
- /** URL of a packaged browser asset in dist: a file: URL from npm (read with fs.readFile), an https: URL
24
- * from JSR (read with fetch). Without a name, the runtime to serve at the runtime URL: gramlot.js when
23
+ /** URL of a packaged browser asset in dist: a file: URL from npm (read with fs.readFile).
24
+ * Without a name, the runtime to serve at the runtime URL: gramlot.js when
25
25
  * GRAMLOT_DEV=DEBUG, gramlot.min.js otherwise. Another name throws a TypeError. */
26
26
  export function runtimeAsset(name = null) {
27
27
  if (name === null) name = gramlotDev() === 'DEBUG' ? 'gramlot.js' : 'gramlot.min.js';
@@ -10,6 +10,8 @@ import type {Resources} from './resources.js';
10
10
 
11
11
  /** Options of `GramlotFileServer`: those of `GramlotServer` and `reload`. */
12
12
  export interface GramlotFileServerOptions extends GramlotServerOptions {
13
+ /** Discover trusted candidate Page classes without running page methods. */
14
+ iterPageClasses(): AsyncGenerator<typeof Page>;
13
15
  /** Import the page module again when it changes; `null` takes the value from `GRAMLOT_DEV`. */
14
16
  reload?: boolean | null;
15
17
  }
@@ -4,11 +4,15 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {realpath, stat} from 'node:fs/promises';
7
+ import {Bag} from '@genrojs/bag';
8
+ import {SourceBag} from '@genrojs/builders';
9
+ import {fromTytx} from '@genrojs/tytx';
10
+ import {readFile, readdir, realpath, stat} from 'node:fs/promises';
8
11
  import {basename, dirname, extname, join, relative, resolve, sep} from 'node:path';
9
12
  import {pathToFileURL} from 'node:url';
10
13
  import {gramlotDev} from './assets.js';
11
14
  import {fileBelow, inside, realFile} from './files.js';
15
+ import {Page} from './page.js';
12
16
  import {GramlotServer, PageNotFound} from './gramlot-server.js';
13
17
  import {InvalidResourceName, SEGMENT, parseRequires} from './resources.js';
14
18
 
@@ -80,6 +84,46 @@ export class GramlotFileServer extends GramlotServer {
80
84
  return (await import(await this._moduleUrl(await this.locatePage(path)))).Page;
81
85
  }
82
86
 
87
+ /** Import route-eligible page modules at startup, without calling their methods. */
88
+ async *iterPageClasses() {
89
+ const seenFiles = new Set(), seenClasses = new Set();
90
+ const visit = async function* (directory, prefix = '') {
91
+ const entries = await readdir(directory, {withFileTypes: true});
92
+ for (const entry of entries.sort((a,b)=>a.name.localeCompare(b.name))) {
93
+ if (entry.isSymbolicLink() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
94
+ const logical = prefix + entry.name;
95
+ if (entry.isDirectory()) yield* visit(join(directory,entry.name), logical + '/');
96
+ else if (entry.isFile() && entry.name.endsWith('.js') && !entry.name.endsWith('_aux.js')) yield logical.slice(0,-3);
97
+ }
98
+ };
99
+ for await (const logical of visit(this.pagesDir)) {
100
+ let file;
101
+ try { file = await this.locatePage(logical); }
102
+ catch (error) { if (error instanceof PageNotFound) continue; throw error; }
103
+ file = await realpath(file);
104
+ if (seenFiles.has(file)) continue;
105
+ seenFiles.add(file);
106
+ const module = await import(await this._moduleUrl(file));
107
+ if (!Object.hasOwn(module,'Page') || module.Page === Page) continue;
108
+ const cls = module.Page;
109
+ if (typeof cls !== 'function' || !(cls.prototype instanceof Page)) throw new TypeError(`Invalid Page export: ${file}`);
110
+ if (!seenClasses.has(cls)) { seenClasses.add(cls); yield cls; }
111
+ }
112
+ }
113
+
114
+ /** Read foo_data.tytx beside foo.js. Data files are not public companion URLs. */
115
+ async resolveData(path) {
116
+ const pageFile = await this.locatePage(path);
117
+ const filename = join(dirname(pageFile), `${basename(pageFile, extname(pageFile))}_data.tytx`);
118
+ let real;
119
+ try { real = await realpath(filename); }
120
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
121
+ if (!inside(real, await realpath(this.pagesDir))) throw new Error('Data companion leaves the pages folder');
122
+ const data = fromTytx(await readFile(real, 'utf8'));
123
+ if (!(data instanceof Bag) || data instanceof SourceBag) throw new TypeError('Initial page data must be a Data Bag');
124
+ return data;
125
+ }
126
+
83
127
  /** Page.css URLs as written, then the companion foo.css and the page logic. */
84
128
  async resolveResources(path, PageClass) {
85
129
  if (parseRequires(PageClass.css_requires).length || parseRequires(PageClass.js_requires).length) {
@@ -3,6 +3,8 @@
3
3
  *
4
4
  * @module
5
5
  */
6
+ import type {Bag} from '@genrojs/bag';
7
+ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
6
8
  import type {Page} from './page.js';
7
9
  import type {Resources} from './resources.js';
8
10
  import type {NameSyntax, NameSyntaxDescriptor} from '../builder/name-syntax.js';
@@ -45,6 +47,16 @@ export class ServerCapacity extends Error {
45
47
  /** The outcome of a refused `auth` rule, or null when the call may proceed. */
46
48
  export type AuthOutcome = 'not_authenticated' | 'not_authorized' | null;
47
49
 
50
+ /** Prepared artifact metadata, also accepted by Page.gramlots. */
51
+ export interface PreparedCollection {
52
+ name: string;
53
+ buildId: string;
54
+ grammar: Record<string, unknown>;
55
+ module: string;
56
+ css: string[];
57
+ dependencies: string[];
58
+ }
59
+
48
60
  /** The options of a `GramlotServer`. */
49
61
  export interface GramlotServerOptions {
50
62
  /** URL of the runtime bundle. */
@@ -60,7 +72,7 @@ export interface GramlotServerOptions {
60
72
  /** Maximum number of registered pages. */
61
73
  maxPages?: number;
62
74
  /** Application collections: generated Builder grammar and root-relative browser module URL. */
63
- collections?: {grammar: Record<string, unknown>; module: string}[];
75
+ collections?: PreparedCollection[];
64
76
  /** The base theme of every page, a folder of the core themes, or false for none; default `gramlot-base`. */
65
77
  cssTheme?: string | false;
66
78
  }
@@ -110,11 +122,17 @@ export class GramlotServer {
110
122
  /** The base theme of every page, or false for none. */
111
123
  cssTheme: string | false;
112
124
  /** The registered pages by id. */
113
- pages: Map<string, {PageClass: typeof Page; owner: unknown; expires: number}>;
125
+ pages: Map<string, {PageClass: typeof Page; path: string; owner: unknown; expires: number}>;
114
126
  /** Create a server. */
127
+ /** Resolve class-local declarations and their named dependencies, base first. */
128
+ pageCollections(PageClass: typeof Page): PreparedCollection[];
129
+ collectionGraph(collections: PreparedCollection[]): PreparedCollection[];
130
+ loadCollections(builder: GramlotBuilder, collections: PreparedCollection[]): void;
115
131
  constructor(options?: GramlotServerOptions);
116
132
  /** The Page class of `path`, or `PageNotFound`. */
117
133
  pageManifest(options?: {prefix?: string}): Promise<Record<string, unknown>>;
134
+ /** Optional initial Data Bag; null when the page has no companion. */
135
+ resolveData(path: string): Promise<Bag | null>;
118
136
  resolvePage(path: string): Promise<typeof Page>;
119
137
  /** The resources of the page at `path` in load order and without mount prefix, or `PageNotFound`. */
120
138
  resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
@@ -4,6 +4,8 @@
4
4
  *
5
5
  * @module
6
6
  */
7
+ import {Bag} from '@genrojs/bag';
8
+ import {Collection} from '@genrojs/builders';
7
9
  import {fromTytx, toTytx} from '@genrojs/tytx';
8
10
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
9
11
  import {NAME_SYNTAX} from '../builder/name-syntax.js';
@@ -28,6 +30,17 @@ const OUTCOME_CODES = new Map([[PageExpired, 'page_expired'], [SourceNotFound, '
28
30
 
29
31
  const isMapping = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
30
32
 
33
+ /** Copy resolved grammar metadata, retaining its compiled validation functions.
34
+ * Cardinality Maps and parent Sets remain local to each builder. */
35
+ function clonePreparedSchema(value) {
36
+ if (value === null || typeof value !== 'object') return value;
37
+ if (Array.isArray(value)) return value.map(clonePreparedSchema);
38
+ if (value instanceof Map) return new Map([...value].map(([key, item]) => [key, clonePreparedSchema(item)]));
39
+ if (value instanceof Set) return new Set(value);
40
+ if (!isMapping(value)) throw new TypeError('Unexpected resolved grammar metadata');
41
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clonePreparedSchema(item)]));
42
+ }
43
+
31
44
  /** Whether `value` is JSON written unchanged by `JSON.stringify`: null, a boolean, a string, a finite number,
32
45
  * or an array or plain object of such values, without cycles. The check of Python `json.dumps(allow_nan=False)`. */
33
46
  function isJson(value, ancestors = new Set()) {
@@ -106,14 +119,67 @@ export class GramlotServer {
106
119
  Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
107
120
  this.pages = new Map();
108
121
  this.collections = [...collections];
122
+ this.preparedGrammars = new WeakMap();
109
123
  }
110
124
 
111
125
  /** The Page class of path, or PageNotFound. */
112
126
  async resolvePage(path) { throw new PageNotFound(`Page not found: ${path}`); }
113
127
 
128
+ /** Class-local declarations accumulate base first, just like Python Page.gramlots. */
129
+ pageCollections(PageClass) {
130
+ const classes = [];
131
+ for (let cls = PageClass; cls && cls !== Function.prototype; cls = Object.getPrototypeOf(cls)) classes.unshift(cls);
132
+ return this.collectionGraph([...this.collections, ...classes.flatMap(cls => Object.hasOwn(cls, 'gramlots') ? cls.gramlots : [])]);
133
+ }
134
+
135
+ /** Resolve named dependencies among prepared records; reject ambiguous identities. */
136
+ collectionGraph(collections) {
137
+ const byName = new Map(), visiting = new Set(), done = new Set(), ordered = [];
138
+ for (const collection of collections) {
139
+ if (typeof collection?.name !== 'string' || !collection.name || !Array.isArray(collection.dependencies)) throw new TypeError('Expected prepared collection descriptors');
140
+ const previous = byName.get(collection.name);
141
+ if (previous && previous !== collection && JSON.stringify(previous) !== JSON.stringify(collection)) throw new Error(`Conflicting collection identity: ${collection.name}`);
142
+ byName.set(collection.name, collection);
143
+ }
144
+ const visit = name => {
145
+ if (done.has(name)) return;
146
+ if (visiting.has(name)) throw new Error(`Collection dependency cycle: ${name}`);
147
+ const collection = byName.get(name);
148
+ if (!collection) throw new Error(`Missing collection dependency: ${name}`);
149
+ visiting.add(name);
150
+ for (const dependency of collection.dependencies) visit(dependency);
151
+ visiting.delete(name); done.add(name); ordered.push(collection);
152
+ };
153
+ for (const name of byName.keys()) visit(name);
154
+ return ordered;
155
+ }
156
+
157
+ /** Retain compilation only; every builder keeps independent schema, Source and Data. */
158
+ loadCollections(builder, collections) {
159
+ if (!collections.length) return;
160
+ let cache = this.preparedGrammars.get(builder.constructor);
161
+ if (!cache) this.preparedGrammars.set(builder.constructor, cache = new Map());
162
+ const initial = builder._collection?.toDocument() ?? null;
163
+ const key = JSON.stringify([initial, collections]);
164
+ let prepared = cache.get(key);
165
+ if (!prepared) {
166
+ for (const collection of collections) builder.loadCollection(collection.grammar);
167
+ prepared = {schema: clonePreparedSchema(builder.schema), names: {...builder.schemaTagNames},
168
+ document: builder._collection.toDocument()};
169
+ cache.set(key, prepared);
170
+ } else {
171
+ builder._schemaOverride = clonePreparedSchema(prepared.schema);
172
+ builder._tagNamesOverride = {...prepared.names};
173
+ builder._collection = new Collection(prepared.document);
174
+ }
175
+ }
176
+
114
177
  /** {css: [url], js: [{url, group}]} in load order and without mount prefix, or PageNotFound. */
115
178
  async resolveResources(path, PageClass) { throw new PageNotFound(`Page resources not found: ${path}`); }
116
179
 
180
+ /** Optional initial Data Bag for this page path; no companion in the neutral server. */
181
+ async resolveData(path) { return null; }
182
+
117
183
  /** The capabilities announced in the bootstrap; none in the base server. */
118
184
  get capabilities() {
119
185
  return [];
@@ -202,14 +268,18 @@ export class GramlotServer {
202
268
  if (typeof PageClass !== 'function' || !(PageClass.prototype instanceof Page)) {
203
269
  throw new TypeError('Page modules must export a subclass of Page');
204
270
  }
271
+ const selected = this.pageCollections(PageClass);
205
272
  const resolved = await this.resolveResources(path, PageClass);
206
- const resources = loadOrder({...resolved, css: [...this.themeCss(PageClass), ...resolved.css]});
207
- if (this.collections.length) resources.collections = this.collections.map(item => item.module);
273
+ const resources = loadOrder({...resolved, css: [...this.themeCss(PageClass), ...selected.flatMap(collection=>collection.css ?? []), ...resolved.css]});
274
+ resources.collections = selected.map(({name,module,buildId}) => {
275
+ if (typeof name!=='string' || !name || typeof module!=='string' || !/^sha256:[0-9a-f]{64}$/.test(buildId)) throw new TypeError('Invalid prepared collection identity');
276
+ return {name,url:module,buildId};
277
+ });
208
278
  if (this.serverAdapter !== null) resources.serverAdapter = this.serverAdapter;
209
279
  this.prune();
210
280
  if (this.pages.size >= this.maxPages) throw new ServerCapacity('Page registry capacity reached');
211
281
  const pageId = crypto.randomUUID().replaceAll('-', '');
212
- this.pages.set(pageId, {PageClass, owner, expires: this.#expiry()});
282
+ this.pages.set(pageId, {PageClass, path, owner, expires: this.#expiry()});
213
283
  return {pageId, title: PageClass.title, resources, nameSyntax: this.nameSyntax.toJSON(),
214
284
  ...(PageClass.devices.length ? {devices: [...PageClass.devices]} : {}),
215
285
  ...(PageClass.locale == null ? {} : {locale: PageClass.locale}),
@@ -229,7 +299,7 @@ export class GramlotServer {
229
299
  rootId: this.rootId, capabilities: this.capabilities, nameSyntax,
230
300
  ...(devices === undefined ? {} : {devices}),
231
301
  ...(locale === undefined ? {} : {locale}), ...(timeZone === undefined ? {} : {timeZone})},
232
- resources: {...(resources.collections ? {collections: resources.collections.map(url => prefixed(prefix, url))} : {}),
302
+ resources: {...(resources.collections ? {collections: resources.collections.map(record => ({...record,url:prefixed(prefix,record.url)}))} : {}),
233
303
  css: resources.css.map(url => prefixed(prefix, url)),
234
304
  js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group})),
235
305
  ...(resources.serverAdapter ? {serverAdapter: prefixed(prefix, resources.serverAdapter)} : {})},
@@ -245,7 +315,9 @@ export class GramlotServer {
245
315
  }
246
316
  // A page module served for its Logic imports the core from the runtime already loaded.
247
317
  head.script(scriptJson({imports: {'@gramlot/gramlot/page': prefixed(prefix, this.runtimeUrl),
248
- '@gramlot/gramlot': prefixed(prefix, this.runtimeUrl)}}),
318
+ '@gramlot/gramlot': prefixed(prefix, this.runtimeUrl),
319
+ '@gramlot/gramlot/components':prefixed(prefix,this.runtimeUrl),
320
+ ...Object.fromEntries((resources.collections ?? []).map(({name,url})=>[`@gramlot/collections/${encodeURIComponent(name)}`,prefixed(prefix,url)]))}}),
249
321
  {type: 'importmap', nonce});
250
322
  const body = root.body();
251
323
  body.div({id: this.rootId});
@@ -279,9 +351,17 @@ export class GramlotServer {
279
351
  const response = {id: request.id, contentType: request.contentType};
280
352
  try {
281
353
  response.value = (await this.#run(request, owner, identity)) ?? null;
354
+ if (request.contentType === 'source' && request.name === 'main') {
355
+ const data = await this.resolveData(this.pages.get(request.pageId).path);
356
+ if (data !== null) {
357
+ if (!(data instanceof Bag)) throw new TypeError('Initial page data must be a Bag');
358
+ response.data = data;
359
+ }
360
+ }
282
361
  return toTytx(response);
283
362
  } catch (error) {
284
363
  delete response.value;
364
+ delete response.data;
285
365
  response.error = {code: OUTCOME_CODES.get(error?.constructor) ?? 'application_error',
286
366
  name: error?.name ?? 'Error', message: error?.message ?? String(error)};
287
367
  if (gramlotDev() === 'DEBUG') response.error.details = error?.stack;
@@ -325,7 +405,7 @@ export class GramlotServer {
325
405
  if (!source) return callable.call(instance, params);
326
406
  const builder = new record.PageClass.sourceBuilder(name,
327
407
  {auth: elementRule => this.#authOutcome(elementRule, owner, identity), nameSyntax: this.nameSyntax});
328
- for (const collection of this.collections) builder.loadCollection(collection.grammar);
408
+ this.loadCollections(builder, this.pageCollections(record.PageClass));
329
409
  const result = await callable.call(instance, builder.root, params);
330
410
  if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
331
411
  return builder.toTytx();
@@ -96,6 +96,7 @@ export class Exposed {
96
96
 
97
97
  /** Server-side page base; unrelated to browser view components. */
98
98
  export class Page extends Exposed {
99
+ static gramlots = [];
99
100
  static title = 'Gramlot';
100
101
  static devices = [];
101
102
  static locale = null;
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
+ import type {PreparedCollection} from './gramlot-server.js';
7
8
  import type {GramlotBuilder} from '../builder/gramlot-builder.js';
8
9
 
9
10
  /** The marker of a Source method: `{auth}` on the method. */
@@ -46,6 +47,8 @@ export class Exposed {
46
47
  export class Page extends Exposed {
47
48
  /** The title of the page document. */
48
49
  static title: string;
50
+ /** Class-local prepared collections; inherited declarations accumulate. */
51
+ static gramlots: PreparedCollection[];
49
52
  static devices: Array<'desktop' | 'tablet' | 'phone'>;
50
53
  static locale: string | null;
51
54
  static timeZone: string | null;
@@ -3,13 +3,17 @@
3
3
  * target selection; this binding owns execution, ask, delay and disposal.
4
4
  */
5
5
 
6
+ import {SourceBag} from '@genrojs/builders';
6
7
  import {invokeHook} from '../binding/hooks.js';
8
+ import {captureCommand} from './menu-command.js';
7
9
 
8
10
  export class ButtonBinding {
9
11
  #binding;
10
12
  #record;
11
13
  #cancelDelay = null;
12
14
  #pendingCount = 0;
15
+ #activations = new Set();
16
+ #warnedCommand = null;
13
17
 
14
18
  /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
15
19
  static for(binding, record) {
@@ -48,7 +52,15 @@ export class ButtonBinding {
48
52
  const found = [];
49
53
  if (controllers.length) found.push('controller');
50
54
  if (attrs.action != null) found.push('action');
55
+ if (node.nodeTag === 'menuline' && attrs.command != null) found.push('registered');
51
56
  if (fireAttributes(attrs).length) found.push('fire');
57
+ if (node.nodeTag === 'menuline' && node.value instanceof SourceBag
58
+ && node.value.getNodes().some(child => child.nodeTag === 'menu') && found.length) {
59
+ throw new Error(`menuline '${node.label}': a submenu cannot also execute a command`);
60
+ }
61
+ if (node.nodeTag==='menuline' && attrs.group && found.length) {
62
+ throw new Error(`menuline '${node.label}': a group cannot execute a command`);
63
+ }
52
64
  if (found.length > 1) {
53
65
  throw new Error(`${node.nodeTag} '${node.label}': ${found.join(' and ')} together; a button has one click mechanism`);
54
66
  }
@@ -68,6 +80,16 @@ export class ButtonBinding {
68
80
  * again, so an ambiguity raises now, and a button that gained a mechanism gets `type="button"`.
69
81
  */
70
82
  refresh() {
83
+ if (this.node.nodeTag === 'menuline') {
84
+ const command = this.node.getAttr('command');
85
+ const definition = command ? this.binding.runtime.gramlot.commands.get(command) : null;
86
+ this.element.setCommandDefinition(definition, this.node.label);
87
+ if (command && !definition && this.#warnedCommand !== command) {
88
+ console.warn(`Unknown command '${command}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`);
89
+ this.#warnedCommand = command;
90
+ }
91
+ }
92
+ for (const activation of this.#activations) if (!activation.current()) activation.cancel();
71
93
  const mechanism = this.mechanism;
72
94
  if (mechanism && this.node.getAttr('type') == null && this.element.getAttribute('type') !== 'button') {
73
95
  this.element.setAttribute('type', 'button');
@@ -79,6 +101,8 @@ export class ButtonBinding {
79
101
  this.element.releaseCommand();
80
102
  delete this.element.activateCommand;
81
103
  this.#cancelDelay?.();
104
+ for (const activation of this.#activations) { activation.cancel(); activation.release(); }
105
+ this.#activations.clear();
82
106
  }
83
107
 
84
108
  handleEvent(event) {
@@ -103,6 +127,9 @@ export class ButtonBinding {
103
127
  if (!mechanism) return;
104
128
  event.stopPropagation();
105
129
  if (this.element.disabled) return;
130
+ const activation = mechanism === 'registered' ? captureCommand(this.binding, event) : null;
131
+ if (mechanism === 'registered' && !activation) return;
132
+ if (activation) this.#activations.add(activation);
106
133
  const counter = this.binding.countClick();
107
134
  // Legacy reads inherited _delay. An explicit zero overrides an ancestor's delay.
108
135
  let owner = this.node;
@@ -116,11 +143,12 @@ export class ButtonBinding {
116
143
  release();
117
144
  this.#cancelDelay = null;
118
145
  this.#pendingCount = 0;
119
- this.#execute(event, count);
146
+ this.#execute(event, count, activation);
120
147
  }, delay);
121
148
  const release = this.binding.track(() => this.#cancelDelay?.());
122
149
  this.#cancelDelay = () => {
123
150
  clearTimeout(timer);
151
+ if (activation) { activation.cancel(); activation.release(); this.#activations.delete(activation); }
124
152
  release();
125
153
  this.#cancelDelay = null;
126
154
  this.#pendingCount = 0;
@@ -128,11 +156,27 @@ export class ButtonBinding {
128
156
  return;
129
157
  }
130
158
  this.#cancelDelay?.();
131
- return this.#execute(event, counter);
159
+ return this.#execute(event, counter, activation);
160
+ }
161
+
162
+ async #executeRegistered(activation) {
163
+ try {
164
+ if (!activation.current()) return;
165
+ const ask = this.node.getAttr('ask'), dialog = this.binding.runtime.askDialog;
166
+ const keywords = {...activation.message.parameters};
167
+ if (ask && dialog.required(this.binding, ask, keywords, 'ask')) {
168
+ const result = await dialog.show(this.binding, ask, keywords);
169
+ if (result === null) return;
170
+ }
171
+ activation.deliver();
172
+ } finally {
173
+ activation.release(); this.#activations.delete(activation);
174
+ }
132
175
  }
133
176
 
134
177
  /** Deliver the last event once; arguments are read when the mechanism executes. */
135
- #execute(event, counter) {
178
+ #execute(event, counter, activation = null) {
179
+ if (activation) return this.#executeRegistered(activation);
136
180
  if (this.binding.closed || this.element.disabled) return;
137
181
  const mechanism = this.mechanism;
138
182
  if (!mechanism) return;
@@ -581,6 +581,14 @@ function componentContext(adapter) {
581
581
  callLogic:(name, keywords) => callLogic(binding.runtime, node, name, keywords),
582
582
  format:(value, options) => app.format(value, options), invoke,
583
583
  remote:(method, keywords, signal) => app.rpc.call('data', method, keywords, {signal}),
584
+ selectionOutputs:({selectedCaption, selectedRecord, fields}, row) => {
585
+ if (binding.closed) return;
586
+ if (selectedCaption) node.setRelativeData(selectedCaption, row?.caption ?? null);
587
+ if (selectedRecord) node.setRelativeData(selectedRecord, row ? new Bag(row.record) : null);
588
+ for (const [name, path] of Object.entries(fields)) {
589
+ node.setRelativeData(path, row?.record[name.slice(9)] ?? null);
590
+ }
591
+ },
584
592
  validationCurrent:() => {
585
593
  const pointer = node.getAttr('value');
586
594
  const path = node.pointerType(pointer) ? node.absDatapath(pointer) : null;
package/src/view/html.js CHANGED
@@ -65,6 +65,7 @@ export class HtmlElement {
65
65
  }
66
66
  for (const [key, value] of Object.entries(node.attr)) {
67
67
  if (key === 'value' && this.definition(node).meta.gramlot_component) continue;
68
+ if (node.nodeTag === 'menuline' && key === 'parameters') continue;
68
69
  if (this.metadataAttributes.has(key) || ['ask', '_ask'].includes(key) || (value && typeof value === 'object' && Object.hasOwn(value, '$gramlotRef'))) continue;
69
70
  if (value != null && !['string', 'number', 'boolean'].includes(typeof value)) {
70
71
  throw new TypeError(`HTML attribute ${key} must be scalar`);
@@ -139,6 +140,13 @@ export class HtmlElement {
139
140
  * control belongs to its ControlAdapter: neither the attribute nor the property is written here.
140
141
  */
141
142
  update(record, node, attrs = node.attr, textValue = DEFAULT_TEXT, visible = null) {
143
+ if (node.nodeTag === 'script') {
144
+ for (const [name, code] of node.codeAttributes()) {
145
+ if (node.activatedCode(name) !== code) {
146
+ throw new Error(`script '${node.label}': '${name}' runs only as received with the Source`);
147
+ }
148
+ }
149
+ }
142
150
  const {element, text} = record;
143
151
  const isHtml = element.namespaceURI === XHTML_NS;
144
152
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
@@ -0,0 +1,45 @@
1
+ /** Registered commands use the existing node-scoped publication bus. */
2
+ import {SourceBag} from '@genrojs/builders';
3
+ import {toTytx,fromTytx} from '@genrojs/tytx';
4
+
5
+ export function commandFrame(node) {
6
+ for(let parent=node.parentNode;parent;parent=parent.parentNode)if(parent.nodeTag==='framePane')return parent;
7
+ return null;
8
+ }
9
+ export function frameRecipient(frame) {
10
+ if(!frame || !(frame.value instanceof SourceBag))return null;
11
+ const center=frame.value.getNodes().find(node=>node.getAttr('region')==='center');
12
+ const targets=[];
13
+ function visit(node){
14
+ if(node.nodeTag==='framePane')return;
15
+ if(node.getAttr('frameTarget')===true)targets.push(node);
16
+ if(node.value instanceof SourceBag)for(const child of node.value.getNodes())visit(child);
17
+ }
18
+ if(center)visit(center);
19
+ return targets.length===1?targets[0]:null;
20
+ }
21
+ function eligible(binding){
22
+ if(binding.closed||!binding.runtime.renderer.attached(binding.node))return false;
23
+ for(let node=binding.node;node;node=node.parentNode){
24
+ const [,attrs]=node.rootBuilder.runtimeValues(node);
25
+ if(attrs.hidden===true||attrs.disabled===true)return false;
26
+ }
27
+ return true;
28
+ }
29
+ function freeze(value){if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}return value;}
30
+ export function captureCommand(binding,event){
31
+ const sender=binding.node,command=sender.getAttr('command');
32
+ const definition=binding.runtime.gramlot.commands.get(command);
33
+ const frame=commandFrame(sender),target=frameRecipient(frame);
34
+ if(!definition||!target){console.warn(`Cannot dispatch command '${command}' at '${sender.label}': missing or duplicate frame recipient`);return null;}
35
+ const raw=sender.getAttr('parameters')??{};
36
+ if(typeof raw!=='object'||Array.isArray(raw))throw new TypeError('Command parameters require a mapping');
37
+ const values=Object.fromEntries(Object.entries(raw).map(([key,value])=>[key,sender.pointerType(value)?sender.getRelativeData(value):value]));
38
+ const parameters=freeze(fromTytx(toTytx(values)));
39
+ const modifiers=Object.freeze(Object.fromEntries(['shift','ctrl','alt','meta'].map(key=>[key,Boolean(event[`${key}Key`])])));
40
+ const message=Object.freeze({sender,target,command,parameters,modifiers});
41
+ let cancelled=false;
42
+ const release=binding.runtime.bindingFor(target).track(()=>{cancelled=true;});
43
+ const current=()=>!cancelled&&eligible(binding)&&frameRecipient(frame)===target&&binding.runtime.renderer.attached(target)&&sender.getAttr('command')===command;
44
+ return {message,current,release,cancel(){cancelled=true;},deliver(){if(current())target.publish(definition.publish,message);}};
45
+ }