Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can bind:group for checkboxes be enhanced to accumulate bits? #14672

Open
webJose opened this issue Dec 11, 2024 · 3 comments
Open

Can bind:group for checkboxes be enhanced to accumulate bits? #14672

webJose opened this issue Dec 11, 2024 · 3 comments

Comments

@webJose
Copy link
Contributor

webJose commented Dec 11, 2024

Describe the problem

I like bitmasked enums. They consume very little RAM and working with them is super fast. I often build a bunch of checkboxes that represent an option (bitmasked value).

Describe the proposed solution

Just to be able to do bind:group using a number and bit values:

<script>
  // State
  let options = $state(0);

  // Or directly as a prop is more desirable:
  let {
    options = $bindable(0),
  } = $props();
</script>

{#each [1, 2, 4, 8] as bit}
  <label>
    <input type="checkbox" value={bit} bind:group={options}>{bit}
  </label>
{/each}

Svelte could detect my options variable is a number and therefore assume that all values in the bound checkboxes will be numbers that are added or removed using bitwise operators.

Importance

nice to have

@webJose
Copy link
Contributor Author

webJose commented Dec 11, 2024

BTW, I did find out last night that bind:group doesn't work with function bindings, which would have been great for this case. I tried:

<input type="checkbox" value={1} bind:group={() => !!(options & 1), (v) => options = v ? options | 1 : options & ~1}>

Also, does function binding work for bind:checked? I also wanted a bind:unchecked, but I guess that if function binding works with bind:checked I can easily simulate my wanted bind:unchecked.

@brunnerh
Copy link
Member

Regarding the group bindings, an issue was opened earlier:

@webJose
Copy link
Contributor Author

webJose commented Dec 11, 2024

Thanks, @brunnerh . I did notice. I was going to open one, but analyzing how bind:group works I figured most likely it was by design, and therefore a mere documentation issue.

BTW, I just tested bind:checked with functions and it does work to easily simulate my wanted bind:unchecked. If anyone is curious:

<script>
	let name = 'world';
	let isUnchecked = $state(false)
</script>

<input type="checkbox" bind:checked={() => !isUnchecked, (v) => isUnchecked = !v}>

<pre>{isUnchecked}</pre>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants