brumate 0.3.0 → 0.4.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.
Files changed (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-DLlRmD9z.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BvDsC6Qr.js +3463 -0
  7. package/dist/client-BvDsC6Qr.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-DBwL2wKQ.d.ts} +390 -181
  9. package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
  10. package/dist/client-routes-BtGpYCef.js.map +1 -0
  11. package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-BbD7JQhj.js → defer-CKWZLv2K.js} +4 -4
  14. package/dist/defer-CKWZLv2K.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-4uTPwR_v.js} +56 -82
  16. package/dist/devtools-4uTPwR_v.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-Be9pxYgv.js} +397 -333
  18. package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
  19. package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
  20. package/dist/events-LgLdp1R7.js.map +1 -0
  21. package/dist/features-CHY5Ekku.js +30 -0
  22. package/dist/features-CHY5Ekku.js.map +1 -0
  23. package/dist/files-WW4RlajL.js +506 -0
  24. package/dist/files-WW4RlajL.js.map +1 -0
  25. package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
  26. package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.js +31 -22
  29. package/dist/highlight.js.map +1 -1
  30. package/dist/{html-mNTKzaDD.js → html-BtKRyi7g.js} +86 -22
  31. package/dist/html-BtKRyi7g.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Bw9Qwu6F.d.ts} +20 -5
  33. package/dist/index.d.ts +96 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-Y6y4uNZp.js} +3751 -676
  37. package/dist/inspect-Y6y4uNZp.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-BjKGJzLN.js} +20 -14
  39. package/dist/loader-BjKGJzLN.js.map +1 -0
  40. package/dist/logo-DQ_OYhBi.js +10 -0
  41. package/dist/logo-DQ_OYhBi.js.map +1 -0
  42. package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
  43. package/dist/navigate-CfOr-TRF.js.map +1 -0
  44. package/dist/nesting-DA5vJw9X.js +265 -0
  45. package/dist/nesting-DA5vJw9X.js.map +1 -0
  46. package/dist/{produce-Doc91GkX.js → produce-B7X9ori9.js} +137 -9
  47. package/dist/produce-B7X9ori9.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-DIgHBVwL.d.ts} +39 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-Q-XkLwFh.js} +11 -6
  50. package/dist/rpc-Q-XkLwFh.js.map +1 -0
  51. package/dist/runtime/batch.js +9 -7
  52. package/dist/runtime/batch.js.map +1 -1
  53. package/dist/runtime/client.d.ts +4 -4
  54. package/dist/runtime/client.js +4 -4
  55. package/dist/runtime/devtools.d.ts +11 -29
  56. package/dist/runtime/devtools.js +3 -1
  57. package/dist/runtime/env.js +14 -2
  58. package/dist/runtime/env.js.map +1 -1
  59. package/dist/runtime/events.d.ts +23 -1
  60. package/dist/runtime/events.js +1 -1
  61. package/dist/runtime/forms.d.ts +2 -2
  62. package/dist/runtime/forms.js +1 -1
  63. package/dist/runtime/hot.d.ts +1 -1
  64. package/dist/runtime/hot.js +5 -2
  65. package/dist/runtime/hot.js.map +1 -1
  66. package/dist/runtime/html.d.ts +2 -2
  67. package/dist/runtime/html.js +1 -1
  68. package/dist/runtime/loader.d.ts +2 -2
  69. package/dist/runtime/loader.js +2 -2
  70. package/dist/runtime/routes.js +4 -1
  71. package/dist/runtime/routes.js.map +1 -1
  72. package/dist/runtime/server.d.ts +5 -5
  73. package/dist/runtime/server.js +5 -5
  74. package/dist/runtime/signals.d.ts +38 -1
  75. package/dist/runtime/signals.js +33 -1
  76. package/dist/runtime/signals.js.map +1 -1
  77. package/dist/runtime/static-loader.d.ts +2 -2
  78. package/dist/runtime/static-loader.js +1 -1
  79. package/dist/runtime/testing.d.ts +18 -3
  80. package/dist/runtime/testing.js +150 -33
  81. package/dist/runtime/testing.js.map +1 -1
  82. package/dist/{server-DuFYRXrd.d.ts → server-BvPIg9pT.d.ts} +84 -22
  83. package/dist/{server-CxVDYE_V.js → server-DjyOVJtJ.js} +598 -164
  84. package/dist/server-DjyOVJtJ.js.map +1 -0
  85. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
  86. package/dist/{static-loader-nZssh66R.js → static-loader-BZR17hSw.js} +78 -99
  87. package/dist/static-loader-BZR17hSw.js.map +1 -0
  88. package/dist/{stream-DCYZO4IF.js → stream-BP5AVmg5.js} +102 -16
  89. package/dist/stream-BP5AVmg5.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1890 -548
  92. package/dist/vite.js.map +1 -1
  93. package/elements.d.ts +951 -0
  94. package/forms/forms.brm.ts +3 -3
  95. package/package.json +12 -3
  96. package/skills/brumate/SKILL.md +58 -0
  97. package/skills/brumate/references/errors.md +2078 -0
  98. package/skills/brumate/references/events.md +117 -0
  99. package/skills/brumate/references/signals.md +61 -0
  100. package/skills/brumate/references/state.md +235 -0
  101. package/skills/brumate/references/syntax.md +250 -0
  102. package/types.d.ts +4 -4
  103. package/dist/client-BD6XT-s5.js +0 -1968
  104. package/dist/client-BD6XT-s5.js.map +0 -1
  105. package/dist/client-routes-JTbGtukf.js.map +0 -1
  106. package/dist/cookies-BzllthiF.js.map +0 -1
  107. package/dist/defer-BbD7JQhj.js.map +0 -1
  108. package/dist/devtools-CQgD7NPB.js.map +0 -1
  109. package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
  110. package/dist/events-CSs7OwIC.js.map +0 -1
  111. package/dist/files-BXSSrQgc.js +0 -205
  112. package/dist/files-BXSSrQgc.js.map +0 -1
  113. package/dist/forms-Bg-CwGqX.js.map +0 -1
  114. package/dist/html-mNTKzaDD.js.map +0 -1
  115. package/dist/inspect-BHpOw1LF.js.map +0 -1
  116. package/dist/loader-Dos_3NP0.js.map +0 -1
  117. package/dist/navigate-O78d_zGN.js.map +0 -1
  118. package/dist/produce-Doc91GkX.js.map +0 -1
  119. package/dist/rpc-ygMRPmN4.js.map +0 -1
  120. package/dist/server-CxVDYE_V.js.map +0 -1
  121. package/dist/static-loader-nZssh66R.js.map +0 -1
  122. package/dist/stream-DCYZO4IF.js.map +0 -1
