File size: 1,814 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { addMeltEventListener, makeElement, disabledAttr, executeCallbacks, kbd, omit, overridable, toWritableStores, } from '../../internal/helpers/index.js';
import { writable } from 'svelte/store';
const defaults = {
    defaultPressed: false,
    disabled: false,
};
export function createToggle(props) {
    const withDefaults = { ...defaults, ...props };
    const options = toWritableStores(omit(withDefaults, 'pressed'));
    const { disabled } = options;
    const pressedWritable = withDefaults.pressed ?? writable(withDefaults.defaultPressed);
    const pressed = overridable(pressedWritable, withDefaults?.onPressedChange);
    function handleToggle() {
        const $disabled = disabled.get();
        if ($disabled)
            return;
        pressed.update((v) => !v);
    }
    const root = makeElement('toggle', {
        stores: [pressed, disabled],
        returned: ([$pressed, $disabled]) => {
            return {
                'data-disabled': disabledAttr($disabled),
                disabled: disabledAttr($disabled),
                'data-state': $pressed ? 'on' : 'off',
                'aria-pressed': $pressed,
                type: 'button',
            };
        },
        action: (node) => {
            const unsub = executeCallbacks(addMeltEventListener(node, 'click', () => {
                handleToggle();
            }), addMeltEventListener(node, 'keydown', (e) => {
                if (e.key !== kbd.ENTER && e.key !== kbd.SPACE)
                    return;
                e.preventDefault();
                handleToggle();
            }));
            return {
                destroy: unsub,
            };
        },
    });
    return {
        elements: {
            root,
        },
        states: {
            pressed,
        },
        options,
    };
}