brumate 0.0.1 → 0.1.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 (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-BBLPU9JR.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-BBLPU9JR.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +63 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-CRZlO11T.js} +743 -163
  22. package/dist/inspect-CRZlO11T.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
@@ -1,17 +1,27 @@
1
- import { a as attributeText, c as insertValue, d as rawHTML, f as spread, i as attribute, l as isRaw, m as vars, n as actionAttributes, o as escape, r as affix, t as VOID_ELEMENTS, u as raw } from "../html-CxWpXngy.js";
2
- import { i as disabledFeatures, n as FunctionReference, o as isAsyncIterable, s as plugins, t as ElementReference } from "../shared-BE_oBSDM.js";
1
+ import { _ as vars, a as attributeText, c as escape, f as raw, g as textValue, i as attribute, m as spread, n as actionAttributes, o as classAttribute, p as rawHTML, r as affix, t as VOID_ELEMENTS, u as insertValue } from "../html-DEeoepg3.js";
2
+ import { i as stateValues, n as FunctionReference, r as isAsyncIterable, t as ElementReference } from "../shared-CWYOd0H3.js";
3
3
  import { t as produce } from "../produce-BRGHP7e0.js";
4
4
  import { t as createContext } from "../context-BG8KCF3v.js";
5
- import { fromCrossJSON } from "seroval";
6
5
  //#region src/runtime/client.ts
7
6
  /** The part that holds an export: `h<n>` and `c<n>` have their own, the rest are in `update`. */
8
7
  function partOf(name) {
9
8
  return /^[hc]\d/.test(name) ? name : "update";
10
9
  }
11
10
  let options;
11
+ /** The URL prefix of server function calls, from the options. */
12
+ let rpcPrefix = "/_brumate";
13
+ /** The scopes of the page, by ID. */
12
14
  const scopes = /* @__PURE__ */ new Map();
15
+ /** What modules of optional features add to the core. See `client-routes.ts` and `hot`. */
16
+ const hooks = {};
13
17
  /** The global key of the devtools hooks. */
14
18
  const DEVTOOLS = Symbol.for("brumate.devtools");
19
+ /**
20
+ * True on the dev server, which has the devtools. A Vite build replaces it
21
+ * with `false`, so the calls of the devtools hooks are left out. Without
22
+ * Vite, `import.meta.env` is undefined, and the hooks are off.
23
+ */
24
+ const DEV = import.meta.env?.DEV;
15
25
  function devtools() {
16
26
  return globalThis[DEVTOOLS];
17
27
  }
@@ -23,27 +33,32 @@ const comments = /* @__PURE__ */ new Map();
23
33
  const elements = /* @__PURE__ */ new Map();
24
34
  let nextId = -1;
25
35
  const refs = /* @__PURE__ */ new Map();
26
- const read = /* @__PURE__ */ new WeakSet();
36
+ /**
37
+ * The records that ran before the core started, or while it stopped. Each
38
+ * state script hands its record to `push`, which the core replaces while it
39
+ * runs, so it reads later records at once.
40
+ */
41
+ function stateQueue() {
42
+ const global = globalThis;
43
+ return global.$brm ??= [];
44
+ }
45
+ /** Reads the records that later state scripts hand over. Set while the core runs. */
46
+ function pushRecords(...added) {
47
+ for (const record of added) readRecord(record);
48
+ return 0;
49
+ }
27
50
  /**
28
51
  * Reads a state record. The first record holds the page state, and later
29
52
  * records settle the promises in it.
30
53
  */
31
- function readRecord(script) {
32
- if (read.has(script)) return;
33
- read.add(script);
34
- const root = script.getAttribute("data-root") ?? "0";
35
- if (!refs.has(root)) refs.set(root, /* @__PURE__ */ new Map());
36
- const decoded = fromCrossJSON(JSON.parse(script.textContent), {
37
- plugins,
38
- disabledFeatures,
39
- refs: refs.get(root)
40
- });
41
- const offset = Number(script.getAttribute("data-offset") ?? 0);
42
- const value = offset && script.hasAttribute("data-scopes") ? shiftState(decoded, offset) : decoded;
43
- if (script.hasAttribute("data-scopes")) {
44
- const drop = script.getAttribute("data-drop");
45
- if (drop) dropScopes(new Set(drop.split(",").map(Number)));
46
- const added = addScopes(value, routeOptions(script));
54
+ function readRecord([script, code]) {
55
+ if (!script?.isConnected) return;
56
+ const root = script.getAttribute("b-root") ?? "0";
57
+ if (!refs.has(root)) refs.set(root, []);
58
+ const decoded = code(refs.get(root), stateValues);
59
+ if (script.hasAttribute("b-scopes")) {
60
+ const unpacked = unpackState(decoded);
61
+ const added = addScopes(hooks.record ? hooks.record(script, unpacked) : unpacked, root);
47
62
  if (writes > 0) refresh(added);
48
63
  }
49
64
  }
@@ -65,70 +80,57 @@ function refresh(added) {
65
80
  });
66
81
  }
67
82
  }
