@gramlot/gramlot 0.2.16 → 0.2.18

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 (47) hide show
  1. package/assets/branding/app-icon.png +0 -0
  2. package/dist/gramlot.js +1413 -235
  3. package/dist/gramlot.min.js +74 -17
  4. package/package.json +9 -5
  5. package/src/binding/ask-dialog.js +108 -0
  6. package/src/binding/providers.js +41 -6
  7. package/src/binding/remote.js +19 -20
  8. package/src/binding/runtime.js +38 -2
  9. package/src/builder/gramlot-builder.js +21 -3
  10. package/src/builder/source.js +18 -5
  11. package/src/builder/webcomponent.json +51 -0
  12. package/src/frame-messages.js +177 -0
  13. package/src/gramlot.d.ts +14 -0
  14. package/src/gramlot.js +9 -1
  15. package/src/handlers/rpc-handler.js +2 -0
  16. package/src/handlers/source-handler.js +1 -0
  17. package/src/handlers/subscriptions-handler.js +103 -0
  18. package/src/index-page-runtime.d.ts +11 -0
  19. package/src/index-page-runtime.js +287 -0
  20. package/src/index-page-styles.js +2 -0
  21. package/src/index-theme.js +5 -0
  22. package/src/index.d.ts +4 -1
  23. package/src/index.js +3 -0
  24. package/src/inout.js +3 -1
  25. package/src/references.d.ts +5 -0
  26. package/src/references.js +23 -1
  27. package/src/renderer/attributes.js +14 -3
  28. package/src/renderer/gramlot-html-renderer.js +9 -2
  29. package/src/renderer/gramlot-renderer.js +5 -1
  30. package/src/renderer/gramlot-svg-renderer.js +2 -1
  31. package/src/server/conformance.js +22 -2
  32. package/src/server/gramlot-server.d.ts +1 -0
  33. package/src/server/gramlot-server.js +12 -0
  34. package/src/server/index-page.d.ts +14 -0
  35. package/src/server/index-page.js +102 -0
  36. package/src/server/page-base.js +88 -0
  37. package/src/server/page.d.ts +8 -2
  38. package/src/server/page.js +3 -76
  39. package/src/view/button.js +17 -3
  40. package/src/view/html.js +4 -3
  41. package/src/webcomponent.js +13 -0
  42. package/themes/gramlot-base/README.md +8 -0
  43. package/themes/gramlot-compact/README.md +49 -0
  44. package/themes/gramlot-compact/theme.css +57 -0
  45. package/themes/gramlot-index/theme.css +51 -0
  46. package/tools/gramlot-tools-inspector.js +1733 -0
  47. package/tools/inspector-agent.js +252 -0
