"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { motion, useReducedMotion } from "motion/react"; import { createPortal } from "react-dom"; import { X } from "lucide-react"; import { CanvasIcon } from "./canvas-icon"; import { iconCatalog, iconCategories, searchIcons, type IconSource } from "./icon-catalog"; import styles from "./canvas.module.css"; const columns = 5, rowHeight = 48; export function IconPicker({ close, choose }: { close: () => void; choose: (name: string, label: string) => void }) { const [query, setQuery] = useState(""); const [category, setCategory] = useState("common"); const [source, setSource] = useState("all"); const [scrollTop, setScrollTop] = useState(0); const [height, setHeight] = useState(240); const [focused, setFocused] = useState(0); const search = useRef(null); const grid = useRef(null); const reduce = useReducedMotion(); const matches = useMemo(() => searchIcons(query, query.trim() ? "all" : category, source), [query, category, source]); useEffect(() => { const previous = document.activeElement as HTMLElement | null; search.current?.focus(); const observer = new ResizeObserver(([entry]) => setHeight(entry.contentRect.height)); if (grid.current) observer.observe(grid.current); return () => { observer.disconnect(); previous?.focus(); }; }, []); useEffect(() => { if (grid.current) grid.current.scrollTop = 0; setScrollTop(0); setFocused(0); }, [query, category, source]); const rows = Math.ceil(matches.length / columns); const firstRow = Math.max(0, Math.floor(scrollTop / rowHeight) - 1); const lastRow = Math.min(rows, Math.ceil((scrollTop + height) / rowHeight) + 1); const visible = matches.slice(firstRow * columns, lastRow * columns); function focusIcon(index: number) { const next = Math.max(0, Math.min(matches.length - 1, index)); setFocused(next); const top = Math.floor(next / columns) * rowHeight; if (grid.current) { if (top < grid.current.scrollTop) grid.current.scrollTop = top; else if (top + rowHeight > grid.current.scrollTop + height) grid.current.scrollTop = top + rowHeight - height; setScrollTop(grid.current.scrollTop); } requestAnimationFrame(() => grid.current?.querySelector(`[data-index="${next}"]`)?.focus()); } return createPortal( { event.stopPropagation(); if (event.key === "Escape") close(); }}>
图标
setQuery(event.target.value)} />
{iconCategories.map(([id, label]) => )}
setScrollTop(event.currentTarget.scrollTop)}>
{visible.map(({ name, label, source }, offset) => { const index = firstRow * columns + offset; return ; })}
{!matches.length &&

未找到图标

}
, document.body); }