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

menu-placement.ts

28 lines1.1 KB

1import type { VerticalHinge } from "./layout";
2​
3/**
4 * Places a menu beside its anchor within the screen region that holds it. A creased hinge splits
5 * the overlay into two regions, so a menu never straddles the fold.
6 */
7export function deriveMenuHorizontalPlacement(input: {
8 readonly anchorX: number;
9 readonly anchorWidth: number;
10 readonly overlayWidth: number;
11 readonly desiredWidth: number;
12 readonly margin: number;
13 /** In the overlay's coordinates. */
14 readonly hinge: VerticalHinge | null;
15}) {
16 const center = input.anchorX + input.anchorWidth / 2;
17 let start = 0;
18 let end = input.overlayWidth;
19 if (input.hinge) {
20 if (center < input.hinge.x) end = input.hinge.x;
21 else start = input.hinge.x + input.hinge.width;
22 }
23 const width = Math.min(input.desiredWidth, Math.max(0, end - start - 2 * input.margin));
24 const preferredLeft =
25 center <= (start + end) / 2 ? input.anchorX : input.anchorX + input.anchorWidth - width;
26 const left = Math.min(Math.max(preferredLeft, start + input.margin), end - width - input.margin);
27 return { left, width };