@@ -0,0 +1,287 @@
1
+ /* @ts-self-types="./index-page-runtime.d.ts" */
2
+ import {compactStyle} from './index-page-styles.js';
3
+ import {THEME_READY, THEME_SET, THEMES, APPEARANCES} from './index-theme.js';
4
+
5
+ /** Index-page behavior; writes UI state through the existing Source records. */
6
+ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEntry = () => {}) {
7
+ const shell = renderer.records.get(root).element;
8
+ const document = shell.ownerDocument;
9
+ const window = document.defaultView;
10
+ const byId = id => document.getElementById(id);
11
+ const node = element => renderer.elements.get(element).node;
12
+ const set = (element, attrs) => node(element).setAttr(attrs);
13
+ const keyboard = byId('keyboard-navigation');
14
+ const theme = byId('index-theme');
15
+ const appearance = byId('index-appearance');
16
+ const sidebar = byId('index-sidebar');
17
+ const sidebarHandle = byId('index-sidebar-divider');
18
+ // localStorage is scoped to this origin; the path separates mounted galleries.
19
+ const preferencesKey = `gramlot.${shell.id}.preferences:${window.location.pathname}`;
20
+ let preferences = {};
21
+ try {
22
+ const saved = JSON.parse(window.localStorage.getItem(preferencesKey));
23
+ if (saved !== null && typeof saved === 'object' && !Array.isArray(saved)) preferences = saved;
24
+ } catch (error) {
25
+ if (error.name !== 'SyntaxError' && error.name !== 'SecurityError') throw error;
26
+ }
27
+ const restoreChoice = (control, value, allowed) => {
28
+ if (!control || !allowed.has(value)) return;
29
+ set(control, {value});
30
+ for (const option of control.options) set(option, {selected: option.value === value});
31
+ };
32
+ restoreChoice(theme, preferences.theme, THEMES);
33
+ restoreChoice(appearance, preferences.appearance, APPEARANCES);
34
+ const families = [...shell.querySelectorAll('.index-sidebar details')];
35
+ const Bag = root.builder.data.constructor;
36
+ const state = new Bag();
37
+ const opened = new Bag();
38
+ state.setItem('opened', opened);
39
+ state.setItem('keyboard', (keyboard?.checked ?? false));
40
+ state.setItem('theme', (theme?.value ?? 'light'));
41
+ state.setItem('appearance', (appearance?.value ?? 'compact'));
42
+ const savePreferences = () => {
43
+ try {
44
+ window.localStorage.setItem(preferencesKey, JSON.stringify({
45
+ theme: state.getItem('theme'), appearance: state.getItem('appearance'),
46
+ sidebarWidth: state.getItem('preferredSidebarWidth'),
47
+ }));
48
+ } catch (error) {
49
+ // A browser may deny storage (including opaque file origins) or exhaust its quota.
50
+ // Keep the current interaction usable; no other persistence mechanism is used.
51
+ if (error.name !== 'SecurityError' && error.name !== 'QuotaExceededError') throw error;
52
+ }
53
+ };
54
+ const entries = new Map();
55
+ const releases = [];
56
+ const style = root.builder.wrapSource(root.value).style(compactStyle, {media: (appearance?.value ?? 'compact') === 'compact' ? 'all' : 'not all'});
57
+ let drag = null;
58
+ let disposed = false;
59
+ let installPrompt = null;
60
+ const previousTheme = document.documentElement.getAttribute('data-theme');
61
+ const listen = (element, type, handler) => {
62
+ if (!element) return;
63
+ element.addEventListener(type, handler);
64
+ releases.push(() => element.removeEventListener(type, handler));
65
+ };
66
+ const stopDrag = () => {
67
+ if (!drag) return;
68
+ const {handle, pointerId} = drag;
69
+ drag = null;
70
+ if (!disposed) set(shell, {data_resizing: null});
71
+ if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
72
+ };
73
+ const dispose = () => {
74
+ if (disposed) return;
75
+ disposed = true;
76
+ installPrompt = null;
77
+ stopDrag();
78
+ for (const release of releases.reverse()) release();
79
+ if (style.parentBag) style.parentBag.popNode(style.label);
80
+ if (previousTheme == null) document.documentElement.removeAttribute('data-theme');
81
+ else document.documentElement.setAttribute('data-theme', previousTheme);
82
+ };
83
+ const send = frame => frame.contentWindow.postMessage({type: THEME_SET, theme: state.getItem('theme'), appearance: state.getItem('appearance')}, '*');
84
+ const applyTheme = () => {
85
+ document.documentElement.setAttribute('data-theme', state.getItem('theme'));
86
+ style.setAttr({media: state.getItem('appearance') === 'compact' ? 'all' : 'not all'});
87
+ for (const {frame} of entries.values()) if (frame) send(frame);
88
+ };
89
+ const updateInspector = () => onSelection(entries, state.getItem('active'));
90
+ function select(key) {
91
+ const entry = entries.get(key);
92
+ if (!opened.getItem(key)) {
93
+ opened.setItem(key, true);
94
+ set(entry.tab, {hidden: false});
95
+ if (entry.frame) set(entry.frame, {src: entry.open.getAttribute('href')});
96
+ }
97
+ if (entry.family) set(entry.family, {open: true});
98
+ for (const [current, item] of entries) {
99
+ const active = current === key;
100
+ set(item.tab, {aria_selected: String(active), tabindex: active && state.getItem('keyboard') ? 0 : -1});
101
+ set(item.panel, {hidden: !active});
102
+ if (item.open) set(item.open, {aria_current: active ? 'page' : null});
103
+ }
104
+ state.setItem('active', key);
105
+ updateInspector();
106
+ }
107
+ function setRatio(entry, value) {
108
+ const ratio = Math.max(20, Math.min(80, value));
109
+ state.setItem(`ratio.${entry.key}`, ratio);
110
+ set(entry.split, {style: `--split-position: ${ratio}%`});
111
+ set(entry.handle, {aria_valuenow: ratio});
112
+ }
113
+ const sidebarMaximum = () => Math.max(120, Math.min(460, Math.floor(window.innerWidth * .6)));
114
+ const setSidebarWidth = (value, remember = false) => {
115
+ const maximum = sidebarMaximum();
116
+ const width = Math.max(120, Math.min(maximum, value));
117
+ state.setItem('sidebarWidth', width);
118
+ set(shell, {style: `--sidebar-width: ${width}px`});
119
+ set(sidebarHandle, {aria_valuenow: width, aria_valuemax: maximum});
120
+ if (remember) {
121
+ state.setItem('preferredSidebarWidth', width);
122
+ savePreferences();
123
+ }
124
+ };
125
+ const beginDrag = (handle, event, move) => {
126
+ if (event.button !== 0) return;
127
+ stopDrag();
128
+ handle.setPointerCapture(event.pointerId);
129
+ drag = {handle, pointerId: event.pointerId, move};
130
+ set(shell, {data_resizing: 'true'});
131
+ event.preventDefault();
132
+ };
133
+ try {
134
+ const install = byId('index-install-button');
135
+ if (install) {
136
+ listen(window, 'beforeinstallprompt', event => {
137
+ event.preventDefault();
138
+ installPrompt = event;
139
+ set(install, {hidden: false, disabled: false});
140
+ });
141
+ listen(window, 'appinstalled', () => {
142
+ installPrompt = null;
143
+ set(install, {hidden: true});
144
+ node(byId('index-install-status')).setValue('App installed.');
145
+ });
146
+ listen(install, 'click', async () => {
147
+ if (!installPrompt) return;
148
+ const prompt = installPrompt;
149
+ installPrompt = null;
150
+ set(install, {disabled: true});
151
+ try {
152
+ await prompt.prompt();
153
+ const {outcome} = await prompt.userChoice;
154
+ if (!disposed) node(byId('index-install-status')).setValue(
155
+ outcome === 'accepted' ? 'Installation accepted.' : 'Installation cancelled. You can also use the browser menu.');
156
+ } catch (error) {
157
+ if (!disposed) node(byId('index-install-status')).setValue(`Installation failed: ${error.message}`);
158
+ } finally {
159
+ if (!disposed) set(install, {hidden: true});
160
+ }
161
+ });
162
+ }
163
+ set(shell, {data_resizing: null});
164
+ // Retain the preferred width when a narrow viewport temporarily limits the visible sidebar.
165
+ const savedWidth = preferences.sidebarWidth;
166
+ const width = typeof savedWidth === 'number' && Number.isFinite(savedWidth) && savedWidth >= 120 && savedWidth <= 460
167
+ ? savedWidth : sidebar.getBoundingClientRect().width || Number(sidebarHandle.getAttribute('aria-valuenow'));
168
+ state.setItem('preferredSidebarWidth', width);
169
+ setSidebarWidth(width);
170
+ listen(sidebarHandle, 'keydown', event => {
171
+ const current = state.getItem('sidebarWidth');
172
+ const value = event.key === 'ArrowLeft' ? current - 10 : event.key === 'ArrowRight' ? current + 10
173
+ : event.key === 'Home' ? 120 : event.key === 'End' ? sidebarMaximum() : null;
174
+ if (value == null) return;
175
+ event.preventDefault();
176
+ setSidebarWidth(value, true);
177
+ });
178
+ listen(sidebarHandle, 'pointerdown', event => beginDrag(sidebarHandle, event,
179
+ x => setSidebarWidth(Math.round(x - shell.getBoundingClientRect().left), true)));
180
+ listen(sidebarHandle, 'lostpointercapture', () => {
181
+ if (drag?.handle === sidebarHandle) stopDrag();
182
+ });
183
+ listen(window, 'resize', () => setSidebarWidth(state.getItem('preferredSidebarWidth')));
184
+ for (const tab of shell.querySelectorAll('.index-tabs button')) {
185
+ const key = tab.id.slice('tab-'.length);
186
+ const entry = {key, tab, panel: byId(`panel-${key}`),
187
+ open: key === 'intro' ? null : byId(`open-${key}`)};
188
+ entries.set(key, entry);
189
+ if (!tab.hidden) opened.setItem(key, true);
190
+ if (tab.getAttribute('aria-selected') === 'true') state.setItem('active', key);
191
+ listen(tab, 'click', () => select(key));
192
+ if (entry.open) listen(entry.open, 'click', event => { event.preventDefault(); select(key); });
193
+ listen(tab, 'keydown', event => {
194
+ if (!state.getItem('keyboard') || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
195
+ const keys = [...entries.keys()].filter(key => opened.getItem(key));
196
+ const index = keys.indexOf(key);
197
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? keys.length - 1
198
+ : (index + (event.key === 'ArrowRight' ? 1 : -1) + keys.length) % keys.length;
199
+ event.preventDefault();
200
+ select(keys[next]);
201
+ entries.get(keys[next]).tab.focus();
202
+ });
203
+ if (key === 'intro') continue;
204
+ entry.family = entry.open.closest('details');
205
+ prepareEntry(entry, {byId, node, set, listen});
206
+ if (entry.panel.classList.contains('index-category')) continue;
207
+ entry.frame = byId(`frame-${key}`);
208
+ entry.split = byId(`split-${key}`);
209
+ entry.handle = byId(`divider-${key}`);
210
+ if (entry.handle) state.setItem(`ratio.${key}`, Number(entry.handle.getAttribute('aria-valuenow')));
211
+ listen(entry.frame, 'load', () => send(entry.frame));
212
+ if (!entry.handle) continue;
213
+ listen(entry.handle, 'keydown', event => {
214
+ const current = state.getItem(`ratio.${key}`);
215
+ const value = event.key === 'ArrowLeft' ? current - 5 : event.key === 'ArrowRight' ? current + 5
216
+ : event.key === 'Home' ? 20 : event.key === 'End' ? 80 : null;
217
+ if (value == null) return;
218
+ event.preventDefault();
219
+ setRatio(entry, value);
220
+ });
221
+ listen(entry.handle, 'pointerdown', event => beginDrag(entry.handle, event, x => {
222
+ const bounds = entry.split.getBoundingClientRect();
223
+ if (bounds.width > 0) setRatio(entry, Math.round((x - bounds.left) * 100 / bounds.width));
224
+ }));
225
+ listen(entry.handle, 'lostpointercapture', () => {
226
+ if (drag?.handle === entry.handle) stopDrag();
227
+ });
228
+ }
229
+ listen(document, 'pointermove', event => {
230
+ if (!drag || event.pointerId !== drag.pointerId) return;
231
+ drag.move(event.clientX);
232
+ });
233
+ for (const type of ['pointerup', 'pointercancel']) listen(document, type, event => {
234
+ if (drag && event.pointerId === drag.pointerId) stopDrag();
235
+ });
236
+ for (const family of families) listen(family, 'toggle', () => set(family, {open: family.open}));
237
+ listen(keyboard, 'change', () => {
238
+ state.setItem('keyboard', (keyboard?.checked ?? false));
239
+ set(keyboard, {checked: (keyboard?.checked ?? false)});
240
+ for (const [key, entry] of entries) {
241
+ if (entry.open) set(entry.open, {tabindex: (keyboard?.checked ?? false) ? 0 : -1});
242
+ set(entry.tab, {tabindex: (keyboard?.checked ?? false) && key === state.getItem('active') ? 0 : -1});
243
+ }
244
+ });
245
+ listen(appearance, 'change', () => {
246
+ if (!APPEARANCES.has((appearance?.value ?? 'compact'))) throw new Error('Index appearance must be base or compact');
247
+ state.setItem('appearance', (appearance?.value ?? 'compact'));
248
+ set(appearance, {value: (appearance?.value ?? 'compact')});
249
+ for (const option of appearance.options) set(option, {selected: option.value === (appearance?.value ?? 'compact')});
250
+ applyTheme();
251
+ savePreferences();
252
+ });
253
+ listen(theme, 'change', () => {
254
+ if (!THEMES.has((theme?.value ?? 'light'))) throw new Error('Index theme must be light or dark');
255
+ state.setItem('theme', (theme?.value ?? 'light'));
256
+ set(theme, {value: (theme?.value ?? 'light')});
257
+ for (const option of theme.options) set(option, {selected: option.value === (theme?.value ?? 'light')});
258
+ applyTheme();
259
+ savePreferences();
260
+ });
261
+ listen(window, 'message', event => {
262
+ if (event.data?.type !== THEME_READY) return;
263
+ for (const {frame} of entries.values()) {
264
+ if (frame && frame.contentWindow === event.source) { send(frame); updateInspector(); break; }
265
+ }
266
+ });
267
+ applyTheme();
268
+ updateInspector();
269
+ renderer.onDispose(root, dispose);
270
+ } catch (error) {
271
+ dispose();
272
+ throw error;
273
+ }
274
+ return {dispose};
275
+ }
276
+
277
+
278
+ /** Re-export as the page's Logic, or delegate indexMount from a custom Logic. */
279
+ export class IndexLogic {
280
+ indexMount(node, {shell_id}) {
281
+ const renderer = this.page.src.renderer;
282
+ const element = renderer.destination.ownerDocument.getElementById(shell_id);
283
+ this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
284
+ }
285
+ }
286
+
287
+ export {THEME_READY, THEME_SET, THEMES, APPEARANCES} from "./index-theme.js";
@@ -0,0 +1,2 @@
1
+ // Generated from themes/gramlot-compact/theme.css.
2
+ export const compactStyle = "/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type=\"button\"]):not([type=\"submit\"]):not([type=\"reset\"]):not([type=\"checkbox\"]):not([type=\"radio\"]):not([type=\"range\"]):not([type=\"color\"]):not([type=\"file\"]):not([type=\"hidden\"]), select, textarea) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type=\"color\"]) { min-block-size: 28px; }\n :where(input[type=\"file\"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n";
@@ -0,0 +1,5 @@
1
+ /** The same bounded parent/frame theme messages serve hosted and local-file pages. */
2
+ export const THEME_READY = 'index:theme-ready';
3
+ export const THEME_SET = 'index:theme-set';
4
+ export const THEMES = new Set(['light', 'dark']);
5
+ export const APPEARANCES = new Set(['base', 'compact']);
package/src/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export {SourceHandler} from './handlers/source-handler.js';
11
11
  export {RpcHandler} from './handlers/rpc-handler.js';
12
12
  export {DomHandler} from './handlers/dom-handler.js';
13
13
  export {UtilitiesHandler} from './handlers/utilities-handler.js';
14
- export type {GramlotOptions, GramlotState} from './gramlot.js';
14
+ export type {GramlotOptions, GramlotState, Publication, SubscriptionHandle} from './gramlot.js';
15
15
  export {PageBootstrap} from './bootstrap.js';
16
16
  export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
17
17
  export {Page} from './server/page.js';
@@ -28,3 +28,6 @@ export {RpcError} from './handlers/rpc-handler.js';
28
28
  export type {RpcErrorOutcome, RpcTransport} from './handlers/rpc-handler.js';
29
29
  export {InOut} from './inout.js';
30
30
  export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, DomNode, DomWindow} from './dom.d.ts';
