All files / src/lib/forms/services date-picker.service.ts

100% Statements 110/110
100% Branches 41/41
100% Functions 28/28
100% Lines 101/101

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 2751x 1x           1x                                                 1x                                     1x     1x     102x 102x     1x 3x     1x 3x     1x 8x   7x 7x   7x     1x 3x     1x 3x     1x 3x     1x 6x     1x   3x     1x   3x     1x 3x         1x 3x     1x 3x     1x 3x     1x 30x     1x 99x   98x 47x   47x 39x   8x     51x     1x   1x 6x 6x 42x 42x 42x   6x     1x 6x 6x 72x 72x   6x     128x 127x 127x                     1x 70x   70x 902x 46x       70x     70x   70x             70x     70x     70x   70x         134x     70x 70x   70x       70x           102x   70x 12x 12x 12x 12x     58x     38x 38x 38x     20x 20x 20x       70x           6x   2x         2x     4x         4x     6x    
import {Inject, LOCALE_ID, Optional} from '@angular/core';
import {DatePipe} from '@angular/common';
 
import {DateSegments} from '../interfaces/DateSegments';
import {DayWithMetadata} from '../interfaces/DayWithMetadata';
import {DateRangeValidationParams} from '../interfaces/DateRangeValidationParams';
 
export const STANDARD_LOCALES: {[key: string]: string} = {
    'en-US': 'M/d/yyyy',
    'sw-KE': 'M/d/yyyy',
    'en-ZW': 'M/d/yyyy',
    'en-PH': 'M/d/yyyy',
    'rw-RW': 'M/d/yyyy',
    'moh-CA': 'M/d/yyyy',
    'fil-PH': 'M/d/yyyy',
    'ne-NP': 'M/d/yyyy',
    'es-US': 'M/d/yyyy',
    'sq-AL': 'yyyy/M/d',
    'bg-BG': 'yyyy/M/d',
    'sr-BA': 'yyyy/M/d',
    'fr-CA': 'yyyy/M/d',
    'zh-CN': 'yyyy/M/d',
    'zh-HK': 'yyyy/M/d',
    'hu-HU': 'yyyy/M/d',
    'ja-JP': 'yyyy/M/d',
    'ko-KR': 'yyyy/M/d',
    'lt-LT': 'yyyy/M/d',
    'sv-SE': 'yyyy/M/d',
    'zh-TW': 'yyyy/M/d',
    'en-ZA': 'yyyy/M/d'
};
 
export abstract class DateAdapter<T> {
    // For calendar widget
    public abstract dayOfFirst(year: number, month: number): number;
    public abstract daysInMonth(year: number, month: number): number;
    public abstract getMonthInfo(year: number, month: number): T;
    public abstract isDisabled(evalDate: Date, dateRangeParams: DateRangeValidationParams): boolean;
    public abstract month(date: Date): number;
    public abstract newDateFromArray(year?: number, month?: number, day?: number): T;
    public abstract newDateFromValue(value?: any): T;
    public abstract prepHeaderDate(date: Date, weekDays?: string[], months?: string[]): string;
    public abstract prepHeaderYear(date: Date, weekDays?: string[], months?: string[]): string;
    public abstract sameDay(_calendarDay: DayWithMetadata, _comparator: Date): boolean;
    public abstract year(date: Date): number;
    public abstract weekdays(): string[];
    public abstract months(): string[];
 
    // For angular directive
    public abstract prepDateStringOutput(input: T): string;
    public abstract processDateInput(input: T | string): Date;
}
 
// Default adapter, will accept String or Native Date
export class NativeDateAdapter implements DateAdapter<Date> {
    private languageCode: string;
 
    constructor(@Optional() @Inject(LOCALE_ID) private _locale?: string) {
        this.languageCode = (_locale) ? _locale.split('-')[0] : 'en';
    }
 
    dayOfFirst(year: number, month: number): number {
        return new Date(year, month, 1).getDay();
    }
 
    daysInMonth(year: number, month: number): number {
        return new Date(year, month + 1, 0).getDate();
    }
 
    isDisabled(evalDate: Date, dateRangeParams: DateRangeValidationParams): boolean {
        if (!dateRangeParams) { return false; }
 
        const dayIsBeforeMinDate = (dateRangeParams.minDate) ? evalDate < dateRangeParams.minDate : false;
        const dayIsAfterMaxDate = (dateRangeParams.maxDate) ? evalDate > dateRangeParams.maxDate : false;
 
        return dayIsBeforeMinDate || dayIsAfterMaxDate;
    }
 
    getMonthInfo(year: number, month: number): Date {
        return new Date(year, month, 15);
    }
 
    month(date: Date): number {
        return date.getMonth();
    }
 
    newDateFromArray(year?: number, month?: number, day?: number): Date {
        return new Date(year, month, day);
    }
 
    newDateFromValue(value?: any) {
        return (value) ? new Date(value) : new Date();
    }
 
    prepHeaderDate(date: Date): string {
 
        return localize(this.languageCode, date, 'EEE, MMM d');
    }
 
    prepHeaderYear(date: Date): string {
 
        return localize(this.languageCode, date, 'yyyy');
    }
 
