-
Notifications
You must be signed in to change notification settings - Fork 86
/
textbox.component.tsx
385 lines (367 loc) · 13 KB
/
textbox.component.tsx
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import React, { useContext, useRef } from "react";
import { MarginProps } from "styled-system";
import { filterStyledSystemMarginProps } from "../../style/utils";
import {
Input,
InputPresentation,
CommonInputProps,
} from "../../__internal__/input";
import { ValidationProps } from "../../__internal__/validations";
import InputIconToggle from "../../__internal__/input-icon-toggle";
import FormField from "../../__internal__/form-field";
import { IconType } from "../icon";
import useUniqueId from "../../hooks/__internal__/useUniqueId";
import { InputBehaviour } from "../../__internal__/input-behaviour";
import StyledPrefix from "./__internal__/prefix.style";
import { TooltipProvider } from "../../__internal__/tooltip-provider";
import useCharacterCount from "../../hooks/__internal__/useCharacterCount";
import useInputAccessibility from "../../hooks/__internal__/useInputAccessibility/useInputAccessibility";
import { ErrorBorder, StyledHintText } from "./textbox.style";
import ValidationMessage from "../../__internal__/validation-message";
import { NewValidationContext } from "../carbon-provider/carbon-provider.component";
import NumeralDateContext from "../numeral-date/numeral-date-context";
import Box from "../box";
import Logger from "../../__internal__/utils/logger";
import guid from "../../__internal__/utils/helpers/guid";
export const ALIGN_DEFAULT = "left";
export const SIZE_DEFAULT = "medium";
export const LABEL_WIDTH_DEFAULT = 30;
export const LABEL_VALIDATION_DEFAULT = false;
export interface CommonTextboxProps
extends ValidationProps,
MarginProps,
Omit<CommonInputProps, "size"> {
/** Prop to specify the aria-labelledby property of the component */
"aria-labelledby"?: string;
/** Identifier used for testing purposes, applied to the root element of the component. */
"data-component"?: string;
/** Identifier used for testing purposes, applied to the root element of the component. */
"data-element"?: string;
/** Identifier used for testing purposes, applied to the root element of the component. */
"data-role"?: string;
/** Breakpoint for adaptive label (inline labels change to top aligned). Enables the adaptive behaviour when set */
adaptiveLabelBreakpoint?: number;
/** Integer to determine a timeout for the deferred callback */
deferTimeout?: number;
/** A hint string rendered before the input but after the label. Intended to describe the purpose or content of the input. */
inputHint?: string;
/** Help content to be displayed under an input */
fieldHelp?: React.ReactNode;
/**
* An optional alternative for props.value, this is useful if the
* real value is an ID but you want to show a human-readable version.
*/
formattedValue?: string;
/**
* Unique identifier for the input.
* Label id will be based on it, using following pattern: [id]-label.
* Will use a randomly generated GUID if none is provided.
*/
id?: string;
/** Type of the icon that will be rendered next to the input */
inputIcon?: IconType;
/** Optional handler for click event on Textbox icon */
iconOnClick?: (
ev: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>
) => void;
/** Optional handler for mouse down event on Textbox icon */
iconOnMouseDown?: (ev: React.MouseEvent<HTMLElement>) => void;
/** Overrides the default tabindex of the component */
iconTabIndex?: number;
/** The width of the input as a percentage */
inputWidth?: number;
/**
* Prop for specifying the max width of the input.
* Leaving the `maxWidth` prop with no value will default the width to '100%'
*/
maxWidth?: string;
/** Additional child elements to display before the input */
leftChildren?: React.ReactNode;
/** Label content */
label?: string;
/** Inline label alignment */
labelAlign?: "left" | "right";
/** [Legacy] Text applied to label help tooltip. When opted into new design validations
* it will render as a hint above the input, unless an `inputHint`
* prop is also passed
*/
labelHelp?: React.ReactNode;
/** When true label is inline */
labelInline?: boolean;
/** Spacing between label and a field for inline label, given number will be multiplied by base spacing unit (8) */
labelSpacing?: 1 | 2;
/** Label width */
labelWidth?: number;
/** Specify a callback triggered on change */
onChange?: (ev: React.ChangeEvent<HTMLInputElement>) => void;
/** Deferred callback to be called after the onChange event */
onChangeDeferred?: () => void;
/** Specify a callback triggered on click */
onClick?: (
ev: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>
) => void;
/** Event handler for the focus event */
onFocus?: (ev: React.FocusEvent<HTMLInputElement>) => void;
/** Event handler for the blur event */
onBlur?: (ev: React.FocusEvent<HTMLInputElement>) => void;
/** Event handler for the mouse down event */
onMouseDown?: (ev: React.MouseEvent<HTMLElement>) => void;
/** Emphasized part of the displayed text */
prefix?: string;
/** Reverses label and input display */
reverse?: boolean;
/** Size of an input */
size?: "small" | "medium" | "large";
/** When true, validation icon will be placed on label instead of being placed on the input */
validationOnLabel?: boolean;
/** Overrides the default tooltip position */
tooltipPosition?: "top" | "bottom" | "left" | "right";
/** Aria label for rendered help component */
helpAriaLabel?: string;
/** Flag to configure component as optional. */
isOptional?: boolean;
}
export interface TextboxProps extends CommonTextboxProps {
/** Content to be rendered next to the input */
children?: React.ReactNode;
/** Container for DatePicker or SelectList components */
positionedChildren?: React.ReactNode;
/** Character limit of the textarea */
characterLimit?: number;
}
let deprecateInputRefWarnTriggered = false;
let deprecateUncontrolledWarnTriggered = false;
export const Textbox = React.forwardRef(
(
{
"aria-labelledby": ariaLabelledBy,
align = ALIGN_DEFAULT,
autoFocus,
children,
disabled,
inputIcon,
leftChildren,
label,
labelAlign,
labelHelp,
labelInline,
labelSpacing,
id,
formattedValue,
inputHint,
fieldHelp,
error,
warning,
info,
name,
reverse,
size = SIZE_DEFAULT,
value,
readOnly,
placeholder,
inputRef,
onBlur,
onClick,
onFocus,
onChange,
onMouseDown,
onChangeDeferred,
deferTimeout,
isOptional,
iconOnClick,
iconOnMouseDown,
iconTabIndex,
validationOnLabel = LABEL_VALIDATION_DEFAULT,
labelWidth = LABEL_WIDTH_DEFAULT,
inputWidth,
maxWidth,
prefix,
adaptiveLabelBreakpoint,
required,
positionedChildren,
tooltipPosition,
"data-component": dataComponent,
"data-element": dataElement,
"data-role": dataRole,
characterLimit,
helpAriaLabel,
...props
}: TextboxProps,
ref: React.ForwardedRef<HTMLInputElement>
) => {
const characterCountValue = typeof value === "string" ? value : "";
const [uniqueId, uniqueName] = useUniqueId(id, name);
const [characterCount, visuallyHiddenHintId] = useCharacterCount(
characterCountValue,
characterLimit
);
const { validationRedesignOptIn } = useContext(NewValidationContext);
const { disableErrorBorder } = useContext(NumeralDateContext);
const computeLabelPropValues = <T,>(prop: T): undefined | T =>
validationRedesignOptIn ? undefined : prop;
if (!deprecateInputRefWarnTriggered && inputRef) {
deprecateInputRefWarnTriggered = true;
Logger.deprecate(
"The `inputRef` prop in `Textbox` component is deprecated and will soon be removed. Please use `ref` instead."
);
}
if (!deprecateUncontrolledWarnTriggered && !onChange) {
deprecateUncontrolledWarnTriggered = true;
Logger.deprecate(
"Uncontrolled behaviour in `Textbox` is deprecated and support will soon be removed. Please make sure all your inputs are controlled."
);
}
const {
labelId,
validationId,
fieldHelpId,
ariaDescribedBy,
} = useInputAccessibility({
id: uniqueId,
validationRedesignOptIn,
error,
warning,
info,
label,
fieldHelp,
});
const hintId = useRef(guid());
const inputHintId = inputHint ? hintId.current : undefined;
const combinedAriaDescribedBy = [
ariaDescribedBy,
inputHintId,
visuallyHiddenHintId,
]
.filter(Boolean)
.join(" ");
const hasIconInside = !!(inputIcon || (validationId && !validationOnLabel));
const input = (
<InputPresentation
align={align}
disabled={disabled}
readOnly={readOnly}
size={size}
error={error}
warning={warning}
info={info}
prefix={prefix}
inputWidth={inputWidth || 100 - labelWidth}
maxWidth={maxWidth}
positionedChildren={positionedChildren}
hasIcon={hasIconInside}
>
{leftChildren}
{prefix && (
<StyledPrefix data-element="textbox-prefix" size={size}>
{prefix}
</StyledPrefix>
)}
<Input
{...(required && { required })}
align={align}
aria-invalid={!!error}
aria-labelledby={ariaLabelledBy}
ariaDescribedBy={combinedAriaDescribedBy}
autoFocus={autoFocus}
deferTimeout={deferTimeout}
disabled={disabled}
id={uniqueId}
inputRef={inputRef}
ref={ref}
name={uniqueName}
onBlur={onBlur}
onChange={onChange}
onChangeDeferred={onChangeDeferred}
onClick={disabled || readOnly ? undefined : onClick}
onFocus={onFocus}
onMouseDown={disabled || readOnly ? undefined : onMouseDown}
placeholder={disabled || readOnly ? "" : placeholder}
readOnly={readOnly}
value={typeof formattedValue === "string" ? formattedValue : value}
validationIconId={validationRedesignOptIn ? undefined : validationId}
{...props}
/>
{children}
<InputIconToggle
align={align}
disabled={disabled}
error={error}
iconTabIndex={iconTabIndex}
info={info}
inputIcon={inputIcon}
onClick={disabled || readOnly ? undefined : iconOnClick || onClick}
onMouseDown={
disabled || readOnly ? undefined : iconOnMouseDown || onMouseDown
}
readOnly={readOnly}
size={size}
useValidationIcon={!(validationRedesignOptIn || validationOnLabel)}
warning={warning}
validationIconId={validationRedesignOptIn ? undefined : validationId}
/>
</InputPresentation>
);
return (
<TooltipProvider
helpAriaLabel={helpAriaLabel}
tooltipPosition={tooltipPosition}
>
<InputBehaviour>
<FormField
disabled={disabled}
fieldHelpId={fieldHelpId}
fieldHelp={computeLabelPropValues(fieldHelp)}
error={error}
warning={warning}
info={info}
label={label}
labelId={labelId}
labelAlign={computeLabelPropValues(labelAlign)}
labelHelp={computeLabelPropValues(labelHelp)}
labelInline={computeLabelPropValues(labelInline)}
labelSpacing={labelSpacing}
labelWidth={computeLabelPropValues(labelWidth)}
id={uniqueId}
reverse={computeLabelPropValues(reverse)}
isOptional={isOptional}
useValidationIcon={computeLabelPropValues(validationOnLabel)}
adaptiveLabelBreakpoint={adaptiveLabelBreakpoint}
isRequired={required}
data-component={dataComponent}
data-role={dataRole}
data-element={dataElement}
validationIconId={
validationRedesignOptIn ? undefined : validationId
}
validationRedesignOptIn={validationRedesignOptIn}
{...filterStyledSystemMarginProps(props)}
>
{(inputHint || (labelHelp && validationRedesignOptIn)) && (
<StyledHintText id={inputHintId} data-element="input-hint">
{inputHint || labelHelp}
</StyledHintText>
)}
{validationRedesignOptIn ? (
<Box position="relative">
<ValidationMessage
error={error}
validationId={validationId}
warning={warning}
/>
{!disableErrorBorder && (error || warning) && (
<ErrorBorder warning={!!(!error && warning)} />
)}
{input}
</Box>
) : (
input
)}
</FormField>
{characterCount}
</InputBehaviour>
</TooltipProvider>
);
}
);
Textbox.displayName = "Textbox";
export default Textbox;