A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { usePathname } from "next/navigation";
import {
ActionButton,
ActionButtonWithTooltip,
} from "@/components/ui/action-button";
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,
FileDown,
Hash,
Link,
List,
ListMinus,
RotateCw,
Trash2,
X,
} from "lucide-react";
import BulkManageListsModal from "./bookmarks/BulkManageListsModal";
import BulkTagModal from "./bookmarks/BulkTagModal";
import { ArchivedActionIcon, FavouritedActionIcon } from "./bookmarks/icons";
export default function BulkBookmarksAction() {
const { t } = useTranslation();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isRemoveFromListDialogOpen, setIsRemoveFromListDialogOpen] =
useState(false);
const [manageListsModal, setManageListsModalOpen] = useState(false);
const [bulkTagModal, setBulkTagModalOpen] = useState(false);
const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(
null,
);
const pathname = usePathname();
const currentPathnameRef = useRef(pathname);
const onError = () => {
toast({
variant: "destructive",
title: "Something went wrong",
description: "There was a problem with your request.",
});
};
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,
onBulkEditDone: () => {
setIsBulkEditEnabled(false);
},
});
useEffect(() => {
setPortalContainer(document.body);
}, []);
// Reset bulk edit state when the route changes
useEffect(() => {
if (pathname !== currentPathnameRef.current) {
currentPathnameRef.current = pathname;
setIsBulkEditEnabled(false);
}
}, [pathname, setIsBulkEditEnabled]);
const recrawlBookmarks = async (archiveFullPage: boolean) => {
const links = await recrawlSelectedLinkBookmarks(archiveFullPage);
toast({
description: `${links.length} bookmarks will be ${archiveFullPage ? "re-crawled and archived!" : "refreshed!"}`,
});
};
function isClipboardAvailable() {
if (typeof window === "undefined") {
return false;
}
return window && window.navigator && window.navigator.clipboard;
}
const copyLinks = async () => {
if (!isClipboardAvailable()) {
toast({
description: `Copying is only available over https`,
});
return;
}
await navigator.clipboard.writeText(selectedBookmarkLinksText());
toast({
description: `Added ${selectedBookmarks.length} bookmark links into the clipboard!`,
});
};
const updateBookmarks = async ({
favourited,
archived,
}: UpdateBookmarkProps) => {
await updateSelectedBookmarks({ favourited, archived });
setIsBulkEditEnabled(false);
toast({
description: `${selectedBookmarks.length} bookmarks have been updated!`,
});
};
const deleteBookmarks = async () => {
await deleteSelectedBookmarks();
toast({
description: `${selectedBookmarks.length} bookmarks have been deleted!`,
});
setIsDeleteDialogOpen(false);
};
const removeBookmarksFromList = async () => {
if (!withinListContext) return;
const results = await removeSelectedBookmarksFromList();
const successes = results.filter((r) => r.status === "fulfilled").length;
if (successes > 0) {
toast({
description: `${successes} bookmarks have been removed from the list!`,
});
}
setIsRemoveFromListDialogOpen(false);
};
const alreadyFavourited =
selectedBookmarks.length &&
selectedBookmarks.every((item) => item.favourited === true);
const alreadyArchived =
selectedBookmarks.length &&
selectedBookmarks.every((item) => item.archived === true);
const actionList = [
{
name: isClipboardAvailable()
? t("actions.copy_link")
: "Copying is only available over https",
icon: <Link size={18} className="size-[18px]" />,
action: () => copyLinks(),
isPending: false,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.remove_from_list"),
icon: <ListMinus size={18} className="size-[18px]" />,
action: () => setIsRemoveFromListDialogOpen(true),
isPending: removeBookmarkFromListMutator.isPending,
hidden:
!isBulkEditEnabled ||
!withinListContext ||
withinListContext.type !== "manual" ||
(withinListContext.userRole !== "editor" &&
withinListContext.userRole !== "owner"),
},
{
name: t("actions.add_to_list"),
icon: <List size={18} className="size-[18px]" />,
action: () => setManageListsModalOpen(true),
isPending: false,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.edit_tags"),
icon: <Hash size={18} className="size-[18px]" />,
action: () => setBulkTagModalOpen(true),
isPending: false,
hidden: !isBulkEditEnabled,
},
{
name: alreadyFavourited ? t("actions.unfavorite") : t("actions.favorite"),
icon: (
<FavouritedActionIcon
favourited={!!alreadyFavourited}
size={18}
className="size-[18px]"
/>
),
action: () => updateBookmarks({ favourited: !alreadyFavourited }),
isPending: updateBookmarkMutator.isPending,
hidden: !isBulkEditEnabled,
},
{
name: alreadyArchived ? t("actions.unarchive") : t("actions.archive"),
icon: (
<ArchivedActionIcon
size={18}
className="size-[18px]"
archived={!!alreadyArchived}
/>
),
action: () => updateBookmarks({ archived: !alreadyArchived }),
isPending: updateBookmarkMutator.isPending,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.preserve_offline_archive"),
icon: <FileDown size={18} className="size-[18px]" />,
action: () => recrawlBookmarks(true),
isPending: recrawlBookmarkMutator.isPending,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.refresh"),
icon: <RotateCw size={18} className="size-[18px]" />,
action: () => recrawlBookmarks(false),
isPending: recrawlBookmarkMutator.isPending,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.delete"),
icon: <Trash2 size={18} className="size-[18px]" color="red" />,
action: () => setIsDeleteDialogOpen(true),
hidden: !isBulkEditEnabled,
},
{
name: isEverythingSelected()
? t("actions.unselect_all")
: t("actions.select_all"),
icon: (
<p className="flex items-center gap-2">
( <CheckCheck size={18} className="size-[18px]" />{" "}
{selectedBookmarks.length} )
</p>
),
action: () =>
isEverythingSelected() ? unSelectAllBookmarks() : selectAllBookmarks(),
alwaysEnable: true,
hidden: !isBulkEditEnabled,
},
{
name: t("actions.close_bulk_edit"),
icon: <X size={18} className="size-[18px]" />,
action: () => setIsBulkEditEnabled(false),
alwaysEnable: true,
hidden: !isBulkEditEnabled,
},
];
const renderActions = (mobile: boolean) => (
<div className="flex min-w-max items-center">
{actionList.map(
({ name, icon, action, isPending, hidden, alwaysEnable }) => {
const className = `${hidden ? "hidden" : "block"} ${
mobile && alwaysEnable ? "-order-1" : ""
}`;
const disabled = !selectedBookmarks.length && !alwaysEnable;
if (mobile) {
return (
<ActionButton
aria-label={name}
title={name}
className={className}
disabled={disabled}
loading={!!isPending}
variant="ghost"
key={name}
onClick={action}
>
{icon}
</ActionButton>
);
}
return (
<ActionButtonWithTooltip
className={className}
tooltip={name}
disabled={disabled}
delayDuration={100}
loading={!!isPending}
variant="ghost"
key={name}
onClick={action}
>
{icon}
</ActionButtonWithTooltip>
);
},
)}
</div>
);
const isModalOpen =
isDeleteDialogOpen ||
isRemoveFromListDialogOpen ||
manageListsModal ||
bulkTagModal;
return (
<div>
<ActionConfirmingDialog
open={isDeleteDialogOpen}
setOpen={setIsDeleteDialogOpen}
title={"Delete Bookmarks"}
description={<p>Are you sure you want to delete these bookmarks?</p>}
actionButton={() => (
<ActionButton
type="button"
variant="destructive"
loading={deleteBookmarkMutator.isPending}
onClick={() => deleteBookmarks()}
>
{t("actions.delete")}
</ActionButton>
)}
/>
<ActionConfirmingDialog
open={isRemoveFromListDialogOpen}
setOpen={setIsRemoveFromListDialogOpen}
title={"Remove Bookmarks from List"}
description={
<p>
Are you sure you want to remove {selectedBookmarks.length} bookmarks
from this list?
</p>
}
actionButton={() => (
<ActionButton
type="button"
variant="destructive"
loading={removeBookmarkFromListMutator.isPending}
onClick={() => removeBookmarksFromList()}
>
{t("actions.remove")}
</ActionButton>
)}
/>
<BulkManageListsModal
bookmarkIds={selectedBookmarks.map((b) => b.id)}
open={manageListsModal}
setOpen={setManageListsModalOpen}
/>
<BulkTagModal
bookmarkIds={selectedBookmarks.map((b) => b.id)}
open={bulkTagModal}
setOpen={setBulkTagModalOpen}
/>
{portalContainer && isBulkEditEnabled && !isModalOpen
? createPortal(
<div className="fixed inset-x-3 bottom-[calc(env(safe-area-inset-bottom)+0.75rem)] z-[70] sm:bottom-6 sm:left-1/2 sm:right-auto sm:w-max sm:max-w-[calc(100vw-2rem)] sm:-translate-x-1/2">
<div
aria-label={t("actions.bulk_edit")}
className="overflow-x-auto rounded-2xl border bg-background/95 p-1 shadow-2xl ring-1 ring-black/5 backdrop-blur-sm duration-200 animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none dark:ring-white/10"
role="toolbar"
>
<div className="sm:hidden">{renderActions(true)}</div>
<div className="hidden sm:block">{renderActions(false)}</div>
</div>
</div>,
portalContainer,
)
: null}
</div>
);
}