Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow 'multiple' Listbox options #92

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion src/lib/components/listbox/Listbox.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
Open,
Closed,
}
export enum ValueMode {
Single,
Multi,
}
export type ListboxOptionDataRef = {
textValue: string;
disabled: boolean;
Expand All @@ -14,6 +18,7 @@
listboxState: ListboxStates;
value: unknown;
orientation: "vertical" | "horizontal";
mode: ValueMode;

labelRef: Writable<HTMLLabelElement | null>;
buttonRef: Writable<HTMLButtonElement | null>;
Expand Down Expand Up @@ -61,6 +66,8 @@
horizontal?: boolean;
/** The selected value */
value?: StateDefinition["value"];
/** Whether the `Listbox` should allow mutliple selections */
multiple?: boolean;
};
</script>

Expand Down Expand Up @@ -89,6 +96,7 @@
export let use: HTMLActionArray = [];
export let disabled = false;
export let horizontal = false;
export let multiple = false;
export let value: StateDefinition["value"];

/***** Events *****/
Expand All @@ -112,6 +120,9 @@
let options: StateDefinition["options"] = [];
let searchQuery: StateDefinition["searchQuery"] = "";
let activeOptionIndex: StateDefinition["activeOptionIndex"] = null;
let mode: StateDefinition["mode"] = multiple
? ValueMode.Multi
: ValueMode.Single;

let api = writable<StateDefinition>({
listboxState,
Expand All @@ -124,6 +135,7 @@
activeOptionIndex,
disabled,
orientation,
mode,
closeListbox() {
if (disabled) return;
if (listboxState === ListboxStates.Closed) return;
Expand Down Expand Up @@ -231,7 +243,25 @@
},
select(value: unknown) {
if (disabled) return;
dispatch("change", value);
dispatch(
"change",
match(mode, {
[ValueMode.Single]: () => value,
[ValueMode.Multi]: () => {
let copy = ($api.value as unknown[]).slice();
let raw = value;

let idx = copy.indexOf(raw);
if (idx === -1) {
copy.push(raw);
} else {
copy.splice(idx, 1);
}

return copy;
},
})
);
},
});
setContext(LISTBOX_CONTEXT_NAME, api);
Expand All @@ -256,6 +286,7 @@
activeOptionIndex,
disabled,
orientation,
mode,
};
});

Expand Down
33 changes: 29 additions & 4 deletions src/lib/components/listbox/ListboxOption.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@

<script lang="ts">
import { onDestroy, onMount, tick } from "svelte";
import { ListboxStates, useListboxContext } from "./Listbox.svelte";
import {
ListboxStates,
useListboxContext,
ValueMode,
} from "./Listbox.svelte";
import { useId } from "$lib/hooks/use-id";
import { Focus } from "$lib/utils/calculate-active-index";
import Render from "$lib/utils/Render.svelte";
Expand All @@ -21,6 +25,7 @@
import { get_current_component } from "svelte/internal";
import type { HTMLActionArray } from "$lib/hooks/use-actions";
import type { TPassThroughProps } from "$lib/types";
import { match } from "$lib/utils/match";

/***** Props *****/
type TAsProp = $$Generic<SupportedAs>;
Expand All @@ -39,13 +44,26 @@
let id = `headlessui-listbox-option-${useId()}`;

let buttonRef = $api.buttonRef;
let isFirstSelected = false;

$: active =
$api.activeOptionIndex !== null
? $api.options[$api.activeOptionIndex].id === id
: false;

$: selected = $api.value === value;
$: selected = match($api.mode, {
[ValueMode.Single]: () => $api.value === value,
[ValueMode.Multi]: () => ($api.value as unknown[]).includes(value),
});

$: isFirstSelected = match($api.mode, {
[ValueMode.Single]: () => selected,
[ValueMode.Multi]: () =>
$api.options.find((option: unknown) =>
($api.value as unknown[]).includes(option)
)?.id === id,
});

$: dataRef = {
disabled,
value,
Expand Down Expand Up @@ -75,7 +93,14 @@
await tick();
if (newState !== oldState || newSelected !== oldSelected) {
if (newState === ListboxStates.Open && newSelected) {
$api.goToOption(Focus.Specific, id);
match($api.mode, {
[ValueMode.Multi]: () => {
if (isFirstSelected) $api.goToOption(Focus.Specific, id);
},
[ValueMode.Single]: () => {
$api.goToOption(Focus.Specific, id);
},
});
}
}
if (newState !== oldState || newActive !== oldActive) {
Expand All @@ -93,7 +118,7 @@
let event = e as any as MouseEvent;
if (disabled) return event.preventDefault();
$api.select(value);
$api.closeListbox();
if ($api.mode === ValueMode.Single) $api.closeListbox();
await tick();
$buttonRef?.focus({ preventScroll: true });
}
Expand Down
6 changes: 3 additions & 3 deletions src/lib/components/listbox/ListboxOptions.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

<script lang="ts">
import { tick } from "svelte";
import { ListboxStates, useListboxContext } from "./Listbox.svelte";
import { ListboxStates, ValueMode, useListboxContext } from './Listbox.svelte';
import { useId } from "$lib/hooks/use-id";
import { match } from "$lib/utils/match";
import { Keys } from "$lib/utils/keyboard";
Expand Down Expand Up @@ -64,9 +64,9 @@
let { dataRef } = $api.options[$api.activeOptionIndex];
$api.select(dataRef.value);
}
$api.closeListbox();
if ($api.mode === ValueMode.Single) $api.closeListbox();
await tick();
$buttonRef?.focus({ preventScroll: true });
if ($api.mode === ValueMode.Single) $buttonRef?.focus({ preventScroll: true });
break;

case match($api.orientation, {
Expand Down
38 changes: 38 additions & 0 deletions src/routes/docs/listbox.svx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,44 @@ You can use these states to conditionally apply whatever active/focus styles you
</Listbox>
```

## Multiple Values

To allow selecting multiple values in your listbox, use the `multiple` prop and pass an array to `value` instead of a single option.

```svelte
<script>
import {
Listbox,
ListboxButton,
ListboxLabel,
ListboxOptions,
ListboxOption,
} from "@rgossiaux/svelte-headlessui";

const people = [
{ id: 1, name: "Durward Reynolds" },
{ id: 2, name: "Kenton Towne" },
{ id: 3, name: "Therese Wunsch" },
{ id: 4, name: "Benedict Kessler" },
{ id: 5, name: "Katelyn Rohan" },
];

let selectedPeople = [people[0], people[1]];
</script>

<Listbox value={selectedPeople} on:change={(e) => (selectedPeople = e.detail)} multiple>
<ListboxLabel>Assignee:</ListboxLabel>
<ListboxButton>{selectedPeople.map((person) => person.name).join(', ')}</ListboxButton>
<ListboxOptions>
{#each people as person (person.id)}
<ListboxOption value={person}>
{person.name}
</ListboxOption>
{/each}
</ListboxOptions>
</Listbox>
```

## Using a custom label

By default, the `Listbox` will use the `<ListboxButton>` contents as the label for screenreaders. If you'd like more control over what is announced to assistive technologies, use the `ListboxLabel` component:
Expand Down