-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathHiddenSelect.tsx
More file actions
218 lines (194 loc) · 7.67 KB
/
HiddenSelect.tsx
File metadata and controls
218 lines (194 loc) · 7.67 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
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {FocusableElement, Key, RefObject} from '@react-types/shared';
import React, {InputHTMLAttributes, JSX, ReactNode, useCallback, useRef} from 'react';
import {selectData} from './useSelect';
import {SelectionMode} from '@react-types/select';
import {SelectState} from '@react-stately/select';
import {useFormReset} from '@react-aria/utils';
import {useFormValidation} from '@react-aria/form';
import {useVisuallyHidden} from '@react-aria/visually-hidden';
export interface AriaHiddenSelectProps {
/**
* Describes the type of autocomplete functionality the input should provide if any. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautocomplete).
*/
autoComplete?: string,
/** The text label for the select. */
label?: ReactNode,
/** HTML form input name. */
name?: string,
/**
* The `<form>` element to associate the input with.
* The value of this attribute must be the id of a `<form>` in the same document.
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form).
*/
form?: string,
/** Sets the disabled state of the select and input. */
isDisabled?: boolean
}
export interface HiddenSelectProps<T, M extends SelectionMode = 'single'> extends AriaHiddenSelectProps {
/** State for the select. */
state: SelectState<T, M>,
/** A ref to the trigger element. */
triggerRef: RefObject<FocusableElement | null>
}
export interface AriaHiddenSelectOptions extends AriaHiddenSelectProps {
/** A ref to the hidden `<select>` element. */
selectRef?: RefObject<HTMLSelectElement | HTMLInputElement | null>
}
export interface HiddenSelectAria {
/** Props for the container element. */
containerProps: React.HTMLAttributes<FocusableElement>,
/** Props for the hidden input element. */
inputProps: React.InputHTMLAttributes<HTMLInputElement>,
/** Props for the hidden select element. */
selectProps: React.SelectHTMLAttributes<HTMLSelectElement>
}
/**
* Provides the behavior and accessibility implementation for a hidden `<select>` element, which
* can be used in combination with `useSelect` to support browser form autofill, mobile form
* navigation, and native HTML form submission.
*/
export function useHiddenSelect<T, M extends SelectionMode = 'single'>(props: AriaHiddenSelectOptions, state: SelectState<T, M>, triggerRef: RefObject<FocusableElement | null>): HiddenSelectAria {
let data = selectData.get(state) || {};
let {autoComplete, name = data.name, form = data.form, isDisabled = data.isDisabled} = props;
let {validationBehavior, isRequired} = data;
let {visuallyHiddenProps} = useVisuallyHidden({
style: {
// Prevent page scrolling.
position: 'fixed',
top: 0,
left: 0
}
});
useFormReset(props.selectRef, state.defaultValue, state.setValue);
useFormValidation({
validationBehavior,
focus: () => triggerRef.current?.focus()
}, state, props.selectRef);
let setValue = state.setValue;
let onChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
if (e.target.multiple) {
setValue(Array.from(
e.target.selectedOptions,
(option) => option.value
) as any);
} else {
setValue(e.currentTarget.value as any);
}
}, [setValue]);
// In Safari, the <select> cannot have `display: none` or `hidden` for autofill to work.
// In Firefox, there must be a <label> to identify the <select> whereas other browsers
// seem to identify it just by surrounding text.
// The solution is to use <VisuallyHidden> to hide the elements, which clips the elements to a
// 1px rectangle. In addition, we hide from screen readers with aria-hidden, and make the <select>
// non tabbable with tabIndex={-1}.
return {
containerProps: {
...visuallyHiddenProps,
'aria-hidden': true,
// @ts-ignore
['data-react-aria-prevent-focus']: true,
// @ts-ignore
['data-a11y-ignore']: 'aria-hidden-focus'
},
inputProps: {
style: {display: 'none'}
},
selectProps: {
tabIndex: -1,
autoComplete,
disabled: isDisabled,
multiple: state.selectionManager.selectionMode === 'multiple',
required: validationBehavior === 'native' && isRequired,
name,
form,
value: (state.value as string | string[]) ?? '',
onChange,
onInput: onChange
}
};
}
/**
* Renders a hidden native `<select>` element, which can be used to support browser
* form autofill, mobile form navigation, and native form submission.
*/
export function HiddenSelect<T, M extends SelectionMode = 'single'>(props: HiddenSelectProps<T, M>): JSX.Element | null {
let {state, triggerRef, label, name, form, isDisabled} = props;
let selectRef = useRef(null);
let inputRef = useRef(null);
let {containerProps, selectProps} = useHiddenSelect({...props, selectRef: state.collection.size <= 300 ? selectRef : inputRef}, state, triggerRef);
// If used in a <form>, use a hidden input so the value can be submitted to a server.
// If the collection isn't too big, use a hidden <select> element for this so that browser
// autofill will work. Otherwise, use an <input type="hidden">.
if (state.collection.size <= 300) {
return (
<div {...containerProps} data-testid="hidden-select-container">
<label>
{label}
<select {...selectProps} ref={selectRef}>
<option />
{[...state.collection.getKeys()].map(key => {
let item = state.collection.getItem(key);
if (item && item.type === 'item') {
return (
<option
key={item.key}
value={item.key}>
{item.textValue}
</option>
);
}
})}
</select>
</label>
</div>
);
} else if (name) {
let data = selectData.get(state) || {};
let {validationBehavior} = data;
// Always render at least one hidden input to ensure required form submission.
let values: (Key | null)[] = Array.isArray(state.value) ? state.value : [state.value];
if (values.length === 0) {
values = [null];
}
let res = values.map((value, i) => {
let inputProps: InputHTMLAttributes<HTMLInputElement> = {
type: 'hidden',
autoComplete: selectProps.autoComplete,
name,
form,
disabled: isDisabled,
value: value ?? ''
};
if (validationBehavior === 'native') {
// Use a hidden <input type="text"> rather than <input type="hidden">
// so that an empty value blocks HTML form submission when the field is required.
return (
<input
key={i}
{...inputProps}
ref={i === 0 ? inputRef : null}
style={{display: 'none'}}
type="text"
required={i === 0 ? selectProps.required : false}
onChange={() => {/** Ignore react warning. */}} />
);
}
return (
<input key={i} {...inputProps} ref={i === 0 ? inputRef : null} />
);
});
return <>{res}</>;
}
return null;
}