A popover hung from its anchor and ran off the foot of the window when the anchor sat low. It now goes over the anchor when it fits neither way better below, and otherwise takes the roomier side with its height cut so it scrolls inside itself; the placement is a pure function with a test, and the box places itself again when its content changes size. The ssh popover showed three long paragraphs above its switch: the explainer and the host-key text now sit in a folded how it works section, and the warning and the switch stay visible. Its sections can no longer give the popover a sideways scroll.
43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
// Where a floating popover sits, without a DOM.
|
|
|
|
// Space kept between a floating box and the viewport's edge.
|
|
const POPOVER_EDGE_PX = 8;
|
|
|
|
/**
|
|
* The left edge for a popover of `width` that wants to start at `left`:
|
|
* pulled in so its right edge stays on screen, but never past the left edge.
|
|
* A filterable column near the right of the window would otherwise open
|
|
* partly outside it.
|
|
*/
|
|
export function clampLeft(
|
|
left: number,
|
|
width: number,
|
|
viewportWidth: number,
|
|
): number {
|
|
const maxLeft = viewportWidth - width - POPOVER_EDGE_PX;
|
|
return Math.max(POPOVER_EDGE_PX, Math.min(left, maxLeft));
|
|
}
|
|
|
|
/**
|
|
* The top edge and the tallest height for a popover of `height` that hangs
|
|
* from an anchor spanning `anchorTop` to `anchorBottom`: under the anchor when
|
|
* it fits there, over it when it does not and there is more room above, and
|
|
* otherwise under it again with the height cut to the room left, so it scrolls
|
|
* inside itself. A popover under a badge near the foot of the window would
|
|
* otherwise run off the page.
|
|
*/
|
|
export function placeVertically(
|
|
anchorTop: number,
|
|
anchorBottom: number,
|
|
height: number,
|
|
viewportHeight: number,
|
|
gap: number,
|
|
): { top: number; maxHeight: number } {
|
|
const below = viewportHeight - anchorBottom - gap - POPOVER_EDGE_PX;
|
|
const above = anchorTop - gap - POPOVER_EDGE_PX;
|
|
if (height <= below || above <= below) {
|
|
return { top: anchorBottom + gap, maxHeight: Math.max(below, 0) };
|
|
}
|
|
const h = Math.min(height, above);
|
|
return { top: anchorTop - gap - h, maxHeight: above };
|
|
}
|