-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtooltip.ts
More file actions
446 lines (381 loc) · 11.6 KB
/
tooltip.ts
File metadata and controls
446 lines (381 loc) · 11.6 KB
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
import { LitElement, html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { createRef, ref } from 'lit/directives/ref.js';
import { EaseOut } from '../../animations/easings.js';
import { addAnimationController } from '../../animations/player.js';
import { fadeOut } from '../../animations/presets/fade/index.js';
import { scaleInCenter } from '../../animations/presets/scale/index.js';
import { themes } from '../../theming/theming-decorator.js';
import { watch } from '../common/decorators/watch.js';
import { registerComponent } from '../common/definitions/register.js';
import type { Constructor } from '../common/mixins/constructor.js';
import { EventEmitterMixin } from '../common/mixins/event-emitter.js';
import { asNumber, isLTR } from '../common/util.js';
import IgcIconComponent from '../icon/icon.js';
import IgcPopoverComponent, {
type PopoverPlacement,
} from '../popover/popover.js';
import { TooltipRegexes, addTooltipController } from './controller.js';
import { styles as shared } from './themes/shared/tooltip.common.css.js';
import { all } from './themes/themes.js';
import { styles } from './themes/tooltip.base.css.js';
export interface IgcTooltipComponentEventMap {
igcOpening: CustomEvent<Element | null>;
igcOpened: CustomEvent<Element | null>;
igcClosing: CustomEvent<Element | null>;
igcClosed: CustomEvent<Element | null>;
}
type TooltipStateOptions = {
show: boolean;
withDelay?: boolean;
withEvents?: boolean;
};
/**
* Provides a way to display supplementary information related to an element when a user interacts with it (e.g., hover, focus).
* It offers features such as placement customization, delays, sticky mode, and animations.
*
* @element igc-tooltip
*
* @slot - Default slot of the tooltip component.
* @slot close-button - Slot for custom sticky-mode close action (e.g., an icon/button).
*
* @csspart base - The wrapping container of the tooltip content.
*
* @fires igcOpening - Emitted before the tooltip begins to open. Can be canceled to prevent opening.
* @fires igcOpened - Emitted after the tooltip has successfully opened and is visible.
* @fires igcClosing - Emitted before the tooltip begins to close. Can be canceled to prevent closing.
* @fires igcClosed - Emitted after the tooltip has been fully removed from view.
*/
@themes(all)
export default class IgcTooltipComponent extends EventEmitterMixin<
IgcTooltipComponentEventMap,
Constructor<LitElement>
>(LitElement) {
public static readonly tagName = 'igc-tooltip';
public static styles = [styles, shared];
/* blazorSuppress */
public static register(): void {
registerComponent(
IgcTooltipComponent,
IgcPopoverComponent,
IgcIconComponent
);
}
private readonly _internals: ElementInternals;
private readonly _controller = addTooltipController(this, {
onShow: this._showOnInteraction,
onHide: this._hideOnInteraction,
onEscape: this._hideOnEscape,
});
private readonly _containerRef = createRef<HTMLElement>();
private readonly _player = addAnimationController(this, this._containerRef);
private readonly _showAnimation = scaleInCenter({
duration: 150,
easing: EaseOut.Quad,
});
private readonly _hideAnimation = fadeOut({
duration: 75,
easing: EaseOut.Sine,
});
private _timeoutId?: number;
private _autoHideDelay = 180;
private _showDelay = 200;
private _hideDelay = 300;
@query('#arrow')
private _arrowElement!: HTMLElement;
private get _arrowOffset() {
if (this.placement.includes('-')) {
// Horizontal start | end placement
if (TooltipRegexes.horizontalStart.test(this.placement)) {
return -8;
}
if (TooltipRegexes.horizontalEnd.test(this.placement)) {
return 8;
}
// Vertical start | end placement
if (TooltipRegexes.start.test(this.placement)) {
return isLTR(this) ? -8 : 8;
}
if (TooltipRegexes.end.test(this.placement)) {
return isLTR(this) ? 8 : -8;
}
}
return 0;
}
/**
* Whether the tooltip is showing.
*
* @attr open
* @default false
*/
@property({ type: Boolean, reflect: true })
public set open(value: boolean) {
this._controller.open = value;
}
public get open(): boolean {
return this._controller.open;
}
/**
* Whether to disable the rendering of the arrow indicator for the tooltip.
*
* @attr disable-arrow
* @default false
*/
@property({ attribute: 'disable-arrow', type: Boolean, reflect: true })
public disableArrow = false;
/**
* The offset of the tooltip from the anchor in pixels.
*
* @attr offset
* @default 6
*/
@property({ type: Number })
public offset = 6;
/**
* Where to place the floating element relative to the parent anchor element.
*
* @attr placement
* @default top
*/
@property()
public placement: PopoverPlacement = 'top';
/**
* An element instance or an IDREF to use as the anchor for the tooltip.
*
* @attr anchor
*/
@property()
public anchor?: Element | string;
/**
* Which event triggers will show the tooltip.
* Expects a comma separate string of different event triggers.
*
* @attr show-triggers
* @default pointerenter
*/
@property({ attribute: 'show-triggers' })
public set showTriggers(value: string) {
this._controller.showTriggers = value;
}
public get showTriggers(): string {
return this._controller.showTriggers;
}
/**
* Which event triggers will hide the tooltip.
* Expects a comma separate string of different event triggers.
*
* @attr hide-triggers
* @default pointerleave, click
*/
@property({ attribute: 'hide-triggers' })
public set hideTriggers(value: string) {
this._controller.hideTriggers = value;
}
public get hideTriggers(): string {
return this._controller.hideTriggers;
}
/**
* Specifies the number of milliseconds that should pass before showing the tooltip.
*
* @attr show-delay
* @default 200
*/
@property({ attribute: 'show-delay', type: Number })
public set showDelay(value: number) {
this._showDelay = Math.max(0, asNumber(value));
}
public get showDelay(): number {
return this._showDelay;
}
/**
* Specifies the number of milliseconds that should pass before hiding the tooltip.
*
* @attr hide-delay
* @default 300
*/
@property({ attribute: 'hide-delay', type: Number })
public set hideDelay(value: number) {
this._hideDelay = Math.max(0, asNumber(value));
}
public get hideDelay(): number {
return this._hideDelay;
}
/**
* Specifies a plain text as tooltip content.
*
* @attr message
*/
@property()
public message = '';
/**
* Specifies if the tooltip remains visible until the user closes it via the close button or Esc key.
*
* @attr sticky
* @default false
*/
@property({ type: Boolean, reflect: true })
public sticky = false;
constructor() {
super();
this._internals = this.attachInternals();
this._internals.role = 'tooltip';
this._internals.ariaAtomic = 'true';
this._internals.ariaLive = 'polite';
}
protected override firstUpdated(): void {
if (this.open) {
this.updateComplete.then(() => {
this._player.playExclusive(this._showAnimation);
this.requestUpdate();
});
}
}
@watch('anchor')
protected _onAnchorChange(): void {
this._controller.resolveAnchor(this.anchor);
}
@watch('sticky')
protected _onStickyChange(): void {
this._internals.role = this.sticky ? 'status' : 'tooltip';
}
private _emitEvent(name: keyof IgcTooltipComponentEventMap): boolean {
return this.emitEvent(name, {
cancelable: name === 'igcOpening' || name === 'igcClosing',
detail: this._controller.anchor,
});
}
private async _applyTooltipState({
show,
withDelay = false,
withEvents = false,
}: TooltipStateOptions): Promise<boolean> {
if (show === this.open) {
return false;
}
if (withEvents && !this._emitEvent(show ? 'igcOpening' : 'igcClosing')) {
return false;
}
const commitStateChange = async () => {
if (show) {
this.open = true;
}
// Make the tooltip ignore most interactions while the animation
// is running. In the rare case when the popover overlaps its anchor
// this will prevent looping between the anchor and tooltip handlers.
this.inert = true;
const animationComplete = await this._player.playExclusive(
show ? this._showAnimation : this._hideAnimation
);
this.inert = false;
this.open = show;
if (animationComplete && withEvents) {
this._emitEvent(show ? 'igcOpened' : 'igcClosed');
}
return animationComplete;
};
if (withDelay) {
clearTimeout(this._timeoutId);
return new Promise(() => {
this._timeoutId = setTimeout(
async () => await commitStateChange(),
show ? this.showDelay : this.hideDelay
);
});
}
return commitStateChange();
}
/**
* Shows the tooltip if not already showing.
* If a target is provided, sets it as a transient anchor.
*/
public async show(target?: Element | string): Promise<boolean> {
if (target) {
this._stopTimeoutAndAnimation();
this._controller.setAnchor(target, true);
}
return await this._applyTooltipState({ show: true });
}
/** Hides the tooltip if not already hidden. */
public async hide(): Promise<boolean> {
return await this._applyTooltipState({ show: false });
}
/** Toggles the tooltip between shown/hidden state */
public async toggle(): Promise<boolean> {
return await (this.open ? this.hide() : this.show());
}
protected _showWithEvent(): Promise<boolean> {
return this._applyTooltipState({
show: true,
withDelay: true,
withEvents: true,
});
}
protected _hideWithEvent(): Promise<boolean> {
return this._applyTooltipState({
show: false,
withDelay: true,
withEvents: true,
});
}
private _showOnInteraction(): void {
this._stopTimeoutAndAnimation();
this._showWithEvent();
}
private _stopTimeoutAndAnimation(): void {
clearTimeout(this._timeoutId);
this._player.stopAll();
}
private _setAutoHide(): void {
this._stopTimeoutAndAnimation();
this._timeoutId = setTimeout(
this._hideWithEvent.bind(this),
this._autoHideDelay
);
}
private _hideOnInteraction(): void {
if (!this.sticky) {
this._setAutoHide();
}
}
private async _hideOnEscape(): Promise<void> {
await this.hide();
this._emitEvent('igcClosed');
}
protected override render() {
return html`
<igc-popover
.inert=${!this.open}
.placement=${this.placement}
.offset=${this.offset}
.anchor=${this._controller.anchor ?? undefined}
.arrow=${this.disableArrow ? null : this._arrowElement}
.arrowOffset=${this._arrowOffset}
.shiftPadding=${8}
?open=${this.open}
flip
shift
>
<div ${ref(this._containerRef)} part="base">
<slot>${this.message}</slot>
${this.sticky
? html`
<slot name="close-button" @click=${this._setAutoHide}>
<igc-icon
name="input_clear"
collection="default"
aria-hidden="true"
></igc-icon>
</slot>
`
: nothing}
${this.disableArrow ? nothing : html`<div id="arrow"></div>`}
</div>
</igc-popover>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'igc-tooltip': IgcTooltipComponent;
}
}