combobox: refactor w/ snippet rendering overrides & better lazy loading
This commit is contained in:
@@ -4,50 +4,35 @@
|
|||||||
value: string;
|
value: string;
|
||||||
/**
|
/**
|
||||||
* Label of the option displayed in the picker and, if the option is
|
* Label of the option displayed in the picker and, if the option is
|
||||||
* selected, in the main input field (unless preview overrides it during
|
* selected, in the main input field. Preview overrides label if provided
|
||||||
* combobox open state).
|
* and the combobox is open (see usePreview prop for exceptions).
|
||||||
*/
|
*/
|
||||||
label?: string;
|
label?: string;
|
||||||
/**
|
/**
|
||||||
* An optional custom render function for the option, receives the
|
* Preview text for the option, displayed in the main input field when
|
||||||
* option as an argument and is used in the picker instead of the
|
* the option is selected. See usePreview prop for controlling when
|
||||||
* label if provided. Note that label should still be provided even
|
* preview takes precedence over label.
|
||||||
* if render is used, as it's used for search and accessibility.
|
|
||||||
*/
|
*/
|
||||||
render?: Snippet<[item: ComboboxOption]>;
|
preview?: string;
|
||||||
/**
|
/**
|
||||||
* Additional information text for the option, displayed beside the
|
* Additional information text for the option, displayed beside the
|
||||||
* label in the picker and, if the option is selected, in the main
|
* label in the picker and, if the option is selected, in the main
|
||||||
* input field.
|
* input field.
|
||||||
*/
|
*/
|
||||||
infotext?: string;
|
infotext?: string;
|
||||||
/**
|
/** An optional icon for the option, displayed in the picker and,
|
||||||
* Snippet override for infotext, receives the option as an argument.
|
* if the option is selected, in the main input field.
|
||||||
* Note that infotext should still be provided even if infotextRender
|
|
||||||
* is used, as it's used for search and accessibility.
|
|
||||||
*/
|
*/
|
||||||
infotextRender?: Snippet<[item: ComboboxOption]>;
|
icon?: IconDef;
|
||||||
/**
|
|
||||||
* Preview text for the option, displayed in the picker and, if the
|
|
||||||
* option is selected and the combobox is open, in the main input field.
|
|
||||||
*/
|
|
||||||
preview?: string;
|
|
||||||
/**
|
|
||||||
* Snippet override for the preview text, receives the option as an
|
|
||||||
* argument. Note that preview should still be provided even if
|
|
||||||
* previewRender is used, as it's used for search and accessibility.
|
|
||||||
*/
|
|
||||||
previewRender?: Snippet<[item: ComboboxOption]>;
|
|
||||||
/** Whether the option is disabled */
|
/** Whether the option is disabled */
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
/** An optional icon for the option, displayed in the picker and,
|
|
||||||
* if the option is selected, in the closed combobox.
|
|
||||||
*/
|
|
||||||
icon?: Snippet<[item: ComboboxOption]> | IconDef;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLabel = (item: ComboboxOption | undefined): string => item?.label ?? item?.value ?? '';
|
/** returns option label, falling back to value or 'Undefined Option' if no option provided */
|
||||||
const getPreview = (item: ComboboxOption | undefined): string => item?.preview ?? getLabel(item);
|
const getLabel = (opt: ComboboxOption | undefined): string =>
|
||||||
|
opt ? (opt.label ?? opt.value) : 'Undefined Option';
|
||||||
|
/** returns option preview, falling back to getLabel if missing */
|
||||||
|
const getPreview = (opt: ComboboxOption | undefined): string => opt?.preview ?? getLabel(opt);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
@@ -61,51 +46,134 @@
|
|||||||
import { Portal } from '@jsrob/svelte-portal';
|
import { Portal } from '@jsrob/svelte-portal';
|
||||||
import { scale } from 'svelte/transition';
|
import { scale } from 'svelte/transition';
|
||||||
import { generateIdentifier, type IconDef } from './util';
|
import { generateIdentifier, type IconDef } from './util';
|
||||||
import type { ClassValue } from 'svelte/elements';
|
import type { ClassValue, MouseEventHandler } from 'svelte/elements';
|
||||||
import { matchSorter } from 'match-sorter';
|
import { matchSorter } from 'match-sorter';
|
||||||
import Spinner from './Spinner.svelte';
|
import Spinner from './Spinner.svelte';
|
||||||
|
import type { KeyOption } from 'match-sorter';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
name?: string;
|
|
||||||
value?: ComboboxOption;
|
|
||||||
open?: boolean;
|
|
||||||
usePreview?: boolean | 'auto';
|
|
||||||
matchWidth?: boolean;
|
|
||||||
options: ComboboxOption[];
|
|
||||||
required?: boolean;
|
|
||||||
invalidMessage?: string | null;
|
|
||||||
label?: string;
|
|
||||||
placeholder?: string;
|
|
||||||
/** displayed by default if no item is selected that has its own icon */
|
|
||||||
icon?: IconDef;
|
|
||||||
/**
|
/**
|
||||||
* enables loading spinner and fallback text if no items are found. may be changed
|
* Name of the input, used for form submission. The currently selected
|
||||||
* internally if lazy is enabled. loading is, however, not bindable, so don't expect
|
* option's value will be submitted under this name.
|
||||||
* any internal changes to be propagated outward.
|
*/
|
||||||
|
name?: string;
|
||||||
|
/** Optional label for the combobox */
|
||||||
|
label?: string;
|
||||||
|
/** Optional placeholder for the main input field */
|
||||||
|
placeholder?: string;
|
||||||
|
/** Whether an option must be selected to continue (default: false) */
|
||||||
|
required?: boolean;
|
||||||
|
/**
|
||||||
|
* Message displayed below the main input field when required but no
|
||||||
|
* option is selected (default: 'Please select an option'). If set to
|
||||||
|
* null, no message is displayed.
|
||||||
|
*/
|
||||||
|
invalidMessage?: string | null;
|
||||||
|
/**
|
||||||
|
* Allows the user to select an option without updating the value
|
||||||
|
* (events are still triggered).
|
||||||
|
*/
|
||||||
|
stateless?: boolean;
|
||||||
|
|
||||||
|
/** Bindable value of the combobox, the currently selected option */
|
||||||
|
value?: ComboboxOption;
|
||||||
|
/** Array of ComboboxOptions for the picker */
|
||||||
|
options: ComboboxOption[];
|
||||||
|
/**
|
||||||
|
* Overrides label render behaviour for all options. Receives the option
|
||||||
|
* as an argument. If not provided, the option's `label` field is used.
|
||||||
|
* Option `label` field must still be present for search, accessibility,
|
||||||
|
* and visibility in the main input field.
|
||||||
|
*/
|
||||||
|
labelRender?: Snippet<[opt: ComboboxOption]>;
|
||||||
|
/**
|
||||||
|
* Overrides infotext render behaviour for all options. Receives the option
|
||||||
|
* as an argument. If not provided, the option's `infotext` field is used.
|
||||||
|
* Option `infotext` field must still be present for search and accessibility.
|
||||||
|
*/
|
||||||
|
infotextRender?: Snippet<[opt: ComboboxOption]>;
|
||||||
|
/**
|
||||||
|
* Overrides icon render behaviour for all options and the main input. Receives
|
||||||
|
* the option as an argument. If not provided, the option's `icon` field is used,
|
||||||
|
* based on the phosphor `IconDef` structure.
|
||||||
|
*/
|
||||||
|
iconRender?: Snippet<[opt: ComboboxOption]>;
|
||||||
|
|
||||||
|
/** Bindable open state of the combobox */
|
||||||
|
open?: boolean;
|
||||||
|
/**
|
||||||
|
* If enabled, matches the picker width to the input width. Otherwise,
|
||||||
|
* the picker width is determined by the average of its content, with
|
||||||
|
* a reasonable minimum (default: false).
|
||||||
|
*/
|
||||||
|
matchWidth?: boolean;
|
||||||
|
/** Uses a compact layout for the search input with less padding and smaller text */
|
||||||
|
compact?: boolean;
|
||||||
|
/**
|
||||||
|
* Optional icon displayed as long as the selected option does not have
|
||||||
|
* its own icon.
|
||||||
|
*/
|
||||||
|
icon?: IconDef | Snippet;
|
||||||
|
/**
|
||||||
|
* Bindable loading state controls visibility of spinner and fallback
|
||||||
|
* text if no options are found (see notFoundMessage). Only changed
|
||||||
|
* internally if lazy loading is used.
|
||||||
*/
|
*/
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
/** applies the loading state on first interaction */
|
/** Special always-disabled option displayed when loading */
|
||||||
lazy?: boolean;
|
loadingOption?: ComboboxOption;
|
||||||
/** uses a compact layout for the search input with less padding and smaller text */
|
/**
|
||||||
compact?: boolean;
|
* Applies the loading state when the picker is opened, allowing for
|
||||||
/** allows the user to select an option without selecting a value (events are still triggered) */
|
* asynchronous loading of options.
|
||||||
stateless?: boolean;
|
* `always`: applies loading state each time the picker is opened
|
||||||
notFoundMessage?: string;
|
* `true`: applies loading state only the first time the picker is opened
|
||||||
|
* `false` (default): loading state must be controlled externally
|
||||||
|
*/
|
||||||
|
lazy?: 'always' | boolean;
|
||||||
|
/**
|
||||||
|
* Controls when the option preview should take precedence over the
|
||||||
|
* label in the main input field.
|
||||||
|
* `auto` (default): uses preview only when the picker is closed
|
||||||
|
* `true`: always uses preview
|
||||||
|
* `false`: never uses preview
|
||||||
|
*/
|
||||||
|
usePreview?: boolean | 'auto';
|
||||||
|
/** Special always-disabled option displayed when no options match the search */
|
||||||
|
notFoundOption?: ComboboxOption;
|
||||||
/**
|
/**
|
||||||
* Configures which option fields are included in the search
|
* Configures which option fields are included in the search
|
||||||
* (default: 'label' and 'value').
|
* (default: 'label' and 'value'). An empty array triggers fallback
|
||||||
|
* to searching by value only.
|
||||||
*/
|
*/
|
||||||
searchKeys?: ('label' | 'value' | 'preview' | 'infotext')[];
|
searchKeys?: ('value' | 'label' | 'preview' | 'infotext')[];
|
||||||
|
|
||||||
|
// TODO: implement searchKeys above.
|
||||||
|
/** Additional classes applied to the persistent div container */
|
||||||
class?: ClassValue | null | undefined;
|
class?: ClassValue | null | undefined;
|
||||||
|
/** Optional action applied to the main input */
|
||||||
use?: () => void;
|
use?: () => void;
|
||||||
|
|
||||||
|
/** Callback when the input value changes, triggering validation */
|
||||||
onvalidate?: (e: InputValidatorEvent) => void;
|
onvalidate?: (e: InputValidatorEvent) => void;
|
||||||
onchange?: (item: ComboboxOption) => void;
|
/** Callback when the selected option changes */
|
||||||
|
onchange?: (opt: ComboboxOption) => void;
|
||||||
|
/** Callback when a search is performed */
|
||||||
onsearch?: (query: string) => boolean | void;
|
onsearch?: (query: string) => boolean | void;
|
||||||
onscroll?: (detail: { event: UIEvent; top: boolean; bottom: boolean }) => void;
|
/** Callback when the picker is scrolled */
|
||||||
/** this callback runs only once on the first interaction if lazy is enabled */
|
onscroll?: (detail: {
|
||||||
onlazy?: () => void;
|
event: UIEvent;
|
||||||
onopen?: () => void;
|
top: boolean;
|
||||||
onclose?: () => void;
|
bottom: boolean;
|
||||||
|
searchInput: string;
|
||||||
|
}) => void;
|
||||||
|
/**
|
||||||
|
* Callback when options should be lazily loaded, see lazy prop.
|
||||||
|
* Expects a promise to be returned, allowing for loading state
|
||||||
|
* to be automatically managed.
|
||||||
|
*/
|
||||||
|
onlazy?: () => Promise<void>;
|
||||||
|
/** Callback when the picker is opened or closed */
|
||||||
|
onopenchange?: (open: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -120,11 +188,12 @@
|
|||||||
label,
|
label,
|
||||||
placeholder,
|
placeholder,
|
||||||
icon,
|
icon,
|
||||||
loading = false,
|
loading = $bindable(false),
|
||||||
lazy = false,
|
lazy = false,
|
||||||
compact = false,
|
compact = false,
|
||||||
stateless = false,
|
stateless = false,
|
||||||
notFoundMessage = 'No results found',
|
loadingOption = { value: 'special-loading', label: 'Loading...' },
|
||||||
|
notFoundOption = { value: 'special-not-found', label: 'No options found' },
|
||||||
searchKeys = ['label', 'value'],
|
searchKeys = ['label', 'value'],
|
||||||
class: classValue,
|
class: classValue,
|
||||||
use,
|
use,
|
||||||
@@ -133,11 +202,15 @@
|
|||||||
onsearch,
|
onsearch,
|
||||||
onscroll,
|
onscroll,
|
||||||
onlazy,
|
onlazy,
|
||||||
onopen,
|
onopenchange,
|
||||||
onclose
|
labelRender,
|
||||||
|
infotextRender,
|
||||||
|
iconRender
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
let id = $derived(generateIdentifier('combobox', name));
|
const id = $derived(generateIdentifier('combobox', name));
|
||||||
|
const searchKeySet = $derived(new Set(searchKeys));
|
||||||
|
const conditionalUse = $derived(use ? use : () => {});
|
||||||
|
|
||||||
let valid = $state(true);
|
let valid = $state(true);
|
||||||
let searchValue = $state('');
|
let searchValue = $state('');
|
||||||
@@ -149,22 +222,21 @@
|
|||||||
let searchContainer = $state<HTMLDivElement | null>(null);
|
let searchContainer = $state<HTMLDivElement | null>(null);
|
||||||
let pickerContainer = $state<HTMLDivElement | null>(null);
|
let pickerContainer = $state<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
// TODO: finish adding support for dynamic search fields
|
|
||||||
// TODO: finish documenting props
|
|
||||||
// TODO: properly support paginated options???
|
|
||||||
// TODO: there's something weird with dropdown placement on narrow screens
|
// TODO: there's something weird with dropdown placement on narrow screens
|
||||||
// TODO: match width to input isn't working properly for vconf selectors
|
// TODO: match width to input isn't working properly for vconf selectors
|
||||||
|
|
||||||
/** stores options filtered according to search value */
|
/** options filtered by search value and searchKeys */
|
||||||
const filteredItems = $derived.by(() => {
|
const filteredItems = $derived.by(() => {
|
||||||
const arr = matchSorter(options, searchValue, { keys: [(item) => getLabel(item)] });
|
let keys: KeyOption<ComboboxOption>[] = [];
|
||||||
// if (loading) {
|
if (searchKeySet.has('label')) keys.push((item) => getLabel(item));
|
||||||
// arr.push({ value: 'loading', label: 'Loading more...', disabled: true });
|
if (searchKeySet.has('preview')) keys.push((item) => getPreview(item));
|
||||||
// }
|
if (searchKeySet.has('infotext')) keys.push('infotext');
|
||||||
|
if (searchKeySet.has('value') || keys.length === 0) keys.push('value');
|
||||||
|
const arr = matchSorter(options, searchValue, { keys });
|
||||||
return arr;
|
return arr;
|
||||||
});
|
});
|
||||||
|
|
||||||
/** stores currently highlighted option (according to keyboard navigation or default item) */
|
/** currently highlighted option, updated by keyboard navigation or defaults to first item */
|
||||||
let highlighted = $derived.by((): ComboboxOption | undefined => {
|
let highlighted = $derived.by((): ComboboxOption | undefined => {
|
||||||
if (!searching) return undefined; // otherwise, the first item is highlighted on first open
|
if (!searching) return undefined; // otherwise, the first item is highlighted on first open
|
||||||
if (filteredItems.length === 0) return undefined;
|
if (filteredItems.length === 0) return undefined;
|
||||||
@@ -172,20 +244,27 @@
|
|||||||
if (!filteredItems[0]?.disabled) return filteredItems[0];
|
if (!filteredItems[0]?.disabled) return filteredItems[0];
|
||||||
});
|
});
|
||||||
|
|
||||||
/** controls whether an icon should be displayed */
|
/**
|
||||||
let iconVisible = $derived(
|
* Whether an icon should be displayed with the main input.
|
||||||
|
* The icon is determined by the following precedence:
|
||||||
|
* highlighted option (only when the picker is open) > selected value > icon prop
|
||||||
|
*/
|
||||||
|
const iconVisible = $derived(
|
||||||
(open && highlighted && highlighted.icon) ||
|
(open && highlighted && highlighted.icon) ||
|
||||||
(value && value.icon && searchValue === '') ||
|
(value && value.icon && searchValue === '') ||
|
||||||
loading ||
|
loading ||
|
||||||
icon !== undefined
|
icon !== undefined
|
||||||
);
|
);
|
||||||
|
|
||||||
/** controls whether the highlighted option should be used in the selection preview */
|
/** whether the highlighted option should be used in the selection preview */
|
||||||
let useHighlighted = $derived.by(() => {
|
const useHighlighted = $derived.by(() => {
|
||||||
return open && highlighted;
|
return open && highlighted;
|
||||||
});
|
});
|
||||||
|
|
||||||
const validateOpts: ValidatorOptions = { required };
|
/** validation options build from props */
|
||||||
|
const validateOpts: ValidatorOptions = $derived({ required });
|
||||||
|
|
||||||
|
/*** HELPER FUNCTIONS ***/
|
||||||
|
|
||||||
/** returns the index of the highlighted item in filteredItems */
|
/** returns the index of the highlighted item in filteredItems */
|
||||||
const getHighlightedIndex = () => {
|
const getHighlightedIndex = () => {
|
||||||
@@ -221,29 +300,29 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
let lazyApplied = false;
|
let lazyApplied = false;
|
||||||
/** opens combobox picker and propages any necessary events */
|
/** opens combobox picker and propagates any necessary events */
|
||||||
const openPicker = () => {
|
const openPicker = async () => {
|
||||||
open = true;
|
open = true;
|
||||||
|
|
||||||
// if lazy and not applied, enable loading state once and run callback
|
|
||||||
if (lazy && !lazyApplied) {
|
|
||||||
lazyApplied = true;
|
|
||||||
loading = true;
|
|
||||||
onlazy?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
updatePickerRect(); // update picker position
|
updatePickerRect(); // update picker position
|
||||||
scrollToHighlighted(); // scroll to highlighted item
|
scrollToHighlighted(); // scroll to highlighted item
|
||||||
onopen?.(); // trigger onopen event if defined
|
onopenchange?.(true); // trigger onopenchange event if defined
|
||||||
|
|
||||||
|
// handle lazy loading behaviour
|
||||||
|
if (lazy === 'always' || (lazy === true && !lazyApplied)) {
|
||||||
|
lazyApplied = true;
|
||||||
|
loading = true;
|
||||||
|
await onlazy?.();
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
/** closes combobox picker and propages any necessary events */
|
/** closes combobox picker and propagates any necessary events */
|
||||||
const closePicker = () => {
|
const closePicker = () => {
|
||||||
open = false;
|
open = false;
|
||||||
|
|
||||||
searchValue = ''; // clear search value for next time picker opens
|
searchValue = ''; // clear search value for next time picker opens
|
||||||
searching = false; // reset searching state
|
searching = false; // reset searching state
|
||||||
highlighted = value; // reset highlighted item to current value
|
highlighted = value; // reset highlighted item to current value
|
||||||
onclose?.(); // trigger onclose event if defined
|
onopenchange?.(false); // trigger onopenchange event if defined
|
||||||
};
|
};
|
||||||
|
|
||||||
/** updates the value of the combobox and triggers any callbacks, including closing the picker */
|
/** updates the value of the combobox and triggers any callbacks, including closing the picker */
|
||||||
@@ -253,7 +332,7 @@
|
|||||||
onchange?.(newValue);
|
onchange?.(newValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** action to set the minimum width of the combobox based on the number of options */
|
/** sets minimum width of the picker as configured by props */
|
||||||
const minWidth: Action<HTMLDivElement, { options: ComboboxOption[] }> = (
|
const minWidth: Action<HTMLDivElement, { options: ComboboxOption[] }> = (
|
||||||
container,
|
container,
|
||||||
buildOpts
|
buildOpts
|
||||||
@@ -269,9 +348,7 @@
|
|||||||
const avg = options.reduce((acc, item) => acc + getLabel(item).length, 0) / options.length;
|
const avg = options.reduce((acc, item) => acc + getLabel(item).length, 0) / options.length;
|
||||||
container.style.width = `${avg * 2.5}ch`;
|
container.style.width = `${avg * 2.5}ch`;
|
||||||
};
|
};
|
||||||
|
|
||||||
f(buildOpts);
|
f(buildOpts);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
update: (updateOpts: typeof buildOpts) => {
|
update: (updateOpts: typeof buildOpts) => {
|
||||||
f(updateOpts);
|
f(updateOpts);
|
||||||
@@ -341,7 +418,7 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const conditionalUse = $derived(use ? use : () => {});
|
/*** EXPORTED API ***/
|
||||||
|
|
||||||
/** focuses the combobox search input */
|
/** focuses the combobox search input */
|
||||||
export const focus = () => {
|
export const focus = () => {
|
||||||
@@ -358,18 +435,21 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// when the value (or, in some circumstances, highlighted item) changes, update the search input
|
/*** EFFECTS & WINDOW CALLBACKS ***/
|
||||||
|
|
||||||
|
// when the value (or, in some circumstances, highlighted item) changes,
|
||||||
|
// update the search input
|
||||||
|
//
|
||||||
|
// expected triggers include: value, highlighted, useHighlighted, usePreview,
|
||||||
|
// searchInput, searching, and open
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (!searchInput) return;
|
if (!searchInput || searching) return;
|
||||||
|
|
||||||
if (useHighlighted && !searching) {
|
if ((!value && !highlighted) || (useHighlighted && !highlighted)) {
|
||||||
|
searchInput.value = '';
|
||||||
|
} else if (useHighlighted) {
|
||||||
searchInput.value = getLabel(highlighted);
|
searchInput.value = getLabel(highlighted);
|
||||||
return;
|
} else if (!usePreview || (usePreview === 'auto' && open)) {
|
||||||
}
|
|
||||||
|
|
||||||
if (untrack(() => searching)) return;
|
|
||||||
|
|
||||||
if (!usePreview || (usePreview === 'auto' && open)) {
|
|
||||||
searchInput.value = getLabel(value);
|
searchInput.value = getLabel(value);
|
||||||
} else {
|
} else {
|
||||||
searchInput.value = getPreview(value);
|
searchInput.value = getPreview(value);
|
||||||
@@ -383,34 +463,33 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
// close picker if clicked outside
|
||||||
// set initial picker position on load
|
const handleWindowClick: MouseEventHandler<Window> = (e) => {
|
||||||
setTimeout(() => {
|
|
||||||
updatePickerRect();
|
|
||||||
}, 500);
|
|
||||||
|
|
||||||
// update picker position on window resize
|
|
||||||
window.addEventListener('resize', updatePickerRect);
|
|
||||||
|
|
||||||
// add window click listener to close picker
|
|
||||||
window.addEventListener('click', (e) => {
|
|
||||||
if (!searchContainer || !pickerContainer) {
|
if (!searchContainer || !pickerContainer) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
!open ||
|
||||||
searchContainer.contains(e.target as Node) ||
|
searchContainer.contains(e.target as Node) ||
|
||||||
pickerContainer.contains(e.target as Node) ||
|
pickerContainer.contains(e.target as Node)
|
||||||
!open
|
|
||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
closePicker();
|
closePicker();
|
||||||
});
|
};
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
// set initial picker position after load
|
||||||
|
setTimeout(() => {
|
||||||
|
updatePickerRect();
|
||||||
|
}, 500);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<svelte:window onresize={updatePickerRect} onclick={handleWindowClick} />
|
||||||
|
|
||||||
<!-- Combobox picker -->
|
<!-- Combobox picker -->
|
||||||
<Portal target="body">
|
<Portal target="body">
|
||||||
{#if open}
|
{#if open}
|
||||||
@@ -442,67 +521,19 @@
|
|||||||
const margin = 10; // 10px margin for top & bottom
|
const margin = 10; // 10px margin for top & bottom
|
||||||
const atTop = target.scrollTop < margin;
|
const atTop = target.scrollTop < margin;
|
||||||
const atBottom = target.scrollTop + target.clientHeight > target.scrollHeight - margin;
|
const atBottom = target.scrollTop + target.clientHeight > target.scrollHeight - margin;
|
||||||
onscroll({ event: e, top: atTop, bottom: atBottom });
|
onscroll({ event: e, top: atTop, bottom: atBottom, searchInput: searchInput?.value ?? '' });
|
||||||
}}
|
}}
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
>
|
>
|
||||||
{#each filteredItems as item, i (item.value)}
|
{#each filteredItems as opt (opt.value)}
|
||||||
<!-- Option container -->
|
{@render option(opt)}
|
||||||
<div
|
|
||||||
data-id={item.value}
|
|
||||||
aria-selected={value?.value === item.value}
|
|
||||||
aria-label={getLabel(item)}
|
|
||||||
aria-disabled={item.disabled}
|
|
||||||
class={[
|
|
||||||
!compact
|
|
||||||
? 'mb-0.5 min-h-10 py-2.5 pr-1.5 pl-5'
|
|
||||||
: 'mb-0.25 min-h-8 py-1.5 pr-1.5 pl-2.5',
|
|
||||||
'flex flex-wrap items-center',
|
|
||||||
'rounded-sm text-sm capitalize outline-hidden select-none',
|
|
||||||
'hover:bg-sui-accent-500/30 dark:hover:bg-sui-accent-700/30',
|
|
||||||
item.value === highlighted?.value && 'bg-sui-accent-500/80 dark:bg-sui-accent-700/80',
|
|
||||||
item.disabled && 'cursor-not-allowed opacity-50'
|
|
||||||
]}
|
|
||||||
role="option"
|
|
||||||
onclick={() => {
|
|
||||||
if (item.disabled) return;
|
|
||||||
updateValue(item);
|
|
||||||
searchInput?.focus();
|
|
||||||
}}
|
|
||||||
onkeydown={() => {}}
|
|
||||||
tabindex="-1"
|
|
||||||
>
|
|
||||||
<!-- Option icon -->
|
|
||||||
{#if item.icon}
|
|
||||||
{@render optionIconOrIconDef(item)}
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Option label / `render` snippet -->
|
|
||||||
<div class={['mr-8', item.icon && 'ml-2']}>
|
|
||||||
{@render snippetOrString(item, item.render || getLabel(item))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Option infotext / `infotextRender` snippet (always right-aligned) -->
|
|
||||||
{#if item.infotext || item.infotextRender}
|
|
||||||
<div class="text-sui-text/80 dark:text-sui-background/80 ml-auto text-sm">
|
|
||||||
{@render snippetOrString(item, item.infotextRender || item.infotext)}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Option checkmark, visible if selected -->
|
|
||||||
{#if value?.value === item.value}
|
|
||||||
<div class={[item?.infotext ? 'ml-2' : 'ml-auto']}>
|
|
||||||
<Check />
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{:else}
|
{:else}
|
||||||
<!-- Display loading state or not found if no options available -->
|
<!-- Display loading state or not found if no options available -->
|
||||||
<span class="block px-5 py-2 text-sm">
|
<span class="block px-5 py-2 text-sm">
|
||||||
{#if loading}
|
{#if loading}
|
||||||
Loading...
|
{@render option(loadingOption, true)}
|
||||||
{:else}
|
{:else}
|
||||||
{notFoundMessage}
|
{@render option(notFoundOption, true)}
|
||||||
{/if}
|
{/if}
|
||||||
</span>
|
</span>
|
||||||
{/each}
|
{/each}
|
||||||
@@ -510,7 +541,7 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</Portal>
|
</Portal>
|
||||||
|
|
||||||
<!-- Combobox persistant container -->
|
<!-- Combobox main input container -->
|
||||||
<div class={classValue}>
|
<div class={classValue}>
|
||||||
<!-- Combobox Label -->
|
<!-- Combobox Label -->
|
||||||
{#if label}
|
{#if label}
|
||||||
@@ -543,6 +574,64 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#snippet optionIcon(opt: ComboboxOption)}
|
||||||
|
{#if iconRender}
|
||||||
|
{@render iconRender(opt)}
|
||||||
|
{:else if opt.icon}
|
||||||
|
<opt.icon.component {...opt.icon.props} />
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<!-- Combobox option -->
|
||||||
|
{#snippet option(opt: ComboboxOption, forceDisabled?: boolean)}
|
||||||
|
{@const optDisabled = opt.disabled || forceDisabled}
|
||||||
|
<!-- Option container -->
|
||||||
|
<div
|
||||||
|
data-id={opt.value}
|
||||||
|
aria-selected={value?.value === opt.value}
|
||||||
|
aria-label={getLabel(opt)}
|
||||||
|
aria-disabled={optDisabled}
|
||||||
|
class={[
|
||||||
|
!compact ? 'mb-0.5 min-h-10 py-2.5 pr-1.5 pl-5' : 'mb-0.25 min-h-8 py-1.5 pr-1.5 pl-2.5',
|
||||||
|
'flex flex-wrap items-center',
|
||||||
|
'rounded-sm text-sm capitalize outline-hidden select-none',
|
||||||
|
'hover:bg-sui-accent-500/30 dark:hover:bg-sui-accent-700/30',
|
||||||
|
opt.value === highlighted?.value && 'bg-sui-accent-500/80 dark:bg-sui-accent-700/80',
|
||||||
|
optDisabled && 'cursor-not-allowed opacity-50'
|
||||||
|
]}
|
||||||
|
role="option"
|
||||||
|
onclick={() => {
|
||||||
|
if (optDisabled) return;
|
||||||
|
updateValue(opt);
|
||||||
|
searchInput?.focus();
|
||||||
|
}}
|
||||||
|
onkeydown={() => {}}
|
||||||
|
tabindex="-1"
|
||||||
|
>
|
||||||
|
<!-- Option icon -->
|
||||||
|
{@render optionIcon(opt)}
|
||||||
|
|
||||||
|
<!-- Option label -->
|
||||||
|
<div class={['mr-8', opt.icon && 'ml-2']}>
|
||||||
|
{@render snippetOrString(opt, labelRender || getLabel(opt))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Option infotext (always right-aligned) -->
|
||||||
|
{#if opt.infotext || infotextRender}
|
||||||
|
<div class="text-sui-text/80 dark:text-sui-background/80 ml-auto text-sm">
|
||||||
|
{@render snippetOrString(opt, infotextRender || opt.infotext)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Option checkmark, visible if selected -->
|
||||||
|
{#if value?.value === opt.value}
|
||||||
|
<div class={[opt?.infotext ? 'ml-2' : 'ml-auto']}>
|
||||||
|
<Check />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
<!-- Search input box -->
|
<!-- Search input box -->
|
||||||
{#snippet searchInputBox(caret: boolean = true)}
|
{#snippet searchInputBox(caret: boolean = true)}
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
@@ -558,12 +647,16 @@
|
|||||||
>
|
>
|
||||||
{#if loading}
|
{#if loading}
|
||||||
<Spinner class="stroke-sui-accent! -mt-0.5" size="1em" />
|
<Spinner class="stroke-sui-accent! -mt-0.5" size="1em" />
|
||||||
{:else if useHighlighted && highlighted?.icon}
|
{:else if useHighlighted && highlighted}
|
||||||
{@render optionIconOrIconDef(highlighted)}
|
{@render optionIcon(highlighted)}
|
||||||
{:else if value?.icon}
|
{:else if value}
|
||||||
{@render optionIconOrIconDef(value)}
|
{@render optionIcon(value)}
|
||||||
{:else if icon}
|
{:else if icon}
|
||||||
|
{#if typeof icon === 'function'}
|
||||||
|
{@render icon()}
|
||||||
|
{:else}
|
||||||
<icon.component {...icon.props} />
|
<icon.component {...icon.props} />
|
||||||
|
{/if}
|
||||||
{:else}
|
{:else}
|
||||||
❌
|
❌
|
||||||
{/if}
|
{/if}
|
||||||
@@ -634,7 +727,7 @@
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- Right-aligned infotext (overlay) -->
|
<!-- Right-aligned infotext (overlay) -->
|
||||||
{#if (value && (value.infotext || value.infotextRender)) || (highlighted && useHighlighted && (highlighted.infotext || highlighted.infotextRender))}
|
{#if (value && value.infotext) || (highlighted && useHighlighted && highlighted.infotext) || infotextRender}
|
||||||
<div
|
<div
|
||||||
class={[
|
class={[
|
||||||
'pointer-events-none absolute top-1/2 -translate-y-1/2 transform text-sm select-none',
|
'pointer-events-none absolute top-1/2 -translate-y-1/2 transform text-sm select-none',
|
||||||
@@ -642,11 +735,10 @@
|
|||||||
caret ? 'end-10' : 'end-[1.125rem]'
|
caret ? 'end-10' : 'end-[1.125rem]'
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
{useHighlighted && highlighted?.infotext ? highlighted.infotext : value?.infotext}
|
{#if useHighlighted && highlighted}
|
||||||
{#if useHighlighted && (highlighted?.infotext || highlighted?.infotextRender)}
|
{@render snippetOrString(highlighted, infotextRender || highlighted.infotext)}
|
||||||
{@render snippetOrString(highlighted!, highlighted.infotextRender)}
|
{:else if value}
|
||||||
{:else if value?.infotext}
|
{@render snippetOrString(value, infotextRender || value.infotext)}
|
||||||
{@render snippetOrString(value, value.infotextRender)}
|
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -663,14 +755,6 @@
|
|||||||
</div>
|
</div>
|
||||||
{/snippet}
|
{/snippet}
|
||||||
|
|
||||||
{#snippet optionIconOrIconDef(opt: ComboboxOption | undefined)}
|
|
||||||
{#if typeof opt?.icon === 'function'}
|
|
||||||
{@render opt.icon(opt)}
|
|
||||||
{:else if opt?.icon}
|
|
||||||
<opt.icon.component {...opt.icon.props} />
|
|
||||||
{/if}
|
|
||||||
{/snippet}
|
|
||||||
|
|
||||||
{#snippet snippetOrString(
|
{#snippet snippetOrString(
|
||||||
opt: ComboboxOption,
|
opt: ComboboxOption,
|
||||||
value: string | Snippet<[item: ComboboxOption]> | undefined
|
value: string | Snippet<[item: ComboboxOption]> | undefined
|
||||||
|
|||||||
@@ -164,16 +164,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#snippet comboRender(item: ComboboxOption)}
|
|
||||||
Opt 1
|
|
||||||
{/snippet}
|
|
||||||
{#snippet comboInfotext(item: ComboboxOption)}
|
|
||||||
User
|
|
||||||
{/snippet}
|
|
||||||
{#snippet comboPreview(item: ComboboxOption)}
|
|
||||||
Preview {item.label}
|
|
||||||
{/snippet}
|
|
||||||
|
|
||||||
<div class="component">
|
<div class="component">
|
||||||
<p class="title">Combobox</p>
|
<p class="title">Combobox</p>
|
||||||
|
|
||||||
@@ -187,17 +177,21 @@
|
|||||||
value: 'option1',
|
value: 'option1',
|
||||||
label: 'Option 1',
|
label: 'Option 1',
|
||||||
preview: 'Prvw',
|
preview: 'Prvw',
|
||||||
infotext: 'Info',
|
infotext: 'Info'
|
||||||
render: comboRender,
|
|
||||||
infotextRender: comboInfotext,
|
|
||||||
previewRender: comboPreview
|
|
||||||
},
|
},
|
||||||
{ value: 'option2', label: 'Option 2' },
|
{ value: 'option2', label: 'Option 2' },
|
||||||
{ value: 'option3', label: 'Option 3', disabled: true }
|
{ value: 'option3', label: 'Option 3', disabled: true }
|
||||||
]}
|
]}
|
||||||
onchange={(e) => console.log('Selected:', e.value)}
|
onchange={(e) => console.log('Selected:', e.value)}
|
||||||
onvalidate={(e) => console.log('Validation:', e.detail)}
|
onvalidate={(e) => console.log('Validation:', e.detail)}
|
||||||
/>
|
>
|
||||||
|
{#snippet labelRender(opt: ComboboxOption)}
|
||||||
|
Processed {opt.label}
|
||||||
|
{/snippet}
|
||||||
|
{#snippet infotextRender(opt: ComboboxOption)}
|
||||||
|
Processed {opt.infotext}
|
||||||
|
{/snippet}
|
||||||
|
</Combobox>
|
||||||
|
|
||||||
<Combobox
|
<Combobox
|
||||||
loading
|
loading
|
||||||
@@ -223,15 +217,17 @@
|
|||||||
label="Lazy combobox"
|
label="Lazy combobox"
|
||||||
placeholder="Choose..."
|
placeholder="Choose..."
|
||||||
options={lazyOptions}
|
options={lazyOptions}
|
||||||
lazy
|
lazy={'always'}
|
||||||
onlazy={() => {
|
onlazy={async () => {
|
||||||
setTimeout(() => {
|
await new Promise((resolve) => setTimeout(resolve, 2500));
|
||||||
lazyOptions = [
|
lazyOptions = [
|
||||||
{ value: 'option1', label: 'Option 1' },
|
{ value: 'option1', label: 'Option 1' },
|
||||||
{ value: 'option2', label: 'Option 2' },
|
{ value: 'option2', label: 'Option 2' },
|
||||||
{ value: 'option3', label: 'Option 3' }
|
{ value: 'option3', label: 'Option 3' }
|
||||||
];
|
];
|
||||||
}, 2500);
|
}}
|
||||||
|
onopenchange={(open) => {
|
||||||
|
if (!open) lazyOptions = [];
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Combobox
|
<Combobox
|
||||||
|
|||||||
Reference in New Issue
Block a user