@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,208 @@
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 {createPlaceholderDate, FieldOptions, getFormatOptions, getPlaceholderTime, isInvalid, useDefaultProps} from './utils';
14
+ import {DateFormatter, toCalendarDateTime, toDateFields} from '@internationalized/date';
15
+ import {DateRange, DateRangePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
16
+ import {RangeValue, ValidationState} from '@react-types/shared';
17
+ import {useControlledState} from '@react-stately/utils';
18
+ import {useRef, useState} from 'react';
19
+
20
+ type TimeRange = RangeValue<TimeValue>;
21
+ export interface DateRangePickerState {
22
+ value: DateRange,
23
+ setValue: (value: DateRange) => void,
24
+ setDate: (part: keyof DateRange, value: DateValue) => void,
25
+ setTime: (part: keyof TimeRange, value: TimeValue) => void,
26
+ setDateTime: (part: keyof DateRange, value: DateValue) => void,
27
+ dateRange: DateRange,
28
+ setDateRange: (value: DateRange) => void,
29
+ timeRange: TimeRange,
30
+ setTimeRange: (value: TimeRange) => void,
31
+ isOpen: boolean,
32
+ setOpen: (isOpen: boolean) => void,
33
+ validationState: ValidationState,
34
+ formatValue(locale: string, fieldOptions: FieldOptions): string,
35
+ confirmPlaceholder(): void,
36
+ granularity: Granularity
37
+ }
38
+
39
+ export function useDateRangePickerState<T extends DateValue>(props: DateRangePickerProps<T>): DateRangePickerState {
40
+ let [isOpen, setOpen] = useState(false);
41
+ let [controlledValue, setControlledValue] = useControlledState<DateRange>(props.value, props.defaultValue || null, props.onChange);
42
+ let [placeholderValue, setPlaceholderValue] = useState(() => controlledValue || {start: null, end: null});
43
+
44
+ // Reset the placeholder if the value prop is set to null.
45
+ if (controlledValue == null && placeholderValue.start && placeholderValue.end) {
46
+ placeholderValue = {start: null, end: null};
47
+ setPlaceholderValue(placeholderValue);
48
+ }
49
+
50
+ let value = controlledValue || placeholderValue;
51
+ let valueRef = useRef(value);
52
+ valueRef.current = value;
53
+
54
+ let setValue = (value: DateRange) => {
55
+ valueRef.current = value;
56
+ setPlaceholderValue(value);
57
+ if (value?.start && value.end) {
58
+ setControlledValue(value);
59
+ } else {
60
+ setControlledValue(null);
61
+ }
62
+ };
63
+
64
+ let v = (value?.start || value?.end || props.placeholderValue);
65
+ let [granularity, defaultTimeZone] = useDefaultProps(v, props.granularity);
66
+ let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
67
+
68
+ let [dateRange, setSelectedDateRange] = useState<DateRange>(null);
69
+ let [timeRange, setSelectedTimeRange] = useState<TimeRange>(null);
70
+
71
+ if (value && value.start && value.end) {
72
+ dateRange = value;
73
+ if ('hour' in value.start) {
74
+ timeRange = value as TimeRange;
75
+ }
76
+ }
77
+
78
+ let commitValue = (dateRange: DateRange, timeRange: TimeRange) => {
79
+ setValue({
80
+ start: 'timeZone' in timeRange.start ? timeRange.start.set(toDateFields(dateRange.start)) : toCalendarDateTime(dateRange.start, timeRange.start),
81
+ end: 'timeZone' in timeRange.end ? timeRange.end.set(toDateFields(dateRange.end)) : toCalendarDateTime(dateRange.end, timeRange.end)
82
+ });
83
+ };
84
+
85
+ // Intercept setValue to make sure the Time section is not changed by date selection in Calendar
86
+ let setDateRange = (range: DateRange) => {
87
+ if (hasTime) {
88
+ if (range.start && range.end && timeRange?.start && timeRange?.end) {
89
+ commitValue(range, timeRange);
90
+ } else {
91
+ setSelectedDateRange(range);
92
+ }
93
+ } else if (range.start && range.end) {
94
+ setValue(range);
95
+ } else {
96
+ setSelectedDateRange(range);
97
+ }
98
+
99
+ if (!hasTime) {
100
+ setOpen(false);
101
+ }
102
+ };
103
+
104
+ let setTimeRange = (range: TimeRange) => {
105
+ if (dateRange?.start && dateRange?.end && range.start && range.end) {
106
+ commitValue(dateRange, range);
107
+ } else {
108
+ setSelectedTimeRange(range);
109
+ }
110
+ };
111
+
112
+ let validationState: ValidationState = props.validationState
113
+ || (value != null && (
114
+ isInvalid(value.start, props.minValue, props.maxValue) ||
115
+ isInvalid(value.end, props.minValue, props.maxValue) ||
116
+ (value.end != null && value.start != null && value.end.compare(value.start) < 0)
117
+ ) ? 'invalid' : null);
118
+
119
+ return {
120
+ value,
121
+ setValue,
122
+ dateRange,
123
+ timeRange,
124
+ granularity,
125
+ setDate(part, date) {
126
+ setDateRange({...dateRange, [part]: date});
127
+ },
128
+ setTime(part, time) {
129
+ setTimeRange({...timeRange, [part]: time});
130
+ },
131
+ setDateTime(part, dateTime) {
132
+ setValue({...value, [part]: dateTime});
133
+ },
134
+ setDateRange,
135
+ setTimeRange,
136
+ isOpen,
137
+ setOpen(isOpen) {
138
+ // Commit the selected date range when the calendar is closed. Use a placeholder time if one wasn't set.
139
+ // If only the time range was set and not the date range, don't commit. The state will be preserved until
140
+ // the user opens the popover again.
141
+ if (!isOpen && !(value?.start && value?.end) && dateRange?.start && dateRange?.end && hasTime) {
142
+ commitValue(dateRange, {
143
+ start: timeRange?.start || getPlaceholderTime(props.placeholderValue),
144
+ end: timeRange?.end || getPlaceholderTime(props.placeholderValue)
145
+ });
146
+ }
147
+
148
+ setOpen(isOpen);
149
+ },
150
+ validationState,
151
+ formatValue(locale, fieldOptions) {
152
+ if (!value || !value.start || !value.end) {
153
+ return '';
154
+ }
155
+
156
+ let startTimeZone = 'timeZone' in value.start ? value.start.timeZone : undefined;
157
+ let startGranularity = props.granularity || (value.start && 'minute' in value.start ? 'minute' : 'day');
158
+ let endTimeZone = 'timeZone' in value.end ? value.end.timeZone : undefined;
159
+ let endGranularity = props.granularity || (value.end && 'minute' in value.end ? 'minute' : 'day');
160
+
161
+ let startOptions = getFormatOptions(fieldOptions, {
162
+ granularity: startGranularity,
163
+ timeZone: startTimeZone,
164
+ hideTimeZone: props.hideTimeZone,
165
+ hourCycle: props.hourCycle
166
+ });
167
+
168
+ let startFormatter = new DateFormatter(locale, startOptions);
169
+ let endFormatter: Intl.DateTimeFormat;
170
+ if (startTimeZone === endTimeZone && startGranularity === endGranularity) {
171
+ // Use formatRange, as it results in shorter output when some of the fields
172
+ // are shared between the start and end dates (e.g. the same month).
173
+ // Formatting will fail if the end date is before the start date. Fall back below when that happens.
174
+ try {
175
+ return startFormatter.formatRange(value.start.toDate(startTimeZone), value.end.toDate(endTimeZone));
176
+ } catch (e) {
177
+ // ignore
178
+ }
179
+
180
+ endFormatter = startFormatter;
181
+ } else {
182
+ let endOptions = getFormatOptions(fieldOptions, {
183
+ granularity: endGranularity,
184
+ timeZone: endTimeZone,
185
+ hideTimeZone: props.hideTimeZone,
186
+ hourCycle: props.hourCycle
187
+ });
188
+
189
+ endFormatter = new DateFormatter(locale, endOptions);
190
+ }
191
+
192
+ return `${startFormatter.format(value.start.toDate(startTimeZone))} – ${endFormatter.format(value.end.toDate(endTimeZone))}`;
193
+ },
194
+ confirmPlaceholder() {
195
+ // Need to use ref value here because the value can be set in the same tick as
196
+ // a blur, which means the component won't have re-rendered yet.
197
+ let value = valueRef.current;
198
+ if (value && Boolean(value.start) !== Boolean(value.end)) {
199
+ let calendar = (value.start || value.end).calendar;
200
+ let placeholder = createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone);
201
+ setValue({
202
+ start: value.start || placeholder,
203
+ end: value.end || placeholder
204
+ });
205
+ }
206
+ }
207
+ };
208
+ }
@@ -0,0 +1,72 @@
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, getLocalTimeZone, Time, toCalendarDateTime, today, toTime} from '@internationalized/date';
14
+ import {DateValue, TimePickerProps, TimeValue} from '@react-types/datepicker';
15
+ import {useControlledState} from '@react-stately/utils';
16
+ import {useDatePickerFieldState} from '.';
17
+ import {useMemo} from 'react';
18
+
19
+ interface TimeFieldProps<T extends TimeValue> extends TimePickerProps<T> {
20
+ locale: string,
21
+ createCalendar: (name: string) => Calendar
22
+ }
23
+
24
+ export function useTimeFieldState<T extends TimeValue>(props: TimeFieldProps<T>) {
25
+ let {
26
+ placeholderValue = new Time(),
27
+ minValue,
28
+ maxValue,
29
+ granularity
30
+ } = props;
31
+
32
+ let [value, setValue] = useControlledState<TimeValue>(
33
+ props.value,
34
+ props.defaultValue,
35
+ props.onChange
36
+ );
37
+
38
+ let v = value || placeholderValue;
39
+ let day = v && 'day' in v ? v : undefined;
40
+ let placeholderDate = useMemo(() => convertValue(placeholderValue), [placeholderValue]);
41
+ let minDate = useMemo(() => convertValue(minValue, day), [minValue, day]);
42
+ let maxDate = useMemo(() => convertValue(maxValue, day), [maxValue, day]);
43
+
44
+ let dateTime = useMemo(() => value == null ? null : convertValue(value), [value]);
45
+ let onChange = newValue => {
46
+ setValue(v && 'day' in v ? newValue : newValue && toTime(newValue));
47
+ };
48
+
49
+ return useDatePickerFieldState({
50
+ ...props,
51
+ value: dateTime,
52
+ defaultValue: undefined,
53
+ minValue: minDate,
54
+ maxValue: maxDate,
55
+ onChange,
56
+ granularity: granularity || 'minute',
57
+ maxGranularity: 'hour',
58
+ placeholderValue: placeholderDate
59
+ });
60
+ }
61
+
62
+ function convertValue(value: TimeValue, date: DateValue = today(getLocalTimeZone())) {
63
+ if (!value) {
64
+ return null;
65
+ }
66
+
67
+ if ('day' in value) {
68
+ return value;
69
+ }
70
+
71
+ return toCalendarDateTime(date, value);
72
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,143 @@
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, now, Time, toCalendar, toCalendarDate, toCalendarDateTime} from '@internationalized/date';
14
+ import {DatePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
15
+ import {useRef} from 'react';
16
+
17
+ export function isInvalid(value: DateValue, minValue: DateValue, maxValue: DateValue) {
18
+ return value != null && (
19
+ (minValue != null && value.compare(minValue) < 0) ||
20
+ (maxValue != null && value.compare(maxValue) > 0)
21
+ );
22
+ }
23
+
24
+ export type FieldOptions = Pick<Intl.DateTimeFormatOptions, 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second'>;
25
+ interface FormatterOptions {
26
+ timeZone?: string,
27
+ hideTimeZone?: boolean,
28
+ granularity?: DatePickerProps<any>['granularity'],
29
+ maxGranularity?: 'year' | 'month' | DatePickerProps<any>['granularity'],
30
+ hourCycle?: 12 | 24
31
+ }
32
+
33
+ const DEFAULT_FIELD_OPTIONS: FieldOptions = {
34
+ year: 'numeric',
35
+ month: 'numeric',
36
+ day: 'numeric',
37
+ hour: 'numeric',
38
+ minute: '2-digit',
39
+ second: '2-digit'
40
+ };
41
+
42
+ export function getFormatOptions(
43
+ fieldOptions: FieldOptions,
44
+ options: FormatterOptions
45
+ ): Intl.DateTimeFormatOptions {
46
+ fieldOptions = {...DEFAULT_FIELD_OPTIONS, ...fieldOptions};
47
+ let granularity = options.granularity || 'minute';
48
+ let keys = Object.keys(fieldOptions);
49
+ let startIdx = keys.indexOf(options.maxGranularity ?? 'year');
50
+ if (startIdx < 0) {
51
+ startIdx = 0;
52
+ }
53
+
54
+ let endIdx = keys.indexOf(granularity);
55
+ if (endIdx < 0) {
56
+ endIdx = 2;
57
+ }
58
+
59
+ if (startIdx > endIdx) {
60
+ throw new Error('maxGranularity must be greater than granularity');
61
+ }
62
+
63
+ let opts: Intl.DateTimeFormatOptions = keys.slice(startIdx, endIdx + 1).reduce((opts, key) => {
64
+ opts[key] = fieldOptions[key];
65
+ return opts;
66
+ }, {});
67
+
68
+ if (options.hourCycle != null) {
69
+ opts.hour12 = options.hourCycle === 12;
70
+ }
71
+
72
+ opts.timeZone = options.timeZone || 'UTC';
73
+
74
+ let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second';
75
+ if (hasTime && options.timeZone && !options.hideTimeZone) {
76
+ opts.timeZoneName = 'short';
77
+ }
78
+
79
+ return opts;
80
+ }
81
+
82
+ export function getPlaceholderTime(placeholderValue: DateValue): TimeValue {
83
+ if (placeholderValue && 'hour' in placeholderValue) {
84
+ return placeholderValue;
85
+ }
86
+
87
+ return new Time();
88
+ }
89
+
90
+ export function convertValue(value: DateValue, calendar: Calendar): DateValue {
91
+ if (value === null) {
92
+ return null;
93
+ }
94
+
95
+ if (!value) {
96
+ return undefined;
97
+ }
98
+
99
+ return toCalendar(value, calendar);
100
+ }
101
+
102
+
103
+ export function createPlaceholderDate(placeholderValue: DateValue, granularity: string, calendar: Calendar, timeZone: string) {
104
+ if (placeholderValue) {
105
+ return convertValue(placeholderValue, calendar);
106
+ }
107
+
108
+ let date = toCalendar(now(timeZone).set({
109
+ hour: 0,
110
+ minute: 0,
111
+ second: 0,
112
+ millisecond: 0
113
+ }), calendar);
114
+
115
+ if (granularity === 'year' || granularity === 'month' || granularity === 'day') {
116
+ return toCalendarDate(date);
117
+ }
118
+
119
+ if (!timeZone) {
120
+ return toCalendarDateTime(date);
121
+ }
122
+
123
+ return date;
124
+ }
125
+
126
+ export function useDefaultProps(v: DateValue, granularity: Granularity): [Granularity, string] {
127
+ // Compute default granularity and time zone from the value. If the value becomes null, keep the last values.
128
+ let lastValue = useRef(v);
129
+ if (v) {
130
+ lastValue.current = v;
131
+ }
132
+
133
+ v = lastValue.current;
134
+ let defaultTimeZone = (v && 'timeZone' in v ? v.timeZone : undefined);
135
+ granularity = granularity || (v && 'minute' in v ? 'minute' : 'day');
136
+
137
+ // props.granularity must actually exist in the value if one is provided.
138
+ if (v && !(granularity in v)) {
139
+ throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
140
+ }
141
+
142
+ return [granularity, defaultTimeZone];
143
+ }