All files / src/components/DateField utils.ts

79.85% Statements 222/278
65.36% Branches 168/257
100% Functions 27/27
79.48% Lines 217/273

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 81410x   10x   10x                                   21x                       21x   21x                                                                                                     21x                             156x   156x                         156x 147x           9x             402x       15x       1171x 1171x   208x 208x           1x     213x                       206x           15x 1x 1x         14x             16x           512x       1171x 1171x   208x 91x   117x                       452x     511x     21x             455x       455x 167x     288x                       10x     10x 10x   3x 2x 1x   1x     1x           3x                                   3x     7x       7x 7x 7x 7x 7x 7x       7x       7x       7x   7x 6x             6x                         7x                 53x   53x   28x                 28x           21x 21x                             2x 2x                   2x 2x       2x 2x               53x 32x                   32x                   53x               156x 9x     147x   49x 48x 48x     1x 1x       1x       45x       47x               2x       2x       1x                           156x   49x       1x       52x       47x       1x           2x       2x       1x       1x                     55x 55x   55x   55x 55x 55x 55x 523x 523x           523x 422x 101x 101x   422x 422x   101x 101x 101x   101x 101x     101x       55x 55x     55x       55x                 156x       156x   156x           156x                   101x       101x                           156x   52x 52x 52x 52x 624x 624x   52x     1x 1x 1x       1x     1x 1x 1x 1x 7x 7x   1x       102x       23x               1104x           4873x               1171x 1171x 1171x   1171x 400x 400x 400x 132x 268x 1x 1x 267x               400x 400x         1171x             1171x       4x 4x     4x       2x                 2x       2x 2x 2x 2x 2x 2x       2x       328x 328x 328x   328x 328x 2x 2x     328x     21x 21x     54x 54x 54x 54x 54x 54x 254x 100x   154x 154x 154x 154x 154x 154x   254x     54x                           22x 22x 22x         22x 1x     22x    
import React from 'react';
 
import {dateTime, expandFormat} from '@gravity-ui/date-utils';
import type {DateTime} from '@gravity-ui/date-utils';
import {dayjs} from '@gravity-ui/date-utils/build/dayjs/index.js';
import type {LongDateFormat} from '@gravity-ui/date-utils/build/settings/types';
import {useLang} from '@gravity-ui/uikit';
 
import type {ExtractFunctionType} from '../types';
import {mergeDateTime} from '../utils/dates';
 
import type {IncompleteDate} from './IncompleteDate';
import {i18n} from './i18n';
import type {
    AvailableSections,
    DateFieldSection,
    DateFieldSectionType,
    DateFormatTokenMap,
    FormatInfo,
    FormatSection,
} from './types';
 
export const EDITABLE_SEGMENTS = {
    year: true,
    quarter: true,
    month: true,
    day: true,
    weekday: true,
    hour: true,
    minute: true,
    second: true,
    dayPeriod: true,
} satisfies AvailableSections;
 
const escapedCharacters = {start: '[', end: ']'};
 
const formatTokenMap: DateFormatTokenMap = {
    // Year
    YY: 'year',
    YYYY: 'year',
 
    // Quarter
    Q: 'quarter',
    Qo: 'quarter',
 
    // Month
    M: 'month',
    MM: 'month',
    MMM: {sectionType: 'month', contentType: 'letter'},
    MMMM: {sectionType: 'month', contentType: 'letter'},
 
    // Day of the month
    D: 'day',
    DD: 'day',
    Do: 'day',
 
    // Day of the week
    d: 'weekday',
    dd: {sectionType: 'weekday', contentType: 'letter'},
    ddd: {sectionType: 'weekday', contentType: 'letter'},
    dddd: {sectionType: 'weekday', contentType: 'letter'},
 
    // Day period AM, PM
    A: {sectionType: 'dayPeriod', contentType: 'letter'},
    a: {sectionType: 'dayPeriod', contentType: 'letter'},
 
    // Hours
    H: 'hour',
    HH: 'hour',
    h: 'hour',
    hh: 'hour',
 
    // Minutes
    m: 'minute',
    mm: 'minute',
 
    // Seconds
    s: 'second',
    ss: 'second',
 
    // Timezone
    z: {sectionType: 'timeZoneName', contentType: 'letter'},
    zzz: {sectionType: 'timeZoneName', contentType: 'letter'},
    Z: {sectionType: 'timeZoneName', contentType: 'letter'},
    ZZ: {sectionType: 'timeZoneName', contentType: 'letter'},
};
 
