feat(components): add ComboBox

Closes #12
This commit is contained in:
Eric Liu 2019-12-30 14:49:24 -08:00
commit d9262ce933
28 changed files with 410 additions and 138 deletions

View file

@ -0,0 +1,53 @@
<script>
import Layout from '../../internal/ui/Layout.svelte';
import ToggleSmall from '../ToggleSmall';
import Button from '../Button';
import ComboBox from './ComboBox.svelte';
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 toggled = false;
let value = undefined;
let selectedIndex = -1;
function shouldFilterItem(item, value) {
if (!toggled || !value) {
return true;
}
return item.text.toLowerCase().includes(value.toLowerCase());
}
</script>
<Layout>
<p>Currently, this component does not support items as slots.</p>
<p>
<code>items</code>
must be an array of objects; mandatory fields are `id` and `text`.
</p>
<pre style="margin-top: 1rem;">
<code>{'items = Array<{ id: string; text: string; }>'}</code>
</pre>
<div style="margin-top: 2rem;">
<ToggleSmall labelText="Enable filtering" bind:toggled />
<Button
size="small"
on:click={() => {
selectedIndex = 1;
}}>
Set item to 'Option 2'
</Button>
</div>
<div style="width: 300px; margin-top: 2rem;">
<ComboBox {...$$props} id="combobox" bind:value bind:selectedIndex {items} {shouldFilterItem} />
</div>
</Layout>

View file

@ -0,0 +1,24 @@
import { withKnobs, select, boolean, text } from '@storybook/addon-knobs';
import Component from './ComboBox.Story.svelte';
export default { title: 'ComboBox', decorators: [withKnobs] };
const sizes = {
'Extra large size (xl)': 'xl',
'Regular size (lg)': '',
'Small size (sm)': 'sm'
};
export const Default = () => ({
Component,
props: {
size: select('Field size (size)', sizes, ''),
placeholder: text('Placeholder text (placeholder)', 'Filter...'),
titleText: text('Title (titleText)', 'Combobox title'),
helperText: text('Helper text (helperText)', 'Optional helper text here'),
light: boolean('Light (light)', false),
disabled: boolean('Disabled (disabled)', false),
invalid: boolean('Invalid (invalid)', false),
invalidText: text('Invalid text (invalidText)', 'A valid value is required')
}
});

View file

