-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
tooltip.ts
528 lines (447 loc) · 17.2 KB
/
tooltip.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/**
* @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 {
Component,
Directive,
Input,
ElementRef,
ViewContainerRef,
NgZone,
Optional,
OnDestroy,
Renderer2,
ChangeDetectorRef,
ViewEncapsulation,
} from '@angular/core';
import {
style,
trigger,
state,
transition,
animate,
AnimationEvent,
} from '@angular/animations';
import {
Overlay,
OverlayState,
OverlayRef,
ComponentPortal,
OverlayConnectionPosition,
OriginConnectionPosition,
} from '../core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {Directionality} from '../core/bidi/index';
import {Platform} from '../core/platform/index';
import {first} from '../core/rxjs/index';
import {ScrollDispatcher} from '../core/overlay/scroll/scroll-dispatcher';
import {coerceBooleanProperty} from '@angular/cdk';
export type TooltipPosition = 'left' | 'right' | 'above' | 'below' | 'before' | 'after';
/** Time in ms to delay before changing the tooltip visibility to hidden */
export const TOUCHEND_HIDE_DELAY = 1500;
/** Time in ms to throttle repositioning after scroll events. */
export const SCROLL_THROTTLE_MS = 20;
/** Creates an error to be thrown if the user supplied an invalid tooltip position. */
export function getMdTooltipInvalidPositionError(position: string) {
return Error(`Tooltip position "${position}" is invalid.`);
}
/**
* Directive that attaches a material design tooltip to the host element. Animates the showing and
* hiding of a tooltip provided position (defaults to below the element).
*
* https://material.google.com/components/tooltips.html
*/
@Directive({
selector: '[md-tooltip], [mdTooltip], [mat-tooltip], [matTooltip]',
host: {
'(longpress)': 'show()',
'(touchend)': 'hide(' + TOUCHEND_HIDE_DELAY + ')',
},
exportAs: 'mdTooltip',
})
export class MdTooltip implements OnDestroy {
_overlayRef: OverlayRef | null;
_tooltipInstance: TooltipComponent | null;
private _position: TooltipPosition = 'below';
private _disabled: boolean = false;
private _tooltipClass: string|string[]|Set<string>|{[key: string]: any};
/** Allows the user to define the position of the tooltip relative to the parent element */
@Input('mdTooltipPosition')
get position(): TooltipPosition { return this._position; }
set position(value: TooltipPosition) {
if (value !== this._position) {
this._position = value;
// TODO(andrewjs): When the overlay's position can be dynamically changed, do not destroy
// the tooltip.
if (this._tooltipInstance) {
this._disposeTooltip();
}
}
}
/** Disables the display of the tooltip. */
@Input('mdTooltipDisabled')
get disabled(): boolean { return this._disabled; }
set disabled(value) {
this._disabled = coerceBooleanProperty(value);
// If tooltip is disabled, hide immediately.
if (this._disabled) {
this.hide(0);
}
}
/** @deprecated */
@Input('tooltip-position')
get _positionDeprecated(): TooltipPosition { return this._position; }
set _positionDeprecated(value: TooltipPosition) { this._position = value; }
/** The default delay in ms before showing the tooltip after show is called */
@Input('mdTooltipShowDelay') showDelay = 0;
/** The default delay in ms before hiding the tooltip after hide is called */
@Input('mdTooltipHideDelay') hideDelay = 0;
private _message: string;
/** The message to be displayed in the tooltip */
@Input('mdTooltip') get message() { return this._message; }
set message(value: string) {
this._message = value;
this._setTooltipMessage(this._message);
}
/** Classes to be passed to the tooltip. Supports the same syntax as `ngClass`. */
@Input('mdTooltipClass')
get tooltipClass() { return this._tooltipClass; }
set tooltipClass(value: string|string[]|Set<string>|{[key: string]: any}) {
this._tooltipClass = value;
if (this._tooltipInstance) {
this._setTooltipClass(this._tooltipClass);
}
}
/** @deprecated */
@Input('md-tooltip')
get _deprecatedMessage(): string { return this.message; }
set _deprecatedMessage(v: string) { this.message = v; }
// Properties with `mat-` prefix for noconflict mode.
@Input('matTooltip')
get _matMessage() { return this.message; }
set _matMessage(v) { this.message = v; }
// Properties with `mat-` prefix for noconflict mode.
@Input('matTooltipPosition')
get _matPosition() { return this.position; }
set _matPosition(v) { this.position = v; }
// Properties with `mat-` prefix for noconflict mode.
@Input('matTooltipDisabled')
get _matDisabled() { return this.disabled; }
set _matDisabled(v) { this.disabled = v; }
// Properties with `mat-` prefix for noconflict mode.
@Input('matTooltipHideDelay')
get _matHideDelay() { return this.hideDelay; }
set _matHideDelay(v) { this.hideDelay = v; }
// Properties with `mat-` prefix for noconflict mode.
@Input('matTooltipShowDelay')
get _matShowDelay() { return this.showDelay; }
set _matShowDelay(v) { this.showDelay = v; }
// Properties with `mat-` prefix for nonconflict mode.
@Input('matTooltipClass')
get _matClass() { return this.tooltipClass; }
set _matClass(v) { this.tooltipClass = v; }
private _enterListener: Function;
private _leaveListener: Function;
constructor(
private _overlay: Overlay,
private _elementRef: ElementRef,
private _scrollDispatcher: ScrollDispatcher,
private _viewContainerRef: ViewContainerRef,
private _ngZone: NgZone,
private _renderer: Renderer2,
private _platform: Platform,
@Optional() private _dir: Directionality) {
// The mouse events shouldn't be bound on iOS devices, because
// they can prevent the first tap from firing its click event.
if (!_platform.IOS) {
this._enterListener =
_renderer.listen(_elementRef.nativeElement, 'mouseenter', () => this.show());
this._leaveListener =
_renderer.listen(_elementRef.nativeElement, 'mouseleave', () => this.hide());
}
}
/**
* Dispose the tooltip when destroyed.
*/
ngOnDestroy() {
if (this._tooltipInstance) {
this._disposeTooltip();
}
// Clean up the event listeners set in the constructor
if (!this._platform.IOS) {
this._enterListener();
this._leaveListener();
}
}
/** Shows the tooltip after the delay in ms, defaults to tooltip-delay-show or 0ms if no input */
show(delay: number = this.showDelay): void {
if (this.disabled || !this._message || !this._message.trim()) { return; }
if (!this._tooltipInstance) {
this._createTooltip();
}
this._setTooltipClass(this._tooltipClass);
this._setTooltipMessage(this._message);
this._tooltipInstance!.show(this._position, delay);
}
/** Hides the tooltip after the delay in ms, defaults to tooltip-delay-hide or 0ms if no input */
hide(delay: number = this.hideDelay): void {
if (this._tooltipInstance) {
this._tooltipInstance.hide(delay);
}
}
/** Shows/hides the tooltip */
toggle(): void {
this._isTooltipVisible() ? this.hide() : this.show();
}
/** Returns true if the tooltip is currently visible to the user */
_isTooltipVisible(): boolean {
return !!this._tooltipInstance && this._tooltipInstance.isVisible();
}
/** Create the tooltip to display */
private _createTooltip(): void {
let overlayRef = this._createOverlay();
let portal = new ComponentPortal(TooltipComponent, this._viewContainerRef);
this._tooltipInstance = overlayRef.attach(portal).instance;
// Dispose the overlay when finished the shown tooltip.
this._tooltipInstance!.afterHidden().subscribe(() => {
// Check first if the tooltip has already been removed through this components destroy.
if (this._tooltipInstance) {
this._disposeTooltip();
}
});
}
/** Create the overlay config and position strategy */
private _createOverlay(): OverlayRef {
let origin = this._getOrigin();
let position = this._getOverlayPosition();
// Create connected position strategy that listens for scroll events to reposition.
// After position changes occur and the overlay is clipped by a parent scrollable then
// close the tooltip.
let strategy = this._overlay.position().connectedTo(this._elementRef, origin, position);
strategy.withScrollableContainers(this._scrollDispatcher.getScrollContainers(this._elementRef));
strategy.onPositionChange.subscribe(change => {
if (change.scrollableViewProperties.isOverlayClipped &&
this._tooltipInstance && this._tooltipInstance.isVisible()) {
this.hide(0);
}
});
let config = new OverlayState();
config.direction = this._dir ? this._dir.value : 'ltr';
config.positionStrategy = strategy;
config.scrollStrategy = this._overlay.scrollStrategies.reposition({
scrollThrottle: SCROLL_THROTTLE_MS
});
this._overlayRef = this._overlay.create(config);
return this._overlayRef;
}
/** Disposes the current tooltip and the overlay it is attached to */
private _disposeTooltip(): void {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._tooltipInstance = null;
}
/** Returns the origin position based on the user's position preference */
_getOrigin(): OriginConnectionPosition {
if (this.position == 'above' || this.position == 'below') {
return {originX: 'center', originY: this.position == 'above' ? 'top' : 'bottom'};
}
const isDirectionLtr = !this._dir || this._dir.value == 'ltr';
if (this.position == 'left' ||
this.position == 'before' && isDirectionLtr ||
this.position == 'after' && !isDirectionLtr) {
return {originX: 'start', originY: 'center'};
}
if (this.position == 'right' ||
this.position == 'after' && isDirectionLtr ||
this.position == 'before' && !isDirectionLtr) {
return {originX: 'end', originY: 'center'};
}
throw getMdTooltipInvalidPositionError(this.position);
}
/** Returns the overlay position based on the user's preference */
_getOverlayPosition(): OverlayConnectionPosition {
if (this.position == 'above') {
return {overlayX: 'center', overlayY: 'bottom'};
}
if (this.position == 'below') {
return {overlayX: 'center', overlayY: 'top'};
}
const isLtr = !this._dir || this._dir.value == 'ltr';
if (this.position == 'left' ||
this.position == 'before' && isLtr ||
this.position == 'after' && !isLtr) {
return {overlayX: 'end', overlayY: 'center'};
}
if (this.position == 'right' ||
this.position == 'after' && isLtr ||
this.position == 'before' && !isLtr) {
return {overlayX: 'start', overlayY: 'center'};
}
throw getMdTooltipInvalidPositionError(this.position);
}
/** Updates the tooltip message and repositions the overlay according to the new message length */
private _setTooltipMessage(message: string) {
// Must wait for the message to be painted to the tooltip so that the overlay can properly
// calculate the correct positioning based on the size of the text.
if (this._tooltipInstance) {
this._tooltipInstance.message = message;
this._tooltipInstance._markForCheck();
first.call(this._ngZone.onMicrotaskEmpty).subscribe(() => {
if (this._tooltipInstance) {
this._overlayRef!.updatePosition();
}
});
}
}
/** Updates the tooltip class */
private _setTooltipClass(tooltipClass: string|string[]|Set<string>|{[key: string]: any}) {
if (this._tooltipInstance) {
this._tooltipInstance.tooltipClass = tooltipClass;
this._tooltipInstance._markForCheck();
}
}
}
export type TooltipVisibility = 'initial' | 'visible' | 'hidden';
/**
* Internal component that wraps the tooltip's content.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-tooltip-component, mat-tooltip-component',
templateUrl: 'tooltip.html',
styleUrls: ['tooltip.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('state', [
state('void', style({transform: 'scale(0)'})),
state('initial', style({transform: 'scale(0)'})),
state('visible', style({transform: 'scale(1)'})),
state('hidden', style({transform: 'scale(0)'})),
transition('* => visible', animate('150ms cubic-bezier(0.0, 0.0, 0.2, 1)')),
transition('* => hidden', animate('150ms cubic-bezier(0.4, 0.0, 1, 1)')),
])
],
host: {
// Forces the element to have a layout in IE and Edge. This fixes issues where the element
// won't be rendered if the animations are disabled or there is no web animations polyfill.
'[style.zoom]': '_visibility === "visible" ? 1 : null',
'(body:click)': 'this._handleBodyInteraction()'
}
})
export class TooltipComponent {
/** Message to display in the tooltip */
message: string;
/** Classes to be added to the tooltip. Supports the same syntax as `ngClass`. */
tooltipClass: string|string[]|Set<string>|{[key: string]: any};
/** The timeout ID of any current timer set to show the tooltip */
_showTimeoutId: number;
/** The timeout ID of any current timer set to hide the tooltip */
_hideTimeoutId: number;
/** Property watched by the animation framework to show or hide the tooltip */
_visibility: TooltipVisibility = 'initial';
/** Whether interactions on the page should close the tooltip */
_closeOnInteraction: boolean = false;
/** The transform origin used in the animation for showing and hiding the tooltip */
_transformOrigin: string = 'bottom';
/** Subject for notifying that the tooltip has been hidden from the view */
private _onHide: Subject<any> = new Subject();
constructor(@Optional() private _dir: Directionality,
private _changeDetectorRef: ChangeDetectorRef) {}
/**
* Shows the tooltip with an animation originating from the provided origin
* @param position Position of the tooltip.
* @param delay Amount of milliseconds to the delay showing the tooltip.
*/
show(position: TooltipPosition, delay: number): void {
// Cancel the delayed hide if it is scheduled
if (this._hideTimeoutId) {
clearTimeout(this._hideTimeoutId);
}
// Body interactions should cancel the tooltip if there is a delay in showing.
this._closeOnInteraction = true;
this._setTransformOrigin(position);
this._showTimeoutId = setTimeout(() => {
this._visibility = 'visible';
// If this was set to true immediately, then a body click that triggers show() would
// trigger interaction and close the tooltip right after it was displayed.
this._closeOnInteraction = false;
// Mark for check so if any parent component has set the
// ChangeDetectionStrategy to OnPush it will be checked anyways
this._markForCheck();
setTimeout(() => this._closeOnInteraction = true, 0);
}, delay);
}
/**
* Begins the animation to hide the tooltip after the provided delay in ms.
* @param delay Amount of milliseconds to delay showing the tooltip.
*/
hide(delay: number): void {
// Cancel the delayed show if it is scheduled
if (this._showTimeoutId) {
clearTimeout(this._showTimeoutId);
}
this._hideTimeoutId = setTimeout(() => {
this._visibility = 'hidden';
this._closeOnInteraction = false;
// Mark for check so if any parent component has set the
// ChangeDetectionStrategy to OnPush it will be checked anyways
this._markForCheck();
}, delay);
}
/**
* Returns an observable that notifies when the tooltip has been hidden from view
*/
afterHidden(): Observable<void> {
return this._onHide.asObservable();
}
/**
* Whether the tooltip is being displayed
*/
isVisible(): boolean {
return this._visibility === 'visible';
}
/** Sets the tooltip transform origin according to the tooltip position */
_setTransformOrigin(value: TooltipPosition) {
const isLtr = !this._dir || this._dir.value == 'ltr';
switch (value) {
case 'before': this._transformOrigin = isLtr ? 'right' : 'left'; break;
case 'after': this._transformOrigin = isLtr ? 'left' : 'right'; break;
case 'left': this._transformOrigin = 'right'; break;
case 'right': this._transformOrigin = 'left'; break;
case 'above': this._transformOrigin = 'bottom'; break;
case 'below': this._transformOrigin = 'top'; break;
default: throw getMdTooltipInvalidPositionError(value);
}
}
_afterVisibilityAnimation(e: AnimationEvent): void {
if (e.toState === 'hidden' && !this.isVisible()) {
this._onHide.next();
}
}
/**
* Interactions on the HTML body should close the tooltip immediately as defined in the
* material design spec.
* https://material.google.com/components/tooltips.html#tooltips-interaction
*/
_handleBodyInteraction(): void {
if (this._closeOnInteraction) {
this.hide(0);
}
}
/**
* Marks that the tooltip needs to be checked in the next change detection run.
* Mainly used for rendering the initial text before positioning a tooltip, which
* can be problematic in components with OnPush change detection.
*/
_markForCheck(): void {
this._changeDetectorRef.markForCheck();
}
}