Skip to content

Commit

Permalink
refactor(module:notification,message): refactor (#2613)
Browse files Browse the repository at this point in the history
* refactor(module:notification,message): refactor

* feat(module:notification): support update by key

* docs: update notification docs

* fix: fix lint
  • Loading branch information
Wendell authored and hsuanxyz committed Dec 12, 2018
1 parent 4bab06a commit 82ac7c5
Show file tree
Hide file tree
Showing 11 changed files with 132 additions and 42 deletions.
16 changes: 12 additions & 4 deletions components/message/nz-message-container.component.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Component, Inject, Optional } from '@angular/core';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Optional, ViewEncapsulation } from '@angular/core';

import { NzMessageConfig, NZ_MESSAGE_CONFIG, NZ_MESSAGE_DEFAULT_CONFIG } from './nz-message-config';
import { NzMessageDataFilled, NzMessageDataOptions } from './nz-message.definitions';

@Component({
changeDetection : ChangeDetectionStrategy.OnPush,
encapsulation : ViewEncapsulation.None,
selector : 'nz-message-container',
preserveWhitespaces: false,
templateUrl : './nz-message-container.component.html'
Expand All @@ -12,8 +14,11 @@ export class NzMessageContainerComponent {
messages: NzMessageDataFilled[] = [];
config: NzMessageConfig = {};

constructor(@Optional() @Inject(NZ_MESSAGE_DEFAULT_CONFIG) defaultConfig: NzMessageConfig,
@Optional() @Inject(NZ_MESSAGE_CONFIG) config: NzMessageConfig) {
constructor(
protected cdr: ChangeDetectorRef,
@Optional() @Inject(NZ_MESSAGE_DEFAULT_CONFIG) defaultConfig: NzMessageConfig,
@Optional() @Inject(NZ_MESSAGE_CONFIG) config: NzMessageConfig
) {
this.setConfig({ ...defaultConfig, ...config });
}

Expand All @@ -28,13 +33,15 @@ export class NzMessageContainerComponent {
}
message.options = this._mergeMessageOptions(message.options);
this.messages.push(message);
this.cdr.detectChanges();
}

// Remove a message by messageId
removeMessage(messageId: string): void {
this.messages.some((message, index) => {
if (message.messageId === messageId) {
this.messages.splice(index, 1);
this.cdr.detectChanges();
return true;
}
});
Expand All @@ -43,9 +50,10 @@ export class NzMessageContainerComponent {
// Remove all messages
removeMessageAll(): void {
this.messages = [];
this.cdr.detectChanges();
}

// Merge default options and cutom message options
// Merge default options and custom message options
protected _mergeMessageOptions(options: NzMessageDataOptions): NzMessageDataOptions {
const defaultOptions: NzMessageDataOptions = {
nzDuration : this.config.nzDuration,
Expand Down
26 changes: 11 additions & 15 deletions components/message/nz-message.component.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import {
animate,
state,
style,
transition,
trigger
} from '@angular/animations';
import {
Component,
Input,
OnDestroy,
OnInit
} from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';

import { NzMessageContainerComponent } from './nz-message-container.component';
import { NzMessageDataFilled, NzMessageDataOptions } from './nz-message.definitions';

@Component({
changeDetection : ChangeDetectionStrategy.OnPush,
encapsulation : ViewEncapsulation.None,
selector : 'nz-message',
preserveWhitespaces: false,
animations : [
Expand All @@ -32,7 +23,7 @@ import { NzMessageDataFilled, NzMessageDataOptions } from './nz-message.definiti
])
])
],
templateUrl : './nz-message.component.html'
templateUrl : './nz-message.component.html'
})
export class NzMessageComponent implements OnInit, OnDestroy {

Expand All @@ -47,7 +38,10 @@ export class NzMessageComponent implements OnInit, OnDestroy {
private _eraseTimingStart: number;
private _eraseTTL: number; // Time to live

constructor(private _messageContainer: NzMessageContainerComponent) {
constructor(
private _messageContainer: NzMessageContainerComponent,
protected cdr: ChangeDetectorRef
) {
}

ngOnInit(): void {
Expand Down Expand Up @@ -88,6 +82,7 @@ export class NzMessageComponent implements OnInit, OnDestroy {
protected _destroy(): void {
if (this._options.nzAnimate) {
this.nzMessage.state = 'leave';
this.cdr.detectChanges();
setTimeout(() => this._messageContainer.removeMessage(this.nzMessage.messageId), 200);
} else {
this._messageContainer.removeMessage(this.nzMessage.messageId);
Expand All @@ -108,6 +103,7 @@ export class NzMessageComponent implements OnInit, OnDestroy {
private _startEraseTimeout(): void {
if (this._eraseTTL > 0) {
this._clearEraseTimeout(); // To prevent calling _startEraseTimeout() more times to create more timer
// TODO: `window` should be removed in milestone II
this._eraseTimer = window.setTimeout(() => this._destroy(), this._eraseTTL);
this._eraseTimingStart = Date.now();
} else {
Expand Down
15 changes: 15 additions & 0 deletions components/notification/demo/update.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
order: 7
title:
zh-CN: 更新消息内容
en-US: Update Notification Content
---

## zh-CN

可以通过唯一的 `nzKey` 来更新内容。

## en-US

Update content with unique `nzKey`.

28 changes: 28 additions & 0 deletions components/notification/demo/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Component } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';

@Component({
selector: 'nz-demo-notification-update',
template: `
<button nz-button [nzType]="'primary'" (click)="createAutoUpdatingNotifications()">Open the notification box</button>
`,
styles : []
})
export class NzDemoNotificationUpdateComponent {

constructor(private notification: NzNotificationService) {
}

createAutoUpdatingNotifications(): void {
this.notification.blank('Notification Title', 'Description.', {
nzKey: 'key'
}
);

setTimeout(() => {
this.notification.blank('New Title', 'New description', {
nzKey: 'key'
});
}, 1000);
}
}
1 change: 1 addition & 0 deletions components/notification/doc/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ The parameters that are set by the `options` support are as follows:

| Argument | Description | Type |
| --- | --- | --- |
| nzKey | The unique identifier of the Notification | string |
| nzDuration | Duration (milliseconds), does not disappear when set to 0 | number |
| nzPauseOnHover | Do not remove automatically when mouse is over while setting to `true` | boolean |
| nzAnimate | Whether to turn on animation | boolean |
Expand Down
3 changes: 2 additions & 1 deletion components/notification/doc/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ subtitle: 通知提醒框

| 参数 | 说明 | 类型 |
| --- | --- | --- |
| nzDuration | 持续时间(毫秒),当设置为0时不消失 | number |
| nzKey | 通知提示的唯一标识符 | string |
| nzDuration | 持续时间(毫秒),当设置为 0 时不消失 | number |
| nzPauseOnHover | 鼠标移上时禁止自动移除 | boolean |
| nzAnimate | 开关动画效果 | boolean |
| nzStyle | 自定义内联样式 | object |
Expand Down
47 changes: 42 additions & 5 deletions components/notification/nz-notification-container.component.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,56 @@
import { Component, Inject, Optional } from '@angular/core';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Optional, ViewEncapsulation } from '@angular/core';

import { NzMessageContainerComponent } from '../message/nz-message-container.component';

import { NzNotificationConfig, NZ_NOTIFICATION_CONFIG, NZ_NOTIFICATION_DEFAULT_CONFIG } from './nz-notification-config';
import { NzNotificationDataFilled } from './nz-notification.definitions';

@Component({
changeDetection : ChangeDetectionStrategy.OnPush,
encapsulation : ViewEncapsulation.None,
selector : 'nz-notification-container',
preserveWhitespaces: false,
templateUrl : './nz-notification-container.component.html'
})
export class NzNotificationContainerComponent extends NzMessageContainerComponent {
constructor(
cdr: ChangeDetectorRef,
@Optional() @Inject(NZ_NOTIFICATION_DEFAULT_CONFIG) defaultConfig: NzNotificationConfig,
@Optional() @Inject(NZ_NOTIFICATION_CONFIG) config: NzNotificationConfig
) {
super(cdr, defaultConfig, config);
}

constructor(@Optional() @Inject(NZ_NOTIFICATION_DEFAULT_CONFIG) defaultConfig: NzNotificationConfig,
@Optional() @Inject(NZ_NOTIFICATION_CONFIG) config: NzNotificationConfig) {
super(defaultConfig, config);
/**
* A list of notifications displayed on the screen.
* @override
*/
messages: NzNotificationDataFilled[] = [];

/**
* Create a new notification.
* If there's a notification whose `nzKey` is same with `nzKey` in `NzNotificationDataFilled`, replace its content instead of create a new one.
* @override
* @param notification
*/
createMessage(notification: NzNotificationDataFilled): void {
notification.options = this._mergeMessageOptions(notification.options);
const key = notification.options.nzKey;
const notificationWithSameKey = this.messages.find(msg => msg.options.nzKey === notification.options.nzKey);
if (key && notificationWithSameKey) {
this.replaceNotification(notificationWithSameKey, notification);
} else {
if (this.messages.length >= this.config.nzMaxStack) {
this.messages.splice(0, 1);
}
this.messages.push(notification);
}
this.cdr.detectChanges();
}

private replaceNotification(old: NzNotificationDataFilled, _new: NzNotificationDataFilled): void {
old.title = _new.title;
old.content = _new.content;
old.template = _new.template;
old.type = _new.type;
}
}
18 changes: 6 additions & 12 deletions components/notification/nz-notification.component.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import {
animate,
state,
style,
transition,
trigger
} from '@angular/animations';
import { Component, Input } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, Input, ViewEncapsulation } from '@angular/core';

import { NzMessageComponent } from '../message/nz-message.component';

import { NzNotificationContainerComponent } from './nz-notification-container.component';
import { NzNotificationDataFilled } from './nz-notification.definitions';

@Component({
encapsulation : ViewEncapsulation.None,
selector : 'nz-notification',
preserveWhitespaces: false,
animations : [
Expand Down Expand Up @@ -42,13 +37,13 @@ import { NzNotificationDataFilled } from './nz-notification.definitions';
])
])
],
templateUrl : './nz-notification.component.html'
templateUrl : './nz-notification.component.html'
})
export class NzNotificationComponent extends NzMessageComponent {
@Input() nzMessage: NzNotificationDataFilled;

constructor(private container: NzNotificationContainerComponent) {
super(container);
constructor(private container: NzNotificationContainerComponent, protected cdr: ChangeDetectorRef) {
super(container, cdr);
}

close(): void {
Expand All @@ -65,6 +60,5 @@ export class NzNotificationComponent extends NzMessageComponent {
} else {
return this.nzMessage.state;
}

}
}
1 change: 1 addition & 0 deletions components/notification/nz-notification.definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface NzNotificationData extends NzMessageData {
}

export interface NzNotificationDataOptions extends NzMessageDataOptions {
nzKey?: string;
/* tslint:disable-next-line:no-any */
nzStyle?: any;
/* tslint:disable-next-line:no-any */
Expand Down
4 changes: 2 additions & 2 deletions components/notification/nz-notification.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export class NzNotificationService extends NzMessageBaseService<NzNotificationCo
overlay: Overlay,
injector: Injector,
cfr: ComponentFactoryResolver,
appRef: ApplicationRef) {

appRef: ApplicationRef
) {
super(overlay, NzNotificationContainerComponent, injector, cfr, appRef, 'notification-');
}

Expand Down
15 changes: 12 additions & 3 deletions components/notification/nz-notification.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import { OverlayContainer } from '@angular/cdk/overlay';
import { Component, TemplateRef, ViewChild } from '@angular/core';
import { fakeAsync, flush, flushMicrotasks, inject, tick, ComponentFixture, TestBed } from '@angular/core/testing';
Expand All @@ -18,9 +17,9 @@ describe('NzNotification', () => {

beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [ NzNotificationModule, NoopAnimationsModule ],
imports : [ NzNotificationModule, NoopAnimationsModule ],
declarations: [ DemoAppComponent ],
providers: [ { provide: NZ_NOTIFICATION_CONFIG, useValue: { nzMaxStack: 2 } } ] // Override default config
providers : [ { provide: NZ_NOTIFICATION_CONFIG, useValue: { nzMaxStack: 2 } } ] // Override default config
});

TestBed.compileComponents();
Expand Down Expand Up @@ -165,6 +164,16 @@ describe('NzNotification', () => {
demoAppFixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('test template content');
});

it('should update an existing notification when keys are matched', () => {
messageService.create(null, null, 'EXISTS', { nzKey: 'exists' });
expect(overlayContainerElement.textContent).toContain('EXISTS');
messageService.create('success', 'Title', 'SHOULD NOT CHANGE', { nzKey: 'exists' });
expect(overlayContainerElement.textContent).not.toContain('EXISTS');
expect(overlayContainerElement.textContent).toContain('Title');
expect(overlayContainerElement.textContent).toContain('SHOULD NOT CHANGE');
expect(overlayContainerElement.querySelector('.ant-notification-notice-icon-success')).not.toBeNull();
});
});

@Component({
Expand Down

0 comments on commit 82ac7c5

Please sign in to comment.