@tschk/moonshine-vue 0.4.4 → 0.4.49

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.
package/src/reactive.ts CHANGED
@@ -7,42 +7,114 @@ import {
7
7
  createSignal,
8
8
  getOwner,
9
9
  onCleanup,
10
+ runWithOwner,
10
11
  untrack,
12
+ type Owner,
11
13
  } from "@tschk/moonshine-dom/reactive";
12
14
  import { createMemo } from "@tschk/moonshine";
13
- import { createMutable } from "@tschk/moonshine-dom/store";
15
+ import {
16
+ collectDeps,
17
+ isTracking,
18
+ trackDependency,
19
+ type Trackable,
20
+ } from "@tschk/moonshine/tracking";
21
+ import { createTrackedSet } from "./set";
22
+ import {
23
+ getComponentContext,
24
+ peekComponentContext,
25
+ withComponentConsumer,
26
+ type ComponentContext,
27
+ } from "@tschk/moonshine-dom/component";
28
+ import { createEmitter } from "./events";
29
+ export { useId } from "./context";
30
+ import {
31
+ createMutable,
32
+ unwrap as unwrapStore,
33
+ } from "@tschk/moonshine-dom/store";
14
34
 
15
35
  const refs = new WeakSet<object>();
36
+ const readonlyRefs = new WeakSet<object>();
37
+ const refTriggers = new WeakMap<Ref<any>, () => void>();
38
+ const refTriggerVersions = new WeakMap<Ref<any>, number>();
16
39
  declare const refBrand: unique symbol;
