"use client"; import type { KeyboardEvent, ReactNode, RefObject } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Badge, Card, Center, Group, Loader, Modal, ScrollArea, SimpleGrid, Stack, Text, TextInput, ThemeIcon, Tooltip, UnstyledButton, useMatches, VisuallyHidden, } from "@mantine/core"; import { useHotkeys } from "@mantine/hooks"; import { IconDeviceMobile, IconHomeFilled, IconLayoutBoard, IconSearch } from "@tabler/icons-react"; import type { RouterOutputs } from "@homarr/api"; import { clientApi } from "@homarr/api/client"; import { useOptionalBoard } from "@homarr/boards/context"; import { useI18n } from "@homarr/translation/client"; import { Link, UserAvatar } from "@homarr/ui"; import { BoardLayoutThumbnail } from "~/components/board/board-layout-thumbnail"; import classes from "./board-switcher.module.css"; export const boardSwitcherHotkey = "shift+c"; interface BoardSwitcherProps { children: (controls: { open: () => void; preload: () => void; hotkey: string }) => ReactNode; } export const BoardSwitcher = ({ children }: BoardSwitcherProps) => { const t = useI18n("board.action.switcher"); const manageBoardsT = useI18n("management.page.board"); const currentBoard = useOptionalBoard(); const [isOpen, setIsOpen] = useState(false); const [search, setSearch] = useState(""); const [activeIndex, setActiveIndex] = useState(0); const responsiveColumnCount = useMatches({ base: 1, sm: 2, lg: 3, xl: 4 }); const optionRefs = useRef>([]); const utils = clientApi.useUtils(); const { data: boards = [], isPending, isError, } = clientApi.board.getManageOverview.useQuery( { fullPreview: true }, { enabled: isOpen, }, ); const switcherBoards = useMemo( () => [ ...boards.filter((board) => board.id !== currentBoard?.id), ...boards.filter((board) => board.id === currentBoard?.id), ], [boards, currentBoard?.id], ); const filteredBoards = useMemo(() => { const normalizedSearch = search.trim().toLocaleLowerCase(); if (normalizedSearch.length === 0) return switcherBoards; return switcherBoards.filter((board) => board.name.toLocaleLowerCase().includes(normalizedSearch)); }, [search, switcherBoards]); const columnCount = Math.max(1, Math.min(filteredBoards.length, responsiveColumnCount)); const modalColumnCount = Math.max(1, Math.min(switcherBoards.length, responsiveColumnCount)); const openSwitcher = useCallback(() => { setIsOpen(true); }, []); const closeSwitcher = useCallback(() => { setIsOpen(false); setSearch(""); setActiveIndex(0); }, []); const preloadBoards = () => void utils.board.getManageOverview.prefetch({ fullPreview: true }); useHotkeys([[boardSwitcherHotkey, openSwitcher, { preventDefault: true }]]); useEffect(() => { if (!isOpen || filteredBoards.length === 0) return; const normalizedIndex = Math.min(activeIndex, filteredBoards.length - 1); if (normalizedIndex !== activeIndex) { setActiveIndex(normalizedIndex); return; } optionRefs.current[normalizedIndex]?.scrollIntoView({ block: "nearest", inline: "nearest" }); }, [activeIndex, filteredBoards.length, isOpen]); const handleModalKeyDown = (event: KeyboardEvent) => { const isSearchInput = event.target instanceof HTMLInputElement && event.target.dataset.boardSwitcherSearch !== undefined; if (!isSearchInput && event.key === "Backspace") { event.preventDefault(); setSearch((current) => current.slice(0, -1)); setActiveIndex(0); return; } if (!isSearchInput && event.key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey) { event.preventDefault(); setSearch((current) => `${current}${event.key}`); setActiveIndex(0); return; } if (filteredBoards.length === 0) return; if (event.key === "Enter") { const target = event.target; if (target instanceof Element && target.closest("[data-board-switcher-option]")) return; event.preventDefault(); optionRefs.current[activeIndex]?.click(); return; } let nextIndex = activeIndex; if (event.key === "ArrowRight") { nextIndex = (activeIndex + 1) % filteredBoards.length; } else if (event.key === "ArrowLeft") { nextIndex = (activeIndex - 1 + filteredBoards.length) % filteredBoards.length; } else if (event.key === "ArrowDown") { const nextRowIndex = activeIndex + columnCount; nextIndex = nextRowIndex; if (nextRowIndex >= filteredBoards.length) nextIndex = activeIndex % columnCount; } else if (event.key === "ArrowUp") { const previousRowIndex = activeIndex - columnCount; if (previousRowIndex >= 0) { nextIndex = previousRowIndex; } else { const lastRowStart = Math.floor((filteredBoards.length - 1) / columnCount) * columnCount; const lastIndexInColumn = lastRowStart + activeIndex; nextIndex = lastIndexInColumn; if (lastIndexInColumn >= filteredBoards.length) nextIndex -= columnCount; } } else { return; } event.preventDefault(); setActiveIndex(nextIndex); requestAnimationFrame(() => optionRefs.current[nextIndex]?.focus({ preventScroll: true })); }; const results = getBoardSwitcherResults({ availableBoardCount: switcherBoards.length, filteredBoards, isError, isPending, search, t, activeIndex, closeSwitcher, setActiveIndex, optionRefs, columnCount, manageBoardsT, }); return ( <> {children({ open: openSwitcher, preload: preloadBoards, hotkey: boardSwitcherHotkey })} {t("keyboard.instructions")} { setSearch(event.currentTarget.value); setActiveIndex(0); }} leftSection={} placeholder={t("title")} aria-label={t("title")} aria-controls="board-switcher-results" radius="xl" classNames={{ input: classes.searchInput }} /> {results} ); }; interface BoardSwitcherResultsProps { availableBoardCount: number; filteredBoards: RouterOutputs["board"]["getManageOverview"]; isError: boolean; isPending: boolean; search: string; t: ReturnType>; activeIndex: number; closeSwitcher: () => void; setActiveIndex: (index: number) => void; optionRefs: RefObject>; columnCount: number; manageBoardsT: ReturnType>; } const getBoardSwitcherResults = ({ availableBoardCount, filteredBoards, isError, isPending, search, t, activeIndex, closeSwitcher, setActiveIndex, optionRefs, columnCount, manageBoardsT, }: BoardSwitcherResultsProps) => { if (isPending) { return (
); } if (isError) { return (
{t("error")}
); } if (availableBoardCount === 0) { return (
{t("empty.title")} {t("empty.description")}
); } if (filteredBoards.length === 0) { return (
{t("search.empty", { search })}
); } return ( {filteredBoards.map((board, index) => ( { optionRefs.current[index] = node; }} className={classes.option} w="100%" maw={240} mx="auto" component={Link} href={`/boards/${encodeURIComponent(board.name)}`} data-active={index === activeIndex} data-board-switcher-option onClick={closeSwitcher} onFocus={() => setActiveIndex(index)} onPointerEnter={() => setActiveIndex(index)} > {board.name} {board.isHome && ( )} {board.isMobileHome && ( )} {board.creator && ( )} ))} ); };