37 lines
1.0 KiB
JavaScript
37 lines
1.0 KiB
JavaScript
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();
|
|
});
|
|
}
|