@gramlot/gramlot 0.2.17 → 0.2.19

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 CHANGED
@@ -8,6 +8,7 @@ import {HttpTransport} from './http-transport.js';
8
8
  import {SourceHandler} from './handlers/source-handler.js';
9
9
  import {RpcHandler} from './handlers/rpc-handler.js';
10
10
  import {DomHandler} from './handlers/dom-handler.js';
11
+ import {SubscriptionsHandler} from './handlers/subscriptions-handler.js';
11
12
  import {UtilitiesHandler} from './handlers/utilities-handler.js';
12
13
 
13
14
  /**
@@ -16,8 +17,9 @@ import {UtilitiesHandler} from './handlers/utilities-handler.js';
16
17
  */
17
18
  export class Gramlot {
18
19
  constructor({pageId, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
19
- element = null, document = globalThis.document, transport = null, collections = []} = {}) {
20
+ element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = []} = {}) {
20
21
  this.pageId = pageId;
22
+ Object.defineProperty(this, '_subscriptions', {value: new SubscriptionsHandler(this)});
21
23
  this.capabilities = Object.freeze([...capabilities]);
22
24
  this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId)});
23
25
  this.data = this.src.builder.data;
@@ -25,6 +27,7 @@ export class Gramlot {
25
27
  this.dom = new DomHandler(this);
26
28
  this.utl = new UtilitiesHandler(this, document);
27
29
  this.state = 'ready';
30
+ this._subscriptions.attach(document);
28
31
  this.abort = new AbortController();
29
32
  if (this.rpc.transport instanceof HttpTransport) {
30
33
  this.pagehide = event => { if (!event.persisted) this.dispose({beacon: true}); };
@@ -32,6 +35,10 @@ export class Gramlot {
32
35
  this.window = document.defaultView;
33
36
  }
34
37
  }
38
+ publish(topic, payload = {}) { return this._subscriptions.publish(topic, payload); }
39
+ subscribe(topic, callback) { return this._subscriptions.subscribe(topic, callback); }
40
+ unsubscribe(registration) { this._subscriptions.unsubscribe(registration); }
41
+
35
42
  start() {
36
43
  if (this.state === 'disposed') return Promise.reject(new Error('Gramlot is disposed'));
37
44
  if (!this.rpc.transport) return Promise.reject(new Error('This Gramlot instance has no server transport'));
@@ -54,6 +61,7 @@ export class Gramlot {
54
61
  dispose({beacon = false} = {}) {
55
62
  if (this.state === 'disposed') return;
56
63
  this.state = 'disposed';
64
+ this._subscriptions.dispose();
57
65
  if (this.pagehide) this.window.removeEventListener('pagehide', this.pagehide);
58
66
  this.abort.abort();
59
67
  for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
@@ -7,6 +7,7 @@
7
7
  import {fromTytx, toTytx} from '@genrojs/tytx';
8
8
  import {Handler} from './handler.js';
9
9
  import {HttpTransport} from '../http-transport.js';
10
+ import {assertTransportData} from '../references.js';
10
11
 
11
12
  /** A request id: 16 random bytes as 32 hex characters; getRandomValues, unlike randomUUID,
12
13
  * exists outside secure contexts too. */
@@ -35,6 +36,7 @@ export class RpcHandler extends Handler {
35
36
  /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
36
37
  async call(contentType, name, params = {}, {signal} = {}) {
37
38
  if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
39
+ assertTransportData(params);
38
40
  const id = requestId();
39
41
  const text = toTytx({id, pageId: this.gramlot.pageId, contentType, name, params});
40
42
  const response = fromTytx(await this.transport.call(text, signal));
@@ -55,6 +55,7 @@ export class SourceHandler extends Handler {
55
55
  }
56
56
  this.gramlot.state = 'started';
57
57
  this.binding.pageStarted();
58
+ this.gramlot._subscriptions.ready();
58
59
  return this.gramlot;
59
60
  }
60
61
  /**
@@ -0,0 +1,103 @@
1
+ import {FrameMessages} from '../frame-messages.js';
2
+ import {Handler} from './handler.js';
3
+ import {sourceTarget} from '@genrojs/builders';
4
+
5
+ /** Page topics and Source self-topics. Owned privately by one Gramlot instance. */
6
+ export class SubscriptionsHandler extends Handler {
7
+ #topics = new Map();
8
+ #handles = new WeakSet();
9
+ #nodeIds = new WeakMap();
10
+ #sequence = 0;
11
+ #closed = false;
12
+ #frames;
13
+
14
+ attach(document) { this.#frames = new FrameMessages(this.gramlot, document); }
15
+ ready() { this.#frames.ready(); }
16
+
17
+ subscribe(topic, callback) {
18
+ this.#requireOpen();
19
+ this.#requireTopic(topic);
20
+ if (typeof callback !== 'function') throw new TypeError('subscribe requires a callback');
21
+ const handle = Object.freeze({});
22
+ this.#handles.add(handle);
23
+ if (!this.#topics.has(topic)) this.#topics.set(topic, new Map());
24
+ this.#topics.get(topic).set(handle, callback);
25
+ return handle;
26
+ }
27
+
28
+ unsubscribe(handle) {
29
+ if (!this.#handles.has(handle)) throw new TypeError('Unknown subscription registration');
30
+ for (const [topic, callbacks] of this.#topics) {
31
+ if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
32
+ }
33
+ }
34
+
35
+ publish(topic, payload = {}) {
36
+ this.#requireOpen();
37
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
38
+ throw new TypeError('publish requires one object of named data');
39
+ }
40
+ if (typeof topic === 'string') return this.#deliver(topic, payload);
41
+ if (!topic || typeof topic !== 'object' || Array.isArray(topic)) {
42
+ throw new TypeError('publish requires a topic string or descriptor');
43
+ }
44
+ const keys = Object.keys(topic);
45
+ if (keys.some(key => !['topic', 'nodeId', 'parent', 'iframe'].includes(key))) {
46
+ throw new Error('This publication route is not implemented yet');
47
+ }
48
+ this.#requireTopic(topic.topic);
49
+ if (topic.parent !== undefined && typeof topic.parent !== 'boolean') throw new TypeError('parent must be boolean');
50
+ if (topic.iframe === '*') throw new Error('Recursive iframe broadcast is not implemented yet');
51
+ if ((topic.parent || topic.iframe !== undefined) && Object.hasOwn(topic, 'nodeId')) {
52
+ throw new Error('Interframe node addressing is not implemented yet');
53
+ }
54
+ const forward = topic.parent || topic.iframe !== undefined ? this.#frames.prepare(topic, payload) : null;
55
+ if (Object.hasOwn(topic, 'nodeId')) {
56
+ const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
57
+ if (!node) throw new Error(`node_id not found: ${topic.nodeId}`);
58
+ return this.publishNode(node, topic.topic, payload);
59
+ }
60
+ this.#deliver(topic.topic, payload);
61
+ forward?.();
62
+ }
63
+
64
+ topicFor(node, topic) {
65
+ this.#requireTopic(topic);
66
+ node = sourceTarget(node);
67
+ const binding = this.gramlot.src.binding.bindingFor(node);
68
+ if (!binding || binding.closed) throw new Error('Topic target is not an active Source node of this page');
69
+ let id = node.getAttr('node_id');
70
+ if (id == null) {
71
+ if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, `gramlot-self-${++this.#sequence}`);
72
+ id = this.#nodeIds.get(node);
73
+ }
74
+ return `${id}_${topic}`;
75
+ }
76
+
77
+ publishNode(node, topic, payload = {}) {
78
+ return this.publish(this.topicFor(node, topic), payload);
79
+ }
80
+
81
+ dispose() {
82
+ this.#closed = true;
83
+ this.#frames.dispose();
84
+ this.#topics.clear();
85
+ }
86
+
87
+ #deliver(topic, payload) {
88
+ this.#requireTopic(topic);
89
+ const callbacks = this.#topics.get(topic);
90
+ if (!callbacks) return;
91
+ // Synchronous, ordered, no retention/equality suppression; exceptions propagate.
92
+ for (const [handle, callback] of [...callbacks]) {
93
+ if (this.#closed) break;
94
+ if (callbacks.has(handle)) callback(payload);
95
+ }
96
+ }
97
+ #requireTopic(topic) {
98
+ if (typeof topic !== 'string' || !topic) throw new TypeError('A topic must be a nonempty string');
99
+ }
100
+ #requireOpen() {
101
+ if (this.#closed) throw new Error('Gramlot subscriptions are disposed');
102
+ }
103
+ }
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';
@@ -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,7 +34,7 @@ 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
 
@@ -180,13 +180,16 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
180
180
  if (!(block instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
181
181
  const excluded = new Set();
182
182
  const exclude = node => {
183
+ if (excluded.has(node)) return;
183
184
  excluded.add(node);
184
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);
185
187
  };
186
188
  // Replacing a node's VALUE retains that node and its reference. Only
187
189
  // the rendered descendants which the replacement removes leave the ref set.
188
190
  // During freeze these can differ from the current Source descendants.
189
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);
190
193
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
191
194
  requireInstallable(block);
192
195
  this.references?.validate(block, excluded);
@@ -9,16 +9,19 @@
9
9
  * native. A closed NodeBinding does nothing (R12).
10
10
  */
11
11
 
12
+ import {AskDialog} from '../binding/ask-dialog.js';
12
13
  import {XHTML_NS} from '../renderer/attributes.js';
13
14
 
14
15
  export class ButtonBinding {
15
16
  #binding;
16
17
  #record;
18
+ #cancelDelay = null;
19
+ #pendingCount = 0;
17
20
 
18
- /** The ButtonBinding of a built element, or null when the element is not a `<button>`. */
21
+ /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
19
22
  static for(binding, record) {
20
23
  const element = record.element;
21
- if (element?.namespaceURI !== XHTML_NS || element.localName !== 'button') return null;
24
+ if (binding.node.nodeTag !== 'button' || element?.namespaceURI !== XHTML_NS || element.localName !== 'button') return null;
22
25
  return new ButtonBinding(binding, record);
23
26
  }
24
27
 
@@ -78,6 +81,7 @@ export class ButtonBinding {
78
81
 
79
82
  detach() {
80
83
  this.element.removeEventListener('click', this);
84
+ this.#cancelDelay?.();
81
85
  }
82
86
 
83
87
  handleEvent(event) {
@@ -96,15 +100,60 @@ export class ButtonBinding {
96
100
  event.stopPropagation();
97
101
  if (this.element.disabled) return;
98
102
  const counter = this.binding.countClick();
103
+ // Legacy reads inherited _delay. An explicit zero overrides an ancestor's delay.
104
+ let owner = this.node;
105
+ while (owner && owner.getAttr('_delay') == null) owner = owner.parentNode;
106
+ const delay = owner ? owner.builder.runtimeValues(owner)[1]._delay : 0;
107
+ if (delay > 0) {
108
+ const count = this.#pendingCount + 1;
109
+ this.#cancelDelay?.();
110
+ this.#pendingCount = count;
111
+ const timer = setTimeout(() => {
112
+ release();
113
+ this.#cancelDelay = null;
114
+ this.#pendingCount = 0;
115
+ this.#execute(event, count);
116
+ }, delay);
117
+ const release = this.binding.track(() => this.#cancelDelay?.());
118
+ this.#cancelDelay = () => {
119
+ clearTimeout(timer);
120
+ release();
121
+ this.#cancelDelay = null;
122
+ this.#pendingCount = 0;
123
+ };
124
+ return;
125
+ }
126
+ this.#cancelDelay?.();
127
+ return this.#execute(event, counter);
128
+ }
129
+
130
+ /** Deliver the last event once; arguments are read when the mechanism executes. */
131
+ #execute(event, counter) {
132
+ if (this.binding.closed || this.element.disabled) return;
133
+ const mechanism = this.mechanism;
134
+ if (!mechanism) return;
99
135
  const node = this.node;
100
136
  const modifiers = eventToString(event);
101
137
  if (mechanism === 'controller') {
102
138
  const provider = this.binding.runtime.bindingFor(this.controllers[0])?.providers[0];
103
139
  provider?.invoke({kind: 'click', event, counter});
104
140
  } else if (mechanism === 'action') {
105
- const [, attrs] = node.builder.runtimeValues(node);
106
- const values = {...attrs, event, _counter: counter, modifiers};
107
- this.binding.runtime.inlineCompiler.compile(node, 'action', node.getAttr('action'), Object.keys(values))(values);
141
+ const read = () => {
142
+ const [, attrs] = node.builder.runtimeValues(node);
143
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== 'ask'));
144
+ return {...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers};
145
+ };
146
+ const execute = result => {
147
+ if (this.binding.closed || result === null) return;
148
+ const values = {...read(), ...result};
149
+ if (result) values._askResult = result;
150
+ this.binding.runtime.inlineCompiler.compile(node, 'action', node.getAttr('action'), Object.keys(values))(values);
151
+ };
152
+ const ask = node.getAttr('ask');
153
+ if (ask && AskDialog.required(this.binding, ask, read(), 'ask')) {
154
+ return AskDialog.show(this.binding, ask, read()).then(execute);
155
+ }
156
+ execute(undefined);
108
157
  } else {
109
158
  const attributes = {modifier: modifiers, _counter: counter};
110
159
  // `fire` wins over the `fire_*` of the same button, as the legacy chain.
package/src/view/html.js CHANGED
@@ -61,7 +61,7 @@ export class HtmlElement {
61
61
  throw new TypeError('HTML text must be scalar');
62
62
  }
63
63
  for (const [key, value] of Object.entries(node.attr)) {
64
- if (this.metadataAttributes.has(key)) continue;
64
+ if (this.metadataAttributes.has(key) || ['ask', '_ask'].includes(key) || (value && typeof value === 'object' && Object.hasOwn(value, '$gramlotRef'))) continue;
65
65
  if (value != null && !['string', 'number', 'boolean'].includes(typeof value)) {
66
66
  throw new TypeError(`HTML attribute ${key} must be scalar`);
67
67
  }
@@ -117,7 +117,7 @@ export class HtmlElement {
117
117
  // The browser reads `sandbox` when `src` or `srcdoc` starts a navigation: `sandbox` is written first.
118
118
  keys.sort((a, b) => (b === 'sandbox') - (a === 'sandbox'));
119
119
  for (const key of keys) {
120
- if (this.metadataAttributes.has(key) || (controlled && key === 'value')) continue;
120
+ if (this.metadataAttributes.has(key) || ['ask', '_ask'].includes(key) || (controlled && key === 'value')) continue;
121
121
  const value = attrs[key];
122
122
  const attrName = key;
123
123
  const propertyName = domPropertyName(attrName);