| 1 | import { useLayoutEffect, useState } from "react"; |
| 2 | |
| 3 | |
| 4 | export function useSelectPopup(visible, control, list, count) { |
| 5 | const [position, setPosition] = useState(null); |
| 6 | useLayoutEffect(() => { |
| 7 | if (!visible) return; |
| 8 | const place = () => { |
| 9 | const rect = control.current.getBoundingClientRect(); |
| 10 | const style = getComputedStyle(control.current); |
| 11 | const gap = 4, margin = 8; |
| 12 | const below = window.innerHeight - rect.bottom - gap - margin; |
| 13 | const above = rect.top - gap - margin; |
| 14 | const upward = below < Math.min(list.current.scrollHeight + 8, 224) && above > below; |
| 15 | const maxHeight = Math.max(40, Math.min(280, upward ? above : below)); |
| 16 | const width = Math.min(rect.width, window.innerWidth - margin * 2); |
| 17 | const height = Math.min(list.current.scrollHeight + 8, maxHeight); |
| 18 | const next = { position: "fixed", zIndex: 10000, boxSizing: "border-box", margin: 0, left: Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin)), top: upward ? Math.max(margin, rect.top - gap - height) : rect.bottom + gap, width, maxHeight, fontFamily: style.fontFamily, fontSize: style.fontSize, lineHeight: style.lineHeight }; |
| 19 | for (const key of ["--ink", "--paper", "--line", "--selected", "--focus", "--muted", "--control-cursor"]) next[key] = style.getPropertyValue(key); |
| 20 | setPosition(next); |
| 21 | }; |
| 22 | const scroll = event => { if (!list.current?.contains(event.target)) place(); }; |
| 23 | place(); |
| 24 | const observer = new ResizeObserver(place); |
| 25 | observer.observe(control.current); |
| 26 | window.addEventListener("resize", place); |
| 27 | document.addEventListener("scroll", scroll, true); |
| 28 | return () => { observer.disconnect(); window.removeEventListener("resize", place); document.removeEventListener("scroll", scroll, true); }; |
| 29 | }, [visible, control, list, count]); |
| 30 | return position || { visibility: "hidden" }; |
| 31 | } |