feat(auto-complete): add forwardRef for input element (#542)

* feat(auto-complete): add forwardRef for input element

* test(auto-complete): add testcase to ensure ref is available

* docs(auto-complete): append props for ref
This commit is contained in:
witt
2021-05-24 11:23:06 +08:00
committed by unix
parent 888ad5d3ef
commit 77c92daf9c
6 changed files with 217 additions and 188 deletions

View File

@@ -1,7 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`AutoComplete should render correctly 1`] = `
<AutoComplete
<ForwardRef
className=""
clearable={false}
disableFreeSolo={false}

View File

@@ -378,16 +378,16 @@ initialize {
"children": Array [
Node {
"data": "
.auto-complete {
width: max-content;
}
.auto-complete {
width: max-content;
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
"next": null,
"parent": [Circular],
"prev": null,
@@ -418,16 +418,16 @@ initialize {
"children": Array [
Node {
"data": "
.auto-complete {
width: max-content;
}
.auto-complete {
width: max-content;
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
"next": null,
"parent": [Circular],
"prev": null,
@@ -1229,16 +1229,16 @@ initialize {
"children": Array [
Node {
"data": "
.auto-complete {
width: max-content;
}
.auto-complete {
width: max-content;
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
"next": null,
"parent": [Circular],
"prev": null,
@@ -1269,16 +1269,16 @@ initialize {
"children": Array [
Node {
"data": "
.auto-complete {
width: max-content;
}
.auto-complete {
width: max-content;
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
",
"next": null,
"parent": [Circular],
"prev": null,

View File

@@ -56,4 +56,11 @@ describe('AutoComplete', () => {
expect(wrapper.prop('width')).toEqual('200px')
})
it('should forward ref by default', () => {
const ref = React.createRef<HTMLInputElement>()
const wrapper = mount(<AutoComplete ref={ref} />)
expect(ref.current).not.toBeNull()
expect(() => wrapper.unmount()).not.toThrow()
})
})

View File

@@ -1,4 +1,13 @@
import React, { CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import React, {
CSSProperties,
PropsWithoutRef,
RefAttributes,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react'
import Input from '../input'
import AutoCompleteItem, { AutoCompleteItemProps } from './auto-complete-item'
import AutoCompleteDropdown from './auto-complete-dropdown'
@@ -71,160 +80,171 @@ const getSearchIcon = (searching?: boolean) => {
return searching ? <Loading size="medium" /> : <span />
}
const AutoComplete: React.FC<React.PropsWithChildren<AutoCompleteProps>> = ({
options,
initialValue: customInitialValue,
onSelect,
onSearch,
onChange,
searching,
children,
size,
status,
value,
width,
clearable,
disabled,
dropdownClassName,
dropdownStyle,
disableMatchWidth,
disableFreeSolo,
...props
}) => {
const ref = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const resetTimer = useRef<number>()
const [state, setState, stateRef] = useCurrentState<string>(customInitialValue)
const [selectVal, setSelectVal] = 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 as Array<AutoCompleteOption>)
}, [searching, options])
const showClearIcon = useMemo(() => clearable && searching === undefined, [
clearable,
searching,
])
const updateValue = (val: string) => {
if (disabled) return
setSelectVal(val)
onSelect && onSelect(val)
setState(val)
inputRef.current && inputRef.current.focus()
}
const updateVisible = (next: boolean) => setVisible(next)
const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setVisible(true)
onSearch && onSearch(event.target.value)
setState(event.target.value)
}
const resetInputValue = () => {
if (!disableFreeSolo) return
if (!state || state === '') return
if (state !== selectVal) {
setState(selectVal)
}
}
useEffect(() => {
onChange && onChange(state)
}, [state])
useEffect(() => {
if (value === undefined) return
setState(value)
}, [value])
const initialValue = useMemo<AutoCompleteConfig>(
() => ({
ref,
const AutoComplete = React.forwardRef<
HTMLInputElement,
React.PropsWithChildren<AutoCompleteProps>
>(
(
{
options,
initialValue: customInitialValue,
onSelect,
onSearch,
onChange,
searching,
children,
size,
value: state,
updateValue,
visible,
updateVisible,
}),
[state, visible, size],
)
status,
value,
width,
clearable,
disabled,
dropdownClassName,
dropdownStyle,
disableMatchWidth,
disableFreeSolo,
...props
},
userRef: React.Ref<HTMLInputElement | null>,
) => {
const ref = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const resetTimer = useRef<number>()
const [state, setState, stateRef] = useCurrentState<string>(customInitialValue)
const [selectVal, setSelectVal] = useState<string>(customInitialValue)
const [visible, setVisible] = useState<boolean>(false)
useImperativeHandle(userRef, () => inputRef.current)
const toggleFocusHandler = (next: boolean) => {
clearTimeout(resetTimer.current)
setVisible(next)
if (next) {
onSearch && onSearch(stateRef.current)
} else {
resetTimer.current = window.setTimeout(() => {
resetInputValue()
clearTimeout(resetTimer.current)
}, 100)
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 as Array<AutoCompleteOption>)
}, [searching, options])
const showClearIcon = useMemo(() => clearable && searching === undefined, [
clearable,
searching,
])
const updateValue = (val: string) => {
if (disabled) return
setSelectVal(val)
onSelect && onSelect(val)
setState(val)
inputRef.current && inputRef.current.focus()
}
const updateVisible = (next: boolean) => setVisible(next)
const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setVisible(true)
onSearch && onSearch(event.target.value)
setState(event.target.value)
}
const resetInputValue = () => {
if (!disableFreeSolo) return
if (!state || state === '') return
if (state !== selectVal) {
setState(selectVal)
}
}
}
const inputProps = {
...props,
width,
disabled,
value: state,
}
useEffect(() => {
onChange && onChange(state)
}, [state])
useEffect(() => {
if (value === undefined) return
setState(value)
}, [value])
return (
<AutoCompleteContext.Provider value={initialValue}>
<div ref={ref} className="auto-complete">
<Input
ref={inputRef}
size={size}
status={status}
onChange={onInputChange}
onFocus={() => toggleFocusHandler(true)}
onBlur={() => toggleFocusHandler(false)}
clearable={showClearIcon}
iconRight={getSearchIcon(searching)}
{...inputProps}
/>
<AutoCompleteDropdown
visible={visible}
disableMatchWidth={disableMatchWidth}
className={dropdownClassName}
dropdownStyle={dropdownStyle}>
{autoCompleteItems}
</AutoCompleteDropdown>
const initialValue = useMemo<AutoCompleteConfig>(
() => ({
ref,
size,
value: state,
updateValue,
visible,
updateVisible,
}),
[state, visible, size],
)
<style jsx>{`
.auto-complete {
width: ${width || 'max-content'};
}
const toggleFocusHandler = (next: boolean) => {
clearTimeout(resetTimer.current)
setVisible(next)
if (next) {
onSearch && onSearch(stateRef.current)
} else {
resetTimer.current = window.setTimeout(() => {
resetInputValue()
clearTimeout(resetTimer.current)
}, 100)
}
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
`}</style>
</div>
</AutoCompleteContext.Provider>
)
}
const inputProps = {
...props,
width,
disabled,
value: state,
}
type AutoCompleteComponent<P = {}> = React.FC<P> & {
return (
<AutoCompleteContext.Provider value={initialValue}>
<div ref={ref} className="auto-complete">
<Input
ref={inputRef}
size={size}
status={status}
onChange={onInputChange}
onFocus={() => toggleFocusHandler(true)}
onBlur={() => toggleFocusHandler(false)}
clearable={showClearIcon}
iconRight={getSearchIcon(searching)}
{...inputProps}
/>
<AutoCompleteDropdown
visible={visible}
disableMatchWidth={disableMatchWidth}
className={dropdownClassName}
dropdownStyle={dropdownStyle}>
{autoCompleteItems}
</AutoCompleteDropdown>
<style jsx>{`
.auto-complete {
width: ${width || 'max-content'};
}
.auto-complete :global(.loading) {
left: -3px;
right: -3px;
width: max-content;
}
`}</style>
</div>
</AutoCompleteContext.Provider>
)
},
)
type AutoCompleteComponent<T, P = {}> = React.ForwardRefExoticComponent<
PropsWithoutRef<P> & RefAttributes<T>
> & {
Item: typeof AutoCompleteItem
Option: typeof AutoCompleteItem
Searching: typeof AutoCompleteSearching
@@ -234,6 +254,6 @@ type AutoCompleteComponent<P = {}> = React.FC<P> & {
type ComponentProps = Partial<typeof defaultProps> &
Omit<Props, keyof typeof defaultProps> &
NativeAttrs
;(AutoComplete as AutoCompleteComponent<ComponentProps>).defaultProps = defaultProps
AutoComplete.defaultProps = defaultProps
export default AutoComplete as AutoCompleteComponent<ComponentProps>
export default AutoComplete as AutoCompleteComponent<HTMLInputElement, ComponentProps>

View File

@@ -1,5 +1,5 @@
import { Layout, Playground, Attributes } from 'lib/components'
import { AutoComplete, Spacer, Badge, Grid, Text } from 'components'
import { AutoComplete, Spacer, Badge, Grid, Text, Code } from 'components'
import { useState, useRef, useEffect } from 'react'
export const meta = {
@@ -286,6 +286,7 @@ AutoComplete control of input field.
| **dropdownStyle** | style of dropdown box | `object` | - | - |
| **disableMatchWidth** | disable Option from follow parent width | `boolean` | - | `false` |
| **disableFreeSolo** | only values can be changed through Select | `boolean` | - | `false` |
| **ref** | forwardRef | <Code>Ref<HTMLInputElement &#124; null></Code> | - | - |
| ... | native props | `InputHTMLAttributes` | `'id', 'className', ...` | - |
<Attributes.Title alias="AutoComplete.Option">AutoComplete.Item</Attributes.Title>

View File

@@ -1,5 +1,5 @@
import { Layout, Playground, Attributes } from 'lib/components'
import { AutoComplete, Spacer, Badge, Text, Grid } from 'components'
import { AutoComplete, Spacer, Badge, Text, Grid, Code } from 'components'
import { useState, useRef, useEffect } from 'react'
export const meta = {
@@ -287,6 +287,7 @@ export const meta = {
| **dropdownStyle** | 自定义下拉框的样式 | `object` | - | - |
| **disableMatchWidth** | 禁止 Option 跟随父元素的宽度 | `boolean` | - | `false` |
| **disableFreeSolo** | 只允许通过 Select 事件更改值 (禁止 Input 输入随意值) | `boolean` | - | `false` |
| **ref** | 转发的原生输入框 Ref | <Code>Ref<HTMLInputElement &#124; null></Code> | - | - |
| ... | 原生属性 | `InputHTMLAttributes` | `'id', 'className', ...` | - |
<Attributes.Title alias="AutoComplete.Option">AutoComplete.Item</Attributes.Title>