@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.
@@ -0,0 +1,230 @@
1
+ import {Bag} from '@genrojs/bag';
2
+
3
+ /**
4
+ * Providers of one Gramlot page (source plan §4.8): the semantic runtime of a `dataFormula` or a
5
+ * `dataController`, owned by its NodeBinding.
6
+ *
7
+ * One owner per trigger (B7): the router delivers the Data changes of the `^` pointers to
8
+ * `receive`; `_timing` is started by `register`; `_init`, `_onBuilt` and `_onStart` are invoked by
9
+ * BindingRuntime; the click of a button invokes the controller nested in it, through ButtonBinding. Every timer is tracked on the NodeBinding, so the close of the node cancels it.
10
+ * A body is named logic (P20), the group method given by `LogicRegistry.resolve`, or inline code
11
+ * compiled by the page's InlineCompiler (S09); there is no fallback from a name to inline.
12
+ */
13
+
14
+ // Control attributes: read by the provider, never passed to the body (P20). `if`/`else` are the
15
+ // names runtimeValues gives to `_if`/`_else`.
16
+ const CONTROL_ATTRIBUTES = new Set([
17
+ 'destination_path', 'result_path', 'func', 'formula', 'script', 'if', 'else',
18
+ '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
19
+ ]);
20
+
21
+ export class Provider {
22
+ #binding;
23
+ #registrations = [];
24
+ #timingRegistration = null;
25
+ #stopTiming = null;
26
+ #cancelDelay = null;
27
+
28
+ constructor(binding) {
29
+ this.#binding = binding;
30
+ binding.track(() => {
31
+ this.cancel();
32
+ this.#closeRegistrations();
33
+ });
34
+ }
35
+
36
+ get binding() { return this.#binding; }
37
+ get node() { return this.binding.node; }
38
+ /** 'formula' | 'controller'. */
39
+ get kind() { throw new Error('Provider.kind is defined by FormulaProvider and ControllerProvider'); }
40
+
41
+ /**
42
+ * Step 4 of §5.1, and every rebinding: the `^` pointers are registered again from the current
43
+ * context (a pointer on a null path is not registered, Q7), and `_timing` starts again from its
44
+ * current value. A numeric `_onStart` must be a finite number not below zero (P22).
45
+ */
46
+ register() {
47
+ const node = this.node;
48
+ const onStart = node.getAttr('_onStart');
49
+ if (typeof onStart === 'number' && !(Number.isFinite(onStart) && onStart >= 0)) {
50
+ throw new Error(`${node.nodeTag} '${node.label}': _onStart must be true or a delay in ms not below 0: ${onStart}`);
51
+ }
52
+ this.#closeRegistrations();
53
+ const router = this.binding.runtime.router;
54
+ for (const [name, pointer] of node.pointers()) {
55
+ if (name === 'datapath') continue;
56
+ const absolute = node.absDatapath(pointer);
57
+ if (absolute === null) continue;
58
+ const [path, attr = null] = absolute.split('?', 2);
59
+ const registration = router.register({path, attr, recipient: this});
60
+ this.#registrations.push(registration);
61
+ if (name === '_timing') this.#timingRegistration = registration;
62
+ }
63
+ this.#startTiming();
64
+ }
65
+
66
+ /**
67
+ * Router recipient. The `_timing` pointer restarts the timer; any other change is a Data
68
+ * trigger: `_userChanges` lets only the level `node` through (D2a), evaluated now; `_delay`
69
+ * debounces, the last call wins, and the arguments are read when the body runs.
70
+ */
71
+ receive(change) {
72
+ if (change.registration === this.#timingRegistration) {
73
+ this.#startTiming();
74
+ return;
75
+ }
76
+ if (this.#resolved('_userChanges') && change.level !== 'node') return;
77
+ const trigger = {kind: 'data', change};
78
+ const delay = this.#resolved('_delay');
79
+ if (delay > 0) this.#debounce(trigger, delay);
80
+ else this.invoke(trigger);
81
+ }
82
+
83
+ /**
84
+ * The one pipeline of every trigger, `{kind: 'data'|'init'|'built'|'start'|'timing', change}` or
85
+ * `{kind: 'click', event, counter}`:
86
+ * arguments, `_if`, body, and for a formula the write of the result at `result_path`. `_if` and
87
+ * `_else` are inline (Q11.1): a false `_if` stops, or `_else` replaces the body (D5); an empty `_if`
88
+ * is absent and an empty `_else` or body is none, as legacy. A body is
89
+ * the inline `formula`/`script`, compiled by the page's InlineCompiler, or the named `func`. An
90
+ * error propagates to the caller (P12). A closed node runs nothing.
91
+ */
92
+ invoke(trigger) {
93
+ if (this.binding.closed) return;
94
+ const node = this.node;
95
+ const formula = this.kind === 'formula';
96
+ const kwargs = this.readArguments(trigger);
97
+ let [attr, body] = [formula ? 'formula' : 'script', node.getAttr(formula ? 'formula' : 'script')];
98
+ // Truthiness of `_if`, `_else` and the body, as legacy (`gnrdomsource.js:371-385, 473-482`).
99
+ const condition = node.getAttr('_if');
100
+ if (condition && !this.#inline('_if', `return (${condition})`, kwargs, false)) {
101
+ [attr, body] = ['_else', node.getAttr('_else')];
102
+ if (!body) return;
103
+ }
104
+ const func = node.getAttr('func');
105
+ let result;
106
+ if (body) {
107
+ result = this.#inline(attr, formula ? `return ${body}` : body, kwargs, true);
108
+ } else if (func === null || func === undefined) {
109
+ // No body, as legacy: a formula writes the Bag of its arguments, a controller does nothing.
110
+ if (!formula) return;
111
+ result = new Bag(authorArguments(kwargs));
112
+ } else {
113
+ const {group, method} = this.binding.runtime.logicRegistry.resolve(func, node);
114
+ result = formula ? method.call(group, kwargs) : method.call(group, node, kwargs);
115
+ }
116
+ if (formula) node.setRelativeData(node.pathAttribute('result_path'), result);
117
+ }
118
+
119
+ /**
120
+ * The kwargs of P20, read now: the resolved author attributes (`^` and `=` alike; null on a null
121
+ * path, D1) without the control attributes, plus `_node`, `_triggerpars` and `_reason`. A Data
122
+ * trigger gives the Data node, the delivered change and its level, as legacy; any other trigger
123
+ * gives null, null and its own name. A click adds `_evt` and the `button_*` arguments of P9.
124
+ */
125
+ readArguments(trigger) {
126
+ const node = this.node;
127
+ const [, attrs] = node.builder.runtimeValues(node);
128
+ const kwargs = {};
129
+ for (const [name, value] of Object.entries(attrs)) {
130
+ if (!CONTROL_ATTRIBUTES.has(name)) kwargs[name] = value;
131
+ }
132
+ const change = trigger.change ?? null;
133
+ const reason = change ? change.level : trigger.kind;
134
+ kwargs._node = change ? change.node : null;
135
+ kwargs._triggerpars = {kw: change, trigger_reason: reason};
136
+ kwargs._reason = reason;
137
+ if (trigger.kind === 'click') Object.assign(kwargs, clickArguments(trigger));
138
+ return kwargs;
139
+ }
140
+
141
+ /** Cancel the pending `_delay` call and stop `_timing`. */
142
+ cancel() {
143
+ this.#cancelDelay?.();
144
+ this.#stopTiming?.();
145
+ }
146
+
147
+ /** `_timing` in seconds: a `setInterval` while the value is above 0; null or 0 stops it. */
148
+ #startTiming() {
149
+ this.#stopTiming?.();
150
+ const seconds = this.#resolved('_timing');
151
+ if (!(seconds > 0)) return;
152
+ const timer = setInterval(() => this.invoke({kind: 'timing', change: null}), seconds * 1000);
153
+ const release = this.binding.track(() => clearInterval(timer));
154
+ this.#stopTiming = () => {
155
+ clearInterval(timer);
156
+ release();
157
+ this.#stopTiming = null;
158
+ };
159
+ }
160
+
161
+ #debounce(trigger, delay) {
162
+ this.#cancelDelay?.();
163
+ let release = null;
164
+ const timer = setTimeout(() => {
165
+ release();
166
+ this.#cancelDelay = null;
167
+ this.invoke(trigger);
168
+ }, delay);
169
+ release = this.binding.track(() => clearTimeout(timer));
170
+ this.#cancelDelay = () => {
171
+ clearTimeout(timer);
172
+ release();
173
+ this.#cancelDelay = null;
174
+ };
175
+ }
176
+
177
+ /** The current value of a control attribute: a pointer is read from Data. */
178
+ #resolved(name) {
179
+ const node = this.node;
180
+ const value = node.getAttr(name);
181
+ return node.pointerType(value) ? node.getRelativeData(value) : value ?? null;
182
+ }
183
+
184
+ /**
185
+ * The inline declaration `attr` run on `kwargs`, as legacy (`gnrdomsource.js:377-378, 480-482`):
186
+ * `this` = node, the parameters `_node`, `_triggerpars`, `_reason`, the click arguments (undefined
187
+ * for any other trigger), then the author attributes; a body (`formula`, `script`, or `_else` in
188
+ * their place) has `_kwargs` first, `_if` has not.
189
+ */
190
+ #inline(attr, source, kwargs, body) {
191
+ const names = [...(body ? ['_kwargs'] : []), ...TRIGGER_FIELDS, ...CLICK_FIELDS,
192
+ ...Object.keys(authorArguments(kwargs))];
193
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, source, names)({...kwargs, _kwargs: kwargs});
194
+ }
195
+
196
+ #closeRegistrations() {
197
+ for (const registration of this.#registrations.splice(0)) registration.close();
198
+ this.#timingRegistration = null;
199
+ }
200
+ }
201
+
202
+ /** The provider of a `dataFormula`: the body's return value is written at `result_path`. */
203
+ export class FormulaProvider extends Provider {
204
+ get kind() { return 'formula'; }
205
+ }
206
+
207
+ /** The provider of a `dataController`: the body runs for its side effects on the node. */
208
+ export class ControllerProvider extends Provider {
209
+ get kind() { return 'controller'; }
210
+ }
211
+
212
+ // The trigger fields of the kwargs, in the legacy order of the inline parameters.
213
+ const TRIGGER_FIELDS = ['_node', '_triggerpars', '_reason'];
214
+ // The fields a click adds (P9): locals of the inline bodies, never author arguments.
215
+ const CLICK_FIELDS = ['_evt', 'button_counter', 'button_shift', 'button_ctrl', 'button_alt', 'button_meta'];
216
+
217
+ /** The kwargs written by the author, without the trigger and click fields. */
218
+ function authorArguments(kwargs) {
219
+ const author = {...kwargs};
220
+ for (const name of [...TRIGGER_FIELDS, ...CLICK_FIELDS]) delete author[name];
221
+ return author;
222
+ }
223
+
224
+ /** `_evt` and the `button_*` arguments of a click trigger (P9). */
225
+ function clickArguments({event, counter}) {
226
+ return {
227
+ _evt: event, button_counter: counter, button_shift: Boolean(event.shiftKey),
228
+ button_ctrl: Boolean(event.ctrlKey), button_alt: Boolean(event.altKey), button_meta: Boolean(event.metaKey),
229
+ };
230
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Data routing of one Gramlot page (source plan §4.5).
3
+ *
4
+ * The router receives every event of Builder's Data wrapper through the one
5
+ * subscription of BindingRuntime, strips the first segment `_root_` and
6
+ * delivers the event to the registrations its path reaches, through a trie
7
+ * by segment: the work of one event does not depend on the unconnected
8
+ * branches.
9
+ */
10
+
11
+ // Builder's content node under the Data wrapper (`_dataroot` → `_root_`).
12
+ const DATA_ROOT = '_root_';
13
+
14
+ /** One trie level: the registrations of one path and the next segments. */
15
+ class RouteNode {
16
+ constructor(parent = null, segment = null) {
17
+ this.parent = parent;
18
+ this.segment = segment;
19
+ this.children = new Map();
20
+ this.registrations = new Set();
21
+ }
22
+ }
23
+
24
+ /** One registered path: `path` without `_root_`, `attr` for a `?attr` pointer. */
25
+ export class DataRegistration {
26
+ #router;
27
+ #path;
28
+ #attr;
29
+ #recipient;
30
+ #order;
31
+ #active = true;
32
+
33
+ constructor(router, {path, attr, recipient, order}) {
34
+ this.#router = router;
35
+ this.#path = path;
36
+ this.#attr = attr;
37
+ this.#recipient = recipient;
38
+ this.#order = order;
39
+ }
40
+
41
+ get router() { return this.#router; }
42
+ get path() { return this.#path; }
43
+ get attr() { return this.#attr; }
44
+ get recipient() { return this.#recipient; }
45
+ get active() { return this.#active; }
46
+ /** Registration order, which is also the delivery order of one event. */
47
+ get order() { return this.#order; }
48
+
49
+ /** Stop receiving; a second call does nothing. */
50
+ close() {
51
+ if (!this.active) return;
52
+ this.#active = false;
53
+ this.router.unregister(this);
54
+ }
55
+ }
56
+
57
+ /** The object delivered to a recipient. */
58
+ export class DataChange {
59
+ constructor({evt, node, path, oldvalue, attrsDiff, reason, fired, level, registration}) {
60
+ this.evt = evt;
61
+ this.node = node;
62
+ this.path = path;
63
+ this.oldvalue = oldvalue;
64
+ this.attrsDiff = attrsDiff;
65
+ this.reason = reason;
66
+ this.fired = fired;
67
+ this.level = level;
68
+ this.registration = registration;
69
+ }
70
+ }
71
+
72
+ export class DataRouter {
73
+ #runtime;
74
+ #root = new RouteNode();
75
+ #routes = new Map();
76
+ #size = 0;
77
+ #order = 0;
78
+
79
+ constructor(runtime) {
80
+ this.#runtime = runtime;
81
+ }
82
+
83
+ get runtime() { return this.#runtime; }
84
+ /** Active registrations. */
85
+ get size() { return this.#size; }
86
+
87
+ /** Register `recipient` on the absolute Data `path` (without `_root_`), optionally on its attribute `attr`. */
88
+ register({path, attr = null, recipient}) {
89
+ if (typeof path !== 'string' || path === '') throw new TypeError(`A Data registration requires a path: ${path}`);
90
+ let route = this.#root;
91
+ for (const segment of path.split('.')) {
92
+ let next = route.children.get(segment);
93
+ if (!next) {
94
+ next = new RouteNode(route, segment);
95
+ route.children.set(segment, next);
96
+ }
97
+ route = next;
98
+ }
99
+ this.#order += 1;
100
+ const registration = new DataRegistration(this, {path, attr, recipient, order: this.#order});
101
+ route.registrations.add(registration);
102
+ this.#routes.set(registration, route);
103
+ this.#size += 1;
104
+ return registration;
105
+ }
106
+
107
+ /** Remove a registration from the trie; called by DataRegistration.close. */
108
+ unregister(registration) {
109
+ let route = this.#routes.get(registration);
110
+ if (!route) return;
111
+ this.#routes.delete(registration);
112
+ route.registrations.delete(registration);
113
+ this.#size -= 1;
114
+ while (route.parent && !route.children.size && !route.registrations.size) {
115
+ route.parent.children.delete(route.segment);
116
+ route = route.parent;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Deliver one event of Builder's Data wrapper. `ins` and `del` carry the parent path, the
122
+ * other events the node path; a `del` from `clear()` carries an array of nodes. An event
123
+ * outside `_root_` and an `autocreate` insertion are ignored.
124
+ */
125
+ deliver(event) {
126
+ const {pathlist} = event;
127
+ if (!pathlist?.length || pathlist[0] !== DATA_ROOT) return;
128
+ if (event.reason === 'autocreate') return;
129
+ const base = pathlist.slice(1);
130
+ const container = event.evt === 'ins' || event.evt === 'del';
131
+ for (const node of Array.isArray(event.node) ? event.node : [event.node]) {
132
+ const segments = container ? [...base, node.label] : base;
133
+ const path = segments.join('.');
134
+ // Candidates are copied before any delivery; a registration closed meanwhile receives nothing.
135
+ for (const [registration, level] of this.#candidates(segments, event)) {
136
+ if (!registration.active) continue;
137
+ registration.recipient.receive(new DataChange({
138
+ evt: event.evt, node, path, oldvalue: event.oldvalue ?? null,
139
+ attrsDiff: event.attrs_diff ?? null, reason: event.reason ?? null,
140
+ fired: event.fired ?? false, level, registration,
141
+ }));
142
+ }
143
+ }
144
+ }
145
+
146
+ /** `[registration, level]` pairs reached by an event on `segments`, in registration order. */
147
+ #candidates(segments, event) {
148
+ const found = [];
149
+ let route = this.#root;
150
+ for (const segment of segments) {
151
+ for (const registration of route.registrations) {
152
+ if (route !== this.#root && this.#accepts(registration, 'child', event)) found.push([registration, 'child']);
153
+ }
154
+ route = route.children.get(segment);
155
+ if (!route) return found.sort(([a], [b]) => a.order - b.order);
156
+ }
157
+ for (const registration of route.registrations) {
158
+ if (this.#accepts(registration, 'node', event)) found.push([registration, 'node']);
159
+ }
160
+ const below = [...route.children.values()];
161
+ while (below.length) {
162
+ const next = below.pop();
163
+ for (const registration of next.registrations) {
164
+ if (this.#accepts(registration, 'container', event)) found.push([registration, 'container']);
165
+ }
166
+ below.push(...next.children.values());
167
+ }
168
+ return found.sort(([a], [b]) => a.order - b.order);
169
+ }
170
+
171
+ /**
172
+ * Whether an event reaches a registration at `level` (node: same path; container: the
173
+ * registered path is below the event path; child: the event path is below it).
174
+ * A value registration receives the value events; an attribute-only `upd_attrs` reaches
175
+ * only the `?attr` registrations of that attribute; a fired event at level child is not
176
+ * delivered. A `?attr` registration also receives the events that insert or delete its
177
+ * node, and those that replace, delete or insert an ancestor (R14).
178
+ */
179
+ #accepts(registration, level, event) {
180
+ const {evt} = event;
181
+ if (registration.attr === null) {
182
+ if (evt === 'upd_attrs') return false;
183
+ return !(level === 'child' && event.fired);
184
+ }
185
+ if (level === 'child') return false;
186
+ if (level === 'container') return evt !== 'upd_attrs';
187
+ if (evt === 'ins' || evt === 'del') return true;
188
+ return Object.hasOwn(event.attrs_diff ?? {}, registration.attr);
189
+ }
190
+ }