INIT
This commit is contained in:
+36
@@ -0,0 +1,36 @@
|
||||
import { boxWith } from "svelte-toolbelt";
|
||||
import { noop } from "./noop.js";
|
||||
const defaultOptions = {
|
||||
afterMs: 10000,
|
||||
onChange: noop,
|
||||
};
|
||||
/**
|
||||
* Creates a box which will be reset to the default value after some time.
|
||||
*
|
||||
* @param defaultValue The value which will be set.
|
||||
* @param afterMs A zero-or-greater delay in milliseconds.
|
||||
*/
|
||||
export function boxAutoReset(defaultValue, options) {
|
||||
const { afterMs, onChange, getWindow } = { ...defaultOptions, ...options };
|
||||
let timeout = null;
|
||||
let value = $state(defaultValue);
|
||||
function resetAfter() {
|
||||
return getWindow().setTimeout(() => {
|
||||
value = defaultValue;
|
||||
onChange?.(defaultValue);
|
||||
}, afterMs);
|
||||
}
|
||||
$effect(() => {
|
||||
return () => {
|
||||
if (timeout)
|
||||
getWindow().clearTimeout(timeout);
|
||||
};
|
||||
});
|
||||
return boxWith(() => value, (v) => {
|
||||
value = v;
|
||||
onChange?.(v);
|
||||
if (timeout)
|
||||
getWindow().clearTimeout(timeout);
|
||||
timeout = resetAfter();
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user