export const PAGE_STEP: Partial<Record<DateFieldSectionType, number>> = {
    year: 5,
    quarter: 2,
    month: 2,
    weekday: 3,
    day: 7,
    hour: 2,
    minute: 15,
    second: 15,
};
 
function getDateSectionConfigFromFormatToken(formatToken: string): {
    type: DateFieldSectionType;
    contentType: 'letter' | 'digit';
} {
    const config = formatTokenMap[formatToken];
 
    Iif (!config) {
        console.error(
            [
                `The token "${formatToken}" is not supported by the Date field.`,
                'Please try using another token.',
            ].join('\n'),
        );
        return {
            type: 'literal',
            contentType: 'letter',
        };
    }
 
    if (typeof config === 'string') {
        return {
            type: config,
            contentType: 'digit',
        };
    }
 
    return {
        type: config.sectionType,
        contentType: config.contentType,
    };
}
 
function isFourDigitYearFormat(format: string) {
    return dateTime().format(format).length === 4;
}
 
function isHour12(format: string) {
    return dateTime().set('hour', 15).format(format) !== '15';
}
 
function getSectionLimits(section: FormatSection, date: IncompleteDate, placeholder: DateTime) {
    const {type, format} = section;
    switch (type) {
        case 'year': {
            const isFourDigit = isFourDigitYearFormat(format);
            return {
                minValue: isFourDigit ? 1 : 0,
                maxValue: isFourDigit ? 9999 : 99,
            };
        }
        case 'quarter': {
            return {minValue: 1, maxValue: 4};
        }
        case 'month': {
            return {
                minValue: 1,
                maxValue: 12,
            };
        }
        case 'weekday': {
            return {
                minValue: 0,
                maxValue: 6,
            };
        }
        case 'day': {
            return {
                minValue: 1,
                maxValue: 31,
            };
        }
        case 'hour': {
            if (isHour12(format)) {
                const isPM = (date.hour ?? placeholder.hour()) >= 12;
                return {
                    minValue: isPM ? 12 : 0,
                    maxValue: isPM ? 23 : 11,
                };
            }
            return {
                minValue: 0,
                maxValue: 23,
            };
        }
        case 'minute':
        case 'second': {
            return {
                minValue: 0,
                maxValue: 59,
            };
        }
    }
    return {};
}
 
function getSectionValue(section: FormatSection, date: IncompleteDate) {
    const type = section.type;
    switch (type) {
        case 'year': {
            if (date.year === null) {
                return null;
            }
            return isFourDigitYearFormat(section.format)
                ? date.year
                : Number(dateTime().set('year', date.year).format(section.format));
        }
        case 'quarter':
        case 'month':
        case 'weekday':
        case 'hour':
        case 'minute':
        case 'second':
        case 'day':
        case 'dayPeriod': {
            return date[type];
        }
    }
    return null;
}
 
const TYPE_MAPPING = {
    weekday: 'day',
    day: 'date',
    dayPeriod: 'hour',
} as const;
 
export function getDurationUnitFromSectionType(type: DateFieldSectionType) {
    Iif (!isEditableSectionType(type)) {
        throw new Error(`${type} section does not have duration unit.`);
    }
 
    if (type in TYPE_MAPPING) {
        return TYPE_MAPPING[type as keyof typeof TYPE_MAPPING];
    }
 
    return type as Exclude<
        DateFieldSectionType,
        keyof typeof TYPE_MAPPING | 'literal' | 'timeZoneName' | 'unknown'
    >;
}
 
