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

@ -16,5 +16,5 @@
"processor": "svelte3/svelte3"
}
],
"ignorePatterns": ["*.snap"]
"ignorePatterns": ["docs", "*.snap"]
}

View file

@ -24,6 +24,7 @@ Currently, the following components are supported:
- CheckboxSkeleton
- CodeSnippet
- CodeSnippetSkeleton
- ComboBox
- ComposedModal
- ModalHeader
- ModalBody

View file

@ -70,4 +70,4 @@
}</script><style>#root[hidden],
#docs-root[hidden] {
display: none !important;
}</style></head><body><div class="sb-nopreview sb-wrapper"><div class="sb-nopreview_main"><h1 class="sb-nopreview_heading sb-heading">No Preview</h1><p>Sorry, but you either have no stories or none are selected somehow.</p><ul><li>Please check the Storybook config.</li><li>Try reloading the page.</li></ul><p>If the problem persists, check the browser console, or the terminal you've run Storybook from.</p></div></div><div class="sb-errordisplay sb-wrapper"><pre id="error-message" class="sb-heading"></pre><pre class="sb-errordisplay_code"><code id="error-stack"></code></pre></div><div id="root"></div><div id="docs-root"></div><script src="runtime~main.e9585d931aedb4990ba2.bundle.js"></script><script src="vendors~main.e9585d931aedb4990ba2.bundle.js"></script><script src="main.e9585d931aedb4990ba2.bundle.js"></script></body></html>
}</style></head><body><div class="sb-nopreview sb-wrapper"><div class="sb-nopreview_main"><h1 class="sb-nopreview_heading sb-heading">No Preview</h1><p>Sorry, but you either have no stories or none are selected somehow.</p><ul><li>Please check the Storybook config.</li><li>Try reloading the page.</li></ul><p>If the problem persists, check the browser console, or the terminal you've run Storybook from.</p></div></div><div class="sb-errordisplay sb-wrapper"><pre id="error-message" class="sb-heading"></pre><pre class="sb-errordisplay_code"><code id="error-stack"></code></pre></div><div id="root"></div><div id="docs-root"></div><script src="runtime~main.36dd655755ce765069a8.bundle.js"></script><script src="vendors~main.36dd655755ce765069a8.bundle.js"></script><script src="main.36dd655755ce765069a8.bundle.js"></script></body></html>

View file

@ -17,4 +17,4 @@
}</script><style>#root[hidden],
#docs-root[hidden] {
display: none !important;
}</style></head><body><div id="root"></div><div id="docs-root"></div><script>window['DOCS_MODE'] = false;</script><script src="runtime~main.67b3c42af12dc2b7ac9d.bundle.js"></script><script src="vendors~main.de76cb4d691ff902e1d8.bundle.js"></script><script src="main.d19aceecbf99f4b72fa7.bundle.js"></script></body></html>
}</style></head><body><div id="root"></div><div id="docs-root"></div><script>window['DOCS_MODE'] = false;</script><script src="runtime~main.67b3c42af12dc2b7ac9d.bundle.js"></script><script src="vendors~main.90220ada78163e544ba9.bundle.js"></script><script src="main.e7e683d3c4fc3d92da31.bundle.js"></script></body></html>

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
{"version":3,"file":"main.36dd655755ce765069a8.bundle.js","sources":["webpack:///main.36dd655755ce765069a8.bundle.js"],"mappings":"AAAA","sourceRoot":""}

View file

@ -1 +0,0 @@
(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{415:function(n,o,c){c(416),c(529),n.exports=c(878)},438:function(n,o){},529:function(n,o,c){"use strict";c.r(o);c(530),c(850)}},[[415,1,2]]]);

View file

@ -0,0 +1 @@
(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{0:function(n,o,c){c(417),c(529),n.exports=c(878)},1:function(n,o){},529:function(n,o,c){"use strict";c.r(o);c(530),c(850)}},[[0,1,2]]]);

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
{"version":3,"file":"main.e9585d931aedb4990ba2.bundle.js","sources":["webpack:///main.e9585d931aedb4990ba2.bundle.js"],"mappings":"AAAA","sourceRoot":""}

View file

