@gramlot/gramlot 0.2.1

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/src/gramlot.js ADDED
@@ -0,0 +1,151 @@
1
+ import {SourceBag, sourceBagFromTytx} from '@genrojs/builders';
2
+ import {GramlotBuilder} from './builder/gramlot-builder.js';
3
+ import {GramlotBuilderBag} from './builder/source.js';
4
+ import {GramlotRenderer} from './renderer/gramlot-renderer.js';
5
+ import {BindingRuntime} from './binding/runtime.js';
6
+ import {LogicRegistry} from './binding/logic.js';
7
+ import {MainTransport} from './transport.js';
8
+
9
+ /**
10
+ * One Gramlot page. The construction order is the one of source plan §4.3: the Data
11
+ * root is Builder's (`_dataroot` → `_root_` → `builder.data`) and the BindingRuntime
12
+ * subscribes to it before the renderer observes the Source.
13
+ */
14
+ export class Gramlot {
15
+ constructor({pageId, mainUrl = '/gramlot/main', sourceUrl = '/gramlot/source', closeUrl = '/gramlot/close', rootId = 'gramlot-root',
16
+ element = null, document = globalThis.document, transport = null, collections = []} = {}) {
17
+ this.pageId = pageId;
18
+ this.logicRegistry = new LogicRegistry(this);
19
+ this.builder = new GramlotBuilder(null, {collections});
20
+ this.binding = new BindingRuntime(this);
21
+ this.builder.binding = this.binding;
22
+ this.data = this.builder.data;
23
+ this.binding.attach();
24
+ this.source = this.builder.source;
25
+ const destination = element ?? document.getElementById(rootId);
26
+ this.renderer = new GramlotRenderer(this.builder, this.source, destination, {binding: this.binding});
27
+ this.transport = transport === false ? null : transport ??
28
+ new MainTransport(mainUrl, undefined, sourceUrl, closeUrl, document.defaultView.navigator);
29
+ this.remoteRequests = new Map();
30
+ this.state = 'ready';
31
+ this.abort = new AbortController();
32
+ if (this.transport instanceof MainTransport) {
33
+ this.pagehide = event => { if (!event.persisted) this.dispose({beacon: true}); };
34
+ document.defaultView.addEventListener('pagehide', this.pagehide);
35
+ this.window = document.defaultView;
36
+ }
37
+ }
38
+ start() {
39
+ if (this.state === 'disposed') return Promise.reject(new Error('Gramlot is disposed'));
40
+ if (!this.transport) return Promise.reject(new Error('This Gramlot instance has no server transport'));
41
+ if (this.loading) return this.loading;
42
+ if (this.state === 'started') return Promise.resolve(this);
43
+ this.state = 'loading';
44
+ this.loading = this.loadMain().finally(() => { this.loading = null; });
45
+ return this.loading;
46
+ }
47
+ async loadMain() {
48
+ try {
49
+ const wire = await this.transport.main(this.pageId, this.abort.signal);
50
+ if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
51
+ return this.mountMainSource(wire);
52
+ } catch (error) {
53
+ if (this.state !== 'disposed') this.state = 'failed';
54
+ throw error;
55
+ }
56
+ }
57
+ /** Start from an embedded typed Source using the same observed insertion as main. */
58
+ startSource(wire) {
59
+ if (!['ready', 'failed'].includes(this.state)) {
60
+ throw new Error(`Cannot start embedded Source while Gramlot is ${this.state}`);
61
+ }
62
+ try { return this.mountMainSource(wire); }
63
+ catch (error) { this.state = 'failed'; throw error; }
64
+ }
65
+ /**
66
+ * Validate and insert `main` (§5.1). When its installation fails after the insertion (its
67
+ * NodeBindings closed again), `main` leaves the Source, so `start` or `startSource` can mount a
68
+ * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
69
+ * NodeBindings (P12, no rollback).
70
+ */
71
+ mountMainSource(wire) {
72
+ const source = this.prepareSource(wire);
73
+ this.renderer.validateCandidate(source);
74
+ try {
75
+ this.source.setItem('main', source);
76
+ } catch (error) {
77
+ if (!this.binding.bindingFor(this.source.getNode('main'))) this.source.popNode('main');
78
+ throw error;
79
+ }
80
+ this.state = 'started';
81
+ this.binding.pageStarted();
82
+ return this;
83
+ }
84
+ /** A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07). */
85
+ prepareSource(wire, builder = this.builder) {
86
+ if (wire instanceof SourceBag) {
87
+ if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
88
+ return wire.bindBuilder(builder);
89
+ }
90
+ const source = sourceBagFromTytx(wire, builder);
91
+ if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
92
+ return source;
93
+ }
94
+
95
+ /**
96
+ * Replace one Source node's children only after incoming Source validation.
97
+ * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
98
+ * or a freeze keeps it, the removal of the target cancels it.
99
+ */
100
+ async remoteSource(target, method, params = {}) {
101
+ if (!this.transport?.source) throw new Error('Remote Source is unavailable without a server transport');
102
+ const binding = this.binding.bindingFor(target);
103
+ if (this.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
104
+ this.remoteRequests.get(target)?.controller.abort();
105
+ const request = {controller: new AbortController()};
106
+ this.remoteRequests.set(target, request);
107
+ const unregister = binding.track(() => request.controller.abort());
108
+ let applying = false;
109
+ const current = () => this.state !== 'disposed' && !request.controller.signal.aborted &&
110
+ this.remoteRequests.get(target) === request && !binding.closed;
111
+ try {
112
+ const wire = await this.transport.source(this.pageId, method, params, request.controller.signal);
113
+ if (!current()) return false;
114
+ const prepared = this.prepareSource(wire, target.builder);
115
+ if (!current()) return false;
116
+ this.renderer.validateCandidate(prepared, {replacingNode: target});
117
+ applying = true;
118
+ unregister();
119
+ // The target's own prefix text belongs to the old body as well.
120
+ target.setValue(prepared, true, {_text: null}, true);
121
+ return true;
122
+ } catch (error) {
123
+ if (!applying && !current()) return false;
124
+ throw error;
125
+ } finally {
126
+ unregister();
127
+ if (this.remoteRequests.get(target) === request) this.remoteRequests.delete(target);
128
+ }
129
+ }
130
+
131
+ reference(descriptor) { return this.renderer.references.resolve(descriptor); }
132
+ /** The Source node of the nearest element generated by the renderer (§4.11bis). */
133
+ getBaseSourceNode(domNode) { return this.renderer.getBaseSourceNode(domNode); }
134
+ /** The element built from a Source node, or null (§4.11bis). */
135
+ getDomNode(sourceNode) { return this.renderer.getDomNode(sourceNode); }
136
+ dispose({beacon = false} = {}) {
137
+ if (this.state === 'disposed') return;
138
+ this.state = 'disposed';
139
+ if (this.pagehide) this.window.removeEventListener('pagehide', this.pagehide);
140
+ this.abort.abort();
141
+ for (const request of this.remoteRequests.values()) request.controller.abort();
142
+ this.remoteRequests.clear();
143
+ try {
144
+ try { this.binding.dispose(); }
145
+ finally { this.renderer.dispose(); }
146
+ } finally {
147
+ if (this.transport instanceof MainTransport) this.transport.close(this.pageId, {beacon});
148
+ this.transport?.dispose?.();
149
+ }
150
+ }
151
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export {Gramlot} from './gramlot.js';
2
+ export {PageBootstrap} from './bootstrap.js';
3
+ export {GramlotBuilder} from './builder/gramlot-builder.js';
4
+ export {GramlotRenderer} from './renderer/gramlot-renderer.js';
5
+ export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
6
+ export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
7
+ export {Bag, BagNode} from '@genrojs/bag';
8
+ export {References} from './references.js';
9
+ export {MainTransport} from './transport.js';
@@ -0,0 +1,43 @@
1
+ /** Opaque references to mounted Source nodes and their DOM elements. */
2
+ import {SourceBag} from '@genrojs/builders';
3
+
4
+ export class References {
5
+ constructor(sourceRoot = null) { this.entries = new Map(); this.sourceRoot = sourceRoot; }
6
+ validate(block, excluded = new Set()) {
7
+ const references = new Map();
8
+ const walk = bag => {
9
+ for (const node of bag.getNodes()) {
10
+ const id = node.getAttr('__ref');
11
+ if (id) {
12
+ if (references.has(id)) throw new Error('Duplicate Source reference');
13
+ const mounted = this.entries.get(id);
14
+ if (block !== this.sourceRoot && mounted && mounted.node !== node && !excluded.has(mounted.node)) {
15
+ throw new Error('Duplicate Source reference');
16
+ }
17
+ references.set(id, node);
18
+ }
19
+ if (node.value instanceof SourceBag) walk(node.value);
20
+ }
21
+ };
22
+ walk(block);
23
+ }
24
+ register(node, element) {
25
+ const id = node.getAttr('__ref');
26
+ if (!id) return;
27
+ if (this.entries.has(id)) throw new Error(`Duplicate Source reference: ${id}`);
28
+ this.entries.set(id, {node, dom: element});
29
+ }
30
+ remove(node) {
31
+ for (const [id, entry] of this.entries) {
32
+ if (entry.node === node) this.entries.delete(id);
33
+ }
34
+ }
35
+ resolve(reference) {
36
+ if (!reference || !['node', 'dom'].includes(reference.kind)) {
37
+ throw new TypeError('Expected a node or DOM reference');
38
+ }
39
+ const entry = this.entries.get(reference.$gramlotRef);
40
+ if (!entry) throw new Error('Source reference is not mounted');
41
+ return entry[reference.kind];
42
+ }
43
+ }
@@ -0,0 +1,120 @@
1
+ // Attribute rules shared by GramlotHtmlRenderer, GramlotSvgRenderer and the live GramlotRenderer.
2
+ // Same table and same functions as src/gramlot/renderer/attributes.py (source plan §1 rule 10).
3
+ import {sourceAttributeItems} from '@genrojs/builders';
4
+
5
+ export const XHTML_NS = 'http://www.w3.org/1999/xhtml';
6
+ export const SVG_NS = 'http://www.w3.org/2000/svg';
7
+
8
+ // Binding attributes are read by the Gramlot runtime and never reach the output (source plan, S02).
9
+ // The names are the resolved ones: runtimeValues turns the keyword names `_if`/`_else` into `if`/`else`.
10
+ const BINDING_ATTRIBUTES = new Set([
11
+ 'default', 'default_value', 'live', 'group', 'visible', 'action', 'fire',
12
+ 'if', 'else', '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
13
+ ]);
14
+ const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on'];
15
+
16
+ // Legacy noConvertStyle (genro_wdg.js:102-108): these attributes stay native attributes, never style.
17
+ const NATIVE_ATTRIBUTES = {
18
+ table: ['width', 'border'],
19
+ editor: ['height'],
20
+ embed: ['width', 'height'],
21
+ img: ['width', 'height'],
22
+ canvas: ['width', 'height'],
23
+ };
24
+
25
+ // A `${name}` template reference; `\${` stays text (Builder's runtimeValues rule).
26
+ const TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
27
+
28
+ // Display directives of the node text: consumed by the renderer, never written as attributes.
29
+ const DISPLAY_ATTRIBUTES = ['format', 'mask', 'locale', 'places', 'dtype'];
30
+
31
+ /** The attributes of `attrs` that are not binding attributes. */
32
+ export function withoutBindingAttributes(attrs) {
33
+ return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name)
34
+ && !BINDING_ATTRIBUTE_PREFIXES.some(prefix => name.startsWith(prefix))));
35
+ }
36
+
37
+ /** The attributes of `attrs` whose value is neither null nor undefined. */
38
+ export function withoutNullValues(attrs) {
39
+ return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
40
+ }
41
+
42
+ /** DOM attribute names: `data_*`/`aria_*` → `data-*`/`aria-*`, `xmlns_x` → `xmlns:x`. */
43
+ export function domNames(attrs) {
44
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => {
45
+ if (name.startsWith('xmlns_')) return [`xmlns:${name.slice(6)}`, value];
46
+ if (name.startsWith('data_') || name.startsWith('aria_')) return [name.replaceAll('_', '-'), value];
47
+ return [name, value];
48
+ }));
49
+ }
50
+
51
+ /** The attributes of a sub-builder boundary node: no dialect adaptation, only the Gramlot filters and names. */
52
+ export function boundaryAttributes(attrs) {
53
+ const {_meta, ...rest} = attrs;
54
+ return domNames(withoutNullValues(withoutBindingAttributes(rest)));
55
+ }
56
+
57
+ /** `[attrs, native]`: the noConvertStyle attributes of `tag` taken out of `attrs`. */
58
+ export function splitNativeAttributes(tag, attrs) {
59
+ const names = NATIVE_ATTRIBUTES[String(tag).toLowerCase()] ?? [];
60
+ const rest = {};
61
+ const native = {};
62
+ for (const [name, value] of Object.entries(attrs)) {
63
+ if (names.includes(name)) native[name] = value;
64
+ else rest[name] = value;
65
+ }
66
+ return [rest, native];
67
+ }
68
+
69
+ /** The node text of a scalar value: booleans as `true`/`false`, as in JavaScript. */
70
+ export function textValue(value) {
71
+ return String(value);
72
+ }
73
+
74
+ /**
75
+ * `[item, attrs]` with the display directives consumed (HTML only).
76
+ * `format`, `places`, `locale` and `dtype` do not format the text in 0.2.0. `mask` follows the
77
+ * legacy rule (gnrlang.js asText): `%s` replaced by the value, no mask when the value is empty.
78
+ */
79
+ export function displayItem(item, attrs) {
80
+ const rest = {...attrs};
81
+ const mask = rest.mask;
82
+ for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
83
+ if (Array.isArray(item)) return [item, rest];
84
+ if (typeof item === 'boolean') item = textValue(item);
85
+ if (mask == null) return [item, rest];
86
+ const text = item == null ? '' : textValue(item);
87
+ return [text === '' ? text : String(mask).replaceAll('%s', () => text), rest];
88
+ }
89
+
90
+ /** The parameter names of the `${name}` templates of `value`, in order; none for a value that is not a string. */
91
+ export function templateParameters(value) {
92
+ return typeof value === 'string' ? [...value.matchAll(TEMPLATE_REFERENCE)].map(([, name]) => name) : [];
93
+ }
94
+
95
+ /** Whether `value` is a `==` expression (Q11.2). */
96
+ export function isExpression(value) {
97
+ return typeof value === 'string' && value.startsWith('==');
98
+ }
99
+
100
+ /**
101
+ * Templates and `==` expressions do not mix (Q11.2): a template that uses a `==` attribute of the same
102
+ * node is an error naming both attributes; a `${…}` inside a `==` attribute or node value is an error
103
+ * naming it.
104
+ */
105
+ export function requireNoExpressionTemplate(node) {
106
+ if (isExpression(node.value) && templateParameters(node.value).length) {
107
+ throw new Error(`${node.nodeTag} '${node.label}': the == node value contains a \${…} template, not accepted in a == expression`);
108
+ }
109
+ const attrs = Object.fromEntries(sourceAttributeItems(node.getAttr()));
110
+ for (const [name, raw] of Object.entries(attrs)) {
111
+ if (isExpression(raw) && templateParameters(raw).length) {
112
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' contains a \${…} template, not accepted in a == expression`);
113
+ }
114
+ for (const param of templateParameters(raw)) {
115
+ if (isExpression(attrs[param])) {
116
+ throw new Error(`${node.nodeTag} '${node.label}': the template of '${name}' uses '${param}', a == expression`);
117
+ }
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,125 @@
1
+ import {HtmlBuilder, HtmlRenderer, SvgBuilder, sourceAttributeItems} from '@genrojs/builders';
2
+ import {GramlotSvgRenderer} from './gramlot-svg-renderer.js';
3
+ import {
4
+ SVG_NS, XHTML_NS, boundaryAttributes, displayItem, domNames, isExpression, requireNoExpressionTemplate,
5
+ splitNativeAttributes, textValue, withoutBindingAttributes, withoutNullValues,
6
+ } from './attributes.js';
7
+
8
+ /**
9
+ * The string renderer of a Gramlot Source, the same class as the Python GramlotHtmlRenderer.
10
+ * It carries the Gramlot attribute rules on Builder's HtmlRenderer: style shortcuts, the parent-dialect
11
+ * prefix, noConvertStyle, DOM names, `mask`, `_text` as node text and the document wrapper.
12
+ * The live GramlotRenderer extends it and replaces only the output.
13
+ */
14
+ export class GramlotHtmlRenderer extends HtmlRenderer {
15
+ // noConvertStyle attributes taken out in _handleMeta, put back after adaptAttrs.
16
+ #nativeAttributes = new WeakMap();
17
+ // The `==` node value computed by evaluateExpressions, read when the node text is written.
18
+ #expressionValues = new WeakMap();
19
+
20
+ /** The compiler of the `==` expressions: a string renderer has none and writes no `==` (S09). */
21
+ get inlineCompiler() { return null; }
22
+
23
+ /** HTML nodes (GramlotBuilder, HtmlBuilder) → this renderer; SVG nodes → one GramlotSvgRenderer owned by it. */
24
+ getRender(builder) {
25
+ if (!this.renders.has(builder)) {
26
+ if (builder instanceof HtmlBuilder) this.addRender(builder, this);
27
+ else if (builder instanceof SvgBuilder) this.addRender(builder, new GramlotSvgRenderer(builder, this));
28
+ }
29
+ return super.getRender(builder);
30
+ }
31
+
32
+ /** A data-element renders nothing: recognized before runtimeValues (R08, revision 10). */
33
+ render(node, opts = {}) {
34
+ if (node._getMeta('data_element')) return null;
35
+ return super.render(node, opts);
36
+ }
37
+
38
+ /**
39
+ * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
40
+ * has no tag. A sub-builder boundary node keeps its attributes literal, with the Gramlot filters and
41
+ * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace.
42
+ */
43
+ _handleMeta(node, runtimeAttrs) {
44
+ const [tag, attrs] = super._handleMeta(node, this.evaluateExpressions(node, runtimeAttrs));
45
+ if (node._getMeta('subbuilder')) {
46
+ const boundary = boundaryAttributes(attrs);
47
+ if (node._getMeta('subbuilder') === 'html') boundary.xmlns = SVG_NS;
48
+ return [tag, boundary];
49
+ }
50
+ const [rest, native] = splitNativeAttributes(tag, attrs);
51
+ if (Object.keys(native).length) this.#nativeAttributes.set(node, native);
52
+ return [tag, rest];
53
+ }
54
+
55
+ /**
56
+ * Step 3 of Q11.2 on the attributes of `node` resolved by runtimeValues, for HTML and SVG nodes: every
57
+ * `==` attribute, and a `==` node value, evaluated by the page's InlineCompiler (§4.10); without a
58
+ * compiler they are null and nothing is written. A template using a `==` attribute is an error.
59
+ */
60
+ evaluateExpressions(node, runtimeAttrs) {
61
+ requireNoExpressionTemplate(node);
62
+ const compiler = this.inlineCompiler;
63
+ const evaluate = (attr, expr) => (compiler ? compiler.compileExpression(node, attr, expr.slice(2))(runtimeAttrs) : null);
64
+ const attrs = {...runtimeAttrs};
65
+ for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
66
+ if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
67
+ }
68
+ if (isExpression(node.value)) this.#expressionValues.set(node, evaluate('', node.value));
69
+ return attrs;
70
+ }
71
+
72
+ /** The node text of `node`: its `==` value computed by evaluateExpressions, otherwise `item`. */
73
+ expressionValue(node, item) {
74
+ return isExpression(node.value) ? this.#expressionValues.get(node) ?? null : item;
75
+ }
76
+
77
+ /** `attrs` with the noConvertStyle attributes set aside by _handleMeta for `node`, null values excluded. */
78
+ restoreNativeAttributes(node, attrs) {
79
+ const native = this.#nativeAttributes.get(node);
80
+ if (!native) return attrs;
81
+ this.#nativeAttributes.delete(node);
82
+ return {...attrs, ...withoutNullValues(native)};
83
+ }
84
+
85
+ /**
86
+ * `_meta`, binding attributes and null values out; `html_<name>` is the literal attribute `<name>`
87
+ * and `gramlot_<name>` an error; Builder's style shortcuts on the rest; DOM names.
88
+ */
89
+ adaptAttrs(attrs) {
90
+ const {_meta, ...rest} = attrs;
91
+ const own = `${this.builder.constructor._name}_`;
92
+ const prefixes = this.builder.constructor.dialectPrefixes;
93
+ const literal = {};
94
+ const styled = {};
95
+ for (const [name, value] of Object.entries(withoutBindingAttributes(rest))) {
96
+ if (value == null) continue;
97
+ if (name.startsWith(own)) {
98
+ throw new Error(`${name}: the attribute prefix '${own}' is not accepted; use the prefix '${prefixes[0]}'`);
99
+ }
100
+ const prefix = prefixes.find(candidate => name.startsWith(candidate));
101
+ if (prefix) literal[name.slice(prefix.length)] = value;
102
+ else styled[name] = value;
103
+ }
104
+ return domNames({...super.adaptAttrs(styled), ...literal});
105
+ }
106
+
107
+ /** The HTML string of one node: noConvertStyle put back, display directives consumed, `_text` as node text. */
108
+ renderedItem(node, item, runtimeAttrs, opts = {}) {
109
+ let attrs;
110
+ [item, attrs] = displayItem(this.expressionValue(node, item), this.restoreNativeAttributes(node, runtimeAttrs));
111
+ const {_text, ...rest} = attrs;
112
+ if (Array.isArray(item) && _text != null) item = [this._escapeText(textValue(_text)), ...item];
113
+ const shown = node.parentNode?._getMeta('subbuilder') === 'html' ? {xmlns: XHTML_NS, ...rest} : rest;
114
+ return super.renderedItem(node, item, shown, opts);
115
+ }
116
+
117
+ /** Builder's finalize; `doctype` prepends `<!doctype html>` and wraps the output in `<html>` when the root is not `html`. */
118
+ finalize(result, target = null, opts = {}) {
119
+ if (!opts.doctype) return super.finalize(result, target, opts);
120
+ let text = this._composeStringFragments(result);
121
+ const roots = this.builder.source.getNodes().filter(node => !node._getMeta('data_element'));
122
+ if (!(roots.length === 1 && roots[0].nodeTag === 'html')) text = `<html>${text}</html>`;
123
+ return super.finalize(`<!doctype html>${text}`, target, opts);
124
+ }
125
+ }