@aevantec/litevue 0.5.6 → 0.5.8

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 (38) hide show
  1. package/README.md +9 -6
  2. package/dist/litevue-devtools.iife.js +1 -1
  3. package/dist/litevue-devtools.mjs +1 -1
  4. package/dist/litevue-devtools.umd.js +1 -1
  5. package/dist/litevue-plugins.dev.iife.js +898 -0
  6. package/dist/litevue-plugins.dev.mjs +880 -0
  7. package/dist/litevue-plugins.iife.js +1 -1
  8. package/dist/litevue-plugins.mjs +1 -1
  9. package/dist/litevue-plugins.umd.js +1 -1
  10. package/dist/litevue.dev.iife.js +2193 -0
  11. package/dist/litevue.dev.mjs +2182 -0
  12. package/dist/litevue.iife.js +1 -1
  13. package/dist/litevue.mjs +1 -1
  14. package/dist/litevue.umd.js +1 -1
  15. package/dist/plugins/collapse.iife.js +1 -1
  16. package/dist/plugins/collapse.mjs +1 -1
  17. package/dist/plugins/collapse.umd.js +1 -1
  18. package/dist/plugins/media.dev.iife.js +249 -0
  19. package/dist/plugins/media.dev.mjs +243 -0
  20. package/dist/plugins/morph.dev.iife.js +217 -0
  21. package/dist/plugins/morph.dev.mjs +212 -0
  22. package/dist/plugins/persist.dev.iife.js +126 -0
  23. package/dist/plugins/persist.dev.mjs +120 -0
  24. package/dist/types/app.d.mts +7 -0
  25. package/dist/types/app.d.ts +7 -0
  26. package/dist/types/directives/bind.d.mts +1 -1
  27. package/dist/types/directives/bind.d.ts +1 -1
  28. package/dist/types/errors.d.mts +36 -0
  29. package/dist/types/errors.d.ts +36 -0
  30. package/dist/types/eval.d.mts +8 -2
  31. package/dist/types/eval.d.ts +8 -2
  32. package/dist/types/index.d.mts +1 -0
  33. package/dist/types/index.d.ts +1 -0
  34. package/dist/types/lazy.d.mts +15 -0
  35. package/dist/types/lazy.d.ts +15 -0
  36. package/dist/types/plugins/morph/index.d.mts +2 -1
  37. package/dist/types/plugins/morph/index.d.ts +2 -1
  38. package/package.json +10 -2
