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

containers.svelte.ts

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