UNPKG

@tapsellorg/angular-material-library

Version:

Angular library for Tapsell

726 lines (714 loc) 25.9 kB
import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material/core'; import { StringUtils } from '@tapsellorg/angular-material-library/src/lib/common'; import * as i0 from '@angular/core'; import { Pipe, NgModule, Injectable } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatPaginatorIntl } from '@angular/material/paginator'; class JalaliDate { constructor(year, month, day) { this.year = year; this.month = month; this.day = day; this.addYears = (years) => { this.year += years; return this; }; this.addMonths = (months) => { const month = this.month + months; return this.setJalaliMonth(month); }; this.addDays = (days) => { const day = this.day + days; return this.setJalaliDay(day); }; } static from(value) { if (value instanceof JalaliDate) { return value; } if (typeof value === 'string' && !isDateStringIso(value)) { value = value.replace(/\s/, 'T'); value = `${value}Z`; } const date = new Date(value); if (Number.isNaN(date) || !(date instanceof Date)) { throw new Error('JalaliDate: Invalid pipe argument'); } return GregorianJalaliHelper.fromGregorian(date); } /** * string type is the jalali form of date: 1399/01/30 */ static parse(value, parseFormat) { const [year, month, day] = value.split('/'); return new JalaliDate(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10)); } clone() { return new JalaliDate(this.year, this.month, this.day); } isValid() { return (this.month > 0 && this.month < 13 && this.day > 0 && this.day <= GregorianJalaliHelper.getDaysPerMonth(this.month, this.year)); } dayOfWeek() { return GregorianJalaliHelper.toGregorian(this).getDay(); } format(displayFormat = 'YYYY/MM/DD') { return StringUtils.stringReplaceBulk(displayFormat, ['YYYY', 'MMMM', 'MM', 'DD'], [this.year, LONG_MONTHS[this.month - 1], this.month, this.day]); } setJalaliMonth(month) { this.year += Math.floor((month - 1) / 12); this.month = Math.floor((((month - 1) % 12) + 12) % 12) + 1; return this; } setJalaliDay(day) { let mDays = GregorianJalaliHelper.getDaysPerMonth(this.month, this.year); if (day <= 0) { while (day <= 0) { this.setJalaliMonth(this.month - 1); mDays = GregorianJalaliHelper.getDaysPerMonth(this.month, this.year); day += mDays; } } else if (day > mDays) { while (day > mDays) { day -= mDays; this.setJalaliMonth(this.month + 1); mDays = GregorianJalaliHelper.getDaysPerMonth(this.month, this.year); } } this.day = day; return this; } } class GregorianJalaliHelperClass { /** * Returns the equivalent jalali date value for a give input Gregorian date. * `gdate` is a JS Date to be converted to jalali. * utc to local */ fromGregorian(gdate) { const g2d = this.gregorianToDay(gdate.getFullYear(), gdate.getMonth() + 1, gdate.getDate()); return this.dayToJalali(g2d); } /* Converts a date of the Jalali calendar to the Julian Day number. @param jy Jalali year (1 to 3100) @param jm Jalali month (1 to 12) @param jd Jalali day (1 to 29/31) @return Julian Day number */ gregorianToDay(gy, gm, gd) { let day = div((gy + div(gm - 8, 6) + 100100) * 1461, 4) + div(153 * mod(gm + 9, 12) + 2, 5) + gd - 34840408; day = day - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752; return day; } /* Converts the Julian Day number to a date in the Jalali calendar. @param jdn Julian Day number @return jy: Jalali year (1 to 3100) jm: Jalali month (1 to 12) jd: Jalali day (1 to 29/31) */ dayToJalali(julianDayNumber) { const gy = this.dayToGregorian(julianDayNumber).getFullYear(); // Calculate Gregorian year (gy). let jalaliYear = gy - 621; const r = this.jalCal(jalaliYear); const gregorianDay = this.gregorianToDay(gy, 3, r.march); let jalaliDay; let jalaliMonth; let numberOfDays; // Find number of days that passed since 1 Farvardin. numberOfDays = julianDayNumber - gregorianDay; if (numberOfDays >= 0) { if (numberOfDays <= 185) { // The first 6 months. jalaliMonth = 1 + div(numberOfDays, 31); jalaliDay = mod(numberOfDays, 31) + 1; return new JalaliDate(jalaliYear, jalaliMonth, jalaliDay); } // The remaining months. numberOfDays -= 186; } else { // Previous Jalali year. jalaliYear -= 1; numberOfDays += 179; if (r.leap === 1) { numberOfDays += 1; } } jalaliMonth = 7 + div(numberOfDays, 30); jalaliDay = mod(numberOfDays, 30) + 1; return new JalaliDate(jalaliYear, jalaliMonth, jalaliDay); } /** * Returns the equivalent JS date value for a give input Jalali date. * `jalaliDate` is an Jalali date to be converted to Gregorian. */ toGregorian(jalaliDate) { const { year, month, day } = jalaliDate; const jdn = this.jalaliToDay(year, month, day); const date = this.dayToGregorian(jdn); date.setHours(6, 30, 3, 200); return date; } /* Converts a date of the Jalali calendar to the Julian Day number. @param jy Jalali year (1 to 3100) @param jm Jalali month (1 to 12) @param jd Jalali day (1 to 29/31) @return Julian Day number */ jalaliToDay(jYear, jMonth, jDay) { const r = this.jalCal(jYear); return (this.gregorianToDay(r.gy, 3, r.march) + (jMonth - 1) * 31 - div(jMonth, 7) * (jMonth - 7) + jDay - 1); } /* Calculates Gregorian and Julian calendar dates from the Julian Day number (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both calendars) to some millions years ahead of the present. @param jdn Julian Day number @return gy: Calendar year (years BC numbered 0, -1, -2, ...) gm: Calendar month (1 to 12) gd: Calendar day of the month M (1 to 28/29/30/31) */ dayToGregorian(julianDayNumber) { let j; j = 4 * julianDayNumber + 139361631; j = j + div(div(4 * julianDayNumber + 183187720, 146097) * 3, 4) * 4 - 3908; const i = div(mod(j, 1461), 4) * 5 + 308; const gDay = div(mod(i, 153), 5) + 1; const gMonth = mod(div(i, 153), 12) + 1; const gYear = div(j, 1461) - 100100 + div(8 - gMonth, 6); return new Date(gYear, gMonth - 1, gDay); } /* This function determines if the Jalali (Persian) year is leap (366-day long) or is the common year (365 days), and finds the day in March (Gregorian calendar) of the first day of the Jalali year (jy). @param jy Jalali calendar year (-61 to 3177) @return leap: number of years since the last leap year (0 to 4) gy: Gregorian year of the beginning of Jalali year march: the March day of Farvardin the 1st (1st day of jy) @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm @see: http://www.fourmilab.ch/documents/calendar/ */ jalCal(jalaliYear) { // Jalali years starting the 33-year rule. const breaks = [ -61, 9, 38, 199, 426, 686, 756, 818, 1111, 1181, 1210, 1635, 2060, 2097, 2192, 2262, 2324, 2394, 2456, 3178, ]; const breaksLength = breaks.length; const gYear = jalaliYear + 621; let leapJ = -14; let jp = breaks[0]; let jm; let jump; let leap; let n; let i; if (jalaliYear < jp || jalaliYear >= breaks[breaksLength - 1]) { throw new Error(`Invalid Jalali year ${jalaliYear}`); } // Find the limiting years for the Jalali year jalaliYear. for (i = 1; i < breaksLength; i += 1) { jm = breaks[i]; jump = jm - jp; if (jalaliYear < jm) { break; } leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4); jp = jm; } n = jalaliYear - jp; // Find the number of leap years from AD 621 to the beginning // of the current Jalali year in the Persian calendar. leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4); if (mod(jump, 33) === 4 && jump - n === 4) { leapJ += 1; } // And the same in the Gregorian calendar (until the year gYear). const leapG = div(gYear, 4) - div((div(gYear, 100) + 1) * 3, 4) - 150; // Determine the Gregorian date of Farvardin the 1st. const march = 20 + leapJ - leapG; // Find how many years have passed since the last leap year. if (jump - n < 6) { n = n - jump + div(jump + 4, 33) * 33; } leap = mod(mod(n + 1, 33) - 1, 4); if (leap === -1) { leap = 4; } return { leap, gy: gYear, march, }; } getDaysPerMonth(month, year) { if (month <= 6) { return 31; } if (month <= 11) { return 30; } if (this.jalCal(year).leap === 0) { return 30; } return 29; } } function mod(a, b) { return a - b * Math.floor(a / b); } function div(a, b) { return Math.trunc(a / b); } const GregorianJalaliHelper = new GregorianJalaliHelperClass(); const LONG_MONTHS = [ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند', ]; const ISO_DATE_REGEX = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d(:[0-5]\d)?(\.\d+)?([+-][0-2]\d:[0-5]\d|Z)?/; function isDateStringIso(dateString) { return ISO_DATE_REGEX.test(dateString); } class MaterialJalaliDateAdapter extends DateAdapter { constructor() { super(); this.dayNames = [...new Array(31)].map((_, i) => (i + 1).toString()); super.setLocale('fa-IR'); } getYear(date) { return this.clone(date).year; } getMonth(date) { return this.clone(date).month - 1; } getDate(date) { return this.clone(date).day; } getDayOfWeek(date) { return this.clone(date).dayOfWeek(); } getMonthNames(style) { // Jalali month names have no abbreviation and should be in long format // switch (style) { // case 'long': // return LONG_MONTHS; // case 'short': // return SHORT_MONTHS; // default: // // case 'narrow': // return NARROW_MONTHS; // } return LONG_MONTHS; } getDateNames() { return this.dayNames; } getDayOfWeekNames(style) { switch (style) { case 'long': return ['یکشنبه', 'دوشنبه', 'سه\u200Cشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه']; case 'short': return ['یک', 'دو', 'سه', 'چهار', 'پنج', 'جمعه', 'شنبه']; default: // case 'narrow': return ['ی', 'د', 'س', 'چ', 'پ', 'ج', 'ش']; } } getYearName(date) { return this.clone(date).year.toString(); } getFirstDayOfWeek() { return 6; } getNumDaysInMonth(date) { return GregorianJalaliHelper.getDaysPerMonth(date.month, date.year); } clone(date) { return date.clone(); // return date.clone().locale('fa-IR'); } createDate(year, month, date) { // console.log('#ee year', year, month, date); if (month < 0 || month > 12) { throw new Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } if (date < 1) { throw new Error(`Invalid date "${date}". Date has to be greater than 0.`); } const result = new JalaliDate(year, month + 1, date); // if (this.getMonth(result) !== month) { // throw new Error(`Invalid date ${date} for month with index ${month}.`); // } if (!result.isValid()) { throw new Error(`Invalid date "${date}" for month with index "${month}".`); } return result; } today() { return GregorianJalaliHelper.fromGregorian(new Date()); } parse(value, parseFormat) { if (typeof value === 'string') { return JalaliDate.parse(value, parseFormat); } return null; } format(date, displayFormat) { date = this.clone(date); if (!this.isValid(date)) { throw new Error('JalaliMomentDateAdapter: Cannot format invalid date.'); } return date.format(displayFormat); } addCalendarYears(date, years) { return this.clone(date).addYears(years); } addCalendarMonths(date, months) { return this.clone(date).addMonths(months); } addCalendarDays(date, days) { return this.clone(date).addDays(days); } toIso8601(date) { return this.clone(date).format('YYYY-MM-DD'); } isDateInstance(obj) { return obj instanceof JalaliDate; } isValid(date) { return this.clone(date).isValid(); } isLeapYear(year) { return year % 4 === 3; } invalid() { return new JalaliDate(-1, -1, -1); } deserialize(value) { let date; if (value instanceof Date) { date = GregorianJalaliHelper.fromGregorian(value); } if (!value) { return null; } if (date && this.isValid(date)) { return date; } return super.deserialize(value); } sameDate(first, second) { if (!first || !second) return false; return !this.compareDate(first, second); } compareDate(first, second) { if (!this.isValid(first) || !this.isValid(second)) return 0; return first.year - second.year || first.month - second.month || first.day - second.day; } } const JALALI_SLASH_FORMATS = { parse: { // eslint-disable-next-line sonarjs/no-duplicate-string dateInput: 'YYYY/MM/DD', }, display: { dateInput: 'YYYY/MM/DD', monthYearLabel: 'YYYY MMMM', dateA11yLabel: 'YYYY/MM/DD', monthYearA11yLabel: 'YYYY MMMM', }, }; const JALALI_NAME_MONTH_FORMATS = { parse: { // eslint-disable-next-line sonarjs/no-duplicate-string dateInput: 'DD MMMM YYYY', }, display: { dateInput: 'DD MMMM YYYY', monthYearLabel: 'MMMM YYYY', dateA11yLabel: 'DD MMMM YYYY', monthYearA11yLabel: 'MMMM YYYY', }, }; // @dynamic class DateUtils { static { this.ISO_DATE_REGEX = ISO_DATE_REGEX; } static isDateStringIso(dateString) { return this.isDateStringIso(dateString); } static getTodayJalali() { return this.gregorianToJalali(new Date()); } static jalaliToGregorian(date) { return GregorianJalaliHelper.toGregorian(date); } static gregorianToJalali(date) { return GregorianJalaliHelper.fromGregorian(date); } static isValidDate(date) { return !Number.isNaN(date) && date instanceof Date; } static format(date, format = 'YYYY/MM/DD') { const hours = date.getHours(); const minutes = date.getMinutes(); return StringUtils.stringReplaceBulk(format, ['YYYY', 'MM', 'DD', 'HH', 'MM'], [ date.getFullYear(), date.getMonth() + 1, date.getDay(), StringUtils.convertToTwoCharactersNumber(hours), StringUtils.convertToTwoCharactersNumber(minutes), ]); } /** * @deprecated use DateUtils.milliSecsToMinSecsConverter(milliSecs) * @param milliSecs */ static miliSecsToMinSecsConverter(milliSecs) { return DateUtils.milliSecsToMinSecsConverter(milliSecs); } static milliSecsToMinSecsConverter(milliSecs) { const secs = Math.floor(milliSecs / 1000); const seconds = secs % 60; const minutes = Math.floor(secs / 60); return { minutes, seconds }; } static isDateToday(_date) { const date = new Date(_date); return date.toDateString() === new Date().toDateString(); } static daysBetween(_date1, _date2) { const date1 = new Date(_date1); const date2 = new Date(_date2); return Math.abs(date1.getTime() - date2.getTime()) / 1000 / 3600 / 24; } static jalaliDaysBetween(_date1, _date2) { const date1 = this.jalaliToGregorian(_date1); const date2 = this.jalaliToGregorian(_date2); return this.daysBetween(date1, date2); } static getHourAndMinuteDate(date) { return `${date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', })}`; } static getOnlyDateISO(date) { const dateObj = new Date(date); return !date || this.isValidDate(dateObj) ? dateObj.toISOString().slice(0, 10) : null; } static calculateFromAndToOfDateRange(dateRange) { const toJalali = DateUtils.getTodayJalali(); toJalali.addDays(dateRange.to); if (!toJalali) { throw new Error('Calculated to jalali is null'); } const toDate = DateUtils.jalaliToGregorian(toJalali); const fromDate = new Date(toDate); fromDate.setDate(toDate.getDate() - (dateRange.length - 1)); const fromJalali = DateUtils.gregorianToJalali(fromDate); return { fromJalali, toJalali, fromDate, toDate }; } } class PghJalaliDatePipe { transform(value, time = false, dateParser) { if (!value) return ''; let jalaliDate; try { if (dateParser && typeof value === 'string') { jalaliDate = JalaliDate.from(dateParser(value)); } else { jalaliDate = JalaliDate.from(value); } } catch (error) { throw new Error('PghJalaliDatePipe: Invalid pipe argument'); } if (!time) { return jalaliDate.format(); } if (value instanceof JalaliDate) { throw new Error("pghJalaliDate Pipe: value type is JalaliDate and time format is required. JalaliDate doesn't have time data. Use a Date object instead"); } const timeFormat = typeof time === 'boolean' ? 'HH:MM' : time; const date = new Date(value); return `${jalaliDate.format()} ${DateUtils.format(date, timeFormat)}`; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDatePipe, isStandalone: false, name: "pghJalaliDate" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDatePipe, decorators: [{ type: Pipe, args: [{ name: 'pghJalaliDate', pure: true, standalone: false, }] }] }); class PghJalaliDateModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDateModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDateModule, declarations: [PghJalaliDatePipe], imports: [CommonModule], exports: [PghJalaliDatePipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDateModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghJalaliDateModule, decorators: [{ type: NgModule, args: [{ declarations: [PghJalaliDatePipe], imports: [CommonModule], exports: [PghJalaliDatePipe], }] }] }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n) { const i = Math.floor(Math.abs(n)); if (i === 0 || n === 1) { return 1; } return 5; } const localeIr = ({ isRial = false }) => [ 'fa-IR', [ ['ق', 'ب'], ['ق.ظ.', 'ب.ظ.'], ['قبل\u200Cازظهر', 'بعدازظهر'], ], [['ق.ظ.', 'ب.ظ.'], u, ['قبل\u200Cازظهر', 'بعدازظهر']], [ ['ی', 'د', 'س', 'چ', 'پ', 'ج', 'ش'], ['یک', 'دو', 'سه', 'چهار', 'پنج', 'جمعه', 'شنبه'], ['یکشنبه', 'دوشنبه', 'سه\u200Cشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'], ['۱ش', '۲ش', '۳ش', '۴ش', '۵ش', 'ج', 'ش'], ], u, [ ['فر', 'ار', 'خر', 'تی', 'مر', 'شه', 'مه', 'آ', 'آذ', 'دی', 'به', 'اس'], ['فرو', 'اردی', 'خرد', 'تیر', 'مرد', 'شهر', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسف'], [ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند', ], ], [ ['ژ', 'ف', 'م', 'آ', 'م', 'ژ', 'ژ', 'ا', 'س', 'ا', 'ن', 'د'], [ 'ژانویه', 'فوریه', 'مارس', 'آوریل', 'مه', 'ژوئن', 'ژوئیه', 'اوت', 'سپتامبر', 'اکتبر', 'نوامبر', 'دسامبر', ], u, ], [ ['ق', 'م'], ['ق.م.', 'م.'], ['قبل از میلاد', 'میلادی'], ], 6, [5, 5], ['y/M/d', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'], ['H:mm', 'H:mm:ss', 'H:mm:ss (z)', 'H:mm:ss (zzzz)'], ['{1}،\u200F {0}', u, '{1}، ساعت {0}', u], ['.', ',', ';', '%', '\u200E+', '\u200E−', 'E', '×', '‰', '∞', 'غیر عدد', ':'], ['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'], 'IRR', isRial ? 'ریال' : 'تومان', isRial ? 'ریال ایران' : 'تومان ایران', { IRR: isRial ? ['ریال', 'ریال', 'ریال'] : ['تومان', 'تومان', 'تومان'], }, 'rtl', plural, ]; class PghPersianMatPaginatorIntl extends MatPaginatorIntl { constructor() { super(...arguments); this.itemsPerPageLabel = 'آیتم در هر صفحه'; this.nextPageLabel = 'صفحه‌ی بعد'; this.previousPageLabel = 'صفحه‌ی قبل'; this.firstPageLabel = 'صفحه اول'; this.lastPageLabel = 'صفحه آخر'; this.getRangeLabel = (page, pageSize, length) => { if (length === 0 || pageSize === 0) return `0 از ${length}`; length = Math.max(length, 0); const startIndex = page * pageSize; const endIndex = startIndex < length ? Math.min(startIndex + pageSize, length) : startIndex + pageSize; return `${startIndex + 1} - ${endIndex} از ${length}`; }; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghPersianMatPaginatorIntl, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghPersianMatPaginatorIntl }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghPersianMatPaginatorIntl, decorators: [{ type: Injectable }] }); const PGH_MAT_PERSIAN_GLOBAL_OPTIONS = [ { provide: DateAdapter, useClass: MaterialJalaliDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: JALALI_SLASH_FORMATS }, { provide: MatPaginatorIntl, useClass: PghPersianMatPaginatorIntl }, ]; /** * Generated bundle index. Do not edit. */ export { DateUtils, GregorianJalaliHelper, JALALI_NAME_MONTH_FORMATS, JALALI_SLASH_FORMATS, JalaliDate, MaterialJalaliDateAdapter, PGH_MAT_PERSIAN_GLOBAL_OPTIONS, PghJalaliDateModule, PghJalaliDatePipe, PghPersianMatPaginatorIntl, localeIr }; //# sourceMappingURL=tapsellorg-angular-material-library-src-lib-jalali-date-adapter.mjs.map