@@ -0,0 +1,880 @@
1
+ import { reactive, store, watchEffect } from "@aevantec/litevue";
2
+ //#region src/plugins/intersect/index.ts
3
+ /**
4
+ * v-intersect="expression" — evaluates the expression when the element
5
+ * enters the viewport.
6
+ *
7
+ * Modifiers:
8
+ * - .once stop observing after the first trigger
9
+ * - .leave trigger when the element leaves the viewport instead
10
+ * - .full require the element to be fully visible (threshold: 1)
11
+ */
12
+ var intersect = (app) => {
13
+ app.directive("intersect", ({ el, get, modifiers }) => {
14
+ const observer = new IntersectionObserver((entries) => {
15
+ for (const entry of entries) if (modifiers?.leave ? !entry.isIntersecting : entry.isIntersecting) {
16
+ get();
17
+ if (modifiers?.once) observer.disconnect();
18
+ }
19
+ }, { threshold: modifiers?.full ? 1 : 0 });
20
+ observer.observe(el);
21
+ return () => observer.disconnect();
22
+ });
23
+ };
24
+ //#endregion
25
+ //#region src/plugins/mask/index.ts
26
+ var tokens = {
27
+ "9": /\d/,
28
+ a: /[a-zA-Z]/,
29
+ "*": /[a-zA-Z0-9]/
30
+ };
31
+ var format = (value, mask) => {
32
+ let out = "";
33
+ let literals = "";
34
+ let vi = 0;
35
+ for (let mi = 0; mi < mask.length; mi++) {
36
+ const re = tokens[mask[mi]];
37
+ if (re) {
38
+ while (vi < value.length && !re.test(value[vi])) vi++;
39
+ if (vi >= value.length) break;
40
+ out += literals + value[vi++];
41
+ literals = "";
42
+ } else {
43
+ literals += mask[mi];
44
+ if (value[vi] === mask[mi]) vi++;
45
+ }
46
+ }
47
+ return out;
48
+ };
49
+ /**
50
+ * v-mask="(999) 999-9999" — formats the input's value as the user types.
51
+ * The attribute value is the literal mask (not evaluated). Tokens:
52
+ * 9 = digit, a = letter, * = alphanumeric; every other character is a
53
+ * literal. Works together with v-model, which receives the masked value.
54
+ */
55
+ var mask = (app) => {
56
+ app.directive("mask", ({ el, exp }) => {
57
+ const input = el;
58
+ const apply = () => {
59
+ const masked = format(input.value, exp);
60
+ if (masked !== input.value) input.value = masked;
61
+ };
62
+ el.addEventListener("input", apply);
63
+ apply();
64
+ return () => el.removeEventListener("input", apply);
65
+ });
66
+ };
67
+ //#endregion
68
+ //#region src/plugins/transition/index.ts
69
+ var toMs = (v) => (parseFloat(v) || 0) * (v.includes("ms") ? 1 : 1e3);
70
+ var maxOf = (durations, delays) => {
71
+ const ds = durations.split(",");
72
+ const dl = delays.split(",");
73
+ let max = 0;
74
+ for (let i = 0; i < ds.length; i++) max = Math.max(max, toMs(ds[i]) + toMs(dl[i % dl.length]));
75
+ return max;
76
+ };
77
+ var durationOf = (el) => {
78
+ const s = getComputedStyle(el);
79
+ return Math.max(maxOf(s.transitionDuration, s.transitionDelay), maxOf(s.animationDuration, s.animationDelay));
80
+ };
81
+ /**
82
+ * v-transition:name="expression" — an animated v-show, using Vue-style
83
+ * classes: name-enter-from/-active/-to on show, name-leave-* before hiding.
84
+ * The element hides only once the leave transition finishes, its duration read
85
+ * from computed styles. The name defaults to "v", and the initial state does
86
+ * not animate unless `.appear` is present.
87
+ *
88
+ * With no expression, on a v-if/v-for element, it switches to unmount mode:
89
+ * enter runs on insertion, and a leave hook makes the core delay removal.
90
+ */
91
+ var transition = (app) => {
92
+ app.directive("transition", ({ el, get, effect, arg, modifiers, exp }) => {
93
+ const elem = el;
94
+ const name = arg || "v";
95
+ const cls = (phase) => `${name}-${phase}`;
96
+ let seq = 0;
97
+ let first = true;
98
+ let endTimer;
99
+ const clear = () => {
100
+ elem.classList.remove(cls("enter-from"), cls("enter-active"), cls("enter-to"), cls("leave-from"), cls("leave-active"), cls("leave-to"));
101
+ };
102
+ const run = (phase, done) => {
103
+ const id = ++seq;
104
+ clear();
105
+ elem.classList.add(cls(phase + "-from"), cls(phase + "-active"));
106
+ elem.offsetWidth;
107
+ elem.classList.remove(cls(phase + "-from"));
108
+ elem.classList.add(cls(phase + "-to"));
109
+ clearTimeout(endTimer);
110
+ endTimer = setTimeout(() => {
111
+ if (id === seq) {
112
+ clear();
113
+ if (done) done();
114
+ }
115
+ }, durationOf(elem));
116
+ };
117
+ if (!exp) {
118
+ let live = true;
119
+ Promise.resolve().then(() => {
120
+ if (live) run("enter");
121
+ });
122
+ elem.__leave = () => new Promise((resolve) => run("leave", resolve));
123
+ return () => {
124
+ live = false;
125
+ clearTimeout(endTimer);
126
+ delete elem.__leave;
127
+ };
128
+ }
129
+ effect(() => {
130
+ const show = !!get();
131
+ if (first) {
132
+ first = false;
133
+ elem.style.display = show ? "" : "none";
134
+ if (show && modifiers?.appear) run("enter");
135
+ return;
136
+ }
137
+ if (show) {
138
+ elem.style.display = "";
139
+ run("enter");
140
+ } else run("leave", () => {
141
+ elem.style.display = "none";
142
+ });
143
+ });
144
+ return () => clearTimeout(endTimer);
145
+ });
146
+ };
147
+ //#endregion
148
+ //#region src/plugins/persist/index.ts
149
+ var PREFIX = "litevue:";
150
+ /** Custom storages registered by name, usable as a directive modifier. */
151
+ var registry = Object.create(null);
152
+ var defaultStorage = "local";
153
+ var builtin = (name) => {
154
+ try {
155
+ if (name === "local" || name === "localStorage") return localStorage;
156
+ if (name === "session" || name === "sessionStorage") return sessionStorage;
157
+ } catch {}
158
+ };
159
+ var resolve$1 = (storage) => {
160
+ const target = storage ?? defaultStorage;
161
+ if (typeof target !== "string") return target;
162
+ return registry[target] ?? builtin(target);
163
+ };
164
+ /**
165
+ * Register a custom storage under a name, selectable anywhere — including as a
166
+ * directive modifier. Any object with getItem/setItem works.
167
+ *
168
+ * registerStorage('memory', myMemoryStorage);
169
+ * persistStore('scratch', { storage: 'memory' });
170
+ * <div v-persist.memory="scratch">…</div>
171
+ */
172
+ var registerStorage = (name, storage) => {
173
+ registry[name] = storage;
174
+ };
175
+ /**
176
+ * Switch the storage used when none is specified. Accepts a registered name
177
+ * ('local', 'session', or your own) or a storage object.
178
+ *
179
+ * setDefaultStorage('session'); // everything defaults to sessionStorage
180
+ */
181
+ var setDefaultStorage = (storage) => {
182
+ defaultStorage = storage;
183
+ };
184
+ /**
185
+ * Which own properties of `target` can round-trip through storage. Methods are
186
+ * behavior, not state; getter-only properties are derived and would throw on
187
+ * restore. An explicit list is filtered too, so naming a getter is a no-op.
188
+ */
189
+ var persistable = (target, keys) => (keys ?? Object.keys(target)).filter((k) => {
190
+ if (k[0] === "$") return false;
191
+ const desc = Object.getOwnPropertyDescriptor(target, k);
192
+ if (desc && desc.get && !desc.set) return false;
193
+ const raw = desc && desc.value;
194
+ if (raw && raw.__v_isRef === true && raw.__v_isReadonly === true) return false;
195
+ return typeof target[k] !== "function";
196
+ });
197
+ /** Restore saved values, then keep storage in sync with every change. */
198
+ var sync = (target, key, keys, storage, run) => {
199
+ if (!storage) return run(() => {});
200
+ const fields = persistable(target, keys);
201
+ try {
202
+ const saved = JSON.parse(storage.getItem(key) || "null");
203
+ if (saved) {
204
+ for (const k of fields) if (k in saved) target[k] = saved[k];
205
+ }
206
+ } catch {}
207
+ return run(() => {
208
+ const snapshot = {};
209
+ for (const k of fields) snapshot[k] = target[k];
210
+ try {
211
+ storage.setItem(key, JSON.stringify(snapshot));
212
+ } catch {}
213
+ });
214
+ };
215
+ /**
216
+ * v-persist="storage-key" — syncs the element's scope to storage: restored on
217
+ * mount, written back on every change, nested values included.
218
+ *
219
+ * The attribute value is the storage key verbatim, not an expression, and
220
+ * falls back to the element id. An argument narrows which properties are
221
+ * stored; a modifier picks the storage (`local` default, `session`, or any
222
+ * name given to registerStorage()).
223
+ *
224
+ * v-persist:draft="composer" — only `draft`
225
+ * v-persist:draft,recipient="composer" — only those two
226
+ * v-persist:draft.session="composer" — and into sessionStorage
227
+ */
228
+ var persist = (app) => {
229
+ app.directive("persist", ({ ctx, el, exp, arg, modifiers, effect }) => {
230
+ const key = PREFIX + (exp || el.id);
231
+ if (key === PREFIX) console.error(`v-persist needs a key: v-persist="my-key".`);
232
+ let storage;
233
+ for (const name in modifiers || {}) {
234
+ if (resolve$1(name)) {
235
+ storage = name;
236
+ break;
237
+ }
238
+ console.error(`v-persist: unknown storage ".${name}" — use .local, .session, or a name passed to registerStorage().`);
239
+ }
240
+ const keys = arg ? arg.split(",").map((k) => k.trim()).filter(Boolean) : void 0;
241
+ sync(ctx.scope, key, keys, resolve$1(storage), effect);
242
+ });
243
+ };
244
+ /**
245
+ * persistStore('cart') — the JS-side counterpart for global stores, which have
246
+ * no element to hang a directive on. Restores immediately, saves on change,
247
+ * and returns a stop function.
248
+ *
249
+ * persistStore('cart') // the whole store
250
+ * persistStore('cart', { keys: ['items'] }) // only these properties
251
+ * persistStore('cart', { key: 'v2:cart' }) // custom storage key
252
+ * persistStore('draft', { storage: 'session' }) // a different storage
253
+ * persistStore('scratch', { storage: myStorage }) // any getItem/setItem
254
+ */
255
+ var persistStore = (name, options = {}) => {
256
+ const target = store(name);
257
+ if (!target) {
258
+ console.error(`persistStore("${name}") — no such store. Register it with store("${name}", { … }) first.`);
259
+ return () => {};
260
+ }
261
+ const storage = resolve$1(options.storage);
262
+ if (!storage) console.error(`persistStore("${name}") — storage "${String(options.storage)}" is not available.`);
263
+ return sync(target, PREFIX + (options.key ?? name), options.keys, storage, watchEffect);
264
+ };
265
+ //#endregion
266
+ //#region src/plugins/focus/index.ts
267
+ var FOCUSABLE = "a[href], button, input, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])";
268
+ /**
269
+ * Focus utilities.
270
+ *
271
+ * v-focus="expression" — focuses the element while the expression is truthy,
272
+ * on mount included, making it an autofocus.
273
+ * - .select also select the text (inputs/textareas)
274
+ *
275
+ * v-trap="expression" — cycles Tab / Shift+Tab within the element while truthy,
276
+ * for accessible modals. Focus enters the first focusable child and returns to
277
+ * the previous element on release or unmount.
278
+ */
279
+ var focus = (app) => {
280
+ app.directive("focus", ({ el, get, effect, modifiers }) => {
281
+ let live = true;
282
+ effect(() => {
283
+ const on = !!get();
284
+ Promise.resolve().then(() => {
285
+ if (live && on) {
286
+ el.focus();
287
+ if (modifiers?.select && el.select) el.select();
288
+ }
289
+ });
290
+ });
291
+ return () => {
292
+ live = false;
293
+ };
294
+ });
295
+ app.directive("trap", ({ el, get, effect }) => {
296
+ let active = false;
297
+ let prevFocus = null;
298
+ const focusables = () => [...el.querySelectorAll(FOCUSABLE)].filter((e) => !e.hasAttribute("disabled"));
299
+ const onKeydown = (e) => {
300
+ if (e.key !== "Tab") return;
301
+ const els = focusables();
302
+ if (!els.length) {
303
+ e.preventDefault();
304
+ return;
305
+ }
306
+ const first = els[0];
307
+ const last = els[els.length - 1];
308
+ const current = document.activeElement;
309
+ if (!el.contains(current)) {
310
+ e.preventDefault();
311
+ first.focus();
312
+ } else if (e.shiftKey && current === first) {
313
+ e.preventDefault();
314
+ last.focus();
315
+ } else if (!e.shiftKey && current === last) {
316
+ e.preventDefault();
317
+ first.focus();
318
+ }
319
+ };
320
+ const release = () => {
321
+ active = false;
322
+ document.removeEventListener("keydown", onKeydown, true);
323
+ if (prevFocus && prevFocus.focus) prevFocus.focus();
324
+ };
325
+ effect(() => {
326
+ const on = !!get();
327
+ if (on && !active) {
328
+ active = true;
329
+ prevFocus = document.activeElement;
330
+ document.addEventListener("keydown", onKeydown, true);
331
+ Promise.resolve().then(() => {
332
+ if (active) (focusables()[0] || el).focus();
333
+ });
334
+ } else if (!on && active) release();
335
+ });
336
+ return () => {
337
+ if (active) release();
338
+ };
339
+ });
340
+ };
341
+ //#endregion
342
+ //#region src/plugins/collapse/index.ts
343
+ /**
344
+ * v-collapse="expression" — expands/collapses the element's height with a
345
+ * transition as the expression toggles. The initial state applies without
346
+ * animating.
347
+ *
348
+ * Modifiers:
349
+ * - .duration-<ms> transition duration (default 250)
350
+ */
351
+ var collapse = (app) => {
352
+ app.directive("collapse", ({ el, get, effect, modifiers }) => {
353
+ const elem = el;
354
+ let duration = 250;
355
+ for (const m in modifiers || {}) {
356
+ const match = /^duration-(\d+)$/.exec(m);
357
+ if (match) duration = +match[1];
358
+ }
359
+ const owned = [
360
+ "overflow",
361
+ "height",
362
+ "transition"
363
+ ];
364
+ const before = owned.map((k) => elem.style[k]);
365
+ elem.style.overflow = "hidden";
366
+ let first = true;
367
+ let seq = 0;
368
+ const timers = /* @__PURE__ */ new Set();
369
+ const later = (fn, ms) => {
370
+ const t = setTimeout(() => {
371
+ timers.delete(t);
372
+ fn();
373
+ }, ms);
374
+ timers.add(t);
375
+ };
376
+ effect(() => {
377
+ const show = !!get();
378
+ const id = ++seq;
379
+ if (first) {
380
+ first = false;
381
+ if (!show) elem.style.height = "0px";
382
+ later(() => {
383
+ elem.style.transition = `height ${duration}ms ease`;
384
+ });
385
+ return;
386
+ }
387
+ if (show) {
388
+ elem.style.height = elem.scrollHeight + "px";
389
+ later(() => {
390
+ if (id === seq) elem.style.height = "";
391
+ }, duration);
392
+ } else {
393
+ elem.style.height = elem.scrollHeight + "px";
394
+ elem.offsetHeight;
395
+ elem.style.height = "0px";
396
+ }
397
+ });
398
+ return () => {
399
+ timers.forEach(clearTimeout);
400
+ owned.forEach((k, i) => elem.style[k] = before[i]);
401
+ };
402
+ });
403
+ };
404
+ //#endregion
405
+ //#region src/plugins/morph/index.ts
406
+ /**
407
+ * A `data-` attribute rather than `v-preserve`: an unrecognised `v-` attribute
408
+ * logs an unknown-directive error, and registering one would have the walker
409
+ * strip it, leaving nothing for the next morph. Matches `data-morph-skip`.
410
+ */
411
+ var preserved = (node, opts) => node.nodeType === 1 && (node.hasAttribute("data-morph-preserve") || !!opts.preserve?.(node));
412
+ var dirRE = /^(?:v-|:|@)/;
413
+ var bindRE = /^(?::|v-bind:)/;
414
+ /**
415
+ * Attributes tried in order when no `key` option is given. All three express
416
+ * identity, so none repeat among siblings the way `name` does on a radio group
417
+ * — hence its absence. The attribute name is part of the key, so `id="5"` and
418
+ * `data-id="5"` stay distinct.
419
+ */
420
+ var KEY_ATTRS = [
421
+ "id",
422
+ "data-key",
423
+ "data-id"
424
+ ];
425
+ var defaultKey = (el) => {
426
+ for (const attr of KEY_ATTRS) {
427
+ const value = el.getAttribute(attr);
428
+ if (value != null) return attr + "=" + value;
429
+ }
430
+ return null;
431
+ };
432
+ /**
433
+ * The nearest stashed context, walking up from a live node. `v-scope` elements
434
+ * record theirs during walk, so inserted markup binds with the scope it landed
435
+ * in rather than the root.
436
+ */
437
+ var nearestCtx = (node) => {
438
+ for (let el = node; el; el = el.parentElement) if (el.__ctx) return el.__ctx;
439
+ };
440
+ /**
441
+ * Attributes the client owns, read from the *incoming* markup — it still
442
+ * carries the directives the live DOM had stripped. `:class` there means the
443
+ * live `class` is bound and must survive the server's static value.
444
+ */
445
+ var boundAttrs = (to) => {
446
+ const owned = /* @__PURE__ */ new Set();
447
+ for (const { name } of to.attributes) if (bindRE.test(name)) owned.add(name.replace(bindRE, "").split(".")[0]);
448
+ else if (name === "v-model") {
449
+ owned.add("value");
450
+ owned.add("checked");
451
+ }
452
+ return owned;
453
+ };
454
+ /**
455
+ * `v-for` and `v-if` render into Blocks: the live DOM holds anchors plus the
456
+ * clones the data produced, while the server still sends one template. Matched
457
+ * positionally, the rest would be deleted as "no longer sent".
458
+ */
459
+ var isBlockRoot = (el) => el.hasAttribute("v-for") || el.hasAttribute("v-if") || el.hasAttribute("v-else") || el.hasAttribute("v-else-if");
460
+ /** True when the client, not the server, decides this element's contents. */
461
+ var ownsChildren = (to) => {
462
+ if (to.hasAttribute("v-text") || to.hasAttribute("v-html") || to.hasAttribute("v-pre") || to.hasAttribute("v-once") || isBlockRoot(to)) return true;
463
+ for (let c = to.firstElementChild; c; c = c.nextElementSibling) if (isBlockRoot(c)) return true;
464
+ return false;
465
+ };
466
+ var patchAttrs = (from, to) => {
467
+ const owned = boundAttrs(to);
468
+ for (const { name, value } of [...to.attributes]) {
469
+ if (dirRE.test(name) || owned.has(name)) continue;
470
+ if (from.getAttribute(name) !== value) from.setAttribute(name, value);
471
+ }
472
+ for (const { name } of [...from.attributes]) {
473
+ if (owned.has(name) || to.hasAttribute(name)) continue;
474
+ from.removeAttribute(name);
475
+ }
476
+ };
477
+ /**
478
+ * Incoming text still holding `{{ }}` is rendered by a text directive on the
479
+ * live side, so the live value wins.
480
+ */
481
+ var isInterpolation = (data, ctx) => data.includes(ctx ? ctx.delimiters[0] : "{{");
482
+ var patchNode = (from, to, ctx, opts) => {
483
+ if (from.nodeType !== to.nodeType) return replaceNode(from, to, ctx, opts);
484
+ if (from.nodeType === 3 || from.nodeType === 8) {
485
+ const data = to.data;
486
+ if (isInterpolation(data, ctx)) return;
487
+ if (from.data !== data) from.data = data;
488
+ return;
489
+ }
490
+ if (from.nodeType !== 1) return;
491
+ const a = from;
492
+ const b = to;
493
+ if (a.tagName !== b.tagName) return replaceNode(from, to, ctx, opts);
494
+ if (opts.skip?.(a, b) || a.hasAttribute("data-morph-skip")) return;
495
+ patchAttrs(a, b);
496
+ if (!ownsChildren(b)) patchChildren(a, b, a.__ctx || ctx, opts);
497
+ };
498
+ var replaceNode = (from, to, ctx, opts) => {
499
+ if (preserved(from, opts)) return;
500
+ const fresh = to.cloneNode(true);
501
+ if (opts.beforeNodeAdded?.(fresh) === false) return;
502
+ ctx?.dispose?.(from);
503
+ from.parentNode.replaceChild(fresh, from);
504
+ opts.afterNodeRemoved?.(from);
505
+ mountNew(fresh, ctx);
506
+ };
507
+ /**
508
+ * Bind never-walked markup with the scope it was inserted into. The walker
509
+ * comes off the context, not an import, so this plugin doesn't pull a second
510
+ * copy of the core into the plugins bundle.
511
+ */
512
+ var mountNew = (node, ctx) => {
513
+ const target = ctx || nearestCtx(node.parentNode);
514
+ target?.walk?.(node, target);
515
+ };
516
+ var patchChildren = (from, to, ctx, opts) => {
517
+ const key = opts.key || defaultKey;
518
+ const keyed = /* @__PURE__ */ new Map();
519
+ for (let n = from.firstChild; n; n = n.nextSibling) if (n.nodeType === 1) {
520
+ const k = key(n);
521
+ if (k == null) continue;
522
+ if (keyed.has(k)) console.warn(`[morph] duplicate key ${JSON.stringify(k)} among siblings; only the last is reusable. Keys must be unique within a parent.`);
523
+ keyed.set(k, n);
524
+ }
525
+ const keyOf = (n) => n && n.nodeType === 1 ? key(n) : null;
526
+ let oldChild = from.firstChild;
527
+ let newChild = to.firstChild;
528
+ const insert = (node) => {
529
+ const fresh = node.cloneNode(true);
530
+ if (opts.beforeNodeAdded?.(fresh) === false) return;
531
+ from.insertBefore(fresh, oldChild);
532
+ mountNew(fresh, ctx);
533
+ };
534
+ while (newChild) {
535
+ const nextNew = newChild.nextSibling;
536
+ const wantKey = keyOf(newChild);
537
+ if (wantKey != null) {
538
+ const match = keyed.get(wantKey);
539
+ if (match) {
540
+ if (match === oldChild) oldChild = oldChild.nextSibling;
541
+ else from.insertBefore(match, oldChild);
542
+ keyed.delete(wantKey);
543
+ patchNode(match, newChild, ctx, opts);
544
+ } else insert(newChild);
545
+ } else if (oldChild && keyOf(oldChild) == null) {
546
+ const nextOld = oldChild.nextSibling;
547
+ patchNode(oldChild, newChild, ctx, opts);
548
+ oldChild = nextOld;
549
+ } else insert(newChild);
550
+ newChild = nextNew;
551
+ }
552
+ while (oldChild) {
553
+ const next = oldChild.nextSibling;
554
+ if (!preserved(oldChild, opts)) {
555
+ ctx?.dispose?.(oldChild);
556
+ from.removeChild(oldChild);
557
+ opts.afterNodeRemoved?.(oldChild);
558
+ }
559
+ oldChild = next;
560
+ }
561
+ };
562
+ /**
563
+ * morph(from, to) — patch `from` in place so it matches `to`, which may be an
564
+ * element or an HTML string for the *outer* element.
565
+ */
566
+ var morph = (from, to, opts = {}) => {
567
+ let target;
568
+ if (typeof to === "string") {
569
+ const holder = document.createElement("template");
570
+ holder.innerHTML = to.trim();
571
+ const content = holder.content;
572
+ target = content.childElementCount === 1 ? content.firstElementChild : (() => {
573
+ const wrapper = from.cloneNode(false);
574
+ wrapper.appendChild(content);
575
+ return wrapper;
576
+ })();
577
+ } else target = to;
578
+ if (target) {
579
+ const restore = captureFocus();
580
+ patchNode(from, target, nearestCtx(from), opts);
581
+ restore();
582
+ }
583
+ return from;
584
+ };
585
+ /**
586
+ * `insertBefore` blurs the node it moves, so a reorder drops focus even though
587
+ * the element survived. Re-focus afterwards and restore the caret. Only
588
+ * observable in a real browser — jsdom does not blur on move.
589
+ */
590
+ var captureFocus = () => {
591
+ const active = document.activeElement;
592
+ if (!active || active === document.body) return () => {};
593
+ const field = active;
594
+ let start = null;
595
+ let end = null;
596
+ try {
597
+ start = field.selectionStart;
598
+ end = field.selectionEnd;
599
+ } catch {}
600
+ return () => {
601
+ if (active === document.activeElement || !active.isConnected) return;
602
+ active.focus();
603
+ if (start !== null) try {
604
+ field.setSelectionRange(start, end);
605
+ } catch {}
606
+ };
607
+ };
608
+ /**
609
+ * Registers `$morph`, so a template can update a region from a fetch response
610
+ * without dropping into JavaScript.
611
+ */
612
+ var morphPlugin = (app) => {
613
+ app.scope.$morph = morph;
614
+ };
615
+ //#endregion
616
+ //#region src/plugins/media/index.ts
617
+ var DEFAULT_BREAKPOINTS = {
618
+ sm: 640,
619
+ md: 768,
620
+ lg: 1024,
621
+ xl: 1280,
622
+ "2xl": 1536
623
+ };
624
+ /**
625
+ * The scale in use until `configure()` runs. Exported because `configure()`
626
+ * replaces rather than merges, so adjusting one breakpoint means spreading
627
+ * this rather than retyping all five.
628
+ */
629
+ var defaultBreakpoints = Object.freeze({ ...DEFAULT_BREAKPOINTS });
630
+ var ALIASES = {
631
+ mobile: "base",
632
+ tablet: "md",
633
+ desktop: "lg"
634
+ };
635
+ var NUMERIC = /^\d+$/;
636
+ /**
637
+ * Two reactive primitives, deliberately:
638
+ *
639
+ * - `bp`, one string, so named keys / `atLeast` / `device` cost each consumer
640
+ * a single dependency however many responsive maps the page declares.
641
+ * - `tick`, for arbitrary `match()` queries. Their results are read off the
642
+ * MediaQueryList rather than mirrored, since registering a query inside a
643
+ * running effect would write a dependency it just read and re-run it.
644
+ */
645
+ var state = reactive({
646
+ bp: "base",
647
+ tick: 0
648
+ });
649
+ var installedScale;
650
+ var scale = { ...DEFAULT_BREAKPOINTS };
651
+ var order = ["base"];
652
+ var active = false;
653
+ var scaleSubs = [];
654
+ var querySubs = /* @__PURE__ */ new Map();
655
+ var supported = () => typeof window !== "undefined" && typeof window.matchMedia === "function";
656
+ var subscribe = (mql, cb) => {
657
+ if (mql.addEventListener) {
658
+ mql.addEventListener("change", cb);
659
+ return {
660
+ mql,
661
+ off: () => mql.removeEventListener("change", cb)
662
+ };
663
+ }
664
+ mql.addListener(cb);
665
+ return {
666
+ mql,
667
+ off: () => mql.removeListener(cb)
668
+ };
669
+ };
670
+ var currentBp = () => {
671
+ for (let i = scaleSubs.length - 1; i >= 0; i--) if (scaleSubs[i].mql.matches) return order[i + 1];
672
+ return "base";
673
+ };
674
+ var buildScale = () => {
675
+ scaleSubs.forEach((s) => s.off());
676
+ scaleSubs = [];
677
+ const names = Object.keys(scale).filter((n) => scale[n] > 0).sort((a, b) => scale[a] - scale[b]);
678
+ order = ["base", ...names];
679
+ if (!supported()) return;
680
+ scaleSubs = names.map((name) => {
681
+ return subscribe(window.matchMedia(`(min-width: ${scale[name]}px)`), () => {
682
+ state.bp = currentBp();
683
+ });
684
+ });
685
+ state.bp = currentBp();
686
+ };
687
+ /**
688
+ * Started by the first read, not by `app.use()`, so `mq` works in a plain
689
+ * module with no app mounted — otherwise it would report a frozen 'base'.
690
+ */
691
+ var activate = () => {
692
+ if (active) return;
693
+ active = true;
694
+ buildScale();
695
+ };
696
+ /**
697
+ * Entry point for every public read: activates, and depends on `tick` so
698
+ * `configure()` can invalidate all of them. `bp` alone is not enough — a key
699
+ * absent from the current scale returns false without touching reactive state,
700
+ * so that effect could never recover once a later scale defined the key.
701
+ */
702
+ var trackAll = () => {
703
+ activate();
704
+ state.tick;
705
+ };
706
+ /** SSR and jsdom have no matchMedia; every query reads false and bp stays base. */
707
+ var rawMatch = (query) => {
708
+ if (!supported()) return false;
709
+ let sub = querySubs.get(query);
710
+ if (!sub) {
711
+ sub = subscribe(window.matchMedia(query), () => state.tick++);
712
+ querySubs.set(query, sub);
713
+ }
714
+ return sub.mql.matches;
715
+ };
716
+ /** A key's lower bound in pixels, or undefined if it names nothing. */
717
+ var keyToPx = (key) => {
718
+ if (typeof key === "number") return key;
719
+ if (key === "base") return 0;
720
+ if (NUMERIC.test(key)) return Number(key);
721
+ const alias = ALIASES[key];
722
+ if (alias !== void 0) return alias === "base" ? 0 : scale[alias];
723
+ return scale[key];
724
+ };
725
+ var atLeastPx = (px) => {
726
+ if (px <= 0) return true;
727
+ const i = order.findIndex((n) => n !== "base" && scale[n] === px);
728
+ if (i !== -1) return order.indexOf(state.bp) >= i;
729
+ state.tick;
730
+ return rawMatch(`(min-width: ${px}px)`);
731
+ };
732
+ var warned = /* @__PURE__ */ new Set();
733
+ var warnOnce = (msg) => {
734
+ if (warned.has(msg)) return;
735
+ warned.add(msg);
736
+ console.warn(`[litevue media] ${msg}`);
737
+ };
738
+ var resolve = (map, fallback) => {
739
+ trackAll();
740
+ if (!map || typeof map !== "object") {
741
+ warnOnce(`expected a responsive map object, got ${typeof map}.`);
742
+ return fallback;
743
+ }
744
+ let best;
745
+ let bestPx = -1;
746
+ for (const key of Object.keys(map)) {
747
+ const px = keyToPx(key);
748
+ if (px === void 0) {
749
+ warnOnce(`"${key}" is not a breakpoint. Known: ${order.join(", ")}, plus the aliases ${Object.keys(ALIASES).join(", ")} and raw pixel widths.`);
750
+ continue;
751
+ }
752
+ if (px >= bestPx && atLeastPx(px)) {
753
+ bestPx = px;
754
+ best = map[key];
755
+ }
756
+ }
757
+ return best !== void 0 ? best : fallback;
758
+ };
759
+ var aliasPx = (alias) => {
760
+ const name = ALIASES[alias];
761
+ const px = scale[name];
762
+ if (px !== void 0) return px;
763
+ warnOnce(`$mqDevice needs "${name}" in your breakpoint scale; falling back to ${DEFAULT_BREAKPOINTS[name]}px. Define it, or use $mqAtLeast with your own keys.`);
764
+ return DEFAULT_BREAKPOINTS[name];
765
+ };
766
+ var mqFn = (map, fallback) => resolve(map, fallback);
767
+ var mq = Object.defineProperties(mqFn, {
768
+ props: { value: (maps) => {
769
+ trackAll();
770
+ const out = {};
771
+ for (const key of Object.keys(maps)) out[key] = resolve(maps[key]);
772
+ return out;
773
+ } },
774
+ breakpoint: {
775
+ get() {
776
+ trackAll();
777
+ return state.bp;
778
+ },
779
+ enumerable: true
780
+ },
781
+ device: {
782
+ get() {
783
+ trackAll();
784
+ if (!atLeastPx(aliasPx("tablet"))) return "mobile";
785
+ return atLeastPx(aliasPx("desktop")) ? "desktop" : "tablet";
786
+ },
787
+ enumerable: true
788
+ },
789
+ atLeast: { value: (key) => {
790
+ trackAll();
791
+ const px = keyToPx(key);
792
+ if (px === void 0) {
793
+ warnOnce(`$mqAtLeast("${key}") — unknown breakpoint, treated as false.`);
794
+ return false;
795
+ }
796
+ return atLeastPx(px);
797
+ } },
798
+ match: { value: (query) => {
799
+ trackAll();
800
+ return rawMatch(query);
801
+ } },
802
+ configure: { value: ({ breakpoints }) => {
803
+ if (!breakpoints) return;
804
+ scale = { ...breakpoints };
805
+ if (active) {
806
+ buildScale();
807
+ state.tick++;
808
+ }
809
+ } }
810
+ });
811
+ /**
812
+ * Drops every live subscription; `activate()` rebuilds them on the next read,
813
+ * so this is safe while something still holds `mq`. The scale is deliberately
814
+ * left alone — a page that configured one still wants it.
815
+ */
816
+ var releaseSubscriptions = () => {
817
+ scaleSubs.forEach((s) => s.off());
818
+ querySubs.forEach((s) => s.off());
819
+ scaleSubs = [];
820
+ querySubs.clear();
821
+ active = false;
822
+ };
823
+ var resetMedia = () => {
824
+ releaseSubscriptions();
825
+ scale = { ...DEFAULT_BREAKPOINTS };
826
+ order = ["base", ...Object.keys(scale).sort((a, b) => scale[a] - scale[b])];
827
+ active = false;
828
+ installedScale = void 0;
829
+ warned.clear();
830
+ state.bp = "base";
831
+ state.tick = 0;
832
+ };
833
+ var media = (app, options) => {
834
+ if (options?.breakpoints) {
835
+ const next = JSON.stringify(options.breakpoints);
836
+ if (installedScale && installedScale !== next) warnOnce("a second app installed media with a different breakpoint scale. The scale is page-wide, so this replaces the first one rather than giving each app its own. Configure it once, or call mq.configure() deliberately if replacing it is what you want.");
837
+ installedScale = next;
838
+ }
839
+ if (options) mq.configure(options);
840
+ app.scope.$mq = mq;
841
+ app.scope.$mqProps = mq.props;
842
+ app.scope.$mqAtLeast = mq.atLeast;
843
+ app.scope.$mqMatch = mq.match;
844
+ Object.defineProperty(app.scope, "$mqBreakpoint", {
845
+ get: () => mq.breakpoint,
846
+ enumerable: true,
847
+ configurable: true
848
+ });
849
+ Object.defineProperty(app.scope, "$mqDevice", {
850
+ get: () => mq.device,
851
+ enumerable: true,
852
+ configurable: true
853
+ });
854
+ return releaseSubscriptions;
855
+ };
856
+ //#endregion
857
+ //#region src/plugins/resize/index.ts
858
+ /**
859
+ * `v-resize="expr"` — element size, which no media query reports and container
860
+ * queries cannot hand to JavaScript. The expression runs with `$width` and
861
+ * `$height` in scope.
862
+ *
863
+ * Separate from the media plugin: that is viewport state, readable with no
864
+ * element involved, while this is bound to the element it sits on.
865
+ */
866
+ var resize = (app) => {
867
+ app.directive("resize", ({ el, get, exp }) => {
868
+ const handler = get(`(($width, $height) => { ${exp} })`);
869
+ const observer = new ResizeObserver((entries) => {
870
+ for (const entry of entries) {
871
+ const box = entry.contentRect;
872
+ handler(box.width, box.height);
873
+ }
874
+ });
875
+ observer.observe(el);
876
+ return () => observer.disconnect();
877
+ });
878
+ };
879
+ //#endregion
880
+ export { collapse, defaultBreakpoints, focus, intersect, mask, media, morph, morphPlugin, mq, persist, persistStore, registerStorage, resetMedia, resize, setDefaultStorage, transition };