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

utils.svelte.ts

63 lines1.8 KB

1import { untrack } from 'svelte'
2// modified from the great https://github.com/svecosystem/runed
3/**
4 * Runs an effect after (`'post'`) or before (`'pre'`) the DOM updates.
5 *
6 * @param flush - When to run the effect: `'post'` uses `$effect`, `'pre'` uses
7 * `$effect.pre`.
8 * @param effect - The effect to run. It may return a cleanup function.
9 */
10function runEffect(
11 flush: 'post' | 'pre',
12 effect: () => void | VoidFunction,
13): void {
14 switch (flush) {
15 case 'post':
16 $effect(effect)
17 break
18 case 'pre':
19 $effect.pre(effect)
20 break
21 }
23type Getter<T> = () => T
24/**
25 * Runs `effect` whenever the reactive state read by `sources` changes, even if
26 * they return the same values, skipping the first run. The effect receives the
27 * new and previous values, and is called untracked, so only `sources` are
28 * tracked.
29 *
30 * @param sources - The getter, or array of getters, to watch.
31 * @param flush - Whether to run after (`'post'`) or before (`'pre'`) the DOM
32 * updates.
33 * @param effect - Called with the new and previous values. It may return a
34 * cleanup function.
35 */
36export const watchChanges = <T>(
37 sources: Getter<T> | Array<Getter<T>>,
38 flush: 'post' | 'pre',
39 effect: (
40 values: T | Array<T>,
41 previousValues: T | undefined | Array<T | undefined>,
42 ) => void,
43) => {
44 let active = false
45 let previousValues: T | undefined | Array<T | undefined> = Array.isArray(
46 sources,
47 )
48 ? []
49 : undefined
50 runEffect(flush, () => {
51 const values = Array.isArray(sources)
52 ? sources.map((source) => source())
53 : sources()
54 if (!active) {
55 active = true
56 previousValues = values
57 return
58 }
59 const cleanup = untrack(() => effect(values, previousValues))
60 previousValues = values
61 return cleanup
62 })