melt
Version:
The next generation of Melt UI. Built for Svelte 5.
45 lines (44 loc) • 1.5 kB
JavaScript
import { extract } from "./utils/extract";
import { isFunction } from "./utils/is";
/**
* Setting `current` calls the `onChange` callback with the new value.
*
* If the value arg is static, it will be used as the default value,
* and subsequent sets will set an internal state that gets read as `current`.
*
* Otherwise, if it is a getter, it will be called every time `current` is read,
* and no internal state is used.
*/
export class Synced {
#internalValue = $state();
#valueArg;
#onChange;
#defaultValue;
#equalityCheck;
constructor({ value, onChange, ...args }) {
this.#valueArg = value;
this.#onChange = onChange;
this.#defaultValue = "defaultValue" in args ? args?.defaultValue : undefined;
this.#equalityCheck = args.equalityCheck;
this.#internalValue = extract(value, this.#defaultValue);
}
get current() {
return isFunction(this.#valueArg)
? this.#valueArg() ?? this.#defaultValue ?? this.#internalValue
: this.#internalValue;
}
set current(value) {
if (this.#equalityCheck === true && this.current === value)
return;
if (isFunction(this.#equalityCheck)) {
if (this.#equalityCheck(this.current, value))
return;
}
if (isFunction(this.#valueArg)) {
this.#onChange?.(value);
return;
}
this.#internalValue = value;
this.#onChange?.(value);
}
}