boto-rb-web 0.34.0
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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +17 -0
- data/assets/boto-web/boot.js +16 -0
- data/assets/boto-web/boto-web.css +32 -0
- data/assets/boto-web/dom/animate.js +49 -0
- data/assets/boto-web/dom/flip.js +41 -0
- data/assets/boto-web/dom/keyed.js +15 -0
- data/assets/boto-web/dom/morph.js +112 -0
- data/assets/boto-web/dom/navigation.js +72 -0
- data/assets/boto-web/dom/sync.js +42 -0
- data/assets/boto-web/net/base.js +5 -0
- data/assets/boto-web/net/protocol.js +46 -0
- data/assets/boto-web/net/sse.js +45 -0
- data/assets/boto-web/net/sse_stream.js +84 -0
- data/assets/boto-web/net/token.js +9 -0
- data/assets/boto-web/net/transport.js +99 -0
- data/assets/boto-web/runtime/component.js +138 -0
- data/assets/boto-web/runtime/events.js +54 -0
- data/assets/boto-web/runtime/hooks.js +82 -0
- data/assets/boto-web/runtime/live.js +12 -0
- data/assets/boto-web/runtime/on.js +36 -0
- data/assets/boto-web/runtime/runtime.js +100 -0
- data/assets/boto-web/runtime/scope.js +112 -0
- data/assets/boto-web/runtime/signals.js +123 -0
- data/assets/boto-web/template/decimal.js +93 -0
- data/assets/boto-web/template/helpers.js +31 -0
- data/assets/boto-web/template/html.js +61 -0
- data/assets/boto-web/template/hydrate.js +25 -0
- data/assets/boto-web/template/ruby/core.js +72 -0
- data/assets/boto-web/template/ruby/lists.js +63 -0
- data/assets/boto-web/template/ruby.js +5 -0
- data/lib/boto/component/arguments.rb +58 -0
- data/lib/boto/component/definition.rb +114 -0
- data/lib/boto/component.rb +107 -0
- data/lib/boto/helper.rb +14 -0
- data/lib/boto/view.rb +63 -0
- data/lib/boto/web/app_extension.rb +78 -0
- data/lib/boto/web/assets.rb +59 -0
- data/lib/boto/web/child_path.rb +38 -0
- data/lib/boto/web/code_class.rb +16 -0
- data/lib/boto/web/compiler/analysis/deps.rb +46 -0
- data/lib/boto/web/compiler/analysis/handlers.rb +47 -0
- data/lib/boto/web/compiler/analysis/walker.rb +174 -0
- data/lib/boto/web/compiler/analysis.rb +44 -0
- data/lib/boto/web/compiler/client_helper.rb +34 -0
- data/lib/boto/web/compiler/computed_body.rb +40 -0
- data/lib/boto/web/compiler/directives.rb +86 -0
- data/lib/boto/web/compiler/expression/calls.rb +149 -0
- data/lib/boto/web/compiler/expression/collections.rb +116 -0
- data/lib/boto/web/compiler/expression/literals.rb +75 -0
- data/lib/boto/web/compiler/expression/logic.rb +53 -0
- data/lib/boto/web/compiler/expression/operators.rb +85 -0
- data/lib/boto/web/compiler/expression/strings.rb +31 -0
- data/lib/boto/web/compiler/expression.rb +93 -0
- data/lib/boto/web/compiler/module_writer/handlers_js.rb +75 -0
- data/lib/boto/web/compiler/module_writer/js.rb +24 -0
- data/lib/boto/web/compiler/module_writer/tag_js.rb +132 -0
- data/lib/boto/web/compiler/module_writer/template_js.rb +89 -0
- data/lib/boto/web/compiler/module_writer/type_shape.rb +28 -0
- data/lib/boto/web/compiler/module_writer.rb +79 -0
- data/lib/boto/web/compiler/template.rb +136 -0
- data/lib/boto/web/compiler/type_map.rb +43 -0
- data/lib/boto/web/compiler/type_scope.rb +68 -0
- data/lib/boto/web/compiler.rb +9 -0
- data/lib/boto/web/dispatcher.rb +113 -0
- data/lib/boto/web/events_endpoint.rb +43 -0
- data/lib/boto/web/failure.rb +30 -0
- data/lib/boto/web/head.rb +24 -0
- data/lib/boto/web/helpers.rb +40 -0
- data/lib/boto/web/hooks.rb +39 -0
- data/lib/boto/web/html.rb +65 -0
- data/lib/boto/web/layouts/context.rb +22 -0
- data/lib/boto/web/layouts/template.rb +31 -0
- data/lib/boto/web/layouts.rb +69 -0
- data/lib/boto/web/modules.rb +37 -0
- data/lib/boto/web/page_endpoint.rb +65 -0
- data/lib/boto/web/project_helpers.rb +54 -0
- data/lib/boto/web/protocol.rb +85 -0
- data/lib/boto/web/registry.rb +86 -0
- data/lib/boto/web/registry_error.rb +8 -0
- data/lib/boto/web/renderer/erb_source.rb +199 -0
- data/lib/boto/web/renderer/render_context.rb +37 -0
- data/lib/boto/web/renderer.rb +94 -0
- data/lib/boto/web/runtime.rb +45 -0
- data/lib/boto/web/scoped_css.rb +113 -0
- data/lib/boto/web/secret_key.rb +8 -0
- data/lib/boto/web/settings.rb +27 -0
- data/lib/boto/web/snapshot/changes.rb +26 -0
- data/lib/boto/web/snapshot/inputs.rb +50 -0
- data/lib/boto/web/snapshot/token.rb +42 -0
- data/lib/boto/web/snapshot.rb +111 -0
- data/lib/boto/web/static_file.rb +35 -0
- data/lib/boto/web/stylesheet.rb +53 -0
- data/lib/boto/web/tailwind.rb +69 -0
- data/lib/boto/web/template_preview.rb +31 -0
- data/lib/boto/web/transports/http.rb +36 -0
- data/lib/boto/web/transports/sse.rb +45 -0
- data/lib/boto/web/transports.rb +21 -0
- data/lib/boto/web/version.rb +7 -0
- data/lib/boto/web/view_loader.rb +21 -0
- data/lib/boto/web.rb +17 -0
- metadata +172 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Interface of PROTOCOL.md: send(envelope), subscribe(view, handler), close().
|
|
2
|
+
// Swapping the transport (WebSocket, later) changes nothing else in the runtime.
|
|
3
|
+
|
|
4
|
+
import { parseResponse } from "./protocol.js";
|
|
5
|
+
import { openEventStream } from "./sse_stream.js";
|
|
6
|
+
|
|
7
|
+
const CSRF_SELECTOR = 'meta[name="csrf-token"]';
|
|
8
|
+
|
|
9
|
+
const defaultReadCsrf = () => globalThis.document?.querySelector(CSRF_SELECTOR)?.content;
|
|
10
|
+
|
|
11
|
+
export class HttpTransport {
|
|
12
|
+
#base;
|
|
13
|
+
#fetch;
|
|
14
|
+
#timers;
|
|
15
|
+
#readCsrf;
|
|
16
|
+
#streams = new Set();
|
|
17
|
+
|
|
18
|
+
constructor({ base = "", fetch = globalThis.fetch, timers = globalThis, readCsrf = defaultReadCsrf } = {}) {
|
|
19
|
+
this.#base = base;
|
|
20
|
+
// Calling fetch as a method of the transport throws "Illegal invocation" in browsers.
|
|
21
|
+
this.#fetch = (...args) => fetch(...args);
|
|
22
|
+
this.#timers = timers;
|
|
23
|
+
this.#readCsrf = readCsrf;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async send(envelope) {
|
|
27
|
+
const response = await this.#fetch(`${this.#base}/_boto/web`, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: { "content-type": "application/json", accept: "application/json", ...this.#csrfHeader() },
|
|
30
|
+
body: JSON.stringify(envelope),
|
|
31
|
+
});
|
|
32
|
+
return parseResponse(await response.json());
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
subscribe(viewSnapshot, handler) {
|
|
36
|
+
const stream = openEventStream({
|
|
37
|
+
url: `${this.#base}/_boto/web/events?view=${encodeURIComponent(viewSnapshot)}`,
|
|
38
|
+
fetch: this.#fetch,
|
|
39
|
+
timers: this.#timers,
|
|
40
|
+
onEvent: (name, data) => toChannelEvent(name, data, handler),
|
|
41
|
+
});
|
|
42
|
+
this.#streams.add(stream);
|
|
43
|
+
return () => {
|
|
44
|
+
stream.stop();
|
|
45
|
+
this.#streams.delete(stream);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
close() {
|
|
50
|
+
for (const stream of this.#streams) stream.stop();
|
|
51
|
+
this.#streams.clear();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
#csrfHeader() {
|
|
55
|
+
const token = this.#readCsrf();
|
|
56
|
+
return token ? { "X-CSRF-Token": token } : {};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function toChannelEvent(name, data, handler) {
|
|
61
|
+
let payload;
|
|
62
|
+
try {
|
|
63
|
+
payload = JSON.parse(data);
|
|
64
|
+
} catch {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
handler({ channel: payload?.channel, name });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Fake, in memory: the handler plays the server.
|
|
71
|
+
export class MemoryTransport {
|
|
72
|
+
#handler;
|
|
73
|
+
#subscribers = new Map();
|
|
74
|
+
|
|
75
|
+
constructor(handler) {
|
|
76
|
+
this.#handler = handler;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async send(envelope) {
|
|
80
|
+
return parseResponse(await this.#handler(envelope));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
subscribe(viewSnapshot, handler) {
|
|
84
|
+
const handlers = this.#subscribers.get(viewSnapshot) ?? new Set();
|
|
85
|
+
handlers.add(handler);
|
|
86
|
+
this.#subscribers.set(viewSnapshot, handlers);
|
|
87
|
+
return () => {
|
|
88
|
+
handlers.delete(handler);
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
push(viewSnapshot, event) {
|
|
93
|
+
for (const handler of this.#subscribers.get(viewSnapshot) ?? []) handler(event);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
close() {
|
|
97
|
+
this.#subscribers.clear();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// A component in the browser: its scope, its render, its events, [(model)] and its server blocks.
|
|
2
|
+
|
|
3
|
+
import { batch, effect } from "./signals.js";
|
|
4
|
+
import { createScope } from "./scope.js";
|
|
5
|
+
import { readPayload } from "../net/token.js";
|
|
6
|
+
import { morph, ownerOf } from "../dom/morph.js";
|
|
7
|
+
import { MODEL_EVENTS, declaredTypes, eventData, listen } from "./events.js";
|
|
8
|
+
import { actionEnvelope, blockEnvelope, refreshEnvelope } from "../net/protocol.js";
|
|
9
|
+
|
|
10
|
+
const INPUT_DELAY_MS = 100;
|
|
11
|
+
|
|
12
|
+
// The data-path of each component from the view down to this one (the view has none).
|
|
13
|
+
export function pathOf(root) {
|
|
14
|
+
const path = [];
|
|
15
|
+
for (let el = root; el; el = ownerOf(el)) {
|
|
16
|
+
if (el.dataset.path) path.unshift(el.dataset.path);
|
|
17
|
+
}
|
|
18
|
+
return path;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function mountComponent(root, { module, runtime }) {
|
|
22
|
+
const scope = createScope({ module, payload: readPayload(root.dataset.snapshot) });
|
|
23
|
+
const context = { root, module, scope, runtime, timers: new WeakMap(), listened: new Set() };
|
|
24
|
+
|
|
25
|
+
effect(() => {
|
|
26
|
+
morph(root, module.render(scope.$));
|
|
27
|
+
// Deferred, so this effect does not track the children's signals.
|
|
28
|
+
queueMicrotask(() => {
|
|
29
|
+
syncChildInputs(root, runtime);
|
|
30
|
+
runtime.hooks.sync(root, { owner: root, update: true });
|
|
31
|
+
});
|
|
32
|
+
for (const type of declaredTypes(root)) listen(context, type, invokeHandler);
|
|
33
|
+
});
|
|
34
|
+
for (const type of MODEL_EVENTS) listen(context, type, invokeHandler);
|
|
35
|
+
for (const [id, deps] of Object.entries(module.blocks ?? {})) watchBlock(context, id, deps);
|
|
36
|
+
|
|
37
|
+
// A burst of input changes sends one refresh, INPUT_DELAY_MS after the last one.
|
|
38
|
+
const refreshInputs = () => exchange(context, (params) => refreshEnvelope({ ...params, inputs: scope.inputs() }));
|
|
39
|
+
let inputTimer;
|
|
40
|
+
return {
|
|
41
|
+
scope,
|
|
42
|
+
refresh: () => exchange(context, refreshEnvelope),
|
|
43
|
+
setInputs(values) {
|
|
44
|
+
if (!scope.setInputs(values)) return;
|
|
45
|
+
clearTimeout(inputTimer);
|
|
46
|
+
inputTimer = setTimeout(refreshInputs, INPUT_DELAY_MS);
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The data-inputs the parent's render writes on each direct child reach that child.
|
|
52
|
+
export function syncChildInputs(root, runtime) {
|
|
53
|
+
for (const el of root.querySelectorAll("[data-component][data-inputs]")) {
|
|
54
|
+
if (ownerOf(el) !== root) continue;
|
|
55
|
+
runtime.componentOf(el)?.setInputs(JSON.parse(el.dataset.inputs));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// An action is pending while the server answers; the answer is applied before the flag goes down.
|
|
60
|
+
export async function runAction(context, action, args) {
|
|
61
|
+
context.scope.setPending(action, true);
|
|
62
|
+
try {
|
|
63
|
+
return await exchange(context, (params) => actionEnvelope({ ...params, action, args }));
|
|
64
|
+
} finally {
|
|
65
|
+
context.scope.setPending(action, false);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// The view and the component are read when the envelope is built, so a retry sends the renewed ones.
|
|
70
|
+
// The changed values of the last envelope built are the ones the answer settles.
|
|
71
|
+
async function exchange(context, build) {
|
|
72
|
+
let sent = {};
|
|
73
|
+
const response = await context.runtime.send(() => {
|
|
74
|
+
const params = requestParams(context);
|
|
75
|
+
sent = params.changed;
|
|
76
|
+
return build(params);
|
|
77
|
+
});
|
|
78
|
+
return applyResponse(response, context, sent);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function requestParams({ root, scope, runtime }) {
|
|
82
|
+
return {
|
|
83
|
+
view: runtime.viewToken(),
|
|
84
|
+
path: pathOf(root),
|
|
85
|
+
component: root.dataset.snapshot,
|
|
86
|
+
changed: scope.changed(),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function applyResponse(response, { root, scope, runtime }, sent = {}) {
|
|
91
|
+
runtime.setViewToken(response.view);
|
|
92
|
+
if (response.component) root.dataset.snapshot = response.component;
|
|
93
|
+
scope.settle(sent);
|
|
94
|
+
scope.apply(response.states ?? {});
|
|
95
|
+
replaceBlocks(root, response.blocks ?? {}, runtime);
|
|
96
|
+
for (const { name, data } of response.events ?? []) {
|
|
97
|
+
root.dispatchEvent(new CustomEvent(name, { detail: data, bubbles: true }));
|
|
98
|
+
}
|
|
99
|
+
return response;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function replaceBlocks(root, blocks, runtime) {
|
|
103
|
+
for (const [id, html] of Object.entries(blocks)) {
|
|
104
|
+
for (const el of blocksOf(root, id)) {
|
|
105
|
+
el.innerHTML = html;
|
|
106
|
+
runtime.mount(el);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (Object.keys(blocks).length) runtime.hooks.sync(root, { owner: root, update: false });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function blocksOf(root, id) {
|
|
113
|
+
return [...root.querySelectorAll("boto-block")].filter((el) => el.dataset.block === id && ownerOf(el) === root);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A block is asked again when one of its deps changes; the first run is the render the page already has.
|
|
117
|
+
// The request waits a microtask: building it reads changed(), which must not track the effect.
|
|
118
|
+
function watchBlock(context, id, deps) {
|
|
119
|
+
const { $ } = context.scope;
|
|
120
|
+
let first = true;
|
|
121
|
+
effect(() => {
|
|
122
|
+
for (const name of deps) void $[name];
|
|
123
|
+
if (first) {
|
|
124
|
+
first = false;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
queueMicrotask(() => exchange(context, (params) => blockEnvelope({ ...params, block: id })));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function invokeHandler(context, el, handlerId, ev) {
|
|
132
|
+
const { $ } = context.scope;
|
|
133
|
+
const handler = context.module.handlers[handlerId];
|
|
134
|
+
const event = eventData(ev);
|
|
135
|
+
const locals = JSON.parse(el.dataset.locals ?? "{}");
|
|
136
|
+
if (handler.assign) return batch(() => handler.assign($, event, locals));
|
|
137
|
+
return runAction(context, handler.action, handler.args($, event, locals));
|
|
138
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
|
|
2
|
+
import { matchesKey, parseOn } from "./on.js";
|
|
3
|
+
import { ownerOf } from "../dom/morph.js";
|
|
4
|
+
|
|
5
|
+
export const MODEL_EVENTS = ["input", "change"];
|
|
6
|
+
|
|
7
|
+
export function declaredTypes(root) {
|
|
8
|
+
return [...root.querySelectorAll("[data-on]")].flatMap((el) => parseOn(el.dataset.on).map((entry) => entry.type));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function listen(context, type, invoke) {
|
|
12
|
+
if (context.listened.has(type)) return;
|
|
13
|
+
context.listened.add(type);
|
|
14
|
+
context.root.addEventListener(type, (ev) => {
|
|
15
|
+
if (MODEL_EVENTS.includes(type)) assignModel(context, ev);
|
|
16
|
+
dispatch(context, ev, invoke);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function assignModel({ root, scope }, ev) {
|
|
21
|
+
const el = ev.target.closest("[data-model]");
|
|
22
|
+
if (!el || ownerOf(el) !== root) return;
|
|
23
|
+
scope.setModel(el.dataset.model, el.type === "checkbox" ? el.checked : el.value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Delegation: the element with data-on belongs to the component around it, so a child's inner
|
|
27
|
+
// elements are left to the child's own listener.
|
|
28
|
+
function dispatch(context, ev, invoke) {
|
|
29
|
+
for (let el = ev.target; el && el !== context.root; el = el.parentElement) {
|
|
30
|
+
if (!el.dataset.on || ownerOf(el) !== context.root) continue;
|
|
31
|
+
for (const entry of parseOn(el.dataset.on)) {
|
|
32
|
+
if (entry.type === ev.type && matchesKey(entry.modifiers, ev.key)) run(context, el, entry, ev, invoke);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function run(context, el, entry, ev, invoke) {
|
|
38
|
+
const { prevent, stop, debounce } = entry.modifiers;
|
|
39
|
+
if (prevent) ev.preventDefault();
|
|
40
|
+
if (stop) ev.stopPropagation();
|
|
41
|
+
debounced(context, el, debounce, () => invoke(context, el, entry.handler, ev));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function debounced({ timers }, el, ms, fn) {
|
|
45
|
+
if (ms === undefined) return fn();
|
|
46
|
+
clearTimeout(timers.get(el));
|
|
47
|
+
timers.set(el, setTimeout(fn, ms));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// A child's emit arrives as a CustomEvent whose detail is the data; a DOM event gives its target's fields.
|
|
51
|
+
export function eventData(ev) {
|
|
52
|
+
if (ev instanceof CustomEvent) return ev.detail;
|
|
53
|
+
return { value: ev.target.value, checked: ev.target.checked, key: ev.key };
|
|
54
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Binds each data-hook element to the project's module at boto-web/hooks/<name>.js and calls its mounted, updated and removed.
|
|
2
|
+
|
|
3
|
+
import { ownerOf } from "../dom/morph.js";
|
|
4
|
+
|
|
5
|
+
const NAME = /^[a-z0-9_-]+$/;
|
|
6
|
+
export const hookUrl = (name, moduleUrl = import.meta.url) => new URL(`../hooks/${name}.js`, moduleUrl).href;
|
|
7
|
+
const defaultLoad = (name) => import(hookUrl(name));
|
|
8
|
+
|
|
9
|
+
// The name is in the path of the import, so anything else is refused before it gets there.
|
|
10
|
+
export function hookName(el) {
|
|
11
|
+
const name = el.dataset.hook;
|
|
12
|
+
if (name === undefined) return null;
|
|
13
|
+
if (NAME.test(name)) return name;
|
|
14
|
+
console.warn(`boto-web: hook "${name}" ignored, the name must match [a-z0-9_-]+`);
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// The connected hook elements whose nearest component is owner (null for the page).
|
|
19
|
+
export function hooksOwnedBy(root, owner) {
|
|
20
|
+
return [...root.querySelectorAll("[data-hook]")].filter(
|
|
21
|
+
(el) => el.isConnected && ownerOf(el) === owner && hookName(el) !== null,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function diffHooks(before, after) {
|
|
26
|
+
const was = new Set(before);
|
|
27
|
+
const now = new Set(after);
|
|
28
|
+
return {
|
|
29
|
+
mounted: after.filter((el) => !was.has(el)),
|
|
30
|
+
updated: after.filter((el) => was.has(el)),
|
|
31
|
+
removed: before.filter((el) => !now.has(el)),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createHooks({ load = defaultLoad } = {}) {
|
|
36
|
+
const modules = new Map(); // name -> the module's promise, so each module loads once
|
|
37
|
+
const live = new Map(); // element -> name, for the hooks mounted and not removed yet
|
|
38
|
+
|
|
39
|
+
const moduleFor = (name) => {
|
|
40
|
+
if (!modules.has(name)) {
|
|
41
|
+
const pending = load(name);
|
|
42
|
+
modules.set(name, pending);
|
|
43
|
+
pending.catch(() => modules.delete(name)); // a failed load is tried again on the next sync
|
|
44
|
+
}
|
|
45
|
+
return modules.get(name);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// Bookkeeping runs before the first await, so each sync sees the state of its own call.
|
|
49
|
+
// updated runs only after a morph of the owner; a mount or a block swap passes update: false.
|
|
50
|
+
async function sync(root, { owner, update }) {
|
|
51
|
+
const before = [...live.keys()].filter((el) => !el.isConnected || ownerOf(el) === owner);
|
|
52
|
+
const { mounted, updated, removed } = diffHooks(before, hooksOwnedBy(root, owner));
|
|
53
|
+
const calls = [];
|
|
54
|
+
for (const el of removed) {
|
|
55
|
+
calls.push([live.get(el), "removed", el]);
|
|
56
|
+
live.delete(el);
|
|
57
|
+
}
|
|
58
|
+
for (const el of mounted) calls.push(bind(el));
|
|
59
|
+
for (const el of updated) {
|
|
60
|
+
const name = hookName(el);
|
|
61
|
+
if (name !== live.get(el)) {
|
|
62
|
+
calls.push([live.get(el), "removed", el], bind(el));
|
|
63
|
+
} else if (update) {
|
|
64
|
+
calls.push([name, "updated", el]);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const [name, method, el] of calls) await call(name, method, el);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function bind(el) {
|
|
71
|
+
const name = hookName(el);
|
|
72
|
+
live.set(el, name);
|
|
73
|
+
return [name, "mounted", el];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function call(name, method, el) {
|
|
77
|
+
const module = await moduleFor(name);
|
|
78
|
+
await module[method]?.(el);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return { sync };
|
|
82
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
|
|
2
|
+
export function liveRefresh(transport, viewSnapshot, onRefresh, { delay = 100 } = {}) {
|
|
3
|
+
let timer = null;
|
|
4
|
+
const unsubscribe = transport.subscribe(viewSnapshot, () => {
|
|
5
|
+
clearTimeout(timer);
|
|
6
|
+
timer = setTimeout(onRefresh, delay);
|
|
7
|
+
});
|
|
8
|
+
return () => {
|
|
9
|
+
clearTimeout(timer);
|
|
10
|
+
unsubscribe();
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
|
|
2
|
+
const DEFAULT_DEBOUNCE = 300;
|
|
3
|
+
const DIGITS = /^\d+$/;
|
|
4
|
+
const KEY_NAMES = { enter: "Enter", esc: "Escape" };
|
|
5
|
+
|
|
6
|
+
export function parseOn(text) {
|
|
7
|
+
return text.trim().split(/\s+/).map(parseEntry);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function parseEntry(token) {
|
|
11
|
+
const [head, handler] = token.split(":");
|
|
12
|
+
if (!handler) throw new TypeError(`invalid data-on entry: ${token}`);
|
|
13
|
+
|
|
14
|
+
const [type, ...parts] = head.split(".");
|
|
15
|
+
return { type, handler, modifiers: modifiersOf(parts) };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function modifiersOf(parts) {
|
|
19
|
+
const modifiers = { prevent: false, stop: false, keys: [], debounce: undefined };
|
|
20
|
+
for (let i = 0; i < parts.length; i++) {
|
|
21
|
+
const part = parts[i];
|
|
22
|
+
if (part === "prevent" || part === "stop") {
|
|
23
|
+
modifiers[part] = true;
|
|
24
|
+
} else if (part === "debounce") {
|
|
25
|
+
// shortcut: a bare debounce waits 300 ms; a number after it is the wait in ms
|
|
26
|
+
modifiers.debounce = DIGITS.test(parts[i + 1] ?? "") ? Number(parts[++i]) : DEFAULT_DEBOUNCE;
|
|
27
|
+
} else {
|
|
28
|
+
modifiers.keys.push(part);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return modifiers;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function matchesKey({ keys }, key) {
|
|
35
|
+
return keys.length === 0 || keys.some((name) => (KEY_NAMES[name] ?? name) === key);
|
|
36
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Mounts the views and components of the page and keeps the view's snapshot; sends envelopes through the transport.
|
|
2
|
+
|
|
3
|
+
import { mountComponent, pathOf } from "./component.js";
|
|
4
|
+
import { createHooks } from "./hooks.js";
|
|
5
|
+
import { liveRefresh } from "./live.js";
|
|
6
|
+
import { ProtocolError } from "../net/protocol.js";
|
|
7
|
+
|
|
8
|
+
// The components sit next to the runtime, so the URL is resolved from its module (wherever the app is mounted).
|
|
9
|
+
export const componentUrl = (name, moduleUrl = import.meta.url) =>
|
|
10
|
+
new URL(`../components/${name.replaceAll("::", "--")}.js`, moduleUrl).href;
|
|
11
|
+
const isExpired = (error) => error instanceof ProtocolError && error.reason === "expired";
|
|
12
|
+
|
|
13
|
+
// The snapshots of a freshly rendered page: the view's (under the key of an empty path) and each component's.
|
|
14
|
+
export async function fetchPageSnapshots(url = globalThis.location.href) {
|
|
15
|
+
const html = await (await globalThis.fetch(url)).text();
|
|
16
|
+
const doc = new globalThis.DOMParser().parseFromString(html, "text/html");
|
|
17
|
+
const components = {};
|
|
18
|
+
for (const el of doc.querySelectorAll("[data-component]")) {
|
|
19
|
+
components[JSON.stringify(pathOf(el))] = el.dataset.snapshot;
|
|
20
|
+
}
|
|
21
|
+
return { view: components["[]"], components };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createRuntime({
|
|
25
|
+
transport,
|
|
26
|
+
importModule = (url) => import(url),
|
|
27
|
+
fetchSnapshots = fetchPageSnapshots,
|
|
28
|
+
hooks = createHooks(),
|
|
29
|
+
}) {
|
|
30
|
+
let viewToken = null;
|
|
31
|
+
const mounted = new WeakSet();
|
|
32
|
+
const roots = new Set();
|
|
33
|
+
const components = new WeakMap();
|
|
34
|
+
const stops = new Map();
|
|
35
|
+
|
|
36
|
+
// An expired snapshot: the page is fetched again and each mounted component takes its new snapshot.
|
|
37
|
+
async function renew() {
|
|
38
|
+
const fresh = await fetchSnapshots();
|
|
39
|
+
viewToken = fresh.view;
|
|
40
|
+
for (const root of roots) {
|
|
41
|
+
const snapshot = fresh.components[JSON.stringify(pathOf(root))];
|
|
42
|
+
if (snapshot) root.dataset.snapshot = snapshot;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const runtime = {
|
|
47
|
+
hooks,
|
|
48
|
+
viewToken: () => viewToken,
|
|
49
|
+
componentOf: (el) => components.get(el),
|
|
50
|
+
setViewToken(token) {
|
|
51
|
+
viewToken = token;
|
|
52
|
+
},
|
|
53
|
+
// build() runs on each try, so the retry reads the renewed snapshots; a second expiry propagates.
|
|
54
|
+
async send(build) {
|
|
55
|
+
try {
|
|
56
|
+
return await transport.send(build());
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!isExpired(error)) throw error;
|
|
59
|
+
await renew();
|
|
60
|
+
return transport.send(build());
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
// Drops the removed roots and stops their live refresh.
|
|
64
|
+
sweep() {
|
|
65
|
+
for (const root of roots) {
|
|
66
|
+
if (root.isConnected) continue;
|
|
67
|
+
roots.delete(root);
|
|
68
|
+
stops.get(root)?.();
|
|
69
|
+
stops.delete(root);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
async start(doc) {
|
|
73
|
+
runtime.sweep();
|
|
74
|
+
const view = doc.querySelector("boto-view[data-component]");
|
|
75
|
+
if (view) {
|
|
76
|
+
viewToken = view.dataset.snapshot;
|
|
77
|
+
await runtime.mount(view);
|
|
78
|
+
}
|
|
79
|
+
// The page's own hooks; the components' hooks are synced by each component's morph.
|
|
80
|
+
await hooks.sync(doc, { owner: null, update: false });
|
|
81
|
+
},
|
|
82
|
+
// Mounts the components under el (el included) that are not mounted yet, outside in.
|
|
83
|
+
async mount(el) {
|
|
84
|
+
const nodes = [...el.querySelectorAll("[data-component]")];
|
|
85
|
+
if (el.hasAttribute("data-component")) nodes.unshift(el);
|
|
86
|
+
for (const node of nodes) {
|
|
87
|
+
if (mounted.has(node)) continue;
|
|
88
|
+
mounted.add(node);
|
|
89
|
+
const module = await importModule(componentUrl(node.dataset.component));
|
|
90
|
+
const component = mountComponent(node, { module, runtime });
|
|
91
|
+
roots.add(node);
|
|
92
|
+
components.set(node, component);
|
|
93
|
+
if (module.live && node.localName === "boto-view") {
|
|
94
|
+
stops.set(node, liveRefresh(transport, runtime.viewToken(), component.refresh));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
return runtime;
|
|
100
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
|
|
2
|
+
import { signal, computed, batch } from "./signals.js";
|
|
3
|
+
import { hydrate, dehydrate } from "../template/hydrate.js";
|
|
4
|
+
import { D } from "../template/decimal.js";
|
|
5
|
+
|
|
6
|
+
// Text the type cannot read (say "1,5" as a decimal) gives undefined, and the assignment is skipped.
|
|
7
|
+
const READERS = {
|
|
8
|
+
integer: (raw) => (/^-?\d+$/.test(raw) ? Number(raw) : undefined),
|
|
9
|
+
decimal: (raw) => {
|
|
10
|
+
try {
|
|
11
|
+
return D.from(raw);
|
|
12
|
+
} catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const sameJson = (type, value, json) => JSON.stringify(dehydrate(type, value)) === JSON.stringify(json);
|
|
19
|
+
|
|
20
|
+
function modelValue(type, raw) {
|
|
21
|
+
if (type === "boolean") return raw;
|
|
22
|
+
if (raw === "") return null;
|
|
23
|
+
const read = READERS[type];
|
|
24
|
+
return read ? read(raw) : raw;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createScope({ module, payload }) {
|
|
28
|
+
const types = module.types ?? {};
|
|
29
|
+
const states = new Map();
|
|
30
|
+
const inputs = new Map();
|
|
31
|
+
const changed = new Set();
|
|
32
|
+
const pending = new Map();
|
|
33
|
+
const $ = {};
|
|
34
|
+
|
|
35
|
+
const pendingOf = (name) => {
|
|
36
|
+
if (!pending.has(name)) pending.set(name, signal(false));
|
|
37
|
+
return pending.get(name);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
for (const [name, json] of Object.entries(payload.s ?? {})) {
|
|
41
|
+
const cell = signal(hydrate(types[name], json));
|
|
42
|
+
states.set(name, cell);
|
|
43
|
+
Object.defineProperty($, name, {
|
|
44
|
+
enumerable: true,
|
|
45
|
+
get: () => cell.value,
|
|
46
|
+
set: (value) => {
|
|
47
|
+
cell.value = value;
|
|
48
|
+
changed.add(name);
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const [name, json] of Object.entries(payload.i ?? {})) {
|
|
54
|
+
const cell = signal(hydrate(types[name], json));
|
|
55
|
+
inputs.set(name, cell);
|
|
56
|
+
Object.defineProperty($, name, { enumerable: true, get: () => cell.value });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
for (const [name, fn] of Object.entries(module.computeds ?? {})) {
|
|
60
|
+
const cell = computed(() => fn($));
|
|
61
|
+
Object.defineProperty($, name, { enumerable: true, get: () => cell.value });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
$.$pending = (name) => pendingOf(name).value;
|
|
65
|
+
|
|
66
|
+
const dehydrated = (name) => dehydrate(types[name], states.get(name).value);
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
$,
|
|
70
|
+
changed() {
|
|
71
|
+
return Object.fromEntries([...changed].map((name) => [name, dehydrated(name)]));
|
|
72
|
+
},
|
|
73
|
+
// After an answer: a name leaves changed only if it still holds the value that was sent; typing during the action stays.
|
|
74
|
+
settle(sent) {
|
|
75
|
+
for (const [name, value] of Object.entries(sent)) {
|
|
76
|
+
if (changed.has(name) && JSON.stringify(dehydrated(name)) === JSON.stringify(value)) changed.delete(name);
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
// The server's states: a value equal to the current one is skipped, so a block refresh cannot loop.
|
|
80
|
+
apply(values) {
|
|
81
|
+
batch(() => {
|
|
82
|
+
for (const [name, json] of Object.entries(values)) {
|
|
83
|
+
const cell = states.get(name);
|
|
84
|
+
if (cell && !sameJson(types[name], cell.value, json)) cell.value = hydrate(types[name], json);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
setInputs(values) {
|
|
89
|
+
let changed = false;
|
|
90
|
+
batch(() => {
|
|
91
|
+
for (const [name, json] of Object.entries(values)) {
|
|
92
|
+
const cell = inputs.get(name);
|
|
93
|
+
if (cell && !sameJson(types[name], cell.value, json)) {
|
|
94
|
+
cell.value = hydrate(types[name], json);
|
|
95
|
+
changed = true;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
return changed;
|
|
100
|
+
},
|
|
101
|
+
inputs() {
|
|
102
|
+
return Object.fromEntries([...inputs].map(([name, cell]) => [name, dehydrate(types[name], cell.value)]));
|
|
103
|
+
},
|
|
104
|
+
setModel(name, raw) {
|
|
105
|
+
const value = modelValue(types[name], raw);
|
|
106
|
+
if (value !== undefined) $[name] = value;
|
|
107
|
+
},
|
|
108
|
+
setPending(name, on) {
|
|
109
|
+
pendingOf(name).value = on;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|