Merge pull request #94 from metonym/multi-select

feat(component): add MultiSelect
This commit is contained in:
Eric Liu 2019-12-31 12:59:47 -08:00 committed by GitHub
commit ecc67211fc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 425 additions and 13 deletions

View file

@ -57,6 +57,7 @@ Currently, the following components are supported:
- ListBoxSelection
- ListItem
- Loading
- MultiSelect
- Modal
- Notification
- ToastNotification

View file

@ -6,6 +6,8 @@
export let disabled = false;
export let id = Math.random();
export let labelText = '';
export let name = '';
export let readonly = false;
export let hideLabel = false;
export let title = '';
export let style = undefined;
@ -37,7 +39,9 @@
{indeterminate}
{disabled}
{checked}
{id} />
{name}
{id}
{readonly} />
<label class={cx('--checkbox-label')} for={id} title={title || undefined}>
<span class={cx('--checkbox-label-text', hideLabel && '--visually-hidden')}>{labelText}</span>
</label>

View file

@ -30,8 +30,9 @@
ListBoxSelection
} from '../ListBox';
let selectedId = undefined;
let inputRef = undefined;
let inputValue = undefined;
let inputValue = '';
let highlightedIndex = -1;
function change(direction) {
@ -49,20 +50,21 @@
afterUpdate(() => {
if (open) {
inputRef.focus();
filteredItems = items.filter(item => shouldFilterItem(item, value));
} else {
highlightedIndex = -1;
inputValue = selectedItem ? selectedItem.text : '';
}
});
$: selectedItem = items[selectedIndex];
$: inputValue = selectedItem ? selectedItem.text : undefined;
$: value = inputValue;
$: ariaLabel = $$props['aria-label'] || 'Choose an item';
$: menuId = `menu-${id}`;
$: comboId = `combo-${id}`;
$: highlightedId = items[highlightedIndex] ? items[highlightedIndex].id : undefined;
$: filteredItems = items.filter(item => shouldFilterItem(item, value));
$: selectedItem = items[selectedIndex];
$: inputValue = selectedItem ? selectedItem.text : undefined;
$: value = inputValue;
</script>
<svelte:body
@ -105,6 +107,7 @@
tabindex="0"
autocomplete="off"
aria-autocomplete="list"
aria-expanded={open}
aria-activedescendant={highlightedId}
aria-labelledby={comboId}
aria-disabled={disabled}
@ -165,10 +168,11 @@
<ListBoxMenu aria-label={ariaLabel} {id}>
{#each filteredItems as item, i (item.id || i)}
<ListBoxMenuItem
active={selectedIndex === i}
active={selectedIndex === i || selectedId === item.id}
highlighted={highlightedIndex === i || selectedIndex === i}
on:click={() => {
selectedIndex = i;
selectedId = item.id;
selectedIndex = items.map(({ id }) => id).indexOf(filteredItems[i].id);
open = false;
}}
on:mouseenter={() => {

View file

@ -1,6 +1,7 @@
<script>
let className = undefined;
export { className as class };
export let id = Math.random();
export let size = undefined;
export let type = 'default';
export let disabled = false;
@ -26,7 +27,8 @@
}
}}
on:click|preventDefault|stopPropagation
{style}>
{style}
{id}>
<slot />
</div>
{#if invalid}

View file

@ -9,18 +9,27 @@
export let translateWithId = id => defaultTranslations[id];
export let style = undefined;
import { getContext } from 'svelte';
import { cx } from '../../lib';
const defaultTranslations = {
[translationIds.close]: 'Close menu',
[translationIds.open]: 'Open menu'
};
const ctx = getContext('MultiSelect');
let fieldRef = undefined;
$: if (ctx && fieldRef) {
ctx.declareRef({ key: 'field', ref: fieldRef });
}
$: ariaExpanded = $$props['aria-expanded'];
$: menuId = `menu-${id}`;
</script>
<div
bind:this={fieldRef}
role={ariaExpanded ? 'combobox' : role}
aria-expanded={ariaExpanded}
aria-owns={(ariaExpanded && menuId) || undefined}
@ -32,6 +41,8 @@
on:mouseover
on:mouseenter
on:mouseleave
on:keydown|preventDefault|stopPropagation
on:blur
{style}>
<slot />
</div>

View file

@ -1,7 +1,7 @@
<script>
let className = undefined;
export { className as class };
export let id = Math.random(); // TODO: Use context to re-use same id per ListBox
export let id = Math.random();
export let style = undefined;
import { cx } from '../../lib';
@ -9,6 +9,11 @@
$: menuId = `menu-${id}`;
</script>
<div role="listbox" id={menuId} class={cx('--list-box__menu', className)} {style}>
<div
role="listbox"
id={menuId}
aria-label={$$props['aria-label']}
class={cx('--list-box__menu', className)}
{style}>
<slot />
</div>

View file

@ -7,21 +7,28 @@
export let translateWithId = id => defaultTranslations[id];
export let style = undefined;
import { createEventDispatcher } from 'svelte';
import { createEventDispatcher, getContext } from 'svelte';
import Close16 from 'carbon-icons-svelte/lib/Close16';
import { cx } from '../../lib';
const dispatch = createEventDispatcher();
const defaultTranslations = {
[translationIds.clearAll]: 'Clear all selected items',
[translationIds.clearSelection]: 'Clear selected item'
};
const dispatch = createEventDispatcher();
const ctx = getContext('MultiSelect');
let selectionRef = undefined;
$: if (ctx && selectionRef) {
ctx.declareRef({ key: 'selection', ref: selectionRef });
}
$: description = selectionCount ? translateWithId('clearAll') : translateWithId('clearSelection');
</script>
<div
bind:this={selectionRef}
role="button"
aria-label="Clear Selection"
tabindex={disabled ? '-1' : '0'}

View file

@ -0,0 +1,41 @@
<script>
import Layout from '../../internal/ui/Layout.svelte';
import Button from '../Button';
import MultiSelect from './MultiSelect.svelte';
let value = '';
let items = [
{ id: 'option-0', text: 'Option 1' },
{ id: 'option-1', text: 'Option 2' },
{ id: 'option-2', text: 'Option 3' },
{ id: 'option-3', text: 'Option 4' },
{
id: 'option-4',
text: 'An example option that is really long to show what should be done to handle long text'
}
];
let selectedIds = [];
</script>
<Layout>
<div>
<Button
size="small"
on:click={() => {
selectedIds = selectedIds.length > 0 ? [] : [items[1].id, items[2].id];
}}>
{selectedIds.length > 0 ? 'Clear' : 'Set initial'} selected items
</Button>
</div>
<div style="width: 300px; margin-top: 2rem;">
<MultiSelect
{...$$props}
id="multiselect"
placeholder="Filter..."
bind:selectedIds
bind:items
bind:value />
</div>
</Layout>

View file

@ -0,0 +1,38 @@
import { withKnobs, select, boolean, text } from '@storybook/addon-knobs';
import Component from './MultiSelect.Story.svelte';
export default { title: 'MultiSelect', decorators: [withKnobs] };
const types = {
'Default (default)': 'default',
'Inline (inline)': 'inline'
};
const sizes = {
'Extra large size (xl)': 'xl',
'Regular size (lg)': '',
'Small size (sm)': 'sm'
};
export const Default = () => ({
Component,
props: {
id: 'multiselect',
titleText: text('Title (titleText)', 'Multiselect Title'),
helperText: text('Helper text (helperText)', 'This is not helper text'),
filterable: boolean('Filterable (filterable)', false),
selectionFeedback: select(
'Selection feedback (selectionFeedback)',
['top', 'fixed', 'top-after-reopen'],
'top-after-reopen'
),
disabled: boolean('Disabled (disabled)', false),
light: boolean('Light variant (light)', false),
useTitleInItem: boolean('Show tooltip on hover', false),
type: select('UI type (Only for `<MultiSelect>`) (type)', types, 'default'),
size: select('Field size (size)', sizes, '') || undefined,
label: text('Label (label)', 'MultiSelect Label'),
invalid: boolean('Show form validation UI (invalid)', false),
invalidText: text('Form validation UI content (invalidText)', 'Invalid Selection')
}
});

View file

@ -0,0 +1,294 @@
<script>
let className = undefined;
export { className as class };
export let id = Math.random();
export let titleText = '';
export let helperText = '';
export let disabled = false;
export let value = '';
export let open = false;
export let selectedIds = [];
export let items = [];
export let itemToString = item => item.text || item.id;
export let placeholder = '';
export let filterable = false;
export let invalid = false;
export let invalidText = '';
export let translateWithId = undefined;
export let size = undefined;
export let type = 'default';
export let locale = 'en';
export let sortItem = (a, b) => a.text.localeCompare(b.text, locale, { numeric: true });
export let filterItem = (item, value) => item.text.toLowerCase().includes(value.toLowerCase());
export let label = '';
export let useTitleInItem = false;
export let selectionFeedback = 'top-after-reopen';
export let light = false;
export let style = undefined;
import { afterUpdate, setContext } from 'svelte';
import WarningFilled16 from 'carbon-icons-svelte/lib/WarningFilled16';
import { cx } from '../../lib';
import Checkbox from '../Checkbox';
import ListBox, {
ListBoxField,
ListBoxMenu,
ListBoxMenuIcon,
ListBoxMenuItem,
ListBoxSelection
} from '../ListBox';
let multiSelectRef = undefined;
let fieldRef = undefined;
let selectionRef = undefined;
let inputRef = undefined;
let inputValue = '';
let initialSorted = false;
let highlightedIndex = -1;
let prevChecked = [];
setContext('MultiSelect', {
declareRef: ({ key, ref }) => {
switch (key) {
case 'field':
fieldRef = ref;
break;
case 'selection':
selectionRef = ref;
break;
}
}
});
function change(direction) {
let index = highlightedIndex + direction;
if (index < 0) {
index = items.length - 1;
} else if (index >= items.length) {
index = 0;
}
highlightedIndex = index;
}
function sort() {
return [
...(checked.length > 1 ? checked.sort(sortItem) : checked),
...unchecked.sort(sortItem)
];
}
afterUpdate(() => {
if (checked.length !== prevChecked.length) {
if (selectionFeedback === 'top') {
sortedItems = sort();
}
prevChecked = checked;
selectedIds = checked.map(({ id }) => id);
}
if (!open) {
if (!initialSorted || selectionFeedback !== 'fixed') {
sortedItems = sort();
initialSorted = true;
}
highlightedIndex = -1;
inputValue = '';
}
items = sortedItems;
});
$: menuId = `menu-${id}`;
$: inline = type === 'inline';
$: ariaLabel = $$props['aria-label'] || 'Choose an item';
$: sortedItems = items.map(item => ({ ...item, checked: selectedIds.includes(item.id) }));
$: checked = sortedItems.filter(({ checked }) => checked);
$: unchecked = sortedItems.filter(({ checked }) => !checked);
$: filteredItems = sortedItems.filter(item => filterItem(item, value));
$: highlightedId = sortedItems[highlightedIndex] ? sortedItems[highlightedIndex].id : undefined;
$: value = inputValue;
</script>
<svelte:body
on:click={({ target }) => {
if (open && multiSelectRef && !multiSelectRef.contains(target)) {
open = false;
}
}} />
<div
bind:this={multiSelectRef}
class={cx('--multi-select__wrapper', '--list-box__wrapper', inline && '--multi-select__wrapper--inline', inline && '--list-box__wrapper--inline', inline && invalid && '--multi-select__wrapper--inline--invalid', inline && invalid && '--list-box__wrapper--inline--invalid', className)}
{style}>
{#if titleText}
<label class={cx('--label', disabled && '--label--disabled')} for={id}>{titleText}</label>
{/if}
{#if !inline && helperText}
<div class={cx('--form__helper-text', disabled && '--form__helper-text--disabled')}>
{helperText}
</div>
{/if}
<ListBox
aria-label={ariaLabel}
class={cx('--multi-select', filterable && '--combo-box', filterable && '--multi-select--filterable', invalid && '--multi-select--invalid', inline && '--multi-select--inline', checked.length > 0 && '--multi-select--selected')}
{id}
{disabled}
{invalid}
{invalidText}
{open}
{light}
{size}>
{#if invalid}
<WarningFilled16 class={cx('--list-box__invalid-icon')} />
{/if}
<ListBoxField
role="button"
tabindex="0"
aria-expanded={open}
on:click={() => {
if (filterable) {
open = true;
inputRef.focus();
} else {
open = !open;
}
}}
on:keydown={({ key }) => {
if (filterable) {
return;
}
if (key === ' ') {
open = !open;
} else if (key === 'Tab') {
if (selectionRef && checked.length > 0) {
selectionRef.focus();
} else {
open = false;
fieldRef.blur();
}
} else if (key === 'ArrowDown') {
change(1);
} else if (key === 'ArrowUp') {
change(-1);
} else if (key === 'Enter') {
if (highlightedIndex > -1) {
sortedItems[highlightedIndex].checked = !sortedItems[highlightedIndex].checked;
}
}
}}
on:blur={({ relatedTarget }) => {
if (relatedTarget && relatedTarget.getAttribute('role') !== 'button') {
fieldRef.focus();
}
}}
{id}
{disabled}
{translateWithId}>
{#if checked.length > 0}
<ListBoxSelection
selectionCount={checked.length}
on:clear={() => {
sortedItems = sortedItems.map(item => ({ ...item, checked: false }));
fieldRef.blur();
}}
{translateWithId}
{disabled} />
{/if}
{#if filterable}
<input
bind:this={inputRef}
role="combobox"
tabindex="0"
autocomplete="off"
aria-autocomplete="list"
aria-expanded={open}
aria-activedescendant={highlightedId}
aria-disabled={disabled}
aria-controls={menuId}
class={cx('--text-input', inputValue === '' && '--text-input--empty')}
on:input={({ target }) => {
inputValue = target.value;
}}
on:keydown
on:keydown|stopPropagation={({ key }) => {
if (key === 'Enter') {
if (highlightedIndex > -1) {
sortedItems[highlightedIndex].checked = !sortedItems[highlightedIndex].checked;
}
} else if (key === 'Tab') {
open = false;
} else if (key === 'ArrowDown') {
change(1);
} else if (key === 'ArrowUp') {
change(-1);
}
}}
on:focus
on:blur
on:blur={({ relatedTarget }) => {
if (relatedTarget && relatedTarget.getAttribute('role') !== 'button') {
inputRef.focus();
}
}}
{disabled}
{placeholder}
{id}
value={inputValue} />
{#if invalid}
<WarningFilled16 class={cx('--list-box__invalid-icon')} />
{/if}
{#if inputValue}
<ListBoxSelection
on:clear={() => {
inputValue = '';
open = false;
}}
{translateWithId}
{disabled}
{open} />
{/if}
<ListBoxMenuIcon
on:click={() => {
open = !open;
}}
{translateWithId}
{open} />
{/if}
{#if !filterable}
<span class={cx('--list-box__label')}>{label}</span>
<ListBoxMenuIcon {open} {translateWithId} />
{/if}
</ListBoxField>
{#if open}
<ListBoxMenu aria-label={ariaLabel} {id}>
{#each filterable ? filteredItems : sortedItems as item, i (item.id || i)}
<ListBoxMenuItem
active={item.checked}
highlighted={highlightedIndex === i}
on:click={() => {
sortedItems = sortedItems.map(_ =>
_.id === item.id ? { ..._, checked: !_.checked } : _
);
fieldRef.focus();
}}
on:mouseenter={() => {
highlightedIndex = i;
}}>
<Checkbox
readonly
tabindex="-1"
id={`checkbox-${item.id}`}
title={useTitleInItem ? itemToString(item) : undefined}
name={itemToString(item)}
labelText={itemToString(item)}
checked={item.checked}
{disabled} />
</ListBoxMenuItem>
{/each}
</ListBoxMenu>
{/if}
</ListBox>
</div>

View file

@ -0,0 +1,3 @@
import MultiSelect from './MultiSelect.svelte';
export default MultiSelect;

View file

@ -32,6 +32,7 @@ import ListBox, {
} from './components/ListBox';
import ListItem from './components/ListItem';
import Loading from './components/Loading';
import MultiSelect from './components/MultiSelect';
import Modal from './components/Modal';
import {
ToastNotification,
@ -123,6 +124,7 @@ export {
Icon,
IconSkeleton,
InlineLoading,
MultiSelect,
Modal,
InlineNotification,
Link,