svelte-toggle icon indicating copy to clipboard operation
svelte-toggle copied to clipboard

Support group binding

Open zumoshi opened this issue 1 year ago • 3 comments

Svelte supports a feature where instead of one separate variable per each checkbox you can have an array and each checkbox will add/remove its name attribute from that array when toggled.

https://svelte.dev/tutorial/group-inputs

Is there any way this can be supported with svelte-toggle?

e.g.

<script>
  import Toggle from "svelte-toggle";

  let items = [];
</script>

<Toggle bind:group={items} name="x" />
<Toggle bind:group={items} name="y" />
<Toggle bind:group={items} name="z" />

Toggling all three should result in items = ['x','y','z']

p.s. Maybe not helpful but I found this: https://svelte.dev/repl/faabda4cabd544bd858a8a8abd0095f5?version=3.12.1

zumoshi avatar Jul 10 '22 13:07 zumoshi

My understanding is that bind:group is intended for inputs whereas svelte-toggleuses a nativebutton` element:

https://github.com/metonym/svelte-toggle/blob/97b294d70783f66d92e04ced55be91c2540c999c/src/Toggle.svelte#L66

metonym avatar Jul 10 '22 14:07 metonym

What I understood was that

<input type="checkbox" bind:group={x} />

is just syntax sugar for

<input type="checkbox"
       checked={x.includes(name)}
       on:change={(e)=> x = e.target.checked ? [...x, name] : x.filter(e=> e !== name)}
/>

it doesn't have any magic that requires a real dom element.

Since this package is intended to be used as a check box it would be nice if we could emulate the api so it could be a drop in replacement with only changing the tag name.

zumoshi avatar Jul 10 '22 18:07 zumoshi

Basically this is a feature request for an easier way to do this:

<script>
let options = []
</script>

<Toggle toggled={options.includes("option1")} on:toggle={(e)=> options = e.detail ? [...options, "option1"] : options.filter(e=> e !== "option1")} label="Option 1" />
<Toggle toggled={options.includes("option2")} on:toggle={(e)=> options = e.detail ? [...options, "option2"] : options.filter(e=> e !== "option2")} label="Option 2" />

and the syntax I propose for it is the same one svelte already has for check boxes so it would be more intuitive for users

<script>
let options = []
</script>

<Toggle bind:group={options} name="option1" label="Option 1" />
<Toggle bind:group={options} name="option2" label="Option 2" />

I think this is a common enough pattern to justify this feature (especially since svelte itself saw fit to include syntax sugar for this pattern despite striving for a minimal API)


Similar pattern is also supported in vuejs (link) and emulated in react (link)

zumoshi avatar Jul 10 '22 19:07 zumoshi