-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTooltipTriggerMixin.js
368 lines (333 loc) · 11.2 KB
/
TooltipTriggerMixin.js
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
import Tooltip from '../components/Tooltip.js';
import { canAnchorPopup } from '../utils/popup.js';
import styles from './TooltipTriggerMixin.css' assert { type: 'css' };
/**
* @param {ReturnType<import('./StateMixin.js').default>} Base
*/
export default function TooltipTriggerMixin(Base) {
class TooltipTrigger extends Base {
static {
this.css(styles);
this.on({
composed({ template, html }) {
template.append(html`
<${Tooltip.elementName} role=tooltip id=tooltip
><slot id=tooltip-slot
on-slotchange={onTooltipTriggerSlotChange} name=tooltip
>{tooltip}</slot></${Tooltip.elementName}>
`);
},
});
}
static TOOLTIP_MOUSE_IDLE_MS = 500;
static TOOLTIP_TOUCH_IDLE_MS = 1500;
/** @type {InstanceType<Tooltip>} */
#tooltip;
/** @type {any} */
#idleDebounce;
#pendingHide = false;
/** @type {HTMLElement[]} */
#watchedParents = [];
#resizeObserver;
#intersectObserver;
onParentScroll = (event) => {
this.updateTooltipPosition();
};
/** @param {any[]} args */
constructor(...args) {
super(...args);
this.#tooltip = /** @type {InstanceType<Tooltip>} */ (this.refs.tooltip.cloneNode(true));
this.#tooltip.removeAttribute('id');
this.#tooltip.style.setProperty('position', 'fixed');
this.#tooltip.setAttribute('aria-hidden', 'true');
this.#resizeObserver = new ResizeObserver((entries) => {
// console.log('RO', entries);
if (!this.#tooltip.open) return;
this.updateTooltipPosition();
});
const threshold = [0, 0.49, 0.5, 0.51, 1];
this.#intersectObserver = new IntersectionObserver((entries) => {
// console.log('IO', entries);
if (!this.#tooltip.open) return;
for (const entry of entries) {
if (entry.intersectionRatio <= 0) {
console.debug('Hide tooltip due to tooltip occlusion');
this.hideTooltip();
return;
}
if (entry.target === this.#tooltip) {
console.debug('Reposition tooltip due to possible tooltip occlusion');
this.updateTooltipPosition();
return;
}
if (entry.target === this) {
if (entry.intersectionRatio <= 0.5) {
console.debug('Hiding tooltip because target is occluded');
this.hideTooltip();
} else {
console.debug('Using InsectionObserver rect to update tooltip');
this.updateTooltipPosition(entry.boundingClientRect);
}
return;
}
}
console.debug('Updating tooltip position because offsetParent change.');
this.updateTooltipPosition();
}, { threshold });
// this.#tooltip.remove();
}
/**
* @param {Event & {currentTarget: HTMLSlotElement}} event
* @return {void}
*/
onTooltipTriggerSlotChange(event) {
const tooltip = this.tooltipClone;
while (tooltip.lastChild) {
tooltip.lastChild.remove();
}
for (const child of event.currentTarget.assignedNodes()) {
tooltip.append(child.cloneNode(true));
}
}
/**
* @this {TooltipTrigger} this
* @param {FocusEvent} event
* @return {void}
*/
onTooltipTriggerFocus(event) {
// console.log('getting focus', event);
if (this.disabledState) return;
if (this.matches(':active')) {
// console.log('abort from active');
return;
}
this.showTooltip();
}
/**
* @this {TooltipTrigger} this
* @param {KeyboardEvent} event
* @return {void}
*/
onTooltipTriggerKeydown(event) {
if (event.ctrlKey) this.hideTooltip();
}
/**
* @this {TooltipTrigger} this
* @return {void}
*/
onTooltipTriggerBlur() {
this.hideTooltip();
}
/**
* @param {MouseEvent|TouchEvent} event
* @this {TooltipTrigger} this
* @return {void}
*/
onTooltipTriggerPointer(event) {
if (this.disabledState) return;
// console.log('tooltip event', event.type);
switch (event.type) {
case 'touchstart':
this.scheduleShowTooltip('touch');
break;
case 'touchend':
case 'touchcancel':
this.scheduleHideTooltip('touch');
break;
case 'click':
case 'mouseout':
this.cancelShowTooltip();
this.hideTooltip();
break;
case 'mousemove':
case 'mouseover':
this.scheduleShowTooltip('mouse');
break;
default:
}
}
get tooltipClone() {
return this.#tooltip;
}
get clonedTooltip() {
return this.#tooltip;
}
cancelShowTooltip() {
// console.log('cancel tooltiptimer');
clearTimeout(this.#idleDebounce);
}
/** @param {'mouse'|'touch'|'keyboard'} type */
scheduleHideTooltip(type) {
clearTimeout(this.#idleDebounce);
if (!this.#tooltip.open) {
// console.log('abort schedule (shown)');
return;
}
let timeout = 0;
switch (type) {
case 'mouse':
timeout = 0;
break;
case 'touch':
timeout = 1500;
break;
default:
}
// console.log('schedule tooltiptimer');
this.#idleDebounce = setTimeout(() => {
// console.log('hide timeout');
this.hideTooltip();
}, timeout);
}
/** @param {'mouse'|'touch'|'keyboard'} type */
scheduleShowTooltip(type) {
if (this.#tooltip.open) {
// console.log('abort schedule (shown)');
return;
}
let timeout = 0;
switch (type) {
case 'mouse':
timeout = this.constructor.TOOLTIP_MOUSE_IDLE_MS;
break;
case 'touch':
timeout = this.constructor.TOOLTIP_TOUCH_IDLE_MS;
break;
default:
}
// console.log('schedule tooltiptimer');
clearTimeout(this.#idleDebounce);
this.#idleDebounce = setTimeout(() => {
// console.log('idle');
this.showTooltip(type === 'touch');
}, timeout);
}
showTooltip(touch = false) {
if (this.#tooltip.open) return;
this.refs.tooltip.open = true;
this.refs.tooltip.touch = touch;
this.#tooltip.touch = touch;
document.body.append(this.#tooltip);
this.updateTooltipPosition();
this.#resizeObserver.observe(this, { box: 'border-box' });
this.#intersectObserver.observe(this);
this.#intersectObserver.observe(this.#tooltip);
/** @type {HTMLElement} */
let offsetParent = this;
while ((offsetParent = offsetParent.offsetParent)) {
this.#resizeObserver.observe(offsetParent, { box: 'border-box' });
// console.log('observing', offsetParent);
this.#watchedParents.push(offsetParent);
this.#intersectObserver.observe(offsetParent);
offsetParent.addEventListener('scroll', this.onParentScroll);
}
window.addEventListener('scroll', this.onParentScroll);
// console.log('offsetparent', this.offsetParent);
this.#tooltip.open = true;
}
hideTooltip() {
this.#resizeObserver.disconnect();
this.#intersectObserver.disconnect();
let parent;
while ((parent = this.#watchedParents.pop())) {
parent.removeEventListener('scroll', this.onParentScroll);
}
window.removeEventListener('scroll', this.onParentScroll);
this.#tooltip.open = false;
this.#tooltip.remove();
this.refs.tooltip.open = false;
const hoverStyle = this.refs.tooltip.style;
hoverStyle.removeProperty('width');
hoverStyle.removeProperty('height');
}
/**
* @param {DOMRect} [domRect]
* @return {void}
*/
updateTooltipPosition(domRect) {
const offset = 8;
// const margin = 8;
/** @type {import('../utils/popup.js').CanAnchorPopUpOptions} */
const anchorOptions = {
anchor: domRect ?? this.getBoundingClientRect(),
width: this.#tooltip.clientWidth,
height: this.#tooltip.clientHeight,
// margin,
};
const isPageRTL = (getComputedStyle(this).direction === 'rtl');
const xStart = isPageRTL ? 'right' : 'left';
const xEnd = isPageRTL ? 'left' : 'right';
/** @type {import('../utils/popup.js').CanAnchorPopUpOptions[]} */
const preferences = [
{ clientY: 'bottom', clientX: 'center', offsetY: offset },
{ clientY: 'bottom', clientX: xStart, offsetY: offset },
{ clientY: 'bottom', clientX: xEnd, offsetY: offset },
{ clientY: 'top', clientX: 'center', offsetY: -offset },
{ clientY: 'top', clientX: xStart, offsetY: -offset },
{ clientY: 'top', clientX: xEnd, offsetY: -offset },
];
let anchorResult;
for (const preference of preferences) {
anchorResult = canAnchorPopup({
...anchorOptions,
...preference,
});
if (anchorResult) break;
}
// console.log({ anchorResult });
if (!anchorResult) {
anchorResult = canAnchorPopup({
...anchorOptions,
...preferences[0],
force: true,
});
}
this.#tooltip.style.setProperty('top', `${anchorResult.pageY}px`);
this.#tooltip.style.setProperty('left', `${anchorResult.pageX}px`);
this.#tooltip.style.setProperty('margin', '0');
this.#tooltip.style.setProperty('transform-origin', `${anchorResult.transformOriginY} ${anchorResult.transformOriginX}`);
const hoverStyle = this.refs.tooltip.style;
hoverStyle.setProperty('width', `${anchorResult.width + (anchorResult.offsetX * 2)}px`);
hoverStyle.setProperty('height', `${anchorResult.height + (anchorResult.offsetY)}px`);
if (anchorResult.clientY === 'bottom') {
hoverStyle.setProperty('top', '100%');
hoverStyle.removeProperty('bottom');
} else {
hoverStyle.removeProperty('top');
hoverStyle.setProperty('height', `${anchorResult.height + (anchorResult.offsetY)}px`);
hoverStyle.setProperty('bottom', '100%');
}
switch (anchorResult.clientX) {
case 'left':
hoverStyle.setProperty('left', '0');
hoverStyle.removeProperty('right');
break;
default:
case 'center':
hoverStyle.removeProperty('left');
hoverStyle.removeProperty('right');
break;
case 'right':
hoverStyle.removeProperty('left');
hoverStyle.setProperty('right', '0');
}
}
connectedCallback() {
super.connectedCallback();
for (const type of ['click', 'mousedown', 'mousemove', 'mouseout',
'touchmove', 'touchstart', 'touchend', 'touchleave', 'touchcancel']) {
this.addEventListener(type, this.onTooltipTriggerPointer, { passive: true });
}
this.addEventListener('focus', this.onTooltipTriggerFocus);
this.addEventListener('blur', this.onTooltipTriggerBlur);
this.addEventListener('keydown', this.onTooltipTriggerKeydown, { passive: true });
}
disconnectedCallback() {
// console.log('disconnected');
this.hideTooltip();
super.disconnectedCallback();
}
}
TooltipTrigger.prototype.tooltip = TooltipTrigger.prop('tooltip');
return TooltipTrigger;
}