feat(auto-complete): add component

This commit is contained in:
unix
2020-03-28 07:02:20 +08:00
parent 2930287d17
commit a52e400355
10 changed files with 543 additions and 155 deletions

View File

@@ -1,22 +1,20 @@
import React, { MutableRefObject } from 'react'
import { NormalSizes } from '../utils/prop-types'
export interface SelectConfig {
export interface AutoCompleteConfig {
value?: string
updateValue?: Function
visible?: boolean
updateVisible?: Function
size?: NormalSizes
disableAll?: boolean
ref?: MutableRefObject<HTMLElement | null>
}
const defaultContext = {
visible: false,
size: 'medium' as NormalSizes,
disableAll: false,
}
export const SelectContext = React.createContext<SelectConfig>(defaultContext)
export const AutoCompleteContext = React.createContext<AutoCompleteConfig>(defaultContext)
export const useSelectContext = (): SelectConfig => React.useContext<SelectConfig>(SelectContext)
export const useAutoCompleteContext = (): AutoCompleteConfig => React.useContext<AutoCompleteConfig>(AutoCompleteContext)

View File

@@ -1,11 +1,37 @@
import React from 'react'
import useTheme from '../styles/use-theme'
import { useAutoCompleteContext } from './auto-complete-context'
import Dropdown from '../shared/dropdown'
const AutoComplete = () => {
interface Props {
visible: boolean
}
const AutoCompleteDropdown: React.FC<React.PropsWithChildren<Props>> = ({
children, visible
}) => {
const theme = useTheme()
const { ref } = useAutoCompleteContext()
const clickHandler = (event: React.MouseEvent<HTMLDivElement>) => {
event.preventDefault()
event.stopPropagation()
event.nativeEvent.stopImmediatePropagation()
}
return (
<div>
</div>
<Dropdown parent={ref} visible={visible}>
<div className="auto-dropdown-dropdown" onClick={clickHandler}>
{children}
<style jsx>{`
.auto-dropdown-dropdown {
border-radius: ${theme.layout.radius};
box-shadow: ${theme.expressiveness.shadowLarge};
background-color: ${theme.palette.background};
}
`}</style>
</div>
</Dropdown>
)
}
export default AutoComplete
export default AutoCompleteDropdown

View File

@@ -1,6 +1,6 @@
import React from 'react'
import withDefaults from '../utils/with-defaults'
import useTheme from '../styles/use-theme'
import AutoCompleteSearch from './auto-complete-searching'
interface Props {
className?: string
@@ -10,36 +10,13 @@ const defaultProps = {
className: '',
}
export type AutoCompleteSearchProps = Props & typeof defaultProps & React.HTMLAttributes<any>
export type AutoCompleteEmptyProps = Props & typeof defaultProps & React.HTMLAttributes<any>
const AutoCompleteSearch: React.FC<React.PropsWithChildren<AutoCompleteSearchProps>> = ({
const AutoCompleteEmpty: React.FC<React.PropsWithChildren<AutoCompleteEmptyProps>> = ({
children, className,
}) => {
const theme = useTheme()
return (
<div className={className}>
{children}
<style jsx>{`
div {
display: flex;
justify-content: center;
text-align: center;
align-items: center;
font-weight: normal;
white-space: pre;
font-size: .875rem;
padding: ${theme.layout.gapHalf};
line-height: 1;
background-color: ${theme.palette.background};
color: ${theme.palette.accents_5};
user-select: none;
border: 0;
border-radius: ${theme.layout.radius};
}
`}</style>
</div>
)
return <AutoCompleteSearch className={className}>{children}</AutoCompleteSearch>
}
export default withDefaults(AutoCompleteSearch, defaultProps)
export default withDefaults(AutoCompleteEmpty, defaultProps)

View File

@@ -1,11 +1,84 @@
import React from 'react'
import React, { useMemo } from 'react'
import withDefaults from '../utils/with-defaults'
import useTheme from '../styles/use-theme'
import { useAutoCompleteContext } from './auto-complete-context'
import { NormalSizes } from 'components/utils/prop-types'
const AutoComplete = () => {
interface Props {
value: string
disabled?: boolean
}
const defaultProps = {
disabled: false,
}
export type AutoCompleteItemProps = Props & typeof defaultProps & React.HTMLAttributes<any>
const getSizes = (size?: NormalSizes) => {
const fontSizes: { [key in NormalSizes]: string } = {
mini: '.7rem',
small: '.75rem',
medium: '.875rem',
large: '1rem',
}
return size ? fontSizes[size] : fontSizes.medium
}
const AutoCompleteItem: React.FC<React.PropsWithChildren<AutoCompleteItemProps>> = ({
value: identValue, children, disabled,
}) => {
const theme = useTheme()
const { value, updateValue, size } = useAutoCompleteContext()
const selectHandler = () => {
updateValue && updateValue(identValue)
}
const isActive = useMemo(() => value === identValue, [identValue, value])
const fontSize = useMemo(() => getSizes(size), [size])
return (
<div>
<div className={`item ${isActive ? 'active' : ''}`} onClick={selectHandler}>
{children}
<style jsx>{`
.item {
display: flex;
justify-content: flex-start;
align-items: center;
font-weight: normal;
white-space: pre;
font-size: ${fontSize};
padding: ${theme.layout.gapHalf};
line-height: 1.2;
background-color: ${theme.palette.background};
color: ${theme.palette.foreground};
user-select: none;
border: 0;
cursor: ${disabled ? 'not-allowed' : 'pointer'};
transition: background 0.2s ease 0s, border-color 0.2s ease 0s;
}
.item:first-of-type {
border-top-left-radius: ${theme.layout.radius};
border-top-right-radius: ${theme.layout.radius};
}
.item:last-of-type {
border-bottom-left-radius: ${theme.layout.radius};
border-bottom-right-radius: ${theme.layout.radius};
}
.item:hover {
background-color: ${theme.palette.accents_1};
}
.item.active {
background-color: ${theme.palette.accents_1};
color: ${theme.palette.success};
}
`}</style>
</div>
)
}
export default AutoComplete
export default withDefaults(AutoCompleteItem, defaultProps)

View File

@@ -1,37 +1,30 @@
import React, { useMemo } from 'react'
import React from 'react'
import withDefaults from '../utils/with-defaults'
import useTheme from '../styles/use-theme'
import { useAutoCompleteContext } from './auto-complete-context'
interface Props {
value: string
disabled?: boolean
className?: string
}
const defaultProps = {
disabled: false,
className: '',
}
export type AutoCompleteItemProps = Props & typeof defaultProps & React.HTMLAttributes<any>
export type AutoCompleteSearchProps = Props & typeof defaultProps & React.HTMLAttributes<any>
const AutoCompleteItem: React.FC<React.PropsWithChildren<AutoCompleteItemProps>> = ({
value: identValue, children, disabled,
const AutoCompleteSearch: React.FC<React.PropsWithChildren<AutoCompleteSearchProps>> = ({
children, className,
}) => {
const theme = useTheme()
const { value, updateValue } = useAutoCompleteContext()
const selectHandler = () => {
updateValue && updateValue(identValue)
}
const isActive = useMemo(() => value === identValue, [identValue, value])
return (
<div className={`item ${isActive ? 'active' : ''}`} onClick={selectHandler}>
<div className={className}>
{children}
<style jsx>{`
.item {
div {
display: flex;
justify-content: flex-start;
justify-content: center;
text-align: center;
align-items: center;
font-weight: normal;
white-space: pre;
@@ -39,34 +32,14 @@ const AutoCompleteItem: React.FC<React.PropsWithChildren<AutoCompleteItemProps>>
padding: ${theme.layout.gapHalf};
line-height: 1;
background-color: ${theme.palette.background};
color: ${theme.palette.foreground};
color: ${theme.palette.accents_5};
user-select: none;
border: 0;
cursor: ${disabled ? 'not-allowed' : 'pointer'};
transition: background 0.2s ease 0s, border-color 0.2s ease 0s;
}
.item:first-of-type {
border-top-left-radius: ${theme.layout.radius};
border-top-right-radius: ${theme.layout.radius};
}
.item:last-of-type {
border-bottom-left-radius: ${theme.layout.radius};
border-bottom-right-radius: ${theme.layout.radius};
}
.item:hover {
background-color: ${theme.palette.accents_1};
}
.item.active {
background-color: ${theme.palette.accents_1};
color: ${theme.palette.success};
border-radius: ${theme.layout.radius};
}
`}</style>
</div>
)
}
export default withDefaults(AutoCompleteItem, defaultProps)
export default withDefaults(AutoCompleteSearch, defaultProps)

View File

@@ -0,0 +1,166 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import Input from '../input'
import AutoCompleteItem from './auto-complete-item'
import AutoCompleteDropdown from './auto-complete-dropdown'
import AutoCompleteSearching from './auto-complete-searching'
import AutoCompleteEmpty from './auto-complete-empty'
import { AutoCompleteContext, AutoCompleteConfig } from './auto-complete-context'
import { NormalSizes, NormalTypes } from '../utils/prop-types'
import ButtonLoading from '../button/button.loading'
import { pickChild } from 'components/utils/collections'
export type AutoCompleteOption = {
label: string
value: string
}
export type AutoCompleteOptions = Array<AutoCompleteOption | typeof AutoCompleteItem>
interface Props {
options: AutoCompleteOptions
size?: NormalSizes
status?: NormalTypes
initialValue?: string
value?: string
width?: string
onChange?: (value: string) => void
onSearch?: (value: string) => void
onSelect?: (value: string) => void
searching?: boolean | undefined
clearable?: boolean
className?: string
}
const defaultProps = {
options: [],
initialValue: '',
disabled: false,
clearable: false,
size: 'medium' as NormalSizes,
className: '',
}
export type AutoCompleteProps = Props & typeof defaultProps & React.InputHTMLAttributes<any>
const childrenToOptionsNode = (options: AutoCompleteOptions) => {
if (options.length === 0) return null
return options.map((item, index) => {
const key = `auto-complete-item-${index}`
if (React.isValidElement(item)) return React.cloneElement(item, { key })
const validItem = item as AutoCompleteOption
return (
<AutoCompleteItem key={key}
value={validItem.value}>
{validItem.label}
</AutoCompleteItem>
)
})
}
// When the search is not set, the "clearable" icon can be displayed in the original location.
// When the search is seted, at least one element should exist to avoid re-render.
const getSearchIcon = (searching?: boolean) => {
if (searching === undefined) return null
return searching ? <ButtonLoading bgColor="transparent" /> : <span />
}
const AutoComplete: React.FC<React.PropsWithChildren<AutoCompleteProps>> = ({
options, initialValue: customInitialValue, onSelect, onSearch, onChange,
searching, children, size, status, value, width, clearable, ...props
}) => {
const ref = useRef<HTMLDivElement>(null)
const [state, setState] = useState<string>(customInitialValue)
const [visible, setVisible] = useState<boolean>(false)
const [, searchChild] = pickChild(children, AutoCompleteSearching)
const [, emptyChild] = pickChild(children, AutoCompleteEmpty)
const autoCompleteItems = useMemo(() => {
const hasSearchChild = searchChild && React.Children.count(searchChild) > 0
const hasEmptyChild = emptyChild && React.Children.count(emptyChild) > 0
if (searching) {
return hasSearchChild ? searchChild : <AutoCompleteSearching>Searching...</AutoCompleteSearching>
}
if (options.length === 0) {
if (state === '') return null
return hasEmptyChild ? emptyChild : <AutoCompleteEmpty>No Options</AutoCompleteEmpty>
}
return childrenToOptionsNode(options)
}, [searching, options])
const showClearIcon = useMemo(
() => clearable && searching === undefined,
[clearable, searching],
)
const updateValue = (val: string) => {
onSelect && onSelect(val)
setState(val)
}
const updateVisible = (next: boolean) => setVisible(next)
const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
onSearch && onSearch(event.target.value)
setState(event.target.value)
}
useEffect(() => onChange && onChange(state), [state])
useEffect(() => {
if (value === undefined) return
setState(value)
}, [value])
const initialValue = useMemo<AutoCompleteConfig>(() => ({
ref, size,
value: state,
updateValue,
visible,
updateVisible,
}), [state, visible, size])
const toggleFocusHandler = (next: boolean) => {
setVisible(next)
if (next) {
onSearch && onSearch(state)
}
}
const inputProps = {
...props,
width,
value: state,
}
return (
<AutoCompleteContext.Provider value={initialValue}>
<div ref={ref} className="auto-complete">
<Input size={size} status={status}
onChange={onInputChange}
onFocus={() => toggleFocusHandler(true)}
onBlur={() => toggleFocusHandler(false)}
clearable={showClearIcon}
iconRight={getSearchIcon(searching)}
{...inputProps} />
<AutoCompleteDropdown visible={visible}>
{autoCompleteItems}
</AutoCompleteDropdown>
<style jsx>{`
.auto-complete {
width: ${width || 'max-content'};
}
`}</style>
</div>
</AutoCompleteContext.Provider>
)
}
type AutoCompleteComponent<P = {}> = React.FC<P> & {
Item: typeof AutoCompleteItem
Option: typeof AutoCompleteItem
Searching: typeof AutoCompleteSearching
Empty: typeof AutoCompleteEmpty
}
type ComponentProps = Partial<typeof defaultProps> & Omit<Props, keyof typeof defaultProps>
(AutoComplete as AutoCompleteComponent<ComponentProps>).defaultProps = defaultProps
export default AutoComplete as AutoCompleteComponent<ComponentProps>

View File

@@ -0,0 +1,11 @@
import AutoComplete from './auto-complete'
import AutoCompleteItem from './auto-complete-item'
import AutoCompleteSearching from './auto-complete-searching'
import AutoCompleteEmpty from './auto-complete-empty'
AutoComplete.Item = AutoCompleteItem
AutoComplete.Option = AutoCompleteItem
AutoComplete.Searching = AutoCompleteSearching
AutoComplete.Empty = AutoCompleteEmpty
export default AutoComplete

View File

@@ -1,7 +1,13 @@
import React from 'react'
import useTheme from '../styles/use-theme'
const ButtonLoading: React.FC<{}> = React.memo(() => {
interface Props {
bgColor?: string
}
const ButtonLoading: React.FC<Props> = React.memo(({
bgColor,
}) => {
const theme = useTheme()
return (
<span className="loading">
@@ -21,7 +27,7 @@ const ButtonLoading: React.FC<{}> = React.memo(() => {
display: flex;
justify-content: center;
align-items: center;
background-color: ${theme.palette.accents_1};
background-color: ${bgColor || theme.palette.accents_1};
}
i {

View File

@@ -37,3 +37,4 @@ export { default as Tabs } from './tabs'
export { default as Progress } from './progress'
export { default as Tree } from './file-tree'
export { default as Badge } from './badge'
export { default as AutoComplete } from './auto-complete'

View File

@@ -1,99 +1,256 @@
import { Layout, Playground, Attributes } from 'lib/components'
import { Avatar, Spacer } from 'components'
import { AutoComplete, Spacer, Badge, Row } from 'components'
import { useState, useRef, useEffect } from 'react'
export const meta = {
title: 'avatar',
description: 'avatar',
title: 'AutoComplete',
description: 'auto-complete',
}
## Avatar
Avatars represent a user or a team. Stacked avatars represent a group of people.
## Auto Complete
<Playground
desc="The `Avatar` contains circle and square."
scope={{ Avatar, Spacer }}
scope={{ AutoComplete }}
code={`
() => {
const url = 'https://zeit.co/api/www/avatar/?u=evilrabbit&s=160'
const options = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
return <AutoComplete placeholder="Enter here" options={options} />
}
`} />
<Playground
title="disabled"
scope={{ AutoComplete }}
code={`
() => {
const options = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
return <AutoComplete disabled options={options} initialValue="London" />
}
`} />
<Playground
title="search"
scope={{ AutoComplete, useState }}
code={`
() => {
const allOptions = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
const [options, setOptions] = useState()
const searchHandler = (currentValue) => {
if (!currentValue) return setOptions([])
const relatedOptions = allOptions.filter(item => item.value.includes(currentValue))
setOptions(relatedOptions)
}
return <AutoComplete options={options} placeholder="Enter here" onSearch={searchHandler} />
}
`} />
<Playground
title="Waiting in search"
scope={{ AutoComplete, useState, useEffect, useRef }}
code={`
() => {
const allOptions = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
const [options, setOptions] = useState()
const [searching, setSearching] = useState(false)
const timer = useRef()
// triggered every time input
const searchHandler = (currentValue) => {
if (!currentValue) return setOptions([])
setSearching(true)
const relatedOptions = allOptions.filter(item => item.value.includes(currentValue))
// this is mock async request
// you can get data in any way
timer.current && clearTimeout(timer.current)
timer.current = setTimeout(() => {
setOptions(relatedOptions)
setSearching(false)
clearTimeout(timer.current)
}, 1000)
}
return (
<AutoComplete searching={searching}
options={options}
placeholder="Enter here"
onSearch={searchHandler} />
)
}
`} />
<Playground
title="custom searching text"
scope={{ AutoComplete }}
code={`
<AutoComplete searching placeholder="Enter here" width="100%">
<AutoComplete.Searching>
<span style={{ color: 'red' }}>waiting...</span>
</AutoComplete.Searching>
</AutoComplete>
`} />
<Playground
title="custom no options"
scope={{ AutoComplete, useState }}
code={`
() => {
const allOptions = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
const [options, setOptions] = useState()
const searchHandler = (currentValue) => {
if (!currentValue) return setOptions([])
const relatedOptions = allOptions.filter(item => item.value.includes(currentValue))
setOptions(relatedOptions)
}
return (
<AutoComplete placeholder="Enter here" width="100%" options={options} onSearch={searchHandler}>
<AutoComplete.Empty>
<span>no options...</span>
</AutoComplete.Empty>
</AutoComplete>
)
}
`} />
<Playground
title="custom option"
scope={{ AutoComplete, useState, Spacer, Badge, Row }}
code={`
() => {
const makeOption = (label, value) => (
<AutoComplete.Option value={value}>
<div style={{ width: '100%' }}>
<div style={{ display: 'flex-inline', width: '100%', alignItems: 'space-between' }}>
<h4>Recent search results </h4>
<Badge type="success" style={{ float: 'right' }}>Recommended</Badge>
</div>
<Spacer y={.5} />
<span>{label}</span>
</div>
</AutoComplete.Option>
)
const allOptions = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
const [options, setOptions] = useState()
const searchHandler = (currentValue) => {
if (!currentValue) return setOptions([])
const relatedOptions = allOptions.filter(item => item.value.includes(currentValue))
const customOptions = relatedOptions.map(({ label, value }) => makeOption(label, value))
setOptions(customOptions)
}
return (
<AutoComplete placeholder="Enter here"
width="100%"
options={options}
onSearch={searchHandler} />
)
}
`} />
<Playground
title="size"
scope={{ AutoComplete, Spacer }}
code={`
() => {
const options = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
return (
<>
<Avatar src={url} />
<Avatar src={url} />
<Avatar src={url} />
<Avatar src={url} />
<AutoComplete placeholder="Mini" size="mini" options={options} />
<Spacer y={.5} />
<Avatar src={url} isSquare />
<Avatar src={url} isSquare />
<Avatar src={url} isSquare />
<Avatar src={url} isSquare />
</>
)
}
`} />
<Playground
title="Size"
desc="You can specify different sizes of `Avatar`."
scope={{ Avatar }}
code={`
() => {
const url = 'https://zeit.co/api/www/avatar/?u=evilrabbit&s=160'
return (
<>
<Avatar src={url} size="mini" />
<Avatar src={url} size="small" />
<Avatar src={url} size="medium" />
<Avatar src={url} size="large" />
<AutoComplete placeholder="Small" size="small" options={options} />
<Spacer y={.5} />
<AutoComplete placeholder="Medium" size="medium" options={options} />
<Spacer y={.5} />
<AutoComplete placeholder="Large" size="large" options={options} />
</>
)
}
`} />
<Playground
title="Text"
scope={{ Avatar }}
code={`
<>
<Avatar text="W" />
<Avatar text="A" />
<Avatar text="W" />
<Avatar text="Joe" />
</>
`} />
<Playground
title="Stacked"
desc="Multiple avatars can overlap and stack together."
scope={{ Avatar }}
title="clearable"
scope={{ AutoComplete }}
code={`
() => {
const url = 'https://zeit.co/api/www/avatar/?u=evilrabbit&s=160'
return (
<>
<Avatar src={url} stacked />
<Avatar src={url} stacked />
<Avatar src={url} stacked />
<Avatar src={url} stacked />
</>
)
const options = [
{ label: 'London', value: 'london' },
{ label: 'Sydney', value: 'sydney' },
{ label: 'Shanghai', value: 'shanghai' },
]
return <AutoComplete placeholder="Enter here" clearable options={options} />
}
`} />
<Attributes edit="/pages/docs/components/avatar.mdx">
<Attributes.Title>Avatar.Props</Attributes.Title>
<Attributes edit="/pages/docs/components/auto-complete.mdx">
<Attributes.Title>AutoComplete.Props</Attributes.Title>
| Attribute | Description | Type | Accepted values | Default
| ---------- | ---------- | ---- | -------------- | ------ |
| **src** | image src | `string` | - | - |
| **stacked** | stacked display group | `boolean` | - | `false` |
| **text** | display text when image is missing | `string` | - | - |
| **size** | avatar size | `string` / `number` | `'mini', 'small', 'medium', 'large', number` | `medium` |
| **isSquare** | avatar shape | `boolean` | - | `false` |
| ... | native props | `ImgHTMLAttributes` | `'alt', 'crossOrigin', 'className', ...` | - |
| **options** | options of input | `AutoCompleteOptions` | - | - |
| **status** | input type | `NormalTypes` | `'default', 'secondary', 'success', 'warning', 'error'` | `default` |
| **size** | input size | `NormalSizes` | `'mini', 'small', 'medium', 'large'` | `medium` |
| **initialValue** | initial value | `string` | - | - |
| **value** | current value | `string` | - | - |
| **width** | container width | `string` | - | - |
| **clearable** | show clear icon | `boolean` | - | `false` |
| **searching** | show loading icon for search | `boolean` | - | `false` |
| **onChange** | value of input is changed | `(value: string) => void` | - | - |
| **onSearch** | called when searching items | `(value: string) => void` | - | - |
| **onSelect** | called when a option is selected | `(value: string) => void` | - | - |
| ... | native props | `InputHTMLAttributes` | `'autoComplete', 'type', 'className', ...` | - |
<Attributes.Title alias="AutoComplete.Option">AutoComplete.Item</Attributes.Title>
| Attribute | Description | Type | Accepted values | Default
| ---------- | ---------- | ---- | -------------- | ------ |
| **value** | a unique ident value | `string` | - | - |
| ... | native props | `HTMLAttributes` | `'id', 'className', ...` | - |
<Attributes.Title>AutoComplete.Searching</Attributes.Title>
| Attribute | Description | Type | Accepted values | Default
| ---------- | ---------- | ---- | -------------- | ------ |
| ... | native props | `HTMLAttributes` | `'id', 'className', ...` | - |
<Attributes.Title>AutoComplete.Empty</Attributes.Title>
| Attribute | Description | Type | Accepted values | Default
| ---------- | ---------- | ---- | -------------- | ------ |
| ... | native props | `HTMLAttributes` | `'id', 'className', ...` | - |
<Attributes.Title>type AutoCompleteOptions</Attributes.Title>
```ts
Array<{
label: string
value: string
} | AutoComplete.Item>
```
</Attributes>