-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtooltip-position-manager.ts
More file actions
446 lines (384 loc) · 12.6 KB
/
tooltip-position-manager.ts
File metadata and controls
446 lines (384 loc) · 12.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 { log } from '../utilities/log';
import { findElement } from '../utilities/dom';
import { ARROW_SIZE } from '../templates/tooltip';
export type TooltipPosition = 'top' | 'bottom' | 'left' | 'right';
const ARROW_GAP = ARROW_SIZE + 6;
const VIEWPORT_PADDING = 4;
const FALLBACK_ORDER: Record<TooltipPosition, TooltipPosition[]> = {
top: ['bottom', 'left', 'right'],
bottom: ['top', 'left', 'right'],
left: ['right', 'top', 'bottom'],
right: ['left', 'top', 'bottom'],
};
const OVERFLOW_RE = /auto|scroll/;
const ARROW_CLASS_FOR_POSITION: Record<TooltipPosition, string> = {
top: 'gist-arrow-bottom',
bottom: 'gist-arrow-top',
left: 'gist-arrow-right',
right: 'gist-arrow-left',
};
export function findTargetElement(selector: string): Element | null {
const element = findElement(selector);
if (!element) {
log(`Tooltip target element not found for selector: ${selector}`);
}
return element;
}
function calculatePosition(
tooltipRect: DOMRect,
targetRect: DOMRect,
position: TooltipPosition
): { top: number; left: number } {
switch (position) {
case 'top':
return {
top: targetRect.top - tooltipRect.height - ARROW_GAP,
left: targetRect.left + (targetRect.width - tooltipRect.width) / 2,
};
case 'bottom':
return {
top: targetRect.bottom + ARROW_GAP,
left: targetRect.left + (targetRect.width - tooltipRect.width) / 2,
};
case 'left':
return {
top: targetRect.top + (targetRect.height - tooltipRect.height) / 2,
left: targetRect.left - tooltipRect.width - ARROW_GAP,
};
case 'right':
return {
top: targetRect.top + (targetRect.height - tooltipRect.height) / 2,
left: targetRect.right + ARROW_GAP,
};
}
}
function isTargetVisible(targetRect: DOMRect, scrollAncestors: Element[]): boolean {
if (
targetRect.bottom <= 0 ||
targetRect.top >= window.innerHeight ||
targetRect.right <= 0 ||
targetRect.left >= window.innerWidth
) {
return false;
}
for (const ancestor of scrollAncestors) {
const ancestorRect = ancestor.getBoundingClientRect();
if (
targetRect.bottom <= ancestorRect.top ||
targetRect.top >= ancestorRect.bottom ||
targetRect.right <= ancestorRect.left ||
targetRect.left >= ancestorRect.right
) {
return false;
}
}
return true;
}
function fitsPrimaryAxis(
coords: { top: number; left: number },
tooltipRect: DOMRect,
position: TooltipPosition
): boolean {
if (position === 'top' || position === 'bottom') {
return coords.top >= 0 && coords.top + tooltipRect.height <= window.innerHeight;
}
return coords.left >= 0 && coords.left + tooltipRect.width <= window.innerWidth;
}
function fitsCrossAxis(tooltipRect: DOMRect, position: TooltipPosition): boolean {
if (position === 'top' || position === 'bottom') {
return tooltipRect.width + VIEWPORT_PADDING * 2 <= window.innerWidth;
}
return tooltipRect.height + VIEWPORT_PADDING * 2 <= window.innerHeight;
}
interface PositionResult {
top: number;
left: number;
position: TooltipPosition;
arrowOffset: number | null;
}
function clampCrossAxis(
coords: { top: number; left: number },
tooltipRect: DOMRect,
position: TooltipPosition
): PositionResult {
let { top, left } = coords;
let arrowOffset: number | null = null;
if (position === 'top' || position === 'bottom') {
const minLeft = VIEWPORT_PADDING;
const maxLeft = window.innerWidth - tooltipRect.width - VIEWPORT_PADDING;
if (maxLeft >= minLeft) {
if (left < minLeft) {
arrowOffset = left - minLeft;
left = minLeft;
} else if (left > maxLeft) {
arrowOffset = left - maxLeft;
left = maxLeft;
}
}
} else {
const minTop = VIEWPORT_PADDING;
const maxTop = window.innerHeight - tooltipRect.height - VIEWPORT_PADDING;
if (maxTop >= minTop) {
if (top < minTop) {
arrowOffset = top - minTop;
top = minTop;
} else if (top > maxTop) {
arrowOffset = top - maxTop;
top = maxTop;
}
}
}
// Ensure the arrow offset doesn't push the arrow outside the tooltip
if (arrowOffset !== null) {
const halfTooltip =
position === 'top' || position === 'bottom' ? tooltipRect.width / 2 : tooltipRect.height / 2;
const maxArrowShift = halfTooltip - ARROW_GAP - VIEWPORT_PADDING;
if (Math.abs(arrowOffset) > maxArrowShift) {
arrowOffset = arrowOffset > 0 ? maxArrowShift : -maxArrowShift;
}
}
return { top, left, position, arrowOffset };
}
function tryPosition(
tooltipRect: DOMRect,
targetRect: DOMRect,
position: TooltipPosition
): PositionResult | null {
const coords = calculatePosition(tooltipRect, targetRect, position);
if (!fitsPrimaryAxis(coords, tooltipRect, position)) return null;
if (!fitsCrossAxis(tooltipRect, position)) return null;
return clampCrossAxis(coords, tooltipRect, position);
}
function findBestPosition(
tooltipRect: DOMRect,
targetRect: DOMRect,
preferred: TooltipPosition
): PositionResult | null {
const preferredResult = tryPosition(tooltipRect, targetRect, preferred);
if (preferredResult) return preferredResult;
for (const fallback of FALLBACK_ORDER[preferred]) {
const result = tryPosition(tooltipRect, targetRect, fallback);
if (result) return result;
}
return null;
}
function applyPosition(tooltipElement: HTMLElement, coords: { top: number; left: number }): void {
tooltipElement.style.position = 'absolute';
tooltipElement.style.top = `${coords.top + window.scrollY}px`;
tooltipElement.style.left = `${coords.left + window.scrollX}px`;
}
function updateArrow(tooltipElement: HTMLElement, result: PositionResult): void {
const arrowEl = tooltipElement.querySelector('.gist-tooltip-arrow') as HTMLElement | null;
if (!arrowEl) return;
arrowEl.classList.remove(
'gist-arrow-top',
'gist-arrow-bottom',
'gist-arrow-left',
'gist-arrow-right'
);
arrowEl.classList.add(ARROW_CLASS_FOR_POSITION[result.position]);
if (result.arrowOffset !== null) {
if (result.position === 'top' || result.position === 'bottom') {
arrowEl.style.left = `calc(50% + ${result.arrowOffset}px)`;
arrowEl.style.removeProperty('top');
} else {
arrowEl.style.top = `calc(50% + ${result.arrowOffset}px)`;
arrowEl.style.removeProperty('left');
}
} else {
if (result.position === 'top' || result.position === 'bottom') {
arrowEl.style.left = '50%';
arrowEl.style.removeProperty('top');
} else {
arrowEl.style.top = '50%';
arrowEl.style.removeProperty('left');
}
}
}
function getScrollableAncestors(element: Element): Element[] {
const ancestors: Element[] = [];
let current = element.parentElement;
while (current) {
const style = getComputedStyle(current);
const overflow = style.overflow + style.overflowX + style.overflowY;
if (OVERFLOW_RE.test(overflow)) {
ancestors.push(current);
}
current = current.parentElement;
}
return ancestors;
}
export interface TooltipHandle {
cleanup: () => void;
reposition: () => void;
}
/**
* Predicts whether the tooltip can be positioned after the target is scrolled
* into view. Returns true only when the target exists in the DOM and at least
* one placement (preferred + fallbacks) would fit the viewport assuming the
* target occupies a centered viewport position after scrollIntoView.
*/
export function canTooltipFitInViewport(
tooltipElement: HTMLElement,
targetSelector: string,
position: TooltipPosition
): boolean {
const targetElement = findTargetElement(targetSelector);
if (!targetElement) return false;
const targetRect = targetElement.getBoundingClientRect();
const vpW = window.innerWidth;
const vpH = window.innerHeight;
const simulatedTargetRect = new DOMRect(
Math.max(0, (vpW - targetRect.width) / 2),
Math.max(0, (vpH - targetRect.height) / 2),
targetRect.width,
targetRect.height
);
tooltipElement.style.display = '';
const tooltipRect = tooltipElement.getBoundingClientRect();
return findBestPosition(tooltipRect, simulatedTargetRect, position) !== null;
}
const SCROLL_POLL_INTERVAL_MS = 50;
const SCROLL_SETTLE_TIMEOUT_MS = 1000;
function waitForScrollSettle(targetElement: Element): Promise<void> {
return new Promise<void>((resolve) => {
let lastRect = targetElement.getBoundingClientRect();
let stableFrames = 0;
const start = Date.now();
function check(): void {
const currentRect = targetElement.getBoundingClientRect();
if (
Math.abs(currentRect.top - lastRect.top) < 1 &&
Math.abs(currentRect.left - lastRect.left) < 1
) {
stableFrames++;
} else {
stableFrames = 0;
}
lastRect = currentRect;
if (stableFrames >= 2 || Date.now() - start > SCROLL_SETTLE_TIMEOUT_MS) {
resolve();
return;
}
setTimeout(check, SCROLL_POLL_INTERVAL_MS);
}
setTimeout(check, SCROLL_POLL_INTERVAL_MS);
});
}
/**
* If the target is already visible, resolves immediately.
* Otherwise, if `canTooltipFitInViewport` predicts a valid placement, smoothly
* scrolls the target into view (including within nested scroll containers) and
* waits for the scroll to settle. Returns false without scrolling when the
* preflight fails.
*/
export async function ensureTargetInView(
tooltipElement: HTMLElement,
targetSelector: string,
position: TooltipPosition
): Promise<boolean> {
const targetElement = findTargetElement(targetSelector);
if (!targetElement) return false;
let scrollAncestors: Element[] = [];
try {
scrollAncestors = getScrollableAncestors(targetElement);
} catch {
// getComputedStyle may throw in test environments
}
const targetRect = targetElement.getBoundingClientRect();
if (isTargetVisible(targetRect, scrollAncestors)) {
return true;
}
if (!canTooltipFitInViewport(tooltipElement, targetSelector, position)) {
log(
`Preflight failed: tooltip would not fit after scrolling target "${targetSelector}" into view`
);
return false;
}
targetElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
await waitForScrollSettle(targetElement);
const postScrollRect = targetElement.getBoundingClientRect();
let postScrollAncestors: Element[] = [];
try {
postScrollAncestors = getScrollableAncestors(targetElement);
} catch {
// ignore
}
return isTargetVisible(postScrollRect, postScrollAncestors);
}
export function positionTooltip(
tooltipElement: HTMLElement,
targetSelector: string,
position: TooltipPosition
): TooltipHandle | null {
const targetElement = findTargetElement(targetSelector);
if (!targetElement) {
return null;
}
let rafId: number | null = null;
let cleaned = false;
let scrollAncestors: Element[] = [];
try {
scrollAncestors = getScrollableAncestors(targetElement);
} catch {
// getComputedStyle may throw in test environments
}
function update(): void {
if (cleaned) {
return;
}
if (!targetElement || !document.contains(targetElement) || !document.contains(tooltipElement)) {
log(`Tooltip or target element removed from DOM, cleaning up listeners`);
cleanup();
return;
}
const targetRect = targetElement.getBoundingClientRect();
if (!isTargetVisible(targetRect, scrollAncestors)) {
tooltipElement.style.display = 'none';
return;
}
tooltipElement.style.display = '';
const tooltipRect = tooltipElement.getBoundingClientRect();
const result = findBestPosition(tooltipRect, targetRect, position);
if (!result) {
tooltipElement.style.display = 'none';
return;
}
applyPosition(tooltipElement, result);
updateArrow(tooltipElement, result);
}
function onScrollOrResize(): void {
if (rafId !== null) {
return;
}
rafId = requestAnimationFrame(() => {
rafId = null;
update();
});
}
function cleanup(): void {
if (cleaned) {
return;
}
cleaned = true;
window.removeEventListener('scroll', onScrollOrResize);
window.removeEventListener('resize', onScrollOrResize);
for (const ancestor of scrollAncestors) {
ancestor.removeEventListener('scroll', onScrollOrResize);
}
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
}
update();
if (cleaned) {
return null;
}
window.addEventListener('scroll', onScrollOrResize, { passive: true });
window.addEventListener('resize', onScrollOrResize, { passive: true });
for (const ancestor of scrollAncestors) {
ancestor.addEventListener('scroll', onScrollOrResize, { passive: true });
}
return { cleanup, reposition: update };
}