-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathuseField.utils.ts
883 lines (756 loc) · 25.6 KB
/
useField.utils.ts
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
import {
AvailableAdjustKeyCode,
FieldSectionsValueBoundaries,
SectionNeighbors,
SectionOrdering,
FieldSectionValueBoundaries,
FieldParsedSelectedSections,
} from './useField.types';
import {
FieldSectionType,
FieldSection,
MuiPickersAdapter,
FieldSectionContentType,
PickersTimezone,
PickerValidDate,
FieldSelectedSections,
PickerValueType,
InferFieldSection,
} from '../../../models';
import { getMonthsInYear } from '../../utils/date-utils';
import { PickerValidValue } from '../../models';
export const getDateSectionConfigFromFormatToken = (
utils: MuiPickersAdapter,
formatToken: string,
): Pick<FieldSection, 'type' | 'contentType'> & { maxLength: number | undefined } => {
const config = utils.formatTokenMap[formatToken];
if (config == null) {
throw new Error(
[
`MUI X: The token "${formatToken}" is not supported by the Date and Time Pickers.`,
'Please try using another token or open an issue on https://github.com/mui/mui-x/issues/new/choose if you think it should be supported.',
].join('\n'),
);
}
if (typeof config === 'string') {
return {
type: config,
contentType: config === 'meridiem' ? 'letter' : 'digit',
maxLength: undefined,
};
}
return {
type: config.sectionType,
contentType: config.contentType,
maxLength: config.maxLength,
};
};
const getDeltaFromKeyCode = (keyCode: Omit<AvailableAdjustKeyCode, 'Home' | 'End'>) => {
switch (keyCode) {
case 'ArrowUp':
return 1;
case 'ArrowDown':
return -1;
case 'PageUp':
return 5;
case 'PageDown':
return -5;
default:
return 0;
}
};
export const getDaysInWeekStr = (utils: MuiPickersAdapter, format: string) => {
const elements: PickerValidDate[] = [];
const now = utils.date(undefined, 'default');
const startDate = utils.startOfWeek(now);
const endDate = utils.endOfWeek(now);
let current = startDate;
while (utils.isBefore(current, endDate)) {
elements.push(current);
current = utils.addDays(current, 1);
}
return elements.map((weekDay) => utils.formatByString(weekDay, format));
};
export const getLetterEditingOptions = (
utils: MuiPickersAdapter,
timezone: PickersTimezone,
sectionType: FieldSectionType,
format: string,
) => {
switch (sectionType) {
case 'month': {
return getMonthsInYear(utils, utils.date(undefined, timezone)).map((month) =>
utils.formatByString(month, format!),
);
}
case 'weekDay': {
return getDaysInWeekStr(utils, format);
}
case 'meridiem': {
const now = utils.date(undefined, timezone);
return [utils.startOfDay(now), utils.endOfDay(now)].map((date) =>
utils.formatByString(date, format),
);
}
default: {
return [];
}
}
};
// This format should be the same on all the adapters
// If some adapter does not respect this convention, then we will need to hardcode the format on each adapter.
export const FORMAT_SECONDS_NO_LEADING_ZEROS = 's';
const NON_LOCALIZED_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
export const getLocalizedDigits = (utils: MuiPickersAdapter) => {
const today = utils.date(undefined);
const formattedZero = utils.formatByString(
utils.setSeconds(today, 0),
FORMAT_SECONDS_NO_LEADING_ZEROS,
);
if (formattedZero === '0') {
return NON_LOCALIZED_DIGITS;
}
return Array.from({ length: 10 }).map((_, index) =>
utils.formatByString(utils.setSeconds(today, index), FORMAT_SECONDS_NO_LEADING_ZEROS),
);
};
export const removeLocalizedDigits = (valueStr: string, localizedDigits: string[]) => {
if (localizedDigits[0] === '0') {
return valueStr;
}
const digits: string[] = [];
let currentFormattedDigit = '';
for (let i = 0; i < valueStr.length; i += 1) {
currentFormattedDigit += valueStr[i];
const matchingDigitIndex = localizedDigits.indexOf(currentFormattedDigit);
if (matchingDigitIndex > -1) {
digits.push(matchingDigitIndex.toString());
currentFormattedDigit = '';
}
}
return digits.join('');
};
export const applyLocalizedDigits = (valueStr: string, localizedDigits: string[]) => {
if (localizedDigits[0] === '0') {
return valueStr;
}
return valueStr
.split('')
.map((char) => localizedDigits[Number(char)])
.join('');
};
export const isStringNumber = (valueStr: string, localizedDigits: string[]) => {
const nonLocalizedValueStr = removeLocalizedDigits(valueStr, localizedDigits);
// `Number(' ')` returns `0` even if ' ' is not a valid number.
return nonLocalizedValueStr !== ' ' && !Number.isNaN(Number(nonLocalizedValueStr));
};
/**
* Remove the leading zeroes to a digit section value.
* E.g.: `03` => `3`
* Warning: Should only be called with non-localized digits. Call `removeLocalizedDigits` with your value if needed.
*/
export const cleanLeadingZeros = (valueStr: string, size: number) => {
let cleanValueStr = valueStr;
// Remove the leading zeros
cleanValueStr = Number(cleanValueStr).toString();
// Add enough leading zeros to fill the section
while (cleanValueStr.length < size) {
cleanValueStr = `0${cleanValueStr}`;
}
return cleanValueStr;
};
export const cleanDigitSectionValue = (
utils: MuiPickersAdapter,
value: number,
sectionBoundaries: FieldSectionValueBoundaries<any>,
localizedDigits: string[],
section: Pick<
FieldSection,
| 'format'
| 'type'
| 'contentType'
| 'hasLeadingZerosInFormat'
| 'hasLeadingZerosInInput'
| 'maxLength'
>,
) => {
if (process.env.NODE_ENV !== 'production') {
if (section.type !== 'day' && section.contentType === 'digit-with-letter') {
throw new Error(
[
`MUI X: The token "${section.format}" is a digit format with letter in it.'
This type of format is only supported for 'day' sections`,
].join('\n'),
);
}
}
if (section.type === 'day' && section.contentType === 'digit-with-letter') {
const date = utils.setDate(
(sectionBoundaries as FieldSectionValueBoundaries<'day'>).longestMonth,
value,
);
return utils.formatByString(date, section.format);
}
// queryValue without leading `0` (`01` => `1`)
let valueStr = value.toString();
if (section.hasLeadingZerosInInput) {
valueStr = cleanLeadingZeros(valueStr, section.maxLength!);
}
return applyLocalizedDigits(valueStr, localizedDigits);
};
export const adjustSectionValue = <TValue extends PickerValidValue>(
utils: MuiPickersAdapter,
timezone: PickersTimezone,
section: InferFieldSection<TValue>,
keyCode: AvailableAdjustKeyCode,
sectionsValueBoundaries: FieldSectionsValueBoundaries,
localizedDigits: string[],
activeDate: PickerValidDate | null,
stepsAttributes?: { minutesStep?: number },
): string => {
const delta = getDeltaFromKeyCode(keyCode);
const isStart = keyCode === 'Home';
const isEnd = keyCode === 'End';
const shouldSetAbsolute = section.value === '' || isStart || isEnd;
const adjustDigitSection = () => {
const sectionBoundaries = sectionsValueBoundaries[section.type]({
currentDate: activeDate,
format: section.format,
contentType: section.contentType,
});
const getCleanValue = (value: number) =>
cleanDigitSectionValue(utils, value, sectionBoundaries, localizedDigits, section);
const step =
section.type === 'minutes' && stepsAttributes?.minutesStep ? stepsAttributes.minutesStep : 1;
const currentSectionValue = parseInt(removeLocalizedDigits(section.value, localizedDigits), 10);
let newSectionValueNumber = currentSectionValue + delta * step;
if (shouldSetAbsolute) {
if (section.type === 'year' && !isEnd && !isStart) {
return utils.formatByString(utils.date(undefined, timezone), section.format);
}
if (delta > 0 || isStart) {
newSectionValueNumber = sectionBoundaries.minimum;
} else {
newSectionValueNumber = sectionBoundaries.maximum;
}
}
if (newSectionValueNumber % step !== 0) {
if (delta < 0 || isStart) {
newSectionValueNumber += step - ((step + newSectionValueNumber) % step); // for JS -3 % 5 = -3 (should be 2)
}
if (delta > 0 || isEnd) {
newSectionValueNumber -= newSectionValueNumber % step;
}
}
if (newSectionValueNumber > sectionBoundaries.maximum) {
return getCleanValue(
sectionBoundaries.minimum +
((newSectionValueNumber - sectionBoundaries.maximum - 1) %
(sectionBoundaries.maximum - sectionBoundaries.minimum + 1)),
);
}
if (newSectionValueNumber < sectionBoundaries.minimum) {
return getCleanValue(
sectionBoundaries.maximum -
((sectionBoundaries.minimum - newSectionValueNumber - 1) %
(sectionBoundaries.maximum - sectionBoundaries.minimum + 1)),
);
}
return getCleanValue(newSectionValueNumber);
};
const adjustLetterSection = () => {
const options = getLetterEditingOptions(utils, timezone, section.type, section.format);
if (options.length === 0) {
return section.value;
}
if (shouldSetAbsolute) {
if (delta > 0 || isStart) {
return options[0];
}
return options[options.length - 1];
}
const currentOptionIndex = options.indexOf(section.value);
const newOptionIndex = (currentOptionIndex + delta) % options.length;
const clampedIndex = (newOptionIndex + options.length) % options.length;
return options[clampedIndex];
};
if (section.contentType === 'digit' || section.contentType === 'digit-with-letter') {
return adjustDigitSection();
}
return adjustLetterSection();
};
export const getSectionVisibleValue = (
section: FieldSection,
target: 'input-rtl' | 'input-ltr' | 'non-input',
localizedDigits: string[],
) => {
let value = section.value || section.placeholder;
const hasLeadingZeros =
target === 'non-input' ? section.hasLeadingZerosInFormat : section.hasLeadingZerosInInput;
if (
target === 'non-input' &&
section.hasLeadingZerosInInput &&
!section.hasLeadingZerosInFormat
) {
value = Number(removeLocalizedDigits(value, localizedDigits)).toString();
}
// In the input, we add an empty character at the end of each section without leading zeros.
// This makes sure that `onChange` will always be fired.
// Otherwise, when your input value equals `1/dd/yyyy` (format `M/DD/YYYY` on DayJs),
// If you press `1`, on the first section, the new value is also `1/dd/yyyy`,
// So the browser will not fire the input `onChange`.
const shouldAddInvisibleSpace =
['input-rtl', 'input-ltr'].includes(target) &&
section.contentType === 'digit' &&
!hasLeadingZeros &&
value.length === 1;
if (shouldAddInvisibleSpace) {
value = `${value}\u200e`;
}
if (target === 'input-rtl') {
value = `\u2068${value}\u2069`;
}
return value;
};
export const changeSectionValueFormat = (
utils: MuiPickersAdapter,
valueStr: string,
currentFormat: string,
newFormat: string,
) => {
if (process.env.NODE_ENV !== 'production') {
if (getDateSectionConfigFromFormatToken(utils, currentFormat).type === 'weekDay') {
throw new Error("changeSectionValueFormat doesn't support week day formats");
}
}
return utils.formatByString(utils.parse(valueStr, currentFormat)!, newFormat);
};
const isFourDigitYearFormat = (utils: MuiPickersAdapter, format: string) =>
utils.formatByString(utils.date(undefined, 'system'), format).length === 4;
export const doesSectionFormatHaveLeadingZeros = (
utils: MuiPickersAdapter,
contentType: FieldSectionContentType,
sectionType: FieldSectionType,
format: string,
) => {
if (contentType !== 'digit') {
return false;
}
const now = utils.date(undefined, 'default');
switch (sectionType) {
// We can't use `changeSectionValueFormat`, because `utils.parse('1', 'YYYY')` returns `1971` instead of `1`.
case 'year': {
if (isFourDigitYearFormat(utils, format)) {
const formatted0001 = utils.formatByString(utils.setYear(now, 1), format);
return formatted0001 === '0001';
}
const formatted2001 = utils.formatByString(utils.setYear(now, 2001), format);
return formatted2001 === '01';
}
case 'month': {
return utils.formatByString(utils.startOfYear(now), format).length > 1;
}
case 'day': {
return utils.formatByString(utils.startOfMonth(now), format).length > 1;
}
case 'weekDay': {
return utils.formatByString(utils.startOfWeek(now), format).length > 1;
}
case 'hours': {
return utils.formatByString(utils.setHours(now, 1), format).length > 1;
}
case 'minutes': {
return utils.formatByString(utils.setMinutes(now, 1), format).length > 1;
}
case 'seconds': {
return utils.formatByString(utils.setSeconds(now, 1), format).length > 1;
}
default: {
throw new Error('Invalid section type');
}
}
};
/**
* Some date libraries like `dayjs` don't support parsing from date with escaped characters.
* To make sure that the parsing works, we are building a format and a date without any separator.
*/
export const getDateFromDateSections = (
utils: MuiPickersAdapter,
sections: FieldSection[],
localizedDigits: string[],
): PickerValidDate => {
// If we have both a day and a weekDay section,
// Then we skip the weekDay in the parsing because libraries like dayjs can't parse complicated formats containing a weekDay.
// dayjs(dayjs().format('dddd MMMM D YYYY'), 'dddd MMMM D YYYY')) // returns `Invalid Date` even if the format is valid.
const shouldSkipWeekDays = sections.some((section) => section.type === 'day');
const sectionFormats: string[] = [];
const sectionValues: string[] = [];
for (let i = 0; i < sections.length; i += 1) {
const section = sections[i];
const shouldSkip = shouldSkipWeekDays && section.type === 'weekDay';
if (!shouldSkip) {
sectionFormats.push(section.format);
sectionValues.push(getSectionVisibleValue(section, 'non-input', localizedDigits));
}
}
const formatWithoutSeparator = sectionFormats.join(' ');
const dateWithoutSeparatorStr = sectionValues.join(' ');
return utils.parse(dateWithoutSeparatorStr, formatWithoutSeparator)!;
};
export const createDateStrForV7HiddenInputFromSections = (sections: FieldSection[]) =>
sections
.map((section) => {
return `${section.startSeparator}${section.value || section.placeholder}${
section.endSeparator
}`;
})
.join('');
export const createDateStrForV6InputFromSections = (
sections: FieldSection[],
localizedDigits: string[],
isRtl: boolean,
) => {
const formattedSections = sections.map((section) => {
const dateValue = getSectionVisibleValue(
section,
isRtl ? 'input-rtl' : 'input-ltr',
localizedDigits,
);
return `${section.startSeparator}${dateValue}${section.endSeparator}`;
});
const dateStr = formattedSections.join('');
if (!isRtl) {
return dateStr;
}
// \u2066: start left-to-right isolation
// \u2067: start right-to-left isolation
// \u2068: start first strong character isolation
// \u2069: pop isolation
// wrap into an isolated group such that separators can split the string in smaller ones by adding \u2069\u2068
return `\u2066${dateStr}\u2069`;
};
export const getSectionsBoundaries = (
utils: MuiPickersAdapter,
localizedDigits: string[],
timezone: PickersTimezone,
): FieldSectionsValueBoundaries => {
const today = utils.date(undefined, timezone);
const endOfYear = utils.endOfYear(today);
const endOfDay = utils.endOfDay(today);
const { maxDaysInMonth, longestMonth } = getMonthsInYear(utils, today).reduce(
(acc, month) => {
const daysInMonth = utils.getDaysInMonth(month);
if (daysInMonth > acc.maxDaysInMonth) {
return { maxDaysInMonth: daysInMonth, longestMonth: month };
}
return acc;
},
{ maxDaysInMonth: 0, longestMonth: null as PickerValidDate | null },
);
return {
year: ({ format }) => ({
minimum: 0,
maximum: isFourDigitYearFormat(utils, format) ? 9999 : 99,
}),
month: () => ({
minimum: 1,
// Assumption: All years have the same amount of months
maximum: utils.getMonth(endOfYear) + 1,
}),
day: ({ currentDate }) => ({
minimum: 1,
maximum: utils.isValid(currentDate) ? utils.getDaysInMonth(currentDate) : maxDaysInMonth,
longestMonth: longestMonth!,
}),
weekDay: ({ format, contentType }) => {
if (contentType === 'digit') {
const daysInWeek = getDaysInWeekStr(utils, format).map(Number);
return {
minimum: Math.min(...daysInWeek),
maximum: Math.max(...daysInWeek),
};
}
return {
minimum: 1,
maximum: 7,
};
},
hours: ({ format }) => {
const lastHourInDay = utils.getHours(endOfDay);
const hasMeridiem =
removeLocalizedDigits(
utils.formatByString(utils.endOfDay(today), format),
localizedDigits,
) !== lastHourInDay.toString();
if (hasMeridiem) {
return {
minimum: 1,
maximum: Number(
removeLocalizedDigits(
utils.formatByString(utils.startOfDay(today), format),
localizedDigits,
),
),
};
}
return {
minimum: 0,
maximum: lastHourInDay,
};
},
minutes: () => ({
minimum: 0,
// Assumption: All years have the same amount of minutes
maximum: utils.getMinutes(endOfDay),
}),
seconds: () => ({
minimum: 0,
// Assumption: All years have the same amount of seconds
maximum: utils.getSeconds(endOfDay),
}),
meridiem: () => ({
minimum: 0,
maximum: 1,
}),
empty: () => ({
minimum: 0,
maximum: 0,
}),
};
};
let warnedOnceInvalidSection = false;
export const validateSections = <TValue extends PickerValidValue>(
sections: InferFieldSection<TValue>[],
valueType: PickerValueType,
) => {
if (process.env.NODE_ENV !== 'production') {
if (!warnedOnceInvalidSection) {
const supportedSections: FieldSectionType[] = ['empty'];
if (['date', 'date-time'].includes(valueType)) {
supportedSections.push('weekDay', 'day', 'month', 'year');
}
if (['time', 'date-time'].includes(valueType)) {
supportedSections.push('hours', 'minutes', 'seconds', 'meridiem');
}
const invalidSection = sections.find((section) => !supportedSections.includes(section.type));
if (invalidSection) {
console.warn(
`MUI X: The field component you are using is not compatible with the "${invalidSection.type}" date section.`,
`The supported date sections are ["${supportedSections.join('", "')}"]\`.`,
);
warnedOnceInvalidSection = true;
}
}
}
};
const transferDateSectionValue = (
utils: MuiPickersAdapter,
section: FieldSection,
dateToTransferFrom: PickerValidDate,
dateToTransferTo: PickerValidDate,
) => {
switch (section.type) {
case 'year': {
return utils.setYear(dateToTransferTo, utils.getYear(dateToTransferFrom));
}
case 'month': {
return utils.setMonth(dateToTransferTo, utils.getMonth(dateToTransferFrom));
}
case 'weekDay': {
const formattedDaysInWeek = getDaysInWeekStr(utils, section.format);
const dayInWeekStrOfActiveDate = utils.formatByString(dateToTransferFrom, section.format);
const dayInWeekOfActiveDate = formattedDaysInWeek.indexOf(dayInWeekStrOfActiveDate);
const dayInWeekOfNewSectionValue = formattedDaysInWeek.indexOf(section.value);
const diff = dayInWeekOfNewSectionValue - dayInWeekOfActiveDate;
return utils.addDays(dateToTransferFrom, diff);
}
case 'day': {
return utils.setDate(dateToTransferTo, utils.getDate(dateToTransferFrom));
}
case 'meridiem': {
const isAM = utils.getHours(dateToTransferFrom) < 12;
const mergedDateHours = utils.getHours(dateToTransferTo);
if (isAM && mergedDateHours >= 12) {
return utils.addHours(dateToTransferTo, -12);
}
if (!isAM && mergedDateHours < 12) {
return utils.addHours(dateToTransferTo, 12);
}
return dateToTransferTo;
}
case 'hours': {
return utils.setHours(dateToTransferTo, utils.getHours(dateToTransferFrom));
}
case 'minutes': {
return utils.setMinutes(dateToTransferTo, utils.getMinutes(dateToTransferFrom));
}
case 'seconds': {
return utils.setSeconds(dateToTransferTo, utils.getSeconds(dateToTransferFrom));
}
default: {
return dateToTransferTo;
}
}
};
const reliableSectionModificationOrder: Record<FieldSectionType, number> = {
year: 1,
month: 2,
day: 3,
weekDay: 4,
hours: 5,
minutes: 6,
seconds: 7,
meridiem: 8,
empty: 9,
};
export const mergeDateIntoReferenceDate = (
utils: MuiPickersAdapter,
dateToTransferFrom: PickerValidDate,
sections: FieldSection[],
referenceDate: PickerValidDate,
shouldLimitToEditedSections: boolean,
): PickerValidDate =>
// cloning sections before sort to avoid mutating it
[...sections]
.sort(
(a, b) => reliableSectionModificationOrder[a.type] - reliableSectionModificationOrder[b.type],
)
.reduce((mergedDate, section) => {
if (!shouldLimitToEditedSections || section.modified) {
return transferDateSectionValue(utils, section, dateToTransferFrom, mergedDate);
}
return mergedDate;
}, referenceDate);
export const isAndroid = () => navigator.userAgent.toLowerCase().includes('android');
// TODO v9: Remove
export const getSectionOrder = (
sections: FieldSection[],
shouldApplyRTL: boolean,
): SectionOrdering => {
const neighbors: SectionNeighbors = {};
if (!shouldApplyRTL) {
sections.forEach((_, index) => {
const leftIndex = index === 0 ? null : index - 1;
const rightIndex = index === sections.length - 1 ? null : index + 1;
neighbors[index] = { leftIndex, rightIndex };
});
return { neighbors, startIndex: 0, endIndex: sections.length - 1 };
}
type PositionMapping = { [from: number]: number };
const rtl2ltr: PositionMapping = {};
const ltr2rtl: PositionMapping = {};
let groupedSectionsStart = 0;
let groupedSectionsEnd = 0;
let RTLIndex = sections.length - 1;
while (RTLIndex >= 0) {
groupedSectionsEnd = sections.findIndex(
// eslint-disable-next-line @typescript-eslint/no-loop-func
(section, index) =>
index >= groupedSectionsStart &&
section.endSeparator?.includes(' ') &&
// Special case where the spaces were not there in the initial input
section.endSeparator !== ' / ',
);
if (groupedSectionsEnd === -1) {
groupedSectionsEnd = sections.length - 1;
}
for (let i = groupedSectionsEnd; i >= groupedSectionsStart; i -= 1) {
ltr2rtl[i] = RTLIndex;
rtl2ltr[RTLIndex] = i;
RTLIndex -= 1;
}
groupedSectionsStart = groupedSectionsEnd + 1;
}
sections.forEach((_, index) => {
const rtlIndex = ltr2rtl[index];
const leftIndex = rtlIndex === 0 ? null : rtl2ltr[rtlIndex - 1];
const rightIndex = rtlIndex === sections.length - 1 ? null : rtl2ltr[rtlIndex + 1];
neighbors[index] = { leftIndex, rightIndex };
});
return { neighbors, startIndex: rtl2ltr[0], endIndex: rtl2ltr[sections.length - 1] };
};
export const parseSelectedSections = (
selectedSections: FieldSelectedSections,
sections: FieldSection[],
): FieldParsedSelectedSections => {
if (selectedSections == null) {
return null;
}
if (selectedSections === 'all') {
return 'all';
}
if (typeof selectedSections === 'string') {
const index = sections.findIndex((section) => section.type === selectedSections);
return index === -1 ? null : index;
}
return selectedSections;
};
export const getSectionValueText = (
section: FieldSection,
utils: MuiPickersAdapter,
): string | undefined => {
if (!section.value) {
return undefined;
}
switch (section.type) {
case 'month': {
if (section.contentType === 'digit') {
return utils.format(utils.setMonth(utils.date(), Number(section.value) - 1), 'month');
}
const parsedDate = utils.parse(section.value, section.format);
return parsedDate ? utils.format(parsedDate, 'month') : undefined;
}
case 'day':
return section.contentType === 'digit'
? utils.format(
utils.setDate(utils.startOfYear(utils.date()), Number(section.value)),
'dayOfMonthFull',
)
: section.value;
case 'weekDay':
// TODO: improve by providing the label of the week day
return undefined;
default:
return undefined;
}
};
export const getSectionValueNow = (
section: FieldSection,
utils: MuiPickersAdapter,
): number | undefined => {
if (!section.value) {
return undefined;
}
switch (section.type) {
case 'weekDay': {
if (section.contentType === 'letter') {
// TODO: improve by resolving the week day number from a letter week day
return undefined;
}
return Number(section.value);
}
case 'meridiem': {
const parsedDate = utils.parse(
`01:00 ${section.value}`,
`${utils.formats.hours12h}:${utils.formats.minutes} ${section.format}`,
);
if (parsedDate) {
return utils.getHours(parsedDate) >= 12 ? 1 : 0;
}
return undefined;
}
case 'day':
return section.contentType === 'digit-with-letter'
? parseInt(section.value, 10)
: Number(section.value);
case 'month': {
if (section.contentType === 'digit') {
return Number(section.value);
}
const parsedDate = utils.parse(section.value, section.format);
return parsedDate ? utils.getMonth(parsedDate) + 1 : undefined;
}
default:
return section.contentType !== 'letter' ? Number(section.value) : undefined;
}
};