@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/dist/gramlot.js +610 -26
- package/dist/gramlot.min.js +21 -21
- package/package.json +3 -2
- package/src/binding/ask-dialog.js +108 -0
- package/src/binding/installation.js +4 -2
- package/src/binding/providers.js +41 -6
- package/src/binding/runtime.js +36 -1
- package/src/builder/binding.json +26 -1
- package/src/builder/gramlot-builder.js +19 -2
- package/src/builder/source.js +18 -5
- package/src/frame-messages.js +177 -0
- package/src/gramlot.d.ts +14 -0
- package/src/gramlot.js +9 -1
- package/src/handlers/rpc-handler.js +2 -0
- package/src/handlers/source-handler.js +1 -0
- package/src/handlers/subscriptions-handler.js +103 -0
- package/src/index.d.ts +1 -1
- package/src/references.d.ts +5 -0
- package/src/references.js +23 -1
- package/src/renderer/attributes.js +3 -3
- package/src/renderer/gramlot-renderer.js +3 -0
- package/src/view/button.js +54 -5
- package/src/view/html.js +2 -2
- package/tools/gramlot-tools-inspector.js +317 -44
- package/tools/inspector-agent.js +252 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gramlot/gramlot",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.19",
|
|
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": {
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
"./themes/*": "./themes/*",
|
|
35
35
|
"./assets/branding/*": "./assets/branding/*",
|
|
36
36
|
"./tools/inspector": "./tools/gramlot-tools-inspector.js",
|
|
37
|
-
"./index-page-runtime": "./src/index-page-runtime.js"
|
|
37
|
+
"./index-page-runtime": "./src/index-page-runtime.js",
|
|
38
|
+
"./tools/inspector-agent": "./tools/inspector-agent.js"
|
|
38
39
|
},
|
|
39
40
|
"files": [
|
|
40
41
|
"LICENSE",
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
2
|
+
|
|
3
|
+
const pages = new WeakMap();
|
|
4
|
+
const SPEC_KEYS = new Set(['title', 'msg', 'fields', '_if', 'askIf']);
|
|
5
|
+
const FIELD_KEYS = new Set(['name', 'lbl', 'tag', 'type', 'default_value', 'required', 'min', 'max', 'step', 'placeholder']);
|
|
6
|
+
|
|
7
|
+
/** A bounded native dialog authored through Source/Data and named Logic. */
|
|
8
|
+
export class AskDialog {
|
|
9
|
+
static required(binding, specification, parameters, attribute) {
|
|
10
|
+
const evaluate = (name, code) => typeof code === 'boolean' ? code
|
|
11
|
+
: binding.runtime.inlineCompiler.compile(binding.node, name, code,
|
|
12
|
+
Object.keys(parameters), `return (${code});`)(parameters);
|
|
13
|
+
if (typeof specification === 'string') {
|
|
14
|
+
const condition = binding.node.getAttr('_ask_if');
|
|
15
|
+
return !condition || Boolean(evaluate('_ask_if', condition));
|
|
16
|
+
}
|
|
17
|
+
// Legacy askIf alone does not suppress the prompt; askOn/skipOn are not ported.
|
|
18
|
+
if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
|
|
19
|
+
return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
static show(binding, specification, parameters, title = 'Parameters') {
|
|
23
|
+
const spec = typeof specification === 'string' ? {msg: specification, title} : specification;
|
|
24
|
+
if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new TypeError('ask requires text or a parameter description');
|
|
25
|
+
for (const key of Object.keys(spec)) {
|
|
26
|
+
if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
|
|
27
|
+
}
|
|
28
|
+
const fields = spec.fields ?? [];
|
|
29
|
+
if (!Array.isArray(fields)) throw new TypeError('ask fields must be an array');
|
|
30
|
+
const names = new Set();
|
|
31
|
+
for (const field of fields) {
|
|
32
|
+
if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error('ask fields require distinct simple names');
|
|
33
|
+
names.add(field.name);
|
|
34
|
+
for (const key of Object.keys(field)) {
|
|
35
|
+
if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
|
|
36
|
+
}
|
|
37
|
+
if (field.tag && !['input', 'textarea'].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
|
|
38
|
+
if (field.type && !['text', 'number', 'date', 'checkbox', 'email', 'password', 'url', 'tel'].includes(field.type)) {
|
|
39
|
+
throw new Error(`Unsupported ask input type: ${field.type}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const app = binding.runtime.gramlot;
|
|
43
|
+
let page = pages.get(app);
|
|
44
|
+
if (!page) {
|
|
45
|
+
const group = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
46
|
+
const requests = new Map();
|
|
47
|
+
class Logic {
|
|
48
|
+
confirm(node, event) { event.preventDefault(); requests.get(node.getAttr('request'))?.finish(true); }
|
|
49
|
+
cancel(node, event) { event.preventDefault(); requests.get(node.getAttr('request'))?.finish(false); }
|
|
50
|
+
}
|
|
51
|
+
app.src.logicRegistry.register(Logic, {group, resource: 'gramlot:ask'});
|
|
52
|
+
page = {group, requests};
|
|
53
|
+
pages.set(app, page);
|
|
54
|
+
}
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const id = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
57
|
+
let finished = false;
|
|
58
|
+
let release = () => {};
|
|
59
|
+
const finish = (confirmed, failure = null) => {
|
|
60
|
+
if (finished) return;
|
|
61
|
+
finished = true;
|
|
62
|
+
const result = confirmed ? Object.fromEntries(fields.map(field =>
|
|
63
|
+
[field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
|
|
64
|
+
page.requests.delete(id);
|
|
65
|
+
release();
|
|
66
|
+
try {
|
|
67
|
+
app.src.source.popNode(id);
|
|
68
|
+
if (app.data.getNode(id)) app.data.popNode(id);
|
|
69
|
+
if (failure) reject(failure);
|
|
70
|
+
else resolve(result);
|
|
71
|
+
} catch (error) { reject(error); }
|
|
72
|
+
};
|
|
73
|
+
page.requests.set(id, {finish});
|
|
74
|
+
release = binding.track(() => finish(false));
|
|
75
|
+
try {
|
|
76
|
+
const builder = new GramlotBuilder();
|
|
77
|
+
const dialog = builder.root.dialog({node_id: id, datapath: id, request: id,
|
|
78
|
+
connect_oncancel: `${page.group}.cancel`, connect_onclose: `${page.group}.cancel`,
|
|
79
|
+
class: 'gramlot-ask', 'aria-labelledby': `${id}_title`,
|
|
80
|
+
style: 'border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;'});
|
|
81
|
+
dialog.h2(spec.title ?? title, {id: `${id}_title`, style: 'font-size:1.1em;margin:0 0 12px;'});
|
|
82
|
+
if (spec.msg) dialog.p(spec.msg);
|
|
83
|
+
const form = dialog.form({request: id, connect_onsubmit: `${page.group}.confirm`});
|
|
84
|
+
for (const field of fields) {
|
|
85
|
+
form.dataSetter({destination_path: `.${field.name}`,
|
|
86
|
+
value: Object.hasOwn(parameters, field.name) ? parameters[field.name]
|
|
87
|
+
: field.default_value ?? (field.type === 'checkbox' ? false : '')});
|
|
88
|
+
const row = form.div({style: 'margin:8px 0;'});
|
|
89
|
+
row.html_label(field.lbl ?? field.name, {for: `${id}_${field.name}`, style: 'display:block;margin-bottom:4px;'});
|
|
90
|
+
const attrs = {id: `${id}_${field.name}`, value: `^.${field.name}`, live: true};
|
|
91
|
+
for (const key of ['required', 'min', 'max', 'step', 'placeholder']) {
|
|
92
|
+
if (field[key] !== undefined) attrs[key] = field[key];
|
|
93
|
+
}
|
|
94
|
+
if (field.tag === 'textarea') row.textarea(attrs);
|
|
95
|
+
else row.input({...attrs, type: field.type ?? 'text'});
|
|
96
|
+
}
|
|
97
|
+
const buttons = form.div({style: 'display:flex;justify-content:flex-end;gap:8px;margin-top:16px;'});
|
|
98
|
+
buttons.button('Cancel', {type: 'button', request: id, connect_onclick: `${page.group}.cancel`});
|
|
99
|
+
buttons.button('Confirm', {type: 'submit', autofocus: fields.length === 0});
|
|
100
|
+
app.src.source.setItem(id, app.src.prepareSource(builder.source));
|
|
101
|
+
const node = app.src.binding.nodeIds.get(id);
|
|
102
|
+
app.dom.getDomNode(node).showModal();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
finish(false, error);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -171,7 +171,8 @@ export function requireInstallable(branch) {
|
|
|
171
171
|
|
|
172
172
|
// Provider attributes (§4.8): only a `dataFormula`, a `dataController`, a `dataRpc` or a `dataRemote`
|
|
173
173
|
// carries them; the lifecycle attributes not a `dataRemote`, whose resolver loads when its Data is read;
|
|
174
|
-
// the callbacks of the call only a `dataRpc`.
|
|
174
|
+
// the callbacks of the call only a `dataRpc`. `_delay` also belongs to Gramlot buttons
|
|
175
|
+
// and rendered ancestors that supply their inherited click delay.
|
|
175
176
|
const PROVIDER_ATTRIBUTES = ['_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges'];
|
|
176
177
|
const PROVIDER_TAGS = new Set(['dataFormula', 'dataController', 'dataRpc', 'dataRemote']);
|
|
177
178
|
const RPC_ATTRIBUTES = ['_onCalling', '_onResult', '_onError'];
|
|
@@ -208,7 +209,8 @@ function requireProviderAttributes(node) {
|
|
|
208
209
|
}
|
|
209
210
|
return;
|
|
210
211
|
}
|
|
211
|
-
const name = PROVIDER_ATTRIBUTES.find(isSet)
|
|
212
|
+
const name = PROVIDER_ATTRIBUTES.find(name => isSet(name)
|
|
213
|
+
&& !(name === '_delay' && !node._getMeta('data_element') && node.nodeTag !== 'html_button'));
|
|
212
214
|
if (!name) return;
|
|
213
215
|
const tags = LIFECYCLE_ATTRIBUTES.includes(name) ? 'dataFormula, dataController and dataRpc'
|
|
214
216
|
: 'dataFormula, dataController, dataRpc and dataRemote';
|
package/src/binding/providers.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {AskDialog} from './ask-dialog.js';
|
|
1
2
|
import {Bag} from '@genrojs/bag';
|
|
2
3
|
import {RpcResolver} from './rpc-resolver.js';
|
|
3
4
|
|
|
@@ -17,6 +18,7 @@ import {RpcResolver} from './rpc-resolver.js';
|
|
|
17
18
|
const CONTROL_ATTRIBUTES = new Set([
|
|
18
19
|
'destination_path', 'result_path', 'func', 'formula', 'script', 'if', 'else',
|
|
19
20
|
'_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
|
|
21
|
+
'_ask', '_ask_if', '_ask_title', '_ask_onCancel',
|
|
20
22
|
'method', 'timeout', '_onCalling', '_onResult', '_onError', 'cacheTime',
|
|
21
23
|
]);
|
|
22
24
|
|
|
@@ -70,6 +72,22 @@ export class Provider {
|
|
|
70
72
|
this.#registrations.push(registration);
|
|
71
73
|
if (name === '_timing') this.#timingRegistration = registration;
|
|
72
74
|
}
|
|
75
|
+
const subscriptions = this.binding.runtime.gramlot._subscriptions;
|
|
76
|
+
for (const name of Object.keys(node.getAttr())) {
|
|
77
|
+
const prefix = name.startsWith('selfsubscribe_') ? 'selfsubscribe_' : name.startsWith('subscribe_') ? 'subscribe_' : null;
|
|
78
|
+
if (!prefix) continue;
|
|
79
|
+
const topic = prefix === 'selfsubscribe_'
|
|
80
|
+
? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
|
|
81
|
+
// Legacy provider declarations subscribe by presence, including a false value.
|
|
82
|
+
const handle = subscriptions.subscribe(topic, payload => {
|
|
83
|
+
const trigger = {kind: 'subscription', topic, payload};
|
|
84
|
+
if (this.#resolved('_userChanges') && topic !== 'node') return;
|
|
85
|
+
const delay = this.#resolved('_delay');
|
|
86
|
+
if (delay > 0) this.#debounce(trigger, delay);
|
|
87
|
+
else this.invoke(trigger);
|
|
88
|
+
});
|
|
89
|
+
this.#registrations.push({close: () => subscriptions.unsubscribe(handle)});
|
|
90
|
+
}
|
|
73
91
|
this.#startTiming();
|
|
74
92
|
if (this.kind === 'remote') this.invoke({kind: 'install', change: null});
|
|
75
93
|
}
|
|
@@ -110,6 +128,22 @@ export class Provider {
|
|
|
110
128
|
const rpc = this.kind === 'rpc';
|
|
111
129
|
const remote = this.kind === 'remote';
|
|
112
130
|
const kwargs = this.readArguments(trigger);
|
|
131
|
+
if (trigger.askResult) {
|
|
132
|
+
Object.assign(kwargs, trigger.askResult);
|
|
133
|
+
kwargs._askResult = trigger.askResult;
|
|
134
|
+
}
|
|
135
|
+
const ask = node.getAttr('_ask');
|
|
136
|
+
if (ask && !trigger.askDone && AskDialog.required(this.binding, ask, kwargs, '_ask')) {
|
|
137
|
+
return AskDialog.show(this.binding, ask, kwargs, node.getAttr('_ask_title') ?? 'Warning').then(result => {
|
|
138
|
+
if (this.binding.closed) return;
|
|
139
|
+
if (result === null) {
|
|
140
|
+
const cancel = node.getAttr('_ask_onCancel');
|
|
141
|
+
if (cancel) this.#inline('_ask_onCancel', cancel, cancel, kwargs, true);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
return this.invoke({...trigger, askDone: true, askResult: result});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
113
147
|
let [attr, body] = [formula ? 'formula' : 'script', node.getAttr(formula ? 'formula' : 'script')];
|
|
114
148
|
// Truthiness of `_if`, `_else` and the body, as legacy (`gnrdomsource.js:371-385, 473-482`).
|
|
115
149
|
const condition = node.getAttr('_if');
|
|
@@ -148,12 +182,13 @@ export class Provider {
|
|
|
148
182
|
readArguments(trigger) {
|
|
149
183
|
const node = this.node;
|
|
150
184
|
const [, attrs] = node.builder.runtimeValues(node);
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
185
|
+
const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) =>
|
|
186
|
+
!CONTROL_ATTRIBUTES.has(name) && !name.startsWith('subscribe_') && !name.startsWith('selfsubscribe_')));
|
|
187
|
+
const kwargs = {...(trigger.kind === 'subscription' ? trigger.payload : {}),
|
|
188
|
+
...this.binding.runtime.renderer.references.resolveArguments(authored)};
|
|
189
|
+
if (trigger.kind === 'subscription') kwargs._subscription_kwargs = trigger.payload;
|
|
155
190
|
const change = trigger.change ?? null;
|
|
156
|
-
const reason = change ? change.level : trigger.kind;
|
|
191
|
+
const reason = change ? change.level : trigger.kind === 'subscription' ? trigger.topic : trigger.kind;
|
|
157
192
|
kwargs._node = change ? change.node : null;
|
|
158
193
|
kwargs._triggerpars = {kw: change, trigger_reason: reason};
|
|
159
194
|
kwargs._reason = reason;
|
|
@@ -330,7 +365,7 @@ export class RemoteProvider extends Provider {
|
|
|
330
365
|
}
|
|
331
366
|
|
|
332
367
|
// The trigger fields of the kwargs, in the legacy order of the inline parameters.
|
|
333
|
-
const TRIGGER_FIELDS = ['_node', '_triggerpars', '_reason'];
|
|
368
|
+
const TRIGGER_FIELDS = ['_node', '_triggerpars', '_reason', '_subscription_kwargs', '_askResult'];
|
|
334
369
|
// The fields a click adds (P9): locals of the inline bodies, never author arguments.
|
|
335
370
|
const CLICK_FIELDS = ['_evt', 'button_counter', 'button_shift', 'button_ctrl', 'button_alt', 'button_meta'];
|
|
336
371
|
|
package/src/binding/runtime.js
CHANGED
|
@@ -388,6 +388,11 @@ export class NodeBinding {
|
|
|
388
388
|
* A node whose `remote` is a string gets its RemoteBinding, created once.
|
|
389
389
|
*/
|
|
390
390
|
registerPointers() {
|
|
391
|
+
// Data elements have semantic lifetime but no rendered item to register their reference.
|
|
392
|
+
if (this.node._getMeta('data_element')) {
|
|
393
|
+
this.runtime.renderer.references.remove(this.node);
|
|
394
|
+
this.runtime.renderer.references.register(this.node, null);
|
|
395
|
+
}
|
|
391
396
|
const node = this.node;
|
|
392
397
|
const dataElement = node._getMeta('data_element');
|
|
393
398
|
if (dataElement && !PROVIDERS[node.nodeTag]) return;
|
|
@@ -403,11 +408,40 @@ export class NodeBinding {
|
|
|
403
408
|
if (name === 'datapath') this.#datapathRegistration = registration;
|
|
404
409
|
if (this.remote && (name === 'remote' || name.startsWith('remote_'))) this.#remoteRegistrations.add(registration);
|
|
405
410
|
}
|
|
406
|
-
if (!dataElement)
|
|
411
|
+
if (!dataElement) {
|
|
412
|
+
this.#registerTopics();
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
407
415
|
this.#provider ??= new PROVIDERS[node.nodeTag](this);
|
|
408
416
|
this.#provider.register();
|
|
409
417
|
}
|
|
410
418
|
|
|
419
|
+
/** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
|
|
420
|
+
#registerTopics() {
|
|
421
|
+
const node = this.node;
|
|
422
|
+
const subscriptions = this.runtime.gramlot._subscriptions;
|
|
423
|
+
for (const [name, handler] of Object.entries(node.getAttr())) {
|
|
424
|
+
const prefix = name.startsWith('selfsubscribe_') ? 'selfsubscribe_' : name.startsWith('subscribe_') ? 'subscribe_' : null;
|
|
425
|
+
if (!prefix) continue;
|
|
426
|
+
if (typeof handler !== 'string' || !handler) throw new TypeError(`${name} requires a handler`);
|
|
427
|
+
const topic = prefix === 'selfsubscribe_'
|
|
428
|
+
? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
|
|
429
|
+
const handle = subscriptions.subscribe(topic, payload => {
|
|
430
|
+
if (this.closed) return;
|
|
431
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
|
|
432
|
+
const {group, method} = this.runtime.logicRegistry.resolve(handler, node);
|
|
433
|
+
return method.call(group, node, payload);
|
|
434
|
+
}
|
|
435
|
+
const [, attrs] = node.builder.runtimeValues(node);
|
|
436
|
+
const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
|
|
437
|
+
!key.startsWith('subscribe_') && !key.startsWith('selfsubscribe_')));
|
|
438
|
+
const values = {...this.runtime.renderer.references.resolveArguments(authored), p_0: payload};
|
|
439
|
+
return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
|
|
440
|
+
});
|
|
441
|
+
this.#registrations.push({close: () => subscriptions.unsubscribe(handle)});
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
411
445
|
/** Close the registrations and make them again from the current pointers, the provider's included (D1). */
|
|
412
446
|
rebind() {
|
|
413
447
|
this.#closeRegistrations();
|
|
@@ -441,6 +475,7 @@ export class NodeBinding {
|
|
|
441
475
|
close() {
|
|
442
476
|
if (this.closed) return;
|
|
443
477
|
this.#closed = true;
|
|
478
|
+
if (this.node._getMeta('data_element')) this.runtime.renderer.references.remove(this.node);
|
|
444
479
|
this.#closeRegistrations();
|
|
445
480
|
const errors = [];
|
|
446
481
|
for (const disposer of this.#disposers.splice(0).reverse()) {
|
package/src/builder/binding.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"name": "binding",
|
|
8
8
|
"version": null,
|
|
9
9
|
"title": "Gramlot binding",
|
|
10
|
-
"description": "Data
|
|
10
|
+
"description": "Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."
|
|
11
11
|
},
|
|
12
12
|
"abstracts": {},
|
|
13
13
|
"elements": {
|
|
@@ -374,6 +374,31 @@
|
|
|
374
374
|
"_meta": {
|
|
375
375
|
"data_element": true
|
|
376
376
|
}
|
|
377
|
+
},
|
|
378
|
+
"html_button": {
|
|
379
|
+
"doc": "Plain native HTML button without Gramlot click mechanisms.",
|
|
380
|
+
"sub_tags": "a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",
|
|
381
|
+
"parent_tags": null,
|
|
382
|
+
"inherits_from": null,
|
|
383
|
+
"ns": null,
|
|
384
|
+
"attributes": {
|
|
385
|
+
"parameters": [
|
|
386
|
+
{
|
|
387
|
+
"name": "kwargs",
|
|
388
|
+
"kind": "var_keyword",
|
|
389
|
+
"role": "attribute",
|
|
390
|
+
"annotation": null,
|
|
391
|
+
"has_default": false
|
|
392
|
+
}
|
|
393
|
+
],
|
|
394
|
+
"accepts_var_keyword": true,
|
|
395
|
+
"accepts_var_positional": false
|
|
396
|
+
},
|
|
397
|
+
"node_label": null,
|
|
398
|
+
"collection_key": null,
|
|
399
|
+
"_meta": {
|
|
400
|
+
"render_tag": "button"
|
|
401
|
+
}
|
|
377
402
|
}
|
|
378
403
|
}
|
|
379
404
|
}
|
|
@@ -20,8 +20,8 @@ import {webcomponentCode} from '../webcomponent.js';
|
|
|
20
20
|
const DATA_FORBIDDEN = 'data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element';
|
|
21
21
|
// Declarations outside Gramlot 0.2.0 that fail explicitly (source plan, section 2).
|
|
22
22
|
const EXCLUDED_ELEMENTS = new Set();
|
|
23
|
-
const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id'
|
|
24
|
-
const EXCLUDED_ATTRIBUTE_PREFIXES = ['
|
|
23
|
+
const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id']);
|
|
24
|
+
const EXCLUDED_ATTRIBUTE_PREFIXES = ['formsubscribe_'];
|
|
25
25
|
|
|
26
26
|
// P18 and B8: the Data path of each data-element, which does not accept `?attr`,
|
|
27
27
|
// and its inline attribute, which excludes `func` on the same node, as `_if` does (Q11.1).
|
|
@@ -31,6 +31,15 @@ const DATA_INLINE_ATTRIBUTES = {dataFormula: 'formula', dataController: 'script'
|
|
|
31
31
|
|
|
32
32
|
/** The P18 violation of a data-element's attributes, or null. */
|
|
33
33
|
function dataElementError(tag, attrs) {
|
|
34
|
+
if (tag === 'html_button' && Object.keys(attrs).some(name =>
|
|
35
|
+
['action', 'ask', '_delay', 'fire'].includes(name) || name.startsWith('fire_'))) {
|
|
36
|
+
return 'plain HTML button: use button for action, ask, fire or _delay';
|
|
37
|
+
}
|
|
38
|
+
if (Object.hasOwn(attrs, 'ask') && tag !== 'button') return "'ask' is supported on buttons";
|
|
39
|
+
if (Object.hasOwn(attrs, '_ask') && !['dataController', 'dataFormula', 'dataRpc'].includes(tag)) return "'_ask' requires a controller, formula or RPC";
|
|
40
|
+
if (['dataSetter', 'dataRemote'].includes(tag) && Object.keys(attrs).some(name => name.startsWith('subscribe_') || name.startsWith('selfsubscribe_'))) {
|
|
41
|
+
return 'topic subscriptions are supported on controllers, formulas, RPCs and rendered elements';
|
|
42
|
+
}
|
|
34
43
|
const pathName = DATA_PATH_ATTRIBUTES[tag];
|
|
35
44
|
if (pathName && String(attrs[pathName] ?? '').includes('?')) {
|
|
36
45
|
return `'${pathName}' does not accept '?attr': '${attrs[pathName]}'`;
|
|
@@ -149,6 +158,12 @@ export class GramlotBuilder extends HtmlBuilder {
|
|
|
149
158
|
return super.validateNode(node, options);
|
|
150
159
|
}
|
|
151
160
|
|
|
161
|
+
/** Both button declarations occupy the native button slot in HTML content models. */
|
|
162
|
+
_validateChildren(parentTag, info, tags, includeMinimum) {
|
|
163
|
+
return super._validateChildren(parentTag, info,
|
|
164
|
+
tags.map(tag => tag === 'html_button' ? 'button' : tag), includeMinimum);
|
|
165
|
+
}
|
|
166
|
+
|
|
152
167
|
/** Custom elements are outside the native HTML child catalogue, as components are. */
|
|
153
168
|
_countsForGrammar(info) {
|
|
154
169
|
return info !== this.schema.webcomponent && super._countsForGrammar(info);
|
|
@@ -156,6 +171,8 @@ export class GramlotBuilder extends HtmlBuilder {
|
|
|
156
171
|
|
|
157
172
|
/** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
|
|
158
173
|
setChild(bag, tag, value, attrs, parentOverride = null) {
|
|
174
|
+
attrs = Object.fromEntries(Object.entries(attrs ?? {}).map(([key, value]) =>
|
|
175
|
+
[key, sourceTarget(value) instanceof SourceBagNode ? this.reference(value) : value]));
|
|
159
176
|
const plain = tag === 'dataSetter' && attrs?.value !== null && typeof attrs?.value === 'object'
|
|
160
177
|
&& Object.getPrototypeOf(attrs.value) === Object.prototype;
|
|
161
178
|
const actual = plain ? {...attrs, value: new Bag(attrs.value)} : attrs;
|
package/src/builder/source.js
CHANGED
|
@@ -3,11 +3,11 @@ import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
|
|
|
3
3
|
|
|
4
4
|
// The inline code attributes of each tag, besides `connect_on<event>` and the `==` expressions of any tag.
|
|
5
5
|
const CODE_ATTRIBUTES = {
|
|
6
|
-
dataFormula: ['formula', '_if', '_else'],
|
|
7
|
-
dataController: ['script', '_if', '_else'],
|
|
8
|
-
dataRpc: ['_if', '_else', '_onCalling', '_onResult', '_onError'],
|
|
6
|
+
dataFormula: ['formula', '_if', '_else', '_ask_if', '_ask_onCancel'],
|
|
7
|
+
dataController: ['script', '_if', '_else', '_ask_if', '_ask_onCancel'],
|
|
8
|
+
dataRpc: ['_ask_if', '_ask_onCancel', '_if', '_else', '_onCalling', '_onResult', '_onError'],
|
|
9
9
|
dataRemote: ['_if', '_else'],
|
|
10
|
-
button: ['action'],
|
|
10
|
+
button: ['action', '_ask_if'],
|
|
11
11
|
};
|
|
12
12
|
|
|
13
13
|
// The control attributes of `remote`, written on the node as they are; every other parameter becomes `remote_<k>`.
|
|
@@ -46,7 +46,15 @@ export class GramlotBuilderBagNode extends SourceBagNode {
|
|
|
46
46
|
...(typeof this.getAttr('remote') === 'string' ? REMOTE_CODE_ATTRIBUTES : [])];
|
|
47
47
|
const items = [];
|
|
48
48
|
for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
|
|
49
|
-
if (typeof value === 'string' && (own.includes(name) || name.startsWith('connect_on'))) items.push([name, value]);
|
|
49
|
+
if (typeof value === 'string' && (own.includes(name) || name.startsWith('connect_on') || name.startsWith('subscribe_') || name.startsWith('selfsubscribe_'))) items.push([name, value]);
|
|
50
|
+
}
|
|
51
|
+
for (const attribute of ['ask', '_ask']) {
|
|
52
|
+
const spec = this.getAttr(attribute);
|
|
53
|
+
if (spec && typeof spec === 'object') {
|
|
54
|
+
for (const key of ['_if', 'askIf']) {
|
|
55
|
+
if (typeof spec[key] === 'string') items.push([`${attribute}.${key}`, spec[key]]);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
50
58
|
}
|
|
51
59
|
for (const [name, value] of sourceAttributeItems(this.getAttr())) {
|
|
52
60
|
if (isExpression(value)) items.push([name, value]);
|
|
@@ -101,6 +109,11 @@ export class GramlotBuilderBagNode extends SourceBagNode {
|
|
|
101
109
|
return wrapSource(this);
|
|
102
110
|
}
|
|
103
111
|
|
|
112
|
+
/** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
|
|
113
|
+
publish(topic, payload = {}) {
|
|
114
|
+
return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
|
|
115
|
+
}
|
|
116
|
+
|
|
104
117
|
/** Builder's pointerType, except that a string starting with `==` is not a pointer. */
|
|
105
118
|
pointerType(v) {
|
|
106
119
|
if (typeof v === 'string' && v.startsWith('==')) return null;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import {toTytx, fromTytx} from '@genrojs/tytx';
|
|
2
|
+
import {SourceBagNode, sourceTarget} from '@genrojs/builders';
|
|
3
|
+
import {assertTransportData} from './references.js';
|
|
4
|
+
|
|
5
|
+
const TYPE = 'gramlot:publish';
|
|
6
|
+
|
|
7
|
+
/** Direct parent/child transport. Every message crosses postMessage, even same-origin. */
|
|
8
|
+
export class FrameMessages {
|
|
9
|
+
#app;
|
|
10
|
+
#window;
|
|
11
|
+
#document;
|
|
12
|
+
#session = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
|
|
13
|
+
#peers = new Map();
|
|
14
|
+
#closed = false;
|
|
15
|
+
#listener;
|
|
16
|
+
#load;
|
|
17
|
+
#hide;
|
|
18
|
+
#show;
|
|
19
|
+
|
|
20
|
+
constructor(app, document) {
|
|
21
|
+
this.#app = app;
|
|
22
|
+
this.#document = document;
|
|
23
|
+
this.#window = document.defaultView;
|
|
24
|
+
this.#listener = event => this.#receive(event);
|
|
25
|
+
this.#load = event => {
|
|
26
|
+
if (event.target?.localName !== 'iframe') return;
|
|
27
|
+
const peer = this.#child(event.target);
|
|
28
|
+
if (!peer) return;
|
|
29
|
+
this.#forget(peer.window);
|
|
30
|
+
this.#send(peer, {kind: 'hello'});
|
|
31
|
+
};
|
|
32
|
+
this.#window.addEventListener('message', this.#listener);
|
|
33
|
+
this.#hide = () => this.#disconnect();
|
|
34
|
+
this.#show = () => this.ready();
|
|
35
|
+
this.#window.addEventListener('pagehide', this.#hide);
|
|
36
|
+
this.#window.addEventListener('pageshow', this.#show);
|
|
37
|
+
document.addEventListener('load', this.#load, true);
|
|
38
|
+
const parent = this.#parent();
|
|
39
|
+
if (parent) this.#send(parent, {kind: 'hello'});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
ready() {
|
|
43
|
+
if (this.#closed || this.#app.state !== 'started') return;
|
|
44
|
+
const parent = this.#parent();
|
|
45
|
+
if (parent) this.#send(parent, {kind: 'ready'});
|
|
46
|
+
for (const frame of this.#document.getElementsByTagName('iframe')) {
|
|
47
|
+
const child = this.#child(frame);
|
|
48
|
+
if (child) this.#send(child, {kind: 'hello'});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
|
|
53
|
+
prepare(descriptor, payload) {
|
|
54
|
+
const peers = [];
|
|
55
|
+
if (descriptor.parent) {
|
|
56
|
+
const parent = this.#parent();
|
|
57
|
+
if (!parent) throw new Error('This page has no parent frame');
|
|
58
|
+
peers.push(parent);
|
|
59
|
+
}
|
|
60
|
+
if (descriptor.iframe !== undefined) {
|
|
61
|
+
const target = descriptor.iframe;
|
|
62
|
+
const node = sourceTarget(target);
|
|
63
|
+
const frame = typeof target === 'string'
|
|
64
|
+
? this.#document.getElementById(target)
|
|
65
|
+
: node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
|
|
66
|
+
const child = this.#child(frame);
|
|
67
|
+
if (!child) throw new Error('iframe destination must be an active Gramlot iframe ID or Source reference');
|
|
68
|
+
peers.push(child);
|
|
69
|
+
}
|
|
70
|
+
const destinations = peers.map(peer => {
|
|
71
|
+
const connection = this.#peers.get(peer.window);
|
|
72
|
+
if (!connection || connection.origin !== peer.origin) throw new Error('Destination page is not ready');
|
|
73
|
+
return {...peer, session: connection.session};
|
|
74
|
+
});
|
|
75
|
+
assertTransportData(payload);
|
|
76
|
+
const wire = toTytx(payload);
|
|
77
|
+
return () => {
|
|
78
|
+
if (this.#closed) return;
|
|
79
|
+
for (const peer of destinations) {
|
|
80
|
+
const current = this.#peer(peer.window);
|
|
81
|
+
if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
|
|
82
|
+
throw new Error('Destination page disconnected before publication');
|
|
83
|
+
}
|
|
84
|
+
this.#send(peer, {kind: 'publish', recipient: peer.session, topic: descriptor.topic, wire});
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
dispose() {
|
|
90
|
+
if (this.#closed) return;
|
|
91
|
+
this.#disconnect();
|
|
92
|
+
this.#closed = true;
|
|
93
|
+
this.#window.removeEventListener('message', this.#listener);
|
|
94
|
+
this.#window.removeEventListener('pagehide', this.#hide);
|
|
95
|
+
this.#window.removeEventListener('pageshow', this.#show);
|
|
96
|
+
this.#document.removeEventListener('load', this.#load, true);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
#disconnect() {
|
|
100
|
+
for (const [window, peer] of this.#peers) this.#send({window, origin: peer.origin}, {kind: 'close'});
|
|
101
|
+
for (const window of this.#peers.keys()) this.#forget(window);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
#forget(window) {
|
|
105
|
+
this.#peers.get(window)?.release?.();
|
|
106
|
+
this.#peers.delete(window);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#remember(peer, session) {
|
|
110
|
+
this.#forget(peer.window);
|
|
111
|
+
const connection = {session, origin: peer.origin};
|
|
112
|
+
if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
|
|
113
|
+
this.#send(peer, {kind: 'close'});
|
|
114
|
+
this.#forget(peer.window);
|
|
115
|
+
});
|
|
116
|
+
this.#peers.set(peer.window, connection);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
#receive(event) {
|
|
120
|
+
if (this.#closed || event.data?.type !== TYPE) return;
|
|
121
|
+
const peer = this.#peer(event.source);
|
|
122
|
+
if (!peer || event.origin !== peer.origin) return;
|
|
123
|
+
const message = event.data;
|
|
124
|
+
if (typeof message.session !== 'string' || !message.session) return;
|
|
125
|
+
if (message.kind === 'hello') {
|
|
126
|
+
this.#forget(peer.window);
|
|
127
|
+
if (message.ready === true) this.#remember(peer, message.session);
|
|
128
|
+
if (this.#app.state === 'started') this.#send(peer, {kind: 'ready'});
|
|
129
|
+
} else if (message.kind === 'ready') {
|
|
130
|
+
const changed = this.#peers.get(peer.window)?.session !== message.session;
|
|
131
|
+
this.#remember(peer, message.session);
|
|
132
|
+
if (changed && this.#app.state === 'started') this.#send(peer, {kind: 'ready'});
|
|
133
|
+
} else if (message.kind === 'close') {
|
|
134
|
+
if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
|
|
135
|
+
} else if (message.kind === 'publish') {
|
|
136
|
+
if (this.#app.state !== 'started' || message.recipient !== this.#session
|
|
137
|
+
|| this.#peers.get(peer.window)?.session !== message.session) return;
|
|
138
|
+
if (typeof message.topic !== 'string' || !message.topic || typeof message.wire !== 'string') return;
|
|
139
|
+
// Dispatch only in this receiving page; never retransmit the routing descriptor.
|
|
140
|
+
this.#app.publish(message.topic, fromTytx(message.wire));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
#send(peer, message) {
|
|
145
|
+
peer.window.postMessage({type: TYPE, session: this.#session, ready: this.#app.state === 'started', ...message}, peer.origin === 'null' ? '*' : peer.origin);
|
|
146
|
+
}
|
|
147
|
+
#parent() {
|
|
148
|
+
const parent = this.#window.parent;
|
|
149
|
+
if (parent === this.#window) return null;
|
|
150
|
+
return {window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI)};
|
|
151
|
+
}
|
|
152
|
+
#child(frame) {
|
|
153
|
+
if (frame?.localName !== 'iframe' || !frame.isConnected || !frame.contentWindow) return null;
|
|
154
|
+
const node = this.#app.dom.getBaseSourceNode(frame);
|
|
155
|
+
if (!node || !this.#app.src.binding.bindingFor(node)
|
|
156
|
+
|| this.#app.dom.getDomNode(node) !== frame) return null;
|
|
157
|
+
const sandbox = frame.getAttribute('sandbox');
|
|
158
|
+
const opaque = sandbox !== null && !sandbox.split(/\s+/).includes('allow-same-origin');
|
|
159
|
+
const origin = opaque ? 'null' : this.#origin(frame.hasAttribute('srcdoc')
|
|
160
|
+
? this.#document.baseURI : frame.getAttribute('src') || this.#document.baseURI);
|
|
161
|
+
return {window: frame.contentWindow, origin, node};
|
|
162
|
+
}
|
|
163
|
+
#origin(address) {
|
|
164
|
+
const url = new URL(address, this.#document.baseURI);
|
|
165
|
+
// Chromium's URL.origin can be file://, while MessageEvent.origin is null.
|
|
166
|
+
return url.protocol === 'file:' ? 'null' : url.origin;
|
|
167
|
+
}
|
|
168
|
+
#peer(window) {
|
|
169
|
+
const parent = this.#parent();
|
|
170
|
+
if (parent?.window === window) return parent;
|
|
171
|
+
for (const frame of this.#document.getElementsByTagName('iframe')) {
|
|
172
|
+
const child = this.#child(frame);
|
|
173
|
+
if (child?.window === window) return child;
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
package/src/gramlot.d.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type {DomElement, DomDocument, DomEvent, DomWindow} from './dom.d.ts';
|
|
7
7
|
import type {Bag} from '@genrojs/bag';
|
|
8
|
+
import type {SourceBagNode} from '@genrojs/builders';
|
|
8
9
|
import type {RpcTransport} from './handlers/rpc-handler.js';
|
|
9
10
|
import type {SourceHandler} from './handlers/source-handler.js';
|
|
10
11
|
import type {RpcHandler} from './handlers/rpc-handler.js';
|
|
@@ -36,6 +37,13 @@ export interface GramlotOptions {
|
|
|
36
37
|
/** The lifecycle state of a `Gramlot` instance. */
|
|
37
38
|
export type GramlotState = 'ready' | 'loading' | 'started' | 'failed' | 'disposed';
|
|
38
39
|
|
|
40
|
+
/** Opaque registration returned by subscribe; meaningful only to its owning page. */
|
|
41
|
+
export interface SubscriptionHandle { readonly __subscriptionHandle: unique symbol; }
|
|
42
|
+
|
|
43
|
+
/** Legacy-shaped publication. Frame forwarding follows synchronous local delivery. */
|
|
44
|
+
export type Publication = string | {topic: string; nodeId: string} |
|
|
45
|
+
{topic: string; parent?: boolean; iframe?: string | SourceBagNode};
|
|
46
|
+
|
|
39
47
|
/** One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`. */
|
|
40
48
|
export class Gramlot {
|
|
41
49
|
/** The id of the server page. */
|
|
@@ -66,6 +74,12 @@ export class Gramlot {
|
|
|
66
74
|
pagehide?: (event: DomEvent) => void;
|
|
67
75
|
/** Create the page instance; the construction order is the one of the source plan. */
|
|
68
76
|
constructor(options?: GramlotOptions);
|
|
77
|
+
/** Publish one named payload; forwarding uses postMessage and requires a ready page. */
|
|
78
|
+
publish(topic: Publication, payload?: Record<string, unknown>): void;
|
|
79
|
+
/** Subscribe to a local page topic, synchronously in registration order. */
|
|
80
|
+
subscribe(topic: string, callback: (payload: Record<string, unknown>) => unknown): SubscriptionHandle;
|
|
81
|
+
/** Remove a registration; repeating removal of an owned handle is harmless. */
|
|
82
|
+
unsubscribe(registration: SubscriptionHandle): void;
|
|
69
83
|
/** Load `main` from the server and mount it; resolves with the instance. */
|
|
70
84
|
start(): Promise<Gramlot>;
|
|
71
85
|
/** Request `main` from the transport and mount it. */
|