@react-aria/datepicker 3.16.1 → 3.17.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.
Files changed (221) hide show
  1. package/dist/import.mjs +6 -6
  2. package/dist/main.js +11 -11
  3. package/dist/main.js.map +1 -1
  4. package/dist/module.js +6 -6
  5. package/dist/module.js.map +1 -1
  6. package/dist/types/src/index.d.ts +12 -0
  7. package/package.json +16 -28
  8. package/src/index.ts +13 -11
  9. package/dist/ar-AE.main.js +0 -21
  10. package/dist/ar-AE.main.js.map +0 -1
  11. package/dist/ar-AE.mjs +0 -23
  12. package/dist/ar-AE.module.js +0 -23
  13. package/dist/ar-AE.module.js.map +0 -1
  14. package/dist/bg-BG.main.js +0 -21
  15. package/dist/bg-BG.main.js.map +0 -1
  16. package/dist/bg-BG.mjs +0 -23
  17. package/dist/bg-BG.module.js +0 -23
  18. package/dist/bg-BG.module.js.map +0 -1
  19. package/dist/cs-CZ.main.js +0 -21
  20. package/dist/cs-CZ.main.js.map +0 -1
  21. package/dist/cs-CZ.mjs +0 -23
  22. package/dist/cs-CZ.module.js +0 -23
  23. package/dist/cs-CZ.module.js.map +0 -1
  24. package/dist/da-DK.main.js +0 -21
  25. package/dist/da-DK.main.js.map +0 -1
  26. package/dist/da-DK.mjs +0 -23
  27. package/dist/da-DK.module.js +0 -23
  28. package/dist/da-DK.module.js.map +0 -1
  29. package/dist/de-DE.main.js +0 -21
  30. package/dist/de-DE.main.js.map +0 -1
  31. package/dist/de-DE.mjs +0 -23
  32. package/dist/de-DE.module.js +0 -23
  33. package/dist/de-DE.module.js.map +0 -1
  34. package/dist/el-GR.main.js +0 -21
  35. package/dist/el-GR.main.js.map +0 -1
  36. package/dist/el-GR.mjs +0 -23
  37. package/dist/el-GR.module.js +0 -23
  38. package/dist/el-GR.module.js.map +0 -1
  39. package/dist/en-US.main.js +0 -21
  40. package/dist/en-US.main.js.map +0 -1
  41. package/dist/en-US.mjs +0 -23
  42. package/dist/en-US.module.js +0 -23
  43. package/dist/en-US.module.js.map +0 -1
  44. package/dist/es-ES.main.js +0 -21
  45. package/dist/es-ES.main.js.map +0 -1
  46. package/dist/es-ES.mjs +0 -23
  47. package/dist/es-ES.module.js +0 -23
  48. package/dist/es-ES.module.js.map +0 -1
  49. package/dist/et-EE.main.js +0 -21
  50. package/dist/et-EE.main.js.map +0 -1
  51. package/dist/et-EE.mjs +0 -23
  52. package/dist/et-EE.module.js +0 -23
  53. package/dist/et-EE.module.js.map +0 -1
  54. package/dist/fi-FI.main.js +0 -21
  55. package/dist/fi-FI.main.js.map +0 -1
  56. package/dist/fi-FI.mjs +0 -23
  57. package/dist/fi-FI.module.js +0 -23
  58. package/dist/fi-FI.module.js.map +0 -1
  59. package/dist/fr-FR.main.js +0 -21
  60. package/dist/fr-FR.main.js.map +0 -1
  61. package/dist/fr-FR.mjs +0 -23
  62. package/dist/fr-FR.module.js +0 -23
  63. package/dist/fr-FR.module.js.map +0 -1
  64. package/dist/he-IL.main.js +0 -21
  65. package/dist/he-IL.main.js.map +0 -1
  66. package/dist/he-IL.mjs +0 -23
  67. package/dist/he-IL.module.js +0 -23
  68. package/dist/he-IL.module.js.map +0 -1
  69. package/dist/hr-HR.main.js +0 -21
  70. package/dist/hr-HR.main.js.map +0 -1
  71. package/dist/hr-HR.mjs +0 -23
  72. package/dist/hr-HR.module.js +0 -23
  73. package/dist/hr-HR.module.js.map +0 -1
  74. package/dist/hu-HU.main.js +0 -21
  75. package/dist/hu-HU.main.js.map +0 -1
  76. package/dist/hu-HU.mjs +0 -23
  77. package/dist/hu-HU.module.js +0 -23
  78. package/dist/hu-HU.module.js.map +0 -1
  79. package/dist/intlStrings.main.js +0 -108
  80. package/dist/intlStrings.main.js.map +0 -1
  81. package/dist/intlStrings.mjs +0 -110
  82. package/dist/intlStrings.module.js +0 -110
  83. package/dist/intlStrings.module.js.map +0 -1
  84. package/dist/it-IT.main.js +0 -21
  85. package/dist/it-IT.main.js.map +0 -1
  86. package/dist/it-IT.mjs +0 -23
  87. package/dist/it-IT.module.js +0 -23
  88. package/dist/it-IT.module.js.map +0 -1
  89. package/dist/ja-JP.main.js +0 -21
  90. package/dist/ja-JP.main.js.map +0 -1
  91. package/dist/ja-JP.mjs +0 -23
  92. package/dist/ja-JP.module.js +0 -23
  93. package/dist/ja-JP.module.js.map +0 -1
  94. package/dist/ko-KR.main.js +0 -21
  95. package/dist/ko-KR.main.js.map +0 -1
  96. package/dist/ko-KR.mjs +0 -23
  97. package/dist/ko-KR.module.js +0 -23
  98. package/dist/ko-KR.module.js.map +0 -1
  99. package/dist/lt-LT.main.js +0 -21
  100. package/dist/lt-LT.main.js.map +0 -1
  101. package/dist/lt-LT.mjs +0 -23
  102. package/dist/lt-LT.module.js +0 -23
  103. package/dist/lt-LT.module.js.map +0 -1
  104. package/dist/lv-LV.main.js +0 -21
  105. package/dist/lv-LV.main.js.map +0 -1
  106. package/dist/lv-LV.mjs +0 -23
  107. package/dist/lv-LV.module.js +0 -23
  108. package/dist/lv-LV.module.js.map +0 -1
  109. package/dist/nb-NO.main.js +0 -21
  110. package/dist/nb-NO.main.js.map +0 -1
  111. package/dist/nb-NO.mjs +0 -23
  112. package/dist/nb-NO.module.js +0 -23
  113. package/dist/nb-NO.module.js.map +0 -1
  114. package/dist/nl-NL.main.js +0 -21
  115. package/dist/nl-NL.main.js.map +0 -1
  116. package/dist/nl-NL.mjs +0 -23
  117. package/dist/nl-NL.module.js +0 -23
  118. package/dist/nl-NL.module.js.map +0 -1
  119. package/dist/pl-PL.main.js +0 -21
  120. package/dist/pl-PL.main.js.map +0 -1
  121. package/dist/pl-PL.mjs +0 -23
  122. package/dist/pl-PL.module.js +0 -23
  123. package/dist/pl-PL.module.js.map +0 -1
  124. package/dist/pt-BR.main.js +0 -21
  125. package/dist/pt-BR.main.js.map +0 -1
  126. package/dist/pt-BR.mjs +0 -23
  127. package/dist/pt-BR.module.js +0 -23
  128. package/dist/pt-BR.module.js.map +0 -1
  129. package/dist/pt-PT.main.js +0 -21
  130. package/dist/pt-PT.main.js.map +0 -1
  131. package/dist/pt-PT.mjs +0 -23
  132. package/dist/pt-PT.module.js +0 -23
  133. package/dist/pt-PT.module.js.map +0 -1
  134. package/dist/ro-RO.main.js +0 -21
  135. package/dist/ro-RO.main.js.map +0 -1
  136. package/dist/ro-RO.mjs +0 -23
  137. package/dist/ro-RO.module.js +0 -23
  138. package/dist/ro-RO.module.js.map +0 -1
  139. package/dist/ru-RU.main.js +0 -21
  140. package/dist/ru-RU.main.js.map +0 -1
  141. package/dist/ru-RU.mjs +0 -23
  142. package/dist/ru-RU.module.js +0 -23
  143. package/dist/ru-RU.module.js.map +0 -1
  144. package/dist/sk-SK.main.js +0 -21
  145. package/dist/sk-SK.main.js.map +0 -1
  146. package/dist/sk-SK.mjs +0 -23
  147. package/dist/sk-SK.module.js +0 -23
  148. package/dist/sk-SK.module.js.map +0 -1
  149. package/dist/sl-SI.main.js +0 -21
  150. package/dist/sl-SI.main.js.map +0 -1
  151. package/dist/sl-SI.mjs +0 -23
  152. package/dist/sl-SI.module.js +0 -23
  153. package/dist/sl-SI.module.js.map +0 -1
  154. package/dist/sr-SP.main.js +0 -21
  155. package/dist/sr-SP.main.js.map +0 -1
  156. package/dist/sr-SP.mjs +0 -23
  157. package/dist/sr-SP.module.js +0 -23
  158. package/dist/sr-SP.module.js.map +0 -1
  159. package/dist/sv-SE.main.js +0 -21
  160. package/dist/sv-SE.main.js.map +0 -1
  161. package/dist/sv-SE.mjs +0 -23
  162. package/dist/sv-SE.module.js +0 -23
  163. package/dist/sv-SE.module.js.map +0 -1
  164. package/dist/tr-TR.main.js +0 -21
  165. package/dist/tr-TR.main.js.map +0 -1
  166. package/dist/tr-TR.mjs +0 -23
  167. package/dist/tr-TR.module.js +0 -23
  168. package/dist/tr-TR.module.js.map +0 -1
  169. package/dist/types.d.ts +0 -108
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/uk-UA.main.js +0 -21
  172. package/dist/uk-UA.main.js.map +0 -1
  173. package/dist/uk-UA.mjs +0 -23
  174. package/dist/uk-UA.module.js +0 -23
  175. package/dist/uk-UA.module.js.map +0 -1
  176. package/dist/useDateField.main.js +0 -181
  177. package/dist/useDateField.main.js.map +0 -1
  178. package/dist/useDateField.mjs +0 -172
  179. package/dist/useDateField.module.js +0 -172
  180. package/dist/useDateField.module.js.map +0 -1
  181. package/dist/useDatePicker.main.js +0 -178
  182. package/dist/useDatePicker.main.js.map +0 -1
  183. package/dist/useDatePicker.mjs +0 -173
  184. package/dist/useDatePicker.module.js +0 -173
  185. package/dist/useDatePicker.module.js.map +0 -1
  186. package/dist/useDatePickerGroup.main.js +0 -120
  187. package/dist/useDatePickerGroup.main.js.map +0 -1
  188. package/dist/useDatePickerGroup.mjs +0 -115
  189. package/dist/useDatePickerGroup.module.js +0 -115
  190. package/dist/useDatePickerGroup.module.js.map +0 -1
  191. package/dist/useDateRangePicker.main.js +0 -224
  192. package/dist/useDateRangePicker.main.js.map +0 -1
  193. package/dist/useDateRangePicker.mjs +0 -219
  194. package/dist/useDateRangePicker.module.js +0 -219
  195. package/dist/useDateRangePicker.module.js.map +0 -1
  196. package/dist/useDateSegment.main.js +0 -370
  197. package/dist/useDateSegment.main.js.map +0 -1
  198. package/dist/useDateSegment.mjs +0 -361
  199. package/dist/useDateSegment.module.js +0 -361
  200. package/dist/useDateSegment.module.js.map +0 -1
  201. package/dist/useDisplayNames.main.js +0 -58
  202. package/dist/useDisplayNames.main.js.map +0 -1
  203. package/dist/useDisplayNames.mjs +0 -53
  204. package/dist/useDisplayNames.module.js +0 -53
  205. package/dist/useDisplayNames.module.js.map +0 -1
  206. package/dist/zh-CN.main.js +0 -21
  207. package/dist/zh-CN.main.js.map +0 -1
  208. package/dist/zh-CN.mjs +0 -23
  209. package/dist/zh-CN.module.js +0 -23
  210. package/dist/zh-CN.module.js.map +0 -1
  211. package/dist/zh-TW.main.js +0 -21
  212. package/dist/zh-TW.main.js.map +0 -1
  213. package/dist/zh-TW.mjs +0 -23
  214. package/dist/zh-TW.module.js +0 -23
  215. package/dist/zh-TW.module.js.map +0 -1
  216. package/src/useDateField.ts +0 -213
  217. package/src/useDatePicker.ts +0 -192
  218. package/src/useDatePickerGroup.ts +0 -138
  219. package/src/useDateRangePicker.ts +0 -243
  220. package/src/useDateSegment.ts +0 -413
  221. package/src/useDisplayNames.ts +0 -51
