-
-
Notifications
You must be signed in to change notification settings - Fork 862
/
Copy pathtooltip.component.ts
293 lines (255 loc) · 9.23 KB
/
tooltip.component.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
import { animateTo, parseDuration, stopAnimations } from '../../internal/animate.js';
import { classMap } from 'lit/directives/class-map.js';
import { getAnimation, setDefaultAnimation } from '../../utilities/animation-registry.js';
import { html } from 'lit';
import { LocalizeController } from '../../utilities/localize.js';
import { property, query } from 'lit/decorators.js';
import { waitForEvent } from '../../internal/event.js';
import { watch } from '../../internal/watch.js';
import ShoelaceElement from '../../internal/shoelace-element.js';
import SlPopup from '../popup/popup.component.js';
import styles from './tooltip.styles.js';
import type { CSSResultGroup } from 'lit';
/**
* @summary Tooltips display additional information based on a specific action.
* @documentation https://shoelace.style/components/tooltip
* @status stable
* @since 2.0
*
* @dependency sl-popup
*
* @slot - The tooltip's target element. Avoid slotting in more than one element, as subsequent ones will be ignored.
* @slot content - The content to render in the tooltip. Alternatively, you can use the `content` attribute.
*
* @event sl-show - Emitted when the tooltip begins to show.
* @event sl-after-show - Emitted after the tooltip has shown and all animations are complete.
* @event sl-hide - Emitted when the tooltip begins to hide.
* @event sl-after-hide - Emitted after the tooltip has hidden and all animations are complete.
*
* @csspart base - The component's base wrapper, an `<sl-popup>` element.
* @csspart base__popup - The popup's exported `popup` part. Use this to target the tooltip's popup container.
* @csspart base__arrow - The popup's exported `arrow` part. Use this to target the tooltip's arrow.
* @csspart body - The tooltip's body where its content is rendered.
*
* @cssproperty --max-width - The maximum width of the tooltip before its content will wrap.
* @cssproperty --hide-delay - The amount of time to wait before hiding the tooltip when hovering.
* @cssproperty --show-delay - The amount of time to wait before showing the tooltip when hovering.
*
* @animation tooltip.show - The animation to use when showing the tooltip.
* @animation tooltip.hide - The animation to use when hiding the tooltip.
*/
export default class SlTooltip extends ShoelaceElement {
static styles: CSSResultGroup = styles;
static dependencies = { 'sl-popup': SlPopup };
private hoverTimeout: number;
private readonly localize = new LocalizeController(this);
@query('slot:not([name])') defaultSlot: HTMLSlotElement;
@query('.tooltip__body') body: HTMLElement;
@query('sl-popup') popup: SlPopup;
/** The tooltip's content. If you need to display HTML, use the `content` slot instead. */
@property() content = '';
/**
* The preferred placement of the tooltip. Note that the actual placement may vary as needed to keep the tooltip
* inside of the viewport.
*/
@property() placement:
| 'top'
| 'top-start'
| 'top-end'
| 'right'
| 'right-start'
| 'right-end'
| 'bottom'
| 'bottom-start'
| 'bottom-end'
| 'left'
| 'left-start'
| 'left-end' = 'top';
/** Disables the tooltip so it won't show when triggered. */
@property({ type: Boolean, reflect: true }) disabled = false;
/** The distance in pixels from which to offset the tooltip away from its target. */
@property({ type: Number }) distance = 8;
/** Indicates whether or not the tooltip is open. You can use this in lieu of the show/hide methods. */
@property({ type: Boolean, reflect: true }) open = false;
/** The distance in pixels from which to offset the tooltip along its target. */
@property({ type: Number }) skidding = 0;
/**
* Controls how the tooltip is activated. Possible options include `click`, `hover`, `focus`, and `manual`. Multiple
* options can be passed by separating them with a space. When manual is used, the tooltip must be activated
* programmatically.
*/
@property() trigger = 'hover focus';
/**
* Enable this option to prevent the tooltip from being clipped when the component is placed inside a container with
* `overflow: auto|hidden|scroll`. Hoisting uses a fixed positioning strategy that works in many, but not all,
* scenarios.
*/
@property({ type: Boolean }) hoist = false;
constructor() {
super();
this.addEventListener('blur', this.handleBlur, true);
this.addEventListener('focus', this.handleFocus, true);
this.addEventListener('click', this.handleClick);
this.addEventListener('keydown', this.handleKeyDown);
this.addEventListener('mouseover', this.handleMouseOver);
this.addEventListener('mouseout', this.handleMouseOut);
}
connectedCallback() {
super.connectedCallback();
}
firstUpdated() {
this.body.hidden = !this.open;
// If the tooltip is visible on init, update its position
if (this.open) {
this.popup.active = true;
this.popup.reposition();
}
}
private handleBlur = () => {
if (this.hasTrigger('focus')) {
this.hide();
}
};
private handleClick = () => {
if (this.hasTrigger('click')) {
if (this.open) {
this.hide();
} else {
this.show();
}
}
};
private handleFocus = () => {
if (this.hasTrigger('focus')) {
this.show();
}
};
private handleKeyDown = (event: KeyboardEvent) => {
// Pressing escape when the target element has focus should dismiss the tooltip
if (this.open && event.key === 'Escape') {
event.stopPropagation();
this.hide();
}
};
private handleMouseOver = () => {
if (this.hasTrigger('hover')) {
const delay = parseDuration(getComputedStyle(this).getPropertyValue('--show-delay'));
clearTimeout(this.hoverTimeout);
this.hoverTimeout = window.setTimeout(() => this.show(), delay);
}
};
private handleMouseOut = () => {
if (this.hasTrigger('hover')) {
const delay = parseDuration(getComputedStyle(this).getPropertyValue('--hide-delay'));
clearTimeout(this.hoverTimeout);
this.hoverTimeout = window.setTimeout(() => this.hide(), delay);
}
};
private hasTrigger(triggerType: string) {
const triggers = this.trigger.split(' ');
return triggers.includes(triggerType);
}
@watch('open', { waitUntilFirstUpdate: true })
async handleOpenChange() {
if (this.open) {
if (this.disabled) {
return;
}
// Show
this.emit('sl-show');
await stopAnimations(this.body);
this.body.hidden = false;
this.popup.active = true;
const { keyframes, options } = getAnimation(this, 'tooltip.show', { dir: this.localize.dir() });
await animateTo(this.popup.popup, keyframes, options);
this.emit('sl-after-show');
} else {
// Hide
this.emit('sl-hide');
await stopAnimations(this.body);
const { keyframes, options } = getAnimation(this, 'tooltip.hide', { dir: this.localize.dir() });
await animateTo(this.popup.popup, keyframes, options);
this.popup.active = false;
this.body.hidden = true;
this.emit('sl-after-hide');
}
}
@watch(['content', 'distance', 'hoist', 'placement', 'skidding'])
async handleOptionsChange() {
if (this.hasUpdated) {
await this.updateComplete;
this.popup.reposition();
}
}
@watch('disabled')
handleDisabledChange() {
if (this.disabled && this.open) {
this.hide();
}
}
/** Shows the tooltip. */
async show() {
if (this.open) {
return undefined;
}
this.open = true;
return waitForEvent(this, 'sl-after-show');
}
/** Hides the tooltip */
async hide() {
if (!this.open) {
return undefined;
}
this.open = false;
return waitForEvent(this, 'sl-after-hide');
}
//
// NOTE: Tooltip is a bit unique in that we're using aria-live instead of aria-labelledby to trick screen readers into
// announcing the content. It works really well, but it violates an accessibility rule. We're also adding the
// aria-describedby attribute to a slot, which is required by <sl-popup> to correctly locate the first assigned
// element, otherwise positioning is incorrect.
//
render() {
return html`
<sl-popup
part="base"
exportparts="
popup:base__popup,
arrow:base__arrow
"
class=${classMap({
tooltip: true,
'tooltip--open': this.open
})}
placement=${this.placement}
distance=${this.distance}
skidding=${this.skidding}
strategy=${this.hoist ? 'fixed' : 'absolute'}
flip
shift
arrow
>
${'' /* eslint-disable-next-line lit-a11y/no-aria-slot */}
<slot slot="anchor" aria-describedby="tooltip"></slot>
${'' /* eslint-disable-next-line lit-a11y/accessible-name */}
<div part="body" id="tooltip" class="tooltip__body" role="tooltip" aria-live=${this.open ? 'polite' : 'off'}>
<slot name="content">${this.content}</slot>
</div>
</sl-popup>
`;
}
}
setDefaultAnimation('tooltip.show', {
keyframes: [
{ opacity: 0, scale: 0.8 },
{ opacity: 1, scale: 1 }
],
options: { duration: 150, easing: 'ease' }
});
setDefaultAnimation('tooltip.hide', {
keyframes: [
{ opacity: 1, scale: 1 },
{ opacity: 0, scale: 0.8 }
],
options: { duration: 150, easing: 'ease' }
});