export function addSegment(
    section: DateFieldSection,
    date: IncompleteDate,
    amount: number,
    placeholder: DateTime,
) {
    Iif (!isEditableSectionType(section.type)) {
        throw new Error();
    }
    let val = date[section.type];
    if (val === null) {
        let newDate;
        if (section.type === 'quarter' || section.type === 'month') {
            newDate = date.set('month', placeholder.month() + 1);
        I} else if (section.type === 'dayPeriod') {
            newDate = date.set('hour', placeholder.hour());
        I} else if (section.type === 'weekday' && date.day && date.day !== placeholder.date()) {
            newDate = date.set('weekday', placeholder.set({date: date.day}).day());
        } else {
            newDate = date.set(
                section.type,
                placeholder[getDurationUnitFromSectionType(section.type)](),
            );
        }
 
        Iif (
            newDate.weekday !== null &&
            (section.type === 'day' ||
                section.type === 'month' ||
                section.type === 'quarter' ||
                section.type === 'year') &&
            newDate.year !== null &&
            newDate.month !== null &&
            newDate.day !== null
        ) {
            newDate = newDate.set(
                'weekday',
                placeholder
                    .set({date: newDate.day, month: newDate.month, year: newDate.year})
                    .day(),
            );
        }
 
        return newDate;
    }
 
    Iif (section.type === 'dayPeriod') {
        const hour = date.hour ?? placeholder.hour();
        val = hour + (hour >= 12 ? -12 : 12);
    } else {
        val = val + amount;
        const min = section.minValue;
        const max = section.maxValue;
        Eif (typeof min === 'number' && typeof max === 'number') {
            const length = max - min + 1;
            val = ((val - min + length) % length) + min;
        }
    }
 
    Iif (section.type === 'dayPeriod') {
        return date.set('hour', val);
    }
 
    Iif (section.type === 'year' && !isFourDigitYearFormat(section.format)) {
        val = dateTime({input: `${val}`.padStart(2, '0'), format: section.format}).year();
    }
 
    const newDate = date.set(section.type, val);
 
    if (newDate.year !== null && newDate.month !== null && newDate.day !== null) {
        if (
            date.weekday !== null &&
            (section.type === 'day' ||
                section.type === 'month' ||
                section.type === 'quarter' ||
                section.type === 'year')
        ) {
            newDate.weekday = placeholder
                .set({date: newDate.day, month: newDate.month, year: newDate.year})
                .day();
        E} else if (section.type === 'weekday') {
            const d = placeholder
                .set({date: newDate.day, month: newDate.month, year: newDate.year})
                .set({day: val});
            newDate.year = d.year();
            newDate.month = d.month();
            newDate.day = d.date();
        }
    }
 
    return newDate;
}
 
export function setSegment(
    section: FormatSection,
    date: IncompleteDate,
    amount: number,
    placeholder: DateTime,
) {
    const type = section.type;
    let newDate;
    switch (type) {
        case 'year': {
            newDate = date.set(
                'year',
                isFourDigitYearFormat(section.format)
                    ? amount
                    : dateTime({
                          input: `${amount}`.padStart(2, '0'),
                          format: section.format,
                      }).year(),
            );
            break;
        }
        case 'quarter':
        case 'month':
        case 'weekday':
        case 'day': {
            newDate = date.set(type, amount);
            break;
        }
        case 'dayPeriod': {
            const hours = date.hour ?? placeholder.hour();
            const wasPM = hours >= 12;
            const isPM = amount === 1;
            if (isPM === wasPM) {
                newDate = date;
            } else {
                newDate = date.set('hour', wasPM ? hours - 12 : hours + 12);
            }
            break;
        }
        case 'hour': {
            // In 12 hour time, ensure that AM/PM does not change
            let sectionAmount = amount;
            Iif (section.minValue === 12 || section.maxValue === 11) {
                const hours = date.hour ?? placeholder.hour();
                const wasPM = hours >= 12;
                if (!wasPM && sectionAmount === 12) {
                    sectionAmount = 0;
                }
                if (wasPM && sectionAmount < 12) {
                    sectionAmount += 12;
                }
            }
            newDate = date.set('hour', sectionAmount);
            break;
        }
        case 'minute':
        case 'second': {
            newDate = date.set(type, amount);
            break;
        }
        default: {
            newDate = date;
            break;
        }
    }
 
    if (newDate.year !== null && newDate.month !== null && newDate.day !== null) {
        Iif (
            newDate.weekday !== null &&
            (type === 'day' || type === 'month' || type === 'quarter' || type === 'year')
        ) {
            newDate = newDate.set(
                'weekday',
                placeholder
                    .set({date: newDate.day, month: newDate.month, year: newDate.year})
                    .day(),
            );
        I} else if (type === 'weekday') {
            const d = placeholder
                .set({date: newDate.day, month: newDate.month, year: newDate.year})
                .set({day: amount});
            newDate.year = d.year();
            newDate.month = d.month();
            newDate.day = d.date();
        }
    }
 
    return newDate;
}
 