@@ -1,243 +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 {AriaButtonProps} from '@react-types/button';
14
- import {AriaDatePickerProps, AriaDateRangePickerProps, DateValue} from '@react-types/datepicker';
15
- import {AriaDialogProps} from '@react-types/dialog';
16
- import {createFocusManager} from '@react-aria/focus';
17
- import {DateRange, RangeCalendarProps} from '@react-types/calendar';
18
- import {DateRangePickerState} from '@react-stately/datepicker';
19
- import {DEFAULT_VALIDATION_RESULT, mergeValidation, privateValidationStateProp} from '@react-stately/form';
20
- import {DOMAttributes, GroupDOMAttributes, KeyboardEvent, RefObject, ValidationResult} from '@react-types/shared';
21
- import {filterDOMProps, mergeProps, nodeContains, useDescription, useId} from '@react-aria/utils';
22
- import {focusManagerSymbol, roleSymbol} from './useDateField';
23
- // @ts-ignore
24
- import intlMessages from '../intl/*.json';
25
- import {useDatePickerGroup} from './useDatePickerGroup';
26
- import {useField} from '@react-aria/label';
27
- import {useFocusWithin} from '@react-aria/interactions';
28
- import {useLocale, useLocalizedStringFormatter} from '@react-aria/i18n';
29
- import {useMemo, useRef} from 'react';
30
-
31
- export interface DateRangePickerAria extends ValidationResult {
32
- /** Props for the date range picker's visible label element, if any. */
33
- labelProps: DOMAttributes,
34
- /** Props for the grouping element containing the date fields and button. */
35
- groupProps: GroupDOMAttributes,
36
- /** Props for the start date field. */
37
- startFieldProps: AriaDatePickerProps<DateValue>,
38
- /** Props for the end date field. */
39
- endFieldProps: AriaDatePickerProps<DateValue>,
40
- /** Props for the popover trigger button. */
41
- buttonProps: AriaButtonProps,
42
- /** Props for the description element, if any. */
43
- descriptionProps: DOMAttributes,
44
- /** Props for the error message element, if any. */
45
- errorMessageProps: DOMAttributes,
46
- /** Props for the popover dialog. */
47
- dialogProps: AriaDialogProps,
48
- /** Props for the range calendar within the popover dialog. */
49
- calendarProps: RangeCalendarProps<DateValue>
50
- }
51
-
52
- /**
53
- * Provides the behavior and accessibility implementation for a date picker component.
54
- * A date range picker combines two DateFields and a RangeCalendar popover to allow
55
- * users to enter or select a date and time range.
56
- */
57
- export function useDateRangePicker<T extends DateValue>(props: AriaDateRangePickerProps<T>, state: DateRangePickerState, ref: RefObject<Element | null>): DateRangePickerAria {
58
- let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-aria/datepicker');
59
- let {isInvalid, validationErrors, validationDetails} = state.displayValidation;
60
- let {labelProps, fieldProps, descriptionProps, errorMessageProps} = useField({
61
- ...props,
62
- labelElementType: 'span',
63
- isInvalid,
64
- errorMessage: props.errorMessage || validationErrors
65
- });
66
-
67
- let labelledBy = fieldProps['aria-labelledby'] || fieldProps.id;
68
-
69
- let {locale} = useLocale();
70
- let range = state.formatValue(locale, {month: 'long'});
71
- let description = range ? stringFormatter.format('selectedRangeDescription', {startDate: range.start, endDate: range.end}) : '';
72
- let descProps = useDescription(description);
73
-
74
- let startFieldProps = {
75
- 'aria-label': stringFormatter.format('startDate'),
76
- 'aria-labelledby': labelledBy
77
- };
78
-
79
- let endFieldProps = {
80
- 'aria-label': stringFormatter.format('endDate'),
81
- 'aria-labelledby': labelledBy
82
- };
83
-
84
- let buttonId = useId();
85
- let dialogId = useId();
86
-
87
- let groupProps = useDatePickerGroup(state, ref);
88
-
89
- let ariaDescribedBy = [descProps['aria-describedby'], fieldProps['aria-describedby']].filter(Boolean).join(' ') || undefined;
90
- let focusManager = useMemo(() => createFocusManager(ref, {
91
- // Exclude the button from the focus manager.
92
- accept: element => element.id !== buttonId
93
- }), [ref, buttonId]);
94
-
95
- let commonFieldProps = {
96
- [focusManagerSymbol]: focusManager,
97
- [roleSymbol]: 'presentation',
98
- 'aria-describedby': ariaDescribedBy,
99
- placeholderValue: props.placeholderValue,
100
- hideTimeZone: props.hideTimeZone,
101
- hourCycle: props.hourCycle,
102
- granularity: props.granularity,
103
- shouldForceLeadingZeros: props.shouldForceLeadingZeros,
104
- isDisabled: props.isDisabled,
105
- isReadOnly: props.isReadOnly,
106
- isRequired: props.isRequired,
107
- validationBehavior: props.validationBehavior
108
- };
109
-
110
- let domProps = filterDOMProps(props);
111
-
112
- let isFocused = useRef(false);
113
- let {focusWithinProps} = useFocusWithin({
114
- ...props,
115
- isDisabled: state.isOpen,
116
- onBlurWithin: e => {
117
- // Ignore when focus moves into the popover.
118
- let dialog = document.getElementById(dialogId);
119
- if (!nodeContains(dialog, e.relatedTarget)) {
120
- isFocused.current = false;
121
- props.onBlur?.(e);
122
- props.onFocusChange?.(false);
123
- }
124
- },
125
- onFocusWithin: e => {
126
- if (!isFocused.current) {
127
- isFocused.current = true;
128
- props.onFocus?.(e);
129
- props.onFocusChange?.(true);
130
- }
131
- }
132
- });
133
-
134
- let startFieldValidation = useRef(DEFAULT_VALIDATION_RESULT);
135
- let endFieldValidation = useRef(DEFAULT_VALIDATION_RESULT);
136
-
137
- return {
138
- groupProps: mergeProps(domProps, groupProps, fieldProps, descProps, focusWithinProps, {
139
- role: 'group' as const,
140
- 'aria-disabled': props.isDisabled || null,
141
- 'aria-describedby': ariaDescribedBy,
142
- onKeyDown(e: KeyboardEvent) {
143
- if (state.isOpen) {
144
- return;
145
- }
146
-
147
- if (props.onKeyDown) {
148
- props.onKeyDown(e);
149
- }
150
- },
151
- onKeyUp(e: KeyboardEvent) {
152
- if (state.isOpen) {
153
- return;
154
- }
155
-
156
- if (props.onKeyUp) {
157
- props.onKeyUp(e);
158
- }
159
- }
160
- }),
161
- labelProps: {
162
- ...labelProps,
163
- onClick: () => {
164
- focusManager.focusFirst();
165
- }
166
- },
167
- buttonProps: {
168
- ...descProps,
169
- id: buttonId,
170
- 'aria-haspopup': 'dialog',
171
- 'aria-label': stringFormatter.format('calendar'),
172
- 'aria-labelledby': `${buttonId} ${labelledBy}`,
173
- 'aria-describedby': ariaDescribedBy,
174
- 'aria-expanded': state.isOpen,
175
- isDisabled: props.isDisabled || props.isReadOnly,
176
- onPress: () => state.setOpen(true)
177
- },
178
- dialogProps: {
179
- id: dialogId,
180
- 'aria-labelledby': `${buttonId} ${labelledBy}`
181
- },
182
- startFieldProps: {
183
- ...startFieldProps,
184
- ...commonFieldProps,
185
- value: state.value?.start ?? null,
186
- defaultValue: state.defaultValue?.start,
187
- onChange: start => state.setDateTime('start', start),
188
- autoFocus: props.autoFocus,
189
- name: props.startName,
190
- form: props.form,
191
- [privateValidationStateProp]: {
192
- realtimeValidation: state.realtimeValidation,
193
- displayValidation: state.displayValidation,
194
- updateValidation(e) {
195
- startFieldValidation.current = e;
196
- state.updateValidation(mergeValidation(e, endFieldValidation.current));
197
- },
198
- resetValidation: state.resetValidation,
199
- commitValidation: state.commitValidation
200
- }
201
- },
202
- endFieldProps: {
203
- ...endFieldProps,
204
- ...commonFieldProps,
205
- value: state.value?.end ?? null,
206
- defaultValue: state.defaultValue?.end,
207
- onChange: end => state.setDateTime('end', end),
208
- name: props.endName,
209
- form: props.form,
210
- [privateValidationStateProp]: {
211
- realtimeValidation: state.realtimeValidation,
212
- displayValidation: state.displayValidation,
213
- updateValidation(e) {
214
- endFieldValidation.current = e;
215
- state.updateValidation(mergeValidation(startFieldValidation.current, e));
216
- },
217
- resetValidation: state.resetValidation,
218
- commitValidation: state.commitValidation
219
- }
220
- },
221
- descriptionProps,
222
- errorMessageProps,
223
- calendarProps: {
224
- autoFocus: true,
225
- value: state.dateRange?.start && state.dateRange.end ? state.dateRange as DateRange : null,
226
- onChange: state.setDateRange,
227
- minValue: props.minValue,
228
- maxValue: props.maxValue,
229
- isDisabled: props.isDisabled,
230
- isReadOnly: props.isReadOnly,
231
- isDateUnavailable: props.isDateUnavailable,
232
- allowsNonContiguousRanges: props.allowsNonContiguousRanges,
233
- defaultFocusedValue: state.dateRange ? undefined : props.placeholderValue,
234
- isInvalid: state.isInvalid,
235
- errorMessage: typeof props.errorMessage === 'function' ? props.errorMessage(state.displayValidation) : (props.errorMessage || state.displayValidation.validationErrors.join(' ')),
236
- firstDayOfWeek: props.firstDayOfWeek,
237
- pageBehavior: props.pageBehavior
238
- },
239
- isInvalid,
240
- validationErrors,
241
- validationDetails
242
- };
243
- }
@@ -1,413 +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 {CalendarDate, toCalendar} from '@internationalized/date';
14
- import {DateFieldState, DateSegment} from '@react-stately/datepicker';
15
- import {getActiveElement, getScrollParent, isIOS, isMac, mergeProps, nodeContains, scrollIntoViewport, useEvent, useId, useLabels, useLayoutEffect} from '@react-aria/utils';
16
- import {hookData} from './useDateField';
17
- import {NumberParser} from '@internationalized/number';
18
- import React, {CSSProperties, useMemo, useRef} from 'react';
19
- import {RefObject} from '@react-types/shared';
20
- import {useDateFormatter, useFilter, useLocale} from '@react-aria/i18n';
21
- import {useDisplayNames} from './useDisplayNames';
22
- import {useSpinButton} from '@react-aria/spinbutton';
23
-
24
- export interface DateSegmentAria {
25
- /** Props for the segment element. */
26
- segmentProps: React.HTMLAttributes<HTMLDivElement>
27
- }
28
-
29
- /**
30
- * Provides the behavior and accessibility implementation for a segment in a date field.
31
- * A date segment displays an individual unit of a date and time, and allows users to edit
32
- * the value by typing or using the arrow keys to increment and decrement.
33
- */
34
- export function useDateSegment(segment: DateSegment, state: DateFieldState, ref: RefObject<HTMLElement | null>): DateSegmentAria {
35
- let enteredKeys = useRef('');
36
- let {locale, direction} = useLocale();
37
- let displayNames = useDisplayNames();
38
- let {ariaLabel, ariaLabelledBy, ariaDescribedBy, focusManager} = hookData.get(state)!;
39
-
40
- let textValue = segment.isPlaceholder ? '' : segment.text;
41
- let options = useMemo(() => state.dateFormatter.resolvedOptions(), [state.dateFormatter]);
42
- let monthDateFormatter = useDateFormatter({month: 'long', timeZone: options.timeZone});
43
- let hourDateFormatter = useDateFormatter({
44
- hour: 'numeric',
45
- hour12: options.hour12,
46
- timeZone: options.timeZone
47
- });
48
-
49
- if (segment.type === 'month' && !segment.isPlaceholder) {
50
- let monthTextValue = monthDateFormatter.format(state.dateValue);
51
- textValue = monthTextValue !== textValue ? `${textValue} – ${monthTextValue}` : monthTextValue;
52
- } else if (segment.type === 'hour' && !segment.isPlaceholder) {
53
- textValue = hourDateFormatter.format(state.dateValue);
54
- }
55
-
56
- let {spinButtonProps} = useSpinButton({
57
- // The ARIA spec says aria-valuenow is optional if there's no value, but aXe seems to require it.
58
- // This doesn't seem to have any negative effects with real AT since we also use aria-valuetext.
59
- // https://github.com/dequelabs/axe-core/issues/3505
60
- value: segment.value ?? undefined,
61
- textValue,
62
- minValue: segment.minValue,
63
- maxValue: segment.maxValue,
64
- isDisabled: state.isDisabled,
65
- isReadOnly: state.isReadOnly || !segment.isEditable,
66
- isRequired: state.isRequired,
67
- onIncrement: () => {
68
- enteredKeys.current = '';
69
- state.increment(segment.type);
70
- },
71
- onDecrement: () => {
72
- enteredKeys.current = '';
73
- state.decrement(segment.type);
74
- },
75
- onIncrementPage: () => {
76
- enteredKeys.current = '';
77
- state.incrementPage(segment.type);
78
- },
79
- onDecrementPage: () => {
80
- enteredKeys.current = '';
81
- state.decrementPage(segment.type);
82
- },
83
- onIncrementToMax: () => {
84
- enteredKeys.current = '';
85
- state.incrementToMax(segment.type);
86
- },
87
- onDecrementToMin: () => {
88
- enteredKeys.current = '';
89
- state.decrementToMin(segment.type);
90
- }
91
- });
92
-
93
- let parser = useMemo(() => new NumberParser(locale, {maximumFractionDigits: 0}), [locale]);
94
-
95
- let backspace = () => {
96
- if (segment.text === segment.placeholder) {
97
- focusManager.focusPrevious();
98
- }
99
- if (parser.isValidPartialNumber(segment.text) && !state.isReadOnly && !segment.isPlaceholder) {
100
- let newValue = segment.text.slice(0, -1);
101
- let parsed = parser.parse(newValue);
102
- newValue = parsed === 0 ? '' : newValue;
103
- if (newValue.length === 0 || parsed === 0) {
104
- state.clearSegment(segment.type);
105
- } else {
106
- state.setSegment(segment.type, parsed);
107
- }
108
- enteredKeys.current = newValue;
109
- } else if (segment.type === 'dayPeriod' || segment.type === 'era') {
110
- state.clearSegment(segment.type);
111
- }
112
- };
113
-
114
- let onKeyDown = (e) => {
115
- // Firefox does not fire selectstart for Ctrl/Cmd + A
116
- // https://bugzilla.mozilla.org/show_bug.cgi?id=1742153
117
- if (e.key === 'a' && (isMac() ? e.metaKey : e.ctrlKey)) {
118
- e.preventDefault();
119
- }
120
-
121
- if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) {
122
- return;
123
- }
124
-
125
- switch (e.key) {
126
- case 'Backspace':
127
- case 'Delete': {
128
- // Safari on iOS does not fire beforeinput for the backspace key because the cursor is at the start.
129
- e.preventDefault();
130
- e.stopPropagation();
131
- backspace();
132
- break;
133
- }
134
- }
135
- };
136
-
137
- // Safari dayPeriod option doesn't work...
138
- let {startsWith} = useFilter({sensitivity: 'base'});
139
- let amPmFormatter = useDateFormatter({hour: 'numeric', hour12: true});
140
- let am = useMemo(() => {
141
- let date = new Date();
142
- date.setHours(0);
143
- return amPmFormatter.formatToParts(date).find(part => part.type === 'dayPeriod')!.value;
144
- }, [amPmFormatter]);
145
-
146
- let pm = useMemo(() => {
147
- let date = new Date();
148
- date.setHours(12);
149
- return amPmFormatter.formatToParts(date).find(part => part.type === 'dayPeriod')!.value;
150
- }, [amPmFormatter]);
151
-
152
- // Get a list of formatted era names so users can type the first character to choose one.
153
- let eraFormatter = useDateFormatter({year: 'numeric', era: 'narrow', timeZone: 'UTC'});
154
- let eras = useMemo(() => {
155
- if (segment.type !== 'era') {
156
- return [];
157
- }
158
-
159
- let date = toCalendar(new CalendarDate(1, 1, 1), state.calendar);
160
- let eras = state.calendar.getEras().map(era => {
161
- let eraDate = date.set({year: 1, month: 1, day: 1, era}).toDate('UTC');
162
- let parts = eraFormatter.formatToParts(eraDate);
163
- let formatted = parts.find(p => p.type === 'era')!.value;
164
- return {era, formatted};
165
- });
166
-
167
- // Remove the common prefix from formatted values. This is so that in calendars with eras like
168
- // ERA0 and ERA1 (e.g. Ethiopic), users can press "0" and "1" to select an era. In other cases,
169
- // the first letter is used.
170
- let prefixLength = commonPrefixLength(eras.map(era => era.formatted));
171
- if (prefixLength) {
172
- for (let era of eras) {
173
- era.formatted = era.formatted.slice(prefixLength);
174
- }
175
- }
176
-
177
- return eras;
178
- }, [eraFormatter, state.calendar, segment.type]);
179
-
180
- let onInput = (key: string) => {
181
- if (state.isDisabled || state.isReadOnly) {
182
- return;
183
- }
184
-
185
- let newValue = enteredKeys.current + key;
186
-
187
- switch (segment.type) {
188
- case 'dayPeriod':
189
- if (startsWith(am, key)) {
190
- state.setSegment('dayPeriod', 0);
191
- } else if (startsWith(pm, key)) {
192
- state.setSegment('dayPeriod', 1);
193
- } else {
194
- break;
195
- }
196
- focusManager.focusNext();
197
- break;
198
- case 'era': {
199
- let matched = eras.find(e => startsWith(e.formatted, key));
200
- if (matched) {
201
- state.setSegment('era', matched.era);
202
- focusManager.focusNext();
203
- }
204
- break;
205
- }
206
- case 'day':
207
- case 'hour':
208
- case 'minute':
209
- case 'second':
210
- case 'month':
211
- case 'year': {
212
- if (!parser.isValidPartialNumber(newValue)) {
213
- return;
214
- }
215
-
216
- let numberValue = parser.parse(newValue);
217
- let segmentValue = numberValue;
218
- if (segment.maxValue !== undefined && numberValue > segment.maxValue) {
219
- segmentValue = parser.parse(key);
220
- }
221
-
222
- if (isNaN(numberValue)) {
223
- return;
224
- }
225
-
226
- state.setSegment(segment.type, segmentValue);
227
-
228
- if (segment.maxValue !== undefined && (Number(numberValue + '0') > segment.maxValue || newValue.length >= String(segment.maxValue).length)) {
229
- enteredKeys.current = '';
230
- focusManager.focusNext();
231
- } else {
232
- enteredKeys.current = newValue;
233
- }
234
- break;
235
- }
236
- }
237
- };
238
-
239
- let onFocus = () => {
240
- enteredKeys.current = '';
241
- if (ref.current) {
242
- scrollIntoViewport(ref.current, {containingElement: getScrollParent(ref.current)});
243
- }
244
-
245
- // Collapse selection to start or Chrome won't fire input events.
246
- let selection = window.getSelection();
247
- selection?.collapse(ref.current);
248
- };
249
-
250
- let documentRef = useRef(typeof document !== 'undefined' ? document : null);
251
- useEvent(documentRef, 'selectionchange', () => {
252
- // Enforce that the selection is collapsed when inside a date segment.
253
- // Otherwise, when tapping on a segment in Android Chrome and then entering text,
254
- // composition events will be fired that break the DOM structure and crash the page.
255
- let selection = window.getSelection();
256
- if (selection?.anchorNode && nodeContains(ref.current, selection?.anchorNode)) {
257
- selection.collapse(ref.current);
258
- }
259
- });
260
-
261
- let compositionRef = useRef<string | null>('');
262
- useEvent(ref, 'beforeinput', e => {
263
- if (!ref.current) {
264
- return;
265
- }
266
- e.preventDefault();
267
-
268
- switch (e.inputType) {
269
- case 'deleteContentBackward':
270
- case 'deleteContentForward':
271
- if (parser.isValidPartialNumber(segment.text) && !state.isReadOnly) {
272
- backspace();
273
- }
274
- break;
275
- case 'insertCompositionText':
276
- // insertCompositionText cannot be canceled.
277
- // Record the current state of the element so we can restore it in the `input` event below.
278
- compositionRef.current = ref.current.textContent;
279
-
280
- // Safari gets stuck in a composition state unless we also assign to the value here.
281
- // eslint-disable-next-line no-self-assign
282
- ref.current.textContent = ref.current.textContent;
283
- break;
284
- default:
285
- if (e.data != null) {
286
- onInput(e.data);
287
- }
288
- break;
289
- }
290
- });
291
-
292
- useEvent(ref, 'input', e => {
293
- let {inputType, data} = e as InputEvent;
294
- switch (inputType) {
295
- case 'insertCompositionText':
296
- // Reset the DOM to how it was in the beforeinput event.
297
- if (ref.current) {
298
- ref.current.textContent = compositionRef.current;
299
- }
300
-
301
- // Android sometimes fires key presses of letters as composition events. Need to handle am/pm keys here too.
302
- // Can also happen e.g. with Pinyin keyboard on iOS.
303
- if (data != null && (startsWith(am, data) || startsWith(pm, data))) {
304
- onInput(data);
305
- }
306
- break;
307
- }
308
- });
309
-
310
- useLayoutEffect(() => {
311
- let element = ref.current;
312
- return () => {
313
- // If the focused segment is removed, focus the previous one, or the next one if there was no previous one.
314
- if (getActiveElement() === element) {
315
- let prev = focusManager.focusPrevious();
316
- if (!prev) {
317
- focusManager.focusNext();
318
- }
319
- }
320
- };
321
- }, [ref, focusManager]);
322
-
323
- // spinbuttons cannot be focused with VoiceOver on iOS.
324
- let touchPropOverrides = isIOS() || segment.type === 'timeZoneName' ? {
325
- role: 'textbox',
326
- 'aria-valuemax': null,
327
- 'aria-valuemin': null,
328
- 'aria-valuetext': null,
329
- 'aria-valuenow': null
330
- } : {};
331
-
332
- // Only apply aria-describedby to the first segment, unless the field is invalid. This avoids it being
333
- // read every time the user navigates to a new segment.
334
- let firstSegment = useMemo(() => state.segments.find(s => s.isEditable), [state.segments]);
335
- if (segment !== firstSegment && !state.isInvalid) {
336
- ariaDescribedBy = undefined;
337
- }
338
-
339
- let id = useId();
340
- let isEditable = !state.isDisabled && !state.isReadOnly && segment.isEditable;
341
-
342
- // Prepend the label passed from the field to each segment name.
343
- // This is needed because VoiceOver on iOS does not announce groups.
344
- let name = segment.type === 'literal' ? '' : displayNames.of(segment.type);
345
- let labelProps = useLabels({
346
- 'aria-label': `${name}${ariaLabel ? `, ${ariaLabel}` : ''}${ariaLabelledBy ? ', ' : ''}`,
347
- 'aria-labelledby': ariaLabelledBy
348
- });
349
-
350
- // Literal segments should not be visible to screen readers. We don't really need any of the above,
351
- // but the rules of hooks mean hooks cannot be conditional so we have to put this condition here.
352
- if (segment.type === 'literal') {
353
- return {
354
- segmentProps: {
355
- 'aria-hidden': true
356
- }
357
- };
358
- }
359
-
360
- let segmentStyle: CSSProperties = {caretColor: 'transparent'};
361
- if (direction === 'rtl') {
362
- // While the bidirectional algorithm seems to work properly on inline elements with actual values, it returns different results for placeholder strings.
363
- // To ensure placeholder render in correct format, we apply the CSS equivalent of LRE (left-to-right embedding). See https://www.unicode.org/reports/tr9/#Explicit_Directional_Embeddings.
364
- // However, we apply this to both placeholders and date segments with an actual value because the date segments will shift around when deleting otherwise.
365
- segmentStyle.unicodeBidi = 'embed';
366
- let format = options[segment.type];
367
- if (format === 'numeric' || format === '2-digit') {
368
- segmentStyle.direction = 'ltr';
369
- }
370
- }
371
-
372
- return {
373
- segmentProps: mergeProps(spinButtonProps, labelProps, {
374
- id,
375
- ...touchPropOverrides,
376
- 'aria-invalid': state.isInvalid ? 'true' : undefined,
377
- 'aria-describedby': ariaDescribedBy,
378
- 'aria-readonly': state.isReadOnly || !segment.isEditable ? 'true' : undefined,
379
- 'data-placeholder': segment.isPlaceholder || undefined,
380
- contentEditable: isEditable,
381
- suppressContentEditableWarning: isEditable,
382
- spellCheck: isEditable ? 'false' : undefined,
383
- autoCorrect: isEditable ? 'off' : undefined,
384
- // Capitalization was changed in React 17...
385
- [parseInt(React.version, 10) >= 17 ? 'enterKeyHint' : 'enterkeyhint']: isEditable ? 'next' : undefined,
386
- inputMode: state.isDisabled || segment.type === 'dayPeriod' || segment.type === 'era' || !isEditable ? undefined : 'numeric',
387
- tabIndex: state.isDisabled ? undefined : 0,
388
- onKeyDown,
389
- onFocus,
390
- style: segmentStyle,
391
- // Prevent pointer events from reaching useDatePickerGroup, and allow native browser behavior to focus the segment.
392
- onPointerDown(e) {
393
- e.stopPropagation();
394
- },
395
- onMouseDown(e) {
396
- e.stopPropagation();
397
- }
398
- })
399
- };
400
- }
401
-
402
- function commonPrefixLength(strings: string[]): number {
403
- // Sort the strings, and compare the characters in the first and last to find the common prefix.
404
- strings.sort();
405
- let first = strings[0];
406
- let last = strings[strings.length - 1];
407
- for (let i = 0; i < first.length; i++) {
408
- if (first[i] !== last[i]) {
409
- return i;
410
- }
411
- }
412
- return 0;
413
- }