31
+
32
+ export {IndexPage} from "./server/index-page.js";
33
+ export {IndexLogic, mountIndexPage} from "./index-page-runtime.js";
package/src/index.js CHANGED
@@ -24,3 +24,6 @@ export {References} from './references.js';
24
24
  export {HttpTransport} from './http-transport.js';
25
25
  export {RpcError} from './handlers/rpc-handler.js';
26
26
  export {InOut} from './inout.js';
27
+
28
+ export {IndexPage} from './server/index-page.js';
29
+ export {IndexLogic, mountIndexPage} from './index-page-runtime.js';
package/src/inout.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * @module
6
6
  */
7
7
  import {Bag} from '@genrojs/bag';
8
+ import {fromTytx} from '@genrojs/tytx';
8
9
 
9
10
  /** The practical length limit of a mailto: URL in mail programs and browsers. */
10
11
  export const MAILTO_LIMIT = 2000;
@@ -88,7 +89,8 @@ export class InOut {
88
89
  return new Promise((resolve, reject) => {
89
90
  input.addEventListener('change', async () => {
90
91
  try {
91
- const bag = Bag.fromTytx(await input.files[0].text());
92
+ const bag = fromTytx(await input.files[0].text());
93
+ if (!(bag instanceof Bag)) throw new TypeError('the file must contain a typed Bag');
92
94
  this.gramlot.data.setItem(path, bag);
93
95
  resolve(bag);
94
96
  } catch (error) {
@@ -6,6 +6,9 @@
6
6
  import type {DomElement} from './dom.d.ts';
7
7
  import type {SourceBag, SourceBagNode} from '@genrojs/builders';
8
8
 
9
+ /** @internal Reject live Source/DOM objects and cycles before serializing transport data. */
10
+ export function assertTransportData(value: unknown): void;
11
+
9
12
  /** A transportable descriptor of one Source node, as made by `GramlotBuilder.reference`. */
10
13
  export interface SourceReference {
11
14
  /** The unique id stored in the `__ref` attribute of the Source node. */
@@ -30,4 +33,6 @@ export class References {
30
33
  remove(node: SourceBagNode): void;
31
34
  /** The Source node or the DOM element a descriptor points to; raises when it is not mounted. */
32
35
  resolve(reference: SourceReference): SourceBagNode | DomElement;
36
+ /** Resolve direct reference-valued arguments against the currently mounted Source. */
37
+ resolveArguments(attributes: Record<string, unknown>): Record<string, unknown>;
33
38
  }
package/src/references.js CHANGED
@@ -4,7 +4,23 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {SourceBag} from '@genrojs/builders';
7
+ import {SourceBag, SourceBagNode, sourceTarget} from '@genrojs/builders';
8
+ import {Bag} from '@genrojs/bag';
9
+
10
+ /** Live references have meaning only in their owning page, never on the wire. */
11
+ export function assertTransportData(value, ancestors = new Set()) {
12
+ if (!value || typeof value !== 'object') return;
13
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
14
+ if (sourceTarget(value) instanceof SourceBagNode || (nodeClass && value instanceof nodeClass)) {
15
+ throw new TypeError('Live Source/DOM references cannot cross a transport boundary');
16
+ }
17
+ if (ancestors.has(value)) throw new TypeError('Transport data cannot contain circular references');
18
+ ancestors.add(value);
19
+ const children = value instanceof Bag
20
+ ? value.getNodes().flatMap(node => [node.staticValue, node.getAttr()]) : Object.values(value);
21
+ for (const child of children) assertTransportData(child, ancestors);
22
+ ancestors.delete(value);
23
+ }
8
24
 
9
25
  export class References {
10
26
  constructor(sourceRoot = null) { this.entries = new Map(); this.sourceRoot = sourceRoot; }
@@ -37,6 +53,12 @@ export class References {
37
53
  if (entry.node === node) this.entries.delete(id);
38
54
  }
39
55
  }
56
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
57
+ resolveArguments(attrs) {
58
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [name,
59
+ value && typeof value === 'object' && Object.hasOwn(value, '$gramlotRef')
60
+ ? this.resolve(value) : value]));
61
+ }
40
62
  resolve(reference) {
41
63
  if (!reference || !['node', 'dom'].includes(reference.kind)) {
42
64
  throw new TypeError('Expected a node or DOM reference');
@@ -8,11 +8,11 @@ export const SVG_NS = 'http://www.w3.org/2000/svg';
8
8
  // Binding attributes are read by the Gramlot runtime and never reach the output (source plan, S02).
9
9
  // The names are the resolved ones: runtimeValues turns the keyword names `_if`/`_else` into `if`/`else`.
10
10
  const BINDING_ATTRIBUTES = new Set([
11
- 'default', 'default_value', 'live', 'group', 'visible', 'action', 'fire',
11
+ 'default', 'default_value', 'live', 'group', 'visible', 'action', 'fire', 'ask', '_ask', '_ask_if', '_ask_title', '_ask_onCancel',
12
12
  'if', 'else', '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
13
13
  'remote', '_cachedRemote', '_onRemote',
14
14
  ]);
15
- const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on', 'remote_'];
15
+ const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on', 'subscribe_', 'selfsubscribe_', 'formsubscribe_', 'remote_'];
16
16
 
17
17
  // Legacy noConvertStyle (genro_wdg.js:102-108): these attributes stay native attributes, never style.
18
18
  const NATIVE_ATTRIBUTES = {
@@ -34,10 +34,21 @@ const URL_ATTRIBUTES = new Set(['href', 'src', 'formaction', 'xlink:href', 'xlin
34
34
 
35
35
  /** The attributes of `attrs` that are not binding attributes. */
36
36
  export function withoutBindingAttributes(attrs) {
37
- return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name)
37
+ return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === 'object' && Object.hasOwn(value, '$gramlotRef')) && !BINDING_ATTRIBUTES.has(name)
38
38
  && !BINDING_ATTRIBUTE_PREFIXES.some(prefix => name.startsWith(prefix))));
39
39
  }
40
40
 
41
+ /** Validate resolved style/class before composition, including literal dialect attributes. */
42
+ export function requireStyleClassAttributes(node, attrs, prefixes = []) {
43
+ for (const [name, value] of Object.entries(attrs)) {
44
+ const prefix = prefixes.find(candidate => name.startsWith(candidate)) ?? '';
45
+ const bare = name.slice(prefix.length);
46
+ if (['style', 'class', '_class'].includes(bare) && value != null && typeof value !== 'string') {
47
+ throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
48
+ }
49
+ }
50
+ }
51
+
41
52
  /**
42
53
  * No attribute of `attrs` (resolved, `==` evaluated) makes the browser run a text outside InlineCompiler:
43
54
  * a name starting with `on` and longer than it, the form of the native event handlers, is an error pointing
@@ -6,9 +6,10 @@
6
6
  */
7
7
  import {HtmlBuilder, HtmlRenderer, SvgBuilder, sourceAttributeItems} from '@genrojs/builders';
8
8
  import {GramlotSvgRenderer} from './gramlot-svg-renderer.js';
9
+ import {webcomponentCode} from '../webcomponent.js';
9
10
  import {
10
11
  SVG_NS, XHTML_NS, boundaryAttributes, displayItem, domNames, isExpression, requireNoExpressionTemplate,
11
- requireNoScriptAttributes, splitNativeAttributes, textValue, withDataSrcdocSandbox, withoutBindingAttributes,
12
+ requireNoScriptAttributes, requireStyleClassAttributes, splitNativeAttributes, textValue, withDataSrcdocSandbox, withoutBindingAttributes,
12
13
  withoutNullValues,
13
14
  } from './attributes.js';
14
15
 
@@ -52,7 +53,13 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
52
53
  const prefixes = this.builder.constructor.dialectPrefixes;
53
54
  const evaluated = this.evaluateExpressions(node, runtimeAttrs);
54
55
  requireNoScriptAttributes(node, evaluated, prefixes);
55
- const [tag, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
56
+ let [tag, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
57
+ requireStyleClassAttributes(node, attrs, prefixes);
58
+ if (node.nodeTag === 'webcomponent') {
59
+ tag = webcomponentCode(node.getAttr());
60
+ const {code, ...rest} = attrs;
61
+ attrs = rest;
62
+ }
56
63
  if (node._getMeta('subbuilder')) {
57
64
  const boundary = boundaryAttributes(attrs);
58
65
  if (node._getMeta('subbuilder') === 'html') boundary.xmlns = SVG_NS;
@@ -48,7 +48,8 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
48
48
  this.disposed = false;
49
49
  this.elements = new WeakMap();
50
50
  // The instance id scopes the generated radio names to this page (P11, S11).
51
- this.instanceId = crypto.randomUUID();
51
+ this.instanceId = Array.from(crypto.getRandomValues(new Uint8Array(16)),
52
+ byte => byte.toString(16).padStart(2, '0')).join('');
52
53
  this.radioGroups = new RadioGroups(this);
53
54
  this.subscription = `html-source-renderer-${this.instanceId}`;
54
55
  source.subscribe(this.subscription, {any: event => this.receive(event)});
@@ -179,13 +180,16 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
179
180
  if (!(block instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
180
181
  const excluded = new Set();
181
182
  const exclude = node => {
183
+ if (excluded.has(node)) return;
182
184
  excluded.add(node);
183
185
  for (const child of this.records.get(node)?.children ?? []) exclude(child);
186
+ if (node.value instanceof SourceBag) for (const child of node.value.getNodes()) exclude(child);
184
187
  };
185
188
  // Replacing a node's VALUE retains that node and its reference. Only
186
189
  // the rendered descendants which the replacement removes leave the ref set.
187
190
  // During freeze these can differ from the current Source descendants.
188
191
  for (const child of this.records.get(replacingNode)?.children ?? []) exclude(child);
192
+ if (replacingNode?.value instanceof SourceBag) for (const child of replacingNode.value.getNodes()) exclude(child);
189
193
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
190
194
  requireInstallable(block);
191
195
  this.references?.validate(block, excluded);
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import {SvgRenderer, svgAttributes} from '@genrojs/builders';
8
8
  import {
9
- boundaryAttributes, domNames, requireNoScriptAttributes, textValue, withoutBindingAttributes, withoutNullValues,
9
+ boundaryAttributes, domNames, requireNoScriptAttributes, requireStyleClassAttributes, textValue, withoutBindingAttributes, withoutNullValues,
10
10
  } from './attributes.js';
11
11
 
12
12
  // SVG elements written `<tag … />`, as the Python SvgRenderer of Builder (the grammar gives them no children).
@@ -42,6 +42,7 @@ export class GramlotSvgRenderer extends SvgRenderer {
42
42
  const evaluated = this.owner.evaluateExpressions(node, runtimeAttrs);
43
43
  requireNoScriptAttributes(node, evaluated);
44
44
  const [tag, attrs] = super._handleMeta(node, evaluated);
45
+ requireStyleClassAttributes(node, attrs);
45
46
  return node._getMeta('subbuilder') ? [tag, svgAttributes(boundaryAttributes(attrs))] : [tag, attrs];
46
47
  }
47
48
 
@@ -120,8 +120,28 @@ export async function checkProtocol(baseUrl, pagePath) {
120
120
 
121
121
  response = await request('GET', rpc);
122
122
  expect('GC-230-120', response.status === 405, `GET ${rpc} answers ${response.status}, not 405`);
123
- response = await request('POST', rpc, {body: toTytx(envelope('source', 'main')), contentType: 'text/plain'});
124
- expect('GC-230-120', response.status === 415, `rpc as text/plain answers ${response.status}, not 415`);
123
+ for (const [path, rule, body] of [
124
+ [rpc, 'GC-230-120', toTytx(envelope('data', 'check_endpoint', {value: 'invalid-byte'}))],
125
+ [config.closeUrl, 'GC-230-125', JSON.stringify({pageId, value: 'invalid-byte'})],
126
+ ]) {
127
+ for (const contentType of ['text/plain', 'application/jsonp', 'application/json-extra', '']) {
128
+ response = await request('POST', path, {body, contentType});
129
+ expect(rule, response.status === 415, `${path} as ${JSON.stringify(contentType)} answers ${response.status}, not 415`);
130
+ }
131
+ // Keep JSON syntax valid: a replacing decoder would dispatch this body instead of rejecting it.
132
+ const invalidUtf8 = Buffer.from(body);
133
+ invalidUtf8[invalidUtf8.indexOf('invalid-byte')] = 0xff;
134
+ response = await request('POST', path, {body: invalidUtf8});
135
+ expect(rule, response.status === 400, `${path} with invalid UTF-8 inside a JSON string answers ${response.status}, not 400`);
136
+ }
137
+ for (const contentType of ['Application/JSON', 'application/json; charset=utf-8', 'application/json ; charset=UTF-8']) {
138
+ response = await call(envelope('data', 'check_endpoint', {value: 'media-type'}), {contentType});
139
+ expect('GC-230-120', response.status === 200 && response.received?.value === 'media-type',
140
+ `rpc as ${contentType} answers ${response.status} ${response.body.slice(0, 200)}, not the endpoint value`);
141
+ response = await request('POST', config.closeUrl, {body: JSON.stringify({pageId: '0'.repeat(32)}), contentType});
142
+ expect('GC-230-125', response.status === 200 && isDeepStrictEqual(parse(response.body, JSON.parse), {ok: true}),
143
+ `close as ${contentType} answers ${response.status} ${response.body.slice(0, 200)}, not 200 {"ok": true}`);
144
+ }
125
145
  response = await request('POST', rpc, {body: '{'});
126
146
  expect('GC-230-120', response.status === 400, `rpc with invalid JSON answers ${response.status}, not 400`);
127
147
  const {pageId: omitted, ...withoutPageId} = envelope('source', 'main');
@@ -102,6 +102,7 @@ export class GramlotServer {
102
102
  /** Create a server. */
103
103
  constructor(options?: GramlotServerOptions);
104
104
  /** The Page class of `path`, or `PageNotFound`. */
105
+ pageManifest(options?: {prefix?: string}): Promise<Record<string, unknown>>;
105
106
  resolvePage(path: string): Promise<typeof Page>;
106
107
  /** The resources of the page at `path` in load order and without mount prefix, or `PageNotFound`. */
107
108
  resolveResources(path: string, PageClass: typeof Page): Promise<Resources>;
@@ -106,6 +106,15 @@ export class GramlotServer {
106
106
  for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
107
107
  }
108
108
 
109
+ /** Describe the root application without registering a page session. */
110
+ async pageManifest({prefix = ''} = {}) {
111
+ const PageClass = await this.resolvePage('/');
112
+ if (PageClass.installable !== true) throw new PageNotFound('The root page is not installable');
113
+ const result = await new PageClass().manifest({baseUrl: prefix + '/'});
114
+ if (!isMapping(result)) throw new TypeError('Page.manifest must return a JSON object');
115
+ return result;
116
+ }
117
+
109
118
  /** Register a page independently of its HTTP or Worker transport. */
110
119
  async registerPage(path, {owner = null} = {}) {
111
120
  const PageClass = await this.resolvePage(path);
@@ -139,6 +148,9 @@ export class GramlotServer {
139
148
  const head = root.head();
140
149
  head.meta({charset: 'utf-8'});
141
150
  head.title(title);
151
+ if (['', 'index'].includes(path.replace(/^\/+|\/+$/g, '')) && this.pages.get(pageId).PageClass.installable === true) {
152
+ head.link({rel: 'manifest', href: prefix + '/app.webmanifest'});
153
+ }
142
154
  // A page module served for its Logic imports the core from the runtime already loaded.
143
155
  head.script(scriptJson({imports: {'@gramlot/gramlot/page': prefixed(prefix, this.runtimeUrl)}}),
144
156
  {type: 'importmap', nonce});
@@ -0,0 +1,14 @@
1
+ import {Page} from './page.js';
2
+ export interface IndexItem { key: string; title: string; url: string; }
3
+ export interface IndexGroup { key: string; title: string; children: IndexItem[]; }
4
+ /** One index shell per document. Override footer to replace or extend standard controls. */
5
+ export class IndexPage extends Page {
6
+ static logoUrl: string;
7
+ static shellId: string;
8
+ static navigation: IndexGroup[];
9
+ introduction(pane: any): void;
10
+ groupPanel(pane: any, group: IndexGroup): void;
11
+ panel(pane: any, item: IndexItem): void;
12
+ footer(pane: any): void;
13
+ behavior(pane: any): void;
14
+ }