Portal the search select list to the body so modals can never clip it

This commit is contained in:
2026-11-21 14:17:37 +01:00
parent 3f119851ae
commit 9d181cb6f6
4 changed files with 240 additions and 20 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@moduletrace/twui",
"version": "0.1.11",
"version": "0.1.12",
"description": "A modular skeletal React component framework for Tailwind CSS v4",
"author": "Benjamin Toby",
"type": "module",
@@ -0,0 +1,83 @@
import { describe, expect, test } from "bun:test";
import twuiSearchSelectListPosition from "./list-position";
const Field = { top: 100, bottom: 140, left: 20, width: 200 };
describe("twuiSearchSelectListPosition", () => {
test("sits below the field when there is room", () => {
const position = twuiSearchSelectListPosition({
field: Field,
listHeight: 160,
viewportWidth: 1200,
viewportHeight: 800,
});
expect(position).toEqual({
placement: "below",
top: 144,
left: 20,
width: 200,
maxHeight: 320,
});
});
test("flips above the field when the list does not fit below", () => {
const position = twuiSearchSelectListPosition({
field: { top: 640, bottom: 680, left: 20, width: 200 },
listHeight: 160,
viewportWidth: 1200,
viewportHeight: 800,
});
expect(position).toEqual({
placement: "above",
bottom: 164,
left: 20,
width: 200,
maxHeight: 320,
});
});
test("stays below when above has no more room", () => {
const position = twuiSearchSelectListPosition({
field: { top: 20, bottom: 60, left: 20, width: 200 },
listHeight: 400,
viewportWidth: 1200,
viewportHeight: 200,
});
expect(position.placement).toBe("below");
expect(position.maxHeight).toBe(80);
});
test("caps the list at the viewport share and the room it has", () => {
const position = twuiSearchSelectListPosition({
field: Field,
listHeight: 1000,
viewportWidth: 1200,
viewportHeight: 800,
});
expect(position.maxHeight).toBe(320);
});
test("keeps the list inside the viewport's horizontal edges", () => {
const nearRightEdge = twuiSearchSelectListPosition({
field: { top: 100, bottom: 140, left: 1100, width: 200 },
listHeight: 160,
viewportWidth: 1200,
viewportHeight: 800,
});
expect(nearRightEdge.left).toBe(992);
expect(nearRightEdge.width).toBe(200);
const narrowViewport = twuiSearchSelectListPosition({
field: { top: 100, bottom: 140, left: 0, width: 400 },
listHeight: 160,
viewportWidth: 300,
viewportHeight: 800,
});
expect(narrowViewport.left).toBe(8);
expect(narrowViewport.width).toBe(284);
});
});
@@ -0,0 +1,68 @@
/**
* Where a search select's option list goes once it is portalled out of the
* field's own box: below the field when there is room, otherwise above it,
* and always kept inside the viewport so a modal's scrolling can never cut
* it off.
*/
export type TWUISearchSelectListPlacement = "below" | "above";
export type TWUISearchSelectListPosition = {
placement: TWUISearchSelectListPlacement;
top?: number;
bottom?: number;
left: number;
width: number;
maxHeight: number;
};
type Params = {
field: { top: number; bottom: number; left: number; width: number };
listHeight: number;
viewportWidth: number;
viewportHeight: number;
/** Space kept between the field and the list. */
gap?: number;
/** Space kept between the list and the viewport's edge. */
margin?: number;
/** The most of the viewport's height the list may take. */
maxHeightShare?: number;
};
export default function twuiSearchSelectListPosition({
field,
listHeight,
viewportWidth,
viewportHeight,
gap = 4,
margin = 8,
maxHeightShare = 0.4,
}: Params): TWUISearchSelectListPosition {
const maxListHeight = Math.max(0, viewportHeight * maxHeightShare);
const spaceBelow = Math.max(
0,
viewportHeight - field.bottom - gap - margin,
);
const spaceAbove = Math.max(0, field.top - gap - margin);
const wanted = Math.min(Math.max(0, listHeight), maxListHeight);
const placement: TWUISearchSelectListPlacement =
wanted > spaceBelow && spaceAbove > spaceBelow ? "above" : "below";
const available = placement === "below" ? spaceBelow : spaceAbove;
const width = Math.max(
0,
Math.min(field.width, viewportWidth - margin * 2),
);
const left = Math.max(
margin,
Math.min(field.left, viewportWidth - width - margin),
);
return {
placement,
...(placement === "below"
? { top: field.bottom + gap }
: { bottom: viewportHeight - field.top + gap }),
left,
width,
maxHeight: Math.max(0, Math.min(maxListHeight, available)),
};
}
+88 -19
View File
@@ -1,5 +1,6 @@
import { Check, ChevronDown, Search, X } from "lucide-react";
import React from "react";
import ReactDOM from "react-dom";
import { twMerge } from "tailwind-merge";
import type {
TWUISelectOptionObject,
@@ -8,6 +9,7 @@ import type {
} from "./Select";
import Span from "../layout/Span";
import twuiSlugify from "../utils/slugify";
import twuiSearchSelectListPosition from "../(utils)/search-select/list-position";
function getOptionLabel<KeyType extends string, T extends { [k: string]: any }>(
option: TWUISelectOptionObject<KeyType, T>,
@@ -73,6 +75,7 @@ export default function SearchSelect<
...props
}: TWUISearchSelectProps<KeyType, T>) {
const rootRef = React.useRef<HTMLDivElement>(null);
const fieldRef = React.useRef<HTMLDivElement>(null);
const inputRef = React.useRef<HTMLInputElement>(null);
const listRef = React.useRef<HTMLUListElement>(null);
const internalSelectRef = React.useRef<HTMLSelectElement>(null);
@@ -100,6 +103,9 @@ export default function SearchSelect<
: "",
);
const [open, setOpen] = React.useState(false);
const [mounted, setMounted] = React.useState(false);
const [listStyle, setListStyle] =
React.useState<React.CSSProperties | null>(null);
const [activeIndex, setActiveIndex] = React.useState(0);
const [validity, setValidity] = React.useState<TWUISelectValidityObject>({
isValid: true,
@@ -218,7 +224,10 @@ export default function SearchSelect<
React.useEffect(() => {
if (!open) return;
const onPointerDown = (e: PointerEvent) => {
if (!rootRef.current?.contains(e.target as Node)) {
if (
!rootRef.current?.contains(e.target as Node) &&
!listRef.current?.contains(e.target as Node)
) {
setOpen(false);
if (!multiple && selected[0]) {
setQuery(getOptionLabel(selected[0]));
@@ -231,6 +240,58 @@ export default function SearchSelect<
return () => document.removeEventListener("pointerdown", onPointerDown);
}, [open, selected, multiple]);
React.useEffect(() => {
setMounted(true);
}, []);
const updateListStyle = React.useCallback(() => {
const fieldEl = fieldRef.current;
const listEl = listRef.current;
if (!fieldEl || !listEl) return;
const rect = fieldEl.getBoundingClientRect();
const position = twuiSearchSelectListPosition({
field: {
top: rect.top,
bottom: rect.bottom,
left: rect.left,
width: rect.width,
},
listHeight: listEl.scrollHeight,
viewportWidth: document.documentElement.clientWidth,
viewportHeight: document.documentElement.clientHeight,
});
setListStyle({
top: position.top,
bottom: position.bottom,
left: position.left,
width: position.width,
maxHeight: position.maxHeight,
});
}, []);
React.useLayoutEffect(() => {
if (!open || !mounted) return;
updateListStyle();
// The list is fixed, so anything that moves the field has to move it
// too. Scrolling the list itself changes nothing to measure.
const onScroll = (e: Event) => {
if (listRef.current?.contains(e.target as Node)) return;
updateListStyle();
};
window.addEventListener("scroll", onScroll, true);
window.addEventListener("resize", updateListStyle);
return () => {
window.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", updateListStyle);
};
}, [open, mounted, updateListStyle, filtered]);
React.useEffect(() => {
if (!open || !listRef.current) return;
listRef.current
@@ -358,6 +419,7 @@ export default function SearchSelect<
<div
{...wrapperProps}
ref={fieldRef}
className={twMerge(
"relative flex items-center gap-2 w-full rounded-default px-3 py-2 outline-1",
"bg-white dark:bg-background-dark",
@@ -542,22 +604,27 @@ export default function SearchSelect<
</button>
</div>
{open ? (
<ul
id={`${fieldId}-listbox`}
ref={listRef}
role="listbox"
aria-multiselectable={multiple || undefined}
className={twMerge(
"absolute left-0 right-0 top-full mt-1 z-100",
"max-h-[40vh] overflow-y-auto",
"rounded-default border border-solid",
"border-slate-200 dark:border-white/10",
"bg-background-light dark:bg-background-dark",
"shadow-lg shadow-slate-200/80 dark:shadow-black/40",
"p-0 m-0 list-none",
)}
>
{mounted && open
? ReactDOM.createPortal(
<ul
id={`${fieldId}-listbox`}
ref={listRef}
role="listbox"
aria-multiselectable={multiple || undefined}
className={twMerge(
"fixed z-[1000]",
"max-h-[40vh] overflow-y-auto",
"rounded-default border border-solid",
"border-slate-200 dark:border-white/10",
"bg-background-light dark:bg-background-dark",
"shadow-lg shadow-slate-200/80 dark:shadow-black/40",
"p-0 m-0 list-none",
)}
style={{
...listStyle,
visibility: listStyle ? "visible" : "hidden",
}}
>
{filtered.length === 0 ? (
<li className="px-3 py-2 text-sm opacity-60">
No options found
@@ -612,8 +679,10 @@ export default function SearchSelect<
);
})
)}
</ul>
) : null}
</ul>,
document.body,
)
: null}
{!validity.isValid && validity.msg ? (
<Span size="smaller" className="text-warning">