68
- /** Adds a number to the scope IDs of a state record. */
69
- function shiftState(state, by) {
70
- const seen = /* @__PURE__ */ new Set();
71
- const shiftValue = (value) => {
72
- if (value instanceof ElementReference) return new ElementReference(value.scope + by, value.anchor);
73
- if (value instanceof FunctionReference) return new FunctionReference(value.ref, value.scope + by);
74
- if (value instanceof Promise) return value.then(shiftValue);
75
- if (typeof value === "object" && value !== null && !seen.has(value)) {
76
- seen.add(value);
77
- if (Array.isArray(value)) value.forEach((item, index) => {
78
- value[index] = shiftValue(item);
79
- });
80
- else if (Object.getPrototypeOf(value) === Object.prototype) for (const [key, item] of Object.entries(value)) value[key] = shiftValue(item);
83
+ /** Reads the groups of scope records back into one record per scope. See `PackedState`. */
84
+ function unpackState(state) {
85
+ const taken = [];
86
+ for (const group of state.g ?? []) {
87
+ const [k, base, flags] = group;
88
+ const count = group[3];
89
+ let at = 4;
90
+ const m = flags & 16 ? group[at++] : void 0;
91
+ const source = flags & 32 ? [] : void 0;
92
+ if (source) taken.push([
93
+ source,
94
+ group[at++],
95
+ group[at++],
96
+ flags & 1
97
+ ]);
98
+ const skip = source && flags & 1 ? 1 : 0;
99
+ let id = flags & 8 ? 0 : base;
100
+ while (at < group.length) {
101
+ id += group[at++];
102
+ const s = group.slice(at - skip, at += count - skip);
103
+ const record = flags & 8 ? {
104
+ k,
105
+ o: id - base
106
+ } : {
107
+ k,
108
+ p: base
109
+ };
110
+ record.s = s;
111
+ if (m !== void 0) record.m = m;
112
+ if (source) source.push(record);
113
+ else if (flags & 1) record.i = s[0];
114
+ else if (flags & 2) record.i = group[at++];
115
+ if (flags & 4) record.c = group[at++];
116
+ state[id] = record;
81
117
  }
82
- return value;
83
- };
84
- const result = {};
85
- for (const [key, record] of Object.entries(state)) result[Number(key) + by] = {
86
- ...record,
87
- p: record.p === void 0 ? void 0 : record.p + by,
88
- o: record.o === void 0 ? void 0 : record.o + by,
89
- c: record.c && Object.fromEntries(Object.entries(record.c).map(([anchor, id]) => [anchor, id + by])),
90
- s: record.s?.map(shiftValue)
91
- };
92
- return result;
93
- }
94
- function routeOptions(script) {
95
- const roots = script.getAttribute("data-roots");
96
- if (roots === null) return;
97
- const alias = /* @__PURE__ */ new Map();
98
- for (const pair of (script.getAttribute("data-alias") ?? "").split(",").filter(Boolean)) {
99
- const [from, to] = pair.split(":").map(Number);
100
- alias.set(from, to);
101
118
  }
102
- return {
103
- alias,
104
- roots: new Set(roots.split(",").filter(Boolean).map(Number))
105
- };
106
- }
107
- /** Removes scopes and the scopes inside them, and runs their cleanups. */
108
- function dropScopes(roots) {
109
- const inside = (scope) => {
110
- for (let current = scope; current; current = current.p ?? current.o) if (roots.has(current.id)) return true;
111
- return false;
112
- };
113
- for (const scope of scopes.values()) if (inside(scope)) {
114
- for (const cleanup of scope.cleanups?.values() ?? []) cleanup();
115
- scope.p?.children.delete(scope);
116
- scopes.delete(scope.id);
119
+ delete state.g;
120
+ for (const [records, source, slot, first] of taken) {
121
+ const values = Array.from(state[source].s[slot]);
122
+ for (let n = 0; n < records.length; n++) {
123
+ const record = records[n];
124
+ record.i = values[n];
125
+ if (first) record.s[0] = values[n];
126
+ }
117
127
  }
128
+ return state;
118
129
  }
119
- function addScopes(state, route) {
130
+ function addScopes(state, root) {
120
131
  const added = [];
121
- const kept = (id) => {
122
- for (let current = id; current !== void 0;) {
123
- if (route.roots.has(current)) return true;
124
- const record = state[current];
125
- current = record?.p ?? record?.o;
126
- }
127
- return false;
128
- };
129
132
  for (const [key, record] of Object.entries(state)) {
130
133
  const id = Number(key);
131
- if (route && !kept(id)) continue;
132
134
  const scope = {
133
135
  id,
134
136
  k: record.k ?? 0,
@@ -138,19 +140,20 @@ function addScopes(state, route) {
138
140
  c: record.c,
139
141
  v: record.v,
140
142
  x: record.x,
141
- children: /* @__PURE__ */ new Set()
143
+ children: /* @__PURE__ */ new Set(),
144
+ r: root
142
145
  };
143
146
  scopes.set(id, scope);
144
147
  added.push(scope);
145
148
  }
146
- const resolveId = (id) => route?.alias.get(id) ?? id;
147
149
  for (const scope of added) {
148
150
  const record = state[scope.id];
149
151
  if (record.p !== void 0) {
150
- scope.p = scopes.get(resolveId(record.p));
152
+ scope.p = scopes.get(record.p);
151
153
  scope.p?.children.add(scope);
154
+ treeChanges++;
152
155
  }
153
- if (record.o !== void 0) scope.o = scopes.get(resolveId(record.o));
156
+ if (record.o !== void 0) scope.o = scopes.get(record.o);
154
157
  }
155
158
  const seen = /* @__PURE__ */ new Set();
156
159
  for (const scope of added) {
@@ -164,25 +167,51 @@ function addScopes(state, route) {
164
167
  });
165
168
  }
166
169
  }
167
- if (remounts.size > 0) restoreRemounts(added);
170
+ hooks.added?.(added);
168
171
  return added;
169
172
  }
170
- const STATE = "script[type=\"brumate/state\"]";
171
- let observer;
172
- /** Stops reading state records that arrive later. */
173
+ /**
174
+ * Indexes the markers of markup that others insert, such as streamed
175
+ * `#loading` bodies and the pages that navigation adds, so `findComment` can
176
+ * take its records at once.
177
+ */
178
+ let markerObserver;
179
+ /** Stops reading state records and markers that arrive later. Later records wait for `init`. */
173
180
  function dispose() {
174
- observer?.disconnect();
175
- observer = void 0;
176
- document.removeEventListener("brumate:refresh", onRefresh);
177
- document.removeEventListener("brumate:hot", onHot);
178
- document.removeEventListener("brumate:remount", onRemount);
181
+ const queue = stateQueue();
182
+ if (queue.push === pushRecords) delete queue.push;
183
+ markerObserver?.disconnect();
184
+ markerObserver = void 0;
185
+ }
186
+ /**
187
+ * Stops reading, before client navigation replaces only some routes. The
188
+ * server renders the new routes with its current values, so only the writes
189
+ * that come after count for the records that stream in later.
190
+ */
191
+ function leaveRoutes() {
192
+ dispose();
193
+ writes = 0;
194
+ }
195
+ /**
196
+ * Removes the scopes of a render, by its `b-root`, with the scopes inside
197
+ * them. Their cleanups run, and their memos no longer load. Its markup
198
+ * stays. `brumate/testing` calls it when a mounted component unmounts.
199
+ */
200
+ function removeRoot(root) {
201
+ const inside = (scope) => {
202
+ for (let current = scope; current; current = current.p ?? current.o) if (current.r === root) return true;
203
+ return false;
204
+ };
205
+ for (const scope of scopes.values()) if (inside(scope)) removeScope(scope);
206
+ refs.delete(root);
207
+ for (const cache of [comments, elements]) for (const [key, node] of cache) if (!node.isConnected) cache.delete(key);
179
208
  }
180
209
  /**
181
210
  * Forgets the code of components that changed on the dev server, so the next
182
- * event or update loads the new code. Their state stays. See `brumate/hot`.
211
+ * event or update loads the new code. Their state stays. `brumate/hot` calls it.
183
212
  */
184
- function onHot(event) {
185
- for (const id of event.detail) {
213
+ function forget(ids) {
214
+ for (const id of ids) {
186
215
  modules.delete(id);
187
216
  loading.delete(id);
188
217
  for (const key of parts.keys()) if (key.startsWith(`${id}:`)) {
@@ -195,10 +224,10 @@ function onHot(event) {
195
224
  const remounts = /* @__PURE__ */ new Map();
196
225
  /**
197
226
  * Keeps the values of the signals of each instance of a component, by
198
- * name, before the page renders again with its new markup.
227
+ * name, before the page renders again with its new markup. `brumate/hot` calls it.
199
228
  */
200
- function onRemount(event) {
201
- const detail = event.detail;
229
+ function remount(detail) {
230
+ hooks.added = restoreRemounts;
202
231
  for (const { id, before, after, signals } of detail) {
203
232
  const names = new Set(signals);
204
233
  const instances = [...scopes.values()].filter((scope) => scope.m === id);
@@ -228,26 +257,10 @@ function restoreRemounts(added) {
228
257
  });
229
258
  }
230
259
  }
231
- function onRefresh(event) {
232
- refreshMemos(event.detail);
233
- }
234
- /**
235
- * Loads again the memos that call these server functions, after a server
236
- * function named them with `refresh`. Each component on the page knows its
237
- * own memos, from its client module.
238
- */
239
- function refreshMemos(ids) {
240
- const roots = [...scopes.values()].filter((scope) => scope.m);
241
- for (const root of roots) loadModule(root.m).then(async (module) => {
242
- const entries = ids.flatMap((id) => module.refresh?.[id] ?? []);
243
- if (entries.length === 0) return;
244
- const updates = await loadPart(module, "update");
245
- for (const [kind, name] of entries) for (const target of kind === root.k ? [root] : descendants(root, kind)) if (scopes.has(target.id)) updates[name](target);
246
- });
247
- }
248
260
  /**
249
261
  * Forgets the page, before another page replaces it. Cleanups run. Loaded
250
- * modules and parts stay, so the next page does not load them again.
262
+ * modules and parts stay, so the next page does not load them again. Only
263
+ * client navigation calls it.
251
264
  */
252
265
  function leavePage() {
253
266
  dispose();
@@ -256,34 +269,33 @@ function leavePage() {
256
269
  comments.clear();
257
270
  elements.clear();
258
271
  pendingEffects.clear();
272
+ hiding = void 0;
259
273
  loads.clear();
260
274
  loadingSlots.clear();
275
+ for (const memoController of memoControllers.values()) memoController.abort();
276
+ memoControllers.clear();
277
+ guesses?.map.clear();
261
278
  nextId = -1;
262
279
  refs.clear();
263
280
  writes = 0;
281
+ calling = 0;
282
+ callEpoch++;
264
283
  lastHandler = Promise.resolve();
265
284
  }
266
285
  /** Reads the page state. The loader calls it once, before the first handler. */
267
286
  function init(value) {
268
287
  options = value;
269
- for (const script of document.querySelectorAll(STATE)) readRecord(script);
270
- observer = new MutationObserver((records) => {
271
- for (const record of records) for (const node of record.addedNodes) {
272
- if (node.nodeType !== 1) continue;
273
- const element = node;
274
- if (element.matches(STATE)) readRecord(element);
275
- else element.querySelectorAll(STATE).forEach(readRecord);
276
- }
277
- });
278
- observer.observe(document, {
288
+ rpcPrefix = value.rpc ?? "/_brumate";
289
+ const queue = stateQueue();
290
+ queue.push = pushRecords;
291
+ for (const record of queue.splice(0)) readRecord(record);
292
+ markerObserver = new MutationObserver(indexAdded);
293
+ markerObserver.observe(document, {
279
294
  childList: true,
280
295
  subtree: true
281
296
  });
282
- document.addEventListener("brumate:refresh", onRefresh);
283
- document.addEventListener("brumate:hot", onHot);
284
- document.addEventListener("brumate:remount", onRemount);
285
297
  indexMarkers(document.documentElement);
286
- devtools()?.attach?.({
298
+ if (DEV) devtools()?.attach?.({
287
299
  scopes,
288
300
  set
289
301
  });
@@ -304,7 +316,12 @@ function callable(value, seen) {
304
316
  function loadModule(id) {
305
317
  let promise = loading.get(id);
306
318
  if (!promise) {
307
- promise = options.load(id).then((module) => {
319
+ promise = Promise.resolve(options.load(id)).then((loaded) => {
320
+ const module = loaded ?? {
321
+ id,
322
+ props: {},
323
+ g: {}
324
+ };
308
325
  modules.set(id, module);
309
326
  return module;
310
327
  });
@@ -316,9 +333,9 @@ function loadPart(module, name) {
316
333
  const key = `${module.id}:${name}`;
317
334
  let promise = parts.get(key);
318
335
  if (!promise) {
319
- promise = module.load(name).then((part) => {
336
+ promise = (module.load ? module.load(name) : Promise.resolve(module)).then((part) => {
320
337
  loadedParts.set(key, part);
321
- devtools()?.part?.(module.id, name);
338
+ if (DEV) devtools()?.part?.(module.id, name);
322
339
  return part;
323
340
  });
324
341
  parts.set(key, promise);
@@ -344,12 +361,17 @@ function withTarget(event, element) {
344
361
  return typeof value === "function" ? value.bind(target) : value;
345
362
  } });
346
363
  }
347
- /** Runs the handler `ref` for an element with a `data-b` anchor. */
364
+ /**
365
+ * Runs the handler `ref` for an element. The scope comes from the element's
366
+ * `b-b` anchor, or from the nearest element around it that has one, which
367
+ * the compiler checks is in the same scope.
368
+ */
348
369
  function handle(element, ref, event) {
349
- const anchor = element.getAttribute("data-b");
370
+ const anchor = element.closest("[b-b]")?.getAttribute("b-b");
350
371
  const scope = anchor ? scopes.get(Number(anchor.split(":")[0])) : void 0;
372
+ if (scope && hiding?.hidden(scope) && element.hasAttribute("b-listen")) return Promise.resolve();
351
373
  const args = event ? [withTarget(event, element)] : [];
352
- devtools()?.handler?.(ref, element, event);
374
+ if (DEV) devtools()?.handler?.(ref, element, event);
353
375
  const loaded = resolve(ref);
354
376
  const started = lastHandler.then(() => loaded).then((handler) => ({ value: handler(scope, ...args) }));
355
377
  lastHandler = started.catch(() => {});
@@ -374,7 +396,7 @@ function set(scope, slot, value) {
374
396
  if (!Object.is(scope.s[slot], value)) {
375
397
  writes++;
376
398
  scope.s[slot] = value;
377
- devtools()?.write?.(scope, slot, value);
399
+ if (DEV) devtools()?.write?.(scope, slot, value);
378
400
  trigger(scope, slot);
379
401
  }
380
402
  return value;
@@ -407,19 +429,28 @@ function cells(scope, links, names) {
407
429
  return result;
408
430
  }
409
431
  const loads = /* @__PURE__ */ new Map();
432
+ let loadCount = 0;
410
433
  const loadingSlots = /* @__PURE__ */ new Set();
434
+ /** Marks a memo as loading. Its readers update the first time, so `$isPending` becomes true. */
435
+ function startLoading(scope, slot, key) {
436
+ if (!loadingSlots.has(key)) {
437
+ loadingSlots.add(key);
438
+ trigger(scope, slot);
439
+ }
440
+ }
441
+ /** True for a promise, or any object with a `then` method. */
442
+ function isThenable(value) {
443
+ return value !== null && typeof value === "object" && typeof value.then === "function";
444
+ }
411
445
  /**
412
446
  * Writes the result of an async memo when it arrives. Until then the slot
413
447
  * keeps its value, and `pending` is true. Only the latest load is written.
414
448
  */
415
449
  function asyncMemo(scope, slot, promise) {
416
450
  const key = `${scope.id}:${slot}`;
417
- const load = (loads.get(key) ?? 0) + 1;
451
+ const load = ++loadCount;
418
452
  loads.set(key, load);
419
- if (!loadingSlots.has(key)) {
420
- loadingSlots.add(key);
421
- trigger(scope, slot);
422
- }
453
+ startLoading(scope, slot, key);
423
454
  const settle = (value, failed = false) => {
424
455
  if (loads.get(key) !== load) return;
425
456
  loadingSlots.delete(key);
@@ -450,7 +481,6 @@ function asyncMemo(scope, slot, promise) {
450
481
  })();
451
482
  }, fail);
452
483
  }
453
- /** Writes a new value of a memo. A promise is loaded with `asyncMemo`. */
454
484
  /** Thrown when a memo reads a value that is still loading. */
455
485
  var NotReady = class extends Error {
456
486
  source;
@@ -462,8 +492,18 @@ var NotReady = class extends Error {
462
492
  let computing = 0;
463
493
  /** Aborts the server function calls of a memo's compute, by memo key. */
464
494
  const memoControllers = /* @__PURE__ */ new Map();
465
- /** The signal for server function calls while a memo computes. */
466
- let memoSignal;
495
+ /** The key of the memo that computes, if any. */
496
+ let memoKey;
497
+ /** The signal for server function calls while a memo computes. It is made on the first call. */
498
+ function memoSignal() {
499
+ if (memoKey === void 0) return;
500
+ let controller = memoControllers.get(memoKey);
501
+ if (!controller) {
502
+ controller = new AbortController();
503
+ memoControllers.set(memoKey, controller);
504
+ }
505
+ return controller.signal;
506
+ }
467
507
  /**
468
508
  * Computes a memo. A promise loads, and the memo keeps its value until it
469
509
  * settles. A memo that reads a value that is still loading keeps its value
@@ -471,50 +511,51 @@ let memoSignal;
471
511
  */
472
512
  function memo(scope, slot, compute) {
473
513
  const key = `${scope.id}:${slot}`;
474
- if (sameSource(key)) return;
514
+ if (guesses?.same(key)) return;
475
515
  let value;
476
516
  memoControllers.get(key)?.abort();
477
- const controller = new AbortController();
478
- memoControllers.set(key, controller);
479
- const outer = memoSignal;
480
- memoSignal = controller.signal;
517
+ memoControllers.delete(key);
518
+ const outer = memoKey;
519
+ memoKey = key;
481
520
  computing++;
482
521
  try {
483
522
  value = compute();
484
523
  } catch (error) {
485
524
  if (!(error instanceof NotReady)) throw error;
486
- if (!loadingSlots.has(key)) {
487
- loadingSlots.add(key);
488
- trigger(scope, slot);
489
- }
525
+ startLoading(scope, slot, key);
490
526
  return;
491
527
  } finally {
492
528
  computing--;
493
- memoSignal = outer;
529
+ memoKey = outer;
494
530
  }
495
- if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
531
+ if (isThenable(value) || isAsyncIterable(value)) {
496
532
  asyncMemo(scope, slot, Promise.resolve(value));
497
533
  return;
498
534
  }
499
535
  const waited = loadingSlots.delete(key);
500
536
  loads.delete(key);
501
- guesses.delete(key);
537
+ guesses?.map.delete(key);
502
538
  if (!Object.is(scope.s[slot], value)) set(scope, slot, value);
503
539
  else if (waited) trigger(scope, slot);
504
540
  }
505
- /** Optimistic values that hold a guess, with the slot that each goes back to. */
506
- const guesses = /* @__PURE__ */ new Map();
541
+ /**
542
+ * The guesses of `$optimistic` values. The first `guess` sets it, so the
543
+ * code that reads guesses is left out of a build that makes none.
544
+ */
545
+ let guesses;
507
546
  /** The values of promises that the server streamed, so a guess knows its source did not change. */
508
547
  const settled = /* @__PURE__ */ new WeakMap();
509
548
  /** True while the source of a guess holds the value it had when the guess was made. */
510
549
  function sameSource(key) {
511
- const entry = guesses.get(key);
550
+ const entry = guesses.map.get(key);
512
551
  if (!entry?.source) return false;
513
552
  const current = entry.source[0].s[entry.source[1]];
514
553
  return Object.is(current, entry.base) || entry.base instanceof Promise && settled.get(entry.base) === current;
515
554
  }
516
555
  /** Server calls that have not finished, from forms and from `rpc`. */
517
556
  let calling = 0;
557
+ /** Counts the pages that client navigation left, so calls of an old page are not counted down. */
558
+ let callEpoch = 0;
518
559
  /**
519
560
  * Writes a guess into an optimistic value. It goes back to its source when
520
561
  * the source changes, which computes it again, or when every server call of
@@ -524,7 +565,12 @@ function guess(scope, slot, ...rest) {
524
565
  const value = rest.at(-1);
525
566
  const source = rest.length === 3 ? [rest[0], rest[1]] : void 0;
526
567
  const base = source && source[0].s[source[1]];
527
- guesses.set(`${scope.id}:${slot}`, {
568
+ guesses ??= {
569
+ map: /* @__PURE__ */ new Map(),
570
+ same: sameSource,
571
+ reset: resetGuesses
572
+ };
573
+ guesses.map.set(`${scope.id}:${slot}`, {
528
574
  scope,
529
575
  slot,
530
576
  source,
@@ -535,18 +581,19 @@ function guess(scope, slot, ...rest) {
535
581
  /** Counts a server call, and puts guesses back when the last one finishes. */
536
582
  function track(request) {
537
583
  calling++;
584
+ const epoch = callEpoch;
538
585
  const done = () => {
586
+ if (epoch !== callEpoch) return;
539
587
  calling--;
540
- setTimeout(resetGuesses, 0);
588
+ setTimeout(() => calling || guesses?.reset(), 0);
541
589
  };
542
590
  request.then(done, done);
543
591
  return request;
544
592
  }
545
593
  function resetGuesses() {
546
- if (calling > 0) return;
547
- for (const [key, { scope, slot, source }] of guesses) {
594
+ for (const [key, { scope, slot, source }] of guesses.map) {
548
595
  if (source && pending(source[0], source[1])) continue;
549
- guesses.delete(key);
596
+ guesses.map.delete(key);
550
597
  if (source && scopes.has(scope.id) && !Object.is(scope.s[slot], source[0].s[source[1]])) set(scope, slot, source[0].s[source[1]]);
551
598
  }
552
599
  }
@@ -580,21 +627,43 @@ function trigger(scope, slot) {
580
627
  const pendingEffects = /* @__PURE__ */ new Map();
581
628
  let running = 0;
582
629
  let flushing = false;
630
+ /** Counts changes to the scope tree, so `run` knows when the descendants it found are out of date. */
631
+ let treeChanges = 0;
583
632
  function run(module, updates, scope, slot) {
584
633
  running++;
634
+ let found;
635
+ let foundAt = treeChanges;
585
636
  try {
586
637
  for (const [kind, name] of module.g[scope.k]?.[slot] ?? []) {
587
638
  const fn = updates[name];
588
- for (const target of kind === scope.k ? [scope] : descendants(scope, kind)) if (name[0] === "e") pendingEffects.set(`${target.id}:${name}`, () => {
589
- if (scopes.has(target.id)) fn(target);
590
- });
591
- else fn(target);
639
+ if (kind === scope.k) {
640
+ runUpdate(fn, name, scope);
641
+ continue;
642
+ }
643
+ if (foundAt !== treeChanges) {
644
+ found = void 0;
645
+ foundAt = treeChanges;
646
+ }
647
+ found ??= /* @__PURE__ */ new Map();
648
+ let targets = found.get(kind);
649
+ if (!targets) {
650
+ targets = descendants(scope, kind);
651
+ found.set(kind, targets);
652
+ }
653
+ for (const target of targets) runUpdate(fn, name, target);
592
654
  }
593
655
  } finally {
594
656
  running--;
595
657
  }
596
658
  if (running === 0) flushEffects();
597
659
  }
660
+ /** Runs an update on a scope. An effect waits until the other updates have run. */
661
+ function runUpdate(fn, name, target) {
662
+ if (name[0] === "e") pendingEffects.set(`${target.id}:${name}`, () => {
663
+ if (scopes.has(target.id)) fn(target);
664
+ });
665
+ else fn(target);
666
+ }
598
667
  /**
599
668
  * Runs the effects that writes scheduled, in the order they were first
600
669
  * scheduled. Writes in an effect schedule more effects, which run after.
@@ -603,8 +672,7 @@ function flushEffects() {
603
672
  if (flushing) return;
604
673
  flushing = true;
605
674
  try {
606
- for (let next = pendingEffects.entries().next(); !next.done; next = pendingEffects.entries().next()) {
607
- const [key, runEffect] = next.value;
675
+ for (const [key, runEffect] of pendingEffects) {
608
676
  pendingEffects.delete(key);
609
677
  runEffect();
610
678
  }
@@ -628,9 +696,26 @@ function destroy(scope) {
628
696
  start.remove();
629
697
  end.remove();
630
698
  }
699
+ removeScope(scope);
700
+ }
701
+ /**
702
+ * Removes a scope from the page: its cleanups run, and its memo state goes,
703
+ * so a load that settles later is not written. Its markup stays.
704
+ */
705
+ function removeScope(scope) {
631
706
  for (const cleanup of scope.cleanups?.values() ?? []) cleanup();
707
+ for (let slot = 0; slot < scope.s.length; slot++) {
708
+ const key = `${scope.id}:${slot}`;
709
+ memoControllers.get(key)?.abort();
710
+ memoControllers.delete(key);
711
+ loads.delete(key);
712
+ loadingSlots.delete(key);
713
+ guesses?.map.delete(key);
714
+ }
715
+ if (scope.h) hiding?.bodies.delete(scope.h);
632
716
  scopes.delete(scope.id);
633
717
  scope.p?.children.delete(scope);
718
+ treeChanges++;
634
719
  }
635
720
  function disposeKinds(scope, kinds) {
636
721
  for (const child of Array.from(scope.children)) if (kinds.includes(child.k)) destroy(child);
@@ -646,6 +731,11 @@ function indexMarkers(root) {
646
731
  if (MARKER.test(data)) comments.set(markerKey(data), node);
647
732
  }
648
733
  }
734
+ /** Indexes the markers in the nodes that mutation records added. */
735
+ function indexAdded(records) {
736
+ for (const record of records) for (const node of record.addedNodes) if (node.nodeType === 1) indexMarkers(node);
737
+ else if (node.nodeType === 8 && MARKER.test(node.data)) comments.set(markerKey(node.data), node);
738
+ }
649
739
  /**
650
740
  * Finds a marker in the page. Returns undefined when the markup is not in
651
741
  * the page, such as `children` inside a block that is closed. Updates to it
@@ -654,7 +744,8 @@ function indexMarkers(root) {
654
744
  function findComment(key) {
655
745
  let comment = comments.get(key);
656
746
  if (!comment?.isConnected) {
657
- indexMarkers(document.documentElement);
747
+ if (markerObserver) indexAdded(markerObserver.takeRecords());
748
+ else indexMarkers(document.documentElement);
658
749
  comment = comments.get(key);
659
750
  }
660
751
  return comment?.isConnected ? comment : void 0;
@@ -663,7 +754,7 @@ function findElement(scope, anchor) {
663
754
  const key = `${scope}:${anchor}`;
664
755
  let element = elements.get(key);
665
756
  if (!element?.isConnected) {
666
- element = document.querySelector(`[data-b="${key}"]`) ?? void 0;
757
+ element = document.querySelector(`[b-b="${key}"]`) ?? void 0;
667
758
  if (element) elements.set(key, element);
668
759
  }
669
760
  return element ?? null;
@@ -691,12 +782,16 @@ function insertHTML(before, html) {
691
782
  const template = document.createElement("template");
692
783
  template.innerHTML = html;
693
784
  const fragment = template.content;
785
+ if (markerObserver) indexAdded(markerObserver.takeRecords());
694
786
  indexMarkers(fragment);
695
787
  options.listen(fragment);
696
788
  const server = serverScopes(fragment);
789
+ const added = hiding?.bodies.size ? [...fragment.childNodes] : void 0;
697
790
  if ("parent" in before) before.parent.append(fragment);
698
791
  else before.parentNode.insertBefore(fragment, before);
699
- for (const fn of context.after.splice(0)) fn();
792
+ if (added) hiding.added(added);
793
+ markerObserver?.takeRecords();
794
+ for (const fn of afterInsert.splice(0)) fn();
700
795
  if (server.length > 0) refresh(server);
701
796
  }
702
797
  /**
@@ -706,7 +801,7 @@ function insertHTML(before, html) {
706
801
  */
707
802
  function serverScopes(root) {
708
803
  const ids = /* @__PURE__ */ new Set();
709
- for (const element of root.querySelectorAll("[data-b]")) ids.add(Number(element.getAttribute("data-b").split(":")[0]));
804
+ for (const element of root.querySelectorAll("[b-b]")) ids.add(Number(element.getAttribute("b-b").split(":")[0]));
710
805
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
711
806
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
712
807
  const match = /^[tb](\d+):/.exec(node.data);
@@ -721,31 +816,59 @@ function serverScopes(root) {
721
816
  * Renders a `#portal` body into its target, between markers with its scope
722
817
  * ID. `kinds` names the body, so a new target first removes it from the old one.
723
818
  */
724
- function portal(scope, target, render, kinds = []) {
819
+ function portalTo(scope, target, render, kinds = []) {
725
820
  disposeKinds(scope, kinds);
726
821
  const element = typeof target === "string" ? document.querySelector(target) : target;
727
822
  if (!(element instanceof Element)) return;
728
823
  insertHTML({ parent: element }, `<!--P${nextId}-->${render(scope)}<!--/P-->`);
729
824
  }
825
+ /** Writes an inserted value between `<!--t…-->` and `<!--/t-->`. */
730
826
  function text(scope, anchor, value) {
731
827
  const start = findComment(`t${scope.id}:${anchor}`);
732
- if (!start) return;
733
- const end = rangeEnd(start);
734
- const node = start.nextSibling;
735
- if ((typeof value === "string" || typeof value === "number") && node?.nodeType === 3 && node.nextSibling === end) {
736
- node.data = String(value);
828
+ if (start) write(start.parentNode, start.nextSibling, rangeEnd(start), value);
829
+ }
830
+ /** Writes an inserted value that is the whole content of the element with the anchor. */
831
+ function content(scope, anchor, value) {
832
+ const element = findElement(scope.id, anchor);
833
+ if (element) write(element, element.firstChild, null, value);
834
+ }
835
+ /**
836
+ * Writes the text of an element whose content is text, such as a `<textarea>`
837
+ * or a `<title>`. A `<textarea>` gets the value too, as `value` does on an
838
+ * `<input>`, so a change replaces what the user typed.
839
+ */
840
+ function writeText(scope, anchor, value) {
841
+ const element = findElement(scope.id, anchor);
842
+ if (element) {
843
+ const written = textValue(value);
844
+ element.textContent = written;
845
+ if (element instanceof HTMLTextAreaElement) element.value = written;
846
+ }
847
+ }
848
+ /**
849
+ * Replaces the nodes of `parent` from `first` up to `end`, or to its last
850
+ * child, with a value. A text node that stays a text node keeps its node.
851
+ */
852
+ function write(parent, first, end, value) {
853
+ if ((typeof value === "string" || typeof value === "number") && first?.nodeType === 3 && first.nextSibling === end) {
854
+ const saved = hiding?.nodes.get(first);
855
+ if (saved) saved.v = String(value);
856
+ else first.data = String(value);
737
857
  return;
738
858
  }
739
- clear(start, end);
740
- if (isRaw(value)) insertHTML(end, rawHTML(value));
741
- else if (typeof value === "string" || typeof value === "number") end.parentNode.insertBefore(document.createTextNode(String(value)), end);
742
- else insertHTML(end, insertValue(value));
859
+ while (first && first !== end) {
860
+ const next = first.nextSibling;
861
+ first.remove();
862
+ first = next;
863
+ }
864
+ insertHTML(end ?? { parent }, insertValue(value));
743
865
  }
744
866
  function setAttribute(element, name, value) {
745
867
  if (name === "value" || name === "checked") element[name] = name === "checked" ? Boolean(value) : value ?? "";
746
- const content = attributeText(name, value);
747
- if (content === void 0) element.removeAttribute(name);
748
- else element.setAttribute(name, content);
868
+ const written = attributeText(name, value);
869
+ if (written === void 0) element.removeAttribute(name);
870
+ else element.setAttribute(name, written);
871
+ if (name === "style") hiding?.styled(element);
749
872
  }
750
873
  function attr(scope, anchor, name, value) {
751
874
  const element = findElement(scope.id, anchor);
@@ -797,7 +920,7 @@ async function reset(scope, anchor, id, body, fallback, kinds) {
797
920
  html = updates[body](scope);
798
921
  } catch (error) {
799
922
  disposeKinds(scope, kinds);
800
- context.after.length = 0;
923
+ afterInsert.length = 0;
801
924
  html = updates[fallback](scope, error);
802
925
  }
803
926
  insertHTML(end, html);
@@ -809,6 +932,164 @@ function fill(scope, anchor, render) {
809
932
  const end = rangeEnd(start);
810
933
  if (start.nextSibling === end) insertHTML(end, render(scope));
811
934
  }
935
+ /**
936
+ * Shows or hides the body of an `#offscreen` block. A body that the page
937
+ * does not have yet renders the first time it shows. `kind` is the body's
938
+ * scope ID in the compiled component.
939
+ */
940
+ function offscreen(scope, anchor, value, render, kind) {
941
+ const start = findComment(`b${scope.id}:${anchor}`);
942
+ if (!start) return;
943
+ const visible = Boolean(value);
944
+ const state = start.data.split(":")[2];
945
+ if (visible ? state === "1" : state !== "1") return;
946
+ start.data = `b${scope.id}:${anchor}:${visible ? 1 : 0}`;
947
+ const end = rangeEnd(start);
948
+ if (state === "-1") {
949
+ insertHTML(end, render(scope));
950
+ return;
951
+ }
952
+ let body;
953
+ for (const child of scope.children) if (child.k === kind) body = child;
954
+ if (body) {
955
+ hiding ??= createHiding();
956
+ if (visible) hiding.show(body);
957
+ else hiding.hide(body, start, end);
958
+ }
959
+ }
960
+ /**
961
+ * The code of hidden `#offscreen` bodies. The first body that hides sets it
962
+ * up, so the core of a page without one only checks that it is not there.
963
+ * A body is hidden with an inline `display: none !important` on each element
964
+ * at its top level, which no stylesheet overrides, and empty text for each
965
+ * text node. The nodes stay in the page, so form fields, focus and media
966
+ * keep their state.
967
+ */
968
+ let hiding;
969
+ /** True for a scope that is `ancestor` or inside it, also through the owner of a component. */
970
+ function within(scope, ancestor) {
971
+ for (let current = scope; current; current = current.p ?? current.o) if (current === ancestor) return true;
972
+ return false;
973
+ }
974
+ /** True for a scope in a hidden `#offscreen` body. */
975
+ function hidden(scope) {
976
+ for (let current = scope; current; current = current.p ?? current.o) if (current.h) return true;
977
+ return false;
978
+ }
979
+ /** The nodes between two markers. */
980
+ function between([start, end]) {
981
+ const result = [];
982
+ for (let node = start.nextSibling; node && node !== end; node = node.nextSibling) result.push(node);
983
+ return result;
984
+ }
985
+ /** The inline style of an element, which an element that is not HTML or SVG may not have. */
986
+ function display(element) {
987
+ return element.style;
988
+ }
989
+ function createHiding() {
990
+ const bodies = /* @__PURE__ */ new Set();
991
+ const nodes = /* @__PURE__ */ new WeakMap();
992
+ const hideNode = (node) => {
993
+ const saved = nodes.get(node);
994
+ if (saved) {
995
+ saved.n++;
996
+ return;
997
+ }
998
+ if (node.nodeType === 3) {
999
+ nodes.set(node, {
1000
+ n: 1,
1001
+ v: node.data
1002
+ });
1003
+ node.data = "";
1004
+ return;
1005
+ }
1006
+ const style = node.nodeType === 1 ? display(node) : void 0;
1007
+ if (style) {
1008
+ nodes.set(node, {
1009
+ n: 1,
1010
+ v: style.getPropertyValue("display"),
1011
+ p: style.getPropertyPriority("display"),
1012
+ a: node.hasAttribute("style")
1013
+ });
1014
+ style.setProperty("display", "none", "important");
1015
+ }
1016
+ };
1017
+ const showNode = (node) => {
1018
+ const saved = nodes.get(node);
1019
+ if (!saved || --saved.n > 0) return;
1020
+ nodes.delete(node);
1021
+ if (node.nodeType === 3) {
1022
+ node.data = saved.v;
1023
+ return;
1024
+ }
1025
+ const element = node;
1026
+ const style = display(element);
1027
+ if (saved.v) style.setProperty("display", saved.v, saved.p);
1028
+ else style.removeProperty("display");
1029
+ if (!saved.a && element.getAttribute("style") === "") element.removeAttribute("style");
1030
+ };
1031
+ return {
1032
+ bodies,
1033
+ nodes,
1034
+ hidden,
1035
+ hide(body, start, end) {
1036
+ const record = {
1037
+ scope: body,
1038
+ ranges: [[start, end]]
1039
+ };
1040
+ body.h = record;
1041
+ bodies.add(record);
1042
+ const inside = [...scopes.values()].filter((scope) => within(scope, body));
1043
+ for (const scope of inside) {
1044
+ const portal = comments.get(`P${scope.id}`);
1045
+ if (portal?.isConnected) record.ranges.push([portal, rangeEnd(portal)]);
1046
+ }
1047
+ for (const range of record.ranges) between(range).forEach(hideNode);
1048
+ for (const scope of inside) {
1049
+ for (const [name, cleanup] of scope.cleanups ?? []) {
1050
+ cleanup();
1051
+ (scope.w ??= /* @__PURE__ */ new Set()).add(name);
1052
+ }
1053
+ scope.cleanups?.clear();
1054
+ }
1055
+ },
1056
+ show(body) {
1057
+ const record = body.h;
1058
+ if (!record) return;
1059
+ body.h = void 0;
1060
+ bodies.delete(record);
1061
+ for (const range of record.ranges) if (range[0].isConnected) between(range).forEach(showNode);
1062
+ for (const scope of scopes.values()) if (scope.w && within(scope, body) && !hidden(scope)) {
1063
+ const ref = `${rootOf(scope).m}#`;
1064
+ for (const name of scope.w) call(ref + name, scope, []);
1065
+ scope.w = void 0;
1066
+ }
1067
+ },
1068
+ paused(scope, name) {
1069
+ if (bodies.size === 0 || !hidden(scope)) return false;
1070
+ (scope.w ??= /* @__PURE__ */ new Set()).add(name);
1071
+ return true;
1072
+ },
1073
+ added(added) {
1074
+ for (const node of added) for (const record of bodies) {
1075
+ for (const [start, end] of record.ranges) if (node.parentNode === start.parentNode && start.compareDocumentPosition(node) & 4 && node.compareDocumentPosition(end) & 4) hideNode(node);
1076
+ const data = node.nodeType === 8 ? node.data : "";
1077
+ const scope = /^P-?\d+$/.test(data) ? scopes.get(Number(data.slice(1))) : void 0;
1078
+ if (scope && within(scope, record.scope)) record.ranges.push([node, rangeEnd(node)]);
1079
+ }
1080
+ },
1081
+ styled(element) {
1082
+ const saved = nodes.get(element);
1083
+ const style = display(element);
1084
+ if (saved && style) {
1085
+ saved.v = style.getPropertyValue("display");
1086
+ saved.p = style.getPropertyPriority("display");
1087
+ saved.a = element.hasAttribute("style");
1088
+ style.setProperty("display", "none", "important");
1089
+ }
1090
+ }
1091
+ };
1092
+ }
812
1093
  /** Updates the items of `#for` or `#repeat`, keeping the elements of items whose keys stay. */
813
1094
  function list(scope, anchor, items, key, render, assign, fallback, fallbackKinds) {
814
1095
  const start = findComment(`b${scope.id}:${anchor}`);
@@ -817,22 +1098,21 @@ function list(scope, anchor, items, key, render, assign, fallback, fallbackKinds
817
1098
  const previous = /* @__PURE__ */ new Map();
818
1099
  const others = [];
819
1100
  let position = 0;
820
- for (let node = start.nextSibling; node && node !== end;) if (node.nodeType === 8 && /^i-?\d+$/.test(node.data)) {
821
- const itemEnd = rangeEnd(node);
822
- const nodes = [];
823
- for (let current = node; current; current = current.nextSibling) {
824
- nodes.push(current);
825
- if (current === itemEnd) break;
826
- }
827
- const item = scopes.get(Number(node.data.slice(1)));
828
- previous.set(key(item.i, position++), {
829
- scope: item,
830
- nodes
831
- });
832
- node = itemEnd.nextSibling;
833
- } else {
834
- others.push(node);
835
- node = node.nextSibling;
1101
+ for (let node = start.nextSibling; node && node !== end;) {
1102
+ const data = node.nodeType === 8 ? node.data : void 0;
1103
+ const id = data ? /^i(-?\d+)$/.exec(data)?.[1] : node.getAttribute?.("b-b")?.split(":")[0];
1104
+ const item = id === void 0 ? void 0 : scopes.get(Number(id));
1105
+ let last = node;
1106
+ if (item && (data || item.p === scope && !fallbackKinds.includes(item.k))) {
1107
+ if (data) last = rangeEnd(node);
1108
+ const nodes = [node];
1109
+ for (let current = node; current !== last;) nodes.push(current = current.nextSibling);
1110
+ previous.set(key(item.i, position++), {
1111
+ scope: item,
1112
+ nodes
1113
+ });
1114
+ } else others.push(node);
1115
+ node = last.nextSibling;
836
1116
  }
837
1117
  if (items.length === 0) {
838
1118
  if (previous.size === 0 && others.length > 0) return;
@@ -844,15 +1124,26 @@ function list(scope, anchor, items, key, render, assign, fallback, fallbackKinds
844
1124
  disposeKinds(scope, fallbackKinds);
845
1125
  for (const node of others) node.parentNode?.removeChild(node);
846
1126
  const parent = end.parentNode;
1127
+ let cursor = start.nextSibling;
1128
+ let added = "";
1129
+ const flush = () => {
1130
+ if (added) {
1131
+ insertHTML(cursor, added);
1132
+ added = "";
1133
+ }
1134
+ };
847
1135
  items.forEach((value, index) => {
848
1136
  const id = key(value, index);
849
1137
  const item = previous.get(id);
850
1138
  if (item) {
1139
+ flush();
851
1140
  previous.delete(id);
852
1141
  assign(item.scope, value, index);
853
- for (const node of item.nodes) parent.insertBefore(node, end);
854
- } else insertHTML(end, render(scope, value, index));
1142
+ if (item.nodes[0] === cursor) cursor = item.nodes.at(-1).nextSibling;
1143
+ else for (const node of item.nodes) parent.insertBefore(node, cursor);
1144
+ } else added += render(scope, value, index);
855
1145
  });
1146
+ flush();
856
1147
  for (const item of previous.values()) {
857
1148
  destroy(item.scope);
858
1149
  for (const node of item.nodes) node.parentNode?.removeChild(node);
@@ -860,15 +1151,15 @@ function list(scope, anchor, items, key, render, assign, fallback, fallbackKinds
860
1151
  }
861
1152
  /** Sets a style variable on the top-level elements of a component instance. */
862
1153
  function setVar(scope, name, value) {
863
- const content = value === null || value === void 0 || value === false ? "" : String(value);
864
- for (const element of document.querySelectorAll(`[data-v="${scope.id}"]`)) element.style.setProperty(name, content);
1154
+ const css = value === null || value === void 0 || value === false ? "" : String(value);
1155
+ for (const element of document.querySelectorAll(`[b-v="${scope.id}"]`)) element.style.setProperty(name, css);
865
1156
  }
866
1157
  /** The scope that provides a context to `scope`: itself or the nearest one above it. */
867
1158
  function findProvider(scope, key) {
868
1159
  for (let current = scope; current; current = current.p ?? current.o) if (current.v && key in current.v) return current;
869
1160
  }
870
1161
  /** Writes a provided value, and the slot of every scope that reads it from this provider. */
871
- function provide(scope, context, value) {
1162
+ function updateContext(scope, context, value) {
872
1163
  scope.v ??= {};
873
1164
  scope.v[context.key] = value;
874
1165
  for (const target of scopes.values()) {
@@ -888,7 +1179,7 @@ function prop(scope, anchor, name, value) {
888
1179
  const apply = (module) => {
889
1180
  const slot = module.props[name];
890
1181
  if (slot !== void 0) {
891
- if (value !== null && typeof value === "object" && typeof value.then === "function") asyncMemo(child, slot, Promise.resolve(value));
1182
+ if (isThenable(value)) asyncMemo(child, slot, Promise.resolve(value));
892
1183
  else set(child, slot, value);
893
1184
  return;
894
1185
  }
@@ -904,31 +1195,28 @@ function prop(scope, anchor, name, value) {
904
1195
  }
905
1196
  /** Runs an effect or a `$client` callback, after the cleanup of its previous run. */
906
1197
  function effect(scope, name, callback) {
1198
+ if (hiding?.paused(scope, name)) return;
907
1199
  scope.cleanups ??= /* @__PURE__ */ new Map();
908
1200
  scope.cleanups.get(name)?.();
909
1201
  const cleanup = callback();
910
- if (typeof cleanup === "function") scope.cleanups.set(name, cleanup);
911
- else scope.cleanups.delete(name);
1202
+ scope.cleanups.set(name, typeof cleanup === "function" ? cleanup : noop);
912
1203
  }
1204
+ function noop() {}
913
1205
  /** Renders the attributes of a form or button that posts to a server function. */
914
1206
  function action(name, id, method, result) {
915
- return actionAttributes(options.rpc ?? "/_brumate", name, id, method, result);
1207
+ return actionAttributes(rpcPrefix, name, id, method, result);
916
1208
  }
917
1209
  /**
918
- * Sends a form to the server function of its `$action`, and writes the
919
- * result into the `$action` when it arrives. It is pending until then.
1210
+ * Sends a form of an `$action`. The code is in `rpc.ts`, which every server
1211
+ * call loads, so the core holds only this.
920
1212
  */
921
1213
  function submitAction(form, submitter) {
922
- const [scopeId, slot] = form.getAttribute("data-result").split(":").map(Number);
923
- const scope = scopes.get(scopeId);
924
- if (!scope) return;
925
- const data = new FormData(form, submitter);
926
- asyncMemo(scope, slot, track(import("../rpc-B86KKjzx.js").then(({ submit }) => submit(options.rpc ?? "/_brumate", form.getAttribute("data-action"), data))));
1214
+ import("../rpc-9fSqL_YK.js").then((module) => module.sendAction(form, submitter));
927
1215
  }
928
1216
  /** Calls a server function. */
929
1217
  async function rpc(id, args) {
930
- const signal = memoSignal;
931
- return track(import("../rpc-B86KKjzx.js").then(({ call: callServer }) => callServer(options.rpc ?? "/_brumate", id, args, signal)));
1218
+ const signal = memoSignal();
1219
+ return track(import("../rpc-9fSqL_YK.js").then((module) => module.call(rpcPrefix, id, args, signal)));
932
1220
  }
933
1221
  /** Renders a value inserted in markup. */
934
1222
  function insert(value) {
@@ -947,7 +1235,7 @@ function component(Child, props, _ctx, scope, anchor) {
947
1235
  parent.c ??= {};
948
1236
  parent.c[anchor] = nextId;
949
1237
  }
950
- if (parent) context.own(parent);
1238
+ if (parent) setOwner(parent);
951
1239
  return Child(props);
952
1240
  }
953
1241
  function dynamic(tag, attributes, children, _ctx, scope) {
@@ -959,94 +1247,99 @@ function dynamic(tag, attributes, children, _ctx, scope) {
959
1247
  const open = `<${name}${spread(attributes)}>`;
960
1248
  return VOID_ELEMENTS.has(name) ? open : `${open}${children ? rawHTML(children) : ""}</${name}>`;
961
1249
  }
962
- var ClientContext = class {
963
- /** Work that waits until rendered markup is in the page. */
964
- after = [];
965
- /** The scope that renders the next component, which becomes its owner. */
966
- owner;
967
- scope(kind, parent, module) {
968
- const id = nextId--;
969
- const parentScope = resolveScope(parent);
970
- const scope = {
971
- id,
972
- k: kind,
973
- p: parentScope,
974
- m: module,
975
- s: [],
976
- children: /* @__PURE__ */ new Set()
977
- };
978
- if (module !== void 0 && this.owner) {
979
- scope.o = this.owner;
980
- this.owner = void 0;
981
- }
982
- parentScope?.children.add(scope);
983
- scopes.set(id, scope);
984
- return id;
985
- }
986
- /** The ID that `$id()` makes. Client scope IDs are negative, so they differ from the server's. */
987
- id(scope, index) {
988
- return `b${resolveScope(scope).id}-${index}`;
989
- }
990
- /** Sets the owner of the next component's root scope. */
991
- own(scope) {
992
- this.owner = resolveScope(scope);
993
- }
994
- /** Provides a value of a context to the scopes inside `scope`. */
995
- provide(context, value, scope) {
996
- const target = resolveScope(scope);
997
- target.v ??= {};
998
- target.v[context.key] = value;
999
- }
1000
- /** Reads a context, and records its slot so that changes to the provided value reach it. */
1001
- consume(context, scope, slot) {
1002
- const target = resolveScope(scope);
1003
- if (slot !== void 0) {
1004
- target.x ??= {};
1005
- target.x[context.key] = slot;
1006
- }
1007
- const provider = findProvider(target, context.key);
1008
- return provider ? provider.v[context.key] : context.defaultValue;
1009
- }
1010
- slots(id, values) {
1011
- scopes.get(id).s = values;
1012
- }
1013
- item(id, value) {
1014
- scopes.get(id).i = value;
1015
- }
1016
- element(scope, anchor) {
1017
- return new ElementReference(scope, anchor);
1018
- }
1019
- /** Adds the markup of a `#head` block to the document's head. */
1020
- head(html) {
1021
- this.after.push(() => insertHTML({ parent: document.head }, html));
1022
- }
1023
- /** Sets the title of the page, for a component that the client renders. */
1024
- title(value) {
1025
- title(value);
1250
+ /** Work that waits until rendered markup is in the page. */
1251
+ const afterInsert = [];
1252
+ /** The scope that renders the next component, which becomes its owner. */
1253
+ let owner;
1254
+ /** Creates a scope for markup that the client renders, and returns its ID. */
1255
+ function createScope(kind, parent, module) {
1256
+ const id = nextId--;
1257
+ const parentScope = resolveScope(parent);
1258
+ const created = {
1259
+ id,
1260
+ k: kind,
1261
+ p: parentScope,
1262
+ m: module,
1263
+ s: [],
1264
+ children: /* @__PURE__ */ new Set()
1265
+ };
1266
+ if (module !== void 0 && owner) {
1267
+ created.o = owner;
1268
+ owner = void 0;
1026
1269
  }
1027
- /** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */
1028
- portal(html) {
1029
- this.after.push(() => insertHTML({ parent: document.body }, html));
1270
+ parentScope?.children.add(created);
1271
+ treeChanges++;
1272
+ scopes.set(id, created);
1273
+ return id;
1274
+ }
1275
+ /** The ID that `$id()` makes. Client scope IDs are negative, so they differ from the server's. */
1276
+ function makeId(scope, index) {
1277
+ return `b${resolveScope(scope).id}-${index}`;
1278
+ }
1279
+ /** Sets the owner of the next component's root scope. */
1280
+ function setOwner(scope) {
1281
+ owner = resolveScope(scope);
1282
+ }
1283
+ /** Provides a value of a context to the scopes inside `scope`. */
1284
+ function provideValue(context, value, scope) {
1285
+ const target = resolveScope(scope);
1286
+ target.v ??= {};
1287
+ target.v[context.key] = value;
1288
+ }
1289
+ /** Reads a context, and records its slot so that changes to the provided value reach it. */
1290
+ function consumeContext(context, scope, slot) {
1291
+ const target = resolveScope(scope);
1292
+ if (slot !== void 0) {
1293
+ target.x ??= {};
1294
+ target.x[context.key] = slot;
1030
1295
  }
1031
- /** Adds a component's stylesheet to the page, if the server did not. */
1032
- style(id, css) {
1033
- if (!document.querySelector(`style[data-brm="${id}"]`)) {
1034
- const style = document.createElement("style");
1035
- style.dataset.brm = id;
1036
- style.textContent = css;
1037
- document.head.append(style);
1038
- }
1039
- return "";
1040
- }
1041
- /** A function prop rendered on the client calls the parent's exported handler. */
1042
- fn(value, ref, scope) {
1043
- if (typeof value !== "function") return value;
1044
- const instance = resolveScope(scope);
1045
- return (...args) => call(ref, instance, args);
1296
+ const provider = findProvider(target, context.key);
1297
+ return provider ? provider.v[context.key] : context.defaultValue;
1298
+ }
1299
+ function setSlots(id, values) {
1300
+ scopes.get(id).s = values;
1301
+ }
1302
+ function setItem(id, value) {
1303
+ scopes.get(id).i = value;
1304
+ }
1305
+ function elementAt(scope, anchor) {
1306
+ return new ElementReference(scope, anchor);
1307
+ }
1308
+ /** Adds the markup of a `#head` block to the document's head. */
1309
+ function addHead(html) {
1310
+ afterInsert.push(() => insertHTML({ parent: document.head }, html));
1311
+ }
1312
+ /** Adds the markup of a `#portal` block at the end of the page, after the markup around it. */
1313
+ function addPortal(html) {
1314
+ afterInsert.push(() => insertHTML({ parent: document.body }, html));
1315
+ }
1316
+ /** Adds a component's stylesheet to the page, if the server did not. */
1317
+ function addStyle(id, css) {
1318
+ if (!document.querySelector(`style[b-style="${id}"]`)) {
1319
+ const sheet = document.createElement("style");
1320
+ sheet.setAttribute("b-style", id);
1321
+ sheet.textContent = css;
1322
+ document.head.append(sheet);
1046
1323
  }
1324
+ return "";
1325
+ }
1326
+ /** A function prop rendered on the client calls the parent's exported handler. */
1327
+ function handlerProp(value, ref, scope) {
1328
+ if (typeof value !== "function") return value;
1329
+ const instance = resolveScope(scope);
1330
+ return (...args) => call(ref, instance, args);
1331
+ }
1332
+ /**
1333
+ * What the loader calls. It is one export, so the loader's import of the core
1334
+ * names one export, and a build keeps the rest only when components call them.
1335
+ */
1336
+ const loader = {
1337
+ init,
1338
+ handle,
1339
+ dispose,
1340
+ submitAction
1047
1341
  };
1048
- const context = new ClientContext();
1049
1342
  //#endregion
1050
- export { DEVTOOLS, action, affix, asyncMemo, attr, attribute, attrs, branch, cells, component, context, createContext, dispose, dynamic, effect, escape, fill, get, guess, handle, init, insert, leavePage, list, loadModule, memo, pending, portal, produce, prop, provide, raw, rekey, reset, rpc, scopeOf, set, setVar, spread, submitAction, text, title, update, vars };
1343
+ export { DEVTOOLS, ElementReference, FunctionReference, action, addHead, addPortal, addStyle, affix, afterInsert, asyncMemo, attr, attribute, attrs, branch, cells, classAttribute, component, consumeContext, content, createContext, createScope, descendants, dispose, dynamic, effect, elementAt, escape, fill, forget, get, guess, handle, handlerProp, hooks, init, insert, leavePage, leaveRoutes, list, loadModule, loadPart, loader, makeId, memo, offscreen, pending, portalTo, produce, prop, provideValue, raw, rekey, remount, removeRoot, removeScope, reset, rpc, rpcPrefix, scopeOf, scopes, set, setItem, setOwner, setSlots, setVar, spread, submitAction, text, title, track, update, updateContext, vars, writeText };
1051
1344
 
1052
1345
  //# sourceMappingURL=client.js.map