feat(combo-box): dispatch select, clear events

Also fixes a bug where the selectedId isn't reset when clearing the selection.
This commit is contained in:
Eric Liu 2020-07-28 18:46:12 -07:00
commit 8dbcf17e89
2 changed files with 22 additions and 3 deletions

View file

@ -11,8 +11,8 @@
{ {
id: "option-4", id: "option-4",
text: text:
"An example option that is really long to show what should be done to handle long text" "An example option that is really long to show what should be done to handle long text",
} },
]; ];
$: toggled = false; $: toggled = false;
@ -58,6 +58,12 @@
bind:ref bind:ref
bind:value bind:value
bind:selectedIndex bind:selectedIndex
on:select={({ detail }) => {
console.log('on:select', detail);
}}
on:clear={() => {
console.log('on:clear');
}}
{items} {items}
{shouldFilterItem} /> {shouldFilterItem} />
</div> </div>

View file

@ -111,7 +111,7 @@
*/ */
export let ref = null; export let ref = null;
import { afterUpdate } from "svelte"; import { createEventDispatcher, afterUpdate } from "svelte";
import WarningFilled16 from "carbon-icons-svelte/lib/WarningFilled16"; import WarningFilled16 from "carbon-icons-svelte/lib/WarningFilled16";
import { import {
ListBox, ListBox,
@ -122,6 +122,8 @@
ListBoxSelection, ListBoxSelection,
} from "../ListBox"; } from "../ListBox";
const dispatch = createEventDispatcher();
let selectedId = undefined; let selectedId = undefined;
let inputValue = ""; let inputValue = "";
let highlightedIndex = -1; let highlightedIndex = -1;
@ -145,9 +147,18 @@
} else { } else {
highlightedIndex = -1; highlightedIndex = -1;
inputValue = selectedItem ? selectedItem.text : ""; inputValue = selectedItem ? selectedItem.text : "";
if (!selectedItem) {
selectedId = undefined;
selectedIndex = -1;
}
} }
}); });
$: if (selectedIndex > -1) {
selectedId = items[selectedIndex].id;
dispatch("select", { selectedId, selectedIndex, selectedItem });
}
$: ariaLabel = $$props["aria-label"] || "Choose an item"; $: ariaLabel = $$props["aria-label"] || "Choose an item";
$: menuId = `menu-${id}`; $: menuId = `menu-${id}`;
$: comboId = `combo-${id}`; $: comboId = `combo-${id}`;
@ -222,6 +233,7 @@
open = !open; open = !open;
if (highlightedIndex > -1 && highlightedIndex !== selectedIndex) { if (highlightedIndex > -1 && highlightedIndex !== selectedIndex) {
selectedIndex = highlightedIndex; selectedIndex = highlightedIndex;
selectedId = items[selectedIndex].id;
open = false; open = false;
} }
} else if (key === 'Tab') { } else if (key === 'Tab') {
@ -250,6 +262,7 @@
{/if} {/if}
{#if inputValue} {#if inputValue}
<ListBoxSelection <ListBoxSelection
on:clear
on:clear={() => { on:clear={() => {
selectedIndex = -1; selectedIndex = -1;
open = false; open = false;