function doesSectionHaveLeadingZeros(
    contentType: 'digit' | 'letter',
    sectionType: DateFieldSectionType,
    format: string,
) {
    if (contentType !== 'digit') {
        return false;
    }
 
    switch (sectionType) {
        case 'year': {
            if (isFourDigitYearFormat(format)) {
                const formatted0001 = dateTime().set('year', 1).format(format);
                return formatted0001 === '0001';
            }
 
            const formatted2001 = dateTime().set('year', 2001).format(format);
            return formatted2001 === '01';
        }
 
        case 'quarter': {
            return false;
        }
 
        case 'month': {
            return dateTime().startOf('year').format(format).length > 1;
        }
 
        case 'day': {
            return dateTime().startOf('month').format(format).length > 1;
        }
 
        case 'weekday': {
            return dateTime().startOf('week').format(format).length > 1;
        }
 
        case 'hour': {
            return dateTime().set('hour', 1).format(format).length > 1;
        }
 
        case 'minute': {
            return dateTime().set('minute', 1).format(format).length > 1;
        }
 
        case 'second': {
            return dateTime().set('second', 1).format(format).length > 1;
        }
 
        default: {
            throw new Error('Invalid section type');
        }
    }
}
 
function getSectionPlaceholder(
    sectionConfig: Pick<DateFieldSection, 'type' | 'contentType'>,
    currentTokenValue: string,
    t: TranslateFunction,
) {
    switch (sectionConfig.type) {
        case 'year': {
            return t('year_placeholder').repeat(dateTime().format(currentTokenValue).length);
        }
 
        case 'quarter': {
            return t('quarter_placeholder').repeat(currentTokenValue.length);
        }
 
        case 'month': {
            return t('month_placeholder').repeat(sectionConfig.contentType === 'letter' ? 4 : 2);
        }
 
        case 'day': {
            return t('day_placeholder').repeat(2);
        }
 
        case 'weekday': {
            return t('weekday_placeholder').repeat(
                sectionConfig.contentType === 'letter' ? currentTokenValue.length : 2,
            );
        }
 
        case 'hour': {
            return t('hour_placeholder').repeat(2);
        }
 
        case 'minute': {
            return t('minute_placeholder').repeat(2);
        }
 
        case 'second': {
            return t('second_placeholder').repeat(2);
        }
 
        case 'dayPeriod': {
            return t('dayPeriod_placeholder');
        }
 
        default: {
            return currentTokenValue;
        }
    }
}
 
type TranslateFunction = ExtractFunctionType<typeof i18n>;
export function splitFormatIntoSections(format: string, t: TranslateFunction = i18n, lang = 'en') {
    const sections: FormatSection[] = [];
    const localeFormats = dayjs.Ls[lang].formats as LongDateFormat;
 
    const expandedFormat = expandFormat(format, localeFormats);
 
    let currentTokenValue = '';
    let isSeparator = false;
    let isInEscapeBoundary = false;
    for (let i = 0; i < expandedFormat.length; i++) {
        const char = expandedFormat[i] || '';
        Iif (isInEscapeBoundary) {
            if (char === escapedCharacters.end) {
                isInEscapeBoundary = false;
                continue;
            }
            currentTokenValue += char;
        } else if (char.match(/[a-zA-Z]/)) {
            if (isSeparator) {
                addLiteralSection(sections, currentTokenValue);
                currentTokenValue = '';
            }
            isSeparator = false;
            currentTokenValue += char;
        } else {
            Eif (!isSeparator) {
                addFormatSection(sections, currentTokenValue, t, lang);
                currentTokenValue = '';
            }
            isSeparator = true;
            Iif (char === escapedCharacters.start) {
                isInEscapeBoundary = true;
            } else {
                currentTokenValue += char;
            }
        }
    }
    Eif (currentTokenValue) {
        Iif (isSeparator) {
            addLiteralSection(sections, currentTokenValue);
        } else {
            addFormatSection(sections, currentTokenValue, t, lang);
        }
    }
 
    return sections;
}
 
