Fix options ordering

This commit is contained in:
Andrew Kingston 2023-03-31 12:07:49 +01:00
parent dbf5bfe83d
commit d8800c2823
1 changed files with 12 additions and 23 deletions

View File

@ -18,8 +18,6 @@
$: options = schema?.constraints?.inclusion || [] $: options = schema?.constraints?.inclusion || []
$: editable = selected && !readonly $: editable = selected && !readonly
$: values = Array.isArray(value) ? value : [value].filter(x => x != null) $: values = Array.isArray(value) ? value : [value].filter(x => x != null)
$: unselectedOptions = options.filter(x => !values.includes(x))
$: orderedOptions = values.concat(unselectedOptions)
$: { $: {
// Close when deselected // Close when deselected
if (!selected) { if (!selected) {
@ -43,7 +41,7 @@
const toggleOption = option => { const toggleOption = option => {
if (!multi) { if (!multi) {
onChange(option) onChange(option === value ? null : option)
close() close()
} else { } else {
if (values.includes(option)) { if (values.includes(option)) {
@ -64,7 +62,7 @@
} else if (e.key === "ArrowUp") { } else if (e.key === "ArrowUp") {
focusedOptionIdx = Math.max(focusedOptionIdx - 1, 0) focusedOptionIdx = Math.max(focusedOptionIdx - 1, 0)
} else if (e.key === "Enter") { } else if (e.key === "Enter") {
toggleOption(orderedOptions[focusedOptionIdx]) toggleOption(options[focusedOptionIdx])
} }
return true return true
} }
@ -100,31 +98,22 @@
{/if} {/if}
{#if isOpen} {#if isOpen}
<div class="options" class:invert on:wheel={e => e.stopPropagation()}> <div class="options" class:invert on:wheel={e => e.stopPropagation()}>
{#each values as val, idx} {#each options as option, idx}
{@const color = getOptionColor(val)} {@const color = getOptionColor(option)}
<div
class="option"
on:click={() => toggleOption(val)}
class:focused={focusedOptionIdx === idx}
>
<div class="badge text" style="--color: {color}">
{val}
</div>
<Icon
name="Checkmark"
color="var(--spectrum-global-color-blue-400)"
/>
</div>
{/each}
{#each unselectedOptions as option, idx}
<div <div
class="option" class="option"
on:click={() => toggleOption(option)} on:click={() => toggleOption(option)}
class:focused={focusedOptionIdx === values.length + idx} class:focused={focusedOptionIdx === idx}
> >
<div class="badge text" style="--color: {getOptionColor(option)}"> <div class="badge text" style="--color: {color}">
{option} {option}
</div> </div>
{#if values.includes(option)}
<Icon
name="Checkmark"
color="var(--spectrum-global-color-blue-400)"
/>
{/if}
</div> </div>
{/each} {/each}
</div> </div>