@gramlot/gramlot 0.2.16 → 0.2.17

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -16,8 +16,8 @@
16
16
  "prepack": "node scripts/build-runtime.mjs"
17
17
  },
18
18
  "dependencies": {
19
- "@genrojs/bag": ">=0.10.3",
20
- "@genrojs/builders": ">=0.4.2",
19
+ "@genrojs/bag": ">=0.11.0",
20
+ "@genrojs/builders": ">=0.5.2",
21
21
  "@genrojs/tytx": ">=0.16.2"
22
22
  },
23
23
  "devDependencies": {
@@ -32,7 +32,9 @@
32
32
  "./page": "./src/server/page.js",
33
33
  "./gramlot-server": "./src/server/gramlot-server.js",
34
34
  "./themes/*": "./themes/*",
35
- "./assets/branding/*": "./assets/branding/*"
35
+ "./assets/branding/*": "./assets/branding/*",
36
+ "./tools/inspector": "./tools/gramlot-tools-inspector.js",
37
+ "./index-page-runtime": "./src/index-page-runtime.js"
36
38
  },
37
39
  "files": [
38
40
  "LICENSE",
@@ -40,7 +42,8 @@
40
42
  "src",
41
43
  "dist",
42
44
  "themes",
43
- "assets"
45
+ "assets",
46
+ "tools"
44
47
  ],
45
48
  "engines": {
46
49
  "node": ">=22"
@@ -1,3 +1,5 @@
1
+ import {toTytx} from '@genrojs/tytx';
2
+
1
3
  /**
2
4
  * The `remote` attribute of a Source node (GC-095 §105): the content of the element is the fragment of a
3
5
  * `@source` method, requested through `gramlot.src.remoteSource` when the node starts and again when a
@@ -5,13 +7,14 @@
5
7
  * request is cancelled with it by `remoteSource` itself (P24), and the answer of a superseded request is
6
8
  * dropped there (latest wins).
7
9
  *
8
- * The control attributes: `_cachedRemote` (no call when the parameters equal the last call's), `_if`
10
+ * The control attributes: `_cachedRemote` (no call when name and parameters equal the last mount's), `_if`
9
11
  * (inline, false → no call, and `_else` runs when present), `_onRemote` (inline, after the fragment is
10
12
  * mounted). The inline code has the parameters as locals and `this` = the node.
11
13
  */
12
14
  export class RemoteBinding {
13
15
  #binding;
14
- // The parameters of the last call, compared by `_cachedRemote`.
16
+ // The name and TYTX parameters of the last mounted call, captured before sending it.
17
+ #lastName = null;
15
18
  #lastParams = null;
16
19
 
17
20
  constructor(binding) {
@@ -25,8 +28,9 @@ export class RemoteBinding {
25
28
  /**
26
29
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
27
30
  * on a closed node, without a name, or when `_if` or `_cachedRemote` stop the call; a false `_if`
28
- * also cancels the request in flight, so its fragment is not mounted after `_else`. A failure of the
29
- * request rejects with an error naming the node, its cause attached.
31
+ * also cancels the request in flight, so its fragment is not mounted after `_else`. A cache hit
32
+ * cancels a pending request too, keeping the mounted fragment. A failure of the request rejects
33
+ * with an error naming the node, its cause attached.
30
34
  */
31
35
  async update() {
32
36
  if (this.closed || !this.binding.hasStamp('start')) return;
@@ -45,15 +49,24 @@ export class RemoteBinding {
45
49
  if (otherwise) this.#inline('_else', otherwise, otherwise, params);
46
50
  return;
47
51
  }
48
- if (attrs._cachedRemote && this.#lastParams && sameValue(params, this.#lastParams)) return;
49
52
  let mounted;
53
+ let text;
50
54
  try {
55
+ text = toTytx(params);
56
+ if (attrs._cachedRemote && name === this.#lastName && text === this.#lastParams) {
57
+ // Keeping the mounted fragment also supersedes any different request still in flight.
58
+ this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
59
+ return;
60
+ }
51
61
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
52
62
  } catch (error) {
53
63
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, {cause: error});
54
64
  }
55
65
  // Only a mounted fragment is the last call `_cachedRemote` compares: a failed request is retried.
56
- if (mounted) this.#lastParams = params;
66
+ if (mounted) {
67
+ this.#lastName = name;
68
+ this.#lastParams = text;
69
+ }
57
70
  const onRemote = node.getAttr('_onRemote');
58
71
  if (mounted && onRemote) this.#inline('_onRemote', onRemote, onRemote, params);
59
72
  }
@@ -62,17 +75,3 @@ export class RemoteBinding {
62
75
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
63
76
  }
64
77
  }
65
-
66
- /** Deep equality of the parameter values: plain objects and arrays by content, dates by time. */
67
- function sameValue(a, b) {
68
- if (Object.is(a, b)) return true;
69
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
70
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
71
- if (!isPlain(a) || !isPlain(b)) return false;
72
- const keys = Object.keys(a);
73
- return keys.length === Object.keys(b).length && keys.every(key => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
74
- }
75
-
76
- function isPlain(value) {
77
- return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
78
- }
@@ -30,7 +30,8 @@ export class BindingRuntime {
30
30
  #router;
31
31
  #installer;
32
32
  #inlineCompiler;
33
- #subscription = `gramlot-data-${crypto.randomUUID()}`;
33
+ #subscription = `gramlot-data-${Array.from(crypto.getRandomValues(new Uint8Array(16)),
34
+ byte => byte.toString(16).padStart(2, '0')).join('')}`;
34
35
  #disposed = false;
35
36
 
36
37
  constructor(gramlot) {
@@ -13,6 +13,8 @@ import {GramlotBuilderBag} from './source.js';
13
13
  import {GramlotHtmlRenderer} from '../renderer/gramlot-html-renderer.js';
14
14
  // Byte copy of src/gramlot/collections/binding.json: the JS package ships js/ only.
15
15
  import BINDING from './binding.json' with {type: 'json'};
16
+ import WEBCOMPONENT from './webcomponent.json' with {type: 'json'};
17
+ import {webcomponentCode} from '../webcomponent.js';
16
18
 
17
19
  // P19: `data` is ambiguous between the legacy data-element and the HTML5 element.
18
20
  const DATA_FORBIDDEN = 'data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element';
@@ -55,6 +57,7 @@ export class GramlotBuilder extends HtmlBuilder {
55
57
  static _sourceClass = GramlotBuilderBag;
56
58
  // Composed on the inherited HtmlBuilder grammar; its data-elements replace Builder's.
57
59
  static { this.defineGrammar(BINDING); }
60
+ static { this.defineGrammar(WEBCOMPONENT); }
58
61
 
59
62
  /** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
60
63
  static get dialectPrefixes() {
@@ -128,6 +131,7 @@ export class GramlotBuilder extends HtmlBuilder {
128
131
 
129
132
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
130
133
  validateNodeValues(tag, value, attrs = {}) {
134
+ if (tag === 'webcomponent') webcomponentCode(attrs);
131
135
  const excluded = excludedAttribute(attrs);
132
136
  if (excluded) throw new Error(`${tag}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
133
137
  const error = dataElementError(tag, attrs);
@@ -137,6 +141,7 @@ export class GramlotBuilder extends HtmlBuilder {
137
141
 
138
142
  /** Builder's node check, plus the excluded attributes (a Source node names tag and label). */
139
143
  validateNode(node, options = {}) {
144
+ if (node.nodeTag === 'webcomponent') webcomponentCode(options.attrs ?? node.getAttr());
140
145
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
141
146
  if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
142
147
  const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
@@ -144,6 +149,11 @@ export class GramlotBuilder extends HtmlBuilder {
144
149
  return super.validateNode(node, options);
145
150
  }
146
151
 
152
+ /** Custom elements are outside the native HTML child catalogue, as components are. */
153
+ _countsForGrammar(info) {
154
+ return info !== this.schema.webcomponent && super._countsForGrammar(info);
155
+ }
156
+
147
157
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
148
158
  setChild(bag, tag, value, attrs, parentOverride = null) {
149
159
  const plain = tag === 'dataSetter' && attrs?.value !== null && typeof attrs?.value === 'object'
@@ -183,7 +193,8 @@ export class GramlotBuilder extends HtmlBuilder {
183
193
  }
184
194
  let id = node.getAttr('__ref');
185
195
  if (id === null || id === undefined) {
186
- id = crypto.randomUUID().replaceAll('-', '');
196
+ id = Array.from(crypto.getRandomValues(new Uint8Array(16)),
197
+ byte => byte.toString(16).padStart(2, '0')).join('');
187
198
  node.setAttr({__ref: id});
188
199
  }
189
200
  return {$gramlotRef: id, kind};
@@ -0,0 +1,51 @@
1
+ {
2
+ "document_format": {
3
+ "name": "builder_grammar",
4
+ "version": "1.1"
5
+ },
6
+ "grammar": {
7
+ "name": "webcomponent",
8
+ "version": null,
9
+ "title": "Gramlot webcomponent",
10
+ "description": "An explicitly loaded autonomous custom element."
11
+ },
12
+ "abstracts": {},
13
+ "elements": {
14
+ "webcomponent": {
15
+ "doc": "Create the custom-element tag named by literal code.",
16
+ "sub_tags": "*",
17
+ "parent_tags": null,
18
+ "inherits_from": null,
19
+ "ns": null,
20
+ "attributes": {
21
+ "parameters": [
22
+ {
23
+ "name": "code",
24
+ "kind": "keyword_only",
25
+ "role": "attribute",
26
+ "annotation": {
27
+ "kind": "type",
28
+ "module": "builtins",
29
+ "name": "str"
30
+ },
31
+ "has_default": false
32
+ },
33
+ {
34
+ "name": "attr",
35
+ "kind": "var_keyword",
36
+ "role": "attribute",
37
+ "annotation": {
38
+ "kind": "any"
39
+ },
40
+ "has_default": false
41
+ }
42
+ ],
43
+ "accepts_var_keyword": true,
44
+ "accepts_var_positional": false
45
+ },
46
+ "node_label": null,
47
+ "collection_key": null,
48
+ "_meta": null
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,11 @@
1
+ export function mountIndexPage(renderer: any, root: any,
2
+ onSelection?: (entries: Map<string, any>, active: string) => void,
3
+ prepareEntry?: (entry: any, context: any) => void): {dispose(): void};
4
+ /** Re-export as Logic, or delegate indexMount from an application's Logic. */
5
+ export class IndexLogic {
6
+ indexMount(node: any, args: {shell_id: string}): void;
7
+ }
8
+ export const THEME_READY: string;
9
+ export const THEME_SET: string;
10
+ export const THEMES: Set<string>;
11
+ export const APPEARANCES: Set<string>;
@@ -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
@@ -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) {
@@ -38,6 +38,17 @@ export function withoutBindingAttributes(attrs) {
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)});