Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PickLabelPosition.ts

46 lines1.7 KB

1/**
2 * Pure clamp/flip math for the floating label that follows the cursor while
3 * the user is picking an element in the in-app browser. Lives in its own
4 * electron-free module so the geometry can be unit-tested without spinning
5 * up an Electron preload context (`PickPreload.ts` itself imports
6 * `electron` and `react-grab/primitives`, which can't load under vitest).
7 *
8 * - Horizontally pins the label to `targetLeft`, clamped into
9 * `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.
10 * - Vertically prefers above the target. If the label would overflow the
11 * top, flips below; if THAT also overflows the bottom, pins to the
12 * bottom margin (better to overlap the highlight than disappear).
13 */
14​
15/** Distance in CSS pixels between the highlight and the floating label. */
16export const LABEL_GAP = 4;
17/** Minimum padding the label keeps from any viewport edge. */
18export const VIEWPORT_MARGIN = 4;
19​
20export function computeLabelPosition(input: {
21 targetLeft: number;
22 targetTop: number;
23 targetBottom: number;
24 labelWidth: number;
25 labelHeight: number;
26 viewportWidth: number;
27 viewportHeight: number;
28}): { x: number; y: number } {
29 const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;
30 const { viewportWidth, viewportHeight } = input;
31​
32 let x = targetLeft;
33 const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;
34 if (x > maxX) x = maxX;
35 if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;
36​
37 let y = targetTop - labelHeight - LABEL_GAP;
38 if (y < VIEWPORT_MARGIN) {
39 y = targetBottom + LABEL_GAP;
40 if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {
41 y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);
42 }
43 }
44​
45 return { x, y };