@react-aria/textfield 3.18.5 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,163 +0,0 @@
1
- /*
2
- * Copyright 2021 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {AriaTextFieldProps} from '@react-types/textfield';
14
- import {getEventTarget, mergeProps, useEffectEvent} from '@react-aria/utils';
15
- import {InputEventHandler, useEffect, useRef} from 'react';
16
- import {RefObject} from '@react-types/shared';
17
- import {TextFieldAria, useTextField} from './useTextField';
18
-
19
- interface FormattedTextFieldState {
20
- validate: (val: string) => boolean,
21
- setInputValue: (val: string) => void
22
- }
23
-
24
-
25
- function supportsNativeBeforeInputEvent() {
26
- return typeof window !== 'undefined' &&
27
- window.InputEvent &&
28
- typeof InputEvent.prototype.getTargetRanges === 'function';
29
- }
30
-
31
- export function useFormattedTextField(props: AriaTextFieldProps, state: FormattedTextFieldState, inputRef: RefObject<HTMLInputElement | null>): TextFieldAria {
32
- // All browsers implement the 'beforeinput' event natively except Firefox
33
- // (currently behind a flag as of Firefox 84). React's polyfill does not
34
- // run in all cases that the native event fires, e.g. when deleting text.
35
- // Use the native event if available so that we can prevent invalid deletions.
36
- // We do not attempt to polyfill this in Firefox since it would be very complicated,
37
- // the benefit of doing so is fairly minor, and it's going to be natively supported soon.
38
- let onBeforeInputFallback = useEffectEvent((e: InputEvent) => {
39
- let input = inputRef.current;
40
- if (!input) {
41
- return;
42
- }
43
-
44
- // Compute the next value of the input if the event is allowed to proceed.
45
- // See https://www.w3.org/TR/input-events-2/#interface-InputEvent-Attributes for a full list of input types.
46
- let nextValue: string | null = null;
47
- switch (e.inputType) {
48
- case 'historyUndo':
49
- case 'historyRedo':
50
- // Explicitly allow undo/redo. e.data is null in this case, but there's no need to validate,
51
- // because presumably the input would have already been validated previously.
52
- return;
53
- case 'insertLineBreak':
54
- // Explicitly allow "insertLineBreak" event, to allow onSubmit for "enter" key. e.data is null in this case.
55
- return;
56
- case 'deleteContent':
57
- case 'deleteByCut':
58
- case 'deleteByDrag':
59
- nextValue = input.value.slice(0, input.selectionStart!) + input.value.slice(input.selectionEnd!);
60
- break;
61
- case 'deleteContentForward':
62
- // This is potentially incorrect, since the browser may actually delete more than a single UTF-16
63
- // character. In reality, a full Unicode grapheme cluster consisting of multiple UTF-16 characters
64
- // or code points may be deleted. However, in our currently supported locales, there are no such cases.
65
- // If we support additional locales in the future, this may need to change.
66
- nextValue = input.selectionEnd === input.selectionStart
67
- ? input.value.slice(0, input.selectionStart!) + input.value.slice(input.selectionEnd! + 1)
68
- : input.value.slice(0, input.selectionStart!) + input.value.slice(input.selectionEnd!);
69
- break;
70
- case 'deleteContentBackward':
71
- nextValue = input.selectionEnd === input.selectionStart
72
- ? input.value.slice(0, input.selectionStart! - 1) + input.value.slice(input.selectionStart!)
73
- : input.value.slice(0, input.selectionStart!) + input.value.slice(input.selectionEnd!);
74
- break;
75
- case 'deleteSoftLineBackward':
76
- case 'deleteHardLineBackward':
77
- nextValue = input.value.slice(input.selectionStart!);
78
- break;
79
- default:
80
- if (e.data != null) {
81
- nextValue =
82
- input.value.slice(0, input.selectionStart!) +
83
- e.data +
84
- input.value.slice(input.selectionEnd!);
85
- }
86
- break;
87
- }
88
-
89
- // If we did not compute a value, or the new value is invalid, prevent the event
90
- // so that the browser does not update the input text, move the selection, or add to
91
- // the undo/redo stack.
92
- if (nextValue == null || !state.validate(nextValue)) {
93
- e.preventDefault();
94
- }
95
- });
96
-
97
- useEffect(() => {
98
- if (!supportsNativeBeforeInputEvent() || !inputRef.current) {
99
- return;
100
- }
101
-
102
- let input = inputRef.current;
103
- input.addEventListener('beforeinput', onBeforeInputFallback, false);
104
- return () => {
105
- input.removeEventListener('beforeinput', onBeforeInputFallback, false);
106
- };
107
- }, [inputRef]);
108
-
109
- let onBeforeInput: InputEventHandler<HTMLInputElement> | null = !supportsNativeBeforeInputEvent()
110
- ? e => {
111
- let nextValue =
112
- getEventTarget(e).value.slice(0, getEventTarget(e).selectionStart!) +
113
- e.data +
114
- getEventTarget(e).value.slice(getEventTarget(e).selectionEnd!);
115
-
116
- if (!state.validate(nextValue)) {
117
- e.preventDefault();
118
- }
119
- }
120
- : null;
121
-
122
- let {labelProps, inputProps: textFieldProps, descriptionProps, errorMessageProps, ...validation} = useTextField(props, inputRef);
123
-
124
- let compositionStartState = useRef<{value: string, selectionStart: number | null, selectionEnd: number | null} | null>(null);
125
- return {
126
- inputProps: mergeProps(
127
- textFieldProps,
128
- {
129
- onBeforeInput,
130
- onCompositionStart() {
131
- // Chrome does not implement Input Events Level 2, which specifies the insertFromComposition
132
- // and deleteByComposition inputType values for the beforeinput event. These are meant to occur
133
- // at the end of a composition (e.g. Pinyin IME, Android auto correct, etc.), and crucially, are
134
- // cancelable. The insertCompositionText and deleteCompositionText input types are not cancelable,
135
- // nor would we want to cancel them because the input from the user is incomplete at that point.
136
- // In Safari, insertFromComposition/deleteFromComposition will fire, however, allowing us to cancel
137
- // the final composition result if it is invalid. As a fallback for Chrome and Firefox, which either
138
- // don't support Input Events Level 2, or beforeinput at all, we store the state of the input when
139
- // the compositionstart event fires, and undo the changes in compositionend (below) if it is invalid.
140
- // Unfortunately, this messes up the undo/redo stack, but until insertFromComposition/deleteByComposition
141
- // are implemented, there is no other way to prevent composed input.
142
- // See https://bugs.chromium.org/p/chromium/issues/detail?id=1022204
143
- let {value, selectionStart, selectionEnd} = inputRef.current!;
144
- compositionStartState.current = {value, selectionStart, selectionEnd};
145
- },
146
- onCompositionEnd() {
147
- if (inputRef.current && !state.validate(inputRef.current.value)) {
148
- // Restore the input value in the DOM immediately so we can synchronously update the selection position.
149
- // But also update the value in React state as well so it is correct for future updates.
150
- let {value, selectionStart, selectionEnd} = compositionStartState.current!;
151
- inputRef.current.value = value;
152
- inputRef.current.setSelectionRange(selectionStart, selectionEnd);
153
- state.setInputValue(value);
154
- }
155
- }
156
- }
157
- ),
158
- labelProps,
159
- descriptionProps,
160
- errorMessageProps,
161
- ...validation
162
- };
163
- }
@@ -1,205 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {AriaTextFieldProps} from '@react-types/textfield';
14
- import {DOMAttributes, ValidationResult} from '@react-types/shared';
15
- import {filterDOMProps, getEventTarget, mergeProps, useFormReset} from '@react-aria/utils';
16
- import React, {
17
- ChangeEvent,
18
- HTMLAttributes,
19
- type JSX,
20
- LabelHTMLAttributes,
21
- RefObject,
22
- useState
23
- } from 'react';
24
- import {useControlledState} from '@react-stately/utils';
25
- import {useField} from '@react-aria/label';
26
- import {useFocusable} from '@react-aria/interactions';
27
- import {useFormValidation} from '@react-aria/form';
28
- import {useFormValidationState} from '@react-stately/form';
29
-
30
- /**
31
- * A map of HTML element names and their interface types.
32
- * For example `'a'` -> `HTMLAnchorElement`.
33
- */
34
- type IntrinsicHTMLElements = {
35
- [K in keyof IntrinsicHTMLAttributes]: IntrinsicHTMLAttributes[K] extends HTMLAttributes<infer T> ? T : never
36
- };
37
-
38
- /**
39
- * A map of HTML element names and their attribute interface types.
40
- * For example `'a'` -> `AnchorHTMLAttributes<HTMLAnchorElement>`.
41
- */
42
- type IntrinsicHTMLAttributes = JSX.IntrinsicElements;
43
-
44
- type DefaultElementType = 'input';
45
-
46
- /**
47
- * The intrinsic HTML element names that `useTextField` supports; e.g. `input`,
48
- * `textarea`.
49
- */
50
- type TextFieldIntrinsicElements = keyof Pick<IntrinsicHTMLElements, 'input' | 'textarea'>;
51
-
52
- /**
53
- * The HTML element interfaces that `useTextField` supports based on what is
54
- * defined for `TextFieldIntrinsicElements`; e.g. `HTMLInputElement`,
55
- * `HTMLTextAreaElement`.
56
- */
57
- type TextFieldHTMLElementType = Pick<IntrinsicHTMLElements, TextFieldIntrinsicElements>;
58
-
59
- /**
60
- * The HTML attributes interfaces that `useTextField` supports based on what
61
- * is defined for `TextFieldIntrinsicElements`; e.g. `InputHTMLAttributes`,
62
- * `TextareaHTMLAttributes`.
63
- */
64
- type TextFieldHTMLAttributesType = Pick<IntrinsicHTMLAttributes, TextFieldIntrinsicElements>;
65
-
66
- /**
67
- * The type of `inputProps` returned by `useTextField`; e.g. `InputHTMLAttributes`,
68
- * `TextareaHTMLAttributes`.
69
- */
70
- type TextFieldInputProps<T extends TextFieldIntrinsicElements> = TextFieldHTMLAttributesType[T];
71
-
72
- export interface AriaTextFieldOptions<T extends TextFieldIntrinsicElements> extends AriaTextFieldProps<TextFieldHTMLElementType[T]> {
73
- /**
74
- * The HTML element used to render the input, e.g. 'input', or 'textarea'.
75
- * It determines whether certain HTML attributes will be included in `inputProps`.
76
- * For example, [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-type).
77
- * @default 'input'
78
- */
79
- inputElementType?: T,
80
- /**
81
- * Controls whether inputted text is automatically capitalized and, if so, in what manner.
82
- * See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize).
83
- */
84
- autoCapitalize?: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters',
85
- /**
86
- * An enumerated attribute that defines what action label or icon to preset for the enter key on virtual keyboards. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/enterkeyhint).
87
- */
88
- enterKeyHint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'
89
- }
90
-
91
- /**
92
- * The type of `ref` object that can be passed to `useTextField` based on the given
93
- * intrinsic HTML element name; e.g.`RefObject<HTMLInputElement>`,
94
- * `RefObject<HTMLTextAreaElement>`.
95
- */
96
- type TextFieldRefObject<T extends TextFieldIntrinsicElements> = RefObject<TextFieldHTMLElementType[T] | null>;
97
-
98
- export interface TextFieldAria<T extends TextFieldIntrinsicElements = DefaultElementType> extends ValidationResult {
99
- /** Props for the input element. */
100
- inputProps: TextFieldInputProps<T>,
101
- /** Props for the text field's visible label element, if any. */
102
- labelProps: DOMAttributes | LabelHTMLAttributes<HTMLLabelElement>,
103
- /** Props for the text field's description element, if any. */
104
- descriptionProps: DOMAttributes,
105
- /** Props for the text field's error message element, if any. */
106
- errorMessageProps: DOMAttributes
107
- }
108
-
109
- /**
110
- * Provides the behavior and accessibility implementation for a text field.
111
- * @param props - Props for the text field.
112
- * @param ref - Ref to the HTML input or textarea element.
113
- */
114
- export function useTextField<T extends TextFieldIntrinsicElements = DefaultElementType>(
115
- props: AriaTextFieldOptions<T>,
116
- ref: TextFieldRefObject<T>
117
- ): TextFieldAria<T> {
118
- let {
119
- inputElementType = 'input',
120
- isDisabled = false,
121
- isRequired = false,
122
- isReadOnly = false,
123
- type = 'text',
124
- validationBehavior = 'aria'
125
- } = props;
126
- let [value, setValue] = useControlledState<string>(props.value, props.defaultValue || '', props.onChange);
127
- let {focusableProps} = useFocusable<TextFieldHTMLElementType[T]>(props, ref);
128
- let validationState = useFormValidationState({
129
- ...props,
130
- value
131
- });
132
- let {isInvalid, validationErrors, validationDetails} = validationState.displayValidation;
133
- let {labelProps, fieldProps, descriptionProps, errorMessageProps} = useField({
134
- ...props,
135
- isInvalid,
136
- errorMessage: props.errorMessage || validationErrors
137
- });
138
- let domProps = filterDOMProps(props, {labelable: true});
139
-
140
- const inputOnlyProps = {
141
- type,
142
- pattern: props.pattern
143
- };
144
-
145
- let [initialValue] = useState(value);
146
- useFormReset(ref, props.defaultValue ?? initialValue, setValue);
147
- useFormValidation(props, validationState, ref);
148
-
149
- return {
150
- labelProps,
151
- inputProps: mergeProps(
152
- domProps,
153
- inputElementType === 'input' ? inputOnlyProps : undefined,
154
- {
155
- disabled: isDisabled,
156
- readOnly: isReadOnly,
157
- required: isRequired && validationBehavior === 'native',
158
- 'aria-required': (isRequired && validationBehavior === 'aria') || undefined,
159
- 'aria-invalid': isInvalid || undefined,
160
- 'aria-errormessage': props['aria-errormessage'],
161
- 'aria-activedescendant': props['aria-activedescendant'],
162
- 'aria-autocomplete': props['aria-autocomplete'],
163
- 'aria-haspopup': props['aria-haspopup'],
164
- 'aria-controls': props['aria-controls'],
165
- value,
166
- onChange: (e: ChangeEvent<HTMLInputElement>) => setValue(getEventTarget(e).value),
167
- autoComplete: props.autoComplete,
168
- autoCapitalize: props.autoCapitalize,
169
- maxLength: props.maxLength,
170
- minLength: props.minLength,
171
- name: props.name,
172
- form: props.form,
173
- placeholder: props.placeholder,
174
- inputMode: props.inputMode,
175
- autoCorrect: props.autoCorrect,
176
- spellCheck: props.spellCheck,
177
- [parseInt(React.version, 10) >= 17 ? 'enterKeyHint' : 'enterkeyhint']: props.enterKeyHint,
178
-
179
- // Clipboard events
180
- onCopy: props.onCopy,
181
- onCut: props.onCut,
182
- onPaste: props.onPaste,
183
-
184
- // Composition events
185
- onCompositionEnd: props.onCompositionEnd,
186
- onCompositionStart: props.onCompositionStart,
187
- onCompositionUpdate: props.onCompositionUpdate,
188
-
189
- // Selection events
190
- onSelect: props.onSelect,
191
-
192
- // Input events
193
- onBeforeInput: props.onBeforeInput,
194
- onInput: props.onInput,
195
- ...focusableProps,
196
- ...fieldProps
197
- }
198
- ),
199
- descriptionProps,
200
- errorMessageProps,
201
- isInvalid,
202
- validationErrors,
203
- validationDetails
204
- };
205
- }