Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

containers.svelte.ts

190 lines6.3 KB

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