From 82b802bd74ca467d6dd0391d66ce45c65a240322 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Wed, 30 Aug 2017 15:56:07 -0700 Subject: [PATCH 01/15] create moment adapter --- package.json | 1 + .../moment-date-adapter/index.ts | 28 ++++ .../moment-date-adapter.spec.ts | 48 ++++++ .../moment-date-adapter.ts | 154 ++++++++++++++++++ .../moment-date-formats.ts | 22 +++ src/material-moment-adapter/package.json | 3 +- 6 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 src/material-moment-adapter/moment-date-adapter/index.ts create mode 100644 src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts create mode 100644 src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts create mode 100644 src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts diff --git a/package.json b/package.json index c0410f53ab5a..d7be6be388fb 100644 --- a/package.json +++ b/package.json @@ -101,6 +101,7 @@ "magic-string": "^0.21.3", "minimatch": "^3.0.4", "minimist": "^1.2.0", + "moment": "^2.18.1", "node-sass": "^4.5.3", "protractor": "^5.1.2", "request": "^2.81.0", diff --git a/src/material-moment-adapter/moment-date-adapter/index.ts b/src/material-moment-adapter/moment-date-adapter/index.ts new file mode 100644 index 000000000000..27b883632412 --- /dev/null +++ b/src/material-moment-adapter/moment-date-adapter/index.ts @@ -0,0 +1,28 @@ +/** + * @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 + */ + +import {NgModule} from '@angular/core'; +import {DateAdapter, MD_DATE_FORMATS} from '@angular/material'; +import {MomentDateAdapter} from './moment-date-adapter'; +import {MD_MOMENT_DATE_FORMATS} from './moment-date-formats'; + +export * from './moment-date-adapter'; +export * from './moment-date-formats'; + + +@NgModule({ + providers: [{provide: DateAdapter, useClass: MomentDateAdapter}], +}) +export class MomentDateModule {} + + +@NgModule({ + imports: [MomentDateModule], + providers: [{provide: MD_DATE_FORMATS, useValue: MD_MOMENT_DATE_FORMATS}], +}) +export class MdMomentDateModule {} diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts new file mode 100644 index 000000000000..a2195cb2a2ee --- /dev/null +++ b/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts @@ -0,0 +1,48 @@ +/** + * @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 + */ + +import {MomentDateAdapter} from './moment-date-adapter'; +import {async, inject, TestBed} from '@angular/core/testing'; +import {MomentDateModule} from './index'; +import {DateAdapter} from '@angular/material'; +import * as moment from 'moment'; + + +const JAN = 0, FEB = 1, MAR = 2, APR = 3, MAY = 4, JUN = 5, JUL = 6, AUG = 7, SEP = 8, OCT = 9, + NOV = 10, DEC = 11; + + +fdescribe('MomentDateAdapter', () => { + let adapter: MomentDateAdapter; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [MomentDateModule] + }).compileComponents(); + })); + + beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { + adapter = d; + })); + + it('should get year', () => { + expect(adapter.getYear(moment({y: 2017, m: JAN, d: 1}))).toBe(2017); + }); + + it('should get month', () => { + expect(adapter.getMonth(moment({y: 2017, m: JAN, d: 1}))).toBe(0); + }); + + it('should get date', () => { + expect(adapter.getDate(moment({y: 2017, m: JAN, d: 1}))).toBe(1); + }); + + it('should get day of week', () => { + expect(adapter.getDayOfWeek(moment({y: 2017, m: JAN, d: 1}))).toBe(0); + }); +}); diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts b/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts new file mode 100644 index 000000000000..3305c46ce7fa --- /dev/null +++ b/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts @@ -0,0 +1,154 @@ +/** + * @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 + */ + +import {Inject, Injectable, LOCALE_ID, Optional} from '@angular/core'; +import {DateAdapter} from '@angular/material'; +import * as moment from 'moment'; + + +/** Creates an array and fills it with values. */ +function range(length: number, valueFunction: (index: number) => T): T[] { + const valuesArray = Array(length); + for (let i = 0; i < length; i++) { + valuesArray[i] = valueFunction(i); + } + return valuesArray; +} + + +/** Adapts Moment.js Dates for use with Angular Material. */ +@Injectable() +export class MomentDateAdapter extends DateAdapter { + private _localeNames: { + longMonths: string[], + shortMonths: string[], + dates: string[], + longDaysOfWeek: string[], + shortDaysOfWeek: string[], + narrowDaysOfWeek: string[] + }; + + constructor(@Optional() @Inject(LOCALE_ID) localeId: any) { + super(); + this.setLocale(localeId || moment.locale()); + } + + setLocale(locale: any) { + super.setLocale(locale); + + // Temporarily change the global locale to get the data we need, then change it back. + let globalLocale = moment.locale(); + moment.locale(locale); + this._localeNames = { + longMonths: moment.months(), + shortMonths: moment.months(), + dates: range(31, (i) => this.createDate(2017, 0, i).format('DD')), + longDaysOfWeek: moment.weekdays(true), + shortDaysOfWeek: moment.weekdaysShort(true), + narrowDaysOfWeek: moment.weekdaysMin(true), + }; + moment.locale(globalLocale); + } + + getYear(date: moment.Moment): number { + return date.year(); + } + + getMonth(date: moment.Moment): number { + return date.month(); + } + + getDate(date: moment.Moment): number { + return date.date(); + } + + getDayOfWeek(date: moment.Moment): number { + return date.weekday(); + } + + getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { + return style == 'long' ? this._localeNames.longMonths : this._localeNames.shortMonths; + } + + getDateNames(): string[] { + return this._localeNames.dates; + } + + getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { + if (style == 'long') { + return this._localeNames.longDaysOfWeek; + } + if (style == 'short') { + return this._localeNames.shortDaysOfWeek; + } + return this._localeNames.narrowDaysOfWeek; + } + + getYearName(date: moment.Moment): string { + return date.format('YYYY'); + } + + getFirstDayOfWeek(): number { + // Moment's `weekday` method uses the current locale's ordering, so this will always be 0. + return 0; + } + + getNumDaysInMonth(date: moment.Moment): number { + return date.daysInMonth(); + } + + clone(date: moment.Moment): moment.Moment { + return date.clone(); + } + + createDate(year: number, month: number, date: number): moment.Moment { + return moment({year, month, date}); + } + + today(): moment.Moment { + return moment(); + } + + parse(value: any, parseFormat: string | string[]): moment.Moment | null { + if (typeof value == 'string') { + return moment(value, parseFormat, this.locale); + } + return value ? moment(value) : null; + } + + format(date: moment.Moment, displayFormat: string): string { + if (!this.isValid(date)) { + throw Error('MomentDateAdapter: Cannot format invalid date.'); + } + return date.format(displayFormat); + } + + addCalendarYears(date: moment.Moment, years: number): moment.Moment { + return date.clone().add({years}); + } + + addCalendarMonths(date: moment.Moment, months: number): moment.Moment { + return date.clone().add({months}); + } + + addCalendarDays(date: moment.Moment, days: number): moment.Moment { + return date.clone().add({days}); + } + + getISODateString(date: moment.Moment): string { + return date.format(); + } + + isDateInstance(obj: any): boolean { + return moment.isMoment(obj); + } + + isValid(date: moment.Moment): boolean { + return date.isValid(); + } +} diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts b/src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts new file mode 100644 index 000000000000..6f4747f0493c --- /dev/null +++ b/src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts @@ -0,0 +1,22 @@ +/** + * @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 + */ + +import {MdDateFormats} from '@angular/material'; + + +export const MD_MOMENT_DATE_FORMATS: MdDateFormats = { + parse: { + dateInput: 'l', + }, + display: { + dateInput: 'l', + monthYearLabel: 'MMM YYYY', + dateA11yLabel: 'LL', + monthYearA11yLabel: 'MMMM YYYY', + }, +}; diff --git a/src/material-moment-adapter/package.json b/src/material-moment-adapter/package.json index 116617becbc5..8e50eeac9aa7 100644 --- a/src/material-moment-adapter/package.json +++ b/src/material-moment-adapter/package.json @@ -17,7 +17,8 @@ "homepage": "https://github.com/angular/material2#readme", "peerDependencies": { "@angular/material": "0.0.0-PLACEHOLDER", - "@angular/core": "^4.0.0" + "@angular/core": "^4.0.0", + "moment": "^2.18.1" }, "dependencies": { "tslib": "^1.7.1" From dedf2350afdfedf0d292c3d36a7239b427efaa7e Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Thu, 31 Aug 2017 15:55:32 -0700 Subject: [PATCH 02/15] add Moment to karma.conf.js --- .../{moment-date-adapter => adapter}/index.ts | 0 .../moment-date-adapter.spec.ts | 0 .../moment-date-adapter.ts | 0 .../moment-date-formats.ts | 0 src/material-moment-adapter/index.spec.ts | 9 --------- src/material-moment-adapter/public_api.ts | 2 +- test/karma.conf.js | 1 + 7 files changed, 2 insertions(+), 10 deletions(-) rename src/material-moment-adapter/{moment-date-adapter => adapter}/index.ts (100%) rename src/material-moment-adapter/{moment-date-adapter => adapter}/moment-date-adapter.spec.ts (100%) rename src/material-moment-adapter/{moment-date-adapter => adapter}/moment-date-adapter.ts (100%) rename src/material-moment-adapter/{moment-date-adapter => adapter}/moment-date-formats.ts (100%) delete mode 100644 src/material-moment-adapter/index.spec.ts diff --git a/src/material-moment-adapter/moment-date-adapter/index.ts b/src/material-moment-adapter/adapter/index.ts similarity index 100% rename from src/material-moment-adapter/moment-date-adapter/index.ts rename to src/material-moment-adapter/adapter/index.ts diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts similarity index 100% rename from src/material-moment-adapter/moment-date-adapter/moment-date-adapter.spec.ts rename to src/material-moment-adapter/adapter/moment-date-adapter.spec.ts diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts similarity index 100% rename from src/material-moment-adapter/moment-date-adapter/moment-date-adapter.ts rename to src/material-moment-adapter/adapter/moment-date-adapter.ts diff --git a/src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts b/src/material-moment-adapter/adapter/moment-date-formats.ts similarity index 100% rename from src/material-moment-adapter/moment-date-adapter/moment-date-formats.ts rename to src/material-moment-adapter/adapter/moment-date-formats.ts diff --git a/src/material-moment-adapter/index.spec.ts b/src/material-moment-adapter/index.spec.ts deleted file mode 100644 index a1ef3b6c1707..000000000000 --- a/src/material-moment-adapter/index.spec.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {_momentAdapter} from './public_api'; - -describe('moment-adapter', () => { - - it('should be tested when running the tests', () => { - expect(_momentAdapter).toBe(0); - }); - -}); diff --git a/src/material-moment-adapter/public_api.ts b/src/material-moment-adapter/public_api.ts index 5f61ef654dcc..8d50b96839d7 100644 --- a/src/material-moment-adapter/public_api.ts +++ b/src/material-moment-adapter/public_api.ts @@ -6,4 +6,4 @@ * found in the LICENSE file at https://angular.io/license */ -export const _momentAdapter = 0; +export * from './adapter'; diff --git a/test/karma.conf.js b/test/karma.conf.js index c120d8a918e9..b2b39d0c7185 100644 --- a/test/karma.conf.js +++ b/test/karma.conf.js @@ -26,6 +26,7 @@ module.exports = (config) => { {pattern: 'node_modules/zone.js/dist/fake-async-test.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js.map', included: false, watched: false}, + {pattern: 'node_modules/moment/min/moment-with-locales.min.js', included: true, watched: false}, // Include all Angular dependencies {pattern: 'node_modules/@angular/**/*', included: false, watched: false}, From 3a6a0cfe54b39c16a03df5edcaa67e2880a78174 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 1 Sep 2017 09:00:29 -0700 Subject: [PATCH 03/15] use MAT_DATE_LOCALE --- src/material-moment-adapter/adapter/index.ts | 7 +++++-- src/material-moment-adapter/adapter/moment-date-adapter.ts | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/material-moment-adapter/adapter/index.ts b/src/material-moment-adapter/adapter/index.ts index 27b883632412..a88afda23779 100644 --- a/src/material-moment-adapter/adapter/index.ts +++ b/src/material-moment-adapter/adapter/index.ts @@ -7,7 +7,7 @@ */ import {NgModule} from '@angular/core'; -import {DateAdapter, MD_DATE_FORMATS} from '@angular/material'; +import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; import {MomentDateAdapter} from './moment-date-adapter'; import {MD_MOMENT_DATE_FORMATS} from './moment-date-formats'; @@ -16,7 +16,10 @@ export * from './moment-date-formats'; @NgModule({ - providers: [{provide: DateAdapter, useClass: MomentDateAdapter}], + providers: [ + MAT_DATE_LOCALE_PROVIDER, + {provide: DateAdapter, useClass: MomentDateAdapter} + ], }) export class MomentDateModule {} diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 3305c46ce7fa..8ae7cbce5f80 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -7,7 +7,7 @@ */ import {Inject, Injectable, LOCALE_ID, Optional} from '@angular/core'; -import {DateAdapter} from '@angular/material'; +import {DateAdapter, MAT_DATE_LOCALE, MAT_DATE_LOCALE_PROVIDER} from '@angular/material'; import * as moment from 'moment'; @@ -33,9 +33,9 @@ export class MomentDateAdapter extends DateAdapter { narrowDaysOfWeek: string[] }; - constructor(@Optional() @Inject(LOCALE_ID) localeId: any) { + constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) { super(); - this.setLocale(localeId || moment.locale()); + this.setLocale(dateLocale || moment.locale()); } setLocale(locale: any) { From f39e9d865837435507bbd711a09b8578368aa75a Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 1 Sep 2017 09:12:34 -0700 Subject: [PATCH 04/15] tests are now running --- test/karma-test-shim.js | 1 + test/karma.conf.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/karma-test-shim.js b/test/karma-test-shim.js index 3dfeae04facc..284a70373c49 100644 --- a/test/karma-test-shim.js +++ b/test/karma-test-shim.js @@ -20,6 +20,7 @@ System.config({ map: { 'rxjs': 'node:rxjs', 'main': 'main.js', + 'moment': 'node:moment/min/moment.min.js', // Angular specific mappings. '@angular/core': 'node:@angular/core/bundles/core.umd.js', diff --git a/test/karma.conf.js b/test/karma.conf.js index b2b39d0c7185..f74f3b336f42 100644 --- a/test/karma.conf.js +++ b/test/karma.conf.js @@ -26,7 +26,7 @@ module.exports = (config) => { {pattern: 'node_modules/zone.js/dist/fake-async-test.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js.map', included: false, watched: false}, - {pattern: 'node_modules/moment/min/moment-with-locales.min.js', included: true, watched: false}, + {pattern: 'node_modules/moment/min/moment.min.js', included: true, watched: false}, // Include all Angular dependencies {pattern: 'node_modules/@angular/**/*', included: false, watched: false}, From a81eeea04a440e8632e20ceedac7ace0d4e45060 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 1 Sep 2017 15:31:00 -0700 Subject: [PATCH 05/15] add in tests --- .../adapter/moment-date-adapter.spec.ts | 493 +++++++++++++++++- .../adapter/moment-date-adapter.ts | 86 +-- 2 files changed, 540 insertions(+), 39 deletions(-) diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index a2195cb2a2ee..778df2e94963 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -9,15 +9,158 @@ import {MomentDateAdapter} from './moment-date-adapter'; import {async, inject, TestBed} from '@angular/core/testing'; import {MomentDateModule} from './index'; -import {DateAdapter} from '@angular/material'; +import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; import * as moment from 'moment'; +import {LOCALE_ID} from '@angular/core'; -const JAN = 0, FEB = 1, MAR = 2, APR = 3, MAY = 4, JUN = 5, JUL = 6, AUG = 7, SEP = 8, OCT = 9, - NOV = 10, DEC = 11; +// Month constants for more readable tests. +const JAN = 0, FEB = 1, MAR = 2, DEC = 11; -fdescribe('MomentDateAdapter', () => { +// Add some locales for testing. These definitions come from Moment.js's fr.js and ja.js locale +// files. (We don't want to the version of moment that comes with locales because it's a lot of +// extra bytes to include in our tests.) +moment.defineLocale('fr', { + months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre' + .split('_'), + monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), + monthsParseExact: true, + weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm' + }, + calendar: { + sameDay: '[Aujourd’hui à] LT', + nextDay: '[Demain à] LT', + nextWeek: 'dddd [à] LT', + lastDay: '[Hier à] LT', + lastWeek: 'dddd [dernier à] LT', + sameElse: 'L' + }, + relativeTime: { + future: 'dans %s', + past: 'il y a %s', + s: 'quelques secondes', + m: 'une minute', + mm: '%d minutes', + h: 'une heure', + hh: '%d heures', + d: 'un jour', + dd: '%d jours', + M: 'un mois', + MM: '%d mois', + y: 'un an', + yy: '%d ans' + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|)/, + // tslint:disable-next-line:variable-name + ordinal: function (number, period) { + switch (period) { + // TODO: Return 'e' when day of month > 1. Move this case inside + // block for masculine words below. + // See https://github.com/moment/moment/issues/3375 + case 'D': + return number + (number === 1 ? 'er' : ''); + + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); + + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4 // The week that contains Jan 4th is the first week of the year. + } +} as any); + +moment.defineLocale('ja', { + months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), + weekdaysShort: '日_月_火_水_木_金_土'.split('_'), + weekdaysMin: '日_月_火_水_木_金_土'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY/MM/DD', + LL: 'YYYY年M月D日', + LLL: 'YYYY年M月D日 HH:mm', + LLLL: 'YYYY年M月D日 HH:mm dddd', + l: 'YYYY/MM/DD', + ll: 'YYYY年M月D日', + lll: 'YYYY年M月D日 HH:mm', + llll: 'YYYY年M月D日 HH:mm dddd' + }, + meridiemParse: /午前|午後/i, + isPM: function (input) { + return input === '午後'; + }, + meridiem: function (hour) { + if (hour < 12) { + return '午前'; + } else { + return '午後'; + } + }, + calendar: { + sameDay: '[今日] LT', + nextDay: '[明日] LT', + nextWeek: '[来週]dddd LT', + lastDay: '[昨日] LT', + lastWeek: '[前週]dddd LT', + sameElse: 'L' + }, + dayOfMonthOrdinalParse: /\d{1,2}日/, + // tslint:disable-next-line:variable-name + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + default: + return number; + } + }, + relativeTime: { + future: '%s後', + past: '%s前', + s: '数秒', + m: '1分', + mm: '%d分', + h: '1時間', + hh: '%d時間', + d: '1日', + dd: '%d日', + M: '1ヶ月', + MM: '%dヶ月', + y: '1年', + yy: '%d年' + } +} as any); + +moment.locale('en'); + + +describe('MomentDateAdapter', () => { let adapter: MomentDateAdapter; beforeEach(async(() => { @@ -28,21 +171,355 @@ fdescribe('MomentDateAdapter', () => { beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { adapter = d; + adapter.setLocale('en'); })); it('should get year', () => { - expect(adapter.getYear(moment({y: 2017, m: JAN, d: 1}))).toBe(2017); + expect(adapter.getYear(moment([2017, JAN, 1]))).toBe(2017); }); it('should get month', () => { - expect(adapter.getMonth(moment({y: 2017, m: JAN, d: 1}))).toBe(0); + expect(adapter.getMonth(moment([2017, JAN, 1]))).toBe(0); }); it('should get date', () => { - expect(adapter.getDate(moment({y: 2017, m: JAN, d: 1}))).toBe(1); + expect(adapter.getDate(moment([2017, JAN, 1]))).toBe(1); }); it('should get day of week', () => { - expect(adapter.getDayOfWeek(moment({y: 2017, m: JAN, d: 1}))).toBe(0); + expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0); + }); + + it('should get same day of week in a locale with a different first day of the week', () => { + adapter.setLocale('fr'); + expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0); + }); + + it('should get long month names', () => { + expect(adapter.getMonthNames('long')).toEqual([ + 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', + 'October', 'November', 'December' + ]); + }); + + it('should get long month names', () => { + expect(adapter.getMonthNames('short')).toEqual([ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ]); + }); + + it('should get narrow month names', () => { + expect(adapter.getMonthNames('narrow')).toEqual([ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ]); + }); + + it('should get month names in a different locale', () => { + adapter.setLocale('ja-JP'); + expect(adapter.getMonthNames('long')).toEqual([ + '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月' + ]); + }); + + it('should get date names', () => { + expect(adapter.getDateNames()).toEqual([ + '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' + ]); + }); + + it('should get date names in a different locale', () => { + adapter.setLocale('ja-JP'); + expect(adapter.getDateNames()).toEqual([ + '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' + ]); + }); + + it('should get long day of week names', () => { + expect(adapter.getDayOfWeekNames('long')).toEqual([ + 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + ]); + }); + + it('should get short day of week names', () => { + expect(adapter.getDayOfWeekNames('short')).toEqual([ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' + ]); + }); + + it('should get narrow day of week names', () => { + expect(adapter.getDayOfWeekNames('narrow')).toEqual([ + 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' + ]); + }); + + it('should get day of week names in a different locale', () => { + adapter.setLocale('ja-JP'); + expect(adapter.getDayOfWeekNames('long')).toEqual([ + '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日' + ]); + }); + + it('should get year name', () => { + expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('2017'); + }); + + it('should get year name in a different locale', () => { + adapter.setLocale('ja-JP'); + expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('2017'); + }); + + it('should get first day of week', () => { + expect(adapter.getFirstDayOfWeek()).toBe(0); + }); + + it('should get first day of week in a different locale', () => { + adapter.setLocale('fr'); + expect(adapter.getFirstDayOfWeek()).toBe(1); + }); + + it('should create Moment date', () => { + expect(adapter.createDate(2017, JAN, 1).format()).toEqual(moment([2017, JAN, 1]).format()); + }); + + it('should not create Moment date with month over/under-flow', () => { + expect(() => adapter.createDate(2017, DEC + 1, 1)).toThrow(); + expect(() => adapter.createDate(2017, JAN - 1, 1)).toThrow(); + }); + + it('should not create Moment date with date over/under-flow', () => { + expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); + expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); + }); + + it('should create Moment date with low year number', () => { + expect(adapter.createDate(-1, JAN, 1).year()).toBe(-1); + expect(adapter.createDate(0, JAN, 1).year()).toBe(0); + expect(adapter.createDate(50, JAN, 1).year()).toBe(50); + expect(adapter.createDate(99, JAN, 1).year()).toBe(99); + expect(adapter.createDate(100, JAN, 1).year()).toBe(100); + }); + + it("should get today's date", () => { + expect(adapter.sameDate(adapter.today(), moment())) + .toBe(true, "should be equal to today's date"); + }); + + it('should parse string according to given format', () => { + expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.format()) + .toEqual(moment([2017, JAN, 2]).format()); + expect(adapter.parse('1/2/2017', 'DD/MM/YYYY')!.format()) + .toEqual(moment([2017, FEB, 1]).format()); + }); + + it('should parse number', () => { + let timestamp = new Date().getTime(); + expect(adapter.parse(timestamp, 'MM/DD/YYYY')!.format()).toEqual(moment(timestamp).format()); + }); + + it ('should parse Date', () => { + let date = new Date(2017, JAN, 1); + expect(adapter.parse(date, 'MM/DD/YYYY')!.format()).toEqual(moment(date).format()); + }); + + it ('should parse Moment date', () => { + let date = moment([2017, JAN, 1]); + let parsedDate = adapter.parse(date, 'MM/DD/YYYY'); + expect(parsedDate!.format()).toEqual(date.format()); + expect(parsedDate).not.toBe(date); + }); + + it('should parse invalid value as invalid', () => { + let d = adapter.parse('hello', 'MM/DD/YYYY'); + expect(d).not.toBeNull(); + expect(adapter.isDateInstance(d)) + .toBe(true, 'Expected string to have been fed through Date.parse'); + expect(adapter.isValid(d as moment.Moment)) + .toBe(false, 'Expected to parse as "invalid date" object'); + }); + + it('should format date according to given format', () => { + expect(adapter.format(moment([2017, JAN, 2]), 'MM/DD/YYYY')).toEqual('01/02/2017'); + expect(adapter.format(moment([2017, JAN, 2]), 'DD/MM/YYYY')).toEqual('02/01/2017'); + }); + + it('should format with a different locale', () => { + expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('Jan 2, 2017'); + adapter.setLocale('ja-JP'); + expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2017年1月2日'); + }); + + it('should throw when attempting to format invalid date', () => { + expect(() => adapter.format(moment(NaN), 'MM/DD/YYYY')) + .toThrowError(/MomentDateAdapter: Cannot format invalid date\./); + }); + + it('should add years', () => { + expect(adapter.addCalendarYears(moment([2017, JAN, 1]), 1).format()) + .toEqual(moment([2018, JAN, 1]).format()); + expect(adapter.addCalendarYears(moment([2017, JAN, 1]), -1).format()) + .toEqual(moment([2016, JAN, 1]).format()); + }); + + it('should respect leap years when adding years', () => { + expect(adapter.addCalendarYears(moment([2016, FEB, 29]), 1).format()) + .toEqual(moment([2017, FEB, 28]).format()); + expect(adapter.addCalendarYears(moment([2016, FEB, 29]), -1).format()) + .toEqual(moment([2015, FEB, 28]).format()); + }); + + it('should add months', () => { + expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), 1).format()) + .toEqual(moment([2017, FEB, 1]).format()); + expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), -1).format()) + .toEqual(moment([2016, DEC, 1]).format()); + }); + + it('should respect month length differences when adding months', () => { + expect(adapter.addCalendarMonths(moment([2017, JAN, 31]), 1).format()) + .toEqual(moment([2017, FEB, 28]).format()); + expect(adapter.addCalendarMonths(moment([2017, MAR, 31]), -1).format()) + .toEqual(moment([2017, FEB, 28]).format()); + }); + + it('should add days', () => { + expect(adapter.addCalendarDays(moment([2017, JAN, 1]), 1).format()) + .toEqual(moment([2017, JAN, 2]).format()); + expect(adapter.addCalendarDays(moment([2017, JAN, 1]), -1).format()) + .toEqual(moment([2016, DEC, 31]).format()); + }); + + it('should clone', () => { + let date = moment([2017, JAN, 1]); + expect(adapter.clone(date).format()).toEqual(date.format()); + expect(adapter.clone(date)).not.toBe(date); + }); + + it('should compare dates', () => { + expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 2]))).toBeLessThan(0); + expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, FEB, 1]))).toBeLessThan(0); + expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2018, JAN, 1]))).toBeLessThan(0); + expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 1]))).toBe(0); + expect(adapter.compareDate(moment([2018, JAN, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0); + expect(adapter.compareDate(moment([2017, FEB, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0); + expect(adapter.compareDate(moment([2017, JAN, 2]), moment([2017, JAN, 1]))).toBeGreaterThan(0); + }); + + it('should clamp date at lower bound', () => { + expect(adapter.clampDate( + moment([2017, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) + .toEqual(moment([2018, JAN, 1])); + }); + + it('should clamp date at upper bound', () => { + expect(adapter.clampDate( + moment([2020, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) + .toEqual(moment([2019, JAN, 1])); + }); + + it('should clamp date already within bounds', () => { + expect(adapter.clampDate( + moment([2018, FEB, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) + .toEqual(moment([2018, FEB, 1])); + }); + + it('should count today as a valid date instance', () => { + let d = moment(); + expect(adapter.isValid(d)).toBe(true); + expect(adapter.isDateInstance(d)).toBe(true); + }); + + it('should count an invalid date as an invalid date instance', () => { + let d = moment(NaN); + expect(adapter.isValid(d)).toBe(false); + expect(adapter.isDateInstance(d)).toBe(true); + }); + + it('should count a string as not a date instance', () => { + let d = '1/1/2017'; + expect(adapter.isDateInstance(d)).toBe(false); + }); + + it('should count a Date as not a date instance', () => { + let d = new Date(); + expect(adapter.isDateInstance(d)).toBe(false); + }); + + it('setLocale should not modify global moment locale', () => { + expect(moment.locale()).toBe('en'); + adapter.setLocale('ja-JP'); + expect(moment.locale()).toBe('en'); + }); + + it('returned Moments should have correct locale', () => { + adapter.setLocale('ja-JP'); + expect(adapter.createDate(2017, JAN, 1).locale()).toBe('ja'); + expect(adapter.today().locale()).toBe('ja'); + expect(adapter.clone(moment()).locale()).toBe('ja'); + expect(adapter.parse('1/1/2017', 'MM/DD/YYYY')!.locale()).toBe('ja'); + expect(adapter.addCalendarDays(moment(), 1).locale()).toBe('ja'); + expect(adapter.addCalendarMonths(moment(), 1).locale()).toBe('ja'); + expect(adapter.addCalendarYears(moment(), 1).locale()).toBe('ja'); + }); + + it('should not change locale of Moments passed as params', () => { + let date = moment(); + expect(date.locale()).toBe('en'); + adapter.setLocale('ja-JP'); + adapter.getYear(date); + adapter.getMonth(date); + adapter.getDate(date); + adapter.getDayOfWeek(date); + adapter.getYearName(date); + adapter.getNumDaysInMonth(date); + adapter.clone(date); + adapter.parse(date, 'MM/DD/YYYY'); + adapter.format(date, 'MM/DD/YYYY'); + adapter.addCalendarDays(date, 1); + adapter.addCalendarMonths(date, 1); + adapter.addCalendarYears(date, 1); + adapter.getISODateString(date); + adapter.isDateInstance(date); + adapter.isValid(date); + expect(date.locale()).toBe('en'); + }); +}); + +describe('MomentDateAdapter with MAT_DATE_LOCALE override', () => { + let adapter: MomentDateAdapter; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [MomentDateModule], + providers: [{provide: MAT_DATE_LOCALE, useValue: 'ja-JP'}] + }).compileComponents(); + })); + + beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { + adapter = d; + })); + + it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => { + expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2017年1月2日'); + }); +}); + +describe('MomentDateAdapter with LOCALE_ID override', () => { + let adapter: MomentDateAdapter; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [MomentDateModule], + providers: [{provide: LOCALE_ID, useValue: 'fr'}] + }).compileComponents(); + })); + + beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { + adapter = d; + })); + + it('should take the default locale id from the LOCALE_ID injection token', () => { + expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2 janv. 2017'); }); }); diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 8ae7cbce5f80..822bcd600733 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -6,8 +6,8 @@ * found in the LICENSE file at https://angular.io/license */ -import {Inject, Injectable, LOCALE_ID, Optional} from '@angular/core'; -import {DateAdapter, MAT_DATE_LOCALE, MAT_DATE_LOCALE_PROVIDER} from '@angular/material'; +import {Inject, Injectable, Optional} from '@angular/core'; +import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; import * as moment from 'moment'; @@ -24,7 +24,12 @@ function range(length: number, valueFunction: (index: number) => T): T[] { /** Adapts Moment.js Dates for use with Angular Material. */ @Injectable() export class MomentDateAdapter extends DateAdapter { - private _localeNames: { + // Note: all of the methods that accept a `moment.Moment` input parameter immediately call + // `this.clone` on it. This is to ensure that we're working with a `moment.Moment` that has the + // correct locale setting while avoiding mutating the original object passed to us. + + private _localeData: { + firstDayOfWeek: number, longMonths: string[], shortMonths: string[], dates: string[], @@ -44,84 +49,103 @@ export class MomentDateAdapter extends DateAdapter { // Temporarily change the global locale to get the data we need, then change it back. let globalLocale = moment.locale(); moment.locale(locale); - this._localeNames = { + this._localeData = { + firstDayOfWeek: moment.localeData().firstDayOfWeek(), longMonths: moment.months(), - shortMonths: moment.months(), - dates: range(31, (i) => this.createDate(2017, 0, i).format('DD')), - longDaysOfWeek: moment.weekdays(true), - shortDaysOfWeek: moment.weekdaysShort(true), - narrowDaysOfWeek: moment.weekdaysMin(true), + shortMonths: moment.monthsShort(), + dates: range(31, (i) => this.createDate(2017, 0, i + 1).format('D')), + longDaysOfWeek: moment.weekdays(), + shortDaysOfWeek: moment.weekdaysShort(), + narrowDaysOfWeek: moment.weekdaysMin(), }; moment.locale(globalLocale); } getYear(date: moment.Moment): number { - return date.year(); + return this.clone(date).year(); } getMonth(date: moment.Moment): number { - return date.month(); + return this.clone(date).month(); } getDate(date: moment.Moment): number { - return date.date(); + return this.clone(date).date(); } getDayOfWeek(date: moment.Moment): number { - return date.weekday(); + return this.clone(date).day(); } getMonthNames(style: 'long' | 'short' | 'narrow'): string[] { - return style == 'long' ? this._localeNames.longMonths : this._localeNames.shortMonths; + // Moment.js doesn't support narrow month names, so we just use short if narrow is requested. + return style == 'long' ? this._localeData.longMonths : this._localeData.shortMonths; } getDateNames(): string[] { - return this._localeNames.dates; + return this._localeData.dates; } getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] { if (style == 'long') { - return this._localeNames.longDaysOfWeek; + return this._localeData.longDaysOfWeek; } if (style == 'short') { - return this._localeNames.shortDaysOfWeek; + return this._localeData.shortDaysOfWeek; } - return this._localeNames.narrowDaysOfWeek; + return this._localeData.narrowDaysOfWeek; } getYearName(date: moment.Moment): string { - return date.format('YYYY'); + return this.clone(date).format('YYYY'); } getFirstDayOfWeek(): number { - // Moment's `weekday` method uses the current locale's ordering, so this will always be 0. - return 0; + return this._localeData.firstDayOfWeek; } getNumDaysInMonth(date: moment.Moment): number { - return date.daysInMonth(); + return this.clone(date).daysInMonth(); } clone(date: moment.Moment): moment.Moment { - return date.clone(); + return date.clone().locale(this.locale); } createDate(year: number, month: number, date: number): moment.Moment { - return moment({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.`); + } + + let result = moment({year, month, date}).locale(this.locale); + + // If the result isn't valid, the date must have been out of bounds for this month. + if (!result.isValid()) { + throw Error(`Invalid date "${date}" for month with index "${month}".`); + } + + return result; } today(): moment.Moment { - return moment(); + return moment().locale(this.locale); } parse(value: any, parseFormat: string | string[]): moment.Moment | null { if (typeof value == 'string') { return moment(value, parseFormat, this.locale); } - return value ? moment(value) : null; + return value ? moment(value).locale(this.locale) : null; } format(date: moment.Moment, displayFormat: string): string { + date = this.clone(date); if (!this.isValid(date)) { throw Error('MomentDateAdapter: Cannot format invalid date.'); } @@ -129,19 +153,19 @@ export class MomentDateAdapter extends DateAdapter { } addCalendarYears(date: moment.Moment, years: number): moment.Moment { - return date.clone().add({years}); + return this.clone(date).add({years}); } addCalendarMonths(date: moment.Moment, months: number): moment.Moment { - return date.clone().add({months}); + return this.clone(date).add({months}); } addCalendarDays(date: moment.Moment, days: number): moment.Moment { - return date.clone().add({days}); + return this.clone(date).add({days}); } getISODateString(date: moment.Moment): string { - return date.format(); + return this.clone(date).format(); } isDateInstance(obj: any): boolean { @@ -149,6 +173,6 @@ export class MomentDateAdapter extends DateAdapter { } isValid(date: moment.Moment): boolean { - return date.isValid(); + return this.clone(date).isValid(); } } From 5aedf7e28f912f3b8e9fd39a61686b4635c9ce02 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 1 Sep 2017 15:54:59 -0700 Subject: [PATCH 06/15] WIP: demo --- src/demo-app/datepicker/datepicker-demo.html | 3 +++ .../datepicker/moment-datepicker.html | 3 +++ src/demo-app/datepicker/moment-datepicker.ts | 20 +++++++++++++++++++ src/demo-app/demo-app/demo-module.ts | 2 ++ src/demo-app/system-config.ts | 2 ++ src/demo-app/tsconfig-aot.json | 3 ++- src/demo-app/tsconfig-build.json | 3 ++- tools/gulp/tasks/development.ts | 2 +- tools/gulp/util/task_helpers.ts | 4 +++- tsconfig.json | 1 + 10 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 src/demo-app/datepicker/moment-datepicker.html create mode 100644 src/demo-app/datepicker/moment-datepicker.ts diff --git a/src/demo-app/datepicker/datepicker-demo.html b/src/demo-app/datepicker/datepicker-demo.html index 9f55b0820c61..62435cb5f16e 100644 --- a/src/demo-app/datepicker/datepicker-demo.html +++ b/src/demo-app/datepicker/datepicker-demo.html @@ -105,3 +105,6 @@

Input disabled, datepicker popup enabled

[startView]="yearView ? 'year' : 'month'">

+ +

Moment.js Datepicker

+

diff --git a/src/demo-app/datepicker/moment-datepicker.html b/src/demo-app/datepicker/moment-datepicker.html new file mode 100644 index 000000000000..fa302aad200f --- /dev/null +++ b/src/demo-app/datepicker/moment-datepicker.html @@ -0,0 +1,3 @@ + + + diff --git a/src/demo-app/datepicker/moment-datepicker.ts b/src/demo-app/datepicker/moment-datepicker.ts new file mode 100644 index 000000000000..ffe3ae704f27 --- /dev/null +++ b/src/demo-app/datepicker/moment-datepicker.ts @@ -0,0 +1,20 @@ +import {ChangeDetectionStrategy, Component} from '@angular/core'; +import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; +import {MomentDateAdapter, MD_MOMENT_DATE_FORMATS} from '@angular/material-moment-adapter'; +import * as moment from 'moment'; + + +@Component({ + moduleId: module.id, + selector: 'demo-moment-datepicker', + templateUrl: 'moment-datepicker.html', + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [ + MAT_DATE_LOCALE_PROVIDER, + {provide: DateAdapter, useClass: MomentDateAdapter}, + {provide: MD_DATE_FORMATS, useValue: MD_MOMENT_DATE_FORMATS}, + ], +}) +export class DemoMomentDatepicker { + date = moment(); +} diff --git a/src/demo-app/demo-app/demo-module.ts b/src/demo-app/demo-app/demo-module.ts index 79de0624a050..023584de33ed 100644 --- a/src/demo-app/demo-app/demo-module.ts +++ b/src/demo-app/demo-app/demo-module.ts @@ -47,6 +47,7 @@ import { OverlayContainer, } from '@angular/material'; import {TableHeaderDemo} from '../table/table-header-demo'; +import {DemoMomentDatepicker} from '../datepicker/moment-datepicker'; @NgModule({ imports: [ @@ -66,6 +67,7 @@ import {TableHeaderDemo} from '../table/table-header-demo'; CheckboxDemo, DatepickerDemo, DemoApp, + DemoMomentDatepicker, DialogDemo, GesturesDemo, GridListDemo, diff --git a/src/demo-app/system-config.ts b/src/demo-app/system-config.ts index 38f8de2c2284..96b0a3d3e9e3 100644 --- a/src/demo-app/system-config.ts +++ b/src/demo-app/system-config.ts @@ -9,6 +9,7 @@ System.config({ map: { 'rxjs': 'node:rxjs', 'main': 'main.js', + 'moment': 'node:moment/min/moment-with-locales.min.js', // Angular specific mappings. '@angular/core': 'node:@angular/core/bundles/core.umd.js', @@ -26,6 +27,7 @@ System.config({ 'node:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/material': 'dist/bundles/material.umd.js', + '@angular/material-moment-adapter': 'dist/bundles/material-moment-adapter.umd.js', '@angular/cdk': 'dist/bundles/cdk.umd.js', '@angular/cdk/a11y': 'dist/bundles/cdk-a11y.umd.js', '@angular/cdk/bidi': 'dist/bundles/cdk-bidi.umd.js', diff --git a/src/demo-app/tsconfig-aot.json b/src/demo-app/tsconfig-aot.json index 2240063c7bce..f868fe1c2677 100644 --- a/src/demo-app/tsconfig-aot.json +++ b/src/demo-app/tsconfig-aot.json @@ -11,7 +11,8 @@ "outDir": ".", "paths": { "@angular/material": ["./material"], - "@angular/cdk/*": ["./cdk/*"] + "@angular/cdk/*": ["./cdk/*"], + "@angular/material-moment-adapter": ["./material-moment-adapter"] } }, "files": [ diff --git a/src/demo-app/tsconfig-build.json b/src/demo-app/tsconfig-build.json index ff3196c1261d..98e6b789b1d1 100644 --- a/src/demo-app/tsconfig-build.json +++ b/src/demo-app/tsconfig-build.json @@ -22,7 +22,8 @@ "baseUrl": ".", "paths": { "@angular/material": ["../../dist/packages/material/public_api"], - "@angular/cdk/*": ["../../dist/packages/cdk/*"] + "@angular/cdk/*": ["../../dist/packages/cdk/*"], + "@angular/material-moment-adapter": ["../../dist/packages/material-moment-adapter"] } }, "files": [ diff --git a/tools/gulp/tasks/development.ts b/tools/gulp/tasks/development.ts index 5d8174a1c4d4..313a74239129 100644 --- a/tools/gulp/tasks/development.ts +++ b/tools/gulp/tasks/development.ts @@ -21,7 +21,7 @@ const materialOutPath = join(outputDir, 'packages', 'material'); /** Array of vendors that are required to serve the demo-app. */ const appVendors = [ - '@angular', 'systemjs', 'zone.js', 'rxjs', 'hammerjs', 'core-js', 'web-animations-js' + '@angular', 'systemjs', 'zone.js', 'rxjs', 'hammerjs', 'core-js', 'web-animations-js', 'moment', ]; /** Glob that matches all required vendors for the demo-app. */ diff --git a/tools/gulp/util/task_helpers.ts b/tools/gulp/util/task_helpers.ts index b9d6edbc5b79..8a109e8ae27b 100644 --- a/tools/gulp/util/task_helpers.ts +++ b/tools/gulp/util/task_helpers.ts @@ -130,7 +130,9 @@ export function buildAppTask(appName: string) { .filter(taskName => gulp.hasTask(taskName)); return sequenceTask( - 'material:clean-build', + // Build all required packages for serving the devapp by just building the moment-adapter + // package. All dependencies of that package (material, cdk) will be built automatically. + 'material-moment-adapter:clean-build', [...buildTasks] ); } diff --git a/tsconfig.json b/tsconfig.json index 6df0c68296f1..89a282dc2dc1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,6 +17,7 @@ "paths": { "@angular/material": ["./src/lib/public_api.ts"], "@angular/cdk/*": ["./src/cdk/*"], + "@angular/material-moment-adapter": ["./src/material-moment-adapter"], "@angular/material-examples": ["./src/material-examples"], "material2-build-tools": ["./tools/package-tools"] } From d10ec976153090825a46ee5a6995bdc0fcb2ea05 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Tue, 5 Sep 2017 15:28:46 -0700 Subject: [PATCH 07/15] add synthetic default imports for moment --- src/demo-app/datepicker/moment-datepicker.ts | 2 +- src/demo-app/tsconfig-aot.json | 2 ++ src/demo-app/tsconfig-build.json | 2 ++ src/material-moment-adapter/adapter/moment-date-adapter.spec.ts | 2 +- src/material-moment-adapter/adapter/moment-date-adapter.ts | 2 +- src/material-moment-adapter/tsconfig-build.json | 2 ++ src/material-moment-adapter/tsconfig-tests.json | 2 ++ tools/package-tools/rollup-globals.ts | 1 + tsconfig.json | 2 ++ 9 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/demo-app/datepicker/moment-datepicker.ts b/src/demo-app/datepicker/moment-datepicker.ts index ffe3ae704f27..9f9fc6d1e6dc 100644 --- a/src/demo-app/datepicker/moment-datepicker.ts +++ b/src/demo-app/datepicker/moment-datepicker.ts @@ -1,7 +1,7 @@ import {ChangeDetectionStrategy, Component} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; import {MomentDateAdapter, MD_MOMENT_DATE_FORMATS} from '@angular/material-moment-adapter'; -import * as moment from 'moment'; +import moment from 'moment'; @Component({ diff --git a/src/demo-app/tsconfig-aot.json b/src/demo-app/tsconfig-aot.json index f868fe1c2677..3835a9097a6e 100644 --- a/src/demo-app/tsconfig-aot.json +++ b/src/demo-app/tsconfig-aot.json @@ -4,6 +4,8 @@ { "extends": "./tsconfig-build", "compilerOptions": { + // Needed for Moment.js since it doesn't have a default export. + "allowSyntheticDefaultImports": true, "experimentalDecorators": true, // TODO(paul): Remove once Angular has been upgraded and supports noUnusedParameters in AOT. "noUnusedParameters": false, diff --git a/src/demo-app/tsconfig-build.json b/src/demo-app/tsconfig-build.json index 98e6b789b1d1..5c2906fd423c 100644 --- a/src/demo-app/tsconfig-build.json +++ b/src/demo-app/tsconfig-build.json @@ -2,6 +2,8 @@ // since the demo-app will be served in the browser. { "compilerOptions": { + // Needed for Moment.js since it doesn't have a default export. + "allowSyntheticDefaultImports": true, "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index 778df2e94963..b48ab584c0cc 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -10,7 +10,7 @@ import {MomentDateAdapter} from './moment-date-adapter'; import {async, inject, TestBed} from '@angular/core/testing'; import {MomentDateModule} from './index'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; -import * as moment from 'moment'; +import moment from 'moment'; import {LOCALE_ID} from '@angular/core'; diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 822bcd600733..49f286bc485d 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -8,7 +8,7 @@ import {Inject, Injectable, Optional} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; -import * as moment from 'moment'; +import moment from 'moment'; /** Creates an array and fills it with values. */ diff --git a/src/material-moment-adapter/tsconfig-build.json b/src/material-moment-adapter/tsconfig-build.json index de8b8dab6d0f..e964dd29752b 100644 --- a/src/material-moment-adapter/tsconfig-build.json +++ b/src/material-moment-adapter/tsconfig-build.json @@ -2,6 +2,8 @@ // needs to be ES2015 since the build process will create FESM bundles using rollup. { "compilerOptions": { + // Needed for Moment.js since it doesn't have a default export. + "allowSyntheticDefaultImports": true, "baseUrl": ".", "declaration": true, "stripInternal": false, diff --git a/src/material-moment-adapter/tsconfig-tests.json b/src/material-moment-adapter/tsconfig-tests.json index 4369cb530a23..a83a2a61d3c0 100644 --- a/src/material-moment-adapter/tsconfig-tests.json +++ b/src/material-moment-adapter/tsconfig-tests.json @@ -4,6 +4,8 @@ { "extends": "./tsconfig-build", "compilerOptions": { + // Needed for Moment.js since it doesn't have a default export. + "allowSyntheticDefaultImports": true, "importHelpers": false, "module": "commonjs", "target": "es5", diff --git a/tools/package-tools/rollup-globals.ts b/tools/package-tools/rollup-globals.ts index 55e513bb9537..7800d3530c51 100644 --- a/tools/package-tools/rollup-globals.ts +++ b/tools/package-tools/rollup-globals.ts @@ -17,6 +17,7 @@ const rollupCdkEntryPoints = cdkSecondaryEntryPoints.reduce((globals: any, entry /** Map of globals that are used inside of the different packages. */ export const rollupGlobals = { 'tslib': 'tslib', + 'moment': 'moment', '@angular/animations': 'ng.animations', '@angular/core': 'ng.core', diff --git a/tsconfig.json b/tsconfig.json index 89a282dc2dc1..e06d166854ce 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,8 @@ // IDEs and TSLint. For IDEs it ensures that `experimentalDecorator` warnings are not showing up. { "compilerOptions": { + // Needed for Moment.js since it doesn't have a default export. + "allowSyntheticDefaultImports": true, "rootDir": ".", "experimentalDecorators": true, "module": "es2015", From 9fd85e4590de4ca896ed0b49a4405473bb6852ca Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Thu, 7 Sep 2017 11:22:49 -0700 Subject: [PATCH 08/15] add locale switching to demo --- src/demo-app/datepicker/datepicker-demo.html | 7 ++++++- src/demo-app/datepicker/datepicker-demo.ts | 2 ++ src/demo-app/datepicker/moment-datepicker.html | 8 +++++--- src/demo-app/datepicker/moment-datepicker.ts | 11 +++++++++-- src/lib/core/datetime/date-adapter.ts | 8 ++++++++ src/lib/datepicker/datepicker-input.ts | 8 ++++++++ .../adapter/moment-date-adapter.spec.ts | 4 ++++ .../adapter/moment-date-adapter.ts | 2 +- 8 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/demo-app/datepicker/datepicker-demo.html b/src/demo-app/datepicker/datepicker-demo.html index 62435cb5f16e..bfaa024ae54a 100644 --- a/src/demo-app/datepicker/datepicker-demo.html +++ b/src/demo-app/datepicker/datepicker-demo.html @@ -107,4 +107,9 @@

Input disabled, datepicker popup enabled

Moment.js Datepicker

-

+

+ + {{l}} + +

+

diff --git a/src/demo-app/datepicker/datepicker-demo.ts b/src/demo-app/datepicker/datepicker-demo.ts index 3fc61b0b3144..88cba3667878 100644 --- a/src/demo-app/datepicker/datepicker-demo.ts +++ b/src/demo-app/datepicker/datepicker-demo.ts @@ -21,6 +21,8 @@ export class DatepickerDemo { date: Date; lastDateInput: Date | null; lastDateChange: Date | null; + locales = ['en', 'fr', 'ja']; + locale = 'en'; dateFilter = (date: Date) => date.getMonth() % 2 == 1 && date.getDate() % 2 == 0; diff --git a/src/demo-app/datepicker/moment-datepicker.html b/src/demo-app/datepicker/moment-datepicker.html index fa302aad200f..109c0ec5853f 100644 --- a/src/demo-app/datepicker/moment-datepicker.html +++ b/src/demo-app/datepicker/moment-datepicker.html @@ -1,3 +1,5 @@ - - - + + + + + diff --git a/src/demo-app/datepicker/moment-datepicker.ts b/src/demo-app/datepicker/moment-datepicker.ts index 9f9fc6d1e6dc..381ace7156f9 100644 --- a/src/demo-app/datepicker/moment-datepicker.ts +++ b/src/demo-app/datepicker/moment-datepicker.ts @@ -1,7 +1,7 @@ -import {ChangeDetectionStrategy, Component} from '@angular/core'; +import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; import {MomentDateAdapter, MD_MOMENT_DATE_FORMATS} from '@angular/material-moment-adapter'; -import moment from 'moment'; +import * as moment from 'moment'; @Component({ @@ -16,5 +16,12 @@ import moment from 'moment'; ], }) export class DemoMomentDatepicker { + @Input() + set locale(value: string) { + this._dateAdapter.setLocale(value); + } + date = moment(); + + constructor(private _dateAdapter: DateAdapter) {} } diff --git a/src/lib/core/datetime/date-adapter.ts b/src/lib/core/datetime/date-adapter.ts index 24172405d036..86369f8c85bf 100644 --- a/src/lib/core/datetime/date-adapter.ts +++ b/src/lib/core/datetime/date-adapter.ts @@ -7,6 +7,9 @@ */ import {InjectionToken, LOCALE_ID} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import {Subject} from 'rxjs/Subject'; + /** InjectionToken for datepicker that can be used to override default locale code. */ export const MAT_DATE_LOCALE = new InjectionToken('MAT_DATE_LOCALE'); @@ -19,6 +22,10 @@ export abstract class DateAdapter { /** The locale to use for all dates. */ protected locale: any; + /** A stream that emits when the locale changes. */ + get localeChanges(): Observable { return this._localeChanges; } + protected _localeChanges= new Subject(); + /** * Gets the year component of the given date. * @param date The date to extract the year from. @@ -184,6 +191,7 @@ export abstract class DateAdapter { */ setLocale(locale: any) { this.locale = locale; + this._localeChanges.next(); } /** diff --git a/src/lib/datepicker/datepicker-input.ts b/src/lib/datepicker/datepicker-input.ts index 7847a51b0bb4..aa09ae366812 100644 --- a/src/lib/datepicker/datepicker-input.ts +++ b/src/lib/datepicker/datepicker-input.ts @@ -182,6 +182,8 @@ export class MdDatepickerInput implements AfterContentInit, ControlValueAcces private _datepickerSubscription = Subscription.EMPTY; + private _localeSubscription = Subscription.EMPTY; + /** The form control validator for whether the input parses. */ private _parseValidator: ValidatorFn = (): ValidationErrors | null => { return this._lastValueValid ? @@ -228,6 +230,11 @@ export class MdDatepickerInput implements AfterContentInit, ControlValueAcces if (!this._dateFormats) { throw createMissingDateImplError('MD_DATE_FORMATS'); } + + // Update the displayed date when the locale changes. + this._localeSubscription = _dateAdapter.localeChanges.subscribe(() => { + this.value = this.value; + }); } ngAfterContentInit() { @@ -245,6 +252,7 @@ export class MdDatepickerInput implements AfterContentInit, ControlValueAcces ngOnDestroy() { this._datepickerSubscription.unsubscribe(); + this._localeSubscription.unsubscribe(); this._valueChange.complete(); this._disabledChange.complete(); } diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index b48ab584c0cc..0ea0bc133554 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -330,6 +330,10 @@ describe('MomentDateAdapter', () => { expect(parsedDate).not.toBe(date); }); + it('should parse empty string as null', () => { + expect(adapter.parse('', 'MM/DD/YYYY')).toBeNull(); + }); + it('should parse invalid value as invalid', () => { let d = adapter.parse('hello', 'MM/DD/YYYY'); expect(d).not.toBeNull(); diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 49f286bc485d..0787b5c936dd 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -138,7 +138,7 @@ export class MomentDateAdapter extends DateAdapter { } parse(value: any, parseFormat: string | string[]): moment.Moment | null { - if (typeof value == 'string') { + if (value && typeof value == 'string') { return moment(value, parseFormat, this.locale); } return value ? moment(value).locale(this.locale) : null; From c1d23ac7ed682f2fdf1b92466f96f3c9c760093d Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Thu, 7 Sep 2017 11:58:15 -0700 Subject: [PATCH 09/15] fix moment import issues with tests --- src/demo-app/tsconfig-aot.json | 2 - src/demo-app/tsconfig-build.json | 2 - .../adapter/moment-date-adapter.spec.ts | 2 +- .../adapter/moment-date-adapter.ts | 45 ++++++++++--------- .../tsconfig-tests.json | 2 - 5 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/demo-app/tsconfig-aot.json b/src/demo-app/tsconfig-aot.json index 3835a9097a6e..f868fe1c2677 100644 --- a/src/demo-app/tsconfig-aot.json +++ b/src/demo-app/tsconfig-aot.json @@ -4,8 +4,6 @@ { "extends": "./tsconfig-build", "compilerOptions": { - // Needed for Moment.js since it doesn't have a default export. - "allowSyntheticDefaultImports": true, "experimentalDecorators": true, // TODO(paul): Remove once Angular has been upgraded and supports noUnusedParameters in AOT. "noUnusedParameters": false, diff --git a/src/demo-app/tsconfig-build.json b/src/demo-app/tsconfig-build.json index 5c2906fd423c..98e6b789b1d1 100644 --- a/src/demo-app/tsconfig-build.json +++ b/src/demo-app/tsconfig-build.json @@ -2,8 +2,6 @@ // since the demo-app will be served in the browser. { "compilerOptions": { - // Needed for Moment.js since it doesn't have a default export. - "allowSyntheticDefaultImports": true, "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index 0ea0bc133554..d5257239ef37 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -10,7 +10,7 @@ import {MomentDateAdapter} from './moment-date-adapter'; import {async, inject, TestBed} from '@angular/core/testing'; import {MomentDateModule} from './index'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; -import moment from 'moment'; +import * as moment from 'moment'; import {LOCALE_ID} from '@angular/core'; diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 0787b5c936dd..c75178f670f2 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -8,7 +8,12 @@ import {Inject, Injectable, Optional} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; -import moment from 'moment'; + +// Depending on whether rollup is used, moment needs to be imported differently. +// TODO(mmalerba): See if we can clean this up at some point. +import {default as _rollupMoment, Moment} from 'moment'; +import * as _moment from 'moment'; +const moment = _rollupMoment || _moment; /** Creates an array and fills it with values. */ @@ -23,9 +28,9 @@ function range(length: number, valueFunction: (index: number) => T): T[] { /** Adapts Moment.js Dates for use with Angular Material. */ @Injectable() -export class MomentDateAdapter extends DateAdapter { - // Note: all of the methods that accept a `moment.Moment` input parameter immediately call - // `this.clone` on it. This is to ensure that we're working with a `moment.Moment` that has the +export class MomentDateAdapter extends DateAdapter { + // Note: all of the methods that accept a `Moment` input parameter immediately call + // `this.clone` on it. This is to ensure that we're working with a `Moment` that has the // correct locale setting while avoiding mutating the original object passed to us. private _localeData: { @@ -61,19 +66,19 @@ export class MomentDateAdapter extends DateAdapter { moment.locale(globalLocale); } - getYear(date: moment.Moment): number { + getYear(date: Moment): number { return this.clone(date).year(); } - getMonth(date: moment.Moment): number { + getMonth(date: Moment): number { return this.clone(date).month(); } - getDate(date: moment.Moment): number { + getDate(date: Moment): number { return this.clone(date).date(); } - getDayOfWeek(date: moment.Moment): number { + getDayOfWeek(date: Moment): number { return this.clone(date).day(); } @@ -96,7 +101,7 @@ export class MomentDateAdapter extends DateAdapter { return this._localeData.narrowDaysOfWeek; } - getYearName(date: moment.Moment): string { + getYearName(date: Moment): string { return this.clone(date).format('YYYY'); } @@ -104,15 +109,15 @@ export class MomentDateAdapter extends DateAdapter { return this._localeData.firstDayOfWeek; } - getNumDaysInMonth(date: moment.Moment): number { + getNumDaysInMonth(date: Moment): number { return this.clone(date).daysInMonth(); } - clone(date: moment.Moment): moment.Moment { + clone(date: Moment): Moment { return date.clone().locale(this.locale); } - createDate(year: number, month: number, date: number): moment.Moment { + createDate(year: number, month: number, date: number): Moment { // 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) { @@ -133,18 +138,18 @@ export class MomentDateAdapter extends DateAdapter { return result; } - today(): moment.Moment { + today(): Moment { return moment().locale(this.locale); } - parse(value: any, parseFormat: string | string[]): moment.Moment | null { + parse(value: any, parseFormat: string | string[]): Moment | null { if (value && typeof value == 'string') { return moment(value, parseFormat, this.locale); } return value ? moment(value).locale(this.locale) : null; } - format(date: moment.Moment, displayFormat: string): string { + format(date: Moment, displayFormat: string): string { date = this.clone(date); if (!this.isValid(date)) { throw Error('MomentDateAdapter: Cannot format invalid date.'); @@ -152,19 +157,19 @@ export class MomentDateAdapter extends DateAdapter { return date.format(displayFormat); } - addCalendarYears(date: moment.Moment, years: number): moment.Moment { + addCalendarYears(date: Moment, years: number): Moment { return this.clone(date).add({years}); } - addCalendarMonths(date: moment.Moment, months: number): moment.Moment { + addCalendarMonths(date: Moment, months: number): Moment { return this.clone(date).add({months}); } - addCalendarDays(date: moment.Moment, days: number): moment.Moment { + addCalendarDays(date: Moment, days: number): Moment { return this.clone(date).add({days}); } - getISODateString(date: moment.Moment): string { + getISODateString(date: Moment): string { return this.clone(date).format(); } @@ -172,7 +177,7 @@ export class MomentDateAdapter extends DateAdapter { return moment.isMoment(obj); } - isValid(date: moment.Moment): boolean { + isValid(date: Moment): boolean { return this.clone(date).isValid(); } } diff --git a/src/material-moment-adapter/tsconfig-tests.json b/src/material-moment-adapter/tsconfig-tests.json index a83a2a61d3c0..4369cb530a23 100644 --- a/src/material-moment-adapter/tsconfig-tests.json +++ b/src/material-moment-adapter/tsconfig-tests.json @@ -4,8 +4,6 @@ { "extends": "./tsconfig-build", "compilerOptions": { - // Needed for Moment.js since it doesn't have a default export. - "allowSyntheticDefaultImports": true, "importHelpers": false, "module": "commonjs", "target": "es5", From 5c7ba67901e26becc4119b7e07a5b3e23fea07a2 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Thu, 7 Sep 2017 14:54:28 -0700 Subject: [PATCH 10/15] fix aot --- src/demo-app/datepicker/moment-datepicker.ts | 9 ++++----- src/material-moment-adapter/adapter/index.ts | 9 +++++++-- tools/gulp/tasks/aot.ts | 4 +++- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/demo-app/datepicker/moment-datepicker.ts b/src/demo-app/datepicker/moment-datepicker.ts index 381ace7156f9..489536e401ca 100644 --- a/src/demo-app/datepicker/moment-datepicker.ts +++ b/src/demo-app/datepicker/moment-datepicker.ts @@ -1,6 +1,6 @@ -import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input} from '@angular/core'; -import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; -import {MomentDateAdapter, MD_MOMENT_DATE_FORMATS} from '@angular/material-moment-adapter'; +import {ChangeDetectionStrategy, Component, Input} from '@angular/core'; +import {DateAdapter, MAT_DATE_LOCALE, MD_DATE_FORMATS} from '@angular/material'; +import {MD_MOMENT_DATE_FORMATS, MomentDateAdapter} from '@angular/material-moment-adapter'; import * as moment from 'moment'; @@ -10,8 +10,7 @@ import * as moment from 'moment'; templateUrl: 'moment-datepicker.html', changeDetection: ChangeDetectionStrategy.OnPush, providers: [ - MAT_DATE_LOCALE_PROVIDER, - {provide: DateAdapter, useClass: MomentDateAdapter}, + {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]}, {provide: MD_DATE_FORMATS, useValue: MD_MOMENT_DATE_FORMATS}, ], }) diff --git a/src/material-moment-adapter/adapter/index.ts b/src/material-moment-adapter/adapter/index.ts index a88afda23779..df84c7dabace 100644 --- a/src/material-moment-adapter/adapter/index.ts +++ b/src/material-moment-adapter/adapter/index.ts @@ -7,7 +7,12 @@ */ import {NgModule} from '@angular/core'; -import {DateAdapter, MAT_DATE_LOCALE_PROVIDER, MD_DATE_FORMATS} from '@angular/material'; +import { + DateAdapter, + MAT_DATE_LOCALE, + MAT_DATE_LOCALE_PROVIDER, + MD_DATE_FORMATS +} from '@angular/material'; import {MomentDateAdapter} from './moment-date-adapter'; import {MD_MOMENT_DATE_FORMATS} from './moment-date-formats'; @@ -18,7 +23,7 @@ export * from './moment-date-formats'; @NgModule({ providers: [ MAT_DATE_LOCALE_PROVIDER, - {provide: DateAdapter, useClass: MomentDateAdapter} + {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]} ], }) export class MomentDateModule {} diff --git a/tools/gulp/tasks/aot.ts b/tools/gulp/tasks/aot.ts index 9c7d35ba5baa..425e95bebccd 100644 --- a/tools/gulp/tasks/aot.ts +++ b/tools/gulp/tasks/aot.ts @@ -18,7 +18,7 @@ const tsconfigFile = join(demoAppOut, 'tsconfig-aot.json'); /** Builds the demo-app and material. To be able to run NGC, apply the metadata workaround. */ task('aot:deps', sequenceTask( 'build:devapp', - ['material:build-release', 'cdk:build-release'], + ['material:build-release', 'cdk:build-release', 'material-moment-adapter:build-release'], 'aot:copy-release' )); @@ -27,6 +27,8 @@ task('aot:deps', sequenceTask( task('aot:copy-release', () => { copySync(join(releasesDir, 'material'), join(demoAppOut, 'material')); copySync(join(releasesDir, 'cdk'), join(demoAppOut, 'cdk')); + copySync( + join(releasesDir, 'material-moment-adapter'), join(demoAppOut, 'material-moment-adapter')); }); /** Build the demo-app and a release to confirm that the library is AOT-compatible. */ From add6ff0ef44e57aa4155953d9929efbacf8c6b9a Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Thu, 7 Sep 2017 16:47:22 -0700 Subject: [PATCH 11/15] address comments --- .../adapter/moment-date-adapter.spec.ts | 145 +----------------- .../adapter/moment-date-adapter.ts | 30 ++-- test/karma-test-shim.js | 2 +- test/karma.conf.js | 2 +- 4 files changed, 18 insertions(+), 161 deletions(-) diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index d5257239ef37..c8330e8f1eaf 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -10,156 +10,14 @@ import {MomentDateAdapter} from './moment-date-adapter'; import {async, inject, TestBed} from '@angular/core/testing'; import {MomentDateModule} from './index'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; -import * as moment from 'moment'; import {LOCALE_ID} from '@angular/core'; +import * as moment from 'moment'; // Month constants for more readable tests. const JAN = 0, FEB = 1, MAR = 2, DEC = 11; -// Add some locales for testing. These definitions come from Moment.js's fr.js and ja.js locale -// files. (We don't want to the version of moment that comes with locales because it's a lot of -// extra bytes to include in our tests.) -moment.defineLocale('fr', { - months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre' - .split('_'), - monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact: true, - weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm' - }, - calendar: { - sameDay: '[Aujourd’hui à] LT', - nextDay: '[Demain à] LT', - nextWeek: 'dddd [à] LT', - lastDay: '[Hier à] LT', - lastWeek: 'dddd [dernier à] LT', - sameElse: 'L' - }, - relativeTime: { - future: 'dans %s', - past: 'il y a %s', - s: 'quelques secondes', - m: 'une minute', - mm: '%d minutes', - h: 'une heure', - hh: '%d heures', - d: 'un jour', - dd: '%d jours', - M: 'un mois', - MM: '%d mois', - y: 'un an', - yy: '%d ans' - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|)/, - // tslint:disable-next-line:variable-name - ordinal: function (number, period) { - switch (period) { - // TODO: Return 'e' when day of month > 1. Move this case inside - // block for masculine words below. - // See https://github.com/moment/moment/issues/3375 - case 'D': - return number + (number === 1 ? 'er' : ''); - - // Words with masculine grammatical gender: mois, trimestre, jour - default: - case 'M': - case 'Q': - case 'DDD': - case 'd': - return number + (number === 1 ? 'er' : 'e'); - - // Words with feminine grammatical gender: semaine - case 'w': - case 'W': - return number + (number === 1 ? 're' : 'e'); - } - }, - week: { - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. - } -} as any); - -moment.defineLocale('ja', { - months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), - weekdaysShort: '日_月_火_水_木_金_土'.split('_'), - weekdaysMin: '日_月_火_水_木_金_土'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY/MM/DD', - LL: 'YYYY年M月D日', - LLL: 'YYYY年M月D日 HH:mm', - LLLL: 'YYYY年M月D日 HH:mm dddd', - l: 'YYYY/MM/DD', - ll: 'YYYY年M月D日', - lll: 'YYYY年M月D日 HH:mm', - llll: 'YYYY年M月D日 HH:mm dddd' - }, - meridiemParse: /午前|午後/i, - isPM: function (input) { - return input === '午後'; - }, - meridiem: function (hour) { - if (hour < 12) { - return '午前'; - } else { - return '午後'; - } - }, - calendar: { - sameDay: '[今日] LT', - nextDay: '[明日] LT', - nextWeek: '[来週]dddd LT', - lastDay: '[昨日] LT', - lastWeek: '[前週]dddd LT', - sameElse: 'L' - }, - dayOfMonthOrdinalParse: /\d{1,2}日/, - // tslint:disable-next-line:variable-name - ordinal: function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '日'; - default: - return number; - } - }, - relativeTime: { - future: '%s後', - past: '%s前', - s: '数秒', - m: '1分', - mm: '%d分', - h: '1時間', - hh: '%d時間', - d: '1日', - dd: '%d日', - M: '1ヶ月', - MM: '%dヶ月', - y: '1年', - yy: '%d年' - } -} as any); - -moment.locale('en'); - - describe('MomentDateAdapter', () => { let adapter: MomentDateAdapter; @@ -170,6 +28,7 @@ describe('MomentDateAdapter', () => { })); beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { + moment.locale('en'); adapter = d; adapter.setLocale('en'); })); diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index c75178f670f2..e39efb7e979e 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -29,9 +29,10 @@ function range(length: number, valueFunction: (index: number) => T): T[] { /** Adapts Moment.js Dates for use with Angular Material. */ @Injectable() export class MomentDateAdapter extends DateAdapter { - // Note: all of the methods that accept a `Moment` input parameter immediately call - // `this.clone` on it. This is to ensure that we're working with a `Moment` that has the - // correct locale setting while avoiding mutating the original object passed to us. + // Note: all of the methods that accept a `Moment` input parameter immediately call `this.clone` + // on it. This is to ensure that we're working with a `Moment` that has the correct locale setting + // while avoiding mutating the original object passed to us. Just calling `.locale(...)` on the + // input would mutate the object. private _localeData: { firstDayOfWeek: number, @@ -48,22 +49,19 @@ export class MomentDateAdapter extends DateAdapter { this.setLocale(dateLocale || moment.locale()); } - setLocale(locale: any) { + setLocale(locale: string) { super.setLocale(locale); - // Temporarily change the global locale to get the data we need, then change it back. - let globalLocale = moment.locale(); - moment.locale(locale); + let momentLocaleData = moment.localeData(locale); this._localeData = { - firstDayOfWeek: moment.localeData().firstDayOfWeek(), - longMonths: moment.months(), - shortMonths: moment.monthsShort(), + firstDayOfWeek: momentLocaleData.firstDayOfWeek(), + longMonths: momentLocaleData.months(), + shortMonths: momentLocaleData.monthsShort(), dates: range(31, (i) => this.createDate(2017, 0, i + 1).format('D')), - longDaysOfWeek: moment.weekdays(), - shortDaysOfWeek: moment.weekdaysShort(), - narrowDaysOfWeek: moment.weekdaysMin(), + longDaysOfWeek: momentLocaleData.weekdays(), + shortDaysOfWeek: momentLocaleData.weekdaysShort(), + narrowDaysOfWeek: momentLocaleData.weekdaysMin(), }; - moment.locale(globalLocale); } getYear(date: Moment): number { @@ -118,8 +116,8 @@ export class MomentDateAdapter extends DateAdapter { } createDate(year: number, month: number, date: number): Moment { - // Check for invalid month and date (except upper bound on date which we have to check after - // creating the Date). + // Moment.js will create an invalid date if any of the components are out of bounds, but we + // explicitly check each case so we can throw more descriptive errors. if (month < 0 || month > 11) { throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`); } diff --git a/test/karma-test-shim.js b/test/karma-test-shim.js index 284a70373c49..51fb7450022c 100644 --- a/test/karma-test-shim.js +++ b/test/karma-test-shim.js @@ -20,7 +20,7 @@ System.config({ map: { 'rxjs': 'node:rxjs', 'main': 'main.js', - 'moment': 'node:moment/min/moment.min.js', + 'moment': 'node:moment/min/moment-with-locales.min.js', // Angular specific mappings. '@angular/core': 'node:@angular/core/bundles/core.umd.js', diff --git a/test/karma.conf.js b/test/karma.conf.js index f74f3b336f42..b2b39d0c7185 100644 --- a/test/karma.conf.js +++ b/test/karma.conf.js @@ -26,7 +26,7 @@ module.exports = (config) => { {pattern: 'node_modules/zone.js/dist/fake-async-test.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js', included: true, watched: false}, {pattern: 'node_modules/hammerjs/hammer.min.js.map', included: false, watched: false}, - {pattern: 'node_modules/moment/min/moment.min.js', included: true, watched: false}, + {pattern: 'node_modules/moment/min/moment-with-locales.min.js', included: true, watched: false}, // Include all Angular dependencies {pattern: 'node_modules/@angular/**/*', included: false, watched: false}, From ef10910f484e8f3f74831a807c618a6062f162ac Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 8 Sep 2017 08:45:30 -0700 Subject: [PATCH 12/15] fix closure issue --- scripts/closure-compiler/build-devapp-bundle.sh | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/closure-compiler/build-devapp-bundle.sh b/scripts/closure-compiler/build-devapp-bundle.sh index 3d3b1607cdf8..8e483922b3fc 100755 --- a/scripts/closure-compiler/build-devapp-bundle.sh +++ b/scripts/closure-compiler/build-devapp-bundle.sh @@ -8,9 +8,10 @@ set -e -o pipefail # Go to the project root directory cd $(dirname $0)/../.. -# Build a release of material and of the CDK package. +# Build a release of material, material-moment-adapter, and cdk packages. $(npm bin)/gulp material:build-release:clean $(npm bin)/gulp cdk:build-release +$(npm bin)/gulp material-moment-adapter:build-release # Build demo-app with ES2015 modules. Closure compiler is then able to parse imports. $(npm bin)/gulp :build:devapp:assets :build:devapp:scss @@ -38,6 +39,7 @@ OPTS=( "--js_module_root=dist/packages" "--js_module_root=dist/releases/material" "--js_module_root=dist/releases/cdk" + "--js_module_root=dist/releases/material-moment-adapter" "--js_module_root=node_modules/@angular/core" "--js_module_root=node_modules/@angular/common" "--js_module_root=node_modules/@angular/compiler" @@ -49,6 +51,7 @@ OPTS=( "--js_module_root=node_modules/@angular/platform-browser-dynamic" "--js_module_root=node_modules/@angular/animations" "--js_module_root=node_modules/@angular/animations/browser" + "--js_module_root=node_modules/moment" # Flags to simplify debugging. "--formatting=PRETTY_PRINT" @@ -57,6 +60,7 @@ OPTS=( # Include the Material and CDK FESM bundles dist/releases/material/@angular/material.js dist/releases/cdk/@angular/cdk.js + dist/releases/material-moment-adapter/@angular/material-moment-adapter.js # Include all Angular FESM bundles. node_modules/@angular/core/@angular/core.js @@ -71,8 +75,9 @@ OPTS=( node_modules/@angular/animations/@angular/animations.js node_modules/@angular/animations/@angular/animations/browser.js - # Include other dependencies like Zone.js and RxJS + # Include other dependencies like Zone.js, Moment.js, and RxJS node_modules/zone.js/dist/zone.js + node_modules/moment/moment.js $rxjsSourceFiles # Include all files from the demo-app package. From e68ab357af21ef14ee01638493fd8bd9e7205de9 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Fri, 8 Sep 2017 10:10:13 -0700 Subject: [PATCH 13/15] add additional explanation of rollup issue --- src/material-moment-adapter/adapter/moment-date-adapter.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index e39efb7e979e..a941eec54354 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -10,6 +10,9 @@ import {Inject, Injectable, Optional} from '@angular/core'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material'; // Depending on whether rollup is used, moment needs to be imported differently. +// Since Moment.js doesn't have a default export, we normally need to import using the `* as` +// syntax. However, rollup creates a synthetic default module and we thus need to import it using +// the `default as` syntax. // TODO(mmalerba): See if we can clean this up at some point. import {default as _rollupMoment, Moment} from 'moment'; import * as _moment from 'moment'; From bbdb0f90f2e05c44a96677268c92de85c4132264 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Mon, 11 Sep 2017 16:43:18 -0700 Subject: [PATCH 14/15] remove moment adapter demo since it is preventing sync into g3 (will add back as a docs example in future PR). --- src/demo-app/datepicker/datepicker-demo.html | 8 ------ src/demo-app/datepicker/datepicker-demo.ts | 3 --- .../datepicker/moment-datepicker.html | 5 ---- src/demo-app/datepicker/moment-datepicker.ts | 26 ------------------- src/demo-app/demo-app/demo-module.ts | 2 -- 5 files changed, 44 deletions(-) delete mode 100644 src/demo-app/datepicker/moment-datepicker.html delete mode 100644 src/demo-app/datepicker/moment-datepicker.ts diff --git a/src/demo-app/datepicker/datepicker-demo.html b/src/demo-app/datepicker/datepicker-demo.html index bfaa024ae54a..9f55b0820c61 100644 --- a/src/demo-app/datepicker/datepicker-demo.html +++ b/src/demo-app/datepicker/datepicker-demo.html @@ -105,11 +105,3 @@

Input disabled, datepicker popup enabled

[startView]="yearView ? 'year' : 'month'">

- -

Moment.js Datepicker

-

- - {{l}} - -

-

diff --git a/src/demo-app/datepicker/datepicker-demo.ts b/src/demo-app/datepicker/datepicker-demo.ts index 88cba3667878..558912fe0e18 100644 --- a/src/demo-app/datepicker/datepicker-demo.ts +++ b/src/demo-app/datepicker/datepicker-demo.ts @@ -13,7 +13,6 @@ export class DatepickerDemo { touch: boolean; filterOdd: boolean; yearView: boolean; - inputDisabled: boolean; datepickerDisabled: boolean; minDate: Date; maxDate: Date; @@ -21,8 +20,6 @@ export class DatepickerDemo { date: Date; lastDateInput: Date | null; lastDateChange: Date | null; - locales = ['en', 'fr', 'ja']; - locale = 'en'; dateFilter = (date: Date) => date.getMonth() % 2 == 1 && date.getDate() % 2 == 0; diff --git a/src/demo-app/datepicker/moment-datepicker.html b/src/demo-app/datepicker/moment-datepicker.html deleted file mode 100644 index 109c0ec5853f..000000000000 --- a/src/demo-app/datepicker/moment-datepicker.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/src/demo-app/datepicker/moment-datepicker.ts b/src/demo-app/datepicker/moment-datepicker.ts deleted file mode 100644 index 489536e401ca..000000000000 --- a/src/demo-app/datepicker/moment-datepicker.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {ChangeDetectionStrategy, Component, Input} from '@angular/core'; -import {DateAdapter, MAT_DATE_LOCALE, MD_DATE_FORMATS} from '@angular/material'; -import {MD_MOMENT_DATE_FORMATS, MomentDateAdapter} from '@angular/material-moment-adapter'; -import * as moment from 'moment'; - - -@Component({ - moduleId: module.id, - selector: 'demo-moment-datepicker', - templateUrl: 'moment-datepicker.html', - changeDetection: ChangeDetectionStrategy.OnPush, - providers: [ - {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]}, - {provide: MD_DATE_FORMATS, useValue: MD_MOMENT_DATE_FORMATS}, - ], -}) -export class DemoMomentDatepicker { - @Input() - set locale(value: string) { - this._dateAdapter.setLocale(value); - } - - date = moment(); - - constructor(private _dateAdapter: DateAdapter) {} -} diff --git a/src/demo-app/demo-app/demo-module.ts b/src/demo-app/demo-app/demo-module.ts index 023584de33ed..79de0624a050 100644 --- a/src/demo-app/demo-app/demo-module.ts +++ b/src/demo-app/demo-app/demo-module.ts @@ -47,7 +47,6 @@ import { OverlayContainer, } from '@angular/material'; import {TableHeaderDemo} from '../table/table-header-demo'; -import {DemoMomentDatepicker} from '../datepicker/moment-datepicker'; @NgModule({ imports: [ @@ -67,7 +66,6 @@ import {DemoMomentDatepicker} from '../datepicker/moment-datepicker'; CheckboxDemo, DatepickerDemo, DemoApp, - DemoMomentDatepicker, DialogDemo, GesturesDemo, GridListDemo, From be25474458d39598ae0a754c3cc8083d799c63d9 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Tue, 12 Sep 2017 13:13:07 -0700 Subject: [PATCH 15/15] fix bad rebase --- src/demo-app/datepicker/datepicker-demo.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/demo-app/datepicker/datepicker-demo.ts b/src/demo-app/datepicker/datepicker-demo.ts index 558912fe0e18..3fc61b0b3144 100644 --- a/src/demo-app/datepicker/datepicker-demo.ts +++ b/src/demo-app/datepicker/datepicker-demo.ts @@ -13,6 +13,7 @@ export class DatepickerDemo { touch: boolean; filterOdd: boolean; yearView: boolean; + inputDisabled: boolean; datepickerDisabled: boolean; minDate: Date; maxDate: Date;