@react-stately/datepicker 3.0.0-alpha.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.
@@ -0,0 +1,422 @@
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 {Calendar, CalendarDateTime, DateFormatter, getMinimumDayInMonth, getMinimumMonthInYear, GregorianCalendar, toCalendar} from '@internationalized/date';
14
+ import {convertValue, createPlaceholderDate, FieldOptions, getFormatOptions, isInvalid, useDefaultProps} from './utils';
15
+ import {DatePickerProps, DateValue, Granularity} from '@react-types/datepicker';
16
+ import {useControlledState} from '@react-stately/utils';
17
+ import {useEffect, useMemo, useRef, useState} from 'react';
18
+ import {ValidationState} from '@react-types/shared';
19
+
20
+ export interface DateSegment {
21
+ type: Intl.DateTimeFormatPartTypes,
22
+ text: string,
23
+ value?: number,
24
+ minValue?: number,
25
+ maxValue?: number,
26
+ isPlaceholder: boolean,
27
+ isEditable: boolean
28
+ }
29
+
30
+ export interface DatePickerFieldState {
31
+ value: DateValue,
32
+ dateValue: Date,
33
+ setValue: (value: CalendarDateTime) => void,
34
+ segments: DateSegment[],
35
+ dateFormatter: DateFormatter,
36
+ validationState: ValidationState,
37
+ granularity: Granularity,
38
+ increment: (type: Intl.DateTimeFormatPartTypes) => void,
39
+ decrement: (type: Intl.DateTimeFormatPartTypes) => void,
40
+ incrementPage: (type: Intl.DateTimeFormatPartTypes) => void,
41
+ decrementPage: (type: Intl.DateTimeFormatPartTypes) => void,
42
+ setSegment: (type: Intl.DateTimeFormatPartTypes, value: number) => void,
43
+ confirmPlaceholder: (type?: Intl.DateTimeFormatPartTypes) => void,
44
+ clearSegment: (type?: Intl.DateTimeFormatPartTypes) => void,
45
+ getFormatOptions(fieldOptions: FieldOptions): Intl.DateTimeFormatOptions
46
+ }
47
+
48
+ const EDITABLE_SEGMENTS = {
49
+ year: true,
50
+ month: true,
51
+ day: true,
52
+ hour: true,
53
+ minute: true,
54
+ second: true,
55
+ dayPeriod: true,
56
+ era: true
57
+ };
58
+
59
+ const PAGE_STEP = {
60
+ year: 5,
61
+ month: 2,
62
+ day: 7,
63
+ hour: 2,
64
+ minute: 15,
65
+ second: 15
66
+ };
67
+
68
+ // Node seems to convert everything to lowercase...
69
+ const TYPE_MAPPING = {
70
+ dayperiod: 'dayPeriod'
71
+ };
72
+
73
+ interface DatePickerFieldProps<T extends DateValue> extends DatePickerProps<T> {
74
+ maxGranularity?: 'year' | 'month' | DatePickerProps<T>['granularity'],
75
+ locale: string,
76
+ createCalendar: (name: string) => Calendar
77
+ }
78
+
79
+ export function useDatePickerFieldState<T extends DateValue>(props: DatePickerFieldProps<T>): DatePickerFieldState {
80
+ let {
81
+ locale,
82
+ createCalendar,
83
+ hideTimeZone
84
+ } = props;
85
+
86
+ let v: DateValue = (props.value || props.defaultValue || props.placeholderValue);
87
+ let [granularity, defaultTimeZone] = useDefaultProps(v, props.granularity);
88
+ let timeZone = defaultTimeZone || 'UTC';
89
+
90
+ // props.granularity must actually exist in the value if one is provided.
91
+ if (v && !(granularity in v)) {
92
+ throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
93
+ }
94
+
95
+ let formatOpts = useMemo(() => ({
96
+ granularity,
97
+ maxGranularity: props.maxGranularity ?? 'year',
98
+ timeZone: defaultTimeZone,
99
+ hideTimeZone,
100
+ hourCycle: props.hourCycle
101
+ }), [props.maxGranularity, granularity, props.hourCycle, defaultTimeZone, hideTimeZone]);
102
+ let opts = useMemo(() => getFormatOptions({}, formatOpts), [formatOpts]);
103
+
104
+ let dateFormatter = useMemo(() => new DateFormatter(locale, opts), [locale, opts]);
105
+ let resolvedOptions = useMemo(() => dateFormatter.resolvedOptions(), [dateFormatter]);
106
+ let calendar = useMemo(() => createCalendar(resolvedOptions.calendar), [createCalendar, resolvedOptions.calendar]);
107
+
108
+ // Determine how many editable segments there are for validation purposes.
109
+ // The result is cached for performance.
110
+ let allSegments = useMemo(() =>
111
+ dateFormatter.formatToParts(new Date())
112
+ .filter(seg => EDITABLE_SEGMENTS[seg.type])
113
+ .reduce((p, seg) => (p[seg.type] = true, p), {})
114
+ , [dateFormatter]);
115
+
116
+ let [validSegments, setValidSegments] = useState<Partial<typeof EDITABLE_SEGMENTS>>(
117
+ () => props.value || props.defaultValue ? {...allSegments} : {}
118
+ );
119
+
120
+ // We keep track of the placeholder date separately in state so that onChange is not called
121
+ // until all segments are set. If the value === null (not undefined), then assume the component
122
+ // is controlled, so use the placeholder as the value until all segments are entered so it doesn't
123
+ // change from uncontrolled to controlled and emit a warning.
124
+ let [placeholderDate, setPlaceholderDate] = useState(
125
+ () => createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone)
126
+ );
127
+
128
+ // Reset placeholder when calendar changes
129
+ let lastCalendarIdentifier = useRef(calendar.identifier);
130
+ useEffect(() => {
131
+ if (calendar.identifier !== lastCalendarIdentifier.current) {
132
+ lastCalendarIdentifier.current = calendar.identifier;
133
+ setPlaceholderDate(placeholder =>
134
+ Object.keys(validSegments).length > 0
135
+ ? toCalendar(placeholder, calendar)
136
+ : createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone)
137
+ );
138
+ }
139
+ }, [calendar, granularity, validSegments, defaultTimeZone, props.placeholderValue]);
140
+
141
+ let [value, setDate] = useControlledState<DateValue>(
142
+ props.value,
143
+ props.defaultValue,
144
+ props.onChange
145
+ );
146
+
147
+ let calendarValue = useMemo(() => convertValue(value, calendar), [value, calendar]);
148
+
149
+ // If there is a value prop, and some segments were previously placeholders, mark them all as valid.
150
+ if (value && Object.keys(validSegments).length < Object.keys(allSegments).length) {
151
+ validSegments = {...allSegments};
152
+ setValidSegments(validSegments);
153
+ }
154
+
155
+ // If the value is set to null and all segments are valid, reset the placeholder.
156
+ if (value == null && Object.keys(validSegments).length === Object.keys(allSegments).length) {
157
+ validSegments = {};
158
+ setValidSegments(validSegments);
159
+ setPlaceholderDate(createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone));
160
+ }
161
+
162
+ // If all segments are valid, use the date from state, otherwise use the placeholder date.
163
+ let displayValue = calendarValue && Object.keys(validSegments).length >= Object.keys(allSegments).length ? calendarValue : placeholderDate;
164
+ let setValue = (newValue: DateValue) => {
165
+ if (props.isDisabled || props.isReadOnly) {
166
+ return;
167
+ }
168
+
169
+ if (Object.keys(validSegments).length >= Object.keys(allSegments).length) {
170
+ // The display calendar should not have any effect on the emitted value.
171
+ // Emit dates in the same calendar as the original value, if any, otherwise gregorian.
172
+ newValue = toCalendar(newValue, v?.calendar || new GregorianCalendar());
173
+ setDate(newValue);
174
+ } else {
175
+ setPlaceholderDate(newValue);
176
+ }
177
+ };
178
+
179
+ let dateValue = useMemo(() => displayValue.toDate(timeZone), [displayValue, timeZone]);
180
+ let segments = useMemo(() =>
181
+ dateFormatter.formatToParts(dateValue)
182
+ .map(segment => {
183
+ let isEditable = EDITABLE_SEGMENTS[segment.type];
184
+ if (segment.type === 'era' && calendar.getEras().length === 1) {
185
+ isEditable = false;
186
+ }
187
+
188
+ return {
189
+ type: TYPE_MAPPING[segment.type] || segment.type,
190
+ text: segment.value,
191
+ ...getSegmentLimits(displayValue, segment.type, resolvedOptions),
192
+ isPlaceholder: EDITABLE_SEGMENTS[segment.type] && !validSegments[segment.type],
193
+ isEditable
194
+ } as DateSegment;
195
+ })
196
+ , [dateValue, validSegments, dateFormatter, resolvedOptions, displayValue, calendar]);
197
+
198
+ let hasEra = useMemo(() => segments.some(s => s.type === 'era'), [segments]);
199
+
200
+ let markValid = (part: Intl.DateTimeFormatPartTypes) => {
201
+ validSegments[part] = true;
202
+ if (part === 'year' && hasEra) {
203
+ validSegments.era = true;
204
+ }
205
+ setValidSegments({...validSegments});
206
+ };
207
+
208
+ let adjustSegment = (type: Intl.DateTimeFormatPartTypes, amount: number) => {
209
+ markValid(type);
210
+ setValue(addSegment(displayValue, type, amount, resolvedOptions));
211
+ };
212
+
213
+ let validationState: ValidationState = props.validationState ||
214
+ (isInvalid(calendarValue, props.minValue, props.maxValue) ? 'invalid' : null);
215
+
216
+ return {
217
+ value: calendarValue,
218
+ dateValue,
219
+ setValue,
220
+ segments,
221
+ dateFormatter,
222
+ validationState,
223
+ granularity,
224
+ increment(part) {
225
+ adjustSegment(part, 1);
226
+ },
227
+ decrement(part) {
228
+ adjustSegment(part, -1);
229
+ },
230
+ incrementPage(part) {
231
+ adjustSegment(part, PAGE_STEP[part] || 1);
232
+ },
233
+ decrementPage(part) {
234
+ adjustSegment(part, -(PAGE_STEP[part] || 1));
235
+ },
236
+ setSegment(part, v) {
237
+ markValid(part);
238
+ setValue(setSegment(displayValue, part, v, resolvedOptions));
239
+ },
240
+ confirmPlaceholder(part) {
241
+ if (props.isDisabled || props.isReadOnly) {
242
+ return;
243
+ }
244
+
245
+ if (!part) {
246
+ // Confirm the rest of the placeholder if any of the segments are valid.
247
+ let numValid = Object.keys(validSegments).length;
248
+ if (numValid > 0 && numValid < Object.keys(allSegments).length) {
249
+ validSegments = {...allSegments};
250
+ setValidSegments(validSegments);
251
+ setValue(displayValue.copy());
252
+ }
253
+ } else if (!validSegments[part]) {
254
+ markValid(part);
255
+ setValue(displayValue.copy());
256
+ }
257
+ },
258
+ clearSegment(part) {
259
+ delete validSegments[part];
260
+ setValidSegments({...validSegments});
261
+
262
+ let placeholder = createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone);
263
+ let value = displayValue;
264
+
265
+ // Reset day period to default without changing the hour.
266
+ if (part === 'dayPeriod' && 'hour' in displayValue && 'hour' in placeholder) {
267
+ let isPM = displayValue.hour >= 12;
268
+ let shouldBePM = placeholder.hour >= 12;
269
+ if (isPM && !shouldBePM) {
270
+ value = displayValue.set({hour: displayValue.hour - 12});
271
+ } else if (!isPM && shouldBePM) {
272
+ value = displayValue.set({hour: displayValue.hour + 12});
273
+ }
274
+ } else if (part in displayValue) {
275
+ value = displayValue.set({[part]: placeholder[part]});
276
+ }
277
+
278
+ setDate(null);
279
+ setValue(value);
280
+ },
281
+ getFormatOptions(fieldOptions: FieldOptions) {
282
+ return getFormatOptions(fieldOptions, formatOpts);
283
+ }
284
+ };
285
+ }
286
+
287
+ function getSegmentLimits(date: DateValue, type: string, options: Intl.ResolvedDateTimeFormatOptions) {
288
+ switch (type) {
289
+ case 'era': {
290
+ let eras = date.calendar.getEras();
291
+ return {
292
+ value: eras.indexOf(date.era),
293
+ minValue: 0,
294
+ maxValue: eras.length - 1
295
+ };
296
+ }
297
+ case 'year':
298
+ return {
299
+ value: date.year,
300
+ minValue: 1,
301
+ maxValue: date.calendar.getYearsInEra(date)
302
+ };
303
+ case 'month':
304
+ return {
305
+ value: date.month,
306
+ minValue: getMinimumMonthInYear(date),
307
+ maxValue: date.calendar.getMonthsInYear(date)
308
+ };
309
+ case 'day':
310
+ return {
311
+ value: date.day,
312
+ minValue: getMinimumDayInMonth(date),
313
+ maxValue: date.calendar.getDaysInMonth(date)
314
+ };
315
+ }
316
+
317
+ if ('hour' in date) {
318
+ switch (type) {
319
+ case 'dayPeriod':
320
+ return {
321
+ value: date.hour >= 12 ? 12 : 0,
322
+ minValue: 0,
323
+ maxValue: 12
324
+ };
325
+ case 'hour':
326
+ if (options.hour12) {
327
+ let isPM = date.hour >= 12;
328
+ return {
329
+ value: date.hour,
330
+ minValue: isPM ? 12 : 0,
331
+ maxValue: isPM ? 23 : 11
332
+ };
333
+ }
334
+
335
+ return {
336
+ value: date.hour,
337
+ minValue: 0,
338
+ maxValue: 23
339
+ };
340
+ case 'minute':
341
+ return {
342
+ value: date.minute,
343
+ minValue: 0,
344
+ maxValue: 59
345
+ };
346
+ case 'second':
347
+ return {
348
+ value: date.second,
349
+ minValue: 0,
350
+ maxValue: 59
351
+ };
352
+ }
353
+ }
354
+
355
+ return {};
356
+ }
357
+
358
+ function addSegment(value: DateValue, part: string, amount: number, options: Intl.ResolvedDateTimeFormatOptions) {
359
+ switch (part) {
360
+ case 'era':
361
+ case 'year':
362
+ case 'month':
363
+ case 'day':
364
+ return value.cycle(part, amount, {round: part === 'year'});
365
+ }
366
+
367
+ if ('hour' in value) {
368
+ switch (part) {
369
+ case 'dayPeriod': {
370
+ let hours = value.hour;
371
+ let isPM = hours >= 12;
372
+ return value.set({hour: isPM ? hours - 12 : hours + 12});
373
+ }
374
+ case 'hour':
375
+ case 'minute':
376
+ case 'second':
377
+ return value.cycle(part, amount, {
378
+ round: part !== 'hour',
379
+ hourCycle: options.hour12 ? 12 : 24
380
+ });
381
+ }
382
+ }
383
+ }
384
+
385
+ function setSegment(value: DateValue, part: string, segmentValue: number, options: Intl.ResolvedDateTimeFormatOptions) {
386
+ switch (part) {
387
+ case 'day':
388
+ case 'month':
389
+ case 'year':
390
+ return value.set({[part]: segmentValue});
391
+ }
392
+
393
+ if ('hour' in value) {
394
+ switch (part) {
395
+ case 'dayPeriod': {
396
+ let hours = value.hour;
397
+ let wasPM = hours >= 12;
398
+ let isPM = segmentValue >= 12;
399
+ if (isPM === wasPM) {
400
+ return value;
401
+ }
402
+ return value.set({hour: wasPM ? hours - 12 : hours + 12});
403
+ }
404
+ case 'hour':
405
+ // In 12 hour time, ensure that AM/PM does not change
406
+ if (options.hour12) {
407
+ let hours = value.hour;
408
+ let wasPM = hours >= 12;
409
+ if (!wasPM && segmentValue === 12) {
410
+ segmentValue = 0;
411
+ }
412
+ if (wasPM && segmentValue < 12) {
413
+ segmentValue += 12;
414
+ }
415
+ }
416
+ // fallthrough
417
+ case 'minute':
418
+ case 'second':
419
+ return value.set({[part]: segmentValue});
420
+ }
421
+ }
422
+ }
@@ -0,0 +1,127 @@
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, DateFormatter, toCalendarDateTime, toDateFields} from '@internationalized/date';
14
+ import {DatePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
15
+ import {FieldOptions, getFormatOptions, getPlaceholderTime, useDefaultProps} from './utils';
16
+ import {isInvalid} from './utils';
17
+ import {useControlledState} from '@react-stately/utils';
18
+ import {useState} from 'react';
19
+ import {ValidationState} from '@react-types/shared';
20
+
21
+ export interface DatePickerState {
22
+ value: DateValue,
23
+ setValue: (value: DateValue) => void,
24
+ dateValue: DateValue,
25
+ setDateValue: (value: CalendarDate) => void,
26
+ timeValue: TimeValue,
27
+ setTimeValue: (value: TimeValue) => void,
28
+ isOpen: boolean,
29
+ setOpen: (isOpen: boolean) => void,
30
+ validationState: ValidationState,
31
+ formatValue(locale: string, fieldOptions: FieldOptions): string,
32
+ granularity: Granularity
33
+ }
34
+
35
+ export function useDatePickerState<T extends DateValue>(props: DatePickerProps<T>): DatePickerState {
36
+ let [isOpen, setOpen] = useState(false);
37
+ let [value, setValue] = useControlledState<DateValue>(props.value, props.defaultValue || null, props.onChange);
38
+
39
+ let v = (value || props.placeholderValue);
40
+ let [granularity, defaultTimeZone] = useDefaultProps(v, props.granularity);
41
+ let dateValue = value != null ? value.toDate(defaultTimeZone ?? 'UTC') : null;
42
+ let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
43
+
44
+ let [selectedDate, setSelectedDate] = useState<DateValue>(null);
45
+ let [selectedTime, setSelectedTime] = useState<TimeValue>(null);
46
+
47
+ if (value) {
48
+ selectedDate = value;
49
+ if ('hour' in value) {
50
+ selectedTime = value;
51
+ }
52
+ }
53
+
54
+ // props.granularity must actually exist in the value if one is provided.
55
+ if (v && !(granularity in v)) {
56
+ throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
57
+ }
58
+
59
+ let commitValue = (date: DateValue, time: TimeValue) => {
60
+ setValue('timeZone' in time ? time.set(toDateFields(date)) : toCalendarDateTime(date, time));
61
+ };
62
+
63
+ // Intercept setValue to make sure the Time section is not changed by date selection in Calendar
64
+ let selectDate = (newValue: CalendarDate) => {
65
+ if (hasTime) {
66
+ if (selectedTime) {
67
+ commitValue(newValue, selectedTime);
68
+ } else {
69
+ setSelectedDate(newValue);
70
+ }
71
+ } else {
72
+ setValue(newValue);
73
+ }
74
+
75
+ if (!hasTime) {
76
+ setOpen(false);
77
+ }
78
+ };
79
+
80
+ let selectTime = (newValue: TimeValue) => {
81
+ if (selectedDate) {
82
+ commitValue(selectedDate, newValue);
83
+ } else {
84
+ setSelectedTime(newValue);
85
+ }
86
+ };
87
+
88
+ let validationState: ValidationState = props.validationState ||
89
+ (isInvalid(value, props.minValue, props.maxValue) ? 'invalid' : null);
90
+
91
+ return {
92
+ value,
93
+ setValue,
94
+ dateValue: selectedDate,
95
+ timeValue: selectedTime,
96
+ setDateValue: selectDate,
97
+ setTimeValue: selectTime,
98
+ granularity,
99
+ isOpen,
100
+ setOpen(isOpen) {
101
+ // Commit the selected date when the calendar is closed. Use a placeholder time if one wasn't set.
102
+ // If only the time was set and not the date, don't commit. The state will be preserved until
103
+ // the user opens the popover again.
104
+ if (!isOpen && !value && selectedDate && hasTime) {
105
+ commitValue(selectedDate, selectedTime || getPlaceholderTime(props.placeholderValue));
106
+ }
107
+
108
+ setOpen(isOpen);
109
+ },
110
+ validationState,
111
+ formatValue(locale, fieldOptions) {
112
+ if (!dateValue) {
113
+ return '';
114
+ }
115
+
116
+ let formatOptions = getFormatOptions(fieldOptions, {
117
+ granularity,
118
+ timeZone: defaultTimeZone,
119
+ hideTimeZone: props.hideTimeZone,
120
+ hourCycle: props.hourCycle
121
+ });
122
+
123
+ let formatter = new DateFormatter(locale, formatOptions);
124
+ return formatter.format(dateValue);
125
+ }
126
+ };
127
+ }