@instructure/ui-date-input 9.6.1-snapshot-2 → 9.7.2

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.
package/CHANGELOG.md CHANGED
@@ -3,12 +3,28 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
- ## [9.6.1-snapshot-2](https://github.com/instructure/instructure-ui/compare/v9.6.0...v9.6.1-snapshot-2) (2024-09-06)
6
+ ## [9.7.2](https://github.com/instructure/instructure-ui/compare/v9.7.0...v9.7.2) (2024-10-10)
7
+
8
+ **Note:** Version bump only for package @instructure/ui-date-input
9
+
10
+
11
+
12
+
13
+
14
+ ## [9.7.1](https://github.com/instructure/instructure-ui/compare/v9.7.0...v9.7.1) (2024-10-10)
15
+
16
+ **Note:** Version bump only for package @instructure/ui-date-input
17
+
18
+
19
+
20
+
21
+
22
+ # [9.7.0](https://github.com/instructure/instructure-ui/compare/v9.6.0...v9.7.0) (2024-09-23)
7
23
 
8
24
 
9
25
  ### Features
10
26
 
11
- * **ui-date-input:** improve DateInput2 api, extend docs ([42c83a2](https://github.com/instructure/instructure-ui/commit/42c83a240434dd52233c482292caa556babb5c3a))
27
+ * **ui-date-input:** improve DateInput2 api, extend docs ([f369604](https://github.com/instructure/instructure-ui/commit/f3696040d59f9baf9b9a27070e6fbc3d458e4495))
12
28
 
13
29
 
14
30
 
@@ -35,45 +35,75 @@ import { passthroughProps } from '@instructure/ui-react-utils';
35
35
  import { ApplyLocaleContext, Locale } from '@instructure/ui-i18n';
36
36
  import { jsx } from '@instructure/emotion';
37
37
  import { propTypes } from './props';
38
- /*
39
- * Tries parsing a date in a given timezone, if it's not possible, returns an empty string
40
- * If parsing is successful an ISO formatted datetime string is returned in UTC timezone
41
- */
42
- function timezoneDateToUtc(dateString, timezone) {
43
- // Don't try to parse short dateString, they are incomplete
44
- if (dateString.length < 10) {
45
- return '';
46
- }
38
+ function parseLocaleDate(dateString = '', locale, timeZone) {
39
+ // This function may seem complicated but it basically does one thing:
40
+ // Given a dateString, a locale and a timeZone. The dateString is assumed to be formatted according
41
+ // to the locale. So if the locale is `en-us` the dateString is expected to be in the format of M/D/YYYY.
42
+ // The dateString is also assumed to be in the given timeZone, so "1/1/2020" in "America/Los_Angeles" timezone is
43
+ // expected to be "2020-01-01T08:00:00.000Z" in UTC time.
44
+ // This function tries to parse the dateString taking these variables into account and return a javascript Date object
45
+ // that is adjusted to be in UTC.
46
+
47
+ // Split string on '.', whitespace, '/', ',' or '-' using regex: /[.\s/.-]+/.
48
+ // The '+' allows splitting on consecutive delimiters.
49
+ // `.filter(Boolean)` is needed because some locales have a delimeter at the end (e.g.: hungarian dates are formatted as `2024. 09. 19.`)
50
+ const splitDate = dateString.split(/[,.\s/.-]+/).filter(Boolean);
51
+
52
+ // create a locale formatted new date to later extract the order and delimeter information
53
+ const localeDate = new Intl.DateTimeFormat(locale).formatToParts(new Date());
54
+ let index = 0;
55
+ let day, month, year;
56
+ localeDate.forEach(part => {
57
+ if (part.type === 'month') {
58
+ month = parseInt(splitDate[index], 10);
59
+ index++;
60
+ } else if (part.type === 'day') {
61
+ day = parseInt(splitDate[index], 10);
62
+ index++;
63
+ } else if (part.type === 'year') {
64
+ year = parseInt(splitDate[index], 10);
65
+ index++;
66
+ }
67
+ });
47
68
 
48
- // Create a Date object from the input date string
49
- const date = new Date(dateString);
69
+ // sensible limitations
70
+ if (!year || !month || !day || year < 1000 || year > 9999) return null;
50
71
 
51
- // Check if the date is valid
52
- if (isNaN(date.getTime())) {
53
- return '';
72
+ // create utc date from year, month (zero indexed) and day
73
+ const date = new Date(Date.UTC(year, month - 1, day));
74
+ if (date.getMonth() !== month - 1 || date.getDate() !== day) {
75
+ // Check if the Date object adjusts the values. If it does, the input is invalid.
76
+ return null;
54
77
  }
55
78
 
56
- // snippet from https://stackoverflow.com/a/57842203
57
- // but it might need to be improved:
58
- // "This produces incorrect datetimes for several hours surrounding daylight saving times if the
59
- // computer running the code is in a zone that doesn't obey the same daylight saving shifts as the target zone."
60
- const utcDate = new Date(date.toLocaleString('en-US', {
61
- timeZone: 'UTC'
62
- }));
63
- const tzDate = new Date(date.toLocaleString('en-US', {
64
- timeZone: timezone
65
- }));
66
- const offset = utcDate.getTime() - tzDate.getTime();
67
- const newDate = new Date(date.getTime() + offset);
68
- return newDate.toISOString();
69
- }
70
- function defaultDateFormatter(dateString, locale, timezone) {
71
- return new Date(dateString).toLocaleDateString(locale, {
72
- month: 'long',
79
+ // Format date string in the provided timezone. The locale here is irrelevant, we only care about how to time is adjusted for the timezone.
80
+ const parts = new Intl.DateTimeFormat('en-US', {
81
+ timeZone,
73
82
  year: 'numeric',
74
- day: 'numeric',
75
- timeZone: timezone
76
- });
83
+ month: '2-digit',
84
+ day: '2-digit',
85
+ hour: '2-digit',
86
+ minute: '2-digit',
87
+ second: '2-digit',
88
+ hour12: false
89
+ }).formatToParts(date);
90
+
91
+ // Extract the date and time parts from the formatted string
92
+ const dateStringInTimezone = parts.reduce((acc, part) => {
93
+ return part.type === 'literal' ? acc : {
94
+ ...acc,
95
+ [part.type]: part.value
96
+ };
97
+ }, {});
98
+
99
+ // Create a date string in the format 'YYYY-MM-DDTHH:mm:ss'
100
+ const dateInTimezone = `${dateStringInTimezone.year}-${dateStringInTimezone.month}-${dateStringInTimezone.day}T${dateStringInTimezone.hour}:${dateStringInTimezone.minute}:${dateStringInTimezone.second}`;
101
+
102
+ // Calculate time difference for timezone offset
103
+ const timeDiff = new Date(dateInTimezone + 'Z').getTime() - date.getTime();
104
+ const utcTime = new Date(date.getTime() - timeDiff);
105
+ // Return the UTC Date corresponding to the time in the specified timezone
106
+ return utcTime;
77
107
  }
78
108
 
79
109
  /**
@@ -88,7 +118,6 @@ const DateInput2 = ({
88
118
  screenReaderLabels,
89
119
  isRequired = false,
90
120
  interaction = 'enabled',
91
- size = 'medium',
92
121
  isInline = false,
93
122
  value,
94
123
  messages,
@@ -96,12 +125,12 @@ const DateInput2 = ({
96
125
  onChange,
97
126
  onBlur,
98
127
  withYearPicker,
99
- onRequestValidateDate,
100
128
  invalidDateErrorMessage,
101
129
  locale,
102
130
  timezone,
103
131
  placeholder,
104
- formatDate = defaultDateFormatter,
132
+ dateFormat,
133
+ onRequestValidateDate,
105
134
  // margin, TODO enable this prop
106
135
  ...rest
107
136
  }) => {
@@ -124,75 +153,111 @@ const DateInput2 = ({
124
153
  // default to the system's timezone
125
154
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
126
155
  };
127
- const _useState = useState(value ? formatDate(value, getLocale(), getTimezone()) : ''),
156
+ const _useState = useState(messages || []),
128
157
  _useState2 = _slicedToArray(_useState, 2),
129
- inputValue = _useState2[0],
130
- setInputValue = _useState2[1];
131
- const _useState3 = useState(messages || []),
158
+ inputMessages = _useState2[0],
159
+ setInputMessages = _useState2[1];
160
+ const _useState3 = useState(false),
132
161
  _useState4 = _slicedToArray(_useState3, 2),
133
- inputMessages = _useState4[0],
134
- setInputMessages = _useState4[1];
135
- const _useState5 = useState(false),
136
- _useState6 = _slicedToArray(_useState5, 2),
137
- showPopover = _useState6[0],
138
- setShowPopover = _useState6[1];
162
+ showPopover = _useState4[0],
163
+ setShowPopover = _useState4[1];
139
164
  useEffect(() => {
140
- setInputMessages(messages || []);
165
+ // don't set input messages if there is an error set already
166
+ if (!inputMessages) {
167
+ setInputMessages(messages || []);
168
+ }
141
169
  }, [messages]);
142
170
  useEffect(() => {
143
- validateInput(true);
144
- }, [inputValue]);
171
+ const _parseDate = parseDate(value),
172
+ _parseDate2 = _slicedToArray(_parseDate, 2),
173
+ utcIsoDate = _parseDate2[1];
174
+ // clear error messages if date becomes valid
175
+ if (utcIsoDate || !value) {
176
+ setInputMessages(messages || []);
177
+ }
178
+ }, [value]);
179
+ const parseDate = (dateString = '') => {
180
+ let date = null;
181
+ if (dateFormat) {
182
+ if (typeof dateFormat === 'string') {
183
+ // use dateFormat instead of the user locale
184
+ date = parseLocaleDate(dateString, dateFormat, getTimezone());
185
+ } else if (dateFormat.parser) {
186
+ date = dateFormat.parser(dateString);
187
+ }
188
+ } else {
189
+ // no dateFormat prop passed, use locale for formatting
190
+ date = parseLocaleDate(dateString, getLocale(), getTimezone());
191
+ }
192
+ return date ? [formatDate(date), date.toISOString()] : ['', ''];
193
+ };
194
+ const formatDate = date => {
195
+ // use formatter function if provided
196
+ if (typeof dateFormat !== 'string' && dateFormat !== null && dateFormat !== void 0 && dateFormat.formatter) {
197
+ return dateFormat.formatter(date);
198
+ }
199
+ // if dateFormat set to a locale, use that, otherwise default to the user's locale
200
+ return date.toLocaleDateString(typeof dateFormat === 'string' ? dateFormat : getLocale(), {
201
+ timeZone: getTimezone(),
202
+ calendar: 'gregory',
203
+ numberingSystem: 'latn'
204
+ });
205
+ };
206
+ const getDateFromatHint = () => {
207
+ const exampleDate = new Date('2024-09-01');
208
+ const formattedDate = formatDate(exampleDate);
209
+
210
+ // Create a regular expression to find the exact match of the number
211
+ const regex = n => {
212
+ return new RegExp(`(?<!\\d)0*${n}(?!\\d)`, 'g');
213
+ };
214
+
215
+ // Replace the matched number with the same number of dashes
216
+ const year = `${exampleDate.getFullYear()}`;
217
+ const month = `${exampleDate.getMonth() + 1}`;
218
+ const day = `${exampleDate.getDate()}`;
219
+ return formattedDate.replace(regex(year), match => 'Y'.repeat(match.length)).replace(regex(month), match => 'M'.repeat(match.length)).replace(regex(day), match => 'D'.repeat(match.length));
220
+ };
145
221
  const handleInputChange = (e, newValue) => {
146
- setInputValue(newValue);
147
- const parsedInput = timezoneDateToUtc(newValue, getTimezone());
148
- onChange === null || onChange === void 0 ? void 0 : onChange(e, parsedInput, newValue);
222
+ const _parseDate3 = parseDate(newValue),
223
+ _parseDate4 = _slicedToArray(_parseDate3, 2),
224
+ utcIsoDate = _parseDate4[1];
225
+ onChange === null || onChange === void 0 ? void 0 : onChange(e, newValue, utcIsoDate);
149
226
  };
150
227
  const handleDateSelected = (dateString, _momentDate, e) => {
151
- const formattedDate = formatDate(dateString, getLocale(), getTimezone());
152
- setInputValue(formattedDate);
153
228
  setShowPopover(false);
154
- onChange === null || onChange === void 0 ? void 0 : onChange(e, dateString, formattedDate);
155
- onRequestValidateDate === null || onRequestValidateDate === void 0 ? void 0 : onRequestValidateDate(dateString, true);
229
+ const newValue = formatDate(new Date(dateString));
230
+ onChange === null || onChange === void 0 ? void 0 : onChange(e, newValue, dateString);
231
+ onRequestValidateDate === null || onRequestValidateDate === void 0 ? void 0 : onRequestValidateDate(e, newValue, dateString);
156
232
  };
157
-
158
- // onlyRemoveError is used to remove the error msg immediately when the user inputs a valid date (and don't wait for blur event)
159
- const validateInput = (onlyRemoveError = false) => {
160
- // don't validate empty input
161
- if (!inputValue || timezoneDateToUtc(inputValue, getTimezone()) || value) {
162
- setInputMessages(messages || []);
163
- return true;
164
- }
165
- // only show error if there is no user provided validation callback
166
- if (!onlyRemoveError && typeof invalidDateErrorMessage === 'string' && !onRequestValidateDate) {
233
+ const handleBlur = e => {
234
+ const _parseDate5 = parseDate(value),
235
+ _parseDate6 = _slicedToArray(_parseDate5, 2),
236
+ localeDate = _parseDate6[0],
237
+ utcIsoDate = _parseDate6[1];
238
+ if (localeDate) {
239
+ if (localeDate !== value) {
240
+ onChange === null || onChange === void 0 ? void 0 : onChange(e, localeDate, utcIsoDate);
241
+ }
242
+ } else if (value && invalidDateErrorMessage) {
167
243
  setInputMessages([{
168
244
  type: 'error',
169
245
  text: invalidDateErrorMessage
170
246
  }]);
171
247
  }
172
- return false;
173
- };
174
- const handleBlur = e => {
175
- if (value) {
176
- const formattedDate = formatDate(value, getLocale(), getTimezone());
177
- if (formattedDate !== inputValue) {
178
- setInputValue(formattedDate);
179
- onChange === null || onChange === void 0 ? void 0 : onChange(e, value, formattedDate);
180
- }
181
- }
182
- validateInput(false);
183
- onRequestValidateDate === null || onRequestValidateDate === void 0 ? void 0 : onRequestValidateDate(value, !!value);
184
- onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
248
+ onRequestValidateDate === null || onRequestValidateDate === void 0 ? void 0 : onRequestValidateDate(e, value || '', utcIsoDate);
249
+ onBlur === null || onBlur === void 0 ? void 0 : onBlur(e, value || '', utcIsoDate);
185
250
  };
251
+ const selectedDate = parseDate(value)[1];
186
252
  return jsx(TextInput, Object.assign({}, passthroughProps(rest), {
187
253
  // margin={'large'} TODO add this prop to TextInput
188
254
  renderLabel: renderLabel,
189
255
  onChange: handleInputChange,
190
256
  onBlur: handleBlur,
191
257
  isRequired: isRequired,
192
- value: inputValue,
193
- placeholder: placeholder,
258
+ value: value,
259
+ placeholder: placeholder !== null && placeholder !== void 0 ? placeholder : getDateFromatHint(),
194
260
  width: width,
195
- size: size,
196
261
  display: isInline ? 'inline-block' : 'block',
197
262
  messages: inputMessages,
198
263
  interaction: interaction,
@@ -202,7 +267,6 @@ const DateInput2 = ({
202
267
  withBorder: false,
203
268
  screenReaderLabel: screenReaderLabels.calendarIcon,
204
269
  shape: "circle",
205
- size: size,
206
270
  interaction: interaction
207
271
  }, _IconCalendarMonthLin || (_IconCalendarMonthLin = jsx(IconCalendarMonthLine, null))),
208
272
  isShowingContent: showPopover,
@@ -215,8 +279,8 @@ const DateInput2 = ({
215
279
  }, jsx(Calendar, {
216
280
  withYearPicker: withYearPicker,
217
281
  onDateSelected: handleDateSelected,
218
- selectedDate: value,
219
- visibleMonth: value,
282
+ selectedDate: selectedDate,
283
+ visibleMonth: selectedDate,
220
284
  locale: getLocale(),
221
285
  timezone: getTimezone(),
222
286
  role: "listbox",
@@ -29,7 +29,6 @@ const propTypes = {
29
29
  renderLabel: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
30
30
  screenReaderLabels: PropTypes.object.isRequired,
31
31
  value: controllable(PropTypes.string),
32
- size: PropTypes.oneOf(['small', 'medium', 'large']),
33
32
  placeholder: PropTypes.string,
34
33
  onChange: PropTypes.func,
35
34
  onBlur: PropTypes.func,
@@ -38,11 +37,11 @@ const propTypes = {
38
37
  isInline: PropTypes.bool,
39
38
  width: PropTypes.string,
40
39
  messages: PropTypes.arrayOf(FormPropTypes.message),
41
- onRequestValidateDate: PropTypes.func,
42
40
  invalidDateErrorMessage: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
43
41
  locale: PropTypes.string,
44
42
  timezone: PropTypes.string,
45
43
  withYearPicker: PropTypes.object,
46
- formatDate: PropTypes.func
44
+ dateFormat: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
45
+ onRequestValidateDate: PropTypes.func
47
46
  };
48
47
  export { propTypes };