melt
Version:
The next generation of Melt UI. Built for Svelte 5.
49 lines (48 loc) • 1.43 kB
JavaScript
import { Synced } from "../Synced.svelte";
import { dataAttr, disabledAttr } from "../utils/attribute";
import { extract } from "../utils/extract";
import { createDataIds } from "../utils/identifiers";
const identifiers = createDataIds("toggle", ["trigger", "hidden-input"]);
export class Toggle {
/* Props */
#props;
disabled = $derived(extract(this.#props.disabled, false));
/* State */
#value;
constructor(props = {}) {
this.#value = new Synced({
value: props.value,
onChange: props.onValueChange,
defaultValue: false,
});
this.#props = props;
}
get value() {
return this.#value.current;
}
set value(value) {
this.#value.current = value;
}
/** The trigger that toggles the value. */
get trigger() {
return {
[identifiers.trigger]: "",
"data-checked": dataAttr(this.value),
"aria-pressed": this.value,
disabled: disabledAttr(this.disabled),
onclick: () => {
if (this.disabled)
return;
this.value = !this.value;
},
};
}
/** A hidden input field to use within forms. */
get hiddenInput() {
return {
[identifiers["hidden-input"]]: "",
type: "hidden",
value: this.value ? "on" : "off",
};
}
}