Options and collections
@codeui/solid v0.3.0
Helpers that turn your data into options for Select, Combobox, and CommandMenu.
Each list component reads its options in its own way. Pick the helper that matches the component.
| Component | What it holds | Helper |
|---|---|---|
| Select | One or more values picked from a popover list. | createSelectOptions |
| Combobox | One value picked by typing into a filtered list. | createComboboxOptions |
| Listbox | One or more values in a list that stays on the page. | None. It takes options with Kobalte's option keys. |
| CommandMenu | No value. It runs the action the user picks. | filterCommandItems |
The two option helpers solve the same problem. You keep a plain value in your state, such as a theme id, while the component works with option objects. Both return options, optionToValue, optionFromValue, props, and controlled. Their configuration and their props() differ, as the sections below show.
createSelectOptions
import { createSelectOptions } from "@codeui/solid";
function createSelectOptions<T, C extends { key?: string; valueKey?: string }>(
values: readonly T[] | Accessor<readonly T[]>,
config?: C,
): CreateSelectOptionsReturn<T, C>;import { createSignal } from "solid-js";
import { createSelectOptions, Select } from "@codeui/solid";
type Theme = { id: string; name: string };
const themes: Theme[] = [
{ id: "dracula", name: "Dracula" },
{ id: "one-dark", name: "One Dark" },
{ id: "night-owl", name: "Night Owl" },
];
export default function SelectOptionsHelperDemo() {
const [themeId, setThemeId] = createSignal("dracula");
const themeOptions = createSelectOptions(themes, { key: "name", valueKey: "id" });
return (
<>
<Select
aria-label="Theme"
label="Theme"
options={themeOptions.options()}
{...themeOptions.props()}
value={themeOptions.optionFromValue(themeId())}
onChange={option => {
const id = themeOptions.optionToValue(option);
if (id) setThemeId(id);
}}
/>
<p>Stored value: {themeId()}</p>
</>
);
}Parameters
| Parameter | Description |
|---|---|
values | The source items, as an array or an accessor that returns one. |
config.key | The field to show as the label. Without it, the label is the whole item. |
config.valueKey | The field to use as the value. Without it, the value is the whole item. |
Return value
| Member | Description |
|---|---|
options() | The items mapped to { label, value }. Pass it to options. |
props() | optionValue, optionTextValue, itemLabel, and valueComponent for Select. It does not include options. |
optionFromValue(value) | The option whose value equals value with ===, or undefined. |
optionToValue(option) | The value of the option, or undefined for null or undefined. |
controlled(value, onChange) | { value, onChange } to spread on Select. value is an accessor of your plain value. onChange receives the plain value and the option. |
The value type follows valueKey. With { valueKey: "id" } on Theme[], the value is Theme["id"].
Edge cases
controlledtreats every falsy value as no selection. A value of0or""never selects an option. UseoptionFromValuedirectly for those values.- There is no
disabledmapping. PassoptionDisabledtoSelectas a function over the{ label, value }option. optionTextValueuses the label when it is a string, andString(value)otherwise. Type-ahead reads it.options()builds new option objects on each call. Compare options byvalue, not by identity.- With an accessor source, the options follow the accessor. Write a new array to the signal to update the list.
createComboboxOptions
import { createComboboxOptions } from "@codeui/solid";
// also exported from "@codeui/solid/combobox/parts"
function createComboboxOptions<T extends string | number>(
values: readonly T[] | Accessor<readonly T[]>,
): CreateComboboxOptionsReturn<T, T>;
function createComboboxOptions<T extends object, C extends ComboboxOptionsConfig<T>>(
values: readonly T[] | Accessor<readonly T[]>,
config: C,
): CreateComboboxOptionsReturn<T[C["valueKey"]], T>;import { createSignal } from "solid-js";
import { Combobox, createComboboxOptions } from "@codeui/solid";
type Font = { id: string; name: string; ligatures: boolean; premium: boolean };
const fonts: Font[] = [
{ id: "jetbrains-mono", name: "JetBrains Mono", ligatures: true, premium: false },
{ id: "fira-code", name: "Fira Code", ligatures: true, premium: false },
{ id: "source-code-pro", name: "Source Code Pro", ligatures: false, premium: false },
{ id: "operator-mono", name: "Operator Mono", ligatures: false, premium: true },
];
export default function ComboboxOptionsHelperDemo() {
const [fontId, setFontId] = createSignal<string | undefined>("fira-code");
const fontOptions = createComboboxOptions(fonts, {
valueKey: "id",
labelKey: "name",
disabledKey: "premium",
});
const font = () => fontOptions.optionFromValue(fontId())?.item;
return (
<>
<Combobox
{...fontOptions.props()}
{...fontOptions.controlled(fontId, setFontId)}
label="Font"
placeholder="Search fonts"
/>
<p>
{font() ? `${font()!.name}, ligatures ${font()!.ligatures ? "on" : "off"}` : "No font"}
</p>
</>
);
}Parameters
| Parameter | Description |
|---|---|
values | The source items, as an array or an accessor that returns one. Strings and numbers need no config. |
config.valueKey | Required for objects. A field whose type is string or number. |
config.labelKey | Required for objects. A string field. The input shows it and the filter searches it. |
config.disabledKey | Optional. A boolean field. true disables the option. |
TypeScript checks each key against the field types, so a labelKey that points to a number field does not compile.
Return value
ComboboxOption<Value, Item> is { value, label, disabled, item }. item is your original object.
| Member | Description |
|---|---|
options() | The normalized options. |
props() | options, plus optionValue: "value", optionTextValue: "label", optionLabel: "label", and optionDisabled: "disabled". Spread it on Combobox or on Root from @codeui/solid/combobox/parts. |
optionFromValue(value) | The option whose value equals value with ===. It returns undefined for null, undefined, or no match. |
optionToValue(option) | The value of the option, or undefined. |
controlled(value, onChange) | { value, onChange } to spread on Combobox. value is the matching option or null. onChange receives the plain value and the option. |
ComboboxOption, ComboboxOptionsConfig, and CreateComboboxOptionsReturn are exported from @codeui/solid and @codeui/solid/combobox/parts.
Edge cases
controlledalways passes a value,nullwhen nothing matches. The combobox is then controlled. Clearing the text calls youronChangewithundefined, and the selection clears. See Clear a controlled value.options()caches the normalized list until the source array changes identity. Mutating the array in place does not update the options. Write a new array.- A form submits the value as a string. A numeric
idof3arrives as"3". labelmust be a string, because the input shows it and the filter searches it. UserenderOptiononComboboxfor rich content in the list.
Reactive options
import { createSignal } from "solid-js";
import { Button, Combobox, createComboboxOptions } from "@codeui/solid";
type Preset = { id: number; name: string };
export default function ReactiveOptionsDemo() {
const [presets, setPresets] = createSignal<Preset[]>([
{ id: 1, name: "Blog header" },
{ id: 2, name: "Tweet card" },
]);
const [presetId, setPresetId] = createSignal<number | undefined>(1);
const presetOptions = createComboboxOptions(presets, { valueKey: "id", labelKey: "name" });
const addPreset = () => {
const id = presets().length + 1;
setPresets([...presets(), { id, name: `Preset ${id}` }]);
};
return (
<>
<Combobox
{...presetOptions.props()}
{...presetOptions.controlled(presetId, setPresetId)}
label="Preset"
placeholder="Search presets"
/>
<Button variant="secondary" onClick={addPreset}>
Save current as preset
</Button>
</>
);
}Pass a signal accessor as values. Each new array rebuilds the options, and the open list updates. The controlled value stays selected as long as an option with that value still exists.
filterCommandItems
import { filterCommandItems, type CommandItem } from "@codeui/solid";
function filterCommandItems<T extends CommandItem>(items: readonly T[], query: string): readonly T[];import { createSignal, For } from "solid-js";
import { filterCommandItems, TextField, type CommandItem } from "@codeui/solid";
const commands: CommandItem[] = [
{ id: "export-png", textValue: "Export as PNG", label: "Export as PNG", group: "Export" },
{ id: "export-svg", textValue: "Export as SVG", label: "Export as SVG", group: "Export" },
{ id: "copy-link", textValue: "Copy share link", label: "Copy share link", group: "Share" },
{
id: "theme-dracula",
textValue: "Dracula",
label: "Dracula",
description: "Dark theme",
group: "Theme",
},
];
export default function FilterCommandItemsDemo() {
const [query, setQuery] = createSignal("");
const results = () => filterCommandItems(commands, query());
return (
<>
<TextField label="Search commands" placeholder="Try export png or dark" value={query()} onChange={setQuery} />
<ul>
<For each={results()} fallback={<li>No command matches.</li>}>
{command => (
<li>
{command.group}: {command.label}
</li>
)}
</For>
</ul>
</>
);
}Parameters
| Parameter | Description |
|---|---|
items | The command items. Each needs a unique id and a plain-text textValue. |
query | The search text. |
Return value
The items that match every word of the query, in their original order. An item matches a word when its textValue, group, section, or plain-string description contains the word. Matching ignores case.
Edge cases
- An empty query, or one with only spaces, returns the
itemsarray itself. - Matching is by substring, not fuzzy. "exp png" matches "Export as PNG". "epng" does not.
- A
descriptionthat is JSX is not searched. Put the searchable words intextValueor pass a string description. CommandMenuuses this function when you leave out itsfilterprop. To change the matching, pass afilterwith the same signature. CallfilterCommandItemsinside it to extend the default.
Related
- Select consumes
createSelectOptions. - Combobox consumes
createComboboxOptions. - CommandMenu uses
filterCommandItemsas its default filter.