UNPKG

ngx-mat-datefns-date-adapter

Version:

[![NPM](https://img.shields.io/npm/l/ngx-mat-datefns-date-adapter)](https://github.com/sapozhnikovay/ngx-mat-datefns-date-adapter/blob/master/LICENSE) [![npm](https://img.shields.io/npm/v/ngx-mat-datefns-date-adapter)](https://www.npmjs.com/package/ngx-ma

277 lines (269 loc) 9.45 kB
import { InjectionToken, Injectable, Optional, Inject, NgModule } from '@angular/core'; import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material/core'; import { addDays, addMonths, addYears, toDate, parseJSON, parseISO, format, getDate, getDay, setDay, getMonth, setMonth, getDaysInMonth, getYear, parse } from 'date-fns'; import { zonedTimeToUtc } from 'date-fns-tz'; import { enUS } from 'date-fns/locale'; const NGX_MAT_DATEFNS_DATE_FORMATS = { parse: { dateInput: 'P', }, display: { dateInput: 'P', monthYearLabel: 'MMM yyyy', dateA11yLabel: 'PP', monthYearA11yLabel: 'MMMM yyyy', }, }; const NGX_MAT_DATEFNS_LOCALES = new InjectionToken('NGX_MAT_DATEFNS_LOCALES'); const NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS = new InjectionToken('NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS', { providedIn: 'root', factory: NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS_FACTORY, }); function NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS_FACTORY() { return { useUtc: false, }; } function range(start, end) { const arr = []; for (let i = start; i <= end; i++) { arr.push(i); } return arr; } const UTC_TIMEZONE = 'UTC'; class NgxDateFnsDateAdapter extends DateAdapter { constructor(dateLocale, locales, options) { super(); this.locales = locales; this.options = options; this.getLocale = (localeCodeOrLocale) => { if (localeCodeOrLocale && localeCodeOrLocale.code) { return localeCodeOrLocale; } if (!this.locales || !this.locales.length) { throw new Error('locales array does not provided or is empty. Provide it via the NGX_MAT_DATEFNS_LOCALES token.'); } const locale = this.locales.find((item) => item.code === localeCodeOrLocale); if (!locale) { throw new Error(`locale '${localeCodeOrLocale}' does not exist in locales array. Add it to the NGX_MAT_DATEFNS_LOCALES token.`); } return locale; }; if (!this.locales || this.locales.length === 0) { this.locales = [enUS]; } try { this.setLocale(dateLocale || enUS); } catch (err) { this.setLocale(enUS); } } setLocale(locale) { if (!locale) { throw new Error('setLocale should be called with the string locale code or date-fns Locale object'); } this._dateFnsLocale = this.getLocale(locale); super.setLocale(locale); } addCalendarDays(date, days) { return addDays(date, days); } addCalendarMonths(date, months) { return addMonths(date, months); } addCalendarYears(date, years) { return addYears(date, years); } clone(date) { return toDate(date); } createDate(year, month, date) { // Check for invalid month and date (except upper bound on date which we have to check after // creating the Date). if (month < 0 || month > 11) { throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } if (date < 1) { throw Error(`Invalid date "${date}". Date has to be greater than 0.`); } const result = this._createDateWithOverflow(year, month, date); // Check that the date wasn't above the upper bound for the month, causing the month to overflow if (result.getMonth() !== month) { throw Error(`Invalid date "${date}" for month with index "${month}".`); } return result; } deserialize(value) { var _a; if (value) { if (typeof value === 'string') { if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.useUtc) { return parseJSON(value); } return parseISO(value); } if (typeof value === 'number') { return toDate(value); } if (value instanceof Date) { return this.clone(value); } return null; } return null; } format(date, displayFormat) { return format(date, displayFormat, { locale: this._dateFnsLocale }); } getDate(date) { return getDate(date); } getDateNames() { return range(1, 31).map((day) => String(day)); } getDayOfWeek(date) { return getDay(date); } getDayOfWeekNames(style) { const map = { long: 'EEEE', short: 'EEE', narrow: 'EEEEE', }; const formatStr = map[style]; const date = new Date(); return range(0, 6).map((day) => format(setDay(date, day), formatStr, { locale: this._dateFnsLocale, })); } getFirstDayOfWeek() { var _a, _b; return (_b = (_a = this._dateFnsLocale.options) === null || _a === void 0 ? void 0 : _a.weekStartsOn) !== null && _b !== void 0 ? _b : 0; } getMonth(date) { return getMonth(date); } getMonthNames(style) { const map = { long: 'LLLL', short: 'LLL', narrow: 'LLLLL', }; const formatStr = map[style]; const date = new Date(); return range(0, 11).map((month) => format(setMonth(date, month), formatStr, { locale: this._dateFnsLocale, })); } getNumDaysInMonth(date) { return getDaysInMonth(date); } getYear(date) { return getYear(date); } getYearName(date) { return format(date, 'yyyy', { locale: this._dateFnsLocale, }); } invalid() { return new Date(NaN); } isDateInstance(obj) { return obj instanceof Date; } isValid(date) { return date instanceof Date && !isNaN(date.getTime()); } parse(value, parseFormat) { var _a; if (value) { if (typeof value === 'string') { if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.useUtc) { const d = parse(value.trim(), parseFormat, new Date(), { locale: this._dateFnsLocale, }); return zonedTimeToUtc(d, UTC_TIMEZONE); } return parse(value.trim(), parseFormat, new Date(), { locale: this._dateFnsLocale, }); } if (typeof value === 'number') { return toDate(value); } if (value instanceof Date) { return this.clone(value); } return null; } return null; } toIso8601(date) { return date.toISOString(); } today() { const d = new Date(); return this._createDateWithOverflow(d.getFullYear(), d.getMonth(), d.getDate()); } /** Creates a date but allows the month and date to overflow. */ _createDateWithOverflow(year, month, date) { const result = this._createDateInternal(year, month, date); // We need to correct for the fact that JS native Date treats years in range [0, 99] as // abbreviations for 19xx. if (year >= 0 && year < 100) { result.setFullYear(this.getYear(result) - 1900); } return result; } _createDateInternal(year, month, date) { var _a; if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.useUtc) { return zonedTimeToUtc(new Date(year, month, date), UTC_TIMEZONE); } return new Date(year, month, date); } } NgxDateFnsDateAdapter.decorators = [ { type: Injectable } ]; NgxDateFnsDateAdapter.ctorParameters = () => [ { type: String, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_LOCALE,] }] }, { type: Array, decorators: [{ type: Optional }, { type: Inject, args: [NGX_MAT_DATEFNS_LOCALES,] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS,] }] } ]; class NgxDateFnsDateModule { } NgxDateFnsDateModule.decorators = [ { type: NgModule, args: [{ providers: [ { provide: DateAdapter, useClass: NgxDateFnsDateAdapter, deps: [MAT_DATE_LOCALE, NGX_MAT_DATEFNS_LOCALES, NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS], }, ], },] } ]; const ɵ0 = NGX_MAT_DATEFNS_DATE_FORMATS, ɵ1 = []; class NgxMatDateFnsDateModule { } NgxMatDateFnsDateModule.decorators = [ { type: NgModule, args: [{ imports: [NgxDateFnsDateModule], providers: [ { provide: MAT_DATE_FORMATS, useValue: ɵ0 }, { provide: NGX_MAT_DATEFNS_LOCALES, useValue: ɵ1 }, ], },] } ]; /* * Public API Surface of ngx-mat-datefns-date-adapter */ /** * Generated bundle index. Do not edit. */ export { NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS, NGX_MAT_DATEFNS_DATE_ADAPTER_OPTIONS_FACTORY, NGX_MAT_DATEFNS_DATE_FORMATS, NGX_MAT_DATEFNS_LOCALES, NgxDateFnsDateAdapter, NgxDateFnsDateModule, NgxMatDateFnsDateModule, ɵ0, ɵ1 }; //# sourceMappingURL=ngx-mat-datefns-date-adapter.js.map