import { untrack } from 'svelte' // modified from the great https://github.com/svecosystem/runed /** * Runs an effect after (`'post'`) or before (`'pre'`) the DOM updates. * @param flush - When to run the effect: `'post'` uses `$effect`, `'pre'` uses `$effect.pre`. * @param effect - The effect to run. It may return a cleanup function. */ function runEffect( flush: 'post' | 'pre', effect: () => void | VoidFunction, ): void { switch (flush) { case 'post': $effect(effect) break case 'pre': $effect.pre(effect) break } } type Getter = () => T /** * Runs `effect` whenever the reactive state read by `sources` changes, even if they return the * same values, skipping the first run. The effect receives the new and previous values, and is * called untracked, so only `sources` are tracked. * @param sources - The getter, or array of getters, to watch. * @param flush - Whether to run after (`'post'`) or before (`'pre'`) the DOM updates. * @param effect - Called with the new and previous values. It may return a cleanup function. */ export const watchChanges = ( sources: Getter | Array>, flush: 'post' | 'pre', effect: ( values: T | Array, previousValues: T | undefined | Array, ) => void, ) => { let active = false let previousValues: T | undefined | Array = Array.isArray( sources, ) ? [] : undefined runEffect(flush, () => { const values = Array.isArray(sources) ? sources.map((source) => source()) : sources() if (!active) { active = true previousValues = values return } const cleanup = untrack(() => effect(values, previousValues)) previousValues = values return cleanup }) }