From f8b1c8a23add3c90f614f892416918cb12672153 Mon Sep 17 00:00:00 2001 From: metonym Date: Sat, 18 Jun 2022 10:13:42 -0700 Subject: [PATCH] fix(select): use first `SelectItem` value as default if `selected` is undefined (#1353) Fixes #570 --- src/Select/Select.svelte | 22 ++++++++++++++++++++-- src/Select/SelectItem.svelte | 3 +++ 2 files changed, 23 insertions(+), 2 deletions(-) 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) => {