@ -1,2 +1,2 @@
!function(modules){function webpackJsonpCallback(data){for(var moduleId,chunkId,chunkIds=data[0],moreModules=data[1],executeModules=data[2],i=0,resolves=[];i<chunkIds.length;i++)chunkId=chunkIds[i],Object.prototype.hasOwnProperty.call(installedChunks,chunkId)&&installedChunks[chunkId]&&resolves.push(installedChunks[chunkId][0]),installedChunks[chunkId]=0;for(moduleId in moreModules)Object.prototype.hasOwnProperty.call(moreModules,moduleId)&&(modules[moduleId]=moreModules[moduleId]);for(parentJsonpFunction&&parentJsonpFunction(data);resolves.length;)resolves.shift()();return deferredModules.push.apply(deferredModules,executeModules||[]),checkDeferredModules()}function checkDeferredModules(){for(var result,i=0;i<deferredModules.length;i++){for(var deferredModule=deferredModules[i],fulfilled=!0,j=1;j<deferredModule.length;j++){var depId=deferredModule[j];0!==installedChunks[depId]&&(fulfilled=!1)}fulfilled&&(deferredModules.splice(i--,1),result=__webpack_require__(__webpack_require__.s=deferredModule[0]))}return result}var installedModules={},installedChunks={1:0},deferredModules=[];function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{enumerable:!0,get:getter})},__webpack_require__.r=function(exports){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(exports,"__esModule",{value:!0})},__webpack_require__.t=function(value,mode){if(1&mode&&(value=__webpack_require__(value)),8&mode)return value;if(4&mode&&"object"==typeof value&&value&&value.__esModule)return value;var ns=Object.create(null);if(__webpack_require__.r(ns),Object.defineProperty(ns,"default",{enumerable:!0,value:value}),2&mode&&"string"!=typeof value)for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key]}.bind(null,key));return ns},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module.default}:function getModuleExports(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="";var jsonpArray=window.webpackJsonp=window.webpackJsonp||[],oldJsonpFunction=jsonpArray.push.bind(jsonpArray);jsonpArray.push=webpackJsonpCallback,jsonpArray=jsonpArray.slice();for(var i=0;i<jsonpArray.length;i++)webpackJsonpCallback(jsonpArray[i]);var parentJsonpFunction=oldJsonpFunction;checkDeferredModules()}([]);
//# sourceMappingURL=runtime~main.e9585d931aedb4990ba2.bundle.js.map
//# sourceMappingURL=runtime~main.36dd655755ce765069a8.bundle.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"runtime~main.36dd655755ce765069a8.bundle.js","sources":["webpack:///runtime~main.36dd655755ce765069a8.bundle.js"],"mappings":"AAAA","sourceRoot":""}

View file

@ -1 +0,0 @@
{"version":3,"file":"runtime~main.e9585d931aedb4990ba2.bundle.js","sources":["webpack:///runtime~main.3fc22874a0adf047f1de.bundle.js"],"mappings":"AAAA","sourceRoot":""}

View file

@ -0,0 +1 @@
{"version":3,"file":"vendors~main.36dd655755ce765069a8.bundle.js","sources":["webpack:///vendors~main.36dd655755ce765069a8.bundle.js"],"mappings":"AAAA;;;;;;;;;;;;;;AAy8PA;;;;;AA6gYA;;AAu8BA;;;;;;;;;;;;;;AAmBA;;;;;AAquPA;;;;;AAkkEA;;;;;;;;;AAukBA;;;AA8odA;;;;;;;;AAg/BA;;;;;;;;AAqEA;;;;;;;;AAkTA;;;;;;;AAyrDA;;;;;;;AAy7CA;;;;;;;AAgdA;;;;;;;AAfA","sourceRoot":""}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
{"version":3,"file":"vendors~main.e9585d931aedb4990ba2.bundle.js","sources":["webpack:///vendors~main.e9585d931aedb4990ba2.bundle.js"],"mappings":"AAAA;;;;;;;;;;;;;;AAmmPA;;;;;AAq7XA;;AAu8BA;;;;;;;;;;;;;;AAmBA;;;;;AA68NA;;;;;AAkkEA;;;;;;;;;AAukBA;;;AA8odA;;;;;;;;AAg/BA;;;;;;;;AAqEA;;;;;;;;AAkTA;;;;;;;AAyrDA;;;;;;;AAy7CA;;;;;;;AA+cA;;;;;;;AAfA","sourceRoot":""}

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,