Open History to see the last commit
1import { SvelteSet, createSubscriber } from 'svelte/reactivity'
2β
3type VoidFn = () => void
4type Subscriber = (update: VoidFn) => void | VoidFn
5β
6export type Box<T> = { current: T }
7β
8export class ReactiveValue<T> implements Box<T> {
9 #fn
10 #subscribe
11β
12 constructor(fn: () => T, onSubscribe: Subscriber) {
13 this.#fn = fn
14 this.#subscribe = createSubscriber((update) => onSubscribe(update))
15 }
16β
17 get current() {
18 this.#subscribe()
19 return this.#fn()
20 }
21}
22β
23/**
24 * Makes all of the top-level keys of an object into $state.raw fields whose initial values
25 * are the same as in the original object. Does not mutate the original object. Provides an `update`
26 * function that _can_ (but does not have to be) be used to replace all of the object's top-level keys
27 * with the values of the new object, while maintaining the original root object's reference.
28 */
29export function createRawRef<T extends {} | Array<unknown>>(
30 init: T,
31): [T, (newValue: T) => void] {
32 const refObj = (Array.isArray(init) ? [] : {}) as T
33 const hiddenKeys = new SvelteSet<PropertyKey>()
34 // Absent keys have no `$state.raw` field to subscribe to, and `length` is a
35 // plain array property, so reads of either are tracked through this instead.
36 // Without it, anything observed while the ref is empty never re-runs.
37 let keyVersion = $state.raw(0)
38 const trackKeys = () => keyVersion
39 const out = new Proxy(refObj, {
40 get(target, prop, receiver) {
41 if (
42 hiddenKeys.has(prop) ||
43 !(prop in target) ||
44 (Array.isArray(target) && prop === 'length')
45 ) {
46 trackKeys()
47 }
48 return Reflect.get(target, prop, receiver)
49 },
50 set(target, prop, value, receiver) {
51 hiddenKeys.delete(prop)
52 if (prop in target) {
53 return Reflect.set(target, prop, value, receiver)
54 }
55 let state = $state.raw(value)
56 Object.defineProperty(target, prop, {
57 configurable: true,
58 enumerable: true,
59 get: () => {
60 // If this is a lazy value, we need to call it.
61 // We can't do something like typeof state === 'function'
62 // because the value could actually be a function that we don't want to call.
63 return state && isBranded(state) ? state() : state
64 },
65 set: (v) => {
66 state = v
67 },
68 })
69 return true
70 },
71 has: (target, prop) => {
72 if (hiddenKeys.has(prop)) {
73 return false
74 }
75 return prop in target
76 },
77 ownKeys(target) {
78 return Reflect.ownKeys(target).filter((key) => !hiddenKeys.has(key))
79 },
80 getOwnPropertyDescriptor(target, prop) {
81 if (hiddenKeys.has(prop)) {
82 return undefined
83 }
84 return Reflect.getOwnPropertyDescriptor(target, prop)
85 },
86 deleteProperty(target, prop) {
87 if (prop in target) {
88 // @ts-expect-error
89 // We need to set the value to undefined to signal to the listeners that the value has changed.
90 // If we just deleted it, the reactivity system wouldn't have any idea that the value was gone.
91 target[prop] = undefined
92 hiddenKeys.add(prop)
93 if (Array.isArray(target)) {
94 target.length--
95 }
96 return true
97 }
98 return false
99 },
100 })
101β
102 function update(newValue: T) {
103 const existingKeys = Object.keys(out)
104 const newKeys = Object.keys(newValue)
105 const keysToRemove = existingKeys.filter((key) => !newKeys.includes(key))
106 // Arrays: delete in descending index order so each `deleteProperty` trap
107 // sees the slot it is removing as the current tail (length-- stays valid).
108 // Forward iteration would shrink the array under our feet and the next
109 // index would no longer be `in target`, tripping the trap.
110 if (Array.isArray(newValue)) {
111 keysToRemove.sort((a, b) => Number(b) - Number(a))
112 }
113 const keysAdded = newKeys.some((key) => !existingKeys.includes(key))
114 for (const key of keysToRemove) {
115 // @ts-expect-error
116 delete out[key]
117 }
118 for (const key of newKeys) {
119 // @ts-expect-error
120 // This craziness is required because TanStack Query defines getters for all of the keys on the object.
121 // These getters track property access, so if we access all of them here, we'll end up tracking everything.
122 // So we wrap the property access in a special function that we can identify later to lazily access the value.
123 // (See above)
124 out[key] = brand(() => newValue[key])
125 }
126 if (keysAdded || keysToRemove.length > 0) {
127 keyVersion++
128 }
129 }
130β
131 // we can't pass `init` directly into the proxy because it'll never set the state fields
132 // (because (prop in target) will always be true)
133 update(init)
134β
135 return [out, update]
136}
137β
138const lazyBrand = Symbol('LazyValue')
139type Branded<T extends () => unknown> = T & { [lazyBrand]: true }
140β
141function brand<T extends () => unknown>(fn: T): Branded<T> {
142 // @ts-expect-error
143 fn[lazyBrand] = true
144 return fn as Branded<T>
145}
146β
147function isBranded<T extends () => unknown>(fn: T): fn is Branded<T> {
148 return Boolean((fn as Branded<T>)[lazyBrand])
149}