UNPKG

bits-ui

Version:

The headless components for Svelte.

45 lines (44 loc) 1.41 kB
import { attachRef } from "svelte-toolbelt"; import { createBitsAttrs, getAriaPressed, getDataDisabled, getDisabled, } from "../../internal/attrs.js"; export const toggleAttrs = createBitsAttrs({ component: "toggle", parts: ["root"], }); export class ToggleRootState { static create(opts) { return new ToggleRootState(opts); } opts; attachment; constructor(opts) { this.opts = opts; this.attachment = attachRef(this.opts.ref); this.onclick = this.onclick.bind(this); } #togglePressed() { if (!this.opts.disabled.current) { this.opts.pressed.current = !this.opts.pressed.current; } } onclick(_) { if (this.opts.disabled.current) return; this.#togglePressed(); } snippetProps = $derived.by(() => ({ pressed: this.opts.pressed.current, })); props = $derived.by(() => ({ [toggleAttrs.root]: "", id: this.opts.id.current, "data-disabled": getDataDisabled(this.opts.disabled.current), "aria-pressed": getAriaPressed(this.opts.pressed.current), "data-state": getToggleDataState(this.opts.pressed.current), disabled: getDisabled(this.opts.disabled.current), onclick: this.onclick, ...this.attachment, })); } export function getToggleDataState(condition) { return condition ? "on" : "off"; }