/
base.ts
501 lines (415 loc) · 14.5 KB
/
base.ts
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import { Direction, Directionality } from '@angular/cdk/bidi';
import { CdkConnectedOverlay, ConnectedOverlayPositionChange, ConnectionPositionPair } from '@angular/cdk/overlay';
import {
AfterViewInit,
ChangeDetectorRef,
ComponentFactoryResolver,
ComponentRef,
Directive,
ElementRef,
EventEmitter,
OnChanges,
OnDestroy,
OnInit,
Optional,
Renderer2,
SimpleChanges,
TemplateRef,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { asapScheduler, Subject } from 'rxjs';
import { delay, distinctUntilChanged, filter, takeUntil } from 'rxjs/operators';
import { NzConfigService, PopConfirmConfig, PopoverConfig } from 'ng-zorro-antd/core/config';
import { NzNoAnimationDirective } from 'ng-zorro-antd/core/no-animation';
import { DEFAULT_TOOLTIP_POSITIONS, getPlacementName, POSITION_MAP, POSITION_TYPE } from 'ng-zorro-antd/core/overlay';
import { BooleanInput, NgClassInterface, NgStyleInterface, NzSafeAny, NzTSType } from 'ng-zorro-antd/core/types';
import { isNotNil, toBoolean } from 'ng-zorro-antd/core/util';
export interface PropertyMapping {
[key: string]: [string, () => unknown];
}
export type NzTooltipTrigger = 'click' | 'focus' | 'hover' | null;
@Directive()
export abstract class NzTooltipBaseDirective implements OnChanges, OnDestroy, AfterViewInit {
arrowPointAtCenter?: boolean;
config?: Required<PopoverConfig | PopConfirmConfig>;
directiveTitle?: NzTSType | null;
directiveContent?: NzTSType | null;
title?: NzTSType | null;
content?: NzTSType | null;
trigger?: NzTooltipTrigger;
placement?: string | string[];
origin?: ElementRef<HTMLElement>;
visible?: boolean;
mouseEnterDelay?: number;
mouseLeaveDelay?: number;
overlayClassName?: string;
overlayStyle?: NgStyleInterface;
visibleChange = new EventEmitter<boolean>();
/**
* For create tooltip dynamically. This should be override for each different component.
*/
protected componentRef!: ComponentRef<NzTooltipBaseComponent>;
/**
* This true title that would be used in other parts on this component.
*/
protected get _title(): NzTSType | null {
return this.title || this.directiveTitle || null;
}
protected get _content(): NzTSType | null {
return this.content || this.directiveContent || null;
}
protected get _trigger(): NzTooltipTrigger {
return typeof this.trigger !== 'undefined' ? this.trigger : 'hover';
}
protected get _placement(): string[] {
const p = this.placement;
return Array.isArray(p) && p.length > 0 ? p : typeof p === 'string' && p ? [p] : ['top'];
}
protected get _visible(): boolean {
return (typeof this.visible !== 'undefined' ? this.visible : this.internalVisible) || false;
}
protected get _mouseEnterDelay(): number {
return this.mouseEnterDelay || 0.15;
}
protected get _mouseLeaveDelay(): number {
return this.mouseLeaveDelay || 0.1;
}
protected get _overlayClassName(): string | null {
return this.overlayClassName || null;
}
protected get _overlayStyle(): NgStyleInterface | null {
return this.overlayStyle || null;
}
private internalVisible = false;
protected getProxyPropertyMap(): PropertyMapping {
return {
noAnimation: ['noAnimation', () => !!this.noAnimation]
};
}
component?: NzTooltipBaseComponent;
protected readonly destroy$ = new Subject<void>();
protected readonly triggerDisposables: Array<() => void> = [];
private delayTimer?: number;
constructor(
public elementRef: ElementRef,
protected hostView: ViewContainerRef,
protected resolver: ComponentFactoryResolver,
protected renderer: Renderer2,
protected noAnimation?: NzNoAnimationDirective,
protected nzConfigService?: NzConfigService
) {}
ngOnChanges(changes: SimpleChanges): void {
const { trigger } = changes;
if (trigger && !trigger.isFirstChange()) {
this.registerTriggers();
}
if (this.component) {
this.updatePropertiesByChanges(changes);
}
}
ngAfterViewInit(): void {
this.createComponent();
this.registerTriggers();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
// Clear toggling timer. Issue #3875 #4317 #4386
this.clearTogglingTimer();
this.removeTriggerListeners();
}
show(): void {
this.component?.show();
}
hide(): void {
this.component?.hide();
}
/**
* Force the component to update its position.
*/
updatePosition(): void {
if (this.component) {
this.component.updatePosition();
}
}
/**
* Create a dynamic tooltip component. This method can be override.
*/
protected createComponent(): void {
const componentRef = this.componentRef;
this.component = componentRef.instance as NzTooltipBaseComponent;
// Remove the component's DOM because it should be in the overlay container.
this.renderer.removeChild(
this.renderer.parentNode(this.elementRef.nativeElement),
componentRef.location.nativeElement
);
this.component.setOverlayOrigin(this.origin || this.elementRef);
this.initProperties();
const ngVisibleChange$ = this.component.nzVisibleChange.pipe(distinctUntilChanged());
ngVisibleChange$.pipe(takeUntil(this.destroy$)).subscribe((visible: boolean) => {
this.internalVisible = visible;
this.visibleChange.emit(visible);
});
// In some cases, the rendering takes into account the height at which the `arrow` is in wrong place,
// so `cdk` sets the container position incorrectly.
// To avoid this, after placing the `arrow` in the correct position, we should `re-calculate` the position of the `overlay`.
ngVisibleChange$
.pipe(
filter((visible: boolean) => visible),
delay(0, asapScheduler),
filter(() => Boolean(this.component?.overlay?.overlayRef)),
takeUntil(this.destroy$)
)
.subscribe(() => {
this.component?.updatePosition();
});
}
protected registerTriggers(): void {
// When the method gets invoked, all properties has been synced to the dynamic component.
// After removing the old API, we can just check the directive's own `nzTrigger`.
const el = this.elementRef.nativeElement;
const trigger = this.trigger;
this.removeTriggerListeners();
if (trigger === 'hover') {
let overlayElement: HTMLElement;
this.triggerDisposables.push(
this.renderer.listen(el, 'mouseenter', () => {
this.delayEnterLeave(true, true, this._mouseEnterDelay);
})
);
this.triggerDisposables.push(
this.renderer.listen(el, 'mouseleave', () => {
this.delayEnterLeave(true, false, this._mouseLeaveDelay);
if (this.component?.overlay.overlayRef && !overlayElement) {
overlayElement = this.component.overlay.overlayRef.overlayElement;
this.triggerDisposables.push(
this.renderer.listen(overlayElement, 'mouseenter', () => {
this.delayEnterLeave(false, true, this._mouseEnterDelay);
})
);
this.triggerDisposables.push(
this.renderer.listen(overlayElement, 'mouseleave', () => {
this.delayEnterLeave(false, false, this._mouseLeaveDelay);
})
);
}
})
);
} else if (trigger === 'focus') {
this.triggerDisposables.push(this.renderer.listen(el, 'focusin', () => this.show()));
this.triggerDisposables.push(this.renderer.listen(el, 'focusout', () => this.hide()));
} else if (trigger === 'click') {
this.triggerDisposables.push(
this.renderer.listen(el, 'click', (e: MouseEvent) => {
e.preventDefault();
this.show();
})
);
}
// Else do nothing because user wants to control the visibility programmatically.
}
private updatePropertiesByChanges(changes: SimpleChanges): void {
this.updatePropertiesByKeys(Object.keys(changes));
}
private updatePropertiesByKeys(keys?: string[]): void {
const mappingProperties: PropertyMapping = {
// common mappings
title: ['nzTitle', () => this._title],
directiveTitle: ['nzTitle', () => this._title],
content: ['nzContent', () => this._content],
directiveContent: ['nzContent', () => this._content],
trigger: ['nzTrigger', () => this._trigger],
placement: ['nzPlacement', () => this._placement],
visible: ['nzVisible', () => this._visible],
mouseEnterDelay: ['nzMouseEnterDelay', () => this._mouseEnterDelay],
mouseLeaveDelay: ['nzMouseLeaveDelay', () => this._mouseLeaveDelay],
overlayClassName: ['nzOverlayClassName', () => this._overlayClassName],
overlayStyle: ['nzOverlayStyle', () => this._overlayStyle],
arrowPointAtCenter: ['nzArrowPointAtCenter', () => this.arrowPointAtCenter],
...this.getProxyPropertyMap()
};
(keys || Object.keys(mappingProperties).filter(key => !key.startsWith('directive'))).forEach(
(property: NzSafeAny) => {
if (mappingProperties[property]) {
const [name, valueFn] = mappingProperties[property];
this.updateComponentValue(name, valueFn());
}
}
);
this.component?.updateByDirective();
}
private initProperties(): void {
this.updatePropertiesByKeys();
}
private updateComponentValue(key: string, value: NzSafeAny): void {
if (typeof value !== 'undefined') {
// @ts-ignore
this.component[key] = value;
}
}
private delayEnterLeave(isOrigin: boolean, isEnter: boolean, delay: number = -1): void {
if (this.delayTimer) {
this.clearTogglingTimer();
} else if (delay > 0) {
this.delayTimer = setTimeout(() => {
this.delayTimer = undefined;
isEnter ? this.show() : this.hide();
}, delay * 1000);
} else {
// `isOrigin` is used due to the tooltip will not hide immediately
// (may caused by the fade-out animation).
isEnter && isOrigin ? this.show() : this.hide();
}
}
private removeTriggerListeners(): void {
this.triggerDisposables.forEach(dispose => dispose());
this.triggerDisposables.length = 0;
}
private clearTogglingTimer(): void {
if (this.delayTimer) {
clearTimeout(this.delayTimer);
this.delayTimer = undefined;
}
}
}
@Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix
export abstract class NzTooltipBaseComponent implements OnDestroy, OnInit {
static ngAcceptInputType_nzVisible: BooleanInput;
static ngAcceptInputType_nzArrowPointAtCenter: BooleanInput;
@ViewChild('overlay', { static: false }) overlay!: CdkConnectedOverlay;
nzTitle: NzTSType | null = null;
nzContent: NzTSType | null = null;
nzArrowPointAtCenter: boolean = false;
nzOverlayClassName!: string;
nzOverlayStyle: NgStyleInterface = {};
nzBackdrop = false;
nzMouseEnterDelay?: number;
nzMouseLeaveDelay?: number;
nzVisibleChange = new Subject<boolean>();
set nzVisible(value: boolean) {
const visible = toBoolean(value);
if (this._visible !== visible) {
this._visible = visible;
this.nzVisibleChange.next(visible);
}
}
get nzVisible(): boolean {
return this._visible;
}
_visible = false;
set nzTrigger(value: NzTooltipTrigger) {
this._trigger = value;
}
get nzTrigger(): NzTooltipTrigger {
return this._trigger;
}
protected _trigger: NzTooltipTrigger = 'hover';
set nzPlacement(value: POSITION_TYPE[]) {
const preferredPosition = value.map(placement => POSITION_MAP[placement]);
this._positions = [...preferredPosition, ...DEFAULT_TOOLTIP_POSITIONS];
}
preferredPlacement: string = 'top';
origin!: ElementRef<NzSafeAny>;
public dir: Direction = 'ltr';
_classMap: NgClassInterface = {};
_prefix = 'ant-tooltip';
_positions: ConnectionPositionPair[] = [...DEFAULT_TOOLTIP_POSITIONS];
protected destroy$ = new Subject<void>();
constructor(
public cdr: ChangeDetectorRef,
@Optional() private directionality: Directionality,
public noAnimation?: NzNoAnimationDirective
) {}
ngOnInit(): void {
this.directionality.change?.pipe(takeUntil(this.destroy$)).subscribe((direction: Direction) => {
this.dir = direction;
this.cdr.detectChanges();
});
this.dir = this.directionality.value;
}
ngOnDestroy(): void {
this.nzVisibleChange.complete();
this.destroy$.next();
this.destroy$.complete();
}
show(): void {
if (this.nzVisible) {
return;
}
if (!this.isEmpty()) {
this.nzVisible = true;
this.nzVisibleChange.next(true);
this.cdr.detectChanges();
}
// for ltr for overlay to display tooltip in correct placement in rtl direction.
if (this.origin && this.overlay && this.overlay.overlayRef && this.overlay.overlayRef.getDirection() === 'rtl') {
this.overlay.overlayRef.setDirection('ltr');
}
}
hide(): void {
if (!this.nzVisible) {
return;
}
this.nzVisible = false;
this.nzVisibleChange.next(false);
this.cdr.detectChanges();
}
updateByDirective(): void {
this.updateStyles();
this.cdr.detectChanges();
Promise.resolve().then(() => {
this.updatePosition();
this.updateVisibilityByTitle();
});
}
/**
* Force the component to update its position.
*/
updatePosition(): void {
if (this.origin && this.overlay && this.overlay.overlayRef) {
this.overlay.overlayRef.updatePosition();
}
}
onPositionChange(position: ConnectedOverlayPositionChange): void {
this.preferredPlacement = getPlacementName(position)!;
this.updateStyles();
// We have to trigger immediate change detection or the element would blink.
this.cdr.detectChanges();
}
setOverlayOrigin(origin: ElementRef<HTMLElement>): void {
this.origin = origin;
this.cdr.markForCheck();
}
onClickOutside(event: MouseEvent): void {
if (!this.origin.nativeElement.contains(event.target) && this.nzTrigger !== null) {
this.hide();
}
}
/**
* Hide the component while the content is empty.
*/
private updateVisibilityByTitle(): void {
if (this.isEmpty()) {
this.hide();
}
}
protected updateStyles(): void {
this._classMap = {
[this.nzOverlayClassName]: true,
[`${this._prefix}-placement-${this.preferredPlacement}`]: true
};
}
/**
* Empty component cannot be opened.
*/
protected abstract isEmpty(): boolean;
}
export function isTooltipEmpty(value: string | TemplateRef<void> | null): boolean {
return value instanceof TemplateRef ? false : value === '' || !isNotNil(value);
}