Sort picker options alphabetically

This commit is contained in:
Andrew Kingston 2021-08-12 10:09:38 +01:00
parent f6cd99166a
commit cb55139cea
1 changed files with 20 additions and 5 deletions

View File

@ -23,7 +23,11 @@
export let readonly = false export let readonly = false
export let quiet = false export let quiet = false
export let autoWidth = false export let autoWidth = false
const dispatch = createEventDispatcher() const dispatch = createEventDispatcher()
$: sortedOptions = getSortedOptions(options, getOptionLabel)
const onClick = () => { const onClick = () => {
dispatch("click") dispatch("click")
if (readonly) { if (readonly) {
@ -31,6 +35,17 @@
} }
open = true open = true
} }
const getSortedOptions = (options, getLabel) => {
if (!options?.length || !Array.isArray(options)) {
return []
}
return options.sort((a, b) => {
const labelA = getLabel(a)
const labelB = getLabel(b)
return labelA > labelB ? 1 : -1
})
}
</script> </script>
<button <button
@ -101,8 +116,8 @@
</svg> </svg>
</li> </li>
{/if} {/if}
{#if options && Array.isArray(options)} {#if sortedOptions.length}
{#each options as option, idx} {#each sortedOptions as option, idx}
<li <li
class="spectrum-Menu-item" class="spectrum-Menu-item"
class:is-selected={isOptionSelected(getOptionValue(option, idx))} class:is-selected={isOptionSelected(getOptionValue(option, idx))}
@ -121,9 +136,9 @@
/> />
</span> </span>
{/if} {/if}
<span class="spectrum-Menu-itemLabel" <span class="spectrum-Menu-itemLabel">
>{getOptionLabel(option, idx)}</span {getOptionLabel(option, idx)}
> </span>
<svg <svg
class="spectrum-Icon spectrum-UIIcon-Checkmark100 spectrum-Menu-checkmark spectrum-Menu-itemIcon" class="spectrum-Icon spectrum-UIIcon-Checkmark100 spectrum-Menu-checkmark spectrum-Menu-itemIcon"
focusable="false" focusable="false"