@@ -1,1968 +0,0 @@
1
- import { a as attributeText, b as textValue, d as handlerEntry, f as insertValue, n as actionAttributes, o as bindEntry, t as VOID_ELEMENTS, v as spread$1 } from "./html-mNTKzaDD.js";
2
- import { a as SlotReference, c as isSlotReference, d as parseId, f as stateValues, i as FunctionReference, m as useSerialEntry, n as Binding, o as isAsyncIterable, r as ElementReference, s as isBinding } from "./produce-Doc91GkX.js";
3
- import { n as ROUTE_KEY } from "./context-CTiSzQRc.js";
4
- import { n as trustedHTML, t as loadOnce } from "./skew-FRmAy9iy.js";
5
- //#region src/runtime/client.ts
6
- /** The part that holds an export: `h<n>` and `c<n>` have their own, the rest are in `update`. */
7
- function partOf(name) {
8
- return /^[hct]\d/.test(name) ? name : "update";
9
- }
10
- let options;
11
- /** The URL prefix of server function calls, from the options. */
12
- let rpcPrefix = "/_brumate";
13
- /** The ID of the build of the page, from the loader. Undefined on the dev server. */
14
- let build;
15
- /**
16
- * Tells the page that the site changed since it loaded: a call answered 409
17
- * with another build, or the code of a handler is gone. The loader then
18
- * loads the next page in full, and an app can save a draft first.
19
- */
20
- function skew(reason) {
21
- document.dispatchEvent(new CustomEvent("brumate:skew", { detail: reason }));
22
- }
23
- /** The scopes of the page, by ID. */
24
- const scopes = /* @__PURE__ */ new Map();
25
- /** What modules of optional features add to the core. See `client-routes.ts` and `hot`. */
26
- const hooks = {};
27
- /** The global key of the devtools hooks. */
28
- const DEVTOOLS = Symbol.for("brumate.devtools");
29
- /**
30
- * True on the dev server, which has the devtools. A Vite build replaces it
31
- * with `false`, so the calls of the devtools hooks are left out. Without
32
- * Vite, `import.meta.env` is undefined, and the hooks are off.
33
- */
34
- const DEV = import.meta.env?.DEV;
35
- function devtools() {
36
- return globalThis[DEVTOOLS];
37
- }
38
- const modules = /* @__PURE__ */ new Map();
39
- const loading = /* @__PURE__ */ new Map();
40
- const parts = /* @__PURE__ */ new Map();
41
- const loadedParts = /* @__PURE__ */ new Map();
42
- const comments = /* @__PURE__ */ new Map();
43
- const elements = /* @__PURE__ */ new Map();
44
- let nextId = -1;
45
- const refs = /* @__PURE__ */ new Map();
46
- /**
47
- * The records that ran before the core started, or while it stopped. Each
48
- * state script hands its record to `push`, which the core replaces while it
49
- * runs, so it reads later records at once.
50
- */
51
- function stateQueue() {
52
- const global = globalThis;
53
- return global.$brm ??= [];
54
- }
55
- /** Reads the records that later state scripts hand over. Set while the core runs. */
56
- function pushRecords(...added) {
57
- for (const record of added) readRecord(record);
58
- return 0;
59
- }
60
- /**
61
- * Reads a state record. The first record holds the page state, and later
62
- * records settle the promises in it.
63
- */
64
- function readRecord([script, code]) {
65
- if (!script?.isConnected) return;
66
- const root = script.getAttribute("b-root") ?? "0";
67
- if (!refs.has(root)) refs.set(root, []);
68
- const decoded = code(refs.get(root), stateValues);
69
- if (script.hasAttribute("b-scopes")) {
70
- const unpacked = unpackState(decoded);
71
- const added = addScopes(hooks.record ? hooks.record(script, unpacked) : unpacked, root);
72
- if (writes > 0) refresh(added);
73
- }
74
- }
75
- /**
76
- * Updates scopes that the server rendered before values changed on the
77
- * client, such as the body of a `#loading` block that streams in after an
78
- * event. Effects do not run: they run only when a value changes. With
79
- * `memosOnly`, as for scopes that the client just rendered with its values,
80
- * only the memos run, so the ones that load start.
81
- */
82
- function refresh(added, memosOnly = false) {
83
- const byModule = /* @__PURE__ */ new Map();
84
- for (const scope of added) {
85
- const id = rootOf(scope).m;
86
- if (!id) continue;
87
- const list = byModule.get(id);
88
- if (list) list.push(scope);
89
- else byModule.set(id, [scope]);
90
- }
91
- for (const [id, list] of byModule) loadModule(id, "state").then(async (module) => {
92
- const byKind = /* @__PURE__ */ new Map();
93
- for (const scope of list) if (!byKind.has(scope.k)) byKind.set(scope.k, refreshNames(module, scope.k, memosOnly));
94
- let any = false;
95
- for (const names of byKind.values()) any ||= names.length > 0;
96
- if (!any) return;
97
- const updates = await loadPart(module, "update", "state");
98
- for (const scope of list) for (const name of byKind.get(scope.k)) if (scopes.has(scope.id)) updates[name](scope);
99
- });
100
- }
101
- /** The names of the updates of a kind of scope that `refresh` runs, memos first. */
102
- function refreshNames(module, kind, memosOnly) {
103
- const memos = /* @__PURE__ */ new Set();
104
- const others = /* @__PURE__ */ new Set();
105
- for (const slots of Object.values(module.g)) for (const entries of Object.values(slots)) for (const [entryKind, name] of entries) {
106
- if (entryKind !== kind || name[0] === "e") continue;
107
- if (name[0] === "m") memos.add(name);
108
- else if (!memosOnly) others.add(name);
109
- }
110
- return [...memos, ...others];
111
- }
112
- /** Reads the groups of scope records back into one record per scope. See `PackedState`. */
113
- function unpackState(state) {
114
- const taken = [];
115
- for (const group of state.g ?? []) {
116
- const [k, base, flags] = group;
117
- const count = group[3];
118
- let at = 4;
119
- const m = flags & 16 ? group[at++] : void 0;
120
- const source = flags & 32 ? [] : void 0;
121
- if (source) taken.push([
122
- source,
123
- group[at++],
124
- group[at++],
125
- flags & 1
126
- ]);
127
- const prefix = flags & 64 ? group[at++] : "";
128
- const id = (n) => prefix ? prefix + n : n;
129
- const skip = source && flags & 1 ? 1 : 0;
130
- let n = flags & 72 ? 0 : base;
131
- while (at < group.length) {
132
- n += group[at++];
133
- const s = group.slice(at - skip, at += count - skip);
134
- const record = flags & 8 ? {
135
- k,
136
- o: id(n - base)
137
- } : {
138
- k,
139
- p: base
140
- };
141
- record.s = s;
142
- if (m !== void 0) record.m = m;
143
- if (source) source.push(record);
144
- else if (flags & 1) record.i = s[0];
145
- else if (flags & 2) record.i = group[at++];
146
- if (flags & 4) record.c = group[at++];
147
- state[id(n)] = record;
148
- }
149
- }
150
- delete state.g;
151
- for (const [records, source, slot, first] of taken) {
152
- const values = Array.from(state[source].s[slot]);
153
- for (let n = 0; n < records.length; n++) {
154
- const record = records[n];
155
- record.i = values[n];
156
- if (first) record.s[0] = values[n];
157
- }
158
- }
159
- return state;
160
- }
161
- function addScopes(state, root) {
162
- const added = [];
163
- for (const [key, record] of Object.entries(state)) {
164
- const id = parseId(key);
165
- const scope = {
166
- id,
167
- k: record.k ?? 0,
168
- m: record.m,
169
- s: record.s ?? [],
170
- i: record.i,
171
- c: record.c,
172
- v: record.v,
173
- x: record.x,
174
- b: record.b,
175
- children: /* @__PURE__ */ new Set(),
176
- r: root
177
- };
178
- scopes.set(id, scope);
179
- added.push(scope);
180
- }
181
- for (const scope of added) {
182
- const record = state[scope.id];
183
- if (record.p !== void 0) {
184
- scope.p = scopes.get(record.p);
185
- scope.p?.children.add(scope);
186
- treeChanges++;
187
- }
188
- if (record.o !== void 0) scope.o = scopes.get(record.o);
189
- if (record.t !== void 0) scope.t = scopes.get(record.t);
190
- }
191
- const seen = /* @__PURE__ */ new Set();
192
- for (const scope of added) {
193
- for (const key of Object.keys(scope.v ?? {})) scope.v[key] = callable(scope.v[key], seen);
194
- for (let i = 0; i < scope.s.length; i++) {
195
- const value = callable(scope.s[i], seen);
196
- scope.s[i] = value;
197
- if (value instanceof Promise) value.then((result) => {
198
- settled.set(value, result);
199
- if (scope.s[i] === value) set(scope, i, result);
200
- });
201
- }
202
- }
203
- hooks.added?.(added);
204
- return added;
205
- }
206
- /**
207
- * Indexes the markers of markup that others insert, such as streamed
208
- * `#loading` bodies and the pages that navigation adds, so `findComment` can
209
- * take its records at once.
210
- */
211
- let markerObserver;
212
- /** Stops reading state records and markers that arrive later. Later records wait for `init`. */
213
- function dispose() {
214
- const queue = stateQueue();
215
- if (queue.push === pushRecords) delete queue.push;
216
- markerObserver?.disconnect();
217
- markerObserver = void 0;
218
- }
219
- /**
220
- * Stops reading, before client navigation replaces only some routes. The
221
- * server renders the new routes with its current values, so only the writes
222
- * that come after count for the records that stream in later.
223
- */
224
- function leaveRoutes() {
225
- dispose();
226
- writes = 0;
227
- }
228
- /**
229
- * Removes the scopes of a render, by its `b-root`, with the scopes inside
230
- * them. Their cleanups run, and their memos no longer load. Its markup
231
- * stays. `brumate/testing` calls it when a mounted component unmounts.
232
- */
233
- function removeRoot(root) {
234
- const inside = (scope) => {
235
- for (let current = scope; current; current = current.p ?? current.o) if (current.r === root) return true;
236
- return false;
237
- };
238
- for (const scope of scopes.values()) if (inside(scope)) removeScope(scope);
239
- refs.delete(root);
240
- for (const cache of [comments, elements]) for (const [key, node] of cache) if (!node.isConnected) cache.delete(key);
241
- }
242
- /**
243
- * Forgets the code of components that changed on the dev server, so the next
244
- * event or update loads the new code. Their state stays. `brumate/hot` calls it.
245
- */
246
- function forget(ids) {
247
- for (const id of ids) {
248
- modules.delete(id);
249
- loading.delete(id);
250
- for (const key of parts.keys()) if (key.startsWith(`${id}:`)) {
251
- parts.delete(key);
252
- loadedParts.delete(key);
253
- }
254
- }
255
- }
256
- /** The values of the signals of components whose markup changed, for when the page renders again. */
257
- const remounts = /* @__PURE__ */ new Map();
258
- /**
259
- * Keeps the values of the signals of each instance of a component, by
260
- * name, before the page renders again with its new markup. `brumate/hot` calls it.
261
- */
262
- function remount(detail) {
263
- hooks.added = restoreRemounts;
264
- for (const { id, before, after, signals } of detail) {
265
- const names = new Set(signals);
266
- const instances = [...scopes.values()].filter((scope) => scope.m === id);
267
- remounts.set(id, {
268
- after,
269
- values: instances.map((root) => {
270
- const values = {};
271
- (before[root.k] ?? []).forEach((name, slot) => {
272
- if (names.has(name)) values[name] = root.s[slot];
273
- });
274
- return values;
275
- })
276
- });
277
- }
278
- }
279
- /** Writes back the values of signals that `onRemount` kept, into the instances of the new page. */
280
- function restoreRemounts(added) {
281
- for (const [id, { after, values }] of remounts) {
282
- const instances = added.filter((scope) => scope.m === id);
283
- if (instances.length === 0) continue;
284
- remounts.delete(id);
285
- instances.forEach((root, index) => {
286
- const saved = values[index];
287
- (after[root.k] ?? []).forEach((name, slot) => {
288
- if (saved && name in saved) set(root, slot, saved[name]);
289
- });
290
- });
291
- }
292
- }
293
- /**
294
- * Forgets the page, before another page replaces it. Cleanups run. Loaded
295
- * modules and parts stay, so the next page does not load them again. Only
296
- * client navigation calls it.
297
- */
298
- function leavePage() {
299
- dispose();
300
- for (const scope of scopes.values()) for (const cleanup of scope.cleanups?.values() ?? []) cleanup();
301
- scopes.clear();
302
- comments.clear();
303
- elements.clear();
304
- unindexed.length = 0;
305
- rendered.length = 0;
306
- pendingEffects.clear();
307
- hiding = void 0;
308
- loads.clear();
309
- loadingSlots.clear();
310
- for (const memoController of memoControllers.values()) memoController.abort();
311
- memoControllers.clear();
312
- renderedLoads.clear();
313
- for (const { timer } of timers.values()) clearTimeout(timer);
314
- timers.clear();
315
- guesses?.map.clear();
316
- nextId = -1;
317
- refs.clear();
318
- writes = 0;
319
- calling = 0;
320
- callEpoch++;
321
- lastHandler = Promise.resolve();
322
- }
323
- /** Reads the page state. The loader calls it once, before the first handler. */
324
- function init(value) {
325
- options = value;
326
- if (value.serial) useSerialEntry(value.serial);
327
- rpcPrefix = value.rpc ?? "/_brumate";
328
- build = value.build;
329
- const queue = stateQueue();
330
- queue.push = pushRecords;
331
- for (const record of queue.splice(0)) readRecord(record);
332
- markerObserver = new MutationObserver(indexAdded);
333
- markerObserver.observe(document, {
334
- childList: true,
335
- subtree: true
336
- });
337
- indexMarkers(document.documentElement);
338
- watchTitles(document);
339
- if (DEV) devtools()?.attach?.({
340
- scopes,
341
- set,
342
- handle
343
- });
344
- }
345
- /**
346
- * The handlers that the core makes from references, with their references,
347
- * so a spread in markup that the browser renders passes them on in `b-on`,
348
- * as a spread on the server does.
349
- */
350
- const handlerReferences = /* @__PURE__ */ new WeakMap();
351
- /** The modifiers that the wrappers of `brumate/events` put on a handler. */
352
- const MODIFIERS = Symbol.for("brumate.modifiers");
353
- /**
354
- * Renders an object of attributes. With `on`, a handler in it that the core
355
- * made from a reference goes into `on` as a `b-on` entry, with the scope and
356
- * the arguments of its reference and the modifiers of its wrappers.
357
- */
358
- function spread(attributes, on) {
359
- if (on) for (const [name, value] of Object.entries(attributes)) {
360
- const reference = /^on[A-Z]/.test(name) && typeof value === "function" ? handlerReferences.get(value) : void 0;
361
- if (reference) on.push(handlerEntry(name, reference.ref, reference.scope, reference.modifiers, reference.args));
362
- if ((name === "value" || name === "checked") && isBinding(value)) on.push(bindEntry(name, value.ref, setterReference(value.set)));
363
- }
364
- return spread$1(attributes);
365
- }
366
- /** The reference of the setter of a binding: as the state has it, or of a handler that the core made. */
367
- function setterReference(set) {
368
- if (set instanceof FunctionReference) return set;
369
- return typeof set === "function" ? handlerReferences.get(set) : void 0;
370
- }
371
- /** Replaces function references with functions that call them. */
372
- function callable(value, seen) {
373
- if (value instanceof FunctionReference) {
374
- if (isTemplate(value.ref)) return templateReference(value.ref, scopes.get(value.scope));
375
- const handler = (...args) => call(value.ref, scopes.get(value.scope), [...value.args ?? [], ...args]);
376
- handlerReferences.set(handler, value);
377
- return handler;
378
- }
379
- if (typeof value === "object" && value !== null && !seen.has(value)) {
380
- seen.add(value);
381
- const prototype = Object.getPrototypeOf(value);
382
- if (Array.isArray(value) || prototype === Object.prototype || prototype === null) {
383
- const record = value;
384
- for (const key of Object.keys(record)) record[key] = callable(record[key], seen);
385
- }
386
- }
387
- return value;
388
- }
389
- function loadModule(id, reason = "write") {
390
- let promise = loading.get(id);
391
- if (!promise) {
392
- promise = Promise.resolve(options.load(id)).then((loaded) => {
393
- const module = loaded ?? {
394
- id,
395
- props: {},
396
- g: {}
397
- };
398
- modules.set(id, module);
399
- return module;
400
- });
401
- loading.set(id, promise);
402
- if (DEV) devtools()?.load?.(id, "entry", reason, promise);
403
- }
404
- return promise;
405
- }
406
- function loadPart(module, name, reason = "write") {
407
- const key = `${module.id}:${name}`;
408
- let promise = parts.get(key);
409
- if (!promise) {
410
- let loaded;
411
- if (!module.load) loaded = Promise.resolve(module);
412
- else loaded = options.loadPart ? options.loadPart(module, name) : module.load(name);
413
- promise = loaded.then((part) => {
414
- loadedParts.set(key, part);
415
- if (DEV) devtools()?.part?.(module.id, name);
416
- return part;
417
- });
418
- parts.set(key, promise);
419
- if (DEV) devtools()?.load?.(module.id, module.load ? name : "all", reason, promise);
420
- }
421
- return promise;
422
- }
423
- /** Waits forever once the page loads again, so no error shows before it goes. */
424
- let reloading;
425
- async function resolve(ref, reason) {
426
- const [id, name] = ref.split("#");
427
- try {
428
- return (await loadPart(await loadModule(id, reason), partOf(name), reason))[name];
429
- } catch (error) {
430
- const next = await serverBuild();
431
- if (!reloading && next !== void 0 && loadOnce(next)) {
432
- skew("code");
433
- location.reload();
434
- reloading = new Promise(() => {});
435
- }
436
- if (reloading) return reloading;
437
- throw error;
438
- }
439
- }
440
- /**
441
- * Asks the server for its build, after the code of a handler failed to
442
- * load. Returns it when it is not the build of the page. Undefined without
443
- * a build, when the request fails, or when the builds are the same.
444
- */
445
- async function serverBuild() {
446
- if (build === void 0) return;
447
- try {
448
- const current = (await fetch(`${rpcPrefix}/`, {
449
- method: "POST",
450
- headers: { "x-brumate-build": build }
451
- })).headers.get("x-brumate-build");
452
- return current !== null && current !== build ? current : void 0;
453
- } catch {
454
- return;
455
- }
456
- }
457
- async function call(ref, scope, args) {
458
- return (await resolve(ref, "call"))(scope, ...args);
459
- }
460
- /** True for a reference to a `#template` that a component got as a prop, such as `Page#t3`. */
461
- function isTemplate(ref) {
462
- return /#t\d/.test(ref);
463
- }
464
- /** The code of templates that is still loading. Updates wait for it, since a render cannot. */
465
- const loadingTemplates = /* @__PURE__ */ new Set();
466
- /**
467
- * A `#template` of another component, which renders at once, as markup does.
468
- * Its code starts to load when the page state is read, and updates wait for it.
469
- */
470
- function templateReference(ref, scope) {
471
- let render;
472
- const code = resolve(ref, "template").then((handler) => {
473
- render = handler;
474
- }).finally(() => loadingTemplates.delete(code));
475
- loadingTemplates.add(code);
476
- return (...args) => render ? render(scope, ...args) : "";
477
- }
478
- let lastHandler = Promise.resolve();
479
- /**
480
- * Keeps `currentTarget` on an event. The handler runs after the event has
481
- * finished dispatching, when the browser has already cleared it.
482
- */
483
- function withTarget(event, element) {
484
- return new Proxy(event, { get(target, key) {
485
- if (key === "currentTarget") return element;
486
- const value = Reflect.get(target, key);
487
- return typeof value === "function" ? value.bind(target) : value;
488
- } });
489
- }
490
- /**
491
- * Runs the handler `ref` for an element. The scope comes from the element's
492
- * `b-b` anchor, or from the nearest element around it that has one, which
493
- * the compiler checks is in the same scope.
494
- */
495
- function handle(element, entry, event) {
496
- const [ref, owner, encoded] = entry.split("@");
497
- const bound = encoded ? JSON.parse(decodeURIComponent(encoded)) : [];
498
- const anchor = owner ?? element.closest("[b-b]")?.getAttribute("b-b")?.split(":")[0];
499
- const scope = anchor ? scopes.get(parseId(anchor)) : void 0;
500
- if (scope && hiding?.hidden(scope) && element.hasAttribute("b-listen")) return Promise.resolve();
501
- if (ref.startsWith("$set:")) {
502
- const field = element;
503
- return call(ref.slice(5), scope, [/^(checkbox|radio)$/i.test(field.type) ? field.checked : field.value]);
504
- }
505
- if (ref.startsWith("$bind#")) {
506
- const [hops = 0, slot = 0] = ref.slice(6).split(".").map(Number);
507
- let target = scope;
508
- for (let hop = 0; hop < hops; hop++) target = target?.p;
509
- const field = element;
510
- if (target) set(target, slot, /^(checkbox|radio)$/i.test(field.type) ? field.checked : field.value);
511
- return Promise.resolve();
512
- }
513
- const args = event ? [...bound, withTarget(event, element)] : bound;
514
- const begun = DEV ? performance.now() : 0;
515
- if (DEV) devtools()?.handler?.(ref, element, event);
516
- const loaded = resolve(ref, "event");
517
- const started = lastHandler.then(() => loaded).then((handler) => {
518
- if (!DEV) return { value: handler(scope, ...args) };
519
- const ready = performance.now();
520
- const value = handler(scope, ...args);
521
- devtools()?.handled?.({
522
- ref,
523
- element,
524
- event: event?.type,
525
- begun,
526
- ready,
527
- end: performance.now(),
528
- result: value
529
- });
530
- return { value };
531
- });
532
- lastHandler = started.catch(() => {});
533
- return started.then((result) => result.value).catch((error) => {
534
- fail(scope, error);
535
- });
536
- }
537
- /**
538
- * Reports an error of client code: a handler, an effect, a `$client`
539
- * callback or a memo that loads. It renders the `#catch` body of the nearest
540
- * `#try` around the scope of the code, through the parents and the owners of
541
- * scopes. Without one, the page gets a `brumate:error` event on `window`,
542
- * with the error and the scope, and the error is logged.
543
- */
544
- function fail(scope, error) {
545
- options.onError?.(error, { scope: scope?.id });
546
- (async () => {
547
- for (let current = scope; current; current = current.p ?? current.o) {
548
- const id = rootOf(current).m;
549
- if (!id) continue;
550
- const module = await loadModule(id, "error");
551
- const entry = module.t?.[current.k];
552
- if (!entry) continue;
553
- let owner = current.p;
554
- while (owner && owner.k !== entry[0]) owner = owner.p;
555
- if (owner) {
556
- await catchInto(owner, module, entry, error);
557
- return;
558
- }
559
- }
560
- window.dispatchEvent(new CustomEvent("brumate:error", { detail: {
561
- error,
562
- scope
563
- } }));
564
- console.error(error);
565
- })();
566
- }
567
- /** Renders the `#catch` body of a `#try` with an error, in place of what the block shows. */
568
- async function catchInto(owner, module, [, anchor, , fallback, kinds], error) {
569
- const updates = await loadPart(module, "update", "error");
570
- const start = findComment(`b${owner.id}:${anchor}`);
571
- if (!start) return;
572
- const end = rangeEnd(start);
573
- disposeKinds(owner, kinds);
574
- clear(start, end);
575
- insertHTML(end, updates[fallback](owner, error));
576
- }
577
- /** Returns the instance of a scope by its ID. */
578
- function scopeOf(id) {
579
- return scopes.get(id);
580
- }
581
- function get(scope, slot) {
582
- const value = scope.s[slot];
583
- if (computing > 0 && value instanceof Promise) throw new NotReady(value);
584
- if (value instanceof ElementReference) {
585
- const element = findElement(value.scope, value.anchor);
586
- if (element) scope.s[slot] = element;
587
- return element ?? void 0;
588
- }
589
- return value;
590
- }
591
- let writes = 0;
592
- /**
593
- * Writes a slot from code of a component. A prop that a parent bound with
594
- * `$bind` writes the parent's slot too, through any number of levels, and
595
- * the parent's update of the prop then finds the value already there. A
596
- * binding with a setter, `$bind(name, fn)`, calls it in place of the write,
597
- * and the parent's update of the prop writes the value that it keeps.
598
- */
599
- function set(scope, slot, value) {
600
- const bound = scope.b?.[slot];
601
- if (bound === void 0 || isSlotReference(bound)) {
602
- writeSlot(scope, slot, value);
603
- const target = bound && scopes.get(bound.scope);
604
- if (target) set(target, bound.slot, value);
605
- } else if (bound instanceof FunctionReference) call(bound.ref, scopes.get(bound.scope), [...bound.args ?? [], value]);
606
- else if (typeof bound === "function") bound(value);
607
- return value;
608
- }
609
- /** Writes a slot, and updates what reads it. */
610
- function writeSlot(scope, slot, value) {
611
- if (!Object.is(scope.s[slot], value)) {
612
- writes++;
613
- scope.s[slot] = value;
614
- if (DEV) devtools()?.write?.(scope, slot, value);
615
- trigger(scope, slot);
616
- }
617
- }
618
- /** What `$bind(name)` passes a child, in markup that the browser renders. */
619
- function binding(value, scope, slot, set) {
620
- return new Binding(value, new SlotReference(typeof scope === "object" ? scope.id : scope, slot), set);
621
- }
622
- /**
623
- * Records the props that a parent bound with `$bind`, among the props that a
624
- * component the browser renders writes: `slots` has the slot of each, by its name.
625
- */
626
- function bindings(scope, props, slots) {
627
- const target = typeof scope === "object" ? scope : scopes.get(scope);
628
- for (const [name, slot] of Object.entries(slots)) {
629
- const value = props[name];
630
- if (target && isBinding(value)) (target.b ??= {})[slot] = value.target;
631
- }
632
- }
633
- /**
634
- * The names of a call of a module function, for its shared code. Each ref
635
- * is a slot of `scope`, `[scope, slot]` for a slot of another scope, or
636
- * `[value]` for a value that does not change, such as a literal argument.
637
- */
638
- function cells(scope, links, names) {
639
- const result = {};
640
- names.forEach((name, index) => {
641
- const ref = links[index];
642
- let owner = scope;
643
- let slot;
644
- if (typeof ref === "number") slot = ref;
645
- else if (ref.length === 2) [owner, slot] = ref;
646
- else {
647
- Object.defineProperty(result, name, {
648
- get: () => ref[0],
649
- set: () => {}
650
- });
651
- return;
652
- }
653
- Object.defineProperty(result, name, {
654
- get: () => get(owner, slot),
655
- set: (value) => set(owner, slot, value)
656
- });
657
- });
658
- return result;
659
- }
660
- const loads = /* @__PURE__ */ new Map();
661
- let loadCount = 0;
662
- const loadingSlots = /* @__PURE__ */ new Set();
663
- /** Marks a memo as loading. Its readers update the first time, so `$isPending` becomes true. */
664
- function startLoading(scope, slot, key) {
665
- if (!loadingSlots.has(key)) {
666
- loadingSlots.add(key);
667
- trigger(scope, slot);
668
- }
669
- }
670
- /** The timers of debounced and throttled memos, by `scope:slot`, with when each last computed. */
671
- const timers = /* @__PURE__ */ new Map();
672
- /**
673
- * Computes a memo of `$debounced` after its value stops changing for `ms`,
674
- * or one of `$throttled` at most once every `ms`, with the last value after
675
- * the wait. The memo is pending while it waits.
676
- */
677
- function timed(scope, slot, ms, throttle, compute) {
678
- const key = `${scope.id}:${slot}`;
679
- const state = timers.get(key) ?? { last: -Infinity };
680
- timers.set(key, state);
681
- const run = () => {
682
- state.timer = void 0;
683
- state.last = Date.now();
684
- if (scopes.get(scope.id) === scope) memo(scope, slot, compute);
685
- };
686
- const since = Date.now() - state.last;
687
- if (throttle && state.timer === void 0 && since >= ms) {
688
- run();
689
- return;
690
- }
691
- if (!throttle) {
692
- clearTimeout(state.timer);
693
- state.timer = void 0;
694
- }
695
- state.timer ??= setTimeout(run, throttle ? ms - since : ms);
696
- startLoading(scope, slot, key);
697
- }
698
- /** True for a promise, or any object with a `then` method. */
699
- function isThenable(value) {
700
- return value !== null && typeof value === "object" && typeof value.then === "function";
701
- }
702
- /**
703
- * Writes the result of an async memo when it arrives. Until then the slot
704
- * keeps its value, and `pending` is true. Only the latest load is written.
705
- */
706
- function asyncMemo(scope, slot, promise) {
707
- const key = `${scope.id}:${slot}`;
708
- const load = ++loadCount;
709
- loads.set(key, load);
710
- startLoading(scope, slot, key);
711
- const settle = (value, failed = false) => {
712
- if (loads.get(key) !== load) return;
713
- loadingSlots.delete(key);
714
- if (!failed && !Object.is(scope.s[slot], value)) set(scope, slot, value);
715
- else trigger(scope, slot);
716
- };
717
- const failed = (error) => {
718
- if (loads.get(key) === load) {
719
- fail(scope, error);
720
- settle(void 0, true);
721
- }
722
- };
723
- promise.then((value) => {
724
- if (!isAsyncIterable(value)) {
725
- settle(value);
726
- return;
727
- }
728
- (async () => {
729
- try {
730
- for await (const item of value) {
731
- if (loads.get(key) !== load) break;
732
- if (loadingSlots.has(key)) settle(item);
733
- else if (!Object.is(scope.s[slot], item)) set(scope, slot, item);
734
- }
735
- } catch (error) {
736
- failed(error);
737
- }
738
- })();
739
- }, failed);
740
- }
741
- /** Thrown when a memo reads a value that is still loading. */
742
- var NotReady = class extends Error {
743
- source;
744
- constructor(source) {
745
- super("The value is still loading");
746
- this.source = source;
747
- }
748
- };
749
- let computing = 0;
750
- /** Aborts the server function calls of a memo's compute, by memo key. */
751
- const memoControllers = /* @__PURE__ */ new Map();
752
- /** The key of the memo that computes, if any. */
753
- let memoKey;
754
- /** The signal for server function calls while a memo computes. It is made on the first call. */
755
- function memoSignal() {
756
- if (memoKey === void 0) return;
757
- let controller = memoControllers.get(memoKey);
758
- if (!controller) {
759
- controller = new AbortController();
760
- memoControllers.set(memoKey, controller);
761
- }
762
- return controller.signal;
763
- }
764
- /**
765
- * Computes a memo. A promise loads, and the memo keeps its value until it
766
- * settles. A memo that reads a value that is still loading keeps its value
767
- * too, and is pending until that value arrives and the memo computes again.
768
- */
769
- function memo(scope, slot, compute) {
770
- const key = `${scope.id}:${slot}`;
771
- if (guesses?.same(key)) return;
772
- const rendered = scope.s[slot];
773
- if (renderedLoads.delete(key) && isThenable(rendered)) {
774
- asyncMemo(scope, slot, Promise.resolve(rendered));
775
- return;
776
- }
777
- let value;
778
- memoControllers.get(key)?.abort();
779
- memoControllers.delete(key);
780
- const outer = memoKey;
781
- memoKey = key;
782
- computing++;
783
- try {
784
- value = compute();
785
- } catch (error) {
786
- if (!(error instanceof NotReady)) throw error;
787
- startLoading(scope, slot, key);
788
- return;
789
- } finally {
790
- computing--;
791
- memoKey = outer;
792
- }
793
- if (isThenable(value) || isAsyncIterable(value)) {
794
- asyncMemo(scope, slot, Promise.resolve(value));
795
- return;
796
- }
797
- const waited = loadingSlots.delete(key);
798
- loads.delete(key);
799
- guesses?.map.delete(key);
800
- if (!Object.is(scope.s[slot], value)) set(scope, slot, value);
801
- else if (waited) trigger(scope, slot);
802
- }
803
- /**
804
- * The guesses of `$optimistic` values. The first `guess` sets it, so the
805
- * code that reads guesses is left out of a build that makes none.
806
- */
807
- let guesses;
808
- /** The values of promises that the server streamed, so a guess knows its source did not change. */
809
- const settled = /* @__PURE__ */ new WeakMap();
810
- /** True while the source of a guess holds the value it had when the guess was made. */
811
- function sameSource(key) {
812
- const entry = guesses.map.get(key);
813
- if (!entry?.source) return false;
814
- const current = entry.source[0].s[entry.source[1]];
815
- return Object.is(current, entry.base) || entry.base instanceof Promise && settled.get(entry.base) === current;
816
- }
817
- /** Server calls that have not finished, from forms and from `rpc`. */
818
- let calling = 0;
819
- /** Counts the pages that client navigation left, so calls of an old page are not counted down. */
820
- let callEpoch = 0;
821
- /**
822
- * Writes a guess into an optimistic value. It goes back to its source when
823
- * the source changes, which computes it again, or when every server call of
824
- * the page finishes, such as after a post failed.
825
- */
826
- function guess(scope, slot, ...rest) {
827
- const value = rest.at(-1);
828
- const source = rest.length === 3 ? [rest[0], rest[1]] : void 0;
829
- const base = source && source[0].s[source[1]];
830
- guesses ??= {
831
- map: /* @__PURE__ */ new Map(),
832
- same: sameSource,
833
- reset: resetGuesses
834
- };
835
- guesses.map.set(`${scope.id}:${slot}`, {
836
- scope,
837
- slot,
838
- source,
839
- base
840
- });
841
- return set(scope, slot, value);
842
- }
843
- /** Counts a server call, and puts guesses back when the last one finishes. */
844
- function track(request) {
845
- calling++;
846
- const epoch = callEpoch;
847
- const done = () => {
848
- if (epoch !== callEpoch) return;
849
- calling--;
850
- setTimeout(() => calling || guesses?.reset(), 0);
851
- };
852
- request.then(done, done);
853
- return request;
854
- }
855
- function resetGuesses() {
856
- for (const [key, { scope, slot, source }] of guesses.map) {
857
- if (source && pending(source[0], source[1])) continue;
858
- guesses.map.delete(key);
859
- if (source && scopes.has(scope.id) && !Object.is(scope.s[slot], source[0].s[source[1]])) set(scope, slot, source[0].s[source[1]]);
860
- }
861
- }
862
- /** True while a new value of a memo loads, or while the server still streams its value. */
863
- function pending(scope, slot) {
864
- return loadingSlots.has(`${scope.id}:${slot}`) || scope.s[slot] instanceof Promise;
865
- }
866
- /** `x++`, `x--`, `++x` and `--x`. */
867
- function update(scope, slot, delta, prefix) {
868
- const previous = get(scope, slot);
869
- set(scope, slot, previous + delta);
870
- return prefix ? previous + delta : previous;
871
- }
872
- function rootOf(scope) {
873
- let current = scope;
874
- while (current.p) current = current.p;
875
- return current;
876
- }
877
- function trigger(scope, slot) {
878
- const id = rootOf(scope).m;
879
- const module = modules.get(id);
880
- const updates = loadedParts.get(`${id}:update`);
881
- if (module && updates && loadingTemplates.size === 0) {
882
- run(module, updates, scope, slot);
883
- return;
884
- }
885
- const loading = loadModule(id).then(async (loaded) => {
886
- if (loaded.g[scope.k]?.[slot]) {
887
- const code = await loadPart(loaded, "update");
888
- await Promise.allSettled(loadingTemplates);
889
- run(loaded, code, scope, slot);
890
- }
891
- });
892
- loadingUpdates.add(loading);
893
- loading.finally(() => loadingUpdates.delete(loading));
894
- }
895
- /** The updates that wait for their code. */
896
- const loadingUpdates = /* @__PURE__ */ new Set();
897
- /**
898
- * Resolves when the updates of the writes so far have run, including those
899
- * whose code is loading. `transition` of `brumate/events` waits for it.
900
- */
901
- async function updated() {
902
- while (loadingUpdates.size > 0) await Promise.allSettled(loadingUpdates);
903
- }
904
- globalThis[Symbol.for("brumate.updated")] = updated;
905
- const pendingEffects = /* @__PURE__ */ new Map();
906
- let running = 0;
907
- let flushing = false;
908
- /** Counts changes to the scope tree, so `run` knows when the descendants it found are out of date. */
909
- let treeChanges = 0;
910
- /** The updates that ran since the outermost `run` started, and when it started, for the devtools. */
911
- let updateCount = 0;
912
- let updateStart = 0;
913
- function run(module, updates, scope, slot) {
914
- if (DEV && running === 0) {
915
- updateCount = 0;
916
- updateStart = performance.now();
917
- }
918
- running++;
919
- let found;
920
- let foundAt = treeChanges;
921
- try {
922
- for (const [kind, name] of module.g[scope.k]?.[slot] ?? []) {
923
- const fn = updates[name];
924
- if (kind === scope.k) {
925
- runUpdate(fn, name, scope);
926
- continue;
927
- }
928
- if (foundAt !== treeChanges) {
929
- found = void 0;
930
- foundAt = treeChanges;
931
- }
932
- found ??= /* @__PURE__ */ new Map();
933
- let targets = found.get(kind);
934
- if (!targets) {
935
- targets = descendants(scope, kind);
936
- found.set(kind, targets);
937
- }
938
- for (const target of targets) runUpdate(fn, name, target);
939
- }
940
- } finally {
941
- running--;
942
- }
943
- if (running === 0) {
944
- flushEffects();
945
- if (DEV) devtools()?.updated?.(updateCount, updateStart, performance.now());
946
- }
947
- }
948
- /** Runs an update on a scope. An effect waits until the other updates have run. */
949
- function runUpdate(fn, name, target) {
950
- if (DEV) updateCount++;
951
- if (name[0] === "e") pendingEffects.set(`${target.id}:${name}`, () => {
952
- if (scopes.has(target.id)) fn(target);
953
- });
954
- else fn(target);
955
- }
956
- /**
957
- * Runs the effects that writes scheduled, in the order they were first
958
- * scheduled. Writes in an effect schedule more effects, which run after.
959
- */
960
- function flushEffects() {
961
- if (flushing) return;
962
- flushing = true;
963
- try {
964
- for (const [key, runEffect] of pendingEffects) {
965
- pendingEffects.delete(key);
966
- runEffect();
967
- }
968
- } finally {
969
- flushing = false;
970
- }
971
- }
972
- function descendants(scope, kind, result = []) {
973
- for (const child of scope.children) {
974
- if (child.k === kind) result.push(child);
975
- descendants(child, kind, result);
976
- }
977
- return result;
978
- }
979
- function destroy(scope) {
980
- if (scope.children.size > 0) for (const child of Array.from(scope.children)) destroy(child);
981
- const start = portals > 0 ? comments.get(`P${scope.id}`) : void 0;
982
- if (start?.isConnected) {
983
- const end = rangeEnd(start);
984
- clear(start, end);
985
- start.remove();
986
- end.remove();
987
- }
988
- removeScope(scope);
989
- sweepIndexes();
990
- }
991
- /**
992
- * Removes a scope from the page: its cleanups run, and its memo state goes,
993
- * so a load that settles later is not written. Its markup stays.
994
- */
995
- function removeScope(scope) {
996
- if (scope.cleanups) for (const cleanup of scope.cleanups.values()) cleanup();
997
- const waiting = memoControllers.size + timers.size + loads.size + loadingSlots.size + (guesses?.map.size ?? 0);
998
- for (let slot = 0; waiting > 0 && slot < scope.s.length; slot++) {
999
- const key = `${scope.id}:${slot}`;
1000
- memoControllers.get(key)?.abort();
1001
- memoControllers.delete(key);
1002
- clearTimeout(timers.get(key)?.timer);
1003
- timers.delete(key);
1004
- loads.delete(key);
1005
- loadingSlots.delete(key);
1006
- guesses?.map.delete(key);
1007
- }
1008
- if (scope.h) hiding?.bodies.delete(scope.h);
1009
- scopes.delete(scope.id);
1010
- scope.p?.children.delete(scope);
1011
- treeChanges++;
1012
- }
1013
- function disposeKinds(scope, kinds) {
1014
- for (const child of Array.from(scope.children)) if (kinds.includes(child.k)) destroy(child);
1015
- }
1016
- const MARKER = /^[btilP]-?\d/;
1017
- function markerKey(data) {
1018
- return data[0] === "b" ? data.split(":").slice(0, 2).join(":") : data;
1019
- }
1020
- const SCOPE_MARKER = /^[tb](-?[\d.]+):/;
1021
- /** True for markup that names a scope from the server: a `b-b` or marker with an ID that is not negative. */
1022
- const SERVER_SCOPES = /b-b="\d|<!--[tb]\d/;
1023
- /** The scopes that the client made since the last insert, which the next insert holds. */
1024
- const rendered = [];
1025
- /** How many `#portal` markers the page has had, so a scope looks for its own only when any have. */
1026
- let portals = 0;
1027
- /**
1028
- * Indexes the markers and the bound elements under `root`, so that updates find them without a
1029
- * search of the page. A search for each row of a long list takes time that grows with the list.
1030
- * With `ids`, it also collects the IDs of the scopes that the markup names. The IDs of scopes
1031
- * that the client made are negative.
1032
- */
1033
- function indexMarkers(root, ids, withElements = true) {
1034
- if (withElements) indexElements(root, ids);
1035
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
1036
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
1037
- const data = node.data;
1038
- if (!MARKER.test(data)) continue;
1039
- comments.set(markerKey(data), node);
1040
- if (data[0] === "P") portals++;
1041
- const match = ids && SCOPE_MARKER.exec(data);
1042
- if (match) ids.add(parseId(match[1]));
1043
- }
1044
- }
1045
- /** The size of the indexes at which they next drop the nodes that left the page. */
1046
- let sweepAt = 4096;
1047
- /**
1048
- * Drops the nodes that left the page from the indexes, once they have grown to twice their size
1049
- * after the last sweep, so a list that the client fills and empties again does not keep its old
1050
- * rows. A node that comes back is indexed again when it is inserted.
1051
- */
1052
- function sweepIndexes() {
1053
- if (comments.size + elements.size < sweepAt) return;
1054
- for (const [key, node] of comments) if (!node.isConnected) comments.delete(key);
1055
- for (const [key, node] of elements) if (!node.isConnected) elements.delete(key);
1056
- sweepAt = Math.max(4096, 2 * (comments.size + elements.size));
1057
- }
1058
- function indexElements(root, ids) {
1059
- if (root.nodeType === 1) indexElement(root, ids);
1060
- if (root.nodeType === 1 || root.nodeType === 9 || root.nodeType === 11) for (const element of root.querySelectorAll("[b-b]")) indexElement(element, ids);
1061
- }
1062
- /**
1063
- * The nodes that inserts of the client put in the page, from the first to the last of each,
1064
- * whose bound elements are not indexed yet. A list that the client creates is often never
1065
- * updated row by row, so its elements are indexed when an update first needs one of them.
1066
- */
1067
- const unindexed = [];
1068
- function indexInserts() {
1069
- for (const [first, last] of unindexed.splice(0)) if (first.isConnected) for (let node = first; node; node = node.nextSibling) {
1070
- indexElements(node);
1071
- if (node === last) break;
1072
- }
1073
- else if (last.isConnected) for (let node = last; node; node = node.previousSibling) indexElements(node);
1074
- }
1075
- function indexElement(element, ids) {
1076
- const key = element.getAttribute("b-b");
1077
- if (key === null) return;
1078
- elements.set(key, element);
1079
- ids?.add(parseId(key.slice(0, key.indexOf(":"))));
1080
- }
1081
- /** Indexes the markers in the nodes that mutation records added. */
1082
- function indexAdded(records) {
1083
- for (const record of records) for (const node of record.addedNodes) if (node.nodeType === 1) indexMarkers(node);
1084
- else if (node.nodeType === 8 && MARKER.test(node.data)) {
1085
- const data = node.data;
1086
- comments.set(markerKey(data), node);
1087
- if (data[0] === "P") portals++;
1088
- }
1089
- }
1090
- /**
1091
- * Finds a marker in the page. Returns undefined when the markup is not in
1092
- * the page, such as `children` inside a block that is closed. Updates to it
1093
- * do nothing, and it updates when the client inserts it again.
1094
- */
1095
- function findComment(key) {
1096
- let comment = comments.get(key);
1097
- if (!comment?.isConnected) {
1098
- if (markerObserver) indexAdded(markerObserver.takeRecords());
1099
- else indexMarkers(document.documentElement);
1100
- comment = comments.get(key);
1101
- }
1102
- return comment?.isConnected ? comment : void 0;
1103
- }
1104
- function findElement(scope, anchor) {
1105
- const key = `${scope}:${anchor}`;
1106
- let element = elements.get(key);
1107
- if (!element?.isConnected) {
1108
- if (markerObserver) {
1109
- indexAdded(markerObserver.takeRecords());
1110
- indexInserts();
1111
- element = elements.get(key);
1112
- }
1113
- if (!element?.isConnected) {
1114
- element = document.querySelector(`[b-b="${key}"]`) ?? void 0;
1115
- if (element) elements.set(key, element);
1116
- }
1117
- }
1118
- return element?.isConnected ? element : null;
1119
- }
1120
- /** Returns the marker that ends the range that `start` opens. */
1121
- function rangeEnd(start) {
1122
- let depth = 0;
1123
- for (let node = start.nextSibling; node; node = node.nextSibling) if (node.nodeType === 8) {
1124
- const data = node.data;
1125
- if (data[0] === "/") {
1126
- if (depth === 0) return node;
1127
- depth--;
1128
- } else if (MARKER.test(data)) depth++;
1129
- }
1130
- throw new Error(`Missing end marker for <!--${start.data}-->`);
1131
- }
1132
- function clear(start, end) {
1133
- if (start.nextSibling === end || !start.nextSibling) return;
1134
- const range = document.createRange();
1135
- range.setStartAfter(start);
1136
- range.setEndBefore(end);
1137
- range.deleteContents();
1138
- }
1139
- /**
1140
- * Inserts rendered HTML before a node, or at the end of a parent, and runs
1141
- * the work that waits for it.
1142
- */
1143
- function insertHTML(before, html) {
1144
- const template = document.createElement("template");
1145
- template.innerHTML = trustedHTML(html);
1146
- const fragment = template.content;
1147
- if (markerObserver) indexAdded(markerObserver.takeRecords());
1148
- const client = rendered.splice(0);
1149
- const fromServer = SERVER_SCOPES.test(html);
1150
- const ids = fromServer ? /* @__PURE__ */ new Set() : void 0;
1151
- indexMarkers(fragment, ids, fromServer);
1152
- options.listen(fragment);
1153
- watchTitles(fragment);
1154
- const server = [];
1155
- for (const id of ids ?? []) {
1156
- const scope = typeof id === "number" && id < 0 ? void 0 : scopes.get(id);
1157
- if (scope) server.push(scope);
1158
- }
1159
- if (!fromServer && fragment.firstChild) {
1160
- unindexed.push([fragment.firstChild, fragment.lastChild]);
1161
- if (unindexed.length > 256) indexInserts();
1162
- }
1163
- const added = hiding?.bodies.size ? [...fragment.childNodes] : void 0;
1164
- if ("parent" in before) before.parent.append(fragment);
1165
- else before.parentNode.insertBefore(fragment, before);
1166
- if (added) hiding.added(added);
1167
- markerObserver?.takeRecords();
1168
- options.inserted?.();
1169
- for (const fn of afterInsert.splice(0)) fn();
1170
- if (server.length > 0) refresh(server);
1171
- const live = client.filter((scope) => scopes.has(scope.id));
1172
- if (live.length > 0) refresh(live, true);
1173
- }
1174
- /**
1175
- * Renders a `#portal` body into its target, between markers with its scope
1176
- * ID. `kinds` names the body, so a new target first removes it from the old one.
1177
- */
1178
- function portalTo(scope, target, render, kinds = []) {
1179
- disposeKinds(scope, kinds);
1180
- const element = typeof target === "string" ? document.querySelector(target) : target;
1181
- if (!(element instanceof Element)) return;
1182
- insertHTML({ parent: element }, `<!--P${nextId}-->${render(scope)}<!--/P-->`);
1183
- }
1184
- /** Writes an inserted value between `<!--t…-->` and `<!--/t-->`. */
1185
- function text(scope, anchor, value) {
1186
- const start = findComment(`t${scope.id}:${anchor}`);
1187
- if (start) write(start.parentNode, start.nextSibling, rangeEnd(start), value);
1188
- }
1189
- /** Writes an inserted value that is the whole content of the element with the anchor. */
1190
- function content(scope, anchor, value) {
1191
- const element = findElement(scope.id, anchor);
1192
- if (element) write(element, element.firstChild, null, value);
1193
- }
1194
- /**
1195
- * Writes the text of an element whose content is text, such as a `<textarea>`
1196
- * or a `<title>`. A `<textarea>` gets the value too, as `value` does on an
1197
- * `<input>`, so a change replaces what the user typed.
1198
- */
1199
- function writeText(scope, anchor, value) {
1200
- const element = findElement(scope.id, anchor);
1201
- if (element) {
1202
- const written = textValue(value);
1203
- if (element.textContent !== written) element.textContent = written;
1204
- if (element instanceof HTMLTextAreaElement && element.value !== written) element.value = written;
1205
- }
1206
- }
1207
- /**
1208
- * Replaces the nodes of `parent` from `first` up to `end`, or to its last
1209
- * child, with a value. A text node that stays a text node keeps its node.
1210
- */
1211
- function write(parent, first, end, value) {
1212
- if ((typeof value === "string" || typeof value === "number") && first?.nodeType === 3 && first.nextSibling === end) {
1213
- const saved = hiding?.nodes.get(first);
1214
- const text = String(value);
1215
- if (saved) saved.v = text;
1216
- else if (first.data !== text) first.data = text;
1217
- return;
1218
- }
1219
- while (first && first !== end) {
1220
- const next = first.nextSibling;
1221
- first.remove();
1222
- first = next;
1223
- }
1224
- insertHTML(end ?? { parent }, insertValue(value));
1225
- }
1226
- /** The `value` and `checked` that updates last wrote to each field. */
1227
- const fieldValues = /* @__PURE__ */ new WeakMap();
1228
- function setAttribute(element, name, value) {
1229
- if (isBinding(value)) value = value.value;
1230
- if (name === "value" || name === "checked") {
1231
- const field = element;
1232
- const next = name === "checked" ? Boolean(value) : String(value ?? "");
1233
- const written = fieldValues.get(element) ?? /* @__PURE__ */ new Map();
1234
- fieldValues.set(element, written);
1235
- const before = written.has(name) ? written.get(name) : field[name];
1236
- written.set(name, next);
1237
- if (!Object.is(before, next) && field[name] !== next) field[name] = next;
1238
- }
1239
- const written = attributeText(name, value);
1240
- if (element.getAttribute(name) === (written ?? null)) return;
1241
- if (written === void 0) element.removeAttribute(name);
1242
- else element.setAttribute(name, written);
1243
- if (name === "style") hiding?.styled(element);
1244
- }
1245
- function attr(scope, anchor, name, value) {
1246
- const element = findElement(scope.id, anchor);
1247
- if (element) setAttribute(element, name, value);
1248
- }
1249
- /** The attributes that the last update of a spread wrote, so the next one removes those it drops. */
1250
- const spreadNames = /* @__PURE__ */ new WeakMap();
1251
- function attrs(scope, anchor, values, own = []) {
1252
- const element = findElement(scope.id, anchor);
1253
- if (element) {
1254
- if (!spreadNames.has(element)) spreadNames.set(element, new Set(element.getAttributeNames().filter((name) => !own.includes(name) && !/^(b-|data-prefetch$)/.test(name))));
1255
- const names = /* @__PURE__ */ new Set();
1256
- for (const [name, value] of Object.entries(values)) if (name !== "children" && !/^on[A-Z]/.test(name)) {
1257
- names.add(name);
1258
- setAttribute(element, name, value);
1259
- }
1260
- for (const name of spreadNames.get(element) ?? []) if (!names.has(name)) setAttribute(element, name, void 0);
1261
- spreadNames.set(element, names);
1262
- }
1263
- }
1264
- /** Shows the branch at `index` of `#if` or `#switch`, or nothing for -1. */
1265
- function branch(scope, anchor, index, renders, kinds) {
1266
- const start = findComment(`b${scope.id}:${anchor}`);
1267
- if (!start) return;
1268
- if (Number(start.data.split(":")[2]) === index) return;
1269
- const end = rangeEnd(start);
1270
- disposeKinds(scope, kinds);
1271
- clear(start, end);
1272
- start.data = `b${scope.id}:${anchor}:${index}`;
1273
- const render = renders[index];
1274
- if (render) insertHTML(end, render(scope));
1275
- }
1276
- /** Renders the body of `#key` again when its value changes. */
1277
- function rekey(scope, anchor, value, render, kinds) {
1278
- scope.keys ??= /* @__PURE__ */ new Map();
1279
- if (scope.keys.has(anchor) && Object.is(scope.keys.get(anchor), value)) return;
1280
- scope.keys.set(anchor, value);
1281
- const start = findComment(`b${scope.id}:${anchor}`);
1282
- if (!start) return;
1283
- const end = rangeEnd(start);
1284
- disposeKinds(scope, kinds);
1285
- clear(start, end);
1286
- insertHTML(end, render(scope));
1287
- }
1288
- /**
1289
- * Renders the body of a `#try` block again, for its `reset` function. If the
1290
- * body throws, the fallback renders again with the error.
1291
- */
1292
- async function reset(scope, anchor, id, body, fallback, kinds) {
1293
- const updates = await loadPart(await loadModule(id, "reset"), "update", "reset");
1294
- const start = findComment(`b${scope.id}:${anchor}`);
1295
- if (!start) return;
1296
- const end = rangeEnd(start);
1297
- disposeKinds(scope, kinds);
1298
- clear(start, end);
1299
- let html;
1300
- try {
1301
- html = updates[body](scope);
1302
- } catch (error) {
1303
- disposeKinds(scope, kinds);
1304
- afterInsert.length = 0;
1305
- html = updates[fallback](scope, error);
1306
- }
1307
- insertHTML(end, html);
1308
- }
1309
- /**
1310
- * Renders the body of a `#client` block once, in place of its fallback.
1311
- * `kinds` are the scope IDs inside the fallback, whose instances go.
1312
- */
1313
- function fill(scope, anchor, render, kinds = []) {
1314
- const start = findComment(`b${scope.id}:${anchor}`);
1315
- if (!start || start.data.split(":").length > 2) return;
1316
- start.data += ":1";
1317
- const end = rangeEnd(start);
1318
- disposeKinds(scope, kinds);
1319
- clear(start, end);
1320
- insertHTML(end, render(scope));
1321
- }
1322
- /**
1323
- * Shows or hides the body of an `#offscreen` block. A body that the page
1324
- * does not have yet renders the first time it shows. `kind` is the body's
1325
- * scope ID in the compiled component.
1326
- */
1327
- function offscreen(scope, anchor, value, render, kind) {
1328
- const start = findComment(`b${scope.id}:${anchor}`);
1329
- if (!start) return;
1330
- const visible = Boolean(value);
1331
- const state = start.data.split(":")[2];
1332
- if (visible ? state === "1" : state !== "1") return;
1333
- start.data = `b${scope.id}:${anchor}:${visible ? 1 : 0}`;
1334
- const end = rangeEnd(start);
1335
- if (state === "-1") {
1336
- insertHTML(end, render(scope));
1337
- return;
1338
- }
1339
- let body;
1340
- for (const child of scope.children) if (child.k === kind) body = child;
1341
- if (body) {
1342
- hiding ??= createHiding();
1343
- if (visible) hiding.show(body);
1344
- else hiding.hide(body, start, end);
1345
- }
1346
- }
1347
- /**
1348
- * The code of hidden `#offscreen` bodies. The first body that hides sets it
1349
- * up, so the core of a page without one only checks that it is not there.
1350
- * A body is hidden with an inline `display: none !important` on each element
1351
- * at its top level, which no stylesheet overrides, and empty text for each
1352
- * text node. The nodes stay in the page, so form fields, focus and media
1353
- * keep their state.
1354
- */
1355
- let hiding;
1356
- /** True for a scope that is `ancestor` or inside it, also through the owner of a component. */
1357
- function within(scope, ancestor) {
1358
- for (let current = scope; current; current = current.p ?? current.o) if (current === ancestor) return true;
1359
- return false;
1360
- }
1361
- /** True for a scope in a hidden `#offscreen` body. */
1362
- function hidden(scope) {
1363
- for (let current = scope; current; current = current.p ?? current.o) if (current.h) return true;
1364
- return false;
1365
- }
1366
- /** The nodes between two markers. */
1367
- function between([start, end]) {
1368
- const result = [];
1369
- for (let node = start.nextSibling; node && node !== end; node = node.nextSibling) result.push(node);
1370
- return result;
1371
- }
1372
- /** The inline style of an element, which an element that is not HTML or SVG may not have. */
1373
- function display(element) {
1374
- return element.style;
1375
- }
1376
- function createHiding() {
1377
- const bodies = /* @__PURE__ */ new Set();
1378
- const nodes = /* @__PURE__ */ new WeakMap();
1379
- const hideNode = (node) => {
1380
- const saved = nodes.get(node);
1381
- if (saved) {
1382
- saved.n++;
1383
- return;
1384
- }
1385
- if (node.nodeType === 3) {
1386
- nodes.set(node, {
1387
- n: 1,
1388
- v: node.data
1389
- });
1390
- node.data = "";
1391
- return;
1392
- }
1393
- const style = node.nodeType === 1 ? display(node) : void 0;
1394
- if (style) {
1395
- nodes.set(node, {
1396
- n: 1,
1397
- v: style.getPropertyValue("display"),
1398
- p: style.getPropertyPriority("display"),
1399
- a: node.hasAttribute("style")
1400
- });
1401
- style.setProperty("display", "none", "important");
1402
- }
1403
- };
1404
- const showNode = (node) => {
1405
- const saved = nodes.get(node);
1406
- if (!saved || --saved.n > 0) return;
1407
- nodes.delete(node);
1408
- if (node.nodeType === 3) {
1409
- node.data = saved.v;
1410
- return;
1411
- }
1412
- const element = node;
1413
- const style = display(element);
1414
- if (saved.v) style.setProperty("display", saved.v, saved.p);
1415
- else style.removeProperty("display");
1416
- if (!saved.a && element.getAttribute("style") === "") element.removeAttribute("style");
1417
- };
1418
- return {
1419
- bodies,
1420
- nodes,
1421
- hidden,
1422
- hide(body, start, end) {
1423
- const record = {
1424
- scope: body,
1425
- ranges: [[start, end]]
1426
- };
1427
- body.h = record;
1428
- bodies.add(record);
1429
- const inside = [...scopes.values()].filter((scope) => within(scope, body));
1430
- for (const scope of inside) {
1431
- const portal = comments.get(`P${scope.id}`);
1432
- if (portal?.isConnected) record.ranges.push([portal, rangeEnd(portal)]);
1433
- }
1434
- for (const range of record.ranges) between(range).forEach(hideNode);
1435
- for (const scope of inside) {
1436
- for (const [name, cleanup] of scope.cleanups ?? []) {
1437
- cleanup();
1438
- (scope.w ??= /* @__PURE__ */ new Set()).add(name);
1439
- }
1440
- scope.cleanups?.clear();
1441
- }
1442
- },
1443
- show(body) {
1444
- const record = body.h;
1445
- if (!record) return;
1446
- body.h = void 0;
1447
- bodies.delete(record);
1448
- for (const range of record.ranges) if (range[0].isConnected) between(range).forEach(showNode);
1449
- for (const scope of scopes.values()) if (scope.w && within(scope, body) && !hidden(scope)) {
1450
- const ref = `${rootOf(scope).m}#`;
1451
- for (const name of scope.w) call(ref + name, scope, []);
1452
- scope.w = void 0;
1453
- }
1454
- },
1455
- paused(scope, name) {
1456
- if (bodies.size === 0 || !hidden(scope)) return false;
1457
- (scope.w ??= /* @__PURE__ */ new Set()).add(name);
1458
- return true;
1459
- },
1460
- added(added) {
1461
- for (const node of added) for (const record of bodies) {
1462
- for (const [start, end] of record.ranges) if (node.parentNode === start.parentNode && start.compareDocumentPosition(node) & 4 && node.compareDocumentPosition(end) & 4) hideNode(node);
1463
- const data = node.nodeType === 8 ? node.data : "";
1464
- const scope = /^P-?[\d.]+$/.test(data) ? scopes.get(parseId(data.slice(1))) : void 0;
1465
- if (scope && within(scope, record.scope)) record.ranges.push([node, rangeEnd(node)]);
1466
- }
1467
- },
1468
- styled(element) {
1469
- const saved = nodes.get(element);
1470
- const style = display(element);
1471
- if (saved && style) {
1472
- saved.v = style.getPropertyValue("display");
1473
- saved.p = style.getPropertyPriority("display");
1474
- saved.a = element.hasAttribute("style");
1475
- style.setProperty("display", "none", "important");
1476
- }
1477
- }
1478
- };
1479
- }
1480
- const ITEM_MARKER = /^i(-?[\d.]+)$/;
1481
- /** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */
1482
- /** The items of a `#for` list: an array as it is, since `list` only reads it, or any iterable as an array. */
1483
- function listOf(value) {
1484
- return Array.isArray(value) ? value : Array.from(value);
1485
- }
1486
- function list(scope, anchor, items, key, render, assign, fallback, fallbackKinds) {
1487
- const start = findComment(`b${scope.id}:${anchor}`);
1488
- if (!start) return;
1489
- const end = rangeEnd(start);
1490
- const previous = /* @__PURE__ */ new Map();
1491
- let others;
1492
- let position = 0;
1493
- for (let node = start.nextSibling; node && node !== end;) {
1494
- let data;
1495
- let id;
1496
- if (node.nodeType === 8) {
1497
- data = node.data;
1498
- id = ITEM_MARKER.exec(data)?.[1];
1499
- } else if (node.nodeType === 1) {
1500
- const bound = node.getAttribute("b-b");
1501
- id = bound === null ? void 0 : bound.slice(0, bound.indexOf(":"));
1502
- }
1503
- const item = id === void 0 ? void 0 : scopes.get(parseId(id));
1504
- let last = node;
1505
- if (item && (data !== void 0 || item.p === scope && !fallbackKinds.includes(item.k))) {
1506
- if (data !== void 0) last = rangeEnd(node);
1507
- previous.set(key(item.i, position), {
1508
- scope: item,
1509
- first: node,
1510
- last,
1511
- position: position++,
1512
- kept: false,
1513
- still: false
1514
- });
1515
- } else (others ??= []).push(node);
1516
- node = last.nextSibling;
1517
- }
1518
- const count = items.length;
1519
- if (count === 0) {
1520
- if (previous.size === 0 && others) return;
1521
- for (const item of previous.values()) destroy(item.scope);
1522
- clear(start, end);
1523
- if (fallback) insertHTML(end, fallback(scope));
1524
- return;
1525
- }
1526
- disposeKinds(scope, fallbackKinds);
1527
- if (others) for (const node of others) node.parentNode?.removeChild(node);
1528
- const parent = end.parentNode;
1529
- const keys = Array.from({ length: count });
1530
- const kept = [];
1531
- for (let index = 0; index < count; index++) {
1532
- const id = keys[index] = key(items[index], index);
1533
- const item = previous.get(id);
1534
- if (item && !item.kept) {
1535
- item.kept = true;
1536
- kept.push(item);
1537
- }
1538
- }
1539
- markInPlace(kept);
1540
- if (kept.length === 0 && previous.size > 0) {
1541
- for (const item of previous.values()) destroy(item.scope);
1542
- previous.clear();
1543
- clear(start, end);
1544
- }
1545
- let cursor = start.nextSibling;
1546
- let added = "";
1547
- for (let index = 0; index < count; index++) {
1548
- const id = keys[index];
1549
- const item = previous.get(id);
1550
- if (!item) {
1551
- added += render(scope, items[index], index);
1552
- continue;
1553
- }
1554
- if (added) {
1555
- insertHTML(cursor, added);
1556
- added = "";
1557
- }
1558
- previous.delete(id);
1559
- assign(item.scope, items[index], index);
1560
- if (item.still) cursor = item.last.nextSibling;
1561
- else for (let node = item.first;;) {
1562
- const next = node.nextSibling;
1563
- parent.insertBefore(node, cursor);
1564
- if (node === item.last) break;
1565
- node = next;
1566
- }
1567
- }
1568
- if (added) insertHTML(cursor, added);
1569
- for (const item of previous.values()) {
1570
- destroy(item.scope);
1571
- for (let node = item.first; node;) {
1572
- const next = node === item.last ? null : node.nextSibling;
1573
- node.parentNode?.removeChild(node);
1574
- node = next;
1575
- }
1576
- }
1577
- }
1578
- /**
1579
- * Marks the items of a list that keep their places: the longest run of `kept`, the items that
1580
- * stay in their new order, whose old positions go up.
1581
- */
1582
- function markInPlace(kept) {
1583
- let sorted = true;
1584
- for (let index = 1; index < kept.length; index++) if (kept[index - 1].position > kept[index].position) {
1585
- sorted = false;
1586
- break;
1587
- }
1588
- if (sorted) {
1589
- for (const item of kept) item.still = true;
1590
- return;
1591
- }
1592
- const tails = [];
1593
- const before = [];
1594
- for (let index = 0; index < kept.length; index++) {
1595
- const position = kept[index].position;
1596
- let low = 0;
1597
- let high = tails.length;
1598
- while (low < high) {
1599
- const middle = low + high >> 1;
1600
- if (kept[tails[middle]].position < position) low = middle + 1;
1601
- else high = middle;
1602
- }
1603
- before[index] = low > 0 ? tails[low - 1] : -1;
1604
- tails[low] = index;
1605
- }
1606
- for (let index = tails.at(-1) ?? -1; index >= 0; index = before[index]) kept[index].still = true;
1607
- }
1608
- /** Sets a style variable on the top-level elements of a component instance. */
1609
- function setVar(scope, name, value) {
1610
- const css = value === null || value === void 0 || value === false ? "" : String(value);
1611
- for (const element of document.querySelectorAll(`[b-v="${scope.id}"]`)) if (element.style.getPropertyValue(name) !== css) element.style.setProperty(name, css);
1612
- }
1613
- /** The scope that provides a context to `scope`: itself or the nearest one above it. */
1614
- function findProvider(scope, key) {
1615
- for (let current = scope; current; current = current.t ?? current.p ?? current.o) if (current.v && key in current.v) return current;
1616
- }
1617
- /** Writes a provided value, and the slot of every scope that reads it from this provider. */
1618
- function updateContext(scope, context, value) {
1619
- scope.v ??= {};
1620
- scope.v[context.key] = value;
1621
- for (const target of scopes.values()) {
1622
- const slot = target.x?.[context.key];
1623
- if (slot !== void 0 && findProvider(target, context.key) === scope) set(target, slot, value);
1624
- }
1625
- }
1626
- /** Sets the title of the page. */
1627
- function title(value) {
1628
- setTitle(value === null || value === void 0 ? "" : String(value));
1629
- }
1630
- /**
1631
- * Sets `document.title`, which writes the first `<title>` of the document.
1632
- * The head gets a `<title>` of its own first, so a `<title>` in markup keeps its text.
1633
- */
1634
- function setTitle(text) {
1635
- if (!document.head.querySelector("title:not([b-t])")) document.head.prepend(document.createElement("title"));
1636
- document.title = text;
1637
- }
1638
- /** Watches the `<title>` elements of markup, once one is in the page. */
1639
- let titleObserver;
1640
- const PAGE_TITLE = "title[b-t]";
1641
- /** True when a node is or holds a `<title>` of markup. */
1642
- function holdsTitle(node) {
1643
- return node instanceof Element && (node.matches(PAGE_TITLE) || !!node.querySelector(PAGE_TITLE));
1644
- }
1645
- /** Gives the page the text of its last `<title>` in markup. Without one, the title stays. */
1646
- function syncTitle() {
1647
- const titles = document.querySelectorAll(PAGE_TITLE);
1648
- const last = titles[titles.length - 1];
1649
- if (last && document.title !== last.textContent) setTitle(last.textContent ?? "");
1650
- }
1651
- /**
1652
- * Starts to follow the `<title>` elements of markup, when `root` has one. A
1653
- * block that adds or removes one, or a change of its text, sets the title.
1654
- */
1655
- function watchTitles(root) {
1656
- if (titleObserver || !root.querySelector(PAGE_TITLE)) return;
1657
- titleObserver = new MutationObserver((records) => {
1658
- for (const record of records) if ((record.target instanceof Element ? record.target : record.target.parentElement)?.closest(PAGE_TITLE) || [...record.addedNodes].some(holdsTitle) || [...record.removedNodes].some(holdsTitle)) {
1659
- syncTitle();
1660
- return;
1661
- }
1662
- });
1663
- titleObserver.observe(document, {
1664
- childList: true,
1665
- subtree: true,
1666
- characterData: true
1667
- });
1668
- }
1669
- /** Writes a prop of a child component. */
1670
- const spreadKeys = /* @__PURE__ */ new WeakMap();
1671
- /**
1672
- * Updates the props of a child component from a spread. A key that the
1673
- * spread passed before and no longer has becomes undefined. `after` names
1674
- * the props after the spread, which win over it.
1675
- */
1676
- function spreadProps(scope, anchor, value, after) {
1677
- const byAnchor = spreadKeys.get(scope) ?? /* @__PURE__ */ new Map();
1678
- spreadKeys.set(scope, byAnchor);
1679
- const before = byAnchor.get(anchor) ?? /* @__PURE__ */ new Set();
1680
- const keys = new Set(Object.keys(value ?? {}).filter((key) => !after.includes(key)));
1681
- byAnchor.set(anchor, keys);
1682
- for (const key of keys) prop(scope, anchor, key, value[key]);
1683
- for (const key of before) if (!keys.has(key)) prop(scope, anchor, key, void 0);
1684
- }
1685
- function prop(scope, anchor, name, value) {
1686
- if (isBinding(value)) value = value.value;
1687
- const id = scope.c?.[anchor];
1688
- const child = id === void 0 ? void 0 : scopes.get(id);
1689
- if (!child?.m) return;
1690
- const apply = (module) => {
1691
- const slot = module.props[name];
1692
- if (slot !== void 0) {
1693
- if (isThenable(value)) asyncMemo(child, slot, Promise.resolve(value));
1694
- else writeSlot(child, slot, value);
1695
- return;
1696
- }
1697
- const all = module.props["*"];
1698
- if (all !== void 0) set(child, all, {
1699
- ...get(child, all),
1700
- [name]: value
1701
- });
1702
- };
1703
- const module = modules.get(child.m);
1704
- if (module) apply(module);
1705
- else loadModule(child.m, "prop").then(apply);
1706
- }
1707
- /** Runs an effect or a `$client` callback, after the cleanup of its previous run. */
1708
- function effect(scope, name, callback) {
1709
- if (hiding?.paused(scope, name)) return;
1710
- scope.cleanups ??= /* @__PURE__ */ new Map();
1711
- scope.cleanups.get(name)?.();
1712
- let cleanup;
1713
- const start = DEV ? performance.now() : 0;
1714
- try {
1715
- cleanup = callback();
1716
- } catch (error) {
1717
- fail(scope, error);
1718
- }
1719
- let stored = typeof cleanup === "function" ? cleanup : noop;
1720
- if (DEV) {
1721
- devtools()?.effect?.(scope, name, "run", performance.now() - start);
1722
- const own = stored;
1723
- stored = () => {
1724
- devtools()?.effect?.(scope, name, "cleanup", 0);
1725
- own();
1726
- };
1727
- }
1728
- scope.cleanups.set(name, stored);
1729
- }
1730
- function noop() {}
1731
- /** Renders the attributes of a form or button that posts to a server function. */
1732
- function action(name, id, method, result) {
1733
- return actionAttributes(rpcPrefix, name, id, method, result, build);
1734
- }
1735
- /**
1736
- * Sends a form of an `$action`. The code is in `rpc.ts`, which every server
1737
- * call loads, so the core holds only this.
1738
- */
1739
- function submitAction(form, submitter) {
1740
- import("./rpc-ygMRPmN4.js").then((module) => module.sendAction(form, submitter));
1741
- }
1742
- /** Calls a server function. */
1743
- async function rpc(id, args) {
1744
- const signal = memoSignal();
1745
- return track(import("./rpc-ygMRPmN4.js").then((module) => module.call(rpcPrefix, id, args, signal)));
1746
- }
1747
- /** Renders a value inserted in markup. Children render here, at `scope`, for their contexts. */
1748
- function insert(value, _ctx, scope) {
1749
- return value instanceof Children ? value.render(resolveScope(scope)) : insertValue(value);
1750
- }
1751
- /** Children that render where they are inserted, and the scopes that they find contexts from. */
1752
- const insertedChildren = [];
1753
- /**
1754
- * Children of a component that the client renders. They render where the
1755
- * component inserts them, so they read the contexts that it provides. `from`
1756
- * is the scope of the markup that wrote them.
1757
- */
1758
- var Children = class {
1759
- from;
1760
- html;
1761
- constructor(from, html) {
1762
- this.from = resolveScope(from);
1763
- this.html = html;
1764
- }
1765
- render(at) {
1766
- if (!at) return this.html();
1767
- const entry = {
1768
- from: this.from,
1769
- at
1770
- };
1771
- insertedChildren.push(entry);
1772
- try {
1773
- return this.html();
1774
- } finally {
1775
- insertedChildren.splice(insertedChildren.indexOf(entry), 1);
1776
- }
1777
- }
1778
- };
1779
- /** The children of a component that the client renders. See `Children`. */
1780
- function children(from, html) {
1781
- return new Children(from, html);
1782
- }
1783
- function resolveScope(scope) {
1784
- if (typeof scope === "object") return scope;
1785
- return scope === void 0 ? void 0 : scopes.get(scope);
1786
- }
1787
- /**
1788
- * Renders a child component on the client. With `scope` and `anchor`,
1789
- * records the child's scope so the parent can update its props.
1790
- */
1791
- function component(Child, props, _ctx, scope, anchor) {
1792
- const parent = resolveScope(scope);
1793
- if (parent && anchor !== void 0) {
1794
- parent.c ??= {};
1795
- parent.c[anchor] = nextId;
1796
- }
1797
- if (parent) setOwner(parent);
1798
- return Child(props);
1799
- }
1800
- function dynamic(tag, attributes, inner, _ctx, scope) {
1801
- if (typeof tag === "function") return component(tag, inner ? {
1802
- ...attributes,
1803
- children: inner
1804
- } : attributes, void 0, scope);
1805
- const name = String(tag);
1806
- const open = `<${name}${spread$1(attributes)}>`;
1807
- return VOID_ELEMENTS.has(name) ? open : `${open}${inner ? insert(inner, void 0, scope) : ""}</${name}>`;
1808
- }
1809
- /** Work that waits until rendered markup is in the page. */
1810
- const afterInsert = [];
1811
- /** The scope that renders the next component, which becomes its owner. */
1812
- let owner;
1813
- /** Creates a scope for markup that the client renders, and returns its ID. */
1814
- function createScope(kind, parent, module) {
1815
- const id = nextId--;
1816
- const parentScope = resolveScope(parent);
1817
- const created = {
1818
- id,
1819
- k: kind,
1820
- p: parentScope,
1821
- m: module,
1822
- s: [],
1823
- children: /* @__PURE__ */ new Set()
1824
- };
1825
- rendered.push(created);
1826
- if (module !== void 0 && owner) {
1827
- created.o = owner;
1828
- owner = void 0;
1829
- }
1830
- const up = created.o ?? parentScope;
1831
- for (let index = insertedChildren.length - 1; index >= 0; index--) if (insertedChildren[index].from === up) {
1832
- created.t = insertedChildren[index].at;
1833
- break;
1834
- }
1835
- parentScope?.children.add(created);
1836
- treeChanges++;
1837
- scopes.set(id, created);
1838
- return id;
1839
- }
1840
- /**
1841
- * The ID that `$id()` makes, as the server does. Client scope IDs are
1842
- * negative, so they differ from the server's.
1843
- */
1844
- function makeId(scope, index) {
1845
- return `b${String(resolveScope(scope).id).replace(/\./g, "_")}-${index}`;
1846
- }
1847
- /** Sets the owner of the next component's root scope. */
1848
- function setOwner(scope) {
1849
- owner = resolveScope(scope);
1850
- }
1851
- /** Provides a value of a context to the scopes inside `scope`. */
1852
- function provideValue(context, value, scope) {
1853
- const target = resolveScope(scope);
1854
- target.v ??= {};
1855
- target.v[context.key] = value;
1856
- }
1857
- /** Reads a context, and records its slot so that changes to the provided value reach it. */
1858
- function consumeContext(context, scope, slot) {
1859
- const target = resolveScope(scope);
1860
- if (slot !== void 0) {
1861
- target.x ??= {};
1862
- target.x[context.key] = slot;
1863
- }
1864
- const provider = findProvider(target, context.key);
1865
- if (provider) return provider.v[context.key];
1866
- if (context.key === "brumate.route" && !globals.has("brumate.route")) globals.set(ROUTE_KEY, currentRoute());
1867
- return globals.has(context.key) ? globals.get(context.key) : context.defaultValue;
1868
- }
1869
- /** The values of the contexts that the runtime provides to the whole page, by key. */
1870
- const globals = /* @__PURE__ */ new Map();
1871
- /** The route of the page: `location`, and the params of the route from the last page state. */
1872
- function currentRoute() {
1873
- const records = document.querySelectorAll("script[b-state][b-params]");
1874
- const params = records[records.length - 1]?.getAttribute("b-params");
1875
- const url = new URL(location.href);
1876
- return {
1877
- url,
1878
- search: url.searchParams,
1879
- params: params ? JSON.parse(params) : {}
1880
- };
1881
- }
1882
- /**
1883
- * Writes a context that the runtime provides to the whole page, and the
1884
- * slot of every scope that reads it without a provider above it.
1885
- */
1886
- function setGlobal(key, value) {
1887
- globals.set(key, value);
1888
- for (const target of scopes.values()) {
1889
- const slot = target.x?.[key];
1890
- if (slot !== void 0 && !findProvider(target, key)) set(target, slot, value);
1891
- }
1892
- }
1893
- /** Reads the route of the page again, after navigation changed it. */
1894
- function updateRoute() {
1895
- setGlobal(ROUTE_KEY, currentRoute());
1896
- }
1897
- /**
1898
- * Slots that the render of a component in the browser filled with a promise,
1899
- * by `scope:slot`. The first compute of their memo takes that promise
1900
- * instead of calling again, so a server function is called once per row.
1901
- */
1902
- const renderedLoads = /* @__PURE__ */ new Set();
1903
- function setSlots(id, values) {
1904
- scopes.get(id).s = values;
1905
- for (let slot = 0; slot < values.length; slot++) {
1906
- const value = values[slot];
1907
- if (isThenable(value)) {
1908
- renderedLoads.add(`${id}:${slot}`);
1909
- Promise.resolve(value).catch(noop);
1910
- }
1911
- }
1912
- }
1913
- function setItem(id, value) {
1914
- scopes.get(id).i = value;
1915
- }
1916
- function elementAt(scope, anchor) {
1917
- return new ElementReference(scope, anchor);
1918
- }
1919
- /**
1920
- * Warns in development that the browser renders a `#defer` block of a
1921
- * component, such as inside a `#client` body of its parent. Only the server
1922
- * renders the body, so the fallback stays.
1923
- */
1924
- function deferInBrowser(id) {
1925
- if (DEV) console.warn(`${id} renders a #defer block in the browser, so it shows its fallback only. Render the component in markup that the server renders.`);
1926
- }
1927
- /** Adds the markup of a `#head` block to the document's head. */
1928
- function addHead(html) {
1929
- afterInsert.push(() => insertHTML({ parent: document.head }, html));
1930
- }
1931
- /** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */
1932
- function addPortal(html) {
1933
- afterInsert.push(() => insertHTML({ parent: document.body }, html));
1934
- }
1935
- /** Adds a component's stylesheet to the page, if the server did not. */
1936
- function addStyle(id, css) {
1937
- if (!document.querySelector(`style[b-style="${id}"]`)) {
1938
- const sheet = document.createElement("style");
1939
- sheet.setAttribute("b-style", id);
1940
- sheet.textContent = css;
1941
- document.head.append(sheet);
1942
- }
1943
- return "";
1944
- }
1945
- /** A function prop rendered on the client calls the parent's exported handler. */
1946
- function handlerProp(value, ref, scope, bound = [], modifiers) {
1947
- if (typeof value !== "function" || isTemplate(ref)) return value;
1948
- const instance = resolveScope(scope);
1949
- const handler = (...args) => call(ref, instance, [...bound, ...args]);
1950
- handlerReferences.set(handler, new FunctionReference(ref, instance?.id ?? scope, bound.length > 0 ? bound : void 0, modifiers ?? value[MODIFIERS]));
1951
- return handler;
1952
- }
1953
- /**
1954
- * What the loader calls. It is one export, so the loader's import of the core
1955
- * names one export, and a build keeps the rest only when components call them.
1956
- */
1957
- const loader = {
1958
- init,
1959
- handle,
1960
- dispose,
1961
- submitAction,
1962
- setGlobal,
1963
- updateRoute
1964
- };
1965
- //#endregion
1966
- export { removeScope as $, guess as A, loadModule as B, dynamic as C, writeText as Ct, fill as D, fail as E, insert as F, offscreen as G, loader as H, leavePage as I, prop as J, pending as K, leaveRoutes as L, handlerProp as M, hooks as N, forget as O, init as P, removeRoot as Q, list as R, dispose as S, updated as St, elementAt as T, makeId as U, loadPart as V, memo as W, rekey as X, provideValue as Y, remount as Z, consumeContext as _, title as _t, addStyle as a, set as at, deferInBrowser as b, updateContext as bt, attr as c, setOwner as ct, bindings as d, skew as dt, reset as et, branch as f, spread as ft, component as g, timed as gt, children as h, text as ht, addPortal as i, scopes as it, handle as j, get as k, attrs as l, setSlots as lt, cells as m, submitAction as mt, action as n, rpcPrefix as nt, afterInsert as o, setGlobal as ot, build as p, spreadProps as pt, portalTo as q, addHead as r, scopeOf as rt, asyncMemo as s, setItem as st, DEVTOOLS as t, rpc as tt, binding as u, setVar as ut, content as v, track as vt, effect as w, descendants as x, updateRoute as xt, createScope as y, update as yt, listOf as z };
1967
-
1968
- //# sourceMappingURL=client-BD6XT-s5.js.map