Skip to content

Commit

Permalink
feat(module:date-picker): support parse input value (#4833)
Browse files Browse the repository at this point in the history
* feat(module:date-picker): support parse input value

* test: fix tests

* chore: support datefnsCompat option

* fix: not import from i18n in core

* chore: change API name and add docs

* chore: change format convert from config to token

* docs: update docs

* chore: move some types

* docs: update docs for date-fns update

* chore: change name and add warning

* docs: update docs
Close #4028
Close #3976
Close #2492
Close #4101
  • Loading branch information
wenqi73 authored Mar 15, 2020
1 parent e7fa38e commit 6a523ba
Show file tree
Hide file tree
Showing 30 changed files with 369 additions and 136 deletions.
4 changes: 2 additions & 2 deletions components/comment/demo/basic.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import { distanceInWords } from 'date-fns';
import { formatDistance } from 'date-fns';

@Component({
selector: 'nz-demo-comment-basic',
Expand Down Expand Up @@ -35,7 +35,7 @@ import { distanceInWords } from 'date-fns';
export class NzDemoCommentBasicComponent {
likes = 0;
dislikes = 0;
time = distanceInWords(new Date(), new Date());
time = formatDistance(new Date(), new Date());

like(): void {
this.likes = 1;
Expand Down
6 changes: 3 additions & 3 deletions components/comment/demo/editor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import { distanceInWords } from 'date-fns';
import { formatDistance } from 'date-fns';

@Component({
selector: 'nz-demo-comment-editor',
Expand Down Expand Up @@ -51,12 +51,12 @@ export class NzDemoCommentEditorComponent {
...this.user,
content,
datetime: new Date(),
displayTime: distanceInWords(new Date(), new Date())
displayTime: formatDistance(new Date(), new Date())
}
].map(e => {
return {
...e,
displayTime: distanceInWords(new Date(), e.datetime)
displayTime: formatDistance(new Date(), e.datetime)
};
});
}, 800);
Expand Down
6 changes: 3 additions & 3 deletions components/comment/demo/list.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import { addDays, distanceInWords } from 'date-fns';
import { addDays, formatDistance } from 'date-fns';

@Component({
selector: 'nz-demo-comment-list',
Expand All @@ -25,15 +25,15 @@ export class NzDemoCommentListComponent {
content:
'We supply a series of design principles, practical patterns and high quality design resources' +
'(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
datetime: distanceInWords(new Date(), addDays(new Date(), 1))
datetime: formatDistance(new Date(), addDays(new Date(), 1))
},
{
author: 'Han Solo',
avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
content:
'We supply a series of design principles, practical patterns and high quality design resources' +
'(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
datetime: distanceInWords(new Date(), addDays(new Date(), 2))
datetime: formatDistance(new Date(), addDays(new Date(), 2))
}
];
}
13 changes: 7 additions & 6 deletions components/core/time/candy-date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@ import {
startOfMonth,
startOfWeek
} from 'date-fns';
import addMonths from 'date-fns/add_months';
import addYears from 'date-fns/add_years';
import setDay from 'date-fns/set_day';
import setMonth from 'date-fns/set_month';
import addMonths from 'date-fns/addMonths';
import addYears from 'date-fns/addYears';
import setDay from 'date-fns/setDay';
import setMonth from 'date-fns/setMonth';
import { warn } from '../logger';
import { IndexableObject } from '../types';

export type WeekDayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export type CandyDateCompareGrain = 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second';
export type CandyDateType = CandyDate | Date | null;
export type SingleValue = CandyDate | null;
Expand Down Expand Up @@ -94,7 +95,7 @@ export class CandyDate implements IndexableObject {
// return this;
// }

calendarStart(options?: { weekStartsOn: number | undefined }): CandyDate {
calendarStart(options?: { weekStartsOn: WeekDayIndex | undefined }): CandyDate {
return new CandyDate(startOfWeek(startOfMonth(this.nativeDate), options));
}

Expand Down Expand Up @@ -168,7 +169,7 @@ export class CandyDate implements IndexableObject {
return new CandyDate(addMonths(this.nativeDate, amount));
}

setDay(day: number, options?: { weekStartsOn: number }): CandyDate {
setDay(day: number, options?: { weekStartsOn: WeekDayIndex }): CandyDate {
return new CandyDate(setDay(this.nativeDate, day, options));
}

Expand Down
8 changes: 2 additions & 6 deletions components/date-picker/abstract-picker.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,9 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe
// Default format when it's empty
if (!this.nzFormat) {
if (this.showWeek) {
this.nzFormat = this.dateHelper.relyOnDatePipe ? 'yyyy-ww' : 'YYYY-WW'; // Format for week
this.nzFormat = 'yyyy-ww'; // Format for week
} else {
if (this.dateHelper.relyOnDatePipe) {
this.nzFormat = this.nzShowTime ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd';
} else {
this.nzFormat = this.nzShowTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD';
}
this.nzFormat = this.nzShowTime ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd';
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions components/date-picker/calendar-footer.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import {
} from '@angular/core';

import { CandyDate, isNonEmptyString, isTemplateRef } from 'ng-zorro-antd/core';
import { DateHelperByDatePipe, DateHelperService, NzCalendarI18nInterface } from 'ng-zorro-antd/i18n';
import { DateHelperService, NzCalendarI18nInterface } from 'ng-zorro-antd/i18n';
import { transCompatFormat } from './lib/util';
import { PREFIX_CLASS } from './name';

@Component({
Expand Down Expand Up @@ -102,10 +103,7 @@ export class CalendarFooterComponent implements OnChanges {
}
if (changes.locale) {
// NOTE: Compat for DatePipe formatting rules
let dateFormat: string = this.locale.dateFormat;
if (this.dateHelper.relyOnDatePipe) {
dateFormat = (this.dateHelper as DateHelperByDatePipe).transCompatFormat(dateFormat);
}
const dateFormat: string = transCompatFormat(this.locale.dateFormat);
this.todayTitle = this.dateHelper.format(this.now.nativeDate, dateFormat);
}
}
Expand Down
61 changes: 59 additions & 2 deletions components/date-picker/date-picker.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import { ComponentFixture, fakeAsync, flush, inject, TestBed, tick } from '@angu
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import isSameDay from 'date-fns/is_same_day';
import isSameDay from 'date-fns/isSameDay';

import { dispatchKeyboardEvent, dispatchMouseEvent, NgStyleInterface, typeInElement } from 'ng-zorro-antd/core';
import en_US from '../i18n/languages/en_US';
import { PREFIX_CLASS } from './name';
import { getPicker, getPickerAbstract, getPickerInput } from './testing/util';

import { NzI18nModule, NzI18nService } from 'ng-zorro-antd/i18n';
import { enUS } from 'date-fns/locale';
import { NZ_DATE_LOCALE, NzI18nModule, NzI18nService } from 'ng-zorro-antd/i18n';
import { NzDatePickerModule } from './date-picker.module';

registerLocaleData(zh);
Expand Down Expand Up @@ -217,6 +218,20 @@ describe('NzDatePickerComponent', () => {
expect(getPickerContainer()).toBeNull();
}));

it('should support nzFormat', fakeAsync(() => {
fixtureInstance.nzFormat = 'dd.MM.yyyy';
fixtureInstance.nzValue = new Date('2020-03-04');
fixture.detectChanges();
openPickerByClickTrigger();
const input = getPickerInput(fixture.debugElement);
expect(input.value).toBe('04.03.2020');
dispatchMouseEvent(queryFromOverlay('.ant-picker-cell')!, 'click');
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(input.value).toBe('24.02.2020');
}));

it('should support nzClassName', () => {
const className = (fixtureInstance.nzClassName = 'my-test-class');
fixture.detectChanges();
Expand Down Expand Up @@ -835,6 +850,46 @@ describe('NzDatePickerComponent', () => {
}
});

describe('date-fns testing', () => {
let fixture: ComponentFixture<NzTestDatePickerComponent>;
let fixtureInstance: NzTestDatePickerComponent;

beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [FormsModule, NoopAnimationsModule, NzDatePickerModule, NzI18nModule],
providers: [{ provide: NZ_DATE_LOCALE, useValue: enUS }],
declarations: [NzTestDatePickerComponent]
});
TestBed.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(NzTestDatePickerComponent);
fixtureInstance = fixture.componentInstance;
fixtureInstance.useSuite = 1;
});

it('should parse input value with nzFormat', fakeAsync(() => {
const nzOnChange = spyOn(fixtureInstance, 'nzOnChange');
fixtureInstance.nzFormat = 'dd.MM.yyyy';
fixture.detectChanges();
dispatchMouseEvent(getPickerInput(fixture.debugElement), 'click');
fixture.detectChanges();
tick(500);
fixture.detectChanges();
const input = getPickerInput(fixture.debugElement);
typeInElement('25.10.2019', input);
fixture.detectChanges();
input.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }));
fixture.detectChanges();
flush();
const result = (nzOnChange.calls.allArgs()[0] as Date[])[0];
expect(result.getFullYear()).toBe(2019);
expect(result.getMonth() + 1).toBe(10);
expect(result.getDate()).toBe(25);
}));
});

@Component({
template: `
<ng-container [ngSwitch]="useSuite">
Expand All @@ -846,6 +901,7 @@ describe('NzDatePickerComponent', () => {
[nzDisabled]="nzDisabled"
[nzClassName]="nzClassName"
[nzDisabledDate]="nzDisabledDate"
[nzFormat]="nzFormat"
[nzLocale]="nzLocale"
[nzPlaceHolder]="nzPlaceHolder"
[nzPopupStyle]="nzPopupStyle"
Expand Down Expand Up @@ -892,6 +948,7 @@ class NzTestDatePickerComponent {
nzAutoFocus: boolean;
nzDisabled: boolean;
nzClassName: string;
nzFormat: string;
nzDisabledDate: (d: Date) => boolean;
nzLocale: any; // tslint:disable-line:no-any
nzPlaceHolder: string;
Expand Down
2 changes: 1 addition & 1 deletion components/date-picker/demo/basic.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import getISOWeek from 'date-fns/get_iso_week';
import getISOWeek from 'date-fns/getISOWeek';
import { en_US, NzI18nService, zh_CN } from 'ng-zorro-antd/i18n';

@Component({
Expand Down
4 changes: 2 additions & 2 deletions components/date-picker/demo/disabled-date.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Component } from '@angular/core';
import differenceInCalendarDays from 'date-fns/difference_in_calendar_days';
import setHours from 'date-fns/set_hours';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import setHours from 'date-fns/setHours';
import { DisabledTimeFn, DisabledTimePartial } from 'ng-zorro-antd/date-picker/standard-types';

@Component({
Expand Down
2 changes: 1 addition & 1 deletion components/date-picker/demo/presetted-ranges.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import endOfMonth from 'date-fns/end_of_month';
import endOfMonth from 'date-fns/endOfMonth';

@Component({
selector: 'nz-demo-date-picker-presetted-ranges',
Expand Down
2 changes: 1 addition & 1 deletion components/date-picker/lib/abstract-panel-header.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
role="button"
type="button"
title="{{ selector.title || null }}"
(click)="selector.onClick ? selector.onClick() : null"
(click)="selector.onClick()"
>
{{ selector.label }}
</button>
Expand Down
2 changes: 1 addition & 1 deletion components/date-picker/lib/abstract-panel-header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export abstract class AbstractPanelHeader implements OnInit, OnChanges {
}

ngOnChanges(changes: SimpleChanges): void {
if (changes.value) {
if (changes.value || changes.locale) {
this.render();
}
}
Expand Down
9 changes: 3 additions & 6 deletions components/date-picker/lib/date-header.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core';
import { PanelSelector } from './interface';

import { DateHelperByDatePipe, DateHelperService } from 'ng-zorro-antd/i18n';
import { DateHelperService } from 'ng-zorro-antd/i18n';
import { AbstractPanelHeader } from './abstract-panel-header';
import { transCompatFormat } from './util';

@Component({
encapsulation: ViewEncapsulation.None,
Expand All @@ -25,16 +26,12 @@ export class DateHeaderComponent extends AbstractPanelHeader {
}

getSelectors(): PanelSelector[] {
let yearFormat: string = this.locale.yearFormat;
if (this.dateHelper.relyOnDatePipe) {
yearFormat = (this.dateHelper as DateHelperByDatePipe).transCompatFormat(yearFormat);
}
return [
{
className: `${this.prefixCls}-year-btn`,
title: this.locale.yearSelect,
onClick: () => this.changeMode('year'),
label: this.dateHelper.format(this.value.nativeDate, yearFormat)
label: this.dateHelper.format(this.value.nativeDate, transCompatFormat(this.locale.yearFormat))
},
{
className: `${this.prefixCls}-month-btn`,
Expand Down
24 changes: 10 additions & 14 deletions components/date-picker/lib/date-table.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { CandyDate, valueFunctionProp } from 'ng-zorro-antd/core';
import { DateHelperService, NzCalendarI18nInterface, NzI18nService } from 'ng-zorro-antd/i18n';
import { AbstractTable } from './abstract-table';
import { DateBodyRow, DateCell, DayCell } from './interface';
import { transCompatFormat } from './util';

@Component({
encapsulation: ViewEncapsulation.None,
Expand Down Expand Up @@ -99,7 +100,7 @@ export class DateTableComponent extends AbstractTable implements OnChanges, OnIn
const day = start.addDays(colIndex);
weekDays.push({
value: day.nativeDate,
title: this.dateHelper.format(day.nativeDate, this.dateHelper.relyOnDatePipe ? 'E' : 'ddd'), // eg. Tue
title: this.dateHelper.format(day.nativeDate, 'E'), // eg. Tue
content: this.dateHelper.format(day.nativeDate, this.getVeryShortWeekFormat()), // eg. Tu,
isSelected: false,
isDisabled: false,
Expand All @@ -111,15 +112,12 @@ export class DateTableComponent extends AbstractTable implements OnChanges, OnIn
}

private getVeryShortWeekFormat(): string {
if (this.dateHelper.relyOnDatePipe) {
return this.i18n
.getLocaleId()
.toLowerCase()
.indexOf('zh') === 0
? 'EEEEE'
: 'EEEEEE'; // Use extreme short for chinese
}
return 'dd';
return this.i18n
.getLocaleId()
.toLowerCase()
.indexOf('zh') === 0
? 'EEEEE'
: 'EEEEEE'; // Use extreme short for chinese
}

makeBodyRows(): DateBodyRow[] {
Expand All @@ -137,11 +135,9 @@ export class DateTableComponent extends AbstractTable implements OnChanges, OnIn

for (let day = 0; day < 7; day++) {
const date = weekStart.addDays(day);
const dateFormat = this.dateHelper.relyOnDatePipe
? 'longDate'
: this.i18n.getLocaleData('DatePicker.lang.dateFormat', 'YYYY-MM-DD');
const dateFormat = transCompatFormat(this.i18n.getLocaleData('DatePicker.lang.dateFormat', 'YYYY-MM-DD'));
const title = this.dateHelper.format(date.nativeDate, dateFormat);
const label = this.dateHelper.format(date.nativeDate, this.dateHelper.relyOnDatePipe ? 'dd' : 'DD');
const label = this.dateHelper.format(date.nativeDate, 'dd');

const cell: DayCell = {
value: date.nativeDate,
Expand Down
4 changes: 3 additions & 1 deletion components/date-picker/lib/decade-header.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ export class DecadeHeaderComponent extends AbstractPanelHeader {
{
className: `${this.prefixCls}-decade-btn`,
title: '',
onClick: () => null,
onClick: () => {
// noop
},
label: `${this.startYear}-${this.endYear}`
}
];
Expand Down
Loading

0 comments on commit 6a523ba

Please sign in to comment.