function addFormatSection(
    sections: FormatSection[],
    token: string,
    t: TranslateFunction,
    lang: string,
) {
    Iif (!token) {
        return;
    }
 
    const sectionConfig = getDateSectionConfigFromFormatToken(token);
 
    const hasLeadingZeros = doesSectionHaveLeadingZeros(
        sectionConfig.contentType,
        sectionConfig.type,
        token,
    );
 
    sections.push({
        ...sectionConfig,
        format: token,
        placeholder: getSectionPlaceholder(sectionConfig, token, t),
        options: getSectionOptions(sectionConfig, token, lang),
        hasLeadingZeros,
    });
}
 
function addLiteralSection(sections: FormatSection[], token: string) {
    Iif (!token) {
        return;
    }
 
    sections.push({
        type: 'literal',
        contentType: 'letter',
        format: token,
        placeholder: token,
        hasLeadingZeros: false,
    });
}
 
function getSectionOptions(
    section: Pick<FormatSection, 'type' | 'contentType'>,
    token: string,
    lang: string,
) {
    switch (section.type) {
        case 'month': {
            const format = section.contentType === 'letter' ? token : 'MMMM';
            let date = dateTime({lang}).startOf('year');
            const options: string[] = [];
            for (let i = 0; i < 12; i++) {
                options.push(date.format(format).toLocaleUpperCase());
                date = date.add(1, 'months');
            }
            return options;
        }
        case 'dayPeriod': {
            const amDayPeriod = dateTime().hour(0);
            const pmDayPeriod = amDayPeriod.hour(12);
            const options = [
                amDayPeriod.format(token).toLocaleUpperCase(),
                pmDayPeriod.format(token).toLocaleUpperCase(),
            ];
            return options;
        }
        case 'weekday': {
            const format = section.contentType === 'letter' ? token : 'dddd';
            let date = dateTime({lang}).day(0);
            const options: string[] = [];
            for (let i = 0; i < 7; i++) {
                options.push(date.format(format).toLocaleUpperCase());
                date = date.add(1, 'day');
            }
            return options;
        }
    }
 
    return undefined;
}
 
export function cleanString(dirtyString: string) {
    return dirtyString.replace(/[\u2066\u2067\u2068\u2069]/g, '');
}
 
export function getEditableSections(
    sections: FormatSection[],
    value: IncompleteDate,
    placeholder: DateTime,
) {
    return sections.map((section) => toEditableSection(section, value, placeholder));
}
 
export function isEditableSectionType(
    type: DateFieldSectionType,
): type is keyof typeof EDITABLE_SEGMENTS {
    return EDITABLE_SEGMENTS[type as keyof typeof EDITABLE_SEGMENTS] ?? false;
}
 
export function toEditableSection(
    section: FormatSection,
    value: IncompleteDate,
    placeholder: DateTime,
): DateFieldSection {
    let renderedValue = section.placeholder;
    let val = isEditableSectionType(section.type) ? value[section.type] : null;
    Iif (section.type === 'timeZoneName') {
        renderedValue = placeholder.format(section.format);
    } else if (isEditableSectionType(section.type) && val !== null) {
        const sectionDate = placeholder.set({month: 0, date: 1, hour: 0, minute: 0, second: 0});
        let sectionType = getDurationUnitFromSectionType(section.type);
        if (section.type === 'month') {
            val -= 1;
        } else if (section.type === 'quarter') {
            sectionType = 'month';
            val = (val - 1) * 3;
        I} else if (section.type === 'dayPeriod') {
            if (value.hour === null) {
                val = val === 1 ? 12 : 0;
            } else {
                val = value.hour;
            }
        }
 
        renderedValue = sectionDate.set(sectionType, val).format(section.format);
        Iif (section.contentType === 'digit' && renderedValue.length < section.placeholder.length) {
            renderedValue = renderedValue.padStart(section.placeholder.length, '0');
        }
    }
 
    const newSection = {
        ...section,
        value: getSectionValue(section, value),
        textValue: renderedValue,
        ...getSectionLimits(section, value, placeholder),
    };
 
    return newSection;
}
 
