A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat: add keyboard shortcuts (#2750)
Mohamed Bassemcb6a25b876c5
diff --git a/apps/web/components/dashboard/BulkBookmarksAction.tsx b/apps/web/components/dashboard/BulkBookmarksAction.tsxindex 2657a27f..ff6c5530 100644--- a/apps/web/components/dashboard/BulkBookmarksAction.tsx+++ b/apps/web/components/dashboard/BulkBookmarksAction.tsx@@ -1,6 +1,6 @@"use client";-import React, { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { usePathname } from "next/navigation";import {ActionButton,@@ -9,6 +9,8 @@ import {import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog";import { toast } from "@/components/ui/sonner";import useBulkActionsStore from "@/lib/bulkActions";+import { useBookmarkBulkMutations } from "@/lib/hooks/useBookmarkBulkActions";+import type { UpdateBookmarkProps } from "@/lib/hooks/useBookmarkBulkActions";import { useTranslation } from "@/lib/i18n/client";import {CheckCheck,@@ -23,58 +25,19 @@ import {X,} from "lucide-react";-import {- useDeleteBookmark,- useRecrawlBookmark,- useUpdateBookmark,-} from "@karakeep/shared-react/hooks/bookmarks";-import { useRemoveBookmarkFromList } from "@karakeep/shared-react/hooks/lists";-import { limitConcurrency } from "@karakeep/shared/concurrency";-import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";-import BulkManageListsModal from "./bookmarks/BulkManageListsModal";import BulkTagModal from "./bookmarks/BulkTagModal";import { ArchivedActionIcon, FavouritedActionIcon } from "./bookmarks/icons";-const MAX_CONCURRENT_BULK_ACTIONS = 50;-export default function BulkBookmarksAction() {const { t } = useTranslation();- const {- selectedBookmarkIds,- visibleBookmarks,- isBulkEditEnabled,- listContext: withinListContext,- } = useBulkActionsStore();- const selectedBookmarks = React.useMemo(() => {- const selected = new Set(selectedBookmarkIds);- return visibleBookmarks.filter((bookmark) => selected.has(bookmark.id));- }, [selectedBookmarkIds, visibleBookmarks]);- const setIsBulkEditEnabled = useBulkActionsStore(- (state) => state.setIsBulkEditEnabled,- );- const selectAllBookmarks = useBulkActionsStore((state) => state.selectAll);- const unSelectAllBookmarks = useBulkActionsStore(- (state) => state.unSelectAll,- );- const isEverythingSelected = useBulkActionsStore(- (state) => state.isEverythingSelected,- );const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);const [isRemoveFromListDialogOpen, setIsRemoveFromListDialogOpen] =useState(false);const [manageListsModal, setManageListsModalOpen] = useState(false);const [bulkTagModal, setBulkTagModalOpen] = useState(false);const pathname = usePathname();- const [currentPathname, setCurrentPathname] = useState("");-- // Reset bulk edit state when the route changes- useEffect(() => {- if (pathname !== currentPathname) {- setCurrentPathname(pathname);- setIsBulkEditEnabled(false);- }- }, [pathname, currentPathname]);+ const currentPathnameRef = useRef(pathname);const onError = () => {toast({@@ -83,56 +46,45 @@ export default function BulkBookmarksAction() {description: "There was a problem with your request.",});};-- const deleteBookmarkMutator = useDeleteBookmark({- onSuccess: () => {- setIsBulkEditEnabled(false);- },- onError,- });-- const updateBookmarkMutator = useUpdateBookmark({- onSuccess: () => {- setIsBulkEditEnabled(false);- },+ const bulkActionsStore = useBulkActionsStore();+ const selectedBookmarks = bulkActionsStore.getSelectedBookmarks();+ const {+ isBulkEditEnabled,+ listContext: withinListContext,+ setIsBulkEditEnabled,+ selectAll: selectAllBookmarks,+ unSelectAll: unSelectAllBookmarks,+ isEverythingSelected,+ } = bulkActionsStore;+ const {+ updateBookmarkMutator,+ deleteBookmarkMutator,+ recrawlBookmarkMutator,+ removeBookmarkFromListMutator,+ updateSelectedBookmarks,+ deleteSelectedBookmarks,+ recrawlSelectedLinkBookmarks,+ removeSelectedBookmarksFromList,+ selectedBookmarkLinksText,+ } = useBookmarkBulkMutations({+ selectedBookmarks,+ listContext: withinListContext,onError,- });-- const recrawlBookmarkMutator = useRecrawlBookmark({- onSuccess: () => {+ onBulkEditDone: () => {setIsBulkEditEnabled(false);},- onError,});- const removeBookmarkFromListMutator = useRemoveBookmarkFromList({- onSuccess: () => {+ // Reset bulk edit state when the route changes+ useEffect(() => {+ if (pathname !== currentPathnameRef.current) {+ currentPathnameRef.current = pathname;setIsBulkEditEnabled(false);- },- onError,- });-- interface UpdateBookmarkProps {- favourited?: boolean;- archived?: boolean;- }+ }+ }, [pathname, setIsBulkEditEnabled]);const recrawlBookmarks = async (archiveFullPage: boolean) => {- const links = selectedBookmarks.filter(- (item) => item.content.type === BookmarkTypes.LINK,- );- await Promise.all(- limitConcurrency(- links.map(- (item) => () =>- recrawlBookmarkMutator.mutateAsync({- bookmarkId: item.id,- archiveFullPage,- }),- ),- MAX_CONCURRENT_BULK_ACTIONS,- ),- );+ const links = await recrawlSelectedLinkBookmarks(archiveFullPage);toast({description: `${links.length} bookmarks will be ${archiveFullPage ? "re-crawled and archived!" : "refreshed!"}`,});@@ -152,14 +104,7 @@ export default function BulkBookmarksAction() {});return;}- const copyString = selectedBookmarks- .map((item) => {- return item.content.type === BookmarkTypes.LINK && item.content.url;- })- .filter(Boolean)- .join("\n");-- await navigator.clipboard.writeText(copyString);+ await navigator.clipboard.writeText(selectedBookmarkLinksText());toast({description: `Added ${selectedBookmarks.length} bookmark links into the clipboard!`,@@ -170,34 +115,15 @@ export default function BulkBookmarksAction() {favourited,archived,}: UpdateBookmarkProps) => {- await Promise.all(- limitConcurrency(- selectedBookmarks.map(- (item) => () =>- updateBookmarkMutator.mutateAsync({- bookmarkId: item.id,- favourited,- archived,- }),- ),- MAX_CONCURRENT_BULK_ACTIONS,- ),- );+ await updateSelectedBookmarks({ favourited, archived });+ setIsBulkEditEnabled(false);toast({description: `${selectedBookmarks.length} bookmarks have been updated!`,});};const deleteBookmarks = async () => {- await Promise.all(- limitConcurrency(- selectedBookmarks.map(- (item) => () =>- deleteBookmarkMutator.mutateAsync({ bookmarkId: item.id }),- ),- MAX_CONCURRENT_BULK_ACTIONS,- ),- );+ await deleteSelectedBookmarks();toast({description: `${selectedBookmarks.length} bookmarks have been deleted!`,});@@ -207,18 +133,7 @@ export default function BulkBookmarksAction() {const removeBookmarksFromList = async () => {if (!withinListContext) return;- const results = await Promise.allSettled(- limitConcurrency(- selectedBookmarks.map(- (item) => () =>- removeBookmarkFromListMutator.mutateAsync({- bookmarkId: item.id,- listId: withinListContext.id,- }),- ),- MAX_CONCURRENT_BULK_ACTIONS,- ),- );+ const results = await removeSelectedBookmarksFromList();const successes = results.filter((r) => r.status === "fulfilled").length;if (successes > 0) {diff --git a/apps/web/components/dashboard/GlobalActions.tsx b/apps/web/components/dashboard/GlobalActions.tsxindex d385111a..3beb733d 100644--- a/apps/web/components/dashboard/GlobalActions.tsx+++ b/apps/web/components/dashboard/GlobalActions.tsx@@ -3,17 +3,37 @@import BulkBookmarksAction from "@/components/dashboard/BulkBookmarksAction";import SortOrderToggle from "@/components/dashboard/SortOrderToggle";import ViewOptions from "@/components/dashboard/ViewOptions";+import { useTranslation } from "@/lib/i18n/client";import { useInBookmarkGridStore } from "@/lib/store/useInBookmarkGridStore";+import { useKeyboardNavigationStore } from "@/lib/store/useKeyboardNavigationStore";+import { Keyboard } from "lucide-react";++import { Button } from "../ui/button";export default function GlobalActions() {+ const { t } = useTranslation();const inBookmarkGrid = useInBookmarkGridStore((state) => state.inBookmarkGrid,);+ const setShortcutsDialogOpen = useKeyboardNavigationStore(+ (state) => state.setShortcutsDialogOpen,+ );return (<div className="flex min-w-max flex-wrap overflow-hidden">{inBookmarkGrid && <ViewOptions />}{inBookmarkGrid && <BulkBookmarksAction />}{inBookmarkGrid && <SortOrderToggle />}+ {inBookmarkGrid && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setShortcutsDialogOpen(true)}+ title={t("keyboard_shortcuts.title")}+ aria-label={t("keyboard_shortcuts.title")}+ >+ <Keyboard className="size-4" />+ </Button>+ )}</div>);}diff --git a/apps/web/components/dashboard/KeyboardShortcutsDialog.tsx b/apps/web/components/dashboard/KeyboardShortcutsDialog.tsxnew file mode 100644index 00000000..ad20c86a--- /dev/null+++ b/apps/web/components/dashboard/KeyboardShortcutsDialog.tsx@@ -0,0 +1,176 @@+"use client";++import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Kbd } from "@/components/ui/kbd";+import { useTranslation } from "@/lib/i18n/client";+import { useBookmarkLayout } from "@/lib/userLocalSettings/bookmarksLayout";+import { getOS } from "@/lib/utils";++function ShortcutRow({+ keys,+ description,+}: {+ keys: string[];+ description: string;+}) {+ return (+ <div className="flex items-center justify-between gap-4 py-1.5">+ <span className="text-sm text-muted-foreground">{description}</span>+ <div className="flex items-center gap-1">+ {keys.map((key, i) => (+ <span key={i} className="flex items-center gap-1">+ {i > 0 && <span className="text-xs text-muted-foreground">/</span>}+ <Kbd>{key}</Kbd>+ </span>+ ))}+ </div>+ </div>+ );+}++function ShortcutSection({+ title,+ shortcuts,+}: {+ title: string;+ shortcuts: { keys: string[]; description: string }[];+}) {+ return (+ <div>+ <h3 className="mb-1 text-sm font-semibold">{title}</h3>+ <div className="divide-y divide-border">+ {shortcuts.map((shortcut, i) => (+ <ShortcutRow+ key={i}+ keys={shortcut.keys}+ description={shortcut.description}+ />+ ))}+ </div>+ </div>+ );+}++export default function KeyboardShortcutsDialog({+ open,+ setOpen,+}: {+ open: boolean;+ setOpen: (open: boolean) => void;+}) {+ const { t } = useTranslation();+ const layout = useBookmarkLayout();+ const hasHorizontalNavigation = layout !== "list" && layout !== "compact";+ const searchModifier = getOS() === "macos" ? "⌘" : "Ctrl";++ const sections = [+ {+ title: t("keyboard_shortcuts.sections.navigation"),+ shortcuts: [+ ...(hasHorizontalNavigation+ ? [+ {+ keys: ["h", "←"],+ description: t("keyboard_shortcuts.move_left"),+ },+ ]+ : []),+ {+ keys: ["j", "↓"],+ description: t("keyboard_shortcuts.move_down"),+ },+ {+ keys: ["k", "↑"],+ description: t("keyboard_shortcuts.move_up"),+ },+ ...(hasHorizontalNavigation+ ? [+ {+ keys: ["l", "→"],+ description: t("keyboard_shortcuts.move_right"),+ },+ ]+ : []),+ {+ keys: ["o", "Enter"],+ description: t("keyboard_shortcuts.open_bookmark"),+ },+ {+ keys: ["Esc"],+ description: t("keyboard_shortcuts.clear_focus"),+ },+ ],+ },+ {+ title: t("keyboard_shortcuts.sections.actions"),+ shortcuts: [+ {+ keys: ["f"],+ description: t("keyboard_shortcuts.toggle_favorite"),+ },+ {+ keys: ["a"],+ description: t("keyboard_shortcuts.toggle_archive"),+ },+ {+ keys: ["#"],+ description: t("keyboard_shortcuts.delete_bookmark"),+ },+ ],+ },+ {+ title: t("keyboard_shortcuts.sections.selection"),+ shortcuts: [+ {+ keys: ["x"],+ description: t("keyboard_shortcuts.toggle_selection"),+ },+ {+ keys: ["* a"],+ description: t("keyboard_shortcuts.select_all"),+ },+ {+ keys: ["* n"],+ description: t("keyboard_shortcuts.deselect_all"),+ },+ ],+ },+ {+ title: t("keyboard_shortcuts.sections.other"),+ shortcuts: [+ {+ keys: ["?"],+ description: t("keyboard_shortcuts.show_help"),+ },+ {+ keys: [`${searchModifier} K`],+ description: t("keyboard_shortcuts.focus_search_alt"),+ },+ ],+ },+ ];++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{t("keyboard_shortcuts.title")}</DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-5">+ {sections.map((section, i) => (+ <ShortcutSection+ key={i}+ title={section.title}+ shortcuts={section.shortcuts}+ />+ ))}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/components/dashboard/bookmarks/AssetCard.tsx b/apps/web/components/dashboard/bookmarks/AssetCard.tsxindex c906f2a7..d20e7285 100644--- a/apps/web/components/dashboard/bookmarks/AssetCard.tsx+++ b/apps/web/components/dashboard/bookmarks/AssetCard.tsx@@ -68,9 +68,11 @@ function AssetImage({export default function AssetCard({bookmark: bookmarkedAsset,className,+ bookmarkIndex,}: {bookmark: ZBookmarkTypeAsset;className?: string;+ bookmarkIndex?: number;}) {return (<BookmarkLayoutAdaptingCard@@ -82,6 +84,7 @@ export default function AssetCard({}bookmark={bookmarkedAsset}className={className}+ bookmarkIndex={bookmarkIndex}wrapTags={true}image={(_layout, className) => (<div className="relative size-full flex-1">diff --git a/apps/web/components/dashboard/bookmarks/BookmarkCard.tsx b/apps/web/components/dashboard/bookmarks/BookmarkCard.tsxindex b120e0b1..4065292e 100644--- a/apps/web/components/dashboard/bookmarks/BookmarkCard.tsx+++ b/apps/web/components/dashboard/bookmarks/BookmarkCard.tsx@@ -12,9 +12,11 @@ import UnknownCard from "./UnknownCard";export default function BookmarkCard({bookmark: initialData,className,+ bookmarkIndex,}: {bookmark: ZBookmark;className?: string;+ bookmarkIndex?: number;}) {const api = useTRPC();const { data: bookmark } = useQuery(@@ -40,6 +42,7 @@ export default function BookmarkCard({return (<LinkCardclassName={className}+ bookmarkIndex={bookmarkIndex}bookmark={{ ...bookmark, content: bookmark.content }}/>);@@ -47,6 +50,7 @@ export default function BookmarkCard({return (<TextCardclassName={className}+ bookmarkIndex={bookmarkIndex}bookmark={{ ...bookmark, content: bookmark.content }}/>);@@ -54,10 +58,17 @@ export default function BookmarkCard({return (<AssetCardclassName={className}+ bookmarkIndex={bookmarkIndex}bookmark={{ ...bookmark, content: bookmark.content }}/>);case BookmarkTypes.UNKNOWN:- return <UnknownCard className={className} bookmark={bookmark} />;+ return (+ <UnknownCard+ className={className}+ bookmarkIndex={bookmarkIndex}+ bookmark={bookmark}+ />+ );}}diff --git a/apps/web/components/dashboard/bookmarks/BookmarkLayoutAdaptingCard.tsx b/apps/web/components/dashboard/bookmarks/BookmarkLayoutAdaptingCard.tsxindex 8a1b4258..b76b0d91 100644--- a/apps/web/components/dashboard/bookmarks/BookmarkLayoutAdaptingCard.tsx+++ b/apps/web/components/dashboard/bookmarks/BookmarkLayoutAdaptingCard.tsx@@ -53,6 +53,7 @@ interface Props {className?: string;fitHeight?: boolean;wrapTags: boolean;+ bookmarkIndex?: number;}function BottomRow({@@ -288,6 +289,7 @@ function ListView({content,footer,className,+ bookmarkIndex,}: Props) {const { showNotes, showTags, showTitle, imageFit } =useBookmarkDisplaySettings();@@ -303,6 +305,7 @@ function ListView({"group relative flex max-h-96 gap-4 overflow-hidden rounded-lg p-2",className,)}+ data-bookmark-index={bookmarkIndex}><MultiBookmarkSelector bookmark={bookmark} /><OwnerIndicator bookmark={bookmark} />@@ -348,6 +351,7 @@ function GridView({wrapTags,layout,fitHeight = false,+ bookmarkIndex,}: Props & { layout: BookmarksLayoutTypes }) {const { showNotes, showTags, showTitle, imageFit } =useBookmarkDisplaySettings();@@ -368,6 +372,7 @@ function GridView({className,fitHeight && layout != "grid" ? "max-h-96" : "h-96",)}+ data-bookmark-index={bookmarkIndex}><MultiBookmarkSelector bookmark={bookmark} /><OwnerIndicator bookmark={bookmark} />@@ -399,7 +404,13 @@ function GridView({);}-function CompactView({ bookmark, title, footer, className }: Props) {+function CompactView({+ bookmark,+ title,+ footer,+ className,+ bookmarkIndex,+}: Props) {const { showTitle } = useBookmarkDisplaySettings();return (<div@@ -408,6 +419,7 @@ function CompactView({ bookmark, title, footer, className }: Props) {className,"max-h-96",)}+ data-bookmark-index={bookmarkIndex}><MultiBookmarkSelector bookmark={bookmark} /><OwnerIndicator bookmark={bookmark} />diff --git a/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx b/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsxindex b3a1881a..8599b14f 100644--- a/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx+++ b/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx@@ -1,13 +1,19 @@-import { useEffect, useMemo } from "react";+import { memo, useEffect, useMemo, useState } from "react";+import KeyboardShortcutsDialog from "@/components/dashboard/KeyboardShortcutsDialog";import NoBookmarksBanner from "@/components/dashboard/bookmarks/NoBookmarksBanner";import { ActionButton } from "@/components/ui/action-button";+import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog";import useBulkActionsStore from "@/lib/bulkActions";+import { useBookmarkKeyboardNavigation } from "@/lib/hooks/useBookmarkKeyboardNavigation";+import { useTranslation } from "@/lib/i18n/client";import { useInBookmarkGridStore } from "@/lib/store/useInBookmarkGridStore";+import { useKeyboardNavigationStore } from "@/lib/store/useKeyboardNavigationStore";import {bookmarkLayoutSwitch,useBookmarkLayout,useGridColumns,} from "@/lib/userLocalSettings/bookmarksLayout";+import { cn } from "@/lib/utils";import tailwindConfig from "@/tailwind.config";import { Slot } from "@radix-ui/react-slot";import { ErrorBoundary } from "react-error-boundary";@@ -22,14 +28,52 @@ import BookmarkCard from "./BookmarkCard";import EditorCard from "./EditorCard";import UnknownCard from "./UnknownCard";-function StyledBookmarkCard({ children }: { children: React.ReactNode }) {+function StyledBookmarkCard({+ children,+ className,+ ...props+}: {+ children: React.ReactNode;+ className?: string;+} & React.HTMLAttributes<HTMLElement>) {return (- <Slot className="mb-4 border border-border bg-card duration-300 ease-in hover:shadow-lg hover:transition-all">+ <Slot+ className={cn(+ "mb-4 border border-border bg-card hover:shadow-lg hover:transition-shadow",+ className,+ )}+ {...props}+ >{children}</Slot>);}+const BookmarkGridItem = memo(function BookmarkGridItem({+ bookmark,+ index,+}: {+ bookmark: ZBookmark;+ index: number;+}) {+ const isFocused = useKeyboardNavigationStore(+ (state) => state.isNavigating && state.focusedIndex === index,+ );++ return (+ <ErrorBoundary fallback={<UnknownCard bookmark={bookmark} />}>+ <StyledBookmarkCard+ className={cn(+ isFocused &&+ "ring-2 ring-primary ring-offset-2 ring-offset-background",+ )}+ >+ <BookmarkCard bookmark={bookmark} bookmarkIndex={index} />+ </StyledBookmarkCard>+ </ErrorBoundary>+ );+});+function getBreakpointConfig(userColumns: number) {const fullConfig = resolveConfig(tailwindConfig);@@ -48,6 +92,57 @@ function getBreakpointConfig(userColumns: number) {return breakpointColumnsObj;}+function getColumnsForViewport(userColumns: number, viewportWidth: number) {+ const fullConfig = resolveConfig(tailwindConfig);+ const screens = fullConfig.theme.screens;+ const lg = parseInt(screens.lg);+ const md = parseInt(screens.md);+ const sm = parseInt(screens.sm);++ if (viewportWidth <= sm) {+ return 1;+ }+ if (viewportWidth <= md) {+ return Math.max(1, Math.min(userColumns, 2));+ }+ if (viewportWidth <= lg) {+ return Math.max(1, userColumns - 1);+ }+ return userColumns;+}++function useActiveGridColumns(userColumns: number) {+ const [activeColumns, setActiveColumns] = useState(userColumns);++ useEffect(() => {+ let animationFrame: number | null = null;+ const updateActiveColumns = () => {+ if (animationFrame !== null) {+ return;+ }+ animationFrame = window.requestAnimationFrame(() => {+ animationFrame = null;+ setActiveColumns(getColumnsForViewport(userColumns, window.innerWidth));+ });+ };++ const updateActiveColumnsImmediately = () => {+ setActiveColumns(getColumnsForViewport(userColumns, window.innerWidth));+ };++ updateActiveColumnsImmediately();+ window.addEventListener("resize", updateActiveColumns);+ return () => {+ window.removeEventListener("resize", updateActiveColumns);+ if (animationFrame !== null) {+ window.cancelAnimationFrame(animationFrame);+ }+ };+ }, [userColumns]);++ return activeColumns;+}+export default function BookmarksGrid({bookmarks,hasNextPage = false,@@ -61,10 +156,17 @@ export default function BookmarksGrid({isFetchingNextPage?: boolean;fetchNextPage?: () => void;}) {+ const { t } = useTranslation();const layout = useBookmarkLayout();const gridColumns = useGridColumns();- const bulkActionsStore = useBulkActionsStore();- const inBookmarkGrid = useInBookmarkGridStore();+ const activeGridColumns = useActiveGridColumns(gridColumns);+ const setVisibleBookmarks = useBulkActionsStore(+ (state) => state.setVisibleBookmarks,+ );+ const setListContext = useBulkActionsStore((state) => state.setListContext);+ const setInBookmarkGrid = useInBookmarkGridStore(+ (state) => state.setInBookmarkGrid,+ );const withinListContext = useBookmarkListContext();const breakpointConfig = useMemo(() => getBreakpointConfig(gridColumns),@@ -72,31 +174,60 @@ export default function BookmarksGrid({);const { ref: loadMoreRef, inView: loadMoreButtonInView } = useInView();+ // For list/compact layouts, navigation is single-column+ const isListLayout = layout === "list" || layout === "compact";+ const navColumns = isListLayout ? 1 : activeGridColumns;++ const {+ helpDialogOpen,+ setHelpDialogOpen,+ deleteDialogOpen,+ setDeleteDialogOpen,+ isBulkDelete,+ deleteCount,+ confirmDelete,+ isDeletePending,+ } = useBookmarkKeyboardNavigation({+ bookmarks,+ columns: navColumns,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ });+useEffect(() => {- bulkActionsStore.setVisibleBookmarks(bookmarks);- bulkActionsStore.setListContext(withinListContext);+ setVisibleBookmarks(bookmarks);+ setListContext(withinListContext);return () => {- bulkActionsStore.setVisibleBookmarks([]);- bulkActionsStore.setListContext(undefined);+ setVisibleBookmarks([]);+ setListContext(undefined);};- }, [bookmarks, withinListContext?.id]);+ }, [bookmarks, setListContext, setVisibleBookmarks, withinListContext]);useEffect(() => {- inBookmarkGrid.setInBookmarkGrid(true);+ setInBookmarkGrid(true);return () => {- inBookmarkGrid.setInBookmarkGrid(false);+ setInBookmarkGrid(false);};- }, []);+ }, [setInBookmarkGrid]);useEffect(() => {if (loadMoreButtonInView && hasNextPage && !isFetchingNextPage) {fetchNextPage();}- }, [loadMoreButtonInView]);+ }, [fetchNextPage, hasNextPage, isFetchingNextPage, loadMoreButtonInView]);if (bookmarks.length == 0 && !showEditorCard) {- return <NoBookmarksBanner />;+ return (+ <>+ <NoBookmarksBanner />+ <KeyboardShortcutsDialog+ open={helpDialogOpen}+ setOpen={setHelpDialogOpen}+ />+ </>+ );}const children = [@@ -105,12 +236,8 @@ export default function BookmarksGrid({<EditorCard /></StyledBookmarkCard>),- ...bookmarks.map((b) => (- <ErrorBoundary key={b.id} fallback={<UnknownCard bookmark={b} />}>- <StyledBookmarkCard>- <BookmarkCard bookmark={b} />- </StyledBookmarkCard>- </ErrorBoundary>+ ...bookmarks.map((bookmark, index) => (+ <BookmarkGridItem key={bookmark.id} bookmark={bookmark} index={index} />)),];return (@@ -150,6 +277,34 @@ export default function BookmarksGrid({</ActionButton></div>)}++ <KeyboardShortcutsDialog+ open={helpDialogOpen}+ setOpen={setHelpDialogOpen}+ />++ <ActionConfirmingDialog+ open={deleteDialogOpen}+ setOpen={setDeleteDialogOpen}+ title={t("dialogs.bookmarks.delete_confirmation_title")}+ description={+ isBulkDelete+ ? t("dialogs.bookmarks.bulk_delete_confirmation_description", {+ count: deleteCount,+ })+ : t("dialogs.bookmarks.delete_confirmation_description")+ }+ actionButton={() => (+ <ActionButton+ type="button"+ variant="destructive"+ loading={isDeletePending}+ onClick={confirmDelete}+ >+ {t("actions.delete")}+ </ActionButton>+ )}+ /></>);}diff --git a/apps/web/components/dashboard/bookmarks/LinkCard.tsx b/apps/web/components/dashboard/bookmarks/LinkCard.tsxindex 778166b5..b0ddfac3 100644--- a/apps/web/components/dashboard/bookmarks/LinkCard.tsx+++ b/apps/web/components/dashboard/bookmarks/LinkCard.tsx@@ -90,9 +90,11 @@ function LinkImage({export default function LinkCard({bookmark: bookmarkLink,className,+ bookmarkIndex,}: {bookmark: ZBookmarkTypeLink;className?: string;+ bookmarkIndex?: number;}) {return (<BookmarkLayoutAdaptingCard@@ -104,6 +106,7 @@ export default function LinkCard({<LinkImage className={className} bookmark={bookmarkLink} />)}className={className}+ bookmarkIndex={bookmarkIndex}/>);}diff --git a/apps/web/components/dashboard/bookmarks/TextCard.tsx b/apps/web/components/dashboard/bookmarks/TextCard.tsxindex 3be3a093..f8d4851b 100644--- a/apps/web/components/dashboard/bookmarks/TextCard.tsx+++ b/apps/web/components/dashboard/bookmarks/TextCard.tsx@@ -16,9 +16,11 @@ import FooterLinkURL from "./FooterLinkURL";export default function TextCard({bookmark,className,+ bookmarkIndex,}: {bookmark: ZBookmarkTypeText;className?: string;+ bookmarkIndex?: number;}) {const banner = bookmark.assets.find((a) => a.assetType == "bannerImage");return (@@ -38,6 +40,7 @@ export default function TextCard({wrapTags={true}bookmark={bookmark}className={className}+ bookmarkIndex={bookmarkIndex}fitHeight={true}image={(layout, className) =>bookmarkLayoutSwitch(layout, {diff --git a/apps/web/components/dashboard/bookmarks/UnknownCard.tsx b/apps/web/components/dashboard/bookmarks/UnknownCard.tsxindex 1d0ea8fb..d2e35093 100644--- a/apps/web/components/dashboard/bookmarks/UnknownCard.tsx+++ b/apps/web/components/dashboard/bookmarks/UnknownCard.tsx@@ -10,9 +10,11 @@ import { BookmarkLayoutAdaptingCard } from "./BookmarkLayoutAdaptingCard";export default function UnknownCard({bookmark,className,+ bookmarkIndex,}: {bookmark: ZBookmark;className?: string;+ bookmarkIndex?: number;}) {const { t } = useTranslation();return (@@ -20,6 +22,7 @@ export default function UnknownCard({title={bookmark.title}bookmark={bookmark}className={className}+ bookmarkIndex={bookmarkIndex}wrapTags={false}image={(_layout) => (<div className="flex size-full flex-1 flex-col items-center justify-center bg-red-50 dark:bg-red-950/10">diff --git a/apps/web/lib/bulkActions.test.ts b/apps/web/lib/bulkActions.test.tsnew file mode 100644index 00000000..7d67d577--- /dev/null+++ b/apps/web/lib/bulkActions.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it } from "vitest";++import type { ZBookmark } from "@karakeep/shared/types/bookmarks";++import useBulkActionsStore from "./bulkActions";++function bookmark(id: string, userId = "user-1") {+ return { id, userId } as ZBookmark;+}++describe("useBulkActionsStore", () => {+ beforeEach(() => {+ useBulkActionsStore.setState({+ selectedBookmarkIds: [],+ visibleBookmarks: [],+ isBulkEditEnabled: false,+ listContext: undefined,+ });+ });++ it("toggles bookmark selection", () => {+ useBulkActionsStore.getState().toggleBookmark("a");+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual(["a"]);++ useBulkActionsStore.getState().toggleBookmark("a");+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual([]);+ });++ it("selects and unselects all visible bookmarks", () => {+ useBulkActionsStore+ .getState()+ .setVisibleBookmarks([bookmark("a"), bookmark("b")]);++ useBulkActionsStore.getState().selectAll();+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual([+ "a",+ "b",+ ]);+ expect(useBulkActionsStore.getState().isEverythingSelected()).toBe(true);++ useBulkActionsStore.getState().unSelectAll();+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual([]);+ expect(useBulkActionsStore.getState().isEverythingSelected()).toBe(false);+ });++ it("clears selection when bulk edit mode changes", () => {+ useBulkActionsStore.setState({+ isBulkEditEnabled: false,+ selectedBookmarkIds: ["a"],+ });++ useBulkActionsStore.getState().setIsBulkEditEnabled(true);+ expect(useBulkActionsStore.getState().isBulkEditEnabled).toBe(true);+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual([]);+ });++ it("preserves selection when bulk edit mode is set to the current value", () => {+ useBulkActionsStore.setState({+ isBulkEditEnabled: true,+ selectedBookmarkIds: ["a"],+ });++ useBulkActionsStore.getState().setIsBulkEditEnabled(true);+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual(["a"]);+ });++ it("derives selected bookmarks from visible bookmarks in visible order", () => {+ useBulkActionsStore.setState({+ selectedBookmarkIds: ["c", "a"],+ visibleBookmarks: [bookmark("a"), bookmark("b"), bookmark("c")],+ });++ expect(+ useBulkActionsStore+ .getState()+ .getSelectedBookmarks()+ .map((item) => item.id),+ ).toEqual(["a", "c"]);+ });++ it("filters selected actionable bookmarks with the provided predicate", () => {+ useBulkActionsStore.setState({+ selectedBookmarkIds: ["owned", "shared"],+ visibleBookmarks: [+ bookmark("owned", "user-1"),+ bookmark("shared", "user-2"),+ ],+ });++ expect(+ useBulkActionsStore+ .getState()+ .getSelectedActionableBookmarks((item) => item.userId === "user-1")+ .map((item) => item.id),+ ).toEqual(["owned"]);+ });+});diff --git a/apps/web/lib/bulkActions.ts b/apps/web/lib/bulkActions.tsindex b19caf01..1130f97b 100644--- a/apps/web/lib/bulkActions.ts+++ b/apps/web/lib/bulkActions.ts@@ -10,11 +10,16 @@ interface BookmarkState {isBulkEditEnabled: boolean;setIsBulkEditEnabled: (isEnabled: boolean) => void;toggleBookmark: (bookmarkId: string) => void;+ setSelectedBookmarkIds: (bookmarkIds: string[]) => void;setVisibleBookmarks: (visibleBookmarks: ZBookmark[]) => void;selectAll: () => void;unSelectAll: () => void;isBookmarkSelected: (bookmarkId: string) => boolean;isEverythingSelected: () => boolean;+ getSelectedBookmarks: () => ZBookmark[];+ getSelectedActionableBookmarks: (+ canActOnBookmark: (bookmark: ZBookmark) => boolean,+ ) => ZBookmark[];setListContext: (listContext: ZBookmarkList | undefined) => void;listContext: ZBookmarkList | undefined;}@@ -39,6 +44,10 @@ const useBulkActionsStore = create<BookmarkState>((set, get) => ({}},+ setSelectedBookmarkIds: (bookmarkIds: string[]) => {+ set({ selectedBookmarkIds: bookmarkIds });+ },+selectAll: () => {set({ selectedBookmarkIds: get().visibleBookmarks.map((b) => b.id) });},@@ -59,9 +68,22 @@ const useBulkActionsStore = create<BookmarkState>((set, get) => ({return visibleBookmarks.every((bookmark) => selected.has(bookmark.id));},+ getSelectedBookmarks: () => {+ const { selectedBookmarkIds, visibleBookmarks } = get();+ const selected = new Set(selectedBookmarkIds);+ return visibleBookmarks.filter((bookmark) => selected.has(bookmark.id));+ },++ getSelectedActionableBookmarks: (canActOnBookmark) => {+ return get().getSelectedBookmarks().filter(canActOnBookmark);+ },+setIsBulkEditEnabled: (isEnabled) => {- set({ isBulkEditEnabled: isEnabled });- set({ selectedBookmarkIds: [] });+ const state = get();+ if (state.isBulkEditEnabled === isEnabled) {+ return;+ }+ set({ isBulkEditEnabled: isEnabled, selectedBookmarkIds: [] });},setVisibleBookmarks: (visibleBookmarks: ZBookmark[]) => {diff --git a/apps/web/lib/hooks/useBookmarkBulkActions.test.ts b/apps/web/lib/hooks/useBookmarkBulkActions.test.tsnew file mode 100644index 00000000..61f79caf--- /dev/null+++ b/apps/web/lib/hooks/useBookmarkBulkActions.test.ts@@ -0,0 +1,202 @@+// @vitest-environment jsdom++import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ZBookmark } from "@karakeep/shared/types/bookmarks";+import type { ZBookmarkList } from "@karakeep/shared/types/lists";++const mutators = vi.hoisted(() => ({+ updateMutateAsync: vi.fn(),+ deleteMutateAsync: vi.fn(),+ recrawlMutateAsync: vi.fn(),+ removeFromListMutateAsync: vi.fn(),+}));++vi.mock("@karakeep/shared-react/hooks/bookmarks", () => ({+ useUpdateBookmark: () => ({+ mutateAsync: mutators.updateMutateAsync,+ isPending: false,+ }),+ useDeleteBookmark: () => ({+ mutateAsync: mutators.deleteMutateAsync,+ isPending: false,+ }),+ useRecrawlBookmark: () => ({+ mutateAsync: mutators.recrawlMutateAsync,+ isPending: false,+ }),+}));++vi.mock("@karakeep/shared-react/hooks/lists", () => ({+ useRemoveBookmarkFromList: () => ({+ mutateAsync: mutators.removeFromListMutateAsync,+ isPending: false,+ }),+}));++import { useBookmarkBulkMutations } from "./useBookmarkBulkActions";++function bookmark(id: string, userId = "user-1", type = "link") {+ return {+ id,+ userId,+ favourited: false,+ archived: false,+ content: {+ type,+ url: `https://example.com/${id}`,+ },+ } as ZBookmark;+}++describe("useBookmarkBulkMutations", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mutators.updateMutateAsync.mockImplementation((input) =>+ Promise.resolve({ id: input.bookmarkId }),+ );+ mutators.deleteMutateAsync.mockResolvedValue({});+ mutators.recrawlMutateAsync.mockResolvedValue({});+ mutators.removeFromListMutateAsync.mockResolvedValue({});+ });++ it("updates each actionable selected bookmark", async () => {+ const selected = [bookmark("a"), bookmark("b")];+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ await act(async () => {+ await result.current.updateSelectedBookmarks({ archived: true });+ });++ expect(mutators.updateMutateAsync).toHaveBeenCalledTimes(2);+ expect(mutators.updateMutateAsync).toHaveBeenNthCalledWith(1, {+ bookmarkId: "a",+ archived: true,+ });+ expect(mutators.updateMutateAsync).toHaveBeenNthCalledWith(2, {+ bookmarkId: "b",+ archived: true,+ });+ });++ it("sets a boolean field to enabled unless all selected bookmarks already have it", async () => {+ const selected = [+ { ...bookmark("a"), favourited: false },+ { ...bookmark("b"), favourited: true },+ ];+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ await act(async () => {+ await result.current.setSelectedBookmarksToNextState("favourited");+ });++ expect(mutators.updateMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "a",+ favourited: true,+ });+ expect(mutators.updateMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "b",+ favourited: true,+ });+ });++ it("sets a boolean field to disabled when all selected bookmarks already have it", async () => {+ const selected = [+ { ...bookmark("a"), archived: true },+ { ...bookmark("b"), archived: true },+ ];+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ await act(async () => {+ await result.current.setSelectedBookmarksToNextState("archived");+ });++ expect(mutators.updateMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "a",+ archived: false,+ });+ expect(mutators.updateMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "b",+ archived: false,+ });+ });++ it("deletes selected actionable bookmarks with settled results", async () => {+ const selected = [bookmark("a"), bookmark("b")];+ mutators.deleteMutateAsync+ .mockResolvedValueOnce({})+ .mockRejectedValueOnce(new Error("failed"));+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ let settled: PromiseSettledResult<unknown>[] = [];+ await act(async () => {+ settled = await result.current.deleteSelectedBookmarksSettled();+ });++ expect(mutators.deleteMutateAsync).toHaveBeenCalledTimes(2);+ expect(settled.map((item) => item.status)).toEqual([+ "fulfilled",+ "rejected",+ ]);+ });++ it("recrawls only selected link bookmarks", async () => {+ const selected = [bookmark("link"), bookmark("asset", "user-1", "asset")];+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ let links: ZBookmark[] = [];+ await act(async () => {+ links = await result.current.recrawlSelectedLinkBookmarks(true);+ });++ expect(links.map((item) => item.id)).toEqual(["link"]);+ expect(mutators.recrawlMutateAsync).toHaveBeenCalledTimes(1);+ expect(mutators.recrawlMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "link",+ archiveFullPage: true,+ });+ });++ it("removes selected bookmarks from the provided list context", async () => {+ const selected = [bookmark("a"), bookmark("b")];+ const listContext = { id: "list-1" } as ZBookmarkList;+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected, listContext }),+ );++ await act(async () => {+ await result.current.removeSelectedBookmarksFromList();+ });++ expect(mutators.removeFromListMutateAsync).toHaveBeenCalledTimes(2);+ expect(mutators.removeFromListMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "a",+ listId: "list-1",+ });+ expect(mutators.removeFromListMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "b",+ listId: "list-1",+ });+ });++ it("builds clipboard text from selected link bookmarks", () => {+ const selected = [bookmark("a"), bookmark("asset", "user-1", "asset")];+ const { result } = renderHook(() =>+ useBookmarkBulkMutations({ selectedBookmarks: selected }),+ );++ expect(result.current.selectedBookmarkLinksText()).toBe(+ "https://example.com/a",+ );+ });+});diff --git a/apps/web/lib/hooks/useBookmarkBulkActions.ts b/apps/web/lib/hooks/useBookmarkBulkActions.tsnew file mode 100644index 00000000..4a877557--- /dev/null+++ b/apps/web/lib/hooks/useBookmarkBulkActions.ts@@ -0,0 +1,190 @@+"use client";++import { useCallback } from "react";++import { limitConcurrency } from "@karakeep/shared/concurrency";+import type { ZBookmark } from "@karakeep/shared/types/bookmarks";+import type { ZBookmarkList } from "@karakeep/shared/types/lists";+import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";+import {+ useDeleteBookmark,+ useRecrawlBookmark,+ useUpdateBookmark,+} from "@karakeep/shared-react/hooks/bookmarks";+import { useRemoveBookmarkFromList } from "@karakeep/shared-react/hooks/lists";++const MAX_CONCURRENT_BULK_ACTIONS = 50;++export interface UpdateBookmarkProps {+ favourited?: boolean;+ archived?: boolean;+}++export function useBookmarkBulkMutations({+ selectedBookmarks,+ selectedActionableBookmarks = () => selectedBookmarks,+ listContext,+ onError,+ onBulkEditDone,+}: {+ selectedBookmarks: ZBookmark[];+ selectedActionableBookmarks?: () => ZBookmark[];+ listContext?: ZBookmarkList;+ onError?: () => void;+ onBulkEditDone?: () => void;+}) {+ const updateBookmarkMutator = useUpdateBookmark({+ onSuccess: onBulkEditDone,+ onError,+ });+ const deleteBookmarkMutator = useDeleteBookmark({+ onSuccess: onBulkEditDone,+ onError,+ });+ const recrawlBookmarkMutator = useRecrawlBookmark({+ onSuccess: onBulkEditDone,+ onError,+ });+ const removeBookmarkFromListMutator = useRemoveBookmarkFromList({+ onSuccess: onBulkEditDone,+ onError,+ });++ const selectedLinkBookmarks = useCallback(+ () =>+ selectedBookmarks.filter(+ (bookmark) => bookmark.content.type === BookmarkTypes.LINK,+ ),+ [selectedBookmarks],+ );++ const updateSelectedBookmarks = useCallback(+ async (+ update: UpdateBookmarkProps,+ bookmarks = selectedActionableBookmarks(),+ ) => {+ if (bookmarks.length === 0) {+ return [];+ }++ return Promise.all(+ limitConcurrency(+ bookmarks.map(+ (bookmark) => () =>+ updateBookmarkMutator.mutateAsync({+ bookmarkId: bookmark.id,+ ...update,+ }),+ ),+ MAX_CONCURRENT_BULK_ACTIONS,+ ),+ );+ },+ [selectedActionableBookmarks, updateBookmarkMutator],+ );++ const setSelectedBookmarksToNextState = useCallback(+ async (field: "favourited" | "archived") => {+ const selected = selectedActionableBookmarks();+ if (selected.length === 0) {+ return [];+ }++ const shouldEnable = !selected.every((bookmark) => bookmark[field]);++ return updateSelectedBookmarks({ [field]: shouldEnable }, selected);+ },+ [selectedActionableBookmarks, updateSelectedBookmarks],+ );++ const deleteSelectedBookmarks = useCallback(async () => {+ const selected = selectedActionableBookmarks();+ await Promise.all(+ limitConcurrency(+ selected.map(+ (bookmark) => () =>+ deleteBookmarkMutator.mutateAsync({ bookmarkId: bookmark.id }),+ ),+ MAX_CONCURRENT_BULK_ACTIONS,+ ),+ );+ return selected;+ }, [deleteBookmarkMutator, selectedActionableBookmarks]);++ const deleteSelectedBookmarksSettled = useCallback(async () => {+ const selected = selectedActionableBookmarks();+ return Promise.allSettled(+ limitConcurrency(+ selected.map(+ (bookmark) => () =>+ deleteBookmarkMutator.mutateAsync({ bookmarkId: bookmark.id }),+ ),+ MAX_CONCURRENT_BULK_ACTIONS,+ ),+ );+ }, [deleteBookmarkMutator, selectedActionableBookmarks]);++ const recrawlSelectedLinkBookmarks = useCallback(+ async (archiveFullPage: boolean) => {+ const links = selectedLinkBookmarks();+ await Promise.all(+ limitConcurrency(+ links.map(+ (bookmark) => () =>+ recrawlBookmarkMutator.mutateAsync({+ bookmarkId: bookmark.id,+ archiveFullPage,+ }),+ ),+ MAX_CONCURRENT_BULK_ACTIONS,+ ),+ );+ return links;+ },+ [recrawlBookmarkMutator, selectedLinkBookmarks],+ );++ const removeSelectedBookmarksFromList = useCallback(async () => {+ if (!listContext) {+ return [];+ }++ return Promise.allSettled(+ limitConcurrency(+ selectedBookmarks.map(+ (bookmark) => () =>+ removeBookmarkFromListMutator.mutateAsync({+ bookmarkId: bookmark.id,+ listId: listContext.id,+ }),+ ),+ MAX_CONCURRENT_BULK_ACTIONS,+ ),+ );+ }, [listContext, removeBookmarkFromListMutator, selectedBookmarks]);++ const selectedBookmarkLinksText = useCallback(() => {+ return selectedBookmarks+ .map((bookmark) => {+ return (+ bookmark.content.type === BookmarkTypes.LINK && bookmark.content.url+ );+ })+ .filter(Boolean)+ .join("\n");+ }, [selectedBookmarks]);++ return {+ updateBookmarkMutator,+ deleteBookmarkMutator,+ recrawlBookmarkMutator,+ removeBookmarkFromListMutator,+ updateSelectedBookmarks,+ setSelectedBookmarksToNextState,+ deleteSelectedBookmarks,+ deleteSelectedBookmarksSettled,+ recrawlSelectedLinkBookmarks,+ removeSelectedBookmarksFromList,+ selectedBookmarkLinksText,+ };+}diff --git a/apps/web/lib/hooks/useBookmarkKeyboardNavigation.test.ts b/apps/web/lib/hooks/useBookmarkKeyboardNavigation.test.tsnew file mode 100644index 00000000..901c95d9--- /dev/null+++ b/apps/web/lib/hooks/useBookmarkKeyboardNavigation.test.ts@@ -0,0 +1,340 @@+// @vitest-environment jsdom++import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import useBulkActionsStore from "@/lib/bulkActions";+import { useKeyboardNavigationStore } from "@/lib/store/useKeyboardNavigationStore";++import type { ZBookmark } from "@karakeep/shared/types/bookmarks";++import { useBookmarkKeyboardNavigation } from "./useBookmarkKeyboardNavigation";++const mocks = vi.hoisted(() => ({+ hotkeys: [] as {+ keys: string;+ callback: () => void;+ options?: { enabled?: boolean };+ }[],+ push: vi.fn(),+ pathname: "/dashboard/bookmarks",+ updateMutate: vi.fn(),+ updateMutateAsync: vi.fn(),+ deleteMutate: vi.fn(),+ deleteMutateAsync: vi.fn(),+ recrawlMutateAsync: vi.fn(),+ removeFromListMutateAsync: vi.fn(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock("react-hotkeys-hook", () => ({+ useHotkeys: (+ keys: string,+ callback: () => void,+ options?: { enabled?: boolean },+ ) => {+ mocks.hotkeys.push({ keys, callback, options });+ },+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: mocks.push }),+ usePathname: () => mocks.pathname,+}));++vi.mock("@/lib/auth/client", () => ({+ useSession: () => ({ data: { user: { id: "user-1" } } }),+}));++vi.mock("../i18n/client", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("sonner", () => ({+ toast: {+ success: mocks.toastSuccess,+ error: mocks.toastError,+ },+}));++vi.mock("@karakeep/shared-react/hooks/bookmarks", () => ({+ useUpdateBookmark: () => ({+ mutate: mocks.updateMutate,+ mutateAsync: mocks.updateMutateAsync,+ isPending: false,+ }),+ useDeleteBookmark: () => ({+ mutate: mocks.deleteMutate,+ mutateAsync: mocks.deleteMutateAsync,+ isPending: false,+ }),+ useRecrawlBookmark: () => ({+ mutateAsync: mocks.recrawlMutateAsync,+ isPending: false,+ }),+}));++vi.mock("@karakeep/shared-react/hooks/lists", () => ({+ useRemoveBookmarkFromList: () => ({+ mutateAsync: mocks.removeFromListMutateAsync,+ isPending: false,+ }),+}));++function bookmark(+ id: string,+ {+ userId = "user-1",+ favourited = false,+ archived = false,+ }: { userId?: string; favourited?: boolean; archived?: boolean } = {},+) {+ return {+ id,+ userId,+ favourited,+ archived,+ content: {+ type: "link",+ url: `https://example.com/${id}`,+ },+ } as ZBookmark;+}++function renderKeyboardHook(+ bookmarks = [bookmark("a"), bookmark("b")],+ {+ hasNextPage = false,+ isFetchingNextPage = false,+ fetchNextPage = vi.fn(),+ }: {+ hasNextPage?: boolean;+ isFetchingNextPage?: boolean;+ fetchNextPage?: () => void;+ } = {},+) {+ return renderHook(() =>+ useBookmarkKeyboardNavigation({+ bookmarks,+ columns: 2,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ }),+ );+}++function hotkey(keys: string) {+ const registration = [...mocks.hotkeys]+ .reverse()+ .find((item) => item.keys === keys);+ if (!registration) {+ throw new Error(`Missing hotkey registration for ${keys}`);+ }+ return registration;+}++describe("useBookmarkKeyboardNavigation", () => {+ afterEach(() => {+ cleanup();+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.hotkeys = [];+ mocks.pathname = "/dashboard/bookmarks";+ mocks.updateMutateAsync.mockImplementation((input) =>+ Promise.resolve({ id: input.bookmarkId, ...input }),+ );+ mocks.deleteMutateAsync.mockResolvedValue({});+ useBulkActionsStore.setState({+ selectedBookmarkIds: [],+ visibleBookmarks: [],+ isBulkEditEnabled: false,+ listContext: undefined,+ });+ useKeyboardNavigationStore.setState({+ focusedIndex: -1,+ isNavigating: false,+ shortcutsDialogOpen: false,+ });+ });++ it("registers movement hotkeys that move keyboard focus", () => {+ renderKeyboardHook([bookmark("a"), bookmark("b"), bookmark("c")]);++ expect(hotkey("j").options?.enabled).toBe(true);++ act(() => {+ hotkey("j").callback();+ });+ expect(useKeyboardNavigationStore.getState().focusedIndex).toBe(0);++ act(() => {+ hotkey("j").callback();+ });+ expect(useKeyboardNavigationStore.getState().focusedIndex).toBe(2);+ });++ it("does not fetch the next page while one is already loading", () => {+ const fetchNextPage = vi.fn();+ useKeyboardNavigationStore.setState({+ focusedIndex: 1,+ isNavigating: true,+ });++ renderKeyboardHook([bookmark("a"), bookmark("b")], {+ hasNextPage: true,+ isFetchingNextPage: true,+ fetchNextPage,+ });++ expect(fetchNextPage).not.toHaveBeenCalled();+ });++ it("toggles the focused bookmark into bulk selection with x", () => {+ const bookmarks = [bookmark("a"), bookmark("b")];+ useKeyboardNavigationStore.setState({+ focusedIndex: 0,+ isNavigating: true,+ });++ renderKeyboardHook(bookmarks);++ act(() => {+ hotkey("x").callback();+ });++ expect(useBulkActionsStore.getState().isBulkEditEnabled).toBe(true);+ expect(useBulkActionsStore.getState().visibleBookmarks).toEqual([]);+ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual(["a"]);+ });++ it("supports the select-all keyboard sequence", () => {+ const bookmarks = [bookmark("a"), bookmark("b")];+ renderKeyboardHook(bookmarks);++ act(() => {+ hotkey("shift+8").callback();+ window.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "a",+ bubbles: true,+ }),+ );+ });++ expect(useBulkActionsStore.getState().selectedBookmarkIds).toEqual([+ "a",+ "b",+ ]);+ });++ it("opens the focused bookmark with enter or o", () => {+ useKeyboardNavigationStore.setState({+ focusedIndex: 1,+ isNavigating: true,+ });++ renderKeyboardHook([bookmark("a"), bookmark("b")]);++ act(() => {+ hotkey("o,enter").callback();+ });++ expect(mocks.push).toHaveBeenCalledWith("/dashboard/preview/b");+ });++ it("updates only owned focused bookmarks from single-bookmark hotkeys", () => {+ useKeyboardNavigationStore.setState({+ focusedIndex: 0,+ isNavigating: true,+ });++ const { unmount } = renderKeyboardHook([+ bookmark("a", { userId: "user-2" }),+ ]);++ act(() => {+ hotkey("f").callback();+ });+ expect(mocks.updateMutate).not.toHaveBeenCalled();++ unmount();+ mocks.hotkeys = [];+ useKeyboardNavigationStore.setState({+ focusedIndex: 0,+ isNavigating: true,+ });+ renderKeyboardHook([bookmark("owned", { favourited: false })]);++ act(() => {+ hotkey("f").callback();+ });++ expect(mocks.updateMutate).toHaveBeenCalledWith(+ {+ bookmarkId: "owned",+ favourited: true,+ },+ expect.any(Object),+ );+ });++ it("bulk favorite only updates selected owned bookmarks", async () => {+ const bookmarks = [+ bookmark("owned", { userId: "user-1" }),+ bookmark("shared", { userId: "user-2" }),+ ];+ useBulkActionsStore.setState({+ isBulkEditEnabled: true,+ visibleBookmarks: bookmarks,+ selectedBookmarkIds: ["owned", "shared"],+ });+ useKeyboardNavigationStore.setState({+ focusedIndex: 0,+ isNavigating: true,+ });++ renderKeyboardHook(bookmarks);++ await act(async () => {+ hotkey("f").callback();+ await Promise.resolve();+ });++ expect(mocks.updateMutateAsync).toHaveBeenCalledTimes(1);+ expect(mocks.updateMutateAsync).toHaveBeenCalledWith({+ bookmarkId: "owned",+ favourited: true,+ });+ });++ it("falls back to the focused bookmark when bulk selection is not actionable", () => {+ const bookmarks = [bookmark("current", { favourited: false })];+ useBulkActionsStore.setState({+ isBulkEditEnabled: true,+ visibleBookmarks: bookmarks,+ selectedBookmarkIds: ["filtered-out"],+ });+ useKeyboardNavigationStore.setState({+ focusedIndex: 0,+ isNavigating: true,+ });++ renderKeyboardHook(bookmarks);++ act(() => {+ hotkey("f").callback();+ });++ expect(mocks.updateMutateAsync).not.toHaveBeenCalled();+ expect(mocks.updateMutate).toHaveBeenCalledWith(+ {+ bookmarkId: "current",+ favourited: true,+ },+ expect.any(Object),+ );+ });+});diff --git a/apps/web/lib/hooks/useBookmarkKeyboardNavigation.ts b/apps/web/lib/hooks/useBookmarkKeyboardNavigation.tsnew file mode 100644index 00000000..6aefc6e8--- /dev/null+++ b/apps/web/lib/hooks/useBookmarkKeyboardNavigation.ts@@ -0,0 +1,733 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { usePathname, useRouter } from "next/navigation";+import { useSession } from "@/lib/auth/client";+import useBulkActionsStore from "@/lib/bulkActions";+import { useBookmarkBulkMutations } from "@/lib/hooks/useBookmarkBulkActions";+import { useKeyboardNavigationStore } from "@/lib/store/useKeyboardNavigationStore";+import { useHotkeys } from "react-hotkeys-hook";+import { toast } from "sonner";++import type { ZBookmark } from "@karakeep/shared/types/bookmarks";++import { useTranslation } from "../i18n/client";++const SEQUENCE_TIMEOUT_MS = 1000;++interface UseBookmarkKeyboardNavigationOptions {+ bookmarks: ZBookmark[];+ columns: number;+ hasNextPage: boolean;+ isFetchingNextPage: boolean;+ fetchNextPage: () => void;+}++type MoveBookmarkFocus = (offset: number, maxIndex: number) => void;++// Resolves whether the current session user can mutate a bookmark.+function useBookmarkOwnership() {+ const { data: session } = useSession();+ const currentUserId = session?.user?.id;++ return useCallback(+ (bookmark: ZBookmark) => currentUserId === bookmark.userId,+ [currentUserId],+ );+}++// Provides guarded helpers for actions that require a focused bookmark.+function useFocusedBookmarkActions(+ focusedBookmark: ZBookmark | null,+ canMutateBookmark: (bookmark: ZBookmark) => boolean,+) {+ const withFocusedBookmark = useCallback(+ (action: (bookmark: ZBookmark) => void) => {+ if (focusedBookmark) {+ action(focusedBookmark);+ }+ },+ [focusedBookmark],+ );++ const withOwnedFocusedBookmark = useCallback(+ (action: (bookmark: ZBookmark) => void) => {+ if (focusedBookmark && canMutateBookmark(focusedBookmark)) {+ action(focusedBookmark);+ }+ },+ [canMutateBookmark, focusedBookmark],+ );++ return { withFocusedBookmark, withOwnedFocusedBookmark };+}++function useBookmarkMoveHotkey({+ keys,+ offset,+ enabled,+ maxIndex,+ moveBy,+}: {+ keys: string;+ offset: number;+ enabled: boolean;+ maxIndex: number;+ moveBy: MoveBookmarkFocus;+}) {+ useHotkeys(+ keys,+ () => moveBy(offset, maxIndex),+ { enabled, preventDefault: true },+ [enabled, maxIndex, moveBy, offset],+ );+}++// Owns keyboard focus movement, focused-card scrolling, and page fetching.+function useBookmarkFocusNavigation({+ bookmarks,+ columns,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ disabled,+}: UseBookmarkKeyboardNavigationOptions & { disabled: boolean }) {+ const { focusedIndex, isNavigating, moveBy, clearFocus, setFocusedIndex } =+ useKeyboardNavigationStore();++ const hasBookmarks = bookmarks.length > 0;+ const maxIndex = bookmarks.length - 1;+ const focusedBookmark =+ focusedIndex >= 0 && focusedIndex < bookmarks.length+ ? bookmarks[focusedIndex]+ : null;++ useEffect(() => {+ if (isNavigating && focusedIndex >= bookmarks.length) {+ if (bookmarks.length === 0) {+ clearFocus();+ } else {+ setFocusedIndex(bookmarks.length - 1);+ }+ }+ }, [+ bookmarks.length,+ clearFocus,+ focusedIndex,+ isNavigating,+ setFocusedIndex,+ ]);++ useEffect(() => {+ if (focusedIndex >= 0 && isNavigating) {+ const el = document.querySelector(+ `[data-bookmark-index="${focusedIndex}"]`,+ );+ if (el) {+ el.scrollIntoView({ behavior: "smooth", block: "nearest" });+ }+ }+ }, [focusedIndex, isNavigating]);++ useEffect(() => {+ if (+ isNavigating &&+ focusedIndex === bookmarks.length - 1 &&+ hasNextPage &&+ !isFetchingNextPage+ ) {+ fetchNextPage();+ }+ }, [+ bookmarks.length,+ fetchNextPage,+ focusedIndex,+ hasNextPage,+ isFetchingNextPage,+ isNavigating,+ ]);++ const movementEnabled = !disabled && hasBookmarks;+ const horizontalMovementEnabled = movementEnabled && columns > 1;+ const arrowMovementEnabled = movementEnabled && isNavigating;+ const horizontalArrowMovementEnabled =+ horizontalMovementEnabled && isNavigating;++ useBookmarkMoveHotkey({+ keys: "h",+ offset: -1,+ enabled: horizontalMovementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "left",+ offset: -1,+ enabled: horizontalArrowMovementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "j",+ offset: columns,+ enabled: movementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "down",+ offset: columns,+ enabled: arrowMovementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "k",+ offset: -columns,+ enabled: movementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "up",+ offset: -columns,+ enabled: arrowMovementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "l",+ offset: 1,+ enabled: horizontalMovementEnabled,+ maxIndex,+ moveBy,+ });+ useBookmarkMoveHotkey({+ keys: "right",+ offset: 1,+ enabled: horizontalArrowMovementEnabled,+ maxIndex,+ moveBy,+ });++ return { focusedIndex, isNavigating, focusedBookmark, clearFocus };+}++// Owns bulk selection state changes and selection sequence hotkeys.+function useBulkBookmarkSelection({+ bookmarks,+ isNavigating,+ hasBookmarks,+ disabled,+ withFocusedBookmark,+ enableBulkEdit,+ selectBookmarks,+ toggleBookmark,+ unSelectAll,+}: {+ bookmarks: ZBookmark[];+ isNavigating: boolean;+ hasBookmarks: boolean;+ disabled: boolean;+ withFocusedBookmark: (action: (bookmark: ZBookmark) => void) => void;+ enableBulkEdit: () => void;+ selectBookmarks: (bookmarks: ZBookmark[]) => void;+ toggleBookmark: (bookmarkId: string) => void;+ unSelectAll: () => void;+}) {+ const selectionSequenceStartedAtRef = useRef<number | null>(null);++ const cancelSelectionSequence = useCallback(() => {+ selectionSequenceStartedAtRef.current = null;+ }, []);++ const getPendingSelectionSequence = useCallback(() => {+ const startedAt = selectionSequenceStartedAtRef.current;+ if (!startedAt || Date.now() - startedAt > SEQUENCE_TIMEOUT_MS) {+ selectionSequenceStartedAtRef.current = null;+ return false;+ }+ selectionSequenceStartedAtRef.current = null;+ return true;+ }, []);++ const selectAllBookmarks = useCallback(() => {+ selectBookmarks(bookmarks);+ }, [bookmarks, selectBookmarks]);++ useEffect(() => {+ const handleSelectionSequence = (event: KeyboardEvent) => {+ if (disabled || !getPendingSelectionSequence()) {+ return;+ }++ if (event.key.toLowerCase() === "a") {+ event.preventDefault();+ event.stopPropagation();+ selectAllBookmarks();+ } else if (event.key.toLowerCase() === "n") {+ event.preventDefault();+ event.stopPropagation();+ unSelectAll();+ }+ };++ window.addEventListener("keydown", handleSelectionSequence, true);+ return () => {+ window.removeEventListener("keydown", handleSelectionSequence, true);+ };+ }, [disabled, getPendingSelectionSequence, selectAllBookmarks, unSelectAll]);++ useHotkeys(+ "x",+ () =>+ withFocusedBookmark((bookmark) => {+ enableBulkEdit();+ toggleBookmark(bookmark.id);+ }),+ { enabled: !disabled && isNavigating, preventDefault: true },+ [+ disabled,+ bookmarks,+ enableBulkEdit,+ isNavigating,+ toggleBookmark,+ withFocusedBookmark,+ ],+ );++ useHotkeys(+ "shift+8",+ () => {+ selectionSequenceStartedAtRef.current = Date.now();+ },+ { enabled: !disabled && hasBookmarks, preventDefault: true },+ [disabled, hasBookmarks],+ );++ return {+ cancelSelectionSequence,+ };+}++// Resets keyboard and bulk-selection state when dashboard navigation changes.+function useBookmarkRouteReset({+ clearFocus,+ cancelSelectionSequence,+}: {+ clearFocus: () => void;+ cancelSelectionSequence: () => void;+}) {+ const pathname = usePathname();+ const previousPathnameRef = useRef(pathname);+ const bulkActionsStore = useBulkActionsStore();++ useEffect(() => {+ if (previousPathnameRef.current === pathname) {+ return;+ }++ previousPathnameRef.current = pathname;+ clearFocus();+ bulkActionsStore.setIsBulkEditEnabled(false);+ cancelSelectionSequence();+ }, [bulkActionsStore, cancelSelectionSequence, clearFocus, pathname]);+}++// Registers hotkeys that open the focused bookmark.+function useBookmarkOpenHotkeys({+ disabled,+ isNavigating,+ withFocusedBookmark,+}: {+ disabled: boolean;+ isNavigating: boolean;+ withFocusedBookmark: (action: (bookmark: ZBookmark) => void) => void;+}) {+ const router = useRouter();++ useHotkeys(+ "o,enter",+ () =>+ withFocusedBookmark((bookmark) =>+ router.push(`/dashboard/preview/${bookmark.id}`),+ ),+ { enabled: !disabled && isNavigating, preventDefault: true },+ [disabled, isNavigating, router, withFocusedBookmark],+ );+}++// Registers favorite and archive hotkeys for focused or selected bookmarks.+function useBookmarkUpdateHotkeys({+ disabled,+ hasBulkSelection,+ isNavigating,+ setSelectedBookmarksToNextState,+ updateBookmarkMutator,+ withOwnedFocusedBookmark,+}: {+ disabled: boolean;+ hasBulkSelection: boolean;+ isNavigating: boolean;+ setSelectedBookmarksToNextState: (+ field: "favourited" | "archived",+ ) => Promise<ZBookmark[]>;+ updateBookmarkMutator: ReturnType<+ typeof useBookmarkBulkMutations+ >["updateBookmarkMutator"];+ withOwnedFocusedBookmark: (action: (bookmark: ZBookmark) => void) => void;+}) {+ const { t } = useTranslation();++ useHotkeys(+ "f",+ () => {+ if (hasBulkSelection) {+ void setSelectedBookmarksToNextState("favourited")+ .then(() => {+ toast.success(t("toasts.bookmarks.updated"));+ })+ .catch(() => undefined);+ } else {+ withOwnedFocusedBookmark((bookmark) =>+ updateBookmarkMutator.mutate(+ {+ bookmarkId: bookmark.id,+ favourited: !bookmark.favourited,+ },+ {+ onSuccess: () => {+ toast.success(t("toasts.bookmarks.updated"));+ },+ },+ ),+ );+ }+ },+ { enabled: !disabled && isNavigating, preventDefault: true },+ [+ disabled,+ hasBulkSelection,+ isNavigating,+ setSelectedBookmarksToNextState,+ t,+ updateBookmarkMutator,+ withOwnedFocusedBookmark,+ ],+ );++ useHotkeys(+ "a",+ () => {+ if (hasBulkSelection) {+ void setSelectedBookmarksToNextState("archived")+ .then(() => {+ toast.success(t("toasts.bookmarks.updated"));+ })+ .catch(() => undefined);+ } else {+ withOwnedFocusedBookmark((bookmark) =>+ updateBookmarkMutator.mutate(+ {+ bookmarkId: bookmark.id,+ archived: !bookmark.archived,+ },+ {+ onSuccess: () => {+ toast.success(t("toasts.bookmarks.updated"));+ },+ },+ ),+ );+ }+ },+ { enabled: !disabled && isNavigating, preventDefault: true },+ [+ disabled,+ hasBulkSelection,+ isNavigating,+ setSelectedBookmarksToNextState,+ t,+ updateBookmarkMutator,+ withOwnedFocusedBookmark,+ ],+ );+}++// Owns delete hotkeys, delete dialog state, and delete confirmation behavior.+function useBookmarkDeleteHotkeys({+ disabled,+ deleteDialogOpen,+ hasBulkSelection,+ isNavigating,+ deleteBookmarkMutator,+ deleteSelectedBookmarksSettled,+ selectedOwnedBookmarks,+ setDeleteDialogOpen,+ withOwnedFocusedBookmark,+}: {+ disabled: boolean;+ deleteDialogOpen: boolean;+ hasBulkSelection: boolean;+ isNavigating: boolean;+ deleteBookmarkMutator: ReturnType<+ typeof useBookmarkBulkMutations+ >["deleteBookmarkMutator"];+ deleteSelectedBookmarksSettled: ReturnType<+ typeof useBookmarkBulkMutations+ >["deleteSelectedBookmarksSettled"];+ selectedOwnedBookmarks: () => ZBookmark[];+ setDeleteDialogOpen: (open: boolean) => void;+ withOwnedFocusedBookmark: (action: (bookmark: ZBookmark) => void) => void;+}) {+ const { t } = useTranslation();+ const bulkActionsStore = useBulkActionsStore();+ const [isBulkDeletePending, setIsBulkDeletePending] = useState(false);+ const modalBookmarkIdRef = useRef<string | null>(null);++ const openDeleteDialog = useCallback(() => {+ if (hasBulkSelection) {+ if (selectedOwnedBookmarks().length === 0) {+ return;+ }+ modalBookmarkIdRef.current = null;+ setDeleteDialogOpen(true);+ } else {+ withOwnedFocusedBookmark((bookmark) => {+ modalBookmarkIdRef.current = bookmark.id;+ setDeleteDialogOpen(true);+ });+ }+ }, [+ hasBulkSelection,+ selectedOwnedBookmarks,+ setDeleteDialogOpen,+ withOwnedFocusedBookmark,+ ]);++ useHotkeys(+ "shift+3,delete",+ openDeleteDialog,+ { enabled: !disabled && isNavigating, preventDefault: true },+ [disabled, hasBulkSelection, isNavigating, openDeleteDialog],+ );++ const isBulkDelete = deleteDialogOpen && modalBookmarkIdRef.current === null;+ const deleteCount = isBulkDelete ? selectedOwnedBookmarks().length : 1;++ const confirmDelete = useCallback(async () => {+ if (isBulkDelete) {+ setIsBulkDeletePending(true);+ const results = await deleteSelectedBookmarksSettled();+ const deletedCount = results.filter(+ (result) => result.status === "fulfilled",+ ).length;+ const failedCount = results.length - deletedCount;+ if (deletedCount > 0) {+ toast.success(t("toasts.bookmarks.deleted"));+ }+ if (failedCount > 0) {+ toast.error(t("common.something_went_wrong"));+ }+ setIsBulkDeletePending(false);+ if (failedCount === 0) {+ setDeleteDialogOpen(false);+ bulkActionsStore.setIsBulkEditEnabled(false);+ }+ } else if (modalBookmarkIdRef.current) {+ deleteBookmarkMutator.mutate(+ {+ bookmarkId: modalBookmarkIdRef.current,+ },+ {+ onSuccess: () => {+ toast.success(t("toasts.bookmarks.deleted"));+ setDeleteDialogOpen(false);+ },+ },+ );+ }+ }, [+ bulkActionsStore,+ deleteBookmarkMutator,+ deleteSelectedBookmarksSettled,+ isBulkDelete,+ t,+ ]);++ return {+ deleteDialogOpen,+ setDeleteDialogOpen,+ isBulkDelete,+ deleteCount,+ confirmDelete,+ isDeletePending: deleteBookmarkMutator.isPending || isBulkDeletePending,+ };+}++// Registers global bookmark-grid hotkeys that are not tied to one bookmark.+function useBookmarkGlobalHotkeys({+ disabled,+ clearFocus,+}: {+ disabled: boolean;+ clearFocus: () => void;+}) {+ const { shortcutsDialogOpen, setShortcutsDialogOpen } =+ useKeyboardNavigationStore();+ const bulkActionsStore = useBulkActionsStore();++ useHotkeys(+ "?",+ () => setShortcutsDialogOpen(true),+ { enabled: !disabled, preventDefault: true, useKey: true },+ [disabled],+ );++ useHotkeys(+ "escape",+ () => {+ if (bulkActionsStore.isBulkEditEnabled) {+ bulkActionsStore.setIsBulkEditEnabled(false);+ } else {+ clearFocus();+ }+ },+ { enabled: !disabled },+ [disabled, bulkActionsStore.isBulkEditEnabled],+ );++ return {+ helpDialogOpen: shortcutsDialogOpen,+ setHelpDialogOpen: setShortcutsDialogOpen,+ };+}++// Composes the bookmark keyboard workflows behind the existing public API.+export function useBookmarkKeyboardNavigation({+ bookmarks,+ columns,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+}: UseBookmarkKeyboardNavigationOptions) {+ const { t } = useTranslation();+ const shortcutsDialogOpen = useKeyboardNavigationStore(+ (state) => state.shortcutsDialogOpen,+ );+ const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);+ const disabled = shortcutsDialogOpen || deleteDialogOpen;+ const hasBookmarks = bookmarks.length > 0;+ const canMutateBookmark = useBookmarkOwnership();+ const bulkActionsStore = useBulkActionsStore();+ const selectedBookmarks = bulkActionsStore.getSelectedBookmarks();+ const { isBulkEditEnabled } = bulkActionsStore;+ const selectedActionableBookmarks = useCallback(+ () => bulkActionsStore.getSelectedActionableBookmarks(canMutateBookmark),+ [bulkActionsStore, canMutateBookmark],+ );+ const hasBulkSelection =+ isBulkEditEnabled && selectedActionableBookmarks().length > 0;+ const enableBulkEdit = useCallback(() => {+ bulkActionsStore.setIsBulkEditEnabled(true);+ }, [bulkActionsStore]);+ const selectBookmarks = useCallback(+ (bookmarks: ZBookmark[]) => {+ enableBulkEdit();+ bulkActionsStore.setSelectedBookmarkIds(+ bookmarks.map((bookmark) => bookmark.id),+ );+ },+ [bulkActionsStore, enableBulkEdit],+ );+ const {+ updateBookmarkMutator,+ deleteBookmarkMutator,+ setSelectedBookmarksToNextState,+ deleteSelectedBookmarksSettled,+ } = useBookmarkBulkMutations({+ selectedBookmarks,+ selectedActionableBookmarks,+ onError: () => {+ toast.error(t("common.something_went_wrong"));+ },+ });++ const focusNavigation = useBookmarkFocusNavigation({+ bookmarks,+ columns,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ disabled,+ });++ const { withFocusedBookmark, withOwnedFocusedBookmark } =+ useFocusedBookmarkActions(+ focusNavigation.focusedBookmark,+ canMutateBookmark,+ );++ const bulkSelection = useBulkBookmarkSelection({+ bookmarks,+ isNavigating: focusNavigation.isNavigating,+ hasBookmarks,+ disabled,+ withFocusedBookmark,+ enableBulkEdit,+ selectBookmarks,+ toggleBookmark: bulkActionsStore.toggleBookmark,+ unSelectAll: bulkActionsStore.unSelectAll,+ });++ useBookmarkRouteReset({+ clearFocus: focusNavigation.clearFocus,+ cancelSelectionSequence: bulkSelection.cancelSelectionSequence,+ });++ useBookmarkOpenHotkeys({+ disabled,+ isNavigating: focusNavigation.isNavigating,+ withFocusedBookmark,+ });++ useBookmarkUpdateHotkeys({+ disabled,+ hasBulkSelection,+ isNavigating: focusNavigation.isNavigating,+ setSelectedBookmarksToNextState,+ updateBookmarkMutator,+ withOwnedFocusedBookmark,+ });++ const deletion = useBookmarkDeleteHotkeys({+ disabled,+ deleteDialogOpen,+ hasBulkSelection,+ isNavigating: focusNavigation.isNavigating,+ deleteBookmarkMutator,+ deleteSelectedBookmarksSettled,+ selectedOwnedBookmarks: selectedActionableBookmarks,+ setDeleteDialogOpen,+ withOwnedFocusedBookmark,+ });++ const globalHotkeys = useBookmarkGlobalHotkeys({+ disabled,+ clearFocus: focusNavigation.clearFocus,+ });++ return {+ focusedIndex: focusNavigation.focusedIndex,+ isNavigating: focusNavigation.isNavigating,+ helpDialogOpen: globalHotkeys.helpDialogOpen,+ setHelpDialogOpen: globalHotkeys.setHelpDialogOpen,+ deleteDialogOpen: deletion.deleteDialogOpen,+ setDeleteDialogOpen: deletion.setDeleteDialogOpen,+ focusedBookmark: focusNavigation.focusedBookmark,+ isBulkDelete: deletion.isBulkDelete,+ deleteCount: deletion.deleteCount,+ confirmDelete: deletion.confirmDelete,+ isDeletePending: deletion.isDeletePending,+ };+}diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.jsonindex 08d5c627..605cbadd 100644--- a/apps/web/lib/i18n/locales/en/translation.json+++ b/apps/web/lib/i18n/locales/en/translation.json@@ -1020,7 +1020,8 @@"dialogs": {"bookmarks": {"delete_confirmation_title": "Delete Bookmark?",- "delete_confirmation_description": "Are you sure you want to delete this bookmark?"+ "delete_confirmation_description": "Are you sure you want to delete this bookmark?",+ "bulk_delete_confirmation_description": "Are you sure you want to delete {{count}} bookmarks?"}},"toasts": {@@ -1129,5 +1130,28 @@"download": "Download","close": "Close","generating": "Generating..."+ },+ "keyboard_shortcuts": {+ "title": "Keyboard Shortcuts",+ "sections": {+ "navigation": "Navigation",+ "actions": "Actions",+ "selection": "Selection",+ "other": "Other"+ },+ "move_left": "Move left",+ "move_down": "Move down",+ "move_up": "Move up",+ "move_right": "Move right",+ "open_bookmark": "Open bookmark",+ "clear_focus": "Clear focus / exit bulk edit",+ "toggle_favorite": "Toggle favorite",+ "toggle_archive": "Archive / Unarchive",+ "delete_bookmark": "Delete bookmark",+ "toggle_selection": "Toggle selection",+ "select_all": "Select all",+ "deselect_all": "Deselect all",+ "show_help": "Show keyboard shortcuts",+ "focus_search_alt": "Focus search"}}diff --git a/apps/web/lib/store/useInBookmarkGridStore.ts b/apps/web/lib/store/useInBookmarkGridStore.tsindex d534dc4c..20c8871e 100644--- a/apps/web/lib/store/useInBookmarkGridStore.ts+++ b/apps/web/lib/store/useInBookmarkGridStore.ts@@ -5,7 +5,14 @@ interface InBookmarkGridState {setInBookmarkGrid: (inBookmarkGrid: boolean) => void;}-export const useInBookmarkGridStore = create<InBookmarkGridState>((set) => ({- inBookmarkGrid: false,- setInBookmarkGrid: (inBookmarkGrid) => set({ inBookmarkGrid }),-}));+export const useInBookmarkGridStore = create<InBookmarkGridState>(+ (set, get) => ({+ inBookmarkGrid: false,+ setInBookmarkGrid: (inBookmarkGrid) => {+ if (get().inBookmarkGrid === inBookmarkGrid) {+ return;+ }+ set({ inBookmarkGrid });+ },+ }),+);diff --git a/apps/web/lib/store/useKeyboardNavigationStore.ts b/apps/web/lib/store/useKeyboardNavigationStore.tsnew file mode 100644index 00000000..c6e24614--- /dev/null+++ b/apps/web/lib/store/useKeyboardNavigationStore.ts@@ -0,0 +1,37 @@+import { create } from "zustand";++interface KeyboardNavigationState {+ focusedIndex: number;+ isNavigating: boolean;+ shortcutsDialogOpen: boolean;+ setFocusedIndex: (index: number) => void;+ clearFocus: () => void;+ moveBy: (delta: number, maxIndex: number) => void;+ setShortcutsDialogOpen: (open: boolean) => void;+}++export const useKeyboardNavigationStore = create<KeyboardNavigationState>(+ (set) => ({+ focusedIndex: -1,+ isNavigating: false,+ shortcutsDialogOpen: false,++ setFocusedIndex: (index) =>+ set({ focusedIndex: index, isNavigating: true }),++ clearFocus: () => set({ focusedIndex: -1, isNavigating: false }),++ moveBy: (delta, maxIndex) =>+ set((state) => {+ if (maxIndex < 0) return state;+ if (!state.isNavigating) return { focusedIndex: 0, isNavigating: true };+ const next = Math.max(+ 0,+ Math.min(state.focusedIndex + delta, maxIndex),+ );+ return { focusedIndex: next, isNavigating: true };+ }),++ setShortcutsDialogOpen: (open) => set({ shortcutsDialogOpen: open }),+ }),+);diff --git a/apps/web/package.json b/apps/web/package.jsonindex 706660f2..9b622738 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -108,6 +108,7 @@"@karakeep/tailwind-config": "workspace:^0.1.0","@karakeep/tsconfig": "workspace:^0.1.0","@next/bundle-analyzer": "15.3.8",+ "@testing-library/react": "^16.3.2","@types/csv-parse": "^1.2.5","@types/emoji-mart": "^3.0.14","@types/react": "^19.2.14",@@ -115,6 +116,7 @@"@types/react-syntax-highlighter": "^15.5.13","@types/request-ip": "^0.0.41","autoprefixer": "^10.4.17",+ "jsdom": "^24.0.0","portless": "^0.10.3","postcss": "^8.4.35","tailwindcss": "^3.4.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 512f467e..bbb0aaa4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -790,6 +790,9 @@ importers:'@next/bundle-analyzer':specifier: 15.3.8version: 15.3.8+ '@testing-library/react':+ specifier: ^16.3.2+ version: 16.3.2(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@types/csv-parse':specifier: ^1.2.5version: 1.2.5@@ -811,6 +814,9 @@ importers:autoprefixer:specifier: ^10.4.17version: 10.4.21([email protected])+ jsdom:+ specifier: ^24.0.0+ version: 24.1.3portless:specifier: ^0.10.3version: 0.10.3@@ -825,7 +831,7 @@ importers:version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: ^3.2.4- version: 3.2.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 3.2.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])apps/workers:dependencies:@@ -7080,6 +7086,25 @@ packages:peerDependencies:react: ^18 || ^19+ '@testing-library/[email protected]':+ resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}+ engines: {node: '>=18'}++ '@testing-library/[email protected]':+ resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}+ engines: {node: '>=18'}+ peerDependencies:+ '@testing-library/dom': ^10.0.0+ '@types/react': ^18.0.0 || ^19.0.0+ '@types/react-dom': ^18.0.0 || ^19.0.0+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+'@tokenizer/[email protected]':resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}engines: {node: '>=18'}@@ -7127,6 +7152,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}+'@types/[email protected]':resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}@@ -7795,6 +7823,9 @@ packages:resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}+resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}engines: {node: '>= 0.4'}@@ -9124,6 +9155,9 @@ packages:react: ^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0react-dom: ^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}+resolution: {integrity: sha512-gd3ypIPfOMr9h5jIKq8E3sHOTCjeirnl0WK5ZdS1AW0Odt0b1PaWaHdJ4Qk4klv+YB9aJBS7mESXjFoDQPu6DA==}@@ -11777,6 +11811,10 @@ packages:peerDependencies:react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}+ hasBin: true+resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==}@@ -13875,6 +13913,10 @@ packages:resolution: {integrity: sha512-AoJ5YMAcXKYxKhuJGdcvse+Voc6v1RgnsR3nWcYU7q4t6z0Q6T86sv5Zq8VIRbOWWFpvdGE83LtdSMNd+6Y0xw==}+ resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}+ engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}+resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==}engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}@@ -24303,6 +24345,27 @@ snapshots:'@tanstack/query-core': 5.90.2react: 19.2.3+ '@testing-library/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.0+ '@babel/runtime': 7.29.2+ '@types/aria-query': 5.0.4+ aria-query: 5.3.0+ dom-accessibility-api: 0.5.16+ lz-string: 1.5.0+ picocolors: 1.1.1+ pretty-format: 27.5.1++ '@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.29.2+ '@testing-library/dom': 10.4.1+ react: 19.2.3+ react-dom: 19.2.3([email protected])+ optionalDependencies:+ '@types/react': 19.2.14+ '@types/react-dom': 19.1.6(@types/[email protected])+'@tokenizer/[email protected]':dependencies:debug: 4.4.3@@ -24349,6 +24412,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@babel/parser': 7.29.2@@ -25185,6 +25250,10 @@ snapshots:dependencies:tslib: 2.8.1+ dependencies:+ dequal: 2.0.3+@@ -26809,6 +26878,8 @@ snapshots:- supports-color- webpack+ [email protected]: {}+dependencies:utila: 0.4.0@@ -29677,6 +29748,8 @@ snapshots:dependencies:react: 19.2.3+ [email protected]: {}+dependencies:sourcemap-codec: 1.4.8@@ -32618,6 +32691,12 @@ snapshots:lodash: 4.17.23renderkid: 3.0.0+ dependencies:+ ansi-regex: 5.0.1+ ansi-styles: 5.2.0+ react-is: 17.0.2+dependencies:'@jest/schemas': 29.6.3@@ -35965,6 +36044,50 @@ snapshots:- tsx- yaml+ [email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ '@types/chai': 5.2.2+ '@vitest/expect': 3.2.4+ '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 3.2.4+ '@vitest/runner': 3.2.4+ '@vitest/snapshot': 3.2.4+ '@vitest/spy': 3.2.4+ '@vitest/utils': 3.2.4+ chai: 5.2.1+ debug: 4.4.1([email protected])+ expect-type: 1.2.2+ magic-string: 0.30.17+ pathe: 2.0.3+ picomatch: 4.0.2+ std-env: 3.9.0+ tinybench: 2.9.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.14+ tinypool: 1.1.1+ tinyrainbow: 2.0.0+ vite: 7.0.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/debug': 4.1.12+ '@types/node': 24.10.3+ happy-dom: 20.3.9+ jsdom: 24.1.3+ transitivePeerDependencies:+ - jiti+ - less+ - lightningcss+ - msw+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml+[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:'@types/chai': 5.2.2