From 2accdc2fad39f2c5c6c86c5d5dbbab0469a338cf Mon Sep 17 00:00:00 2001 From: Thomas Date: Sat, 22 Aug 2026 11:15:40 +0200 Subject: [PATCH] feat: rework board switcher (#6660) * feat: rework board switcher * fix: address board switcher review --- .../after-the-installation.mdx | 6 +- apps/docs/docs/management/boards/index.mdx | 4 + .../boards/(content)/_header-actions.tsx | 60 +--- .../board/board-switcher.module.css | 21 ++ .../src/components/board/board-switcher.tsx | 331 ++++++++++++++++++ .../src/components/onboarding/board-tour.tsx | 10 - .../src/components/user-avatar-menu.tsx | 188 +++++----- packages/translation/src/lang/en.json | 19 + 8 files changed, 482 insertions(+), 157 deletions(-) create mode 100644 apps/nextjs/src/components/board/board-switcher.module.css create mode 100644 apps/nextjs/src/components/board/board-switcher.tsx diff --git a/apps/docs/docs/getting-started/after-the-installation.mdx b/apps/docs/docs/getting-started/after-the-installation.mdx index bcf9b92fa..dcd800dc8 100644 --- a/apps/docs/docs/getting-started/after-the-installation.mdx +++ b/apps/docs/docs/getting-started/after-the-installation.mdx @@ -132,8 +132,8 @@ Here you have the following options in the header: - **Search**: Here you can search for data. You can search for integrations, boards, actions, sites and much more. Some actions may be context dependent (eg. will only show when certain widgets are on your page) - **Edit board**: Clicking this button will toggle edit mode. In this mode you can edit the contents of your board. - **Settings**: Clicking this button will redirect you to a settings page where you can adjust the board settings (page title, colors, ...). -- **Board switcher**: Use this button to open another board that you can access. -- **Profile**: This avatar will be visible on every page. Clicking it will show a menu with actions. +- **Profile**: This avatar will be visible on every page. Its menu includes the board switcher; press `Shift+C` to open + it directly. The current board is left out of the results. When entering the edit mode, you'll get some additional buttons to work with: @@ -369,7 +369,7 @@ Each page highlights the list view and the create action so you know where to fi ### Board tour -When you first open a board, a tour highlights the board header elements: search, edit mode, settings, board switcher, and user menu. +When you first open a board, a tour highlights the board header elements: search, edit mode, settings, and the user menu. ### Tour controls diff --git a/apps/docs/docs/management/boards/index.mdx b/apps/docs/docs/management/boards/index.mdx index 92d709e3c..9ddf9732c 100644 --- a/apps/docs/docs/management/boards/index.mdx +++ b/apps/docs/docs/management/boards/index.mdx @@ -27,6 +27,10 @@ opening it. Containers include their visible widgets and app icons instead of ap Names of boards must be unique because this will be used in the URL to load the desired board. +Press `Shift+C`, or select **Switch board** from the user menu, to open the board switcher. It shows +structural previews of the other boards you can access. Start typing to filter by name, use the arrow keys to move +through the results, and press `Enter` to open the selected board. + ## Create a new board When creating a board, the availability of the board name will be checked for you. diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx index f85d78d27..476706ded 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx @@ -3,18 +3,9 @@ import { useCallback, useEffect, useRef, useState } from "react"; import dynamic from "next/dynamic"; import { useRouter, useSearchParams } from "next/navigation"; -import { Box, Center, Loader, Menu, ScrollArea } from "@mantine/core"; import { useHotkeys } from "@mantine/hooks"; import { notifications } from "@mantine/notifications"; -import { - IconDeviceFloppy, - IconLayoutBoard, - IconPencil, - IconPencilOff, - IconReplace, - IconSettings, - IconX, -} from "@tabler/icons-react"; +import { IconDeviceFloppy, IconPencil, IconPencilOff, IconSettings, IconX } from "@tabler/icons-react"; import { clientApi } from "@homarr/api/client"; import { useRequiredBoard } from "@homarr/boards/context"; @@ -25,8 +16,6 @@ import { hotkeys } from "@homarr/definitions"; import { useConfirmModal } from "@homarr/modals"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { useI18n } from "@homarr/translation/client"; -import { Link } from "@homarr/ui"; - import { useBoardPermissions } from "~/components/board/permissions/client"; import { loadGridEditorAsync, scheduleGridEditorWarmup } from "~/components/board/sections/grid/grid-editor-loader"; import { HeaderButton } from "~/components/layout/header/button"; @@ -56,9 +45,7 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool const t = useI18n("board"); const { hasChangeAccess } = useBoardPermissions(board); - if (!hasChangeAccess) { - return ; - } + if (!hasChangeAccess) return null; return ( <> @@ -73,8 +60,6 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool )} - - ); }; @@ -235,47 +220,6 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => { ); }; -const SelectBoardsMenu = () => { - const t = useI18n("board"); - const [isOpen, setIsOpen] = useState(false); - const utils = clientApi.useUtils(); - const { data: boards = [], isPending } = clientApi.board.getAllBoards.useQuery(undefined, { enabled: isOpen }); - const preloadBoards = () => void utils.board.getAllBoards.prefetch(); - - return ( - - - - - - - - - - - {isPending && ( -
- -
- )} - {boards.map((board) => ( - } - > - {board.name} - - ))} -
-
-
-
-
- ); -}; - const anchorSelector = "a[href]:not([target='_blank'])"; const usePreventLeaveWithDirty = (isDirty: boolean) => { const tBoard = useI18n("board"); diff --git a/apps/nextjs/src/components/board/board-switcher.module.css b/apps/nextjs/src/components/board/board-switcher.module.css new file mode 100644 index 000000000..41894a29b --- /dev/null +++ b/apps/nextjs/src/components/board/board-switcher.module.css @@ -0,0 +1,21 @@ +.content { + outline: none; +} + +.option { + min-width: 0; + border-radius: var(--mantine-radius-md); + outline: none; +} + +.card { + height: 100%; + overflow: hidden; +} + +.option:hover .card, +.option:focus-visible .card, +.option[data-active="true"] .card { + border-color: var(--mantine-primary-color-filled); + box-shadow: var(--mantine-shadow-md); +} diff --git a/apps/nextjs/src/components/board/board-switcher.tsx b/apps/nextjs/src/components/board/board-switcher.tsx new file mode 100644 index 000000000..bb309b6b4 --- /dev/null +++ b/apps/nextjs/src/components/board/board-switcher.tsx @@ -0,0 +1,331 @@ +"use client"; + +import type { KeyboardEvent, ReactNode, RefObject } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + Card, + Center, + Group, + Kbd, + Loader, + Modal, + ScrollArea, + SimpleGrid, + Stack, + Text, + ThemeIcon, + UnstyledButton, + useMatches, + VisuallyHidden, +} from "@mantine/core"; +import { useHotkeys } from "@mantine/hooks"; +import { IconArrowDown, IconArrowRight, IconLayoutBoard, IconReplace } 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 } 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 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(undefined, { + enabled: isOpen, + }); + + const availableBoards = useMemo( + () => boards.filter((board) => board.id !== currentBoard?.id), + [boards, currentBoard?.id], + ); + const filteredBoards = useMemo(() => { + const normalizedSearch = search.trim().toLocaleLowerCase(); + if (normalizedSearch.length === 0) return availableBoards; + return availableBoards.filter((board) => board.name.toLocaleLowerCase().includes(normalizedSearch)); + }, [availableBoards, search]); + const columnCount = Math.max(1, Math.min(filteredBoards.length, responsiveColumnCount)); + + const openSwitcher = useCallback(() => { + setIsOpen(true); + }, []); + const closeSwitcher = useCallback(() => { + setIsOpen(false); + setSearch(""); + setActiveIndex(0); + }, []); + const preloadBoards = () => void utils.board.getManageOverview.prefetch(); + + 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) => { + if (event.key === "Backspace") { + event.preventDefault(); + setSearch((current) => current.slice(0, -1)); + setActiveIndex(0); + return; + } + + if (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: availableBoards.length, + filteredBoards, + isError, + isPending, + search, + t, + activeIndex, + closeSwitcher, + setActiveIndex, + optionRefs, + columnCount, + }); + + return ( + <> + {children({ open: openSwitcher, preload: preloadBoards, hotkey: boardSwitcherHotkey })} + + + + + + {t("title")} + + } + size={1280} + yOffset={32} + overlayProps={{ backgroundOpacity: 0.18, blur: 2 }} + transitionProps={{ transition: "fade", duration: 100, timingFunction: "ease" }} + > + + {t("keyboard.instructions")} + + {results} + + + + {currentBoard && ( + + {t("currentHidden", { name: currentBoard.name })} + + )} + + + + + + + + + {t("keyboard.navigate")} + + Enter + + {t("keyboard.open")} + + + + + + + ); +}; + +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; +} + +const getBoardSwitcherResults = ({ + availableBoardCount, + filteredBoards, + isError, + isPending, + search, + t, + activeIndex, + closeSwitcher, + setActiveIndex, + optionRefs, + columnCount, +}: 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={320} + 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} + + + + + + ))} + + ); +}; diff --git a/apps/nextjs/src/components/onboarding/board-tour.tsx b/apps/nextjs/src/components/onboarding/board-tour.tsx index 3b5af7418..9429c9e52 100644 --- a/apps/nextjs/src/components/onboarding/board-tour.tsx +++ b/apps/nextjs/src/components/onboarding/board-tour.tsx @@ -66,16 +66,6 @@ export const BoardTourProvider = ({ children }: PropsWithChildren) => { /> ), }, - { - id: "board-switcher", - title: t("switcher.title"), - content: ( - - ), - }, { id: "board-user-menu", title: t("userMenu.title"), diff --git a/apps/nextjs/src/components/user-avatar-menu.tsx b/apps/nextjs/src/components/user-avatar-menu.tsx index 5f6165db8..9ec551171 100644 --- a/apps/nextjs/src/components/user-avatar-menu.tsx +++ b/apps/nextjs/src/components/user-avatar-menu.tsx @@ -8,6 +8,7 @@ import { IconHome, IconLogin, IconLogout, + IconReplace, IconSettings, IconRobot, IconTool, @@ -22,6 +23,7 @@ import { Link } from "@homarr/ui"; import { useAuthContext } from "~/app/[locale]/_client-providers/session"; import { useOptionalHomarrAssistant } from "./assistant/assistant-context"; +import { BoardSwitcher } from "./board/board-switcher"; import { CurrentColorSchemeCombobox } from "./color-scheme/current-color-scheme-combobox"; import { CurrentLanguageCombobox } from "./language/current-language-combobox"; import { DockerQuickAccessModal } from "./layout/header/docker-quick-access-modal"; @@ -41,6 +43,7 @@ const formatHotkeyLabel = (hotkey: string, modifierLabel: string) => export const UserAvatarMenu = ({ children, availableUpdates, isDockerEnabled }: UserAvatarMenuProps) => { const t = useI18n("common.userAvatar.menu"); + const tBoard = useI18n("board"); const session = useSession(); const { logoutUrl } = useAuthContext(); @@ -56,98 +59,111 @@ export const UserAvatarMenu = ({ children, availableUpdates, isDockerEnabled }: }, [logoutUrl]); return ( - // We use keepMounted so we can add event listeners to prevent navigating away without saving the board - - - - }> - {t("homeBoard")} - - - - - - - - - - - {Boolean(session.data) && ( - <> - {assistant?.enabled && ( - : - } - rightSection={ - assistant.unreadCount > 0 ? ( - - {assistant.unreadCount > 99 ? "99+" : assistant.unreadCount} - - ) : assistant.isRunning ? ( - - {t("assistantThinking")} - - ) : ( - {formatHotkeyLabel(hotkeys.openAssistant, t("modifier"))} - ) - } - onClick={assistant.open} - > - {t("assistant")} - - )} + + {({ open, preload, hotkey }) => ( + // We use keepMounted so we can add event listeners to prevent navigating away without saving the board + + + + }> + {t("homeBoard")} + } + leftSection={} + rightSection={{formatHotkeyLabel(hotkey, t("modifier"))}} + onClick={open} + onFocus={preload} + onPointerEnter={preload} > - {t("preferences")} + {tBoard("action.switch")} + - }> - {t("management")} + + - {isDockerEnabled && ( - } onClick={() => openDockerModal()}> - {invariantTechnicalLabels.docker} + + + + + {Boolean(session.data) && ( + <> + {assistant?.enabled && ( + : + } + rightSection={ + assistant.unreadCount > 0 ? ( + + {assistant.unreadCount > 99 ? "99+" : assistant.unreadCount} + + ) : assistant.isRunning ? ( + + {t("assistantThinking")} + + ) : ( + {formatHotkeyLabel(hotkeys.openAssistant, t("modifier"))} + ) + } + onClick={assistant.open} + > + {t("assistant")} + + )} + } + > + {t("preferences")} + + + }> + {t("management")} + + {isDockerEnabled && ( + } onClick={() => openDockerModal()}> + {invariantTechnicalLabels.docker} + + )} + + )} + + {session.status === "authenticated" ? ( + } color="red"> + {t("logout")} + + ) : ( + }> + {t("login")} )} - - )} - - {session.status === "authenticated" ? ( - } color="red"> - {t("logout")} - - ) : ( - }> - {t("login")} - - )} - - - - ) : assistant?.unreadCount ? ( - assistant.unreadCount > 99 ? ( - "99+" - ) : ( - assistant.unreadCount - ) - ) : undefined - } - > - {children} - - - + + + + ) : assistant?.unreadCount ? ( + assistant.unreadCount > 99 ? ( + "99+" + ) : ( + assistant.unreadCount + ) + ) : undefined + } + > + {children} + + + + )} + ); }; diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json index 65b423d4f..b67a8a6ab 100644 --- a/packages/translation/src/lang/en.json +++ b/packages/translation/src/lang/en.json @@ -5130,6 +5130,25 @@ "addContent": "Add board content", "settings": "Board settings", "switch": "Switch board", + "switcher": { + "title": "Switch board", + "search": { + "empty": "No boards match \"{search}\"." + }, + "results": "Available boards", + "preview": "Preview of {name} with {count} items", + "currentHidden": "Current board: {name}", + "keyboard": { + "navigate": "Navigate", + "open": "Open", + "instructions": "Type to filter boards. Use the arrow keys to move through results and Enter to open a board." + }, + "empty": { + "title": "No other boards", + "description": "There are no other boards you can access." + }, + "error": "Boards could not be loaded." + }, "create": { "availability": { "checking": "Checking availability…",