@ -0,0 +1,183 @@
<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 selectedIndex = -1;
export let items = [];
export let itemToString = item => item.text || item.id;
export let placeholder = '';
export let shouldFilterItem = () => true;
export let invalid = false;
export let invalidText = '';
export let translateWithId = undefined;
export let size = undefined;
export let light = false;
export let style = undefined;
import { afterUpdate } from 'svelte';
import WarningFilled16 from 'carbon-icons-svelte/lib/WarningFilled16';
import { cx } from '../../lib';
import ListBox, {
ListBoxField,
ListBoxMenu,
ListBoxMenuIcon,
ListBoxMenuItem,
ListBoxSelection
} from '../ListBox';
let inputRef = undefined;
let inputValue = undefined;
let highlightedIndex = -1;
function change(direction) {
let index = highlightedIndex + direction;
if (index < 0) {
index = items.length - 1;
} else if (index >= items.length) {
index = 0;
}
highlightedIndex = index;
}
afterUpdate(() => {
if (open) {
inputRef.focus();
} 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));
</script>
<svelte:body
on:click={({ target }) => {
if (open && inputRef && !inputRef.contains(target)) {
open = false;
}
}} />
<div class={cx('--list-box__wrapper', className)} {style}>
{#if titleText}
<label class={cx('--label', disabled && '--label--disabled')} for={id}>{titleText}</label>
{/if}
{#if helperText}
<div class={cx('--form__helper-text', disabled && '--form__helper-text--disabled')}>
{helperText}
</div>
{/if}
<ListBox
class={cx('--combo-box')}
id={comboId}
aria-label={ariaLabel}
{disabled}
{invalid}
{invalidText}
{open}
{light}
{size}>
<ListBoxField
role="button"
aria-expanded={open}
on:click={() => {
open = true;
}}
{id}
{disabled}
{translateWithId}>
<input
bind:this={inputRef}
tabindex="0"
autocomplete="off"
aria-autocomplete="list"
aria-activedescendant={highlightedId}
aria-labelledby={comboId}
aria-disabled={disabled}
aria-controls={open ? menuId : undefined}
aria-owns={open ? menuId : undefined}
class={cx('--text-input', inputValue === '' && '--text-input--empty')}
on:input={({ target }) => {
inputValue = target.value;
}}
on:keydown
on:keydown|stopPropagation={({ key }) => {
if (key === 'Enter') {
open = !open;
if (highlightedIndex > -1 && highlightedIndex !== selectedIndex) {
selectedIndex = highlightedIndex;
open = false;
}
} 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={() => {
selectedIndex = -1;
open = false;
}}
{translateWithId}
{disabled}
{open} />
{/if}
<ListBoxMenuIcon
on:click={() => {
open = !open;
}}
{translateWithId}
{open} />
</ListBoxField>
{#if open}
<ListBoxMenu aria-label={ariaLabel} {id}>
{#each filteredItems as item, i (item.id || i)}
<ListBoxMenuItem
active={selectedIndex === i}
highlighted={highlightedIndex === i || selectedIndex === i}
on:click={() => {
selectedIndex = i;
open = false;
}}
on:mouseenter={() => {
highlightedIndex = i;
}}>
{itemToString(item)}
</ListBoxMenuItem>
{/each}
</ListBoxMenu>
{/if}
</ListBox>
</div>

View file

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

View file

@ -17,6 +17,7 @@
role="listbox"
tabindex="-1"
data-invalid={invalid || undefined}
aria-label={$$props['aria-label']}
class={cx('--list-box', size && `--list-box--${size}`, type === 'inline' && '--list-box--inline', disabled && '--list-box--disabled', open && '--list-box--expanded', light && '--list-box--light', className)}
on:keydown
on:keydown={event => {

View file

@ -22,11 +22,16 @@
<div
role={ariaExpanded ? 'combobox' : role}
aria-expanded={ariaExpanded}
aria-owns={(ariaExpanded && menuId) || undefined}
aria-controls={(ariaExpanded && menuId) || undefined}
aria-label={ariaExpanded ? translateWithId('close') : translateWithId('open')}
tabindex={disabled ? '-1' : tabindex}
class={cx('--list-box__field', className)}
on:click
on:mouseover
on:mouseenter
on:mouseleave
{style}>
<slot />
</div>

View file

@ -17,6 +17,9 @@
$: description = open ? translateWithId('close') : translateWithId('open');
</script>
<div class={cx('--list-box__menu-icon', open && '--list-box__menu-icon--open', className)} {style}>
<ChevronDown16 name="chevron--down" aria-label={description} title={description} />
<div
on:click|preventDefault|stopPropagation
class={cx('--list-box__menu-icon', open && '--list-box__menu-icon--open', className)}
{style}>
<ChevronDown16 name="chevron--down" tabindex="-1" aria-label={description} title={description} />
</div>

View file

@ -1,16 +1,15 @@
<script>
let className = undefined;
export { className as class };
export let active = false;
export let highlighted = false;
export let style = undefined;
import { cx } from '../../lib';
</script>
<div
class={cx('--list-box__menu-item', active && '--list-box__menu-item--active', highlighted && '--list-box__menu-item--highlighted', className)}
{style}>
on:click
on:mouseenter
on:mouseleave
class={cx('--list-box__menu-item', active && '--list-box__menu-item--active', highlighted && '--list-box__menu-item--highlighted')}>
<div class={cx('--list-box__menu-item__option')}>
<slot />
</div>

View file

@ -27,19 +27,17 @@
tabindex={disabled ? '-1' : '0'}
title={description}
class={cx('--list-box__selection', selectionCount && '--tag--filter', selectionCount && '--list-box__selection--multi', className)}
on:click
on:click|stopPropagation={event => {
on:click|preventDefault|stopPropagation={event => {
if (!disabled) {
dispatch('clear', event);
}
}}
on:keydown
on:keydown|stopPropagation={event => {
if (!disabled && event.key === 'Enter') {
dispatch('clear', event);
}
}}
{style}>
{selectionCount}
<Close16 />
{#if selectionCount}{selectionCount}{/if}
<Close16 focusable="false" tabindex="-1" />
</div>

View file

@ -5,6 +5,7 @@ import Checkbox, { CheckboxSkeleton } from './components/Checkbox';
import ContentSwitcher, { Switch } from './components/ContentSwitcher';
import Copy from './components/Copy';
import CopyButton from './components/CopyButton';
import ComboBox from './components/ComboBox';
import ComposedModal, { ModalHeader, ModalBody, ModalFooter } from './components/ComposedModal';
import CodeSnippet, { CodeSnippetSkeleton } from './components/CodeSnippet';
import DataTableSkeleton from './components/DataTableSkeleton';
@ -98,6 +99,7 @@ export {
ClickableTile,
CodeSnippet,
CodeSnippetSkeleton,
ComboBox,
ComposedModal,
ModalHeader,
ModalBody,