diff --git a/src/Select/Select.svelte b/src/Select/Select.svelte index b3365693..78eb8c97 100644 --- a/src/Select/Select.svelte +++ b/src/Select/Select.svelte @@ -71,8 +71,26 @@ const dispatch = createEventDispatcher(); const selectedValue = writable(selected); + const defaultSelectId = writable(null); + const defaultValue = writable(null); - setContext("Select", { selectedValue }); + setContext("Select", { + selectedValue, + setDefaultValue: (id, value) => { + /** + * Use the first `SelectItem` value as the + * default value if `selected` is `undefined`. + */ + if ($defaultValue === null) { + defaultSelectId.set(id); + defaultValue.set(value); + } else { + if ($defaultSelectId === id) { + selectedValue.set(value); + } + } + }, + }); afterUpdate(() => { selected = $selectedValue; @@ -80,7 +98,7 @@ }); $: errorId = `error-${id}`; - $: selectedValue.set(selected); + $: selectedValue.set(selected ?? $defaultValue);
diff --git a/src/Select/SelectItem.svelte b/src/Select/SelectItem.svelte index 7edae98c..abd4e771 100644 --- a/src/Select/SelectItem.svelte +++ b/src/Select/SelectItem.svelte @@ -13,8 +13,11 @@ import { getContext, onMount } from "svelte"; + const id = "ccs-" + Math.random().toString(36); const ctx = getContext("Select") || getContext("TimePickerSelect"); + $: ctx?.setDefaultValue?.(id, value); + let selected = false; const unsubscribe = ctx.selectedValue.subscribe((currentValue) => {