function parseDate(options: {input: string; format: string; timeZone?: string}) {
    let date = dateTime(options);
    Iif (!date.isValid()) {
        date = dateTime({...options, format: undefined});
    }
    return date;
}
 
function isDateStringWithTimeZone(str: string) {
    return /z$/i.test(str) || /[+-]\d\d:\d\d$/.test(str);
}
 
/**
 * Trims leading and trailing spaces from a string and replaces multiple consecutive spaces with a single space.
 * @param str - The input string to process.
 * @returns The processed string with trimmed spaces and single spaces between words.
 */
function trimExtraSpaces(str: string) {
    return str.trim().replace(/\s+/g, ' ');
}
 
export function parseDateFromString(str: string, format: string, timeZone?: string): DateTime {
    const input = typeof str === 'string' ? trimExtraSpaces(str) : str;
    let date = parseDate({input, format, timeZone});
    Eif (date.isValid()) {
        Eif (timeZone && !isDateStringWithTimeZone(str)) {
            const time = parseDate({input: str, format});
            date = mergeDateTime(date, time);
        }
    }
 
    return date;
}
 
export function useFormatSections(format: string) {
    const {t} = i18n.useTranslation();
    const {lang} = useLang();
    const [sections, setSections] = React.useState(() => splitFormatIntoSections(format, t, lang));
 
    const [previous, setFormat] = React.useState({format, lang});
    if (format !== previous.format || lang !== previous.lang) {
        setFormat({format, lang});
        setSections(splitFormatIntoSections(format, t, lang));
    }
 
    return sections;
}
 
const dateUnits = ['day', 'month', 'quarter', 'year'] satisfies DateFieldSectionType[];
const timeUnits = ['second', 'minute', 'hour'] satisfies DateFieldSectionType[];
 
export function getFormatInfo(sections: FormatSection[]): FormatInfo {
    const availableUnits: AvailableSections = {};
    let hasDate = false;
    let hasTime = false;
    let minDateUnitIndex = dateUnits.length - 1;
    let minTimeUnitIndex = timeUnits.length - 1;
    for (const s of sections) {
        if (!isEditableSectionType(s.type)) {
            continue;
        }
        const dateUnitIndex = dateUnits.indexOf(s.type as any);
        const timeUnitIndex = timeUnits.indexOf(s.type as any);
        availableUnits[s.type] = true;
        hasDate ||= dateUnitIndex !== -1;
        hasTime ||= timeUnitIndex !== -1;
        minDateUnitIndex =
            dateUnitIndex === -1 ? minDateUnitIndex : Math.min(dateUnitIndex, minDateUnitIndex);
        minTimeUnitIndex =
            timeUnitIndex === -1 ? minTimeUnitIndex : Math.min(timeUnitIndex, minTimeUnitIndex);
    }
    return {
        availableUnits,
        hasDate,
        hasTime,
        minDateUnit: dateUnits[minDateUnitIndex] ?? 'day',
        minTimeUnit: timeUnits[minTimeUnitIndex] ?? 'second',
    };
}
 
export function adjustDateToFormat(
    date: DateTime,
    formatInfo: FormatInfo,
    method: 'startOf' | 'endOf' = 'startOf',
) {
    let newDate = date;
    Eif (formatInfo.hasDate) {
        Iif (formatInfo.minDateUnit !== 'day') {
            newDate = newDate[method](formatInfo.minDateUnit);
            newDate = mergeDateTime(newDate, date);
        }
    }
    if (formatInfo.hasTime) {
        newDate = mergeDateTime(newDate, date[method](formatInfo.minTimeUnit));
    }
 
    return newDate;
}