-
Notifications
You must be signed in to change notification settings - Fork 661
Expand file tree
/
Copy pathTextInput.tsx
More file actions
325 lines (303 loc) · 11.4 KB
/
TextInput.tsx
File metadata and controls
325 lines (303 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import type {MouseEventHandler} from 'react'
import React, {useCallback, useState, useId, useEffect, useRef} from 'react'
import {isValidElementType} from 'react-is'
import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic'
import {clsx} from 'clsx'
import {AlertFillIcon} from '@primer/octicons-react'
import classes from './TextInput.module.css'
import TextInputInnerVisualSlot from '../internal/components/TextInputInnerVisualSlot'
import type {Merge} from '../utils/types'
import type {StyledWrapperProps} from '../internal/components/TextInputWrapper'
import TextInputWrapper from '../internal/components/TextInputWrapper'
import TextInputAction from '../internal/components/TextInputInnerAction'
import UnstyledTextInput from '../internal/components/UnstyledTextInput'
import VisuallyHidden from '../_VisuallyHidden'
import {CharacterCounter} from '../utils/character-counter'
import Text from '../Text'
import {useMergedRefs} from '../hooks'
export type TextInputNonPassthroughProps = {
/** @deprecated Use `leadingVisual` or `trailingVisual` prop instead */
icon?: React.ElementType
/** Whether the to show a loading indicator in the input */
loading?: boolean
/**
* Which position to render the loading indicator
* 'auto' (default): at the end of the input, unless a `leadingVisual` is passed. Then, it will render at the beginning
* 'leading': at the beginning of the input
* 'trailing': at the end of the input
**/
loaderPosition?: 'auto' | 'leading' | 'trailing'
/** Text for screen readers to convey the loading state */
loaderText?: string
/**
* A visual that renders inside the input before the typing area
*/
leadingVisual?: React.ElementType | React.ReactNode
/**
* A visual that renders inside the input after the typing area
*/
trailingVisual?: React.ElementType | React.ReactNode
/**
* A visual that renders inside the input after the typing area
*/
trailingAction?: React.ReactElement<React.HTMLProps<HTMLButtonElement>>
/**
* Optional character limit for the input. If provided, a character counter will be displayed below the input.
* When the limit is exceeded, validation styling will be applied.
*/
characterLimit?: number
} & Partial<
Pick<
StyledWrapperProps,
| 'block'
| 'contrast'
| 'disabled'
| 'monospace'
| 'width'
| 'maxWidth'
| 'minWidth'
| 'variant'
| 'size'
| 'validationStatus'
>
>
export type TextInputProps = Merge<React.ComponentPropsWithoutRef<'input'>, TextInputNonPassthroughProps>
// using forwardRef is important so that other components can autofocus the input
const TextInput = React.forwardRef<HTMLInputElement, TextInputProps>(
(
{
icon: IconComponent,
leadingVisual: LeadingVisual,
trailingVisual: TrailingVisual,
trailingAction,
block,
className,
contrast,
disabled,
loading,
loaderPosition = 'auto',
loaderText = 'Loading',
monospace,
validationStatus,
size: sizeProp,
onFocus,
onBlur,
// start deprecated props
variant: variantProp,
width: widthProp,
minWidth: minWidthProp,
maxWidth: maxWidthProp,
// end deprecated props
type = 'text',
required,
characterLimit,
onChange,
value,
defaultValue,
...inputProps
},
ref,
) => {
const [isInputFocused, setIsInputFocused] = useState<boolean>(false)
const inputRef = useRef<HTMLInputElement>(null)
const mergedRef = useMergedRefs(inputRef, ref)
const [characterCount, setCharacterCount] = useState<string>('')
const [isOverLimit, setIsOverLimit] = useState<boolean>(false)
const [screenReaderMessage, setScreenReaderMessage] = useState<string>('')
const characterCounterRef = useRef<CharacterCounter | null>(null)
const lastCountedLengthRef = useRef<number | null>(null)
const lastCharacterCountRef = useRef<string>('')
const lastIsOverLimitRef = useRef<boolean>(false)
const lastScreenReaderMessageRef = useRef<string>('')
// this class is necessary to style FilterSearch, plz no touchy!
const wrapperClasses = clsx(className, 'TextInput-wrapper')
const showLeadingLoadingIndicator =
loading && (loaderPosition === 'leading' || Boolean(LeadingVisual && loaderPosition !== 'trailing'))
const showTrailingLoadingIndicator =
loading && (loaderPosition === 'trailing' || Boolean(loaderPosition === 'auto' && !LeadingVisual))
// Date/time input types that have segment-based focus
const isSegmentedInputType = type === 'date' || type === 'time' || type === 'datetime-local'
const focusInput: MouseEventHandler = e => {
// Don't call focus() if the input itself was clicked on date/time inputs.
if (e.target !== inputRef.current || !isSegmentedInputType) {
inputRef.current?.focus()
}
}
const leadingVisualId = useId()
const trailingVisualId = useId()
const loadingId = useId()
const inputDescribedBy =
clsx(
inputProps['aria-describedby'],
LeadingVisual && leadingVisualId,
TrailingVisual && trailingVisualId,
loading && loadingId,
) || undefined
const handleInputFocus = useCallback(
(e: React.FocusEvent<HTMLInputElement>) => {
setIsInputFocused(true)
onFocus && onFocus(e)
},
[onFocus],
)
const handleInputBlur = useCallback(
(e: React.FocusEvent<HTMLInputElement>) => {
setIsInputFocused(false)
onBlur && onBlur(e)
},
[onBlur],
)
// Initialize character counter
useEffect(() => {
if (characterLimit) {
characterCounterRef.current = new CharacterCounter({
onCountUpdate: (count, overLimit, message) => {
if (message !== lastCharacterCountRef.current) {
lastCharacterCountRef.current = message
setCharacterCount(message)
}
if (overLimit !== lastIsOverLimitRef.current) {
lastIsOverLimitRef.current = overLimit
setIsOverLimit(overLimit)
}
},
onScreenReaderAnnounce: message => {
if (message !== lastScreenReaderMessageRef.current) {
lastScreenReaderMessageRef.current = message
setScreenReaderMessage(message)
}
},
})
lastCountedLengthRef.current = null
return () => {
characterCounterRef.current?.cleanup()
characterCounterRef.current = null
lastCountedLengthRef.current = null
lastCharacterCountRef.current = ''
lastIsOverLimitRef.current = false
lastScreenReaderMessageRef.current = ''
}
}
}, [characterLimit])
// Update character count when value changes or on mount
useEffect(() => {
if (characterLimit && characterCounterRef.current) {
const currentValue =
value !== undefined ? String(value) : defaultValue !== undefined ? String(defaultValue) : ''
const currentLength = currentValue.length
if (currentLength !== lastCountedLengthRef.current) {
lastCountedLengthRef.current = currentLength
characterCounterRef.current.updateCharacterCount(currentLength, characterLimit)
}
}
}, [value, defaultValue, characterLimit])
// Handle input change with character counter
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
if (characterLimit && characterCounterRef.current) {
const currentLength = e.target.value.length
if (currentLength !== lastCountedLengthRef.current) {
lastCountedLengthRef.current = currentLength
characterCounterRef.current.updateCharacterCount(currentLength, characterLimit)
}
}
onChange?.(e)
},
[onChange, characterLimit],
)
const characterCountId = useId()
const characterCountStaticMessageId = useId()
const isValid = isOverLimit ? 'error' : validationStatus
return (
<>
<TextInputWrapper
block={block}
className={wrapperClasses}
validationStatus={isValid}
contrast={contrast}
disabled={disabled}
monospace={monospace}
size={sizeProp}
width={widthProp}
minWidth={minWidthProp}
maxWidth={maxWidthProp}
variant={variantProp}
hasLeadingVisual={Boolean(LeadingVisual || showLeadingLoadingIndicator)}
hasTrailingVisual={Boolean(TrailingVisual || showTrailingLoadingIndicator)}
hasTrailingAction={Boolean(trailingAction)}
isInputFocused={isInputFocused}
onClick={focusInput}
aria-busy={Boolean(loading)}
>
{IconComponent && <IconComponent className="TextInput-icon" />}
<TextInputInnerVisualSlot
visualPosition="leading"
showLoadingIndicator={showLeadingLoadingIndicator}
hasLoadingIndicator={typeof loading === 'boolean'}
id={leadingVisualId}
>
{typeof LeadingVisual !== 'string' && isValidElementType(LeadingVisual) ? <LeadingVisual /> : LeadingVisual}
</TextInputInnerVisualSlot>
<UnstyledTextInput
ref={mergedRef}
disabled={disabled}
onFocus={handleInputFocus}
onBlur={handleInputBlur}
onChange={handleInputChange}
type={type}
aria-required={required}
aria-invalid={isValid === 'error' ? 'true' : undefined}
value={value}
defaultValue={defaultValue}
{...inputProps}
aria-describedby={
characterLimit
? [characterCountStaticMessageId, inputDescribedBy].filter(Boolean).join(' ') || undefined
: inputDescribedBy
}
data-component="input"
/>
{loading && <VisuallyHidden id={loadingId}>{loaderText}</VisuallyHidden>}
<TextInputInnerVisualSlot
visualPosition="trailing"
showLoadingIndicator={showTrailingLoadingIndicator}
hasLoadingIndicator={typeof loading === 'boolean'}
id={trailingVisualId}
data-testid="text-input-trailing-visual"
>
{typeof TrailingVisual !== 'string' && isValidElementType(TrailingVisual) ? (
<TrailingVisual />
) : (
TrailingVisual
)}
</TextInputInnerVisualSlot>
{trailingAction}
</TextInputWrapper>
{characterLimit && (
<>
<VisuallyHidden aria-live="polite" role="status">
{screenReaderMessage}
</VisuallyHidden>
<VisuallyHidden id={characterCountStaticMessageId}>
You can enter up to {characterLimit} {characterLimit === 1 ? 'character' : 'characters'}
</VisuallyHidden>
<Text
aria-hidden="true"
id={characterCountId}
size="small"
className={clsx(classes.CharacterCounter, isOverLimit && classes['CharacterCounter--error'])}
>
{isOverLimit && <AlertFillIcon size={16} />}
{characterCount}
</Text>
</>
)}
</>
)
},
) as PolymorphicForwardRefComponent<'input', TextInputProps>
TextInput.displayName = 'TextInput'
export default Object.assign(TextInput, {
__SLOT__: Symbol('TextInput'),
Action: TextInputAction,
})