|
@@ -1,4 +1,4 @@
|
|
|
-import { useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
|
|
|
|
|
|
+import { useCallback, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
|
|
import { createPortal } from "react-dom";
|
|
import { createPortal } from "react-dom";
|
|
|
import { Check, ChevronDown, ChevronRight, Search, X } from "lucide-react";
|
|
import { Check, ChevronDown, ChevronRight, Search, X } from "lucide-react";
|
|
|
import { cn } from "../../lib/utils";
|
|
import { cn } from "../../lib/utils";
|
|
@@ -19,20 +19,28 @@ export function TreeSelect({ treeData, value, onChange, placeholder = "请选择
|
|
|
const rows = useMemo(() => flatten(treeData), [treeData]), selected = rows.find((row) => row.value === value);
|
|
const rows = useMemo(() => flatten(treeData), [treeData]), selected = rows.find((row) => row.value === value);
|
|
|
const [open, setOpen] = useState(false), [query, setQuery] = useState(""), [active, setActive] = useState("");
|
|
const [open, setOpen] = useState(false), [query, setQuery] = useState(""), [active, setActive] = useState("");
|
|
|
const [expanded, setExpanded] = useState(() => new Set(treeData.map((node) => node.value)));
|
|
const [expanded, setExpanded] = useState(() => new Set(treeData.map((node) => node.value)));
|
|
|
- const [position, setPosition] = useState<{ left: number; top?: number; bottom?: number; width: number; maxHeight: number }>({ left: 0, top: 0, width: 280, maxHeight: 360 });
|
|
|
|
|
const keyword = query.trim().toLocaleLowerCase();
|
|
const keyword = query.trim().toLocaleLowerCase();
|
|
|
const matches = new Set(rows.filter((row) => row.path.toLocaleLowerCase().includes(keyword)).flatMap((row) => [row.value, ...row.ancestors]));
|
|
const matches = new Set(rows.filter((row) => row.path.toLocaleLowerCase().includes(keyword)).flatMap((row) => [row.value, ...row.ancestors]));
|
|
|
const visible = rows.filter((row) => keyword ? matches.has(row.value) : row.ancestors.every((parent) => expanded.has(parent)));
|
|
const visible = rows.filter((row) => keyword ? matches.has(row.value) : row.ancestors.every((parent) => expanded.has(parent)));
|
|
|
const tabStop = visible.some((row) => row.value === active) ? active : visible[0]?.value;
|
|
const tabStop = visible.some((row) => row.value === active) ? active : visible[0]?.value;
|
|
|
|
|
+ const place = useCallback(() => {
|
|
|
|
|
+ if (!trigger.current || !popup.current) return;
|
|
|
|
|
+ const rect = trigger.current.getBoundingClientRect(), gap = 6, margin = 10;
|
|
|
|
|
+ const below = window.innerHeight - rect.bottom - gap - margin, above = rect.top - gap - margin;
|
|
|
|
|
+ const upward = below < 260 && above > below;
|
|
|
|
|
+ const height = Math.max(0, Math.min(360, upward ? above : below));
|
|
|
|
|
+ const width = Math.min(Math.max(rect.width, 280), window.innerWidth - margin * 2);
|
|
|
|
|
+ // 在原生弹层绘制前同步写入坐标,避免等待 React 更新时闪到左上角。
|
|
|
|
|
+ Object.assign(popup.current.style, {
|
|
|
|
|
+ left: `${Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin))}px`,
|
|
|
|
|
+ top: upward ? "auto" : `${rect.bottom + gap}px`,
|
|
|
|
|
+ bottom: upward ? `${window.innerHeight - rect.top + gap}px` : "auto",
|
|
|
|
|
+ width: `${width}px`,
|
|
|
|
|
+ maxHeight: `${height}px`,
|
|
|
|
|
+ });
|
|
|
|
|
+ }, []);
|
|
|
useLayoutEffect(() => {
|
|
useLayoutEffect(() => {
|
|
|
if (!open) return;
|
|
if (!open) return;
|
|
|
- function place() {
|
|
|
|
|
- const rect = trigger.current!.getBoundingClientRect(), gap = 6, margin = 10;
|
|
|
|
|
- const below = window.innerHeight - rect.bottom - gap - margin, above = rect.top - gap - margin;
|
|
|
|
|
- const upward = below < 260 && above > below;
|
|
|
|
|
- const height = Math.max(0, Math.min(360, upward ? above : below)), width = Math.min(Math.max(rect.width, 280), window.innerWidth - margin * 2);
|
|
|
|
|
- setPosition({ left: Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin)), top: upward ? undefined : rect.bottom + gap, bottom: upward ? window.innerHeight - rect.top + gap : undefined, width, maxHeight: height });
|
|
|
|
|
- }
|
|
|
|
|
place();
|
|
place();
|
|
|
setExpanded((current) => new Set([...current, ...(selected?.ancestors || [])]));
|
|
setExpanded((current) => new Set([...current, ...(selected?.ancestors || [])]));
|
|
|
setActive(selected?.value || rows[0]?.value || "");
|
|
setActive(selected?.value || rows[0]?.value || "");
|
|
@@ -40,7 +48,7 @@ export function TreeSelect({ treeData, value, onChange, placeholder = "请选择
|
|
|
const reposition = (event: Event) => { if (!popup.current?.contains(event.target as Node)) place(); };
|
|
const reposition = (event: Event) => { if (!popup.current?.contains(event.target as Node)) place(); };
|
|
|
window.addEventListener("resize", place); window.addEventListener("scroll", reposition, true);
|
|
window.addEventListener("resize", place); window.addEventListener("scroll", reposition, true);
|
|
|
return () => { window.removeEventListener("resize", place); window.removeEventListener("scroll", reposition, true); };
|
|
return () => { window.removeEventListener("resize", place); window.removeEventListener("scroll", reposition, true); };
|
|
|
- }, [open, selected?.value, rows]);
|
|
|
|
|
|
|
+ }, [open, selected?.value, rows, place]);
|
|
|
function close(restoreFocus = true) { popup.current?.hidePopover(); if (restoreFocus) trigger.current?.focus(); }
|
|
function close(restoreFocus = true) { popup.current?.hidePopover(); if (restoreFocus) trigger.current?.focus(); }
|
|
|
function choose(next: string) { if (next && rows.find((row) => row.value === next)?.disabled) return; onChange(next); close(); }
|
|
function choose(next: string) { if (next && rows.find((row) => row.value === next)?.disabled) return; onChange(next); close(); }
|
|
|
function focus(value: string) { setActive(value); items.current.get(value)?.focus(); }
|
|
function focus(value: string) { setActive(value); items.current.get(value)?.focus(); }
|
|
@@ -61,7 +69,7 @@ export function TreeSelect({ treeData, value, onChange, placeholder = "请选择
|
|
|
return <span className={cn("ui-tree-select", className)}>
|
|
return <span className={cn("ui-tree-select", className)}>
|
|
|
<button ref={trigger} name={name} type="button" role="combobox" aria-label={ariaLabel} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required} aria-haspopup="tree" aria-expanded={open} aria-controls={`${id}-tree`} popoverTarget={id} disabled={disabled} className="ui-tree-select-trigger" title={selected?.path || placeholder} onKeyDown={(event) => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); popup.current?.showPopover(); } }}>{icon && <span className="ui-tree-select-icon" aria-hidden="true">{icon}</span>}<span className={cn("ui-tree-select-value", !selected && "is-placeholder")}>{selected?.path || placeholder}</span><ChevronDown size={15} aria-hidden="true" /></button>
|
|
<button ref={trigger} name={name} type="button" role="combobox" aria-label={ariaLabel} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required} aria-haspopup="tree" aria-expanded={open} aria-controls={`${id}-tree`} popoverTarget={id} disabled={disabled} className="ui-tree-select-trigger" title={selected?.path || placeholder} onKeyDown={(event) => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); popup.current?.showPopover(); } }}>{icon && <span className="ui-tree-select-icon" aria-hidden="true">{icon}</span>}<span className={cn("ui-tree-select-value", !selected && "is-placeholder")}>{selected?.path || placeholder}</span><ChevronDown size={15} aria-hidden="true" /></button>
|
|
|
{clearable && value && <button className="ui-tree-select-clear" type="button" disabled={disabled} aria-label={`清空${ariaLabel}`} onClick={(event) => { event.preventDefault(); event.stopPropagation(); choose(""); }}><X size={13} /></button>}
|
|
{clearable && value && <button className="ui-tree-select-clear" type="button" disabled={disabled} aria-label={`清空${ariaLabel}`} onClick={(event) => { event.preventDefault(); event.stopPropagation(); choose(""); }}><X size={13} /></button>}
|
|
|
- {createPortal(<div id={id} ref={popup} popover="auto" className="ui-tree-select-popup" style={position} onToggle={(event) => { const next = event.newState === "open"; setOpen(next); if (!next) setQuery(""); }} onMouseDown={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()} onBlur={(event) => { if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget as Node) && event.relatedTarget !== trigger.current) close(false); }}>
|
|
|
|
|
|
|
+ {createPortal(<div id={id} ref={popup} popover="auto" className="ui-tree-select-popup" onBeforeToggle={(event) => { if (event.newState === "open") place(); }} onToggle={(event) => { const next = event.newState === "open"; setOpen(next); if (!next) setQuery(""); }} onMouseDown={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()} onBlur={(event) => { if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget as Node) && event.relatedTarget !== trigger.current) close(false); }}>
|
|
|
<label className="ui-tree-select-search"><Search size={15} aria-hidden="true" /><input ref={search} aria-label={`搜索${ariaLabel}`} placeholder="搜索区域名称或完整路径" value={query} onChange={(event) => setQuery(event.target.value)} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "ArrowDown" && visible.length) { event.preventDefault(); focus(visible[0].value); } else if (event.key === "ArrowUp" && visible.length) { event.preventDefault(); focus(visible[visible.length - 1].value); } else if (event.key === "Enter") { event.preventDefault(); if (visible.length === 1) choose(visible[0].value); } }} /></label>
|
|
<label className="ui-tree-select-search"><Search size={15} aria-hidden="true" /><input ref={search} aria-label={`搜索${ariaLabel}`} placeholder="搜索区域名称或完整路径" value={query} onChange={(event) => setQuery(event.target.value)} onKeyDown={(event) => { if (isImeComposing(event)) return; if (event.key === "ArrowDown" && visible.length) { event.preventDefault(); focus(visible[0].value); } else if (event.key === "ArrowUp" && visible.length) { event.preventDefault(); focus(visible[visible.length - 1].value); } else if (event.key === "Enter") { event.preventDefault(); if (visible.length === 1) choose(visible[0].value); } }} /></label>
|
|
|
{clearable && <button type="button" className="ui-tree-select-all" aria-pressed={!value} onClick={() => choose("")}><span>{placeholder}</span>{!value && <Check size={15} aria-hidden="true" />}</button>}
|
|
{clearable && <button type="button" className="ui-tree-select-all" aria-pressed={!value} onClick={() => choose("")}><span>{placeholder}</span>{!value && <Check size={15} aria-hidden="true" />}</button>}
|
|
|
<div id={`${id}-tree`} className="ui-tree-select-tree" role="tree" aria-label={`${ariaLabel}树`}>
|
|
<div id={`${id}-tree`} className="ui-tree-select-tree" role="tree" aria-label={`${ariaLabel}树`}>
|