17
- export class Ref<T> {
40
+ export class Ref<T, S = T> {
18
41
  declare readonly [refBrand]: true;
19
42
  private readonly read: () => T;
20
- private readonly write?: (value: T) => void;
21
- constructor(read: () => T, write?: (value: T) => void) {
43
+ private readonly write?: (value: any) => void;
44
+ constructor(read: () => T, write?: (value: S) => void) {
22
45
  this.read = read;
23
46
  this.write = write;
24
47
  refs.add(this);
48
+ if (!write) readonlyRefs.add(this);
25
49
  }
26
50
  get value(): T {
27
51
  return this.read();
28
52
  }
29
- set value(value: T) {
53
+ set value(value: S) {
30
54
  if (!this.write) throw new TypeError("Native ref is readonly");
31
55
  this.write(value);
32
56
  }
33
57
  }
34
- export function isRef(value: unknown): value is Ref<any> {
58
+ export function isRef(value: unknown): value is Ref<any, any> {
35
59
  return typeof value === "object" && value !== null && refs.has(value);
36
60
  }
37
- function plain(value: unknown): value is object {
61
+ export type MaybeRef<T = any> = T | Ref<T> | Readonly<Ref<T>>;
62
+ export type MaybeRefOrGetter<T = any> = MaybeRef<T> | (() => T);
63
+ function plain(value: unknown): value is Record<PropertyKey, unknown> {
38
64
  if (value === null || typeof value !== "object") return false;
39
65
  const proto = Object.getPrototypeOf(value);
40
66
  return Array.isArray(value) || proto === Object.prototype || proto === null;
41
67
  }
42
68
  const proxies = new WeakMap<object, object>();
69
+ const shallowReactiveMap = new WeakMap<object, object>();
70
+ const readonlyMap = new WeakMap<object, object>();
71
+ const shallowReadonlyMap = new WeakMap<object, object>();
43
72
  const targets = new WeakMap<object, object>();
73
+ const reactiveProxies = new WeakSet<object>();
74
+ const readonlyProxies = new WeakSet<object>();
75
+ const shallowProxies = new WeakSet<object>();
76
+ const rawMarked = new WeakSet<object>();
77
+
78
+ export function markRaw<T extends object>(value: T): T {
79
+ if (
80
+ value !== null &&
81
+ (typeof value === "object" || typeof value === "function")
82
+ ) {
83
+ rawMarked.add(value);
84
+ }
85
+ return value;
86
+ }
87
+ export function toRaw<T>(observed: T): T {
88
+ if (observed === null || typeof observed !== "object") return observed;
89
+ const target = targets.get(observed);
90
+ return target ? toRaw(target as T) : observed;
91
+ }
44
92
  export function isReactive(value: unknown): value is object {
45
- return value !== null && typeof value === "object" && targets.has(value);
93
+ if (value === null || typeof value !== "object") return false;
94
+ if (readonlyProxies.has(value)) {
95
+ const target = targets.get(value);
96
+ return target ? isReactive(target) : false;
97
+ }
98
+ return reactiveProxies.has(value);
99
+ }
100
+ export function isReadonly(value: unknown): boolean {
101
+ return (
102
+ value !== null &&
103
+ typeof value === "object" &&
104
+ (readonlyProxies.has(value) || readonlyRefs.has(value))
105
+ );
106
+ }
107
+ export function isShallow(value: unknown): boolean {
108
+ return (
109
+ value !== null && typeof value === "object" && shallowProxies.has(value)
110
+ );
111
+ }
112
+ export function isProxy(value: unknown): boolean {
113
+ return (
114
+ value !== null &&
115
+ typeof value === "object" &&
116
+ (reactiveProxies.has(value) || readonlyProxies.has(value))
117
+ );
46
118
  }
47
119
  const arrayIndex = (key: PropertyKey) =>
48
120
  typeof key === "string" &&
@@ -51,23 +123,74 @@ const arrayIndex = (key: PropertyKey) =>
51
123
  export type Unwrap<T> =
52
124
  T extends Readonly<Ref<infer V>>
53
125
  ? V
54
- : T extends Function | Date | Map<unknown, unknown> | Set<unknown>
55
- ? T
56
- : T extends readonly unknown[]
57
- ? {
58
- [K in keyof T]: T[K] extends Readonly<Ref<any>>
59
- ? T[K]
60
- : Unwrap<T[K]>;
61
- }
62
- : T extends object
63
- ? { [K in keyof T]: Unwrap<T[K]> }
64
- : T;
126
+ : T extends Set<infer V>
127
+ ? Set<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
128
+ : T extends ReadonlySet<infer V>
129
+ ? ReadonlySet<V extends Readonly<Ref<any>> ? V : Unwrap<V>>
130
+ : T extends Function | Date | Map<unknown, unknown> | Node | Window
131
+ ? T
132
+ : T extends readonly unknown[]
133
+ ? {
134
+ [K in keyof T]: T[K] extends Readonly<Ref<any>>
135
+ ? T[K]
136
+ : Unwrap<T[K]>;
137
+ }
138
+ : T extends object
139
+ ? { [K in keyof T]: Unwrap<T[K]> }
140
+ : T;
141
+ export type DeepReadonly<T> = T extends
142
+ ((...args: any[]) => any) | Date | RegExp | Node | Window
143
+ ? T
144
+ : T extends Readonly<Ref<infer V>>
145
+ ? Readonly<Ref<DeepReadonly<Unwrap<V>>>>
146
+ : T extends Set<infer V> | ReadonlySet<infer V>
147
+ ? ReadonlySet<DeepReadonly<V>>
148
+ : T extends Map<infer K, infer V> | ReadonlyMap<infer K, infer V>
149
+ ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
150
+ : T extends readonly unknown[]
151
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
152
+ : T extends object
153
+ ? { readonly [K in keyof T]: DeepReadonly<Unwrap<T[K]>> }
154
+ : T;
155
+ function rawValue<T>(value: T): T {
156
+ return toRaw(value);
157
+ }
158
+ function wrapValue<T>(value: T): T {
159
+ if (value === null || typeof value !== "object") return value;
160
+ const raw: object = unwrapStore(value);
161
+ if (rawMarked.has(value) || rawMarked.has(raw)) return raw as T;
162
+ return plain(raw) || raw instanceof Set ? (reactive(value) as T) : value;
163
+ }
164
+ function wrapReadonly<T>(value: T): T {
165
+ if (value === null || typeof value !== "object") return value;
166
+ const raw: object = toRaw(value);
167
+ if (rawMarked.has(value) || rawMarked.has(raw)) return value;
168
+ return plain(raw) || raw instanceof Set ? (readonly(value) as T) : value;
169
+ }
65
170
  export function reactive<T extends object>(value: T): Unwrap<T> {
66
- if (!plain(value))
67
- throw new TypeError("Native reactive requires a plain object or array");
171
+ if (readonlyProxies.has(value)) return value as Unwrap<T>;
68
172
  const existing = proxies.get(value);
69
173
  if (existing) return existing as Unwrap<T>;
70
- const mutable = createMutable(value, { equals: Object.is });
174
+ const rawTarget = unwrapStore(value);
175
+ if (rawMarked.has(value) || rawMarked.has(rawTarget))
176
+ return rawTarget as Unwrap<T>;
177
+ const cachedRaw = proxies.get(rawTarget);
178
+ if (cachedRaw) return cachedRaw as Unwrap<T>;
179
+ if (rawTarget instanceof Set) {
180
+ if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
181
+ const proxy = createTrackedSet(rawTarget, wrapValue, rawValue);
182
+ reactiveProxies.add(proxy);
183
+ targets.set(proxy, rawTarget);
184
+ proxies.set(rawTarget, proxy);
185
+ proxies.set(proxy, proxy);
186
+ return proxy as Unwrap<T>;
187
+ }
188
+ if (!plain(rawTarget))
189
+ throw new TypeError(
190
+ "Native reactive requires a plain object, array or Set",
191
+ );
192
+ if (!Object.isExtensible(rawTarget)) return rawTarget as Unwrap<T>;
193
+ const mutable = createMutable(rawTarget, { equals: Object.is });
71
194
  const cached = proxies.get(mutable);
72
195
  if (cached) return cached as Unwrap<T>;
73
196
  const proxy = new Proxy(mutable, {
@@ -75,11 +198,10 @@ export function reactive<T extends object>(value: T): Unwrap<T> {
75
198
  const next = Reflect.get(target, key, receiver);
76
199
  if (isRef(next))
77
200
  return Array.isArray(target) && arrayIndex(key) ? next : next.value;
78
- return plain(next) ? reactive(next) : next;
201
+ return wrapValue(next);
79
202
  },
80
203
  set(target, key, next) {
81
- if (typeof next === "object" && next !== null)
82
- next = targets.get(next) ?? next;
204
+ if (typeof next === "object" && next !== null) next = toRaw(next);
83
205
  return batch(() =>
84
206
  untrack(() => {
85
207
  const previous = Reflect.get(target, key);
@@ -95,35 +217,454 @@ export function reactive<T extends object>(value: T): Unwrap<T> {
95
217
  );
96
218
  },
97
219
  });
98
- targets.set(proxy, mutable);
220
+ reactiveProxies.add(proxy);
221
+ targets.set(proxy, rawTarget);
222
+ proxies.set(rawTarget, proxy);
99
223
  proxies.set(mutable, proxy);
100
224
  proxies.set(proxy, proxy);
101
225
  return proxy as Unwrap<T>;
102
226
  }
227
+
228
+ type ShallowCell = ReturnType<typeof createSignal<number>>;
229
+ type ShallowState = {
230
+ reads: Map<PropertyKey, ShallowCell>;
231
+ has: Map<PropertyKey, ShallowCell>;
232
+ keys?: ShallowCell;
233
+ };
234
+ const shallowStates = new WeakMap<object, ShallowState>();
235
+ const shallowArrayMutations = new Set([
236
+ "push",
237
+ "pop",
238
+ "shift",
239
+ "unshift",
240
+ "splice",
241
+ "sort",
242
+ "reverse",
243
+ "fill",
244
+ "copyWithin",
245
+ ]);
246
+ function getShallowState(target: object): ShallowState {
247
+ let node = shallowStates.get(target);
248
+ if (!node) {
249
+ node = { reads: new Map(), has: new Map() };
250
+ shallowStates.set(target, node);
251
+ }
252
+ return node;
253
+ }
254
+ function trackShallow(
255
+ map: Map<PropertyKey, ShallowCell>,
256
+ key: PropertyKey,
257
+ ): void {
258
+ if (!isTracking()) return;
259
+ let cell = map.get(key);
260
+ if (!cell) map.set(key, (cell = createSignal(0, { equals: false })));
261
+ cell[0]();
262
+ }
263
+ function notifyShallow(cell: ShallowCell | undefined): void {
264
+ cell?.[1]((version) => version + 1);
265
+ }
266
+
267
+ export function shallowReactive<T extends object>(value: T): T {
268
+ if (readonlyProxies.has(value)) return value;
269
+ if (shallowProxies.has(value) && reactiveProxies.has(value)) return value;
270
+ const rawTarget = toRaw(value);
271
+ if (
272
+ rawMarked.has(value) ||
273
+ rawMarked.has(rawTarget) ||
274
+ !Object.isExtensible(rawTarget)
275
+ )
276
+ return rawTarget;
277
+ const existing = shallowReactiveMap.get(rawTarget);
278
+ if (existing) return existing as T;
279
+ if (rawTarget instanceof Set) {
280
+ const proxy = createTrackedSet(rawTarget, (v) => v, rawValue);
281
+ reactiveProxies.add(proxy);
282
+ shallowProxies.add(proxy);
283
+ targets.set(proxy, rawTarget);
284
+ shallowReactiveMap.set(rawTarget, proxy);
285
+ shallowReactiveMap.set(proxy, proxy);
286
+ return proxy as unknown as T;
287
+ }
288
+ if (!plain(rawTarget))
289
+ throw new TypeError(
290
+ "Native shallowReactive requires a plain object, array or Set",
291
+ );
292
+ const methods = new Map<PropertyKey, Function>();
293
+ const proxy = new Proxy(rawTarget, {
294
+ get(target, key, receiver) {
295
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
296
+ if (
297
+ !descriptor?.get &&
298
+ (Object.hasOwn(target, key) ||
299
+ typeof (target as Record<PropertyKey, unknown>)[key] !== "function")
300
+ ) {
301
+ trackShallow(getShallowState(target).reads, key);
302
+ }
303
+ const result = Reflect.get(target, key, receiver);
304
+ if (
305
+ Array.isArray(target) &&
306
+ typeof key === "string" &&
307
+ shallowArrayMutations.has(key) &&
308
+ result === Reflect.get(Array.prototype, key)
309
+ ) {
310
+ let method = methods.get(key);
311
+ if (!method) {
312
+ method = function (this: unknown, ...args: unknown[]) {
313
+ return batch(() =>
314
+ untrack(() => Reflect.apply(result as Function, this, args)),
315
+ );
316
+ };
317
+ methods.set(key, method);
318
+ }
319
+ return method;
320
+ }
321
+ return result;
322
+ },
323
+ has(target, key) {
324
+ trackShallow(getShallowState(target).has, key);
325
+ return Reflect.has(target, key);
326
+ },
327
+ ownKeys(target) {
328
+ if (isTracking()) {
329
+ const node = getShallowState(target);
330
+ if (Array.isArray(target)) trackShallow(node.reads, "length");
331
+ else (node.keys ??= createSignal(0, { equals: false }))[0]();
332
+ }
333
+ return Reflect.ownKeys(target);
334
+ },
335
+ set(target, key, next, receiver) {
336
+ return batch(() =>
337
+ untrack(() => {
338
+ const isArray = Array.isArray(target);
339
+ const prevLength = isArray ? target.length : 0;
340
+ const hadKey = Object.hasOwn(target, key);
341
+ const previous = (target as Record<PropertyKey, unknown>)[key];
342
+ const ok = Reflect.set(target, key, next, receiver);
343
+ if (!ok) return false;
344
+ const node = shallowStates.get(target);
345
+ if (!node) return true;
346
+ if (!hadKey) {
347
+ notifyShallow(node.reads.get(key));
348
+ notifyShallow(node.has.get(key));
349
+ notifyShallow(node.keys);
350
+ if (isArray && target.length !== prevLength) {
351
+ notifyShallow(node.reads.get("length"));
352
+ }
353
+ } else if (!Object.is(previous, next)) {
354
+ notifyShallow(node.reads.get(key));
355
+ if (isArray) {
356
+ if (key === "length" && target.length < prevLength) {
357
+ for (let i = target.length; i < prevLength; i++) {
358
+ const idxKey = String(i);
359
+ notifyShallow(node.reads.get(idxKey));
360
+ notifyShallow(node.has.get(idxKey));
361
+ }
362
+ notifyShallow(node.keys);
363
+ } else if (key !== "length" && target.length !== prevLength) {
364
+ notifyShallow(node.reads.get("length"));
365
+ }
366
+ }
367
+ }
368
+ return true;
369
+ }),
370
+ );
371
+ },
372
+ deleteProperty(target, key) {
373
+ return batch(() =>
374
+ untrack(() => {
375
+ const hadKey = Object.hasOwn(target, key);
376
+ const ok = Reflect.deleteProperty(target, key);
377
+ if (ok && hadKey) {
378
+ const node = shallowStates.get(target);
379
+ if (node) {
380
+ notifyShallow(node.reads.get(key));
381
+ notifyShallow(node.has.get(key));
382
+ notifyShallow(node.keys);
383
+ }
384
+ }
385
+ return ok;
386
+ }),
387
+ );
388
+ },
389
+ });
390
+ reactiveProxies.add(proxy);
391
+ shallowProxies.add(proxy);
392
+ targets.set(proxy, rawTarget);
393
+ shallowReactiveMap.set(rawTarget, proxy);
394
+ shallowReactiveMap.set(proxy, proxy);
395
+ return proxy as T;
396
+ }
397
+
398
+ const readonlySetStates = new WeakMap<
399
+ object,
400
+ { target: Set<unknown>; deep: boolean }
401
+ >();
402
+ function readonlySetState(value: object) {
403
+ const found = readonlySetStates.get(value);
404
+ if (!found) throw new TypeError("Set method requires a native readonly Set");
405
+ return found;
406
+ }
407
+ function readonlySetIterator(
408
+ receiver: Set<unknown>,
409
+ entries: boolean,
410
+ ): SetIterator<any> {
411
+ const s = readonlySetState(receiver);
412
+ return (function* () {
413
+ for (const value of s.target) {
414
+ const wrapped = s.deep ? wrapReadonly(value) : value;
415
+ yield entries ? [wrapped, wrapped] : wrapped;
416
+ }
417
+ return undefined;
418
+ })();
419
+ }
420
+ const readonlySetMethods = {
421
+ get size() {
422
+ return readonlySetState(this).target.size;
423
+ },
424
+ has(this: Set<unknown>, key: unknown) {
425
+ const { target } = readonlySetState(this);
426
+ const raw = toRaw(key);
427
+ return target.has(key) || target.has(raw);
428
+ },
429
+ add() {
430
+ throw new TypeError("Cannot mutate a readonly Set");
431
+ },
432
+ delete() {
433
+ throw new TypeError("Cannot mutate a readonly Set");
434
+ },
435
+ clear() {
436
+ throw new TypeError("Cannot mutate a readonly Set");
437
+ },
438
+ keys(this: Set<unknown>) {
439
+ return readonlySetIterator(this, false);
440
+ },
441
+ values(this: Set<unknown>) {
442
+ return readonlySetIterator(this, false);
443
+ },
444
+ entries(this: Set<unknown>) {
445
+ return readonlySetIterator(this, true);
446
+ },
447
+ [Symbol.iterator](this: Set<unknown>) {
448
+ return readonlySetIterator(this, false);
449
+ },
450
+ forEach(
451
+ this: Set<unknown>,
452
+ callback: (value: unknown, key: unknown, set: Set<unknown>) => void,
453
+ thisArg?: unknown,
454
+ ) {
455
+ if (typeof callback !== "function")
456
+ throw new TypeError("Set callback must be a function");
457
+ const s = readonlySetState(this);
458
+ s.target.forEach((value) => {
459
+ const wrapped = s.deep ? wrapReadonly(value) : value;
460
+ callback.call(thisArg, wrapped, wrapped, this);
461
+ });
462
+ },
463
+ };
464
+ function createReadonlySet(target: Set<unknown>, deep: boolean): Set<unknown> {
465
+ const proxy = new Proxy(target, {
466
+ get(source, key, receiver) {
467
+ return Object.hasOwn(readonlySetMethods, key) && key in source
468
+ ? Reflect.get(readonlySetMethods, key, receiver)
469
+ : Reflect.get(source, key, receiver);
470
+ },
471
+ });
472
+ readonlySetStates.set(proxy, { target, deep });
473
+ return proxy;
474
+ }
475
+
476
+ function createReadonly<T extends object>(value: T, shallow: boolean): any {
477
+ if (isRef(value)) {
478
+ if (readonlyRefs.has(value) && (!shallow || shallowProxies.has(value))) {
479
+ return value;
480
+ }
481
+ const cache = shallow ? shallowReadonlyMap : readonlyMap;
482
+ const cachedRef = cache.get(value);
483
+ if (cachedRef) return cachedRef;
484
+ const roRef = new Ref(() =>
485
+ shallow ? value.value : wrapReadonly(value.value),
486
+ );
487
+ if (shallow) shallowProxies.add(roRef);
488
+ targets.set(roRef, value);
489
+ cache.set(value, roRef);
490
+ return roRef;
491
+ }
492
+ if (!shallow && readonlyProxies.has(value) && !shallowProxies.has(value)) {
493
+ return value;
494
+ }
495
+ if (shallow && readonlyProxies.has(value) && shallowProxies.has(value)) {
496
+ return value;
497
+ }
498
+ const underlying = readonlyProxies.has(value)
499
+ ? ((targets.get(value) as T) ?? value)
500
+ : value;
501
+ const rawCandidate = toRaw(underlying);
502
+ if (
503
+ rawMarked.has(value) ||
504
+ rawMarked.has(underlying) ||
505
+ rawMarked.has(rawCandidate) ||
506
+ !Object.isExtensible(rawCandidate)
507
+ ) {
508
+ return value;
509
+ }
510
+ const cache = shallow ? shallowReadonlyMap : readonlyMap;
511
+ const existing = cache.get(underlying);
512
+ if (existing) return existing;
513
+ if (rawCandidate instanceof Set) {
514
+ const proxy = createReadonlySet(
515
+ underlying as unknown as Set<unknown>,
516
+ !shallow,
517
+ );
518
+ readonlyProxies.add(proxy);
519
+ if (shallow) shallowProxies.add(proxy);
520
+ targets.set(proxy, underlying);
521
+ cache.set(underlying, proxy);
522
+ cache.set(proxy, proxy);
523
+ return proxy;
524
+ }
525
+ if (!plain(rawCandidate))
526
+ throw new TypeError(
527
+ "Native readonly requires a plain object, array or Set",
528
+ );
529
+ const proxy = new Proxy(underlying, {
530
+ get(target, key, receiver) {
531
+ const next = Reflect.get(target, key, receiver);
532
+ if (shallow) return next;
533
+ if (isRef(next)) {
534
+ return Array.isArray(target) && arrayIndex(key)
535
+ ? readonly(next)
536
+ : wrapReadonly(next.value);
537
+ }
538
+ return wrapReadonly(next);
539
+ },
540
+ set(_target, key) {
541
+ throw new TypeError(
542
+ `Cannot assign to read only property '${String(key)}'`,
543
+ );
544
+ },
545
+ deleteProperty(_target, key) {
546
+ throw new TypeError(
547
+ `Cannot delete property '${String(key)}' of a readonly object`,
548
+ );
549
+ },
550
+ defineProperty(_target, key) {
551
+ throw new TypeError(
552
+ `Cannot define property '${String(key)}' on a readonly object`,
553
+ );
554
+ },
555
+ });
556
+ readonlyProxies.add(proxy);
557
+ if (shallow) shallowProxies.add(proxy);
558
+ targets.set(proxy, underlying);
559
+ cache.set(underlying, proxy);
560
+ cache.set(proxy, proxy);
561
+ return proxy;
562
+ }
563
+
564
+ export function readonly<T extends object>(value: T): DeepReadonly<T> {
565
+ return createReadonly(value, false);
566
+ }
567
+ export function shallowReadonly<T extends object>(value: T): Readonly<T> {
568
+ return createReadonly(value, true);
569
+ }
570
+
103
571
  export function ref<T>(value: Ref<T>): Ref<T>;
104
572
  export function ref<T>(value: T): Ref<Unwrap<T>>;
105
- export function ref<T>(value: T | Ref<T>): Ref<any> {
573
+ export function ref<T = any>(): Ref<T | undefined>;
574
+ export function ref<T>(value?: T | Ref<T>): Ref<any> {
106
575
  if (isRef(value)) return value;
107
- const convert = (next: T): T => (plain(next) ? (reactive(next) as T) : next);
576
+ const convert = wrapValue<T>;
577
+ let forceTrigger = false;
108
578
  const [read, write] = createSignal(convert(value as T), {
109
- equals: Object.is,
579
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
580
+ });
581
+ const refObject = new Ref(read, (next) => write(() => convert(next)));
582
+ refTriggers.set(refObject, () => {
583
+ forceTrigger = true;
584
+ try {
585
+ refTriggerVersions.set(
586
+ refObject,
587
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
588
+ );
589
+ write((current) => current);
590
+ } finally {
591
+ forceTrigger = false;
592
+ }
110
593
  });
111
- return new Ref(read, (next) => write(() => convert(next)));
594
+ return refObject;
112
595
  }
113
- /** Keep external snapshots intact; only replacing .value notifies this ref. */
596
+ /** Keep external snapshots intact; only replacing .value or triggerRef notifies this ref. */
114
597
  export function shallowRef<T extends Readonly<Ref<any>>>(value: T): T;
115
598
  export function shallowRef<T>(value: T): Ref<T>;
116
599
  export function shallowRef<T = any>(): Ref<T | undefined>;
117
600
  export function shallowRef(value?: unknown): Ref<any> {
118
601
  if (isRef(value)) return value;
119
- const [read, write] = createSignal(value, { equals: Object.is });
120
- return new Ref(read, (next) => write(() => next));
602
+ let forceTrigger = false;
603
+ const [read, write] = createSignal<unknown>(value, {
604
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
605
+ });
606
+ const refObject = new Ref(read, (next) => write(() => next));
607
+ shallowProxies.add(refObject);
608
+ refTriggers.set(refObject, () => {
609
+ forceTrigger = true;
610
+ try {
611
+ refTriggerVersions.set(
612
+ refObject,
613
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
614
+ );
615
+ write((current: unknown) => current);
616
+ } finally {
617
+ forceTrigger = false;
618
+ }
619
+ });
620
+ return refObject;
621
+ }
622
+ export function triggerRef(target: Readonly<Ref<any>>): void {
623
+ if (!isRef(target)) throw new TypeError("triggerRef requires a native ref");
624
+ refTriggers.get(target)?.();
625
+ }
626
+ export type CustomRefFactory<T> = (
627
+ track: () => void,
628
+ trigger: () => void,
629
+ ) => {
630
+ get: () => T;
631
+ set: (value: T) => void;
632
+ };
633
+ export function customRef<T>(factory: CustomRefFactory<T>): Ref<T> {
634
+ if (typeof factory !== "function")
635
+ throw new TypeError("customRef requires a factory function");
636
+ const [readVersion, writeVersion] = createSignal(0, { equals: false });
637
+ let refObject!: Ref<T>;
638
+ const track = () => {
639
+ readVersion();
640
+ };
641
+ const trigger = () => {
642
+ refTriggerVersions.set(
643
+ refObject,
644
+ (refTriggerVersions.get(refObject) ?? 0) + 1,
645
+ );
646
+ writeVersion((v) => v + 1);
647
+ };
648
+ const { get, set } = factory(track, trigger);
649
+ if (typeof get !== "function" || typeof set !== "function")
650
+ throw new TypeError("customRef factory must return get and set functions");
651
+ refObject = new Ref(
652
+ () => get(),
653
+ (value) => set(value),
654
+ );
655
+ refTriggers.set(refObject, trigger);
656
+ return refObject;
121
657
  }
122
658
  /** Unwrap native refs without invoking ordinary function values. */
123
659
  export function unref<T>(value: T): T extends Readonly<Ref<infer V>> ? V : T;
124
660
  export function unref(value: unknown): unknown {
125
661
  return isRef(value) ? value.value : value;
126
662
  }
663
+ /** Normalize values, refs, and zero-arg getters to their underlying value. */
664
+ export function toValue<T>(source: MaybeRefOrGetter<T>): T;
665
+ export function toValue(source: unknown): unknown {
666
+ return typeof source === "function" ? source() : unref(source);
667
+ }
127
668
  export type ToRef<T> = [T] extends [Readonly<Ref<any>>] ? T : Ref<T>;
128
669
  export function toRef<T extends Readonly<Ref<any>>>(value: T): T;
129
670
  export function toRef<T>(getter: () => T): Readonly<Ref<T>>;
@@ -205,128 +746,355 @@ export function computed<T>(
205
746
  );
206
747
  }
207
748
  export type WatchSource<T = unknown> = Readonly<Ref<T>> | (() => T);
208
- export type WatchOptions = { flush: "sync"; immediate?: boolean };
749
+ export type WatchOptions = {
750
+ flush: "sync";
751
+ immediate?: boolean;
752
+ deep?: boolean | number;
753
+ once?: boolean;
754
+ };
755
+ export type WatchStopHandle = () => void;
756
+ export interface WatchHandle extends WatchStopHandle {
757
+ pause: () => void;
758
+ resume: () => void;
759
+ stop: () => void;
760
+ }
761
+ export type WatchCallback<V = any, OV = any> = (
762
+ value: V,
763
+ previous: OV,
764
+ onCleanup: (fn: () => void) => void,
765
+ ) => void;
766
+ type MapWatchSources<T> = {
767
+ -readonly [K in keyof T]: T[K] extends WatchSource<infer V>
768
+ ? V
769
+ : T[K] extends object
770
+ ? T[K]
771
+ : never;
772
+ };
773
+
774
+ let activeWatcherCleanup: ((fn: () => void) => void) | undefined;
775
+
776
+ export function onWatcherCleanup(
777
+ cleanupFn: () => void,
778
+ failSilently = false,
779
+ ): void {
780
+ if (typeof cleanupFn !== "function")
781
+ throw new TypeError("Watcher cleanup must be a function");
782
+ if (activeWatcherCleanup) {
783
+ activeWatcherCleanup(cleanupFn);
784
+ } else if (!failSilently) {
785
+ throw new Error("onWatcherCleanup requires an active watcher");
786
+ }
787
+ }
788
+
789
+ type DepSnapshot = Array<{ node: Trackable; version: number }>;
790
+ function captureDeps(fn: () => void): DepSnapshot {
791
+ const nodes = collectDeps(fn, undefined, true);
792
+ return nodes.map((node) => ({ node, version: node.version }));
793
+ }
794
+ function depsChanged(prev: DepSnapshot, next: DepSnapshot): boolean {
795
+ if (prev.length !== next.length) return true;
796
+ for (let i = 0; i < next.length; i++) {
797
+ if (
798
+ prev[i]!.node !== next[i]!.node ||
799
+ prev[i]!.version !== next[i]!.version
800
+ )
801
+ return true;
802
+ }
803
+ return false;
804
+ }
805
+ function traverse(
806
+ value: unknown,
807
+ depth = Infinity,
808
+ seen = new Set<unknown>(),
809
+ ): unknown {
810
+ if (
811
+ depth <= 0 ||
812
+ value === null ||
813
+ typeof value !== "object" ||
814
+ rawMarked.has(value) ||
815
+ rawMarked.has(toRaw(value))
816
+ )
817
+ return value;
818
+ if (seen.has(value)) return value;
819
+ seen.add(value);
820
+ depth--;
821
+ if (isRef(value)) {
822
+ const inner = value.value;
823
+ if (depth > 0) traverse(inner, depth, seen);
824
+ } else if (Array.isArray(value)) {
825
+ for (let i = 0; i < value.length; i++) {
826
+ traverse(value[i], depth, seen);
827
+ }
828
+ } else if (value instanceof Set || value instanceof Map) {
829
+ value.forEach((entry) => {
830
+ traverse(entry, depth, seen);
831
+ });
832
+ } else if (plain(value)) {
833
+ for (const key in value) {
834
+ traverse(value[key], depth, seen);
835
+ }
836
+ for (const symbol of Object.getOwnPropertySymbols(value)) {
837
+ if (Object.prototype.propertyIsEnumerable.call(value, symbol)) {
838
+ traverse(value[symbol], depth, seen);
839
+ }
840
+ }
841
+ }
842
+ return value;
843
+ }
844
+ function createWatchHandle(
845
+ stop: () => void,
846
+ pause: () => void,
847
+ resume: () => void,
848
+ ): WatchHandle {
849
+ const handle = (() => {
850
+ stop();
851
+ }) as WatchHandle;
852
+ handle.stop = stop;
853
+ handle.pause = pause;
854
+ handle.resume = resume;
855
+ return handle;
856
+ }
857
+
209
858
  export function watch<T>(
210
859
  source: WatchSource<T>,
211
- callback: (
212
- value: T,
213
- previous: T | undefined,
214
- onCleanup: (fn: () => void) => void,
215
- ) => void,
860
+ callback: WatchCallback<T, T | undefined>,
216
861
  options: WatchOptions,
217
- ): () => void;
862
+ ): WatchHandle;
218
863
  export function watch<T extends readonly unknown[]>(
219
864
  source: { [K in keyof T]: WatchSource<T[K]> },
220
- callback: (
221
- value: T,
222
- previous: T | undefined,
223
- onCleanup: (fn: () => void) => void,
224
- ) => void,
865
+ callback: WatchCallback<T, T | undefined>,
866
+ options: WatchOptions,
867
+ ): WatchHandle;
868
+ export function watch<T extends readonly (WatchSource<unknown> | object)[]>(
869
+ source: readonly [...T],
870
+ callback: WatchCallback<MapWatchSources<T>, MapWatchSources<T> | undefined>,
871
+ options: WatchOptions,
872
+ ): WatchHandle;
873
+ export function watch<T extends object>(
874
+ source: T,
875
+ callback: WatchCallback<T, T | undefined>,
225
876
  options: WatchOptions,
226
- ): () => void;
877
+ ): WatchHandle;
227
878
  export function watch(
228
- source: WatchSource<any> | readonly WatchSource<any>[],
229
- callback: (
230
- value: any,
231
- previous: any,
232
- onCleanup: (fn: () => void) => void,
233
- ) => void,
879
+ source: WatchSource<any> | object | readonly (WatchSource<any> | object)[],
880
+ callback: WatchCallback<any, any>,
234
881
  options: WatchOptions,
235
- ): () => void {
882
+ ): WatchHandle {
236
883
  if (
237
884
  !options ||
238
885
  options.flush !== "sync" ||
239
- Object.keys(options).some((key) => key !== "flush" && key !== "immediate")
886
+ Object.keys(options).some(
887
+ (key) =>
888
+ key !== "flush" &&
889
+ key !== "immediate" &&
890
+ key !== "deep" &&
891
+ key !== "once",
892
+ ) ||
893
+ (options.immediate !== undefined &&
894
+ typeof options.immediate !== "boolean") ||
895
+ (options.once !== undefined && typeof options.once !== "boolean") ||
896
+ (options.deep !== undefined &&
897
+ typeof options.deep !== "boolean" &&
898
+ (typeof options.deep !== "number" || Number.isNaN(options.deep)))
240
899
  )
241
900
  throw new TypeError(
242
- "Native watch supports only flush:'sync' and immediate",
901
+ "Native watch supports only flush:'sync', immediate, deep, and once",
243
902
  );
244
903
  const sources = Array.isArray(source) ? source : [source];
245
- if (sources.some((item) => !isRef(item) && typeof item !== "function"))
246
- throw new TypeError("Native watch requires refs or getters");
904
+ if (
905
+ sources.some(
906
+ (item) => !isRef(item) && !isReactive(item) && typeof item !== "function",
907
+ )
908
+ )
909
+ throw new TypeError(
910
+ "Native watch requires refs, reactive objects, or getters",
911
+ );
247
912
  const outer = getOwner();
248
913
  if (outer?.disposed)
249
914
  throw new Error("Cannot watch from a disposed native owner");
250
915
  const reportError = captureWatchErrorHandler();
916
+ const depths = sources.map((item) => {
917
+ if (typeof options.deep === "number")
918
+ return options.deep <= 0 ? 0 : options.deep;
919
+ if (options.deep === true) return Infinity;
920
+ if (options.deep === false) return isReactive(item) ? 1 : 0;
921
+ return isReactive(item) ? (isShallow(item) ? 1 : Infinity) : 0;
922
+ });
251
923
  let stop!: () => void;
924
+ let pause!: () => void;
925
+ let resume!: () => void;
252
926
  createRoot((dispose) => {
253
927
  stop = dispose;
254
928
  let previous: any[] | undefined;
929
+ let previousVersions: number[] | undefined;
930
+ let previousDepSnapshots: Array<DepSnapshot | undefined> | undefined;
255
931
  let reading = false;
256
- const cleanups: Array<() => void> = [];
257
932
  let active = true;
933
+ let paused = false;
934
+ let dirtyWhilePaused = false;
935
+ let lastDeps: Array<Parameters<typeof trackDependency>[0]> = [];
936
+ const [readResume, writeResume] = createSignal(0, { equals: false });
937
+ const cleanups: Array<() => void> = [];
938
+ pause = () => {
939
+ if (active) paused = true;
940
+ };
941
+ resume = () => {
942
+ if (!active || !paused) return;
943
+ paused = false;
944
+ if (dirtyWhilePaused) {
945
+ dirtyWhilePaused = false;
946
+ writeResume((v) => v + 1);
947
+ }
948
+ };
258
949
  const clean = () => {
259
950
  let failed = false;
260
951
  let failure: unknown;
261
- for (const fn of cleanups.splice(0)) {
262
- try {
263
- untrack(() =>
264
- reportError ? invokeWatch(reportError, "watch cleanup", fn) : fn(),
265
- );
266
- } catch (error) {
267
- if (!failed) failure = error;
268
- failed = true;
952
+ const prevCleanup = activeWatcherCleanup;
953
+ activeWatcherCleanup = undefined;
954
+ try {
955
+ for (const fn of cleanups.splice(0)) {
956
+ try {
957
+ untrack(() =>
958
+ reportError
959
+ ? invokeWatch(reportError, "watch cleanup", fn)
960
+ : fn(),
961
+ );
962
+ } catch (error) {
963
+ if (!failed) failure = error;
964
+ failed = true;
965
+ }
269
966
  }
967
+ } finally {
968
+ activeWatcherCleanup = prevCleanup;
270
969
  }
271
970
  if (failed) throw failure;
272
971
  };
273
972
  onCleanup(() => {
274
973
  active = false;
974
+ paused = false;
975
+ dirtyWhilePaused = false;
275
976
  clean();
276
977
  });
277
978
  createComputed(() => {
979
+ readResume();
278
980
  // Getter reporting may write its source; callback feedback remains reentrant.
279
- if (reportError && reading) return;
280
- let values: any[];
981
+ if ((reportError && reading) || !active) return;
982
+ if (paused) {
983
+ dirtyWhilePaused = true;
984
+ for (const dep of lastDeps) {
985
+ dep.validate?.();
986
+ trackDependency(dep);
987
+ }
988
+ return;
989
+ }
990
+ let values!: any[];
991
+ const depSnapshots: Array<DepSnapshot | undefined> = [];
992
+ const prevCleanup = activeWatcherCleanup;
993
+ activeWatcherCleanup = undefined;
281
994
  reading = true;
282
995
  try {
283
- values = sources.map((item) =>
284
- isRef(item)
285
- ? item.value
286
- : reportError
287
- ? invokeWatch(reportError, "watch getter", item)
288
- : item(),
289
- );
996
+ lastDeps = collectDeps(
997
+ () => {
998
+ values = sources.map((item, i) => {
999
+ const depth = depths[i]!;
1000
+ let value: any;
1001
+ if (depth > 0) {
1002
+ depSnapshots[i] = captureDeps(() => {
1003
+ value = isRef(item)
1004
+ ? item.value
1005
+ : typeof item === "function"
1006
+ ? reportError
1007
+ ? invokeWatch(reportError, "watch getter", item)
1008
+ : item()
1009
+ : item;
1010
+ traverse(value, depth);
1011
+ });
1012
+ } else {
1013
+ value = isRef(item)
1014
+ ? item.value
1015
+ : typeof item === "function"
1016
+ ? reportError
1017
+ ? invokeWatch(reportError, "watch getter", item)
1018
+ : item()
1019
+ : item;
1020
+ }
1021
+ return value;
1022
+ });
1023
+ },
1024
+ undefined,
1025
+ true,
1026
+ ) as Array<Parameters<typeof trackDependency>[0]>;
290
1027
  } finally {
291
1028
  reading = false;
1029
+ activeWatcherCleanup = prevCleanup;
292
1030
  }
1031
+ const versions = sources.map((item) =>
1032
+ isRef(item) ? (refTriggerVersions.get(item) ?? 0) : 0,
1033
+ );
293
1034
  if (
294
1035
  previous &&
295
- values.every((value, i) => Object.is(value, previous![i]))
1036
+ values.every(
1037
+ (value, i) =>
1038
+ Object.is(value, previous![i]) &&
1039
+ versions[i] === previousVersions![i] &&
1040
+ (depths[i] === 0 ||
1041
+ !depsChanged(previousDepSnapshots![i]!, depSnapshots[i]!)),
1042
+ )
296
1043
  )
297
1044
  return;
298
1045
  const old = previous;
299
1046
  previous = values;
1047
+ previousVersions = versions;
1048
+ previousDepSnapshots = depSnapshots;
300
1049
  if (!old && !options.immediate) return;
301
1050
  untrack(() => {
302
1051
  clean();
303
1052
  if (!active) return;
304
- const invoke = () =>
305
- callback(
306
- Array.isArray(source) ? values : values[0],
307
- Array.isArray(source) ? old : old?.[0],
308
- (fn) => {
309
- if (typeof fn !== "function")
310
- throw new TypeError("Watcher cleanup must be a function");
311
- if (active) cleanups.push(fn);
312
- else if (reportError)
313
- invokeWatch(reportError, "watch cleanup", fn);
314
- else fn();
315
- },
316
- );
317
- if (reportError) invokeWatch(reportError, "watch callback", invoke);
318
- else invoke();
1053
+ const registerCleanup = (fn: () => void) => {
1054
+ if (typeof fn !== "function")
1055
+ throw new TypeError("Watcher cleanup must be a function");
1056
+ if (active) cleanups.push(fn);
1057
+ else if (reportError) invokeWatch(reportError, "watch cleanup", fn);
1058
+ else fn();
1059
+ };
1060
+ const invoke = () => {
1061
+ const previousCleanup = activeWatcherCleanup;
1062
+ activeWatcherCleanup = registerCleanup;
1063
+ try {
1064
+ return callback(
1065
+ Array.isArray(source) ? values : values[0],
1066
+ Array.isArray(source) ? old : old?.[0],
1067
+ registerCleanup,
1068
+ );
1069
+ } finally {
1070
+ activeWatcherCleanup = previousCleanup;
1071
+ }
1072
+ };
1073
+ try {
1074
+ if (reportError) invokeWatch(reportError, "watch callback", invoke);
1075
+ else invoke();
1076
+ } catch (error) {
1077
+ if (options.once && active) {
1078
+ try {
1079
+ stop();
1080
+ } catch {
1081
+ /* Preserve callback failure when once-stop cleanup also throws. */
1082
+ }
1083
+ }
1084
+ throw error;
1085
+ }
1086
+ if (options.once && active) stop();
319
1087
  });
320
1088
  });
321
1089
  });
322
1090
  if (outer) onCleanup(stop);
323
- return stop;
1091
+ return createWatchHandle(stop, pause, resume);
324
1092
  }
325
1093
 
326
1094
  /** Synchronously track an owned effect; no component render scheduler is implied. */
327
1095
  export function watchSyncEffect(
328
1096
  effect: (onCleanup: (fn: () => void) => void) => void,
329
- ): () => void {
1097
+ ): WatchHandle {
330
1098
  if (typeof effect !== "function")
331
1099
  throw new TypeError("Watcher effect must be a function");
332
1100
  const outer = getOwner();
@@ -334,51 +1102,100 @@ export function watchSyncEffect(
334
1102
  throw new Error("Cannot watch from a disposed native owner");
335
1103
  const reportError = captureWatchErrorHandler();
336
1104
  let stop!: () => void;
1105
+ let pause!: () => void;
1106
+ let resume!: () => void;
337
1107
  createRoot((dispose) => {
338
1108
  stop = dispose;
339
1109
  let active = true;
340
1110
  let running = false;
1111
+ let paused = false;
1112
+ let dirtyWhilePaused = false;
1113
+ let lastDeps: Array<Parameters<typeof trackDependency>[0]> = [];
1114
+ const [readResume, writeResume] = createSignal(0, { equals: false });
341
1115
  const cleanups: Array<() => void> = [];
1116
+ pause = () => {
1117
+ if (active) paused = true;
1118
+ };
1119
+ resume = () => {
1120
+ if (!active || !paused) return;
1121
+ paused = false;
1122
+ if (dirtyWhilePaused) {
1123
+ dirtyWhilePaused = false;
1124
+ writeResume((v) => v + 1);
1125
+ }
1126
+ };
342
1127
  const clean = () => {
343
1128
  let failed = false;
344
1129
  let failure: unknown;
345
- for (const fn of cleanups.splice(0)) {
346
- try {
347
- untrack(() =>
348
- reportError ? invokeWatch(reportError, "watch cleanup", fn) : fn(),
349
- );
350
- } catch (error) {
351
- if (!failed) failure = error;
352
- failed = true;
1130
+ const prevCleanup = activeWatcherCleanup;
1131
+ activeWatcherCleanup = undefined;
1132
+ try {
1133
+ for (const fn of cleanups.splice(0)) {
1134
+ try {
1135
+ untrack(() =>
1136
+ reportError
1137
+ ? invokeWatch(reportError, "watch cleanup", fn)
1138
+ : fn(),
1139
+ );
1140
+ } catch (error) {
1141
+ if (!failed) failure = error;
1142
+ failed = true;
1143
+ }
353
1144
  }
1145
+ } finally {
1146
+ activeWatcherCleanup = prevCleanup;
354
1147
  }
355
1148
  if (failed) throw failure;
356
1149
  };
357
1150
  onCleanup(() => {
358
1151
  active = false;
1152
+ paused = false;
1153
+ dirtyWhilePaused = false;
359
1154
  clean();
360
1155
  });
361
1156
  createComputed(() => {
1157
+ readResume();
362
1158
  if (running || !active) return;
1159
+ if (paused) {
1160
+ dirtyWhilePaused = true;
1161
+ for (const dep of lastDeps) {
1162
+ dep.validate?.();
1163
+ trackDependency(dep);
1164
+ }
1165
+ return;
1166
+ }
363
1167
  running = true;
364
1168
  try {
365
1169
  untrack(clean);
366
1170
  if (!active) return;
367
- const invoke = () =>
368
- effect((fn) => {
369
- if (typeof fn !== "function")
370
- throw new TypeError("Watcher cleanup must be a function");
371
- if (active) cleanups.push(fn);
372
- });
373
- if (reportError) invokeWatch(reportError, "watch effect", invoke);
374
- else invoke();
375
- } catch (error) {
376
- if (!reportError)
1171
+ const registerCleanup = (fn: () => void) => {
1172
+ if (typeof fn !== "function")
1173
+ throw new TypeError("Watcher cleanup must be a function");
1174
+ if (active) cleanups.push(fn);
1175
+ };
1176
+ const invoke = () => {
1177
+ const previousCleanup = activeWatcherCleanup;
1178
+ activeWatcherCleanup = registerCleanup;
377
1179
  try {
378
- untrack(clean);
379
- } catch {
380
- /* Preserve the effect failure. */
1180
+ return effect(registerCleanup);
1181
+ } finally {
1182
+ activeWatcherCleanup = previousCleanup;
381
1183
  }
1184
+ };
1185
+ lastDeps = collectDeps(
1186
+ () => {
1187
+ if (reportError) invokeWatch(reportError, "watch effect", invoke);
1188
+ else invoke();
1189
+ },
1190
+ undefined,
1191
+ true,
1192
+ ) as Array<Parameters<typeof trackDependency>[0]>;
1193
+ } catch (error) {
1194
+ try {
1195
+ untrack(clean);
1196
+ } catch {
1197
+ /* Preserve the effect failure. */
1198
+ }
382
1199
  throw error;
383
1200
  } finally {
384
1201
  running = false;
@@ -386,5 +1203,502 @@ export function watchSyncEffect(
386
1203
  });
387
1204
  });
388
1205
  if (outer) onCleanup(stop);
389
- return stop;
1206
+ return createWatchHandle(stop, pause, resume);
1207
+ }
1208
+
1209
+ let activeEffectScope: EffectScope | undefined;
1210
+ const componentScopes = new WeakMap<ComponentContext, EffectScope>();
1211
+ const scopeCleanups = new WeakMap<EffectScope, Array<() => void>>();
1212
+
1213
+ function runEffectScope<T>(
1214
+ scope: EffectScope,
1215
+ scopeOwner: Owner,
1216
+ fn: () => T,
1217
+ ): T {
1218
+ const prev = activeEffectScope;
1219
+ activeEffectScope = scope;
1220
+ try {
1221
+ return runWithOwner(scopeOwner, fn);
1222
+ } finally {
1223
+ activeEffectScope = prev;
1224
+ }
1225
+ }
1226
+
1227
+ export class EffectScope {
1228
+ private isActive = true;
1229
+ private readonly owner: Owner;
1230
+ private readonly disposeOwner: () => void;
1231
+ private readonly scopes: Set<EffectScope> = new Set();
1232
+ private readonly parent?: EffectScope;
1233
+
1234
+ constructor(detached = false) {
1235
+ let disposeOwner!: () => void;
1236
+ let scopeOwner!: Owner;
1237
+ createRoot((dispose) => {
1238
+ disposeOwner = dispose;
1239
+ scopeOwner = getOwner()!;
1240
+ });
1241
+ this.disposeOwner = disposeOwner;
1242
+ this.owner = scopeOwner;
1243
+ scopeCleanups.set(this, []);
1244
+ if (!detached) {
1245
+ const parent = getCurrentScope();
1246
+ if (parent && parent.active) {
1247
+ this.parent = parent;
1248
+ parent.scopes.add(this);
1249
+ } else {
1250
+ const outer = getOwner();
1251
+ if (outer && !outer.disposed) {
1252
+ onCleanup(() => this.stop(true));
1253
+ }
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ get active(): boolean {
1259
+ return this.isActive;
1260
+ }
1261
+
1262
+ run<T>(fn: () => T): T | undefined {
1263
+ if (!this.isActive) return undefined;
1264
+ return runEffectScope(this, this.owner, fn);
1265
+ }
1266
+
1267
+ stop(fromParent = false): void {
1268
+ if (!this.isActive) return;
1269
+ this.isActive = false;
1270
+ let failed = false;
1271
+ let failure: unknown;
1272
+ try {
1273
+ this.disposeOwner();
1274
+ } catch (error) {
1275
+ failed = true;
1276
+ failure = error;
1277
+ }
1278
+ for (const child of Array.from(this.scopes)) {
1279
+ this.scopes.delete(child);
1280
+ try {
1281
+ child.stop(true);
1282
+ } catch (error) {
1283
+ if (!failed) failure = error;
1284
+ failed = true;
1285
+ }
1286
+ }
1287
+ const cleanups = scopeCleanups.get(this);
1288
+ if (cleanups) {
1289
+ for (const cleanup of cleanups.splice(0)) {
1290
+ try {
1291
+ untrack(cleanup);
1292
+ } catch (error) {
1293
+ if (!failed) failure = error;
1294
+ failed = true;
1295
+ }
1296
+ }
1297
+ }
1298
+ if (!fromParent && this.parent) {
1299
+ this.parent.scopes.delete(this);
1300
+ }
1301
+ if (failed) throw failure;
1302
+ }
1303
+ }
1304
+
1305
+ export function effectScope(detached?: boolean): EffectScope {
1306
+ return new EffectScope(detached);
1307
+ }
1308
+
1309
+ export function getCurrentScope(): EffectScope | undefined {
1310
+ if (activeEffectScope) {
1311
+ return activeEffectScope.active ? activeEffectScope : undefined;
1312
+ }
1313
+ const frame = peekComponentContext();
1314
+ if (frame?.active && !frame.owner.disposed) {
1315
+ let scope = componentScopes.get(frame);
1316
+ if (!scope) {
1317
+ scope = new EffectScope(true);
1318
+ componentScopes.set(frame, scope);
1319
+ runWithOwner(frame.owner, () => {
1320
+ onCleanup(() => scope!.stop(true));
1321
+ });
1322
+ }
1323
+ return scope.active ? scope : undefined;
1324
+ }
1325
+ return undefined;
1326
+ }
1327
+
1328
+ export function onScopeDispose(fn: () => void, failSilently = false): void {
1329
+ if (typeof fn !== "function")
1330
+ throw new TypeError("onScopeDispose callback must be a function");
1331
+ const scope = getCurrentScope();
1332
+ if (scope) {
1333
+ scopeCleanups.get(scope)?.push(fn);
1334
+ } else if (!failSilently) {
1335
+ throw new Error("onScopeDispose requires an active effectScope");
1336
+ }
1337
+ }
1338
+
1339
+ export type TemplateRef<T = unknown> = Readonly<Ref<T | null>>;
1340
+
1341
+ const templateRefBindings = new WeakMap<
1342
+ Ref<any>,
1343
+ {
1344
+ get: () => any;
1345
+ set: (value: any) => void;
1346
+ }
1347
+ >();
1348
+ const componentTemplateRefKeys = new WeakMap<ComponentContext, Set<string>>();
1349
+
1350
+ /** Internal binder lookup for readonly useTemplateRef instances. */
1351
+ export function getTemplateRefBinding<T>(target: Readonly<Ref<T | null>>):
1352
+ | {
1353
+ get: () => T | null | undefined;
1354
+ set: (value: T | null) => void;
1355
+ }
1356
+ | undefined {
1357
+ return templateRefBindings.get(target as Ref<any>);
1358
+ }
1359
+
1360
+ /** Native component template ref; readonly to user code, bound by template ref wave. */
1361
+ export function useTemplateRef<T = unknown, K extends string = string>(
1362
+ key: K,
1363
+ ): TemplateRef<T> {
1364
+ const frame = getComponentContext();
1365
+ if (typeof key !== "string" || key.length === 0)
1366
+ throw new TypeError("Template ref key must be a non-empty string");
1367
+ let keys = componentTemplateRefKeys.get(frame);
1368
+ if (!keys) {
1369
+ keys = new Set();
1370
+ componentTemplateRefKeys.set(frame, keys);
1371
+ }
1372
+ if (keys.has(key))
1373
+ throw new Error(`useTemplateRef(${JSON.stringify(key)}) already exists`);
1374
+ keys.add(key);
1375
+ if (frame.mode === "ssr") return new Ref<T | null>(() => null);
1376
+ const [read, write] = createSignal<T | null>(null, { equals: Object.is });
1377
+ const refObject = new Ref<T | null>(read);
1378
+ templateRefBindings.set(refObject, { get: read, set: write });
1379
+ return refObject;
1380
+ }
1381
+
1382
+ export interface DefineModelOptions<T = any, G = T, S = T> {
1383
+ default?: any;
1384
+ required?: boolean;
1385
+ get?: (v: T) => G;
1386
+ set?: (v: S) => any;
1387
+ }
1388
+
1389
+ export type ModelRef<T, M extends PropertyKey = string, G = T, S = T> = Ref<
1390
+ G,
1391
+ S
1392
+ > &
1393
+ [ModelRef<T, M, G, S>, Record<M, true | undefined>];
1394
+
1395
+ const camelizeModelKey = (key: string) =>
1396
+ key.replace(/-(\w)/g, (_, letter: string) => letter.toUpperCase());
1397
+ const hyphenateModelKey = (key: string) =>
1398
+ key.replace(/\B([A-Z])/g, "-$1").toLowerCase();
1399
+ const emptyModelModifiers: Record<PropertyKey, true | undefined> =
1400
+ /* @__PURE__ */ Object.freeze({});
1401
+ const unsetModelValue = /* @__PURE__ */ Symbol("moonshine.vue.model.unset");
1402
+ const hasListenerOn = (target: object, key: string) =>
1403
+ key in target && Reflect.get(target, key, target) != null;
1404
+
1405
+ export function createModel<V, M extends PropertyKey = string, G = V, S = V>(
1406
+ props: Record<string, any>,
1407
+ name: string,
1408
+ options?: DefineModelOptions<V, G, S>,
1409
+ booleanCast?: boolean,
1410
+ soleFunction = false,
1411
+ ): ModelRef<V, M, G, S> {
1412
+ const frame = getComponentContext();
1413
+ if (props === null || typeof props !== "object" || Array.isArray(props)) {
1414
+ throw new TypeError("useModel requires a props object");
1415
+ }
1416
+ if (typeof name !== "string" || name.length === 0) {
1417
+ throw new TypeError("useModel requires a non-empty string prop name");
1418
+ }
1419
+ if (
1420
+ options !== undefined &&
1421
+ (options === null || typeof options !== "object" || Array.isArray(options))
1422
+ ) {
1423
+ throw new TypeError("useModel options must be an object");
1424
+ }
1425
+ if (options?.get !== undefined && typeof options.get !== "function") {
1426
+ throw new TypeError("useModel get option must be a function");
1427
+ }
1428
+ if (options?.set !== undefined && typeof options.set !== "function") {
1429
+ throw new TypeError("useModel set option must be a function");
1430
+ }
1431
+ const raw = (
1432
+ frame.props !== null &&
1433
+ typeof frame.props === "object" &&
1434
+ !Array.isArray(frame.props)
1435
+ ? frame.props
1436
+ : props
1437
+ ) as Record<string, unknown>;
1438
+ const emit = createEmitter<Record<string, readonly unknown[]>>(raw);
1439
+ const camelName = camelizeModelKey(name);
1440
+ const hyphenName = hyphenateModelKey(camelName);
1441
+ const rawUpdateEvent = "update:" + name;
1442
+ const camelUpdateKey = "onUpdate:" + camelName;
1443
+ const rawUpdateKey = "onUpdate:" + name;
1444
+ const hyphenUpdateKey = "onUpdate:" + hyphenName;
1445
+
1446
+ const hasUpdateListener = () =>
1447
+ hasListenerOn(raw, camelUpdateKey) ||
1448
+ hasListenerOn(raw, rawUpdateKey) ||
1449
+ hasListenerOn(raw, hyphenUpdateKey) ||
1450
+ hasListenerOn(raw, camelUpdateKey + "Once") ||
1451
+ hasListenerOn(raw, rawUpdateKey + "Once") ||
1452
+ hasListenerOn(raw, hyphenUpdateKey + "Once") ||
1453
+ (props !== raw &&
1454
+ (hasListenerOn(props, camelUpdateKey) ||
1455
+ hasListenerOn(props, rawUpdateKey) ||
1456
+ hasListenerOn(props, hyphenUpdateKey)));
1457
+
1458
+ const hasDefaultOption = options !== undefined && "default" in options;
1459
+ let hasCachedDefault = false;
1460
+ let cachedDefault: unknown;
1461
+ const resolveDefault = () => {
1462
+ if (!hasDefaultOption) return undefined;
1463
+ const def = options!.default;
1464
+ if (!soleFunction && typeof def === "function") {
1465
+ if (!hasCachedDefault) {
1466
+ cachedDefault = withComponentConsumer(frame, () =>
1467
+ untrack(() => (def as () => unknown)()),
1468
+ );
1469
+ hasCachedDefault = true;
1470
+ }
1471
+ return cachedDefault;
1472
+ }
1473
+ return def;
1474
+ };
1475
+
1476
+ let prevRawOnly: unknown = unsetModelValue;
1477
+ const readIncomingProp = (): {
1478
+ hasProp: boolean;
1479
+ rawValue: unknown;
1480
+ resolved: V;
1481
+ } => {
1482
+ let hasProp = false;
1483
+ let propValue: unknown;
1484
+ if (name in raw) {
1485
+ hasProp = true;
1486
+ propValue = Reflect.get(raw, name, raw);
1487
+ } else if (camelName in raw) {
1488
+ hasProp = true;
1489
+ propValue = Reflect.get(raw, camelName, raw);
1490
+ } else if (hyphenName in raw) {
1491
+ hasProp = true;
1492
+ propValue = Reflect.get(raw, hyphenName, raw);
1493
+ }
1494
+ const rawOnly = propValue;
1495
+ if (props !== raw) {
1496
+ const fromProps =
1497
+ name in props
1498
+ ? Reflect.get(props, name, props)
1499
+ : Reflect.get(props, camelName, props);
1500
+ if (!hasProp && fromProps !== undefined) {
1501
+ hasProp = true;
1502
+ propValue = fromProps;
1503
+ } else if (
1504
+ hasProp &&
1505
+ propValue === undefined &&
1506
+ fromProps !== undefined &&
1507
+ (prevRawOnly === unsetModelValue || !Object.is(fromProps, prevRawOnly))
1508
+ ) {
1509
+ propValue = fromProps;
1510
+ }
1511
+ }
1512
+ if (rawOnly !== undefined) prevRawOnly = rawOnly;
1513
+ let resolved = propValue;
1514
+ if (resolved === undefined && hasDefaultOption) {
1515
+ resolved = resolveDefault();
1516
+ }
1517
+ if (booleanCast !== undefined) {
1518
+ if (!hasProp && !hasDefaultOption) {
1519
+ resolved = false;
1520
+ } else if (booleanCast && (resolved === "" || resolved === hyphenName)) {
1521
+ resolved = true;
1522
+ }
1523
+ }
1524
+ return { hasProp, rawValue: propValue, resolved: resolved as V };
1525
+ };
1526
+
1527
+ let forceTrigger = false;
1528
+ let writing = false;
1529
+ const initial = untrack(readIncomingProp);
1530
+ const [readLocal, writeLocal] = createSignal<V>(initial.resolved, {
1531
+ equals: (prev, next) => !forceTrigger && Object.is(prev, next),
1532
+ });
1533
+ let prevHasProp = initial.hasProp;
1534
+ let prevRawValue = initial.rawValue;
1535
+ let prevSetValue: unknown = unsetModelValue;
1536
+ let localWrittenInSSR = false;
1537
+
1538
+ if (frame.mode === "dom") {
1539
+ let initialized = false;
1540
+ createComputed(() => {
1541
+ const next = readIncomingProp();
1542
+ if (!initialized) {
1543
+ initialized = true;
1544
+ prevHasProp = next.hasProp;
1545
+ prevRawValue = next.rawValue;
1546
+ untrack(() => writeLocal(() => next.resolved));
1547
+ return;
1548
+ }
1549
+ if (
1550
+ next.hasProp !== prevHasProp ||
1551
+ !Object.is(next.rawValue, prevRawValue)
1552
+ ) {
1553
+ prevHasProp = next.hasProp;
1554
+ prevRawValue = next.rawValue;
1555
+ if (!writing) prevSetValue = unsetModelValue;
1556
+ untrack(() => writeLocal(() => next.resolved));
1557
+ }
1558
+ });
1559
+ }
1560
+
1561
+ const getter = options?.get;
1562
+ const setter = options?.set;
1563
+ let modelRef!: ModelRef<V, M, G, S>;
1564
+
1565
+ const read = (): G => {
1566
+ const value =
1567
+ frame.mode === "ssr" && !localWrittenInSSR
1568
+ ? readIncomingProp().resolved
1569
+ : readLocal();
1570
+ return getter ? getter(value) : (value as unknown as G);
1571
+ };
1572
+
1573
+ const write = (next: S): void => {
1574
+ const currentLocal =
1575
+ frame.mode === "ssr" && !localWrittenInSSR
1576
+ ? untrack(readIncomingProp).resolved
1577
+ : untrack(readLocal);
1578
+ const emittedValue = (setter ? setter(next) : next) as unknown as V;
1579
+ if (
1580
+ Object.is(emittedValue, currentLocal) &&
1581
+ Object.is(next, emittedValue) &&
1582
+ (prevSetValue === unsetModelValue || Object.is(next, prevSetValue))
1583
+ ) {
1584
+ return;
1585
+ }
1586
+ prevSetValue = next;
1587
+ localWrittenInSSR = true;
1588
+ refTriggerVersions.set(
1589
+ modelRef,
1590
+ (refTriggerVersions.get(modelRef) ?? 0) + 1,
1591
+ );
1592
+ writing = true;
1593
+ try {
1594
+ if (!Object.is(next, emittedValue)) {
1595
+ forceTrigger = true;
1596
+ }
1597
+ try {
1598
+ writeLocal(() => emittedValue);
1599
+ } finally {
1600
+ forceTrigger = false;
1601
+ }
1602
+ emit(rawUpdateEvent, emittedValue);
1603
+ const post = untrack(readIncomingProp);
1604
+ if (post.hasProp && hasUpdateListener()) {
1605
+ prevHasProp = post.hasProp;
1606
+ prevRawValue = post.rawValue;
1607
+ writeLocal(() => post.resolved);
1608
+ }
1609
+ } finally {
1610
+ writing = false;
1611
+ }
1612
+ };
1613
+
1614
+ const resolveModifiers = (): Record<PropertyKey, true | undefined> => {
1615
+ const mod =
1616
+ (camelName === "modelValue"
1617
+ ? (Reflect.get(raw, "modelModifiers", raw) ??
1618
+ Reflect.get(raw, "modelValueModifiers", raw) ??
1619
+ Reflect.get(raw, "model-valueModifiers", raw))
1620
+ : undefined) ??
1621
+ Reflect.get(raw, name + "Modifiers", raw) ??
1622
+ Reflect.get(raw, camelName + "Modifiers", raw) ??
1623
+ Reflect.get(raw, hyphenName + "Modifiers", raw) ??
1624
+ (props !== raw
1625
+ ? ((camelName === "modelValue"
1626
+ ? (Reflect.get(props, "modelModifiers", props) ??
1627
+ Reflect.get(props, "modelValueModifiers", props))
1628
+ : undefined) ??
1629
+ Reflect.get(props, name + "Modifiers", props) ??
1630
+ Reflect.get(props, camelName + "Modifiers", props))
1631
+ : undefined);
1632
+ if (!mod || typeof mod !== "object") return emptyModelModifiers;
1633
+ const normalized: Record<PropertyKey, true | undefined> = {};
1634
+ for (const key of Reflect.ownKeys(mod)) {
1635
+ if (Reflect.get(mod, key, mod)) {
1636
+ normalized[key] = true;
1637
+ }
1638
+ }
1639
+ return Object.freeze(normalized);
1640
+ };
1641
+ const modifiers = resolveModifiers() as Record<M, true | undefined>;
1642
+
1643
+ modelRef = new Ref<G, S>(read, write) as ModelRef<V, M, G, S>;
1644
+ refTriggers.set(modelRef, () => {
1645
+ forceTrigger = true;
1646
+ try {
1647
+ refTriggerVersions.set(
1648
+ modelRef,
1649
+ (refTriggerVersions.get(modelRef) ?? 0) + 1,
1650
+ );
1651
+ writeLocal((current) => current);
1652
+ } finally {
1653
+ forceTrigger = false;
1654
+ }
1655
+ });
1656
+ Object.defineProperty(modelRef, Symbol.iterator, {
1657
+ value: function* () {
1658
+ yield modelRef;
1659
+ yield modifiers;
1660
+ },
1661
+ writable: false,
1662
+ enumerable: false,
1663
+ configurable: true,
1664
+ });
1665
+ return modelRef;
1666
+ }
1667
+
1668
+ export function useModel<
1669
+ T extends Record<string, any>,
1670
+ K extends keyof T & string,
1671
+ M extends PropertyKey = string,
1672
+ G = Exclude<T[K], undefined>,
1673
+ S = Exclude<T[K], undefined>,
1674
+ >(
1675
+ props: T,
1676
+ name: K,
1677
+ options: DefineModelOptions<Exclude<T[K], undefined>, G, S> & {
1678
+ default: Exclude<T[K], undefined> | (() => Exclude<T[K], undefined>);
1679
+ },
1680
+ ): ModelRef<Exclude<T[K], undefined>, M, G, S>;
1681
+ export function useModel<
1682
+ T extends Record<string, any>,
1683
+ K extends keyof T & string,
1684
+ M extends PropertyKey = string,
1685
+ G = T[K],
1686
+ S = T[K],
1687
+ >(
1688
+ props: T,
1689
+ name: K,
1690
+ options?: DefineModelOptions<T[K], G, S>,
1691
+ ): ModelRef<T[K], M, G, S>;
1692
+ export function useModel<
1693
+ T extends Record<string, any>,
1694
+ K extends keyof T & string,
1695
+ M extends PropertyKey = string,
1696
+ G = T[K],
1697
+ S = T[K],
1698
+ >(
1699
+ props: T,
1700
+ name: K,
1701
+ options?: DefineModelOptions<T[K], G, S>,
1702
+ ): ModelRef<T[K], M, G, S> {
1703
+ return createModel<T[K], M, G, S>(props, name, options);
390
1704
  }