@react-aria/textfield 3.0.0-nightly-641446f65-240905

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.
@@ -0,0 +1,120 @@
1
+ var $4Z7CR$react = require("react");
2
+ var $4Z7CR$reactariautils = require("@react-aria/utils");
3
+ var $4Z7CR$reactstatelyutils = require("@react-stately/utils");
4
+ var $4Z7CR$reactarialabel = require("@react-aria/label");
5
+ var $4Z7CR$reactariafocus = require("@react-aria/focus");
6
+ var $4Z7CR$reactariaform = require("@react-aria/form");
7
+ var $4Z7CR$reactstatelyform = require("@react-stately/form");
8
+
9
+
10
+ function $parcel$export(e, n, v, s) {
11
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
12
+ }
13
+
14
+ $parcel$export(module.exports, "useTextField", () => $9076f978e02df845$export$712718f7aec83d5);
15
+ /*
16
+ * Copyright 2020 Adobe. All rights reserved.
17
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
18
+ * you may not use this file except in compliance with the License. You may obtain a copy
19
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
20
+ *
21
+ * Unless required by applicable law or agreed to in writing, software distributed under
22
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
23
+ * OF ANY KIND, either express or implied. See the License for the specific language
24
+ * governing permissions and limitations under the License.
25
+ */
26
+
27
+
28
+
29
+
30
+
31
+
32
+ function $9076f978e02df845$export$712718f7aec83d5(props, ref) {
33
+ let { inputElementType: inputElementType = 'input', isDisabled: isDisabled = false, isRequired: isRequired = false, isReadOnly: isReadOnly = false, type: type = 'text', validationBehavior: validationBehavior = 'aria' } = props;
34
+ let [value, setValue] = (0, $4Z7CR$reactstatelyutils.useControlledState)(props.value, props.defaultValue || '', props.onChange);
35
+ let { focusableProps: focusableProps } = (0, $4Z7CR$reactariafocus.useFocusable)(props, ref);
36
+ let validationState = (0, $4Z7CR$reactstatelyform.useFormValidationState)({
37
+ ...props,
38
+ value: value
39
+ });
40
+ let { isInvalid: isInvalid, validationErrors: validationErrors, validationDetails: validationDetails } = validationState.displayValidation;
41
+ let { labelProps: labelProps, fieldProps: fieldProps, descriptionProps: descriptionProps, errorMessageProps: errorMessageProps } = (0, $4Z7CR$reactarialabel.useField)({
42
+ ...props,
43
+ isInvalid: isInvalid,
44
+ errorMessage: props.errorMessage || validationErrors
45
+ });
46
+ let domProps = (0, $4Z7CR$reactariautils.filterDOMProps)(props, {
47
+ labelable: true
48
+ });
49
+ const inputOnlyProps = {
50
+ type: type,
51
+ pattern: props.pattern
52
+ };
53
+ (0, $4Z7CR$reactariautils.useFormReset)(ref, value, setValue);
54
+ (0, $4Z7CR$reactariaform.useFormValidation)(props, validationState, ref);
55
+ (0, $4Z7CR$react.useEffect)(()=>{
56
+ // This works around a React/Chrome bug that prevents textarea elements from validating when controlled.
57
+ // We prevent React from updating defaultValue (i.e. children) of textarea when `value` changes,
58
+ // which causes Chrome to skip validation. Only updating `value` is ok in our case since our
59
+ // textareas are always controlled. React is planning on removing this synchronization in a
60
+ // future major version.
61
+ // https://github.com/facebook/react/issues/19474
62
+ // https://github.com/facebook/react/issues/11896
63
+ if (ref.current instanceof (0, $4Z7CR$reactariautils.getOwnerWindow)(ref.current).HTMLTextAreaElement) {
64
+ let input = ref.current;
65
+ Object.defineProperty(input, 'defaultValue', {
66
+ get: ()=>input.value,
67
+ set: ()=>{},
68
+ configurable: true
69
+ });
70
+ }
71
+ }, [
72
+ ref
73
+ ]);
74
+ return {
75
+ labelProps: labelProps,
76
+ inputProps: (0, $4Z7CR$reactariautils.mergeProps)(domProps, inputElementType === 'input' ? inputOnlyProps : undefined, {
77
+ disabled: isDisabled,
78
+ readOnly: isReadOnly,
79
+ required: isRequired && validationBehavior === 'native',
80
+ 'aria-required': isRequired && validationBehavior === 'aria' || undefined,
81
+ 'aria-invalid': isInvalid || undefined,
82
+ 'aria-errormessage': props['aria-errormessage'],
83
+ 'aria-activedescendant': props['aria-activedescendant'],
84
+ 'aria-autocomplete': props['aria-autocomplete'],
85
+ 'aria-haspopup': props['aria-haspopup'],
86
+ value: value,
87
+ onChange: (e)=>setValue(e.target.value),
88
+ autoComplete: props.autoComplete,
89
+ autoCapitalize: props.autoCapitalize,
90
+ maxLength: props.maxLength,
91
+ minLength: props.minLength,
92
+ name: props.name,
93
+ placeholder: props.placeholder,
94
+ inputMode: props.inputMode,
95
+ // Clipboard events
96
+ onCopy: props.onCopy,
97
+ onCut: props.onCut,
98
+ onPaste: props.onPaste,
99
+ // Composition events
100
+ onCompositionEnd: props.onCompositionEnd,
101
+ onCompositionStart: props.onCompositionStart,
102
+ onCompositionUpdate: props.onCompositionUpdate,
103
+ // Selection events
104
+ onSelect: props.onSelect,
105
+ // Input events
106
+ onBeforeInput: props.onBeforeInput,
107
+ onInput: props.onInput,
108
+ ...focusableProps,
109
+ ...fieldProps
110
+ }),
111
+ descriptionProps: descriptionProps,
112
+ errorMessageProps: errorMessageProps,
113
+ isInvalid: isInvalid,
114
+ validationErrors: validationErrors,
115
+ validationDetails: validationDetails
116
+ };
117
+ }
118
+
119
+
120
+ //# sourceMappingURL=useTextField.main.js.map
@@ -0,0 +1 @@
1
+ {"mappings":";;;;;;;;;;;;;;AAAA;;;;;;;;;;CAUC;;;;;;;AAmGM,SAAS,yCACd,KAA8B,EAC9B,GAA0B;IAE1B,IAAI,oBACF,mBAAmB,qBACnB,aAAa,mBACb,aAAa,mBACb,aAAa,aACb,OAAO,4BACP,qBAAqB,QACtB,GAAqD;IACtD,IAAI,CAAC,OAAO,SAAS,GAAG,CAAA,GAAA,2CAAiB,EAAU,MAAM,KAAK,EAAE,MAAM,YAAY,IAAI,IAAI,MAAM,QAAQ;IACxG,IAAI,kBAAC,cAAc,EAAC,GAAG,CAAA,GAAA,kCAAW,EAAE,OAAO;IAC3C,IAAI,kBAAkB,CAAA,GAAA,8CAAqB,EAAE;QAC3C,GAAG,KAAK;eACR;IACF;IACA,IAAI,aAAC,SAAS,oBAAE,gBAAgB,qBAAE,iBAAiB,EAAC,GAAG,gBAAgB,iBAAiB;IACxF,IAAI,cAAC,UAAU,cAAE,UAAU,oBAAE,gBAAgB,qBAAE,iBAAiB,EAAC,GAAG,CAAA,GAAA,8BAAO,EAAE;QAC3E,GAAG,KAAK;mBACR;QACA,cAAc,MAAM,YAAY,IAAI;IACtC;IACA,IAAI,WAAW,CAAA,GAAA,oCAAa,EAAE,OAAO;QAAC,WAAW;IAAI;IAErD,MAAM,iBAAiB;cACrB;QACA,SAAS,MAAM,OAAO;IACxB;IAEA,CAAA,GAAA,kCAAW,EAAE,KAAK,OAAO;IACzB,CAAA,GAAA,sCAAgB,EAAE,OAAO,iBAAiB;IAE1C,CAAA,GAAA,sBAAQ,EAAE;QACR,wGAAwG;QACxG,gGAAgG;QAChG,4FAA4F;QAC5F,2FAA2F;QAC3F,wBAAwB;QACxB,iDAAiD;QACjD,iDAAiD;QACjD,IAAI,IAAI,OAAO,YAAY,CAAA,GAAA,oCAAa,EAAE,IAAI,OAAO,EAAE,mBAAmB,EAAE;YAC1E,IAAI,QAAQ,IAAI,OAAO;YACvB,OAAO,cAAc,CAAC,OAAO,gBAAgB;gBAC3C,KAAK,IAAM,MAAM,KAAK;gBACtB,KAAK,KAAO;gBACZ,cAAc;YAChB;QACF;IACF,GAAG;QAAC;KAAI;IAER,OAAO;oBACL;QACA,YAAY,CAAA,GAAA,gCAAS,EACnB,UACA,qBAAqB,UAAU,iBAAiB,WAChD;YACE,UAAU;YACV,UAAU;YACV,UAAU,cAAc,uBAAuB;YAC/C,iBAAiB,AAAC,cAAc,uBAAuB,UAAW;YAClE,gBAAgB,aAAa;YAC7B,qBAAqB,KAAK,CAAC,oBAAoB;YAC/C,yBAAyB,KAAK,CAAC,wBAAwB;YACvD,qBAAqB,KAAK,CAAC,oBAAoB;YAC/C,iBAAiB,KAAK,CAAC,gBAAgB;mBACvC;YACA,UAAU,CAAC,IAAqC,SAAS,EAAE,MAAM,CAAC,KAAK;YACvE,cAAc,MAAM,YAAY;YAChC,gBAAgB,MAAM,cAAc;YACpC,WAAW,MAAM,SAAS;YAC1B,WAAW,MAAM,SAAS;YAC1B,MAAM,MAAM,IAAI;YAChB,aAAa,MAAM,WAAW;YAC9B,WAAW,MAAM,SAAS;YAE1B,mBAAmB;YACnB,QAAQ,MAAM,MAAM;YACpB,OAAO,MAAM,KAAK;YAClB,SAAS,MAAM,OAAO;YAEtB,qBAAqB;YACrB,kBAAkB,MAAM,gBAAgB;YACxC,oBAAoB,MAAM,kBAAkB;YAC5C,qBAAqB,MAAM,mBAAmB;YAE9C,mBAAmB;YACnB,UAAU,MAAM,QAAQ;YAExB,eAAe;YACf,eAAe,MAAM,aAAa;YAClC,SAAS,MAAM,OAAO;YACtB,GAAG,cAAc;YACjB,GAAG,UAAU;QACf;0BAEF;2BACA;mBACA;0BACA;2BACA;IACF;AACF","sources":["packages/@react-aria/textfield/src/useTextField.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AriaTextFieldProps} from '@react-types/textfield';\nimport {\n ChangeEvent,\n HTMLAttributes,\n type JSX,\n LabelHTMLAttributes,\n RefObject,\n useEffect\n} from 'react';\nimport {DOMAttributes, ValidationResult} from '@react-types/shared';\nimport {filterDOMProps, getOwnerWindow, mergeProps, useFormReset} from '@react-aria/utils';\nimport {useControlledState} from '@react-stately/utils';\nimport {useField} from '@react-aria/label';\nimport {useFocusable} from '@react-aria/focus';\nimport {useFormValidation} from '@react-aria/form';\nimport {useFormValidationState} from '@react-stately/form';\n\n/**\n * A map of HTML element names and their interface types.\n * For example `'a'` -> `HTMLAnchorElement`.\n */\ntype IntrinsicHTMLElements = {\n [K in keyof IntrinsicHTMLAttributes]: IntrinsicHTMLAttributes[K] extends HTMLAttributes<infer T> ? T : never\n};\n\n/**\n * A map of HTML element names and their attribute interface types.\n * For example `'a'` -> `AnchorHTMLAttributes<HTMLAnchorElement>`.\n */\ntype IntrinsicHTMLAttributes = JSX.IntrinsicElements;\n\ntype DefaultElementType = 'input';\n\n/**\n * The intrinsic HTML element names that `useTextField` supports; e.g. `input`,\n * `textarea`.\n */\ntype TextFieldIntrinsicElements = keyof Pick<IntrinsicHTMLElements, 'input' | 'textarea'>;\n\n/**\n * The HTML element interfaces that `useTextField` supports based on what is\n * defined for `TextFieldIntrinsicElements`; e.g. `HTMLInputElement`,\n * `HTMLTextAreaElement`.\n */\ntype TextFieldHTMLElementType = Pick<IntrinsicHTMLElements, TextFieldIntrinsicElements>;\n\n/**\n * The HTML attributes interfaces that `useTextField` supports based on what\n * is defined for `TextFieldIntrinsicElements`; e.g. `InputHTMLAttributes`,\n * `TextareaHTMLAttributes`.\n */\ntype TextFieldHTMLAttributesType = Pick<IntrinsicHTMLAttributes, TextFieldIntrinsicElements>;\n\n/**\n * The type of `inputProps` returned by `useTextField`; e.g. `InputHTMLAttributes`,\n * `TextareaHTMLAttributes`.\n */\ntype TextFieldInputProps<T extends TextFieldIntrinsicElements> = TextFieldHTMLAttributesType[T];\n\nexport interface AriaTextFieldOptions<T extends TextFieldIntrinsicElements> extends AriaTextFieldProps {\n /**\n * The HTML element used to render the input, e.g. 'input', or 'textarea'.\n * It determines whether certain HTML attributes will be included in `inputProps`.\n * For example, [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-type).\n * @default 'input'\n */\n inputElementType?: T,\n /**\n * Controls whether inputted text is automatically capitalized and, if so, in what manner.\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize).\n */\n autoCapitalize?: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters'\n}\n\n/**\n * The type of `ref` object that can be passed to `useTextField` based on the given\n * intrinsic HTML element name; e.g.`RefObject<HTMLInputElement>`,\n * `RefObject<HTMLTextAreaElement>`.\n */\ntype TextFieldRefObject<T extends TextFieldIntrinsicElements> = RefObject<TextFieldHTMLElementType[T] | null>;\n\nexport interface TextFieldAria<T extends TextFieldIntrinsicElements = DefaultElementType> extends ValidationResult {\n /** Props for the input element. */\n inputProps: TextFieldInputProps<T>,\n /** Props for the text field's visible label element, if any. */\n labelProps: DOMAttributes | LabelHTMLAttributes<HTMLLabelElement>,\n /** Props for the text field's description element, if any. */\n descriptionProps: DOMAttributes,\n /** Props for the text field's error message element, if any. */\n errorMessageProps: DOMAttributes\n}\n\n/**\n * Provides the behavior and accessibility implementation for a text field.\n * @param props - Props for the text field.\n * @param ref - Ref to the HTML input or textarea element.\n */\nexport function useTextField<T extends TextFieldIntrinsicElements = DefaultElementType>(\n props: AriaTextFieldOptions<T>,\n ref: TextFieldRefObject<T>\n): TextFieldAria<T> {\n let {\n inputElementType = 'input',\n isDisabled = false,\n isRequired = false,\n isReadOnly = false,\n type = 'text',\n validationBehavior = 'aria'\n }: AriaTextFieldOptions<TextFieldIntrinsicElements> = props;\n let [value, setValue] = useControlledState<string>(props.value, props.defaultValue || '', props.onChange);\n let {focusableProps} = useFocusable(props, ref);\n let validationState = useFormValidationState({\n ...props,\n value\n });\n let {isInvalid, validationErrors, validationDetails} = validationState.displayValidation;\n let {labelProps, fieldProps, descriptionProps, errorMessageProps} = useField({\n ...props,\n isInvalid,\n errorMessage: props.errorMessage || validationErrors\n });\n let domProps = filterDOMProps(props, {labelable: true});\n\n const inputOnlyProps = {\n type,\n pattern: props.pattern\n };\n\n useFormReset(ref, value, setValue);\n useFormValidation(props, validationState, ref);\n\n useEffect(() => {\n // This works around a React/Chrome bug that prevents textarea elements from validating when controlled.\n // We prevent React from updating defaultValue (i.e. children) of textarea when `value` changes,\n // which causes Chrome to skip validation. Only updating `value` is ok in our case since our\n // textareas are always controlled. React is planning on removing this synchronization in a\n // future major version.\n // https://github.com/facebook/react/issues/19474\n // https://github.com/facebook/react/issues/11896\n if (ref.current instanceof getOwnerWindow(ref.current).HTMLTextAreaElement) {\n let input = ref.current;\n Object.defineProperty(input, 'defaultValue', {\n get: () => input.value,\n set: () => {},\n configurable: true\n });\n }\n }, [ref]);\n\n return {\n labelProps,\n inputProps: mergeProps(\n domProps,\n inputElementType === 'input' ? inputOnlyProps : undefined,\n {\n disabled: isDisabled,\n readOnly: isReadOnly,\n required: isRequired && validationBehavior === 'native',\n 'aria-required': (isRequired && validationBehavior === 'aria') || undefined,\n 'aria-invalid': isInvalid || undefined,\n 'aria-errormessage': props['aria-errormessage'],\n 'aria-activedescendant': props['aria-activedescendant'],\n 'aria-autocomplete': props['aria-autocomplete'],\n 'aria-haspopup': props['aria-haspopup'],\n value,\n onChange: (e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value),\n autoComplete: props.autoComplete,\n autoCapitalize: props.autoCapitalize,\n maxLength: props.maxLength,\n minLength: props.minLength,\n name: props.name,\n placeholder: props.placeholder,\n inputMode: props.inputMode,\n\n // Clipboard events\n onCopy: props.onCopy,\n onCut: props.onCut,\n onPaste: props.onPaste,\n\n // Composition events\n onCompositionEnd: props.onCompositionEnd,\n onCompositionStart: props.onCompositionStart,\n onCompositionUpdate: props.onCompositionUpdate,\n\n // Selection events\n onSelect: props.onSelect,\n\n // Input events\n onBeforeInput: props.onBeforeInput,\n onInput: props.onInput,\n ...focusableProps,\n ...fieldProps\n }\n ),\n descriptionProps,\n errorMessageProps,\n isInvalid,\n validationErrors,\n validationDetails\n };\n}\n"],"names":[],"version":3,"file":"useTextField.main.js.map"}
@@ -0,0 +1,115 @@
1
+ import {useEffect as $ig234$useEffect} from "react";
2
+ import {filterDOMProps as $ig234$filterDOMProps, useFormReset as $ig234$useFormReset, getOwnerWindow as $ig234$getOwnerWindow, mergeProps as $ig234$mergeProps} from "@react-aria/utils";
3
+ import {useControlledState as $ig234$useControlledState} from "@react-stately/utils";
4
+ import {useField as $ig234$useField} from "@react-aria/label";
5
+ import {useFocusable as $ig234$useFocusable} from "@react-aria/focus";
6
+ import {useFormValidation as $ig234$useFormValidation} from "@react-aria/form";
7
+ import {useFormValidationState as $ig234$useFormValidationState} from "@react-stately/form";
8
+
9
+ /*
10
+ * Copyright 2020 Adobe. All rights reserved.
11
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License. You may obtain a copy
13
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software distributed under
16
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
17
+ * OF ANY KIND, either express or implied. See the License for the specific language
18
+ * governing permissions and limitations under the License.
19
+ */
20
+
21
+
22
+
23
+
24
+
25
+
26
+ function $2d73ec29415bd339$export$712718f7aec83d5(props, ref) {
27
+ let { inputElementType: inputElementType = 'input', isDisabled: isDisabled = false, isRequired: isRequired = false, isReadOnly: isReadOnly = false, type: type = 'text', validationBehavior: validationBehavior = 'aria' } = props;
28
+ let [value, setValue] = (0, $ig234$useControlledState)(props.value, props.defaultValue || '', props.onChange);
29
+ let { focusableProps: focusableProps } = (0, $ig234$useFocusable)(props, ref);
30
+ let validationState = (0, $ig234$useFormValidationState)({
31
+ ...props,
32
+ value: value
33
+ });
34
+ let { isInvalid: isInvalid, validationErrors: validationErrors, validationDetails: validationDetails } = validationState.displayValidation;
35
+ let { labelProps: labelProps, fieldProps: fieldProps, descriptionProps: descriptionProps, errorMessageProps: errorMessageProps } = (0, $ig234$useField)({
36
+ ...props,
37
+ isInvalid: isInvalid,
38
+ errorMessage: props.errorMessage || validationErrors
39
+ });
40
+ let domProps = (0, $ig234$filterDOMProps)(props, {
41
+ labelable: true
42
+ });
43
+ const inputOnlyProps = {
44
+ type: type,
45
+ pattern: props.pattern
46
+ };
47
+ (0, $ig234$useFormReset)(ref, value, setValue);
48
+ (0, $ig234$useFormValidation)(props, validationState, ref);
49
+ (0, $ig234$useEffect)(()=>{
50
+ // This works around a React/Chrome bug that prevents textarea elements from validating when controlled.
51
+ // We prevent React from updating defaultValue (i.e. children) of textarea when `value` changes,
52
+ // which causes Chrome to skip validation. Only updating `value` is ok in our case since our
53
+ // textareas are always controlled. React is planning on removing this synchronization in a
54
+ // future major version.
55
+ // https://github.com/facebook/react/issues/19474
56
+ // https://github.com/facebook/react/issues/11896
57
+ if (ref.current instanceof (0, $ig234$getOwnerWindow)(ref.current).HTMLTextAreaElement) {
58
+ let input = ref.current;
59
+ Object.defineProperty(input, 'defaultValue', {
60
+ get: ()=>input.value,
61
+ set: ()=>{},
62
+ configurable: true
63
+ });
64
+ }
65
+ }, [
66
+ ref
67
+ ]);
68
+ return {
69
+ labelProps: labelProps,
70
+ inputProps: (0, $ig234$mergeProps)(domProps, inputElementType === 'input' ? inputOnlyProps : undefined, {
71
+ disabled: isDisabled,
72
+ readOnly: isReadOnly,
73
+ required: isRequired && validationBehavior === 'native',
74
+ 'aria-required': isRequired && validationBehavior === 'aria' || undefined,
75
+ 'aria-invalid': isInvalid || undefined,
76
+ 'aria-errormessage': props['aria-errormessage'],
77
+ 'aria-activedescendant': props['aria-activedescendant'],
78
+ 'aria-autocomplete': props['aria-autocomplete'],
79
+ 'aria-haspopup': props['aria-haspopup'],
80
+ value: value,
81
+ onChange: (e)=>setValue(e.target.value),
82
+ autoComplete: props.autoComplete,
83
+ autoCapitalize: props.autoCapitalize,
84
+ maxLength: props.maxLength,
85
+ minLength: props.minLength,
86
+ name: props.name,
87
+ placeholder: props.placeholder,
88
+ inputMode: props.inputMode,
89
+ // Clipboard events
90
+ onCopy: props.onCopy,
91
+ onCut: props.onCut,
92
+ onPaste: props.onPaste,
93
+ // Composition events
94
+ onCompositionEnd: props.onCompositionEnd,
95
+ onCompositionStart: props.onCompositionStart,
96
+ onCompositionUpdate: props.onCompositionUpdate,
97
+ // Selection events
98
+ onSelect: props.onSelect,
99
+ // Input events
100
+ onBeforeInput: props.onBeforeInput,
101
+ onInput: props.onInput,
102
+ ...focusableProps,
103
+ ...fieldProps
104
+ }),
105
+ descriptionProps: descriptionProps,
106
+ errorMessageProps: errorMessageProps,
107
+ isInvalid: isInvalid,
108
+ validationErrors: validationErrors,
109
+ validationDetails: validationDetails
110
+ };
111
+ }
112
+
113
+
114
+ export {$2d73ec29415bd339$export$712718f7aec83d5 as useTextField};
115
+ //# sourceMappingURL=useTextField.module.js.map
@@ -0,0 +1,115 @@
1
+ import {useEffect as $ig234$useEffect} from "react";
2
+ import {filterDOMProps as $ig234$filterDOMProps, useFormReset as $ig234$useFormReset, getOwnerWindow as $ig234$getOwnerWindow, mergeProps as $ig234$mergeProps} from "@react-aria/utils";
3
+ import {useControlledState as $ig234$useControlledState} from "@react-stately/utils";
4
+ import {useField as $ig234$useField} from "@react-aria/label";
5
+ import {useFocusable as $ig234$useFocusable} from "@react-aria/focus";
6
+ import {useFormValidation as $ig234$useFormValidation} from "@react-aria/form";
7
+ import {useFormValidationState as $ig234$useFormValidationState} from "@react-stately/form";
8
+
9
+ /*
10
+ * Copyright 2020 Adobe. All rights reserved.
11
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License. You may obtain a copy
13
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software distributed under
16
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
17
+ * OF ANY KIND, either express or implied. See the License for the specific language
18
+ * governing permissions and limitations under the License.
19
+ */
20
+
21
+
22
+
23
+
24
+
25
+
26
+ function $2d73ec29415bd339$export$712718f7aec83d5(props, ref) {
27
+ let { inputElementType: inputElementType = 'input', isDisabled: isDisabled = false, isRequired: isRequired = false, isReadOnly: isReadOnly = false, type: type = 'text', validationBehavior: validationBehavior = 'aria' } = props;
28
+ let [value, setValue] = (0, $ig234$useControlledState)(props.value, props.defaultValue || '', props.onChange);
29
+ let { focusableProps: focusableProps } = (0, $ig234$useFocusable)(props, ref);
30
+ let validationState = (0, $ig234$useFormValidationState)({
31
+ ...props,
32
+ value: value
33
+ });
34
+ let { isInvalid: isInvalid, validationErrors: validationErrors, validationDetails: validationDetails } = validationState.displayValidation;
35
+ let { labelProps: labelProps, fieldProps: fieldProps, descriptionProps: descriptionProps, errorMessageProps: errorMessageProps } = (0, $ig234$useField)({
36
+ ...props,
37
+ isInvalid: isInvalid,
38
+ errorMessage: props.errorMessage || validationErrors
39
+ });
40
+ let domProps = (0, $ig234$filterDOMProps)(props, {
41
+ labelable: true
42
+ });
43
+ const inputOnlyProps = {
44
+ type: type,
45
+ pattern: props.pattern
46
+ };
47
+ (0, $ig234$useFormReset)(ref, value, setValue);
48
+ (0, $ig234$useFormValidation)(props, validationState, ref);
49
+ (0, $ig234$useEffect)(()=>{
50
+ // This works around a React/Chrome bug that prevents textarea elements from validating when controlled.
51
+ // We prevent React from updating defaultValue (i.e. children) of textarea when `value` changes,
52
+ // which causes Chrome to skip validation. Only updating `value` is ok in our case since our
53
+ // textareas are always controlled. React is planning on removing this synchronization in a
54
+ // future major version.
55
+ // https://github.com/facebook/react/issues/19474
56
+ // https://github.com/facebook/react/issues/11896
57
+ if (ref.current instanceof (0, $ig234$getOwnerWindow)(ref.current).HTMLTextAreaElement) {
58
+ let input = ref.current;
59
+ Object.defineProperty(input, 'defaultValue', {
60
+ get: ()=>input.value,
61
+ set: ()=>{},
62
+ configurable: true
63
+ });
64
+ }
65
+ }, [
66
+ ref
67
+ ]);
68
+ return {
69
+ labelProps: labelProps,
70
+ inputProps: (0, $ig234$mergeProps)(domProps, inputElementType === 'input' ? inputOnlyProps : undefined, {
71
+ disabled: isDisabled,
72
+ readOnly: isReadOnly,
73
+ required: isRequired && validationBehavior === 'native',
74
+ 'aria-required': isRequired && validationBehavior === 'aria' || undefined,
75
+ 'aria-invalid': isInvalid || undefined,
76
+ 'aria-errormessage': props['aria-errormessage'],
77
+ 'aria-activedescendant': props['aria-activedescendant'],
78
+ 'aria-autocomplete': props['aria-autocomplete'],
79
+ 'aria-haspopup': props['aria-haspopup'],
80
+ value: value,
81
+ onChange: (e)=>setValue(e.target.value),
82
+ autoComplete: props.autoComplete,
83
+ autoCapitalize: props.autoCapitalize,
84
+ maxLength: props.maxLength,
85
+ minLength: props.minLength,
86
+ name: props.name,
87
+ placeholder: props.placeholder,
88
+ inputMode: props.inputMode,
89
+ // Clipboard events
90
+ onCopy: props.onCopy,
91
+ onCut: props.onCut,
92
+ onPaste: props.onPaste,
93
+ // Composition events
94
+ onCompositionEnd: props.onCompositionEnd,
95
+ onCompositionStart: props.onCompositionStart,
96
+ onCompositionUpdate: props.onCompositionUpdate,
97
+ // Selection events
98
+ onSelect: props.onSelect,
99
+ // Input events
100
+ onBeforeInput: props.onBeforeInput,
101
+ onInput: props.onInput,
102
+ ...focusableProps,
103
+ ...fieldProps
104
+ }),
105
+ descriptionProps: descriptionProps,
106
+ errorMessageProps: errorMessageProps,
107
+ isInvalid: isInvalid,
108
+ validationErrors: validationErrors,
109
+ validationDetails: validationDetails
110
+ };
111
+ }
112
+
113
+
114
+ export {$2d73ec29415bd339$export$712718f7aec83d5 as useTextField};
115
+ //# sourceMappingURL=useTextField.module.js.map
@@ -0,0 +1 @@
1
+ {"mappings":";;;;;;;;AAAA;;;;;;;;;;CAUC;;;;;;;AAmGM,SAAS,yCACd,KAA8B,EAC9B,GAA0B;IAE1B,IAAI,oBACF,mBAAmB,qBACnB,aAAa,mBACb,aAAa,mBACb,aAAa,aACb,OAAO,4BACP,qBAAqB,QACtB,GAAqD;IACtD,IAAI,CAAC,OAAO,SAAS,GAAG,CAAA,GAAA,yBAAiB,EAAU,MAAM,KAAK,EAAE,MAAM,YAAY,IAAI,IAAI,MAAM,QAAQ;IACxG,IAAI,kBAAC,cAAc,EAAC,GAAG,CAAA,GAAA,mBAAW,EAAE,OAAO;IAC3C,IAAI,kBAAkB,CAAA,GAAA,6BAAqB,EAAE;QAC3C,GAAG,KAAK;eACR;IACF;IACA,IAAI,aAAC,SAAS,oBAAE,gBAAgB,qBAAE,iBAAiB,EAAC,GAAG,gBAAgB,iBAAiB;IACxF,IAAI,cAAC,UAAU,cAAE,UAAU,oBAAE,gBAAgB,qBAAE,iBAAiB,EAAC,GAAG,CAAA,GAAA,eAAO,EAAE;QAC3E,GAAG,KAAK;mBACR;QACA,cAAc,MAAM,YAAY,IAAI;IACtC;IACA,IAAI,WAAW,CAAA,GAAA,qBAAa,EAAE,OAAO;QAAC,WAAW;IAAI;IAErD,MAAM,iBAAiB;cACrB;QACA,SAAS,MAAM,OAAO;IACxB;IAEA,CAAA,GAAA,mBAAW,EAAE,KAAK,OAAO;IACzB,CAAA,GAAA,wBAAgB,EAAE,OAAO,iBAAiB;IAE1C,CAAA,GAAA,gBAAQ,EAAE;QACR,wGAAwG;QACxG,gGAAgG;QAChG,4FAA4F;QAC5F,2FAA2F;QAC3F,wBAAwB;QACxB,iDAAiD;QACjD,iDAAiD;QACjD,IAAI,IAAI,OAAO,YAAY,CAAA,GAAA,qBAAa,EAAE,IAAI,OAAO,EAAE,mBAAmB,EAAE;YAC1E,IAAI,QAAQ,IAAI,OAAO;YACvB,OAAO,cAAc,CAAC,OAAO,gBAAgB;gBAC3C,KAAK,IAAM,MAAM,KAAK;gBACtB,KAAK,KAAO;gBACZ,cAAc;YAChB;QACF;IACF,GAAG;QAAC;KAAI;IAER,OAAO;oBACL;QACA,YAAY,CAAA,GAAA,iBAAS,EACnB,UACA,qBAAqB,UAAU,iBAAiB,WAChD;YACE,UAAU;YACV,UAAU;YACV,UAAU,cAAc,uBAAuB;YAC/C,iBAAiB,AAAC,cAAc,uBAAuB,UAAW;YAClE,gBAAgB,aAAa;YAC7B,qBAAqB,KAAK,CAAC,oBAAoB;YAC/C,yBAAyB,KAAK,CAAC,wBAAwB;YACvD,qBAAqB,KAAK,CAAC,oBAAoB;YAC/C,iBAAiB,KAAK,CAAC,gBAAgB;mBACvC;YACA,UAAU,CAAC,IAAqC,SAAS,EAAE,MAAM,CAAC,KAAK;YACvE,cAAc,MAAM,YAAY;YAChC,gBAAgB,MAAM,cAAc;YACpC,WAAW,MAAM,SAAS;YAC1B,WAAW,MAAM,SAAS;YAC1B,MAAM,MAAM,IAAI;YAChB,aAAa,MAAM,WAAW;YAC9B,WAAW,MAAM,SAAS;YAE1B,mBAAmB;YACnB,QAAQ,MAAM,MAAM;YACpB,OAAO,MAAM,KAAK;YAClB,SAAS,MAAM,OAAO;YAEtB,qBAAqB;YACrB,kBAAkB,MAAM,gBAAgB;YACxC,oBAAoB,MAAM,kBAAkB;YAC5C,qBAAqB,MAAM,mBAAmB;YAE9C,mBAAmB;YACnB,UAAU,MAAM,QAAQ;YAExB,eAAe;YACf,eAAe,MAAM,aAAa;YAClC,SAAS,MAAM,OAAO;YACtB,GAAG,cAAc;YACjB,GAAG,UAAU;QACf;0BAEF;2BACA;mBACA;0BACA;2BACA;IACF;AACF","sources":["packages/@react-aria/textfield/src/useTextField.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AriaTextFieldProps} from '@react-types/textfield';\nimport {\n ChangeEvent,\n HTMLAttributes,\n type JSX,\n LabelHTMLAttributes,\n RefObject,\n useEffect\n} from 'react';\nimport {DOMAttributes, ValidationResult} from '@react-types/shared';\nimport {filterDOMProps, getOwnerWindow, mergeProps, useFormReset} from '@react-aria/utils';\nimport {useControlledState} from '@react-stately/utils';\nimport {useField} from '@react-aria/label';\nimport {useFocusable} from '@react-aria/focus';\nimport {useFormValidation} from '@react-aria/form';\nimport {useFormValidationState} from '@react-stately/form';\n\n/**\n * A map of HTML element names and their interface types.\n * For example `'a'` -> `HTMLAnchorElement`.\n */\ntype IntrinsicHTMLElements = {\n [K in keyof IntrinsicHTMLAttributes]: IntrinsicHTMLAttributes[K] extends HTMLAttributes<infer T> ? T : never\n};\n\n/**\n * A map of HTML element names and their attribute interface types.\n * For example `'a'` -> `AnchorHTMLAttributes<HTMLAnchorElement>`.\n */\ntype IntrinsicHTMLAttributes = JSX.IntrinsicElements;\n\ntype DefaultElementType = 'input';\n\n/**\n * The intrinsic HTML element names that `useTextField` supports; e.g. `input`,\n * `textarea`.\n */\ntype TextFieldIntrinsicElements = keyof Pick<IntrinsicHTMLElements, 'input' | 'textarea'>;\n\n/**\n * The HTML element interfaces that `useTextField` supports based on what is\n * defined for `TextFieldIntrinsicElements`; e.g. `HTMLInputElement`,\n * `HTMLTextAreaElement`.\n */\ntype TextFieldHTMLElementType = Pick<IntrinsicHTMLElements, TextFieldIntrinsicElements>;\n\n/**\n * The HTML attributes interfaces that `useTextField` supports based on what\n * is defined for `TextFieldIntrinsicElements`; e.g. `InputHTMLAttributes`,\n * `TextareaHTMLAttributes`.\n */\ntype TextFieldHTMLAttributesType = Pick<IntrinsicHTMLAttributes, TextFieldIntrinsicElements>;\n\n/**\n * The type of `inputProps` returned by `useTextField`; e.g. `InputHTMLAttributes`,\n * `TextareaHTMLAttributes`.\n */\ntype TextFieldInputProps<T extends TextFieldIntrinsicElements> = TextFieldHTMLAttributesType[T];\n\nexport interface AriaTextFieldOptions<T extends TextFieldIntrinsicElements> extends AriaTextFieldProps {\n /**\n * The HTML element used to render the input, e.g. 'input', or 'textarea'.\n * It determines whether certain HTML attributes will be included in `inputProps`.\n * For example, [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-type).\n * @default 'input'\n */\n inputElementType?: T,\n /**\n * Controls whether inputted text is automatically capitalized and, if so, in what manner.\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize).\n */\n autoCapitalize?: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters'\n}\n\n/**\n * The type of `ref` object that can be passed to `useTextField` based on the given\n * intrinsic HTML element name; e.g.`RefObject<HTMLInputElement>`,\n * `RefObject<HTMLTextAreaElement>`.\n */\ntype TextFieldRefObject<T extends TextFieldIntrinsicElements> = RefObject<TextFieldHTMLElementType[T] | null>;\n\nexport interface TextFieldAria<T extends TextFieldIntrinsicElements = DefaultElementType> extends ValidationResult {\n /** Props for the input element. */\n inputProps: TextFieldInputProps<T>,\n /** Props for the text field's visible label element, if any. */\n labelProps: DOMAttributes | LabelHTMLAttributes<HTMLLabelElement>,\n /** Props for the text field's description element, if any. */\n descriptionProps: DOMAttributes,\n /** Props for the text field's error message element, if any. */\n errorMessageProps: DOMAttributes\n}\n\n/**\n * Provides the behavior and accessibility implementation for a text field.\n * @param props - Props for the text field.\n * @param ref - Ref to the HTML input or textarea element.\n */\nexport function useTextField<T extends TextFieldIntrinsicElements = DefaultElementType>(\n props: AriaTextFieldOptions<T>,\n ref: TextFieldRefObject<T>\n): TextFieldAria<T> {\n let {\n inputElementType = 'input',\n isDisabled = false,\n isRequired = false,\n isReadOnly = false,\n type = 'text',\n validationBehavior = 'aria'\n }: AriaTextFieldOptions<TextFieldIntrinsicElements> = props;\n let [value, setValue] = useControlledState<string>(props.value, props.defaultValue || '', props.onChange);\n let {focusableProps} = useFocusable(props, ref);\n let validationState = useFormValidationState({\n ...props,\n value\n });\n let {isInvalid, validationErrors, validationDetails} = validationState.displayValidation;\n let {labelProps, fieldProps, descriptionProps, errorMessageProps} = useField({\n ...props,\n isInvalid,\n errorMessage: props.errorMessage || validationErrors\n });\n let domProps = filterDOMProps(props, {labelable: true});\n\n const inputOnlyProps = {\n type,\n pattern: props.pattern\n };\n\n useFormReset(ref, value, setValue);\n useFormValidation(props, validationState, ref);\n\n useEffect(() => {\n // This works around a React/Chrome bug that prevents textarea elements from validating when controlled.\n // We prevent React from updating defaultValue (i.e. children) of textarea when `value` changes,\n // which causes Chrome to skip validation. Only updating `value` is ok in our case since our\n // textareas are always controlled. React is planning on removing this synchronization in a\n // future major version.\n // https://github.com/facebook/react/issues/19474\n // https://github.com/facebook/react/issues/11896\n if (ref.current instanceof getOwnerWindow(ref.current).HTMLTextAreaElement) {\n let input = ref.current;\n Object.defineProperty(input, 'defaultValue', {\n get: () => input.value,\n set: () => {},\n configurable: true\n });\n }\n }, [ref]);\n\n return {\n labelProps,\n inputProps: mergeProps(\n domProps,\n inputElementType === 'input' ? inputOnlyProps : undefined,\n {\n disabled: isDisabled,\n readOnly: isReadOnly,\n required: isRequired && validationBehavior === 'native',\n 'aria-required': (isRequired && validationBehavior === 'aria') || undefined,\n 'aria-invalid': isInvalid || undefined,\n 'aria-errormessage': props['aria-errormessage'],\n 'aria-activedescendant': props['aria-activedescendant'],\n 'aria-autocomplete': props['aria-autocomplete'],\n 'aria-haspopup': props['aria-haspopup'],\n value,\n onChange: (e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value),\n autoComplete: props.autoComplete,\n autoCapitalize: props.autoCapitalize,\n maxLength: props.maxLength,\n minLength: props.minLength,\n name: props.name,\n placeholder: props.placeholder,\n inputMode: props.inputMode,\n\n // Clipboard events\n onCopy: props.onCopy,\n onCut: props.onCut,\n onPaste: props.onPaste,\n\n // Composition events\n onCompositionEnd: props.onCompositionEnd,\n onCompositionStart: props.onCompositionStart,\n onCompositionUpdate: props.onCompositionUpdate,\n\n // Selection events\n onSelect: props.onSelect,\n\n // Input events\n onBeforeInput: props.onBeforeInput,\n onInput: props.onInput,\n ...focusableProps,\n ...fieldProps\n }\n ),\n descriptionProps,\n errorMessageProps,\n isInvalid,\n validationErrors,\n validationDetails\n };\n}\n"],"names":[],"version":3,"file":"useTextField.module.js.map"}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@react-aria/textfield",
3
+ "version": "3.0.0-nightly-641446f65-240905",
4
+ "description": "Spectrum UI components in React",
5
+ "license": "Apache-2.0",
6
+ "main": "dist/main.js",
7
+ "module": "dist/module.js",
8
+ "exports": {
9
+ "types": "./dist/types.d.ts",
10
+ "import": "./dist/import.mjs",
11
+ "require": "./dist/main.js"
12
+ },
13
+ "types": "dist/types.d.ts",
14
+ "source": "src/index.ts",
15
+ "files": [
16
+ "dist",
17
+ "src"
18
+ ],
19
+ "sideEffects": false,
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/adobe/react-spectrum"
23
+ },
24
+ "dependencies": {
25
+ "@react-aria/focus": "^3.0.0-nightly-641446f65-240905",
26
+ "@react-aria/form": "^3.0.0-nightly-641446f65-240905",
27
+ "@react-aria/label": "^3.0.0-nightly-641446f65-240905",
28
+ "@react-aria/utils": "^3.0.0-nightly-641446f65-240905",
29
+ "@react-stately/form": "^3.0.0-nightly-641446f65-240905",
30
+ "@react-stately/utils": "^3.0.0-nightly-641446f65-240905",
31
+ "@react-types/shared": "^3.0.0-nightly-641446f65-240905",
32
+ "@react-types/textfield": "^3.0.0-nightly-641446f65-240905",
33
+ "@swc/helpers": "^0.5.0"
34
+ },
35
+ "peerDependencies": {
36
+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "stableVersion": "3.14.8"
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
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
+ export type {TextFieldAria} from './useTextField';
13
+ export {useTextField} from './useTextField';
14
+ export {useFormattedTextField} from './useFormattedTextField';
15
+ export type {AriaTextFieldOptions} from './useTextField';
16
+ export type {AriaTextFieldProps} from '@react-types/textfield';
@@ -0,0 +1,161 @@
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 {mergeProps, useEffectEvent} from '@react-aria/utils';
15
+ import {RefObject} from '@react-types/shared';
16
+ import {TextFieldAria, useTextField} from './useTextField';
17
+ import {useEffect, useRef} from 'react';
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
+ // @ts-ignore
29
+ typeof InputEvent.prototype.getTargetRanges === 'function';
30
+ }
31
+
32
+ export function useFormattedTextField(props: AriaTextFieldProps, state: FormattedTextFieldState, inputRef: RefObject<HTMLInputElement | null>): TextFieldAria {
33
+ // All browsers implement the 'beforeinput' event natively except Firefox
34
+ // (currently behind a flag as of Firefox 84). React's polyfill does not
35
+ // run in all cases that the native event fires, e.g. when deleting text.
36
+ // Use the native event if available so that we can prevent invalid deletions.
37
+ // We do not attempt to polyfill this in Firefox since it would be very complicated,
38
+ // the benefit of doing so is fairly minor, and it's going to be natively supported soon.
39
+ let onBeforeInputFallback = useEffectEvent((e: InputEvent) => {
40
+ let input = inputRef.current;
41
+
42
+ // Compute the next value of the input if the event is allowed to proceed.
43
+ // See https://www.w3.org/TR/input-events-2/#interface-InputEvent-Attributes for a full list of input types.
44
+ let nextValue: string;
45
+ switch (e.inputType) {
46
+ case 'historyUndo':
47
+ case 'historyRedo':
48
+ // Explicitly allow undo/redo. e.data is null in this case, but there's no need to validate,
49
+ // because presumably the input would have already been validated previously.
50
+ return;
51
+ case 'insertLineBreak':
52
+ // Explicitly allow "insertLineBreak" event, to allow onSubmit for "enter" key. e.data is null in this case.
53
+ return;
54
+ case 'deleteContent':
55
+ case 'deleteByCut':
56
+ case 'deleteByDrag':
57
+ nextValue = input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
58
+ break;
59
+ case 'deleteContentForward':
60
+ // This is potentially incorrect, since the browser may actually delete more than a single UTF-16
61
+ // character. In reality, a full Unicode grapheme cluster consisting of multiple UTF-16 characters
62
+ // or code points may be deleted. However, in our currently supported locales, there are no such cases.
63
+ // If we support additional locales in the future, this may need to change.
64
+ nextValue = input.selectionEnd === input.selectionStart
65
+ ? input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd + 1)
66
+ : input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
67
+ break;
68
+ case 'deleteContentBackward':
69
+ nextValue = input.selectionEnd === input.selectionStart
70
+ ? input.value.slice(0, input.selectionStart - 1) + input.value.slice(input.selectionStart)
71
+ : input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
72
+ break;
73
+ case 'deleteSoftLineBackward':
74
+ case 'deleteHardLineBackward':
75
+ nextValue = input.value.slice(input.selectionStart);
76
+ break;
77
+ default:
78
+ if (e.data != null) {
79
+ nextValue =
80
+ input.value.slice(0, input.selectionStart) +
81
+ e.data +
82
+ input.value.slice(input.selectionEnd);
83
+ }
84
+ break;
85
+ }
86
+
87
+ // If we did not compute a value, or the new value is invalid, prevent the event
88
+ // so that the browser does not update the input text, move the selection, or add to
89
+ // the undo/redo stack.
90
+ if (nextValue == null || !state.validate(nextValue)) {
91
+ e.preventDefault();
92
+ }
93
+ });
94
+
95
+ useEffect(() => {
96
+ if (!supportsNativeBeforeInputEvent()) {
97
+ return;
98
+ }
99
+
100
+ let input = inputRef.current;
101
+ input.addEventListener('beforeinput', onBeforeInputFallback, false);
102
+ return () => {
103
+ input.removeEventListener('beforeinput', onBeforeInputFallback, false);
104
+ };
105
+ }, [inputRef, onBeforeInputFallback]);
106
+
107
+ let onBeforeInput = !supportsNativeBeforeInputEvent()
108
+ ? e => {
109
+ let nextValue =
110
+ e.target.value.slice(0, e.target.selectionStart) +
111
+ e.data +
112
+ e.target.value.slice(e.target.selectionEnd);
113
+
114
+ if (!state.validate(nextValue)) {
115
+ e.preventDefault();
116
+ }
117
+ }
118
+ : null;
119
+
120
+ let {labelProps, inputProps: textFieldProps, descriptionProps, errorMessageProps, ...validation} = useTextField(props, inputRef);
121
+
122
+ let compositionStartState = useRef(null);
123
+ return {
124
+ inputProps: mergeProps(
125
+ textFieldProps,
126
+ {
127
+ onBeforeInput,
128
+ onCompositionStart() {
129
+ // Chrome does not implement Input Events Level 2, which specifies the insertFromComposition
130
+ // and deleteByComposition inputType values for the beforeinput event. These are meant to occur
131
+ // at the end of a composition (e.g. Pinyin IME, Android auto correct, etc.), and crucially, are
132
+ // cancelable. The insertCompositionText and deleteCompositionText input types are not cancelable,
133
+ // nor would we want to cancel them because the input from the user is incomplete at that point.
134
+ // In Safari, insertFromComposition/deleteFromComposition will fire, however, allowing us to cancel
135
+ // the final composition result if it is invalid. As a fallback for Chrome and Firefox, which either
136
+ // don't support Input Events Level 2, or beforeinput at all, we store the state of the input when
137
+ // the compositionstart event fires, and undo the changes in compositionend (below) if it is invalid.
138
+ // Unfortunately, this messes up the undo/redo stack, but until insertFromComposition/deleteByComposition
139
+ // are implemented, there is no other way to prevent composed input.
140
+ // See https://bugs.chromium.org/p/chromium/issues/detail?id=1022204
141
+ let {value, selectionStart, selectionEnd} = inputRef.current;
142
+ compositionStartState.current = {value, selectionStart, selectionEnd};
143
+ },
144
+ onCompositionEnd() {
145
+ if (!state.validate(inputRef.current.value)) {
146
+ // Restore the input value in the DOM immediately so we can synchronously update the selection position.
147
+ // But also update the value in React state as well so it is correct for future updates.
148
+ let {value, selectionStart, selectionEnd} = compositionStartState.current;
149
+ inputRef.current.value = value;
150
+ inputRef.current.setSelectionRange(selectionStart, selectionEnd);
151
+ state.setInputValue(value);
152
+ }
153
+ }
154
+ }
155
+ ),
156
+ labelProps,
157
+ descriptionProps,
158
+ errorMessageProps,
159
+ ...validation
160
+ };
161
+ }