@dualjack/svelte-tools
Version:
### Why? Because runes are not safe to toss around by design.
39 lines (38 loc) • 973 B
JavaScript
export default function watch(src, cb, options) {
let isPaused = $state(false);
let oldValue;
let isLazyPass = false;
function run(newValue) {
if (isPaused)
return;
// Run once and change the flag.
if (options?.lazy && !isLazyPass) {
isLazyPass = true;
return;
}
cb(newValue, oldValue);
oldValue = newValue;
}
$effect.root(() => {
if (options?.pre) {
// Pre - before DOM modifications.
$effect.pre(() => {
run(src());
});
}
else {
// After DOM modifications.
$effect(() => {
run(src());
});
}
});
return {
pause: () => isPaused = true,
resume: () => isPaused = false,
isPaused: {
get current() { return isPaused; },
set current(v) { isPaused = v; },
},
};
}