    sameDay(_calendarDay: DayWithMetadata, _comparator: Date): boolean {
        return _calendarDay.day === _comparator.getDate()
            && _calendarDay.month === _comparator.getMonth()
            && _calendarDay.year === _comparator.getFullYear();
    }
 
    year(date: Date): number {
        return date.getFullYear();
    }
 
    weekdays(): string[] {
        return getWeekdays(this.languageCode);
    }
 
    months(): string[] {
        return getMonths(this.languageCode);
    }
 
    prepDateStringOutput(input: Date): string {
        return (input) ? new Date(this.processDateInput(input)).toLocaleDateString(this._locale) : '';
    }
 
    processDateInput(input: Date | string): Date {
        if (!input) { return null; }
 
        if (typeof input === 'string') {
            const dateSegments = parseInput(input, this._locale);
 
            if (Array.isArray(dateSegments.splitDate) && dateSegments.splitDate.length === 3 && dateSegments.year) {
                return new Date(parseInt(dateSegments.year, 10), parseInt(dateSegments.month, 10) - 1, parseInt(dateSegments.day, 10));
            } else {
                return new Date(input);
            }
        } else {
            return input;
        }
    }
}
 
export function getWeekdays(lang: string): string[] {
    const weekdays = [];
    for (let i = 0; i < 7; i++) {
        const date = new Date();
        const testDate = date.setDate(date.getDate() - date.getDay() + i);
        weekdays.push(localize(lang, new Date(testDate), 'EEE'));
    }
    return weekdays;
}
 
export function getMonths(lang: string): string[] {
    const months = [];
    for (let i = 0; i < 12; i++) {
        const testDate = new Date().setMonth(i);
        months.push(localize(lang, new Date(testDate), 'MMM'));
    }
    return months;
}
 
export function localize(_languageCode: string = 'en', date: Date, format: string): string {
    const pipe = new DatePipe(_languageCode);
    return pipe.transform(date, format);
}
 
 
/* Currently only support shortDate strings (with non-alphanumeric separators) of:
    {
        Month-Day-Year: if included in STANDARD_LOCALES,
        Year-Month-Day: if included in STANDARD_LOCALES,
        Day-Month-Year: for all locales outside of STANDARD_LOCALES
    }
 */
export function parseInput(input: string, locale: string): DateSegments {
    let format = STANDARD_LOCALES[locale];
    // Covers case of partial locale code provided
    if (!format) {
        const localeKey = Object.keys(STANDARD_LOCALES).find(key => key.includes(locale));
        format = STANDARD_LOCALES[localeKey];
    }
 
    // Split string on any non-alphanumeric characters, not including spaces
    const regexSplit = input.split(/[^\w\s]+/g).filter(Boolean);
 
    // Parse digit-only string, or use the regexSplit value
    const splitDate = (regexSplit.length <= 1 && input.length === 8) ? parseDigitOnlyDate(input, format) : regexSplit;
 
    const dateSegments = {
        splitDate,
        year: '',
        month: '',
        day: ''
    };
 
    const splitDateCp = splitDate.slice(0);
 
    // Set year
    dateSegments.year = setYearSegment(splitDateCp);
 
    // Set Day and Month
    Object.assign(dateSegments, setMonthAndDaySegments(splitDateCp, format));
 
    return dateSegments;
}
 
function setYearSegment(splitDateArray: string[]): string {
    // Find year
    const year = splitDateArray.find(segment => segment.length === 4);
 
    // Remove year from working array
    const yearIndex = splitDateArray.indexOf(year);
    splitDateArray.splice(yearIndex, 1);
 
    return year;
}
 
function setMonthAndDaySegments(splitDateArray: string[], format: string): {day: string; month: string} {
    const segments = {
        day: '',
        month: ''
    };
 
    // See if we can determine which segment is the days segment
    const assumedDay = splitDateArray.find(segment => parseInt(segment, 10) > 12);
 
    if (assumedDay) {
        segments.day = assumedDay;
        const dayIndex = splitDateArray.indexOf(assumedDay);
        splitDateArray.splice(dayIndex, 1);
        segments.month = splitDateArray[0];
        // Otherwise, make a reasonable guess
    } else {
        switch (format) {
            case 'M/d/yyyy':
            case 'yyyy/M/d':
                segments.month = splitDateArray[0];
                segments.day = splitDateArray[1];
                break;
            // Assume 'dd/MM/yyyy' for anything else
            default:
                segments.month = splitDateArray[1];
                segments.day = splitDateArray[0];
                break;
        }
    }
 
    return segments;
}
 
function parseDigitOnlyDate(input: string, format: string): string[] {
    let splitDate: string[];
 
    switch (format) {
        case 'yyyy/M/d':
            splitDate = [
                input.slice(0, 4),
                input.slice(4, 6),
                input.slice(6)
            ];
            break;
        // Assume 'dd/MM/yyyy' or 'M/d/yyyy' for anything else
        default:
            splitDate = [
                input.slice(0, 2),
                input.slice(2, 4),
                input.slice(4)
            ];
            break;
    }
 
    return splitDate;
}