diff options
| author | Mohamed Bassem <me@mbassem.com> | 2024-04-19 00:09:27 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-04-19 00:09:27 +0100 |
| commit | e0999f701cd1834c3d940113cd8dd5247c5fe95f (patch) | |
| tree | c4169a564ecd3f933e711bcc8ef7db20532174ea | |
| parent | deba31ee010f785a9739fd4df8a64a3056c9593d (diff) | |
| download | karakeep-e0999f701cd1834c3d940113cd8dd5247c5fe95f.tar.zst | |
feature: Nested lists (#110). Fixes #62
* feature: Add support for nested lists
* prevent moving the parent to a subtree
23 files changed, 1894 insertions, 212 deletions
diff --git a/apps/web/app/dashboard/lists/[listId]/page.tsx b/apps/web/app/dashboard/lists/[listId]/page.tsx index 49bf77f7..f8c5e0b6 100644 --- a/apps/web/app/dashboard/lists/[listId]/page.tsx +++ b/apps/web/app/dashboard/lists/[listId]/page.tsx @@ -1,6 +1,6 @@ import { notFound } from "next/navigation"; import Bookmarks from "@/components/dashboard/bookmarks/Bookmarks"; -import DeleteListButton from "@/components/dashboard/lists/DeleteListButton"; +import ListHeader from "@/components/dashboard/lists/ListHeader"; import { api } from "@/server/api/client"; import { TRPCError } from "@trpc/server"; @@ -26,14 +26,7 @@ export default async function ListPage({ query={{ listId: list.id }} showDivider={true} showEditorCard={true} - header={ - <div className="flex justify-between"> - <span className="text-2xl"> - {list.icon} {list.name} - </span> - <DeleteListButton list={list} /> - </div> - } + header={<ListHeader initialData={list} />} /> ); } diff --git a/apps/web/components/dashboard/bookmarks/AddToListModal.tsx b/apps/web/components/dashboard/bookmarks/AddToListModal.tsx index bfe6d53f..3b8a6700 100644 --- a/apps/web/components/dashboard/bookmarks/AddToListModal.tsx +++ b/apps/web/components/dashboard/bookmarks/AddToListModal.tsx @@ -16,21 +16,15 @@ import { FormItem, FormMessage, } from "@/components/ui/form"; -import { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import LoadingSpinner from "@/components/ui/spinner"; import { toast } from "@/components/ui/use-toast"; -import { api } from "@/lib/trpc"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { z } from "zod"; +import { useAddBookmarkToList } from "@hoarder/shared-react/hooks/lists"; + +import { BookmarkListSelector } from "../lists/BookmarkListSelector"; + export default function AddToListModal({ bookmarkId, open, @@ -49,20 +43,13 @@ export default function AddToListModal({ resolver: zodResolver(formSchema), }); - const { data: lists, isPending: isFetchingListsPending } = - api.lists.list.useQuery(); - - const bookmarksInvalidationFunction = - api.useUtils().bookmarks.getBookmarks.invalidate; - const { mutate: addToList, isPending: isAddingToListPending } = - api.lists.addToList.useMutation({ - onSuccess: (_resp, req) => { + useAddBookmarkToList({ + onSuccess: () => { toast({ description: "List has been updated!", }); setOpen(false); - bookmarksInvalidationFunction({ listId: req.listId }); }, onError: (e) => { if (e.data?.code == "BAD_REQUEST") { @@ -79,8 +66,6 @@ export default function AddToListModal({ }, }); - const isPending = isFetchingListsPending || isAddingToListPending; - return ( <Dialog open={open} onOpenChange={setOpen}> <DialogContent> @@ -98,42 +83,20 @@ export default function AddToListModal({ </DialogHeader> <div className="py-4"> - {lists ? ( - <FormField - control={form.control} - name="listId" - render={({ field }) => { - return ( - <FormItem> - <FormControl> - <Select onValueChange={field.onChange}> - <SelectTrigger className="w-full"> - <SelectValue placeholder="Select a list" /> - </SelectTrigger> - <SelectContent> - <SelectGroup> - {lists?.lists.map((l) => ( - <SelectItem key={l.id} value={l.id}> - {l.icon} {l.name} - </SelectItem> - ))} - {lists && lists.lists.length == 0 && ( - <SelectItem value="nolist" disabled> - You don't currently have any lists. - </SelectItem> - )} - </SelectGroup> - </SelectContent> - </Select> - </FormControl> - <FormMessage /> - </FormItem> - ); - }} - /> - ) : ( - <LoadingSpinner /> - )} + <FormField + control={form.control} + name="listId" + render={({ field }) => { + return ( + <FormItem> + <FormControl> + <BookmarkListSelector onChange={field.onChange} /> + </FormControl> + <FormMessage /> + </FormItem> + ); + }} + /> </div> <DialogFooter className="sm:justify-end"> <DialogClose asChild> @@ -144,7 +107,7 @@ export default function AddToListModal({ <ActionButton type="submit" loading={isAddingToListPending} - disabled={isPending} + disabled={isAddingToListPending} > Add </ActionButton> diff --git a/apps/web/components/dashboard/lists/AllListsView.tsx b/apps/web/components/dashboard/lists/AllListsView.tsx index 00e76a23..308af5db 100644 --- a/apps/web/components/dashboard/lists/AllListsView.tsx +++ b/apps/web/components/dashboard/lists/AllListsView.tsx @@ -1,31 +1,59 @@ "use client"; import Link from "next/link"; -import { useNewListModal } from "@/components/dashboard/sidebar/NewListModal"; +import { EditListModal } from "@/components/dashboard/lists/EditListModal"; import { Button } from "@/components/ui/button"; -import { api } from "@/lib/trpc"; -import { keepPreviousData } from "@tanstack/react-query"; -import { Plus } from "lucide-react"; +import { CollapsibleTriggerChevron } from "@/components/ui/collapsible"; +import { MoreHorizontal, Plus } from "lucide-react"; import type { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { CollapsibleBookmarkLists } from "./CollapsibleBookmarkLists"; +import { ListOptions } from "./ListOptions"; + function ListItem({ name, icon, path, + style, + list, + open, + collapsible, }: { name: string; icon: string; path: string; + style?: React.CSSProperties; + list?: ZBookmarkList; + open?: boolean; + collapsible: boolean; }) { return ( - <Link href={path}> - <div className="rounded-md border border-border bg-background px-4 py-2 text-lg"> - <p className="text-nowrap"> - {icon} {name} - </p> - </div> - </Link> + <li + className="my-2 flex items-center justify-between rounded-md border border-border p-2 hover:bg-accent/50" + style={style} + > + <span className="flex flex-1 items-center gap-1"> + {collapsible && ( + <CollapsibleTriggerChevron className="size-5" open={open ?? false} /> + )} + <Link href={path} className="flex flex-1 gap-1"> + <p className="text-nowrap text-lg"> + {icon} {name} + </p> + </Link> + </span> + {list && ( + <ListOptions list={list}> + <Button + className="flex h-full items-center justify-end" + variant="ghost" + > + <MoreHorizontal /> + </Button> + </ListOptions> + )} + </li> ); } @@ -34,34 +62,41 @@ export default function AllListsView({ }: { initialData: ZBookmarkList[]; }) { - const { setOpen: setIsNewListModalOpen } = useNewListModal(); - let { data: lists } = api.lists.list.useQuery(undefined, { - initialData: { lists: initialData }, - placeholderData: keepPreviousData, - }); - - // TODO: This seems to be a bug in react query - lists ||= { lists: initialData }; - return ( - <div className="flex flex-col flex-wrap gap-2 md:flex-row"> - <Button - className="my-auto flex h-full" - onClick={() => setIsNewListModalOpen(true)} - > - <Plus /> - <span className="my-auto">New List</span> - </Button> - <ListItem name="Favourites" icon="⭐️" path={`/dashboard/favourites`} /> - <ListItem name="Archive" icon="🗄️" path={`/dashboard/archive`} /> - {lists.lists.map((l) => ( - <ListItem - key={l.id} - name={l.name} - icon={l.icon} - path={`/dashboard/lists/${l.id}`} - /> - ))} - </div> + <ul> + <EditListModal> + <Button className="mb-2 flex h-full w-full items-center"> + <Plus /> + <span>New List</span> + </Button> + </EditListModal> + <ListItem + collapsible={false} + name="Favourites" + icon="⭐️" + path={`/dashboard/favourites`} + /> + <ListItem + collapsible={false} + name="Archive" + icon="🗄️" + path={`/dashboard/archive`} + /> + <CollapsibleBookmarkLists + initialData={initialData} + render={({ item, level, open }) => ( + <ListItem + key={item.item.id} + name={item.item.name} + icon={item.item.icon} + list={item.item} + path={`/dashboard/lists/${item.item.id}`} + collapsible={item.children.length > 0} + open={open} + style={{ marginLeft: `${level * 1}rem` }} + /> + )} + /> + </ul> ); } diff --git a/apps/web/components/dashboard/lists/BookmarkListSelector.tsx b/apps/web/components/dashboard/lists/BookmarkListSelector.tsx new file mode 100644 index 00000000..fdae1c17 --- /dev/null +++ b/apps/web/components/dashboard/lists/BookmarkListSelector.tsx @@ -0,0 +1,63 @@ +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import LoadingSpinner from "@/components/ui/spinner"; + +import { useBookmarkLists } from "@hoarder/shared-react/hooks/lists"; + +export function BookmarkListSelector({ + value, + onChange, + hideSubtreeOf, + placeholder = "Select a list", +}: { + value?: string | null; + onChange: (value: string) => void; + placeholder?: string; + hideSubtreeOf?: string; +}) { + const { data, isPending: isFetchingListsPending } = useBookmarkLists(); + let { allPaths } = data ?? {}; + + if (isFetchingListsPending) { + return <LoadingSpinner />; + } + + allPaths = allPaths?.filter((path) => { + if (!hideSubtreeOf) { + return true; + } + return !path.map((p) => p.id).includes(hideSubtreeOf); + }); + + return ( + <Select onValueChange={onChange} value={value ?? undefined}> + <SelectTrigger className="w-full"> + <SelectValue placeholder={placeholder} /> + </SelectTrigger> + <SelectContent> + <SelectGroup> + {allPaths?.map((path) => { + const l = path[path.length - 1]; + const name = path.map((p) => `${p.icon} ${p.name}`).join(" / "); + return ( + <SelectItem key={l.id} value={l.id}> + {name} + </SelectItem> + ); + })} + {allPaths && allPaths.length == 0 && ( + <SelectItem value="nolist" disabled> + You don't currently have any lists. + </SelectItem> + )} + </SelectGroup> + </SelectContent> + </Select> + ); +} diff --git a/apps/web/components/dashboard/lists/CollapsibleBookmarkLists.tsx b/apps/web/components/dashboard/lists/CollapsibleBookmarkLists.tsx new file mode 100644 index 00000000..da1b7408 --- /dev/null +++ b/apps/web/components/dashboard/lists/CollapsibleBookmarkLists.tsx @@ -0,0 +1,111 @@ +import { useEffect, useState } from "react"; +import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible"; +import { FullPageSpinner } from "@/components/ui/full-page-spinner"; + +import { + augmentBookmarkListsWithInitialData, + useBookmarkLists, +} from "@hoarder/shared-react/hooks/lists"; +import { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { ZBookmarkListTreeNode } from "@hoarder/shared/utils/listUtils"; + +type RenderFunc = (params: { + item: ZBookmarkListTreeNode; + level: number; + open: boolean; +}) => React.ReactNode; + +type IsOpenFunc = (list: ZBookmarkListTreeNode) => boolean; + +function ListItem({ + node, + render, + level, + className, + isOpenFunc, +}: { + node: ZBookmarkListTreeNode; + render: RenderFunc; + isOpenFunc: IsOpenFunc; + level: number; + className?: string; +}) { + // Not the most efficient way to do this, but it works for now + const isAnyChildOpen = ( + node: ZBookmarkListTreeNode, + isOpenFunc: IsOpenFunc, + ): boolean => { + if (isOpenFunc(node)) { + return true; + } + return node.children.some((l) => isAnyChildOpen(l, isOpenFunc)); + }; + const [open, setOpen] = useState(false); + useEffect(() => { + setOpen((curr) => curr || isAnyChildOpen(node, isOpenFunc)); + }, [node, isOpenFunc]); + + return ( + <Collapsible open={open} onOpenChange={setOpen} className={className}> + {render({ + item: node, + level, + open, + })} + <CollapsibleContent> + {node.children.map((l) => ( + <ListItem + isOpenFunc={isOpenFunc} + key={l.item.id} + node={l} + render={render} + level={level + 1} + className={className} + /> + ))} + </CollapsibleContent> + </Collapsible> + ); +} + +export function CollapsibleBookmarkLists({ + render, + initialData, + className, + isOpenFunc, +}: { + initialData?: ZBookmarkList[]; + render: RenderFunc; + isOpenFunc?: IsOpenFunc; + className?: string; +}) { + let { data } = useBookmarkLists(undefined, { + initialData: initialData ? { lists: initialData } : undefined, + }); + + // TODO: This seems to be a bug in react query + if (initialData) { + data = augmentBookmarkListsWithInitialData(data, initialData); + } + + if (!data) { + return <FullPageSpinner />; + } + + const { root } = data; + + return ( + <div> + {Object.values(root).map((l) => ( + <ListItem + key={l.item.id} + node={l} + render={render} + level={0} + className={className} + isOpenFunc={isOpenFunc ?? (() => false)} + /> + ))} + </div> + ); +} diff --git a/apps/web/components/dashboard/lists/DeleteListButton.tsx b/apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx index 774b79ac..bf1969bf 100644 --- a/apps/web/components/dashboard/lists/DeleteListButton.tsx +++ b/apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx @@ -1,26 +1,34 @@ -"use client"; - -import { useRouter } from "next/navigation"; +import { usePathname, useRouter } from "next/navigation"; import { ActionButton } from "@/components/ui/action-button"; import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog"; -import { Button } from "@/components/ui/button"; import { toast } from "@/components/ui/use-toast"; -import { api } from "@/lib/trpc"; -import { Trash2 } from "lucide-react"; import type { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { useDeleteBookmarkList } from "@hoarder/shared-react/hooks/lists"; -export default function DeleteListButton({ list }: { list: ZBookmarkList }) { +export default function DeleteListConfirmationDialog({ + list, + children, + open, + setOpen, +}: { + list: ZBookmarkList; + children?: React.ReactNode; + open: boolean; + setOpen: (v: boolean) => void; +}) { + const currentPath = usePathname(); const router = useRouter(); - const listsInvalidationFunction = api.useUtils().lists.list.invalidate; - const { mutate: deleteList, isPending } = api.lists.delete.useMutation({ + const { mutate: deleteList, isPending } = useDeleteBookmarkList({ onSuccess: () => { - listsInvalidationFunction(); toast({ description: `List "${list.icon} ${list.name}" is deleted!`, }); - router.push("/"); + setOpen(false); + if (currentPath.includes(list.id)) { + router.push("/dashboard/lists"); + } }, onError: () => { toast({ @@ -29,8 +37,11 @@ export default function DeleteListButton({ list }: { list: ZBookmarkList }) { }); }, }); + return ( <ActionConfirmingDialog + open={open} + setOpen={setOpen} title={`Delete ${list.icon} ${list.name}?`} description={`Are you sure you want to delete ${list.icon} ${list.name}?`} actionButton={() => ( @@ -44,10 +55,7 @@ export default function DeleteListButton({ list }: { list: ZBookmarkList }) { </ActionButton> )} > - <Button className="mt-auto flex gap-2" variant="destructiveOutline"> - <Trash2 className="size-5" /> - <span className="hidden md:block">Delete List</span> - </Button> + {children} </ActionConfirmingDialog> ); } diff --git a/apps/web/components/dashboard/sidebar/NewListModal.tsx b/apps/web/components/dashboard/lists/EditListModal.tsx index 5169fbb5..993c975b 100644 --- a/apps/web/components/dashboard/sidebar/NewListModal.tsx +++ b/apps/web/components/dashboard/lists/EditListModal.tsx @@ -1,5 +1,5 @@ -"use client"; - +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; import { ActionButton } from "@/components/ui/action-button"; import { Button } from "@/components/ui/button"; import { @@ -9,12 +9,14 @@ import { DialogFooter, DialogHeader, DialogTitle, + DialogTrigger, } from "@/components/ui/dialog"; import { Form, FormControl, FormField, FormItem, + FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; @@ -24,46 +26,75 @@ import { PopoverTrigger, } from "@/components/ui/popover"; import { toast } from "@/components/ui/use-toast"; -import { api } from "@/lib/trpc"; import data from "@emoji-mart/data"; import Picker from "@emoji-mart/react"; import { zodResolver } from "@hookform/resolvers/zod"; +import { X } from "lucide-react"; import { useForm } from "react-hook-form"; import { z } from "zod"; -import { create } from "zustand"; -export const useNewListModal = create<{ - open: boolean; - setOpen: (v: boolean) => void; -}>((set) => ({ - open: false, - setOpen: (open: boolean) => set(() => ({ open })), -})); +import { + useCreateBookmarkList, + useEditBookmarkList, +} from "@hoarder/shared-react/hooks/lists"; +import { ZBookmarkList } from "@hoarder/shared/types/lists"; -export default function NewListModal() { - const { open, setOpen } = useNewListModal(); +import { BookmarkListSelector } from "./BookmarkListSelector"; +export function EditListModal({ + open: userOpen, + setOpen: userSetOpen, + list, + parent, + children, +}: { + open?: boolean; + setOpen?: (v: boolean) => void; + list?: ZBookmarkList; + parent?: ZBookmarkList; + children?: React.ReactNode; +}) { + const router = useRouter(); + if ( + (userOpen !== undefined && !userSetOpen) || + (userOpen === undefined && userSetOpen) + ) { + throw new Error("You must provide both open and setOpen or neither"); + } + const [customOpen, customSetOpen] = useState(false); const formSchema = z.object({ name: z.string(), icon: z.string(), + parentId: z.string().nullish(), }); const form = useForm<z.infer<typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues: { - name: "", - icon: "🚀", + name: list?.name ?? "", + icon: list?.icon ?? "🚀", + parentId: list?.parentId ?? parent?.id, }, }); + const [open, setOpen] = [ + userOpen ?? customOpen, + userSetOpen ?? customSetOpen, + ]; - const listsInvalidationFunction = api.useUtils().lists.list.invalidate; + useEffect(() => { + form.reset({ + name: list?.name ?? "", + icon: list?.icon ?? "🚀", + parentId: list?.parentId ?? parent?.id, + }); + }, [open]); - const { mutate: createList, isPending } = api.lists.create.useMutation({ - onSuccess: () => { + const { mutate: createList, isPending: isCreating } = useCreateBookmarkList({ + onSuccess: (resp) => { toast({ description: "List has been created!", }); - listsInvalidationFunction(); setOpen(false); + router.push(`/dashboard/lists/${resp.id}`); form.reset(); }, onError: (e) => { @@ -90,6 +121,41 @@ export default function NewListModal() { }, }); + const { mutate: editList, isPending: isEditing } = useEditBookmarkList({ + onSuccess: () => { + toast({ + description: "List has been updated!", + }); + setOpen(false); + form.reset(); + }, + onError: (e) => { + if (e.data?.code == "BAD_REQUEST") { + if (e.data.zodError) { + toast({ + variant: "destructive", + description: Object.values(e.data.zodError.fieldErrors) + .flat() + .join("\n"), + }); + } else { + toast({ + variant: "destructive", + description: e.message, + }); + } + } else { + toast({ + variant: "destructive", + title: "Something went wrong", + }); + } + }, + }); + + const isEdit = !!list; + const isPending = isCreating || isEditing; + return ( <Dialog open={open} @@ -98,15 +164,19 @@ export default function NewListModal() { setOpen(s); }} > + {children && <DialogTrigger asChild>{children}</DialogTrigger>} <DialogContent> <Form {...form}> <form onSubmit={form.handleSubmit((value) => { - createList(value); + value.parentId = value.parentId === "" ? null : value.parentId; + isEdit + ? editList({ ...value, listId: list.id }) + : createList(value); })} > <DialogHeader> - <DialogTitle>New List</DialogTitle> + <DialogTitle>{isEdit ? "Edit" : "New"} List</DialogTitle> </DialogHeader> <div className="flex w-full gap-2 py-4"> <FormField @@ -156,6 +226,38 @@ export default function NewListModal() { }} /> </div> + <FormField + control={form.control} + name="parentId" + render={({ field }) => { + return ( + <FormItem className="grow pb-4"> + <FormLabel>Parent</FormLabel> + <div className="flex items-center gap-1"> + <FormControl> + <BookmarkListSelector + // Hide the current list from the list of parents + hideSubtreeOf={list ? list.id : undefined} + value={field.value} + onChange={field.onChange} + placeholder={"No Parent"} + /> + </FormControl> + <Button + type="button" + variant="ghost" + onClick={() => { + form.reset({ parentId: null }); + }} + > + <X /> + </Button> + </div> + <FormMessage /> + </FormItem> + ); + }} + /> <DialogFooter className="sm:justify-end"> <DialogClose asChild> <Button type="button" variant="secondary"> @@ -163,7 +265,7 @@ export default function NewListModal() { </Button> </DialogClose> <ActionButton type="submit" loading={isPending}> - Create + {list ? "Save" : "Create"} </ActionButton> </DialogFooter> </form> diff --git a/apps/web/components/dashboard/lists/ListHeader.tsx b/apps/web/components/dashboard/lists/ListHeader.tsx new file mode 100644 index 00000000..6796d484 --- /dev/null +++ b/apps/web/components/dashboard/lists/ListHeader.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { MoreHorizontal } from "lucide-react"; + +import { api } from "@hoarder/shared-react/trpc"; +import { ZBookmarkList } from "@hoarder/shared/types/lists"; + +import { ListOptions } from "./ListOptions"; + +export default function ListHeader({ + initialData, +}: { + initialData: ZBookmarkList & { bookmarks: string[] }; +}) { + const router = useRouter(); + const { data: list, error } = api.lists.get.useQuery( + { + listId: initialData.id, + }, + { + initialData, + }, + ); + + if (error) { + // This is usually exercised during list deletions. + if (error.data?.code == "NOT_FOUND") { + router.push("/dashboard/lists"); + } + } + + return ( + <div className="flex justify-between"> + <span className="text-2xl"> + {list.icon} {list.name} + </span> + <ListOptions list={list}> + <Button variant="ghost"> + <MoreHorizontal /> + </Button> + </ListOptions> + </div> + ); +} diff --git a/apps/web/components/dashboard/lists/ListOptions.tsx b/apps/web/components/dashboard/lists/ListOptions.tsx new file mode 100644 index 00000000..b44d8a23 --- /dev/null +++ b/apps/web/components/dashboard/lists/ListOptions.tsx @@ -0,0 +1,71 @@ +"use client"; + +import { useState } from "react"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { Pencil, Plus, Trash2 } from "lucide-react"; + +import { ZBookmarkList } from "@hoarder/shared/types/lists"; + +import { EditListModal } from "../lists/EditListModal"; +import DeleteListConfirmationDialog from "./DeleteListConfirmationDialog"; + +export function ListOptions({ + list, + children, +}: { + list: ZBookmarkList; + children?: React.ReactNode; +}) { + const [deleteListDialogOpen, setDeleteListDialogOpen] = useState(false); + const [newNestedListModalOpen, setNewNestedListModalOpen] = useState(false); + const [editModalOpen, setEditModalOpen] = useState(false); + + return ( + <DropdownMenu> + <EditListModal + open={newNestedListModalOpen} + setOpen={setNewNestedListModalOpen} + parent={list} + /> + <EditListModal + open={editModalOpen} + setOpen={setEditModalOpen} + list={list} + /> + <DeleteListConfirmationDialog + list={list} + open={deleteListDialogOpen} + setOpen={setDeleteListDialogOpen} + /> + <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger> + <DropdownMenuContent> + <DropdownMenuItem + className="flex gap-2" + onClick={() => setEditModalOpen(true)} + > + <Pencil className="size-4" /> + <span>Edit</span> + </DropdownMenuItem> + <DropdownMenuItem + className="flex gap-2" + onClick={() => setNewNestedListModalOpen(true)} + > + <Plus className="size-4" /> + <span>New nested list</span> + </DropdownMenuItem> + <DropdownMenuItem + className="flex gap-2" + onClick={() => setDeleteListDialogOpen(true)} + > + <Trash2 className="size-4" /> + <span>Delete</span> + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + ); +} diff --git a/apps/web/components/dashboard/sidebar/AllLists.tsx b/apps/web/components/dashboard/sidebar/AllLists.tsx index 6ab42851..b1c6ddb2 100644 --- a/apps/web/components/dashboard/sidebar/AllLists.tsx +++ b/apps/web/components/dashboard/sidebar/AllLists.tsx @@ -1,12 +1,18 @@ "use client"; +import { useCallback } from "react"; import Link from "next/link"; -import { api } from "@/lib/trpc"; -import { Plus } from "lucide-react"; +import { usePathname } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { CollapsibleTriggerTriangle } from "@/components/ui/collapsible"; +import { MoreHorizontal, Plus } from "lucide-react"; import type { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { ZBookmarkListTreeNode } from "@hoarder/shared/utils/listUtils"; -import NewListModal, { useNewListModal } from "./NewListModal"; +import { CollapsibleBookmarkLists } from "../lists/CollapsibleBookmarkLists"; +import { EditListModal } from "../lists/EditListModal"; +import { ListOptions } from "../lists/ListOptions"; import SidebarItem from "./SidebarItem"; export default function AllLists({ @@ -14,21 +20,20 @@ export default function AllLists({ }: { initialData: { lists: ZBookmarkList[] }; }) { - let { data: lists } = api.lists.list.useQuery(undefined, { - initialData, - }); - // TODO: This seems to be a bug in react query - lists ||= initialData; - const { setOpen } = useNewListModal(); - + const pathName = usePathname(); + const isNodeOpen = useCallback( + (node: ZBookmarkListTreeNode) => pathName.includes(node.item.id), + [pathName], + ); return ( <ul className="max-h-full gap-y-2 overflow-auto text-sm font-medium"> - <NewListModal /> <li className="flex justify-between pb-2 font-bold"> <p>Lists</p> - <Link href="#" onClick={() => setOpen(true)}> - <Plus /> - </Link> + <EditListModal> + <Link href="#"> + <Plus /> + </Link> + </EditListModal> </li> <SidebarItem logo={<span className="text-lg">📋</span>} @@ -48,15 +53,45 @@ export default function AllLists({ path={`/dashboard/archive`} className="py-0.5" /> - {lists.lists.map((l) => ( - <SidebarItem - key={l.id} - logo={<span className="text-lg"> {l.icon}</span>} - name={l.name} - path={`/dashboard/lists/${l.id}`} - className="py-0.5" + + { + <CollapsibleBookmarkLists + initialData={initialData.lists} + isOpenFunc={isNodeOpen} + render={({ item: node, level, open }) => ( + <SidebarItem + collapseButton={ + node.children.length > 0 && ( + <CollapsibleTriggerTriangle + className="absolute left-0 top-1/2 size-2 -translate-y-1/2" + open={open} + /> + ) + } + logo={ + <span className="flex"> + <span className="text-lg"> {node.item.icon}</span> + </span> + } + name={node.item.name} + path={`/dashboard/lists/${node.item.id}`} + right={ + <ListOptions list={node.item}> + <Button + size="none" + variant="ghost" + className="invisible group-hover:visible" + > + <MoreHorizontal className="size-4" /> + </Button> + </ListOptions> + } + className="group py-0.5" + style={{ marginLeft: `${level * 1}rem` }} + /> + )} /> - ))} + } </ul> ); } diff --git a/apps/web/components/dashboard/sidebar/SidebarItem.tsx b/apps/web/components/dashboard/sidebar/SidebarItem.tsx index 7e5eb3bd..262fd9ae 100644 --- a/apps/web/components/dashboard/sidebar/SidebarItem.tsx +++ b/apps/web/components/dashboard/sidebar/SidebarItem.tsx @@ -1,5 +1,6 @@ "use client"; +import React from "react"; import Link from "next/link"; import { usePathname } from "next/navigation"; import { cn } from "@/lib/utils"; @@ -9,25 +10,36 @@ export default function SidebarItem({ logo, path, className, + style, + collapseButton, + right = null, }: { name: string; logo: React.ReactNode; path: string; + style?: React.CSSProperties; className?: string; + right?: React.ReactNode; + collapseButton?: React.ReactNode; }) { const currentPath = usePathname(); return ( <li className={cn( - "rounded-lg px-3 py-2 hover:bg-accent", + "relative rounded-lg px-3 py-2 hover:bg-accent", path == currentPath ? "bg-accent/50" : "", className, )} + style={style} > - <Link href={path} className="flex w-full gap-x-2"> - {logo} - <span className="my-auto"> {name} </span> - </Link> + {collapseButton} + <div className="flex justify-between"> + <Link href={path} className="flex w-full gap-x-2"> + {logo} + <span className="my-auto"> {name} </span> + </Link> + {right} + </div> </li> ); } diff --git a/apps/web/components/ui/action-confirming-dialog.tsx b/apps/web/components/ui/action-confirming-dialog.tsx index 980bdd60..37895ee7 100644 --- a/apps/web/components/ui/action-confirming-dialog.tsx +++ b/apps/web/components/ui/action-confirming-dialog.tsx @@ -1,5 +1,3 @@ -"use client"; - import { useState } from "react"; import { Dialog, @@ -18,14 +16,21 @@ export default function ActionConfirmingDialog({ description, actionButton, children, + open: userIsOpen, + setOpen: userSetOpen, }: { + open?: boolean; + setOpen?: (v: boolean) => void; title: React.ReactNode; description: React.ReactNode; actionButton: (setDialogOpen: (open: boolean) => void) => React.ReactNode; children: React.ReactNode; }) { - const [isDialogOpen, setDialogOpen] = useState(false); - + const [customIsOpen, setCustomIsOpen] = useState(false); + const [isDialogOpen, setDialogOpen] = [ + userIsOpen ?? customIsOpen, + userSetOpen ?? setCustomIsOpen, + ]; return ( <Dialog open={isDialogOpen} onOpenChange={setDialogOpen}> <DialogTrigger asChild>{children}</DialogTrigger> diff --git a/apps/web/components/ui/collapsible.tsx b/apps/web/components/ui/collapsible.tsx new file mode 100644 index 00000000..43f40402 --- /dev/null +++ b/apps/web/components/ui/collapsible.tsx @@ -0,0 +1,55 @@ +"use client"; + +import { cn } from "@/lib/utils"; +import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"; +import { ChevronRight, Triangle } from "lucide-react"; + +const Collapsible = CollapsiblePrimitive.Root; + +const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger; + +const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent; + +function CollapsibleTriggerTriangle({ + open, + className, +}: { + open: boolean; + className?: string; +}) { + return ( + <CollapsibleTrigger asChild> + <Triangle + className={cn( + "fill-foreground", + !open ? "rotate-90" : "rotate-180", + className, + )} + /> + </CollapsibleTrigger> + ); +} + +function CollapsibleTriggerChevron({ + open, + className, +}: { + open: boolean; + className?: string; +}) { + return ( + <CollapsibleTrigger asChild> + <ChevronRight + className={cn(!open ? "rotate-0" : "rotate-90", className)} + /> + </CollapsibleTrigger> + ); +} + +export { + Collapsible, + CollapsibleTrigger, + CollapsibleContent, + CollapsibleTriggerTriangle, + CollapsibleTriggerChevron, +}; diff --git a/apps/web/package.json b/apps/web/package.json index af8a286e..8f35e0ad 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -23,6 +23,7 @@ "@hoarder/shared-react": "workspace:^0.1.0", "@hoarder/trpc": "workspace:^0.1.0", "@hookform/resolvers": "^3.3.4", + "@radix-ui/react-collapsible": "^1.0.3", "@radix-ui/react-dialog": "^1.0.5", "@radix-ui/react-dropdown-menu": "^2.0.6", "@radix-ui/react-label": "^2.0.2", diff --git a/packages/db/drizzle/0019_many_vertigo.sql b/packages/db/drizzle/0019_many_vertigo.sql new file mode 100644 index 00000000..7b58bf85 --- /dev/null +++ b/packages/db/drizzle/0019_many_vertigo.sql @@ -0,0 +1,2 @@ +DROP INDEX IF EXISTS `bookmarkLists_name_userId_unique`;--> statement-breakpoint +ALTER TABLE bookmarkLists ADD `parentId` text REFERENCES bookmarkLists(id) ON DELETE SET NULL; diff --git a/packages/db/drizzle/meta/0019_snapshot.json b/packages/db/drizzle/meta/0019_snapshot.json new file mode 100644 index 00000000..b60ba498 --- /dev/null +++ b/packages/db/drizzle/meta/0019_snapshot.json @@ -0,0 +1,986 @@ +{ + "version": "5", + "dialect": "sqlite", + "id": "3e975d6c-1289-487f-8e78-6f4eda5243d2", + "prevId": "ca4ff2bd-aed3-474d-92a1-68e3a8349e01", + "tables": { + "account": { + "name": "account", + "columns": { + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "providerAccountId": { + "name": "providerAccountId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_type": { + "name": "token_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_state": { + "name": "session_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "account_userId_user_id_fk": { + "name": "account_userId_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "account_provider_providerAccountId_pk": { + "columns": [ + "provider", + "providerAccountId" + ], + "name": "account_provider_providerAccountId_pk" + } + }, + "uniqueConstraints": {} + }, + "apiKey": { + "name": "apiKey", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyId": { + "name": "keyId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyHash": { + "name": "keyHash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "apiKey_keyId_unique": { + "name": "apiKey_keyId_unique", + "columns": [ + "keyId" + ], + "isUnique": true + }, + "apiKey_name_userId_unique": { + "name": "apiKey_name_userId_unique", + "columns": [ + "name", + "userId" + ], + "isUnique": true + } + }, + "foreignKeys": { + "apiKey_userId_user_id_fk": { + "name": "apiKey_userId_user_id_fk", + "tableFrom": "apiKey", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarkAssets": { + "name": "bookmarkAssets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "assetType": { + "name": "assetType", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assetId": { + "name": "assetId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fileName": { + "name": "fileName", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "bookmarkAssets_id_bookmarks_id_fk": { + "name": "bookmarkAssets_id_bookmarks_id_fk", + "tableFrom": "bookmarkAssets", + "tableTo": "bookmarks", + "columnsFrom": [ + "id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarkLinks": { + "name": "bookmarkLinks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "imageUrl": { + "name": "imageUrl", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "favicon": { + "name": "favicon", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "htmlContent": { + "name": "htmlContent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crawledAt": { + "name": "crawledAt", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "crawlStatus": { + "name": "crawlStatus", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'pending'" + } + }, + "indexes": {}, + "foreignKeys": { + "bookmarkLinks_id_bookmarks_id_fk": { + "name": "bookmarkLinks_id_bookmarks_id_fk", + "tableFrom": "bookmarkLinks", + "tableTo": "bookmarks", + "columnsFrom": [ + "id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarkLists": { + "name": "bookmarkLists", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parentId": { + "name": "parentId", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "bookmarkLists_userId_idx": { + "name": "bookmarkLists_userId_idx", + "columns": [ + "userId" + ], + "isUnique": false + } + }, + "foreignKeys": { + "bookmarkLists_userId_user_id_fk": { + "name": "bookmarkLists_userId_user_id_fk", + "tableFrom": "bookmarkLists", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "bookmarkLists_parentId_bookmarkLists_id_fk": { + "name": "bookmarkLists_parentId_bookmarkLists_id_fk", + "tableFrom": "bookmarkLists", + "tableTo": "bookmarkLists", + "columnsFrom": [ + "parentId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarkTags": { + "name": "bookmarkTags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "bookmarkTags_name_idx": { + "name": "bookmarkTags_name_idx", + "columns": [ + "name" + ], + "isUnique": false + }, + "bookmarkTags_userId_idx": { + "name": "bookmarkTags_userId_idx", + "columns": [ + "userId" + ], + "isUnique": false + }, + "bookmarkTags_userId_name_unique": { + "name": "bookmarkTags_userId_name_unique", + "columns": [ + "userId", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "bookmarkTags_userId_user_id_fk": { + "name": "bookmarkTags_userId_user_id_fk", + "tableFrom": "bookmarkTags", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarkTexts": { + "name": "bookmarkTexts", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "bookmarkTexts_id_bookmarks_id_fk": { + "name": "bookmarkTexts_id_bookmarks_id_fk", + "tableFrom": "bookmarkTexts", + "tableTo": "bookmarks", + "columnsFrom": [ + "id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarks": { + "name": "bookmarks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "archived": { + "name": "archived", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "favourited": { + "name": "favourited", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "taggingStatus": { + "name": "taggingStatus", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'pending'" + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "bookmarks_userId_idx": { + "name": "bookmarks_userId_idx", + "columns": [ + "userId" + ], + "isUnique": false + }, + "bookmarks_archived_idx": { + "name": "bookmarks_archived_idx", + "columns": [ + "archived" + ], + "isUnique": false + }, + "bookmarks_favourited_idx": { + "name": "bookmarks_favourited_idx", + "columns": [ + "favourited" + ], + "isUnique": false + }, + "bookmarks_createdAt_idx": { + "name": "bookmarks_createdAt_idx", + "columns": [ + "createdAt" + ], + "isUnique": false + } + }, + "foreignKeys": { + "bookmarks_userId_user_id_fk": { + "name": "bookmarks_userId_user_id_fk", + "tableFrom": "bookmarks", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "bookmarksInLists": { + "name": "bookmarksInLists", + "columns": { + "bookmarkId": { + "name": "bookmarkId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "listId": { + "name": "listId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "addedAt": { + "name": "addedAt", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "bookmarksInLists_bookmarkId_idx": { + "name": "bookmarksInLists_bookmarkId_idx", + "columns": [ + "bookmarkId" + ], + "isUnique": false + }, + "bookmarksInLists_listId_idx": { + "name": "bookmarksInLists_listId_idx", + "columns": [ + "listId" + ], + "isUnique": false + } + }, + "foreignKeys": { + "bookmarksInLists_bookmarkId_bookmarks_id_fk": { + "name": "bookmarksInLists_bookmarkId_bookmarks_id_fk", + "tableFrom": "bookmarksInLists", + "tableTo": "bookmarks", + "columnsFrom": [ + "bookmarkId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "bookmarksInLists_listId_bookmarkLists_id_fk": { + "name": "bookmarksInLists_listId_bookmarkLists_id_fk", + "tableFrom": "bookmarksInLists", + "tableTo": "bookmarkLists", + "columnsFrom": [ + "listId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "bookmarksInLists_bookmarkId_listId_pk": { + "columns": [ + "bookmarkId", + "listId" + ], + "name": "bookmarksInLists_bookmarkId_listId_pk" + } + }, + "uniqueConstraints": {} + }, + "session": { + "name": "session", + "columns": { + "sessionToken": { + "name": "sessionToken", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "session_userId_user_id_fk": { + "name": "session_userId_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "userId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "tagsOnBookmarks": { + "name": "tagsOnBookmarks", + "columns": { + "bookmarkId": { + "name": "bookmarkId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tagId": { + "name": "tagId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attachedAt": { + "name": "attachedAt", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attachedBy": { + "name": "attachedBy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tagsOnBookmarks_tagId_idx": { + "name": "tagsOnBookmarks_tagId_idx", + "columns": [ + "bookmarkId" + ], + "isUnique": false + }, + "tagsOnBookmarks_bookmarkId_idx": { + "name": "tagsOnBookmarks_bookmarkId_idx", + "columns": [ + "bookmarkId" + ], + "isUnique": false + } + }, + "foreignKeys": { + "tagsOnBookmarks_bookmarkId_bookmarks_id_fk": { + "name": "tagsOnBookmarks_bookmarkId_bookmarks_id_fk", + "tableFrom": "tagsOnBookmarks", + "tableTo": "bookmarks", + "columnsFrom": [ + "bookmarkId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tagsOnBookmarks_tagId_bookmarkTags_id_fk": { + "name": "tagsOnBookmarks_tagId_bookmarkTags_id_fk", + "tableFrom": "tagsOnBookmarks", + "tableTo": "bookmarkTags", + "columnsFrom": [ + "tagId" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "tagsOnBookmarks_bookmarkId_tagId_pk": { + "columns": [ + "bookmarkId", + "tagId" + ], + "name": "tagsOnBookmarks_bookmarkId_tagId_pk" + } + }, + "uniqueConstraints": {} + }, + "user": { + "name": "user", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "emailVerified": { + "name": "emailVerified", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'user'" + } + }, + "indexes": { + "user_email_unique": { + "name": "user_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {} + }, + "verificationToken": { + "name": "verificationToken", + "columns": { + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "verificationToken_identifier_token_pk": { + "columns": [ + "identifier", + "token" + ], + "name": "verificationToken_identifier_token_pk" + } + }, + "uniqueConstraints": {} + } + }, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + } +}
\ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 89dc6610..67a48b68 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -134,6 +134,13 @@ "when": 1713183014188, "tag": "0018_bright_infant_terrible", "breakpoints": true + }, + { + "idx": 19, + "version": "5", + "when": 1713432890859, + "tag": "0019_many_vertigo", + "breakpoints": true } ] }
\ No newline at end of file diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 6a7128c0..037be814 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -2,6 +2,7 @@ import type { AdapterAccount } from "@auth/core/adapters"; import { createId } from "@paralleldrive/cuid2"; import { relations } from "drizzle-orm"; import { + AnySQLiteColumn, index, integer, primaryKey, @@ -223,9 +224,10 @@ export const bookmarkLists = sqliteTable( userId: text("userId") .notNull() .references(() => users.id, { onDelete: "cascade" }), + parentId: text("parentId") + .references((): AnySQLiteColumn => bookmarkLists.id, { onDelete: "set null" }), }, (bl) => ({ - unq: unique().on(bl.name, bl.userId), userIdIdx: index("bookmarkLists_userId_idx").on(bl.userId), }), ); @@ -318,6 +320,10 @@ export const bookmarkListsRelations = relations( fields: [bookmarkLists.userId], references: [users.id], }), + parent: one(bookmarkLists, { + fields: [bookmarkLists.parentId], + references: [bookmarkLists.id], + }), }), ); diff --git a/packages/shared-react/hooks/bookmarks.ts b/packages/shared-react/hooks/bookmarks.ts index 5f246b38..2a549d1f 100644 --- a/packages/shared-react/hooks/bookmarks.ts +++ b/packages/shared-react/hooks/bookmarks.ts @@ -8,7 +8,7 @@ export function useCreateBookmarkWithPostHook( const apiUtils = api.useUtils(); const postCreationCB = useBookmarkPostCreationHook(); return api.bookmarks.createBookmark.useMutation({ - ...opts, + ...opts[0], onSuccess: async (res, req, meta) => { apiUtils.bookmarks.getBookmarks.invalidate(); apiUtils.bookmarks.searchBookmarks.invalidate(); @@ -23,7 +23,7 @@ export function useDeleteBookmark( ) { const apiUtils = api.useUtils(); return api.bookmarks.deleteBookmark.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmarks.invalidate(); apiUtils.bookmarks.searchBookmarks.invalidate(); @@ -37,7 +37,7 @@ export function useUpdateBookmark( ) { const apiUtils = api.useUtils(); return api.bookmarks.updateBookmark.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmarks.invalidate(); apiUtils.bookmarks.searchBookmarks.invalidate(); @@ -52,7 +52,7 @@ export function useRecrawlBookmark( ) { const apiUtils = api.useUtils(); return api.bookmarks.recrawlBookmark.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmark.invalidate({ bookmarkId: req.bookmarkId }); return opts[0]?.onSuccess?.(res, req, meta); @@ -65,7 +65,7 @@ export function useUpdateBookmarkTags( ) { const apiUtils = api.useUtils(); return api.bookmarks.updateTags.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmark.invalidate({ bookmarkId: req.bookmarkId }); diff --git a/packages/shared-react/hooks/lists.ts b/packages/shared-react/hooks/lists.ts index d5654f9f..61e50689 100644 --- a/packages/shared-react/hooks/lists.ts +++ b/packages/shared-react/hooks/lists.ts @@ -1,11 +1,44 @@ +import { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { + listsToTree, + ZBookmarkListRoot, +} from "@hoarder/shared/utils/listUtils"; + import { api } from "../trpc"; +export function useCreateBookmarkList( + ...opts: Parameters<typeof api.lists.create.useMutation> +) { + const apiUtils = api.useUtils(); + return api.lists.create.useMutation({ + ...opts[0], + onSuccess: (res, req, meta) => { + apiUtils.lists.list.invalidate(); + return opts[0]?.onSuccess?.(res, req, meta); + }, + }); +} + +export function useEditBookmarkList( + ...opts: Parameters<typeof api.lists.edit.useMutation> +) { + const apiUtils = api.useUtils(); + return api.lists.edit.useMutation({ + ...opts[0], + onSuccess: (res, req, meta) => { + apiUtils.lists.list.invalidate(); + apiUtils.lists.get.invalidate({ listId: req.listId }); + return opts[0]?.onSuccess?.(res, req, meta); + }, + }); +} + export function useAddBookmarkToList( ...opts: Parameters<typeof api.lists.addToList.useMutation> ) { const apiUtils = api.useUtils(); return api.lists.addToList.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmarks.invalidate({ listId: req.listId }); return opts[0]?.onSuccess?.(res, req, meta); @@ -18,10 +51,51 @@ export function useRemoveBookmarkFromList( ) { const apiUtils = api.useUtils(); return api.lists.removeFromList.useMutation({ - ...opts, + ...opts[0], onSuccess: (res, req, meta) => { apiUtils.bookmarks.getBookmarks.invalidate({ listId: req.listId }); return opts[0]?.onSuccess?.(res, req, meta); }, }); } + +export function useDeleteBookmarkList( + ...opts: Parameters<typeof api.lists.delete.useMutation> +) { + const apiUtils = api.useUtils(); + return api.lists.delete.useMutation({ + ...opts[0], + onSuccess: (res, req, meta) => { + apiUtils.lists.list.invalidate(); + apiUtils.lists.get.invalidate({ listId: req.listId }); + return opts[0]?.onSuccess?.(res, req, meta); + }, + }); +} + +export function useBookmarkLists( + ...opts: Parameters<typeof api.lists.list.useQuery> +) { + return api.lists.list.useQuery(opts[0], { + ...opts[1], + select: (data) => { + return { data: data.lists, ...listsToTree(data.lists) }; + }, + }); +} + +export function augmentBookmarkListsWithInitialData( + data: + | { + data: ZBookmarkList[]; + root: ZBookmarkListRoot; + allPaths: ZBookmarkList[][]; + } + | undefined, + initialData: ZBookmarkList[], +) { + if (data) { + return data; + } + return { data: initialData, ...listsToTree(initialData) }; +} diff --git a/packages/shared/utils/listUtils.ts b/packages/shared/utils/listUtils.ts new file mode 100644 index 00000000..1dd3d476 --- /dev/null +++ b/packages/shared/utils/listUtils.ts @@ -0,0 +1,55 @@ +import { ZBookmarkList } from "../types/lists"; + +export interface ZBookmarkListTreeNode { + item: ZBookmarkList; + children: ZBookmarkListTreeNode[]; +} + +export type ZBookmarkListRoot = Record<string, ZBookmarkListTreeNode>; + +export function listsToTree(lists: ZBookmarkList[]) { + const idToList = lists.reduce<Record<string, ZBookmarkList>>((acc, list) => { + acc[list.id] = list; + return acc; + }, {}); + + const root: ZBookmarkListRoot = {}; + + // Prepare all refs + const refIdx = lists.reduce<Record<string, ZBookmarkListTreeNode>>( + (acc, l) => { + acc[l.id] = { + item: l, + children: [], + }; + return acc; + }, + {}, + ); + + // Build the tree + lists.forEach((list) => { + const node = refIdx[list.id]; + if (list.parentId) { + refIdx[list.parentId].children.push(node); + } else { + root[list.id] = node; + } + }); + + const allPaths: ZBookmarkList[][] = []; + const dfs = (node: ZBookmarkListTreeNode, path: ZBookmarkList[]) => { + const list = idToList[node.item.id]; + const newPath = [...path, list]; + allPaths.push(newPath); + node.children.forEach((child) => { + dfs(child, newPath); + }); + }; + + Object.values(root).forEach((node) => { + dfs(node, []); + }); + + return { allPaths, root }; +} diff --git a/packages/trpc/routers/lists.ts b/packages/trpc/routers/lists.ts index 74b4f737..5cab0ac3 100644 --- a/packages/trpc/routers/lists.ts +++ b/packages/trpc/routers/lists.ts @@ -10,6 +10,15 @@ import type { Context } from "../index"; import { authedProcedure, router } from "../index"; import { ensureBookmarkOwnership } from "./bookmarks"; +const zNewBookmarkListSchema = z.object({ + name: z + .string() + .min(1, "List name can't be empty") + .max(20, "List name is at most 20 chars"), + icon: z.string(), + parentId: z.string().nullish(), +}); + export const ensureListOwnership = experimental_trpcMiddleware<{ ctx: Context; input: { listId: string }; @@ -44,41 +53,50 @@ export const ensureListOwnership = experimental_trpcMiddleware<{ export const listsAppRouter = router({ create: authedProcedure + .input(zNewBookmarkListSchema) + .output(zBookmarkListSchema) + .mutation(async ({ input, ctx }) => { + const [result] = await ctx.db + .insert(bookmarkLists) + .values({ + name: input.name, + icon: input.icon, + userId: ctx.user.id, + parentId: input.parentId, + }) + .returning(); + return result; + }), + edit: authedProcedure .input( - z.object({ - name: z - .string() - .min(1, "List name can't be empty") - .max(20, "List name is at most 20 chars"), - icon: z.string(), - }), + zNewBookmarkListSchema + .partial() + .merge(z.object({ listId: z.string() })) + .refine((val) => val.parentId != val.listId, { + message: "List can't be its own parent", + path: ["parentId"], + }), ) .output(zBookmarkListSchema) .mutation(async ({ input, ctx }) => { - try { - const result = await ctx.db - .insert(bookmarkLists) - .values({ - name: input.name, - icon: input.icon, - userId: ctx.user.id, - }) - .returning(); - return result[0]; - } catch (e) { - if (e instanceof SqliteError) { - if (e.code == "SQLITE_CONSTRAINT_UNIQUE") { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "List already exists", - }); - } - } - throw new TRPCError({ - code: "INTERNAL_SERVER_ERROR", - message: "Something went wrong", - }); + const result = await ctx.db + .update(bookmarkLists) + .set({ + name: input.name, + icon: input.icon, + parentId: input.parentId, + }) + .where( + and( + eq(bookmarkLists.id, input.listId), + eq(bookmarkLists.userId, ctx.user.id), + ), + ) + .returning(); + if (result.length == 0) { + throw new TRPCError({ code: "NOT_FOUND" }); } + return result[0]; }), delete: authedProcedure .input( @@ -187,6 +205,7 @@ export const listsAppRouter = router({ id: res.id, name: res.name, icon: res.icon, + parentId: res.parentId, bookmarks: res.bookmarksInLists.map((b) => b.bookmarkId), }; }), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d5c4915c..0e64f565 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -425,6 +425,9 @@ importers: '@hookform/resolvers': specifier: ^3.3.4 version: 3.3.4(react-hook-form@7.50.1(react@18.2.0)) + '@radix-ui/react-collapsible': + specifier: ^1.0.3 + version: 1.0.3(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0) '@radix-ui/react-dialog': specifier: ^1.0.5 version: 1.0.5(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0) @@ -2977,6 +2980,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-collapsible@1.0.3': + resolution: {integrity: sha512-UBmVDkmR6IvDsloHVN+3rtx4Mi5TFvylYXpluuv0f37dtaz3H99bp8No0LGXRigVpl3UAT4l9j6bIchh42S/Gg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-collection@1.0.3': resolution: {integrity: sha512-3SzW+0PW7yBBoQlT8wNcGtaxaD0XSu0uLUFgrtHY08Acx05TaHaOmVLR73c0j/cqpDy53KBMO7s0dx2wmOIDIA==} peerDependencies: @@ -16185,6 +16201,23 @@ snapshots: react-dom: 18.2.0(react@18.2.0) dev: false + '@radix-ui/react-collapsible@1.0.3(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)': + dependencies: + '@babel/runtime': 7.23.9 + '@radix-ui/primitive': 1.0.1 + '@radix-ui/react-compose-refs': 1.0.1(@types/react@18.2.58)(react@18.2.0) + '@radix-ui/react-context': 1.0.1(@types/react@18.2.58)(react@18.2.0) + '@radix-ui/react-id': 1.0.1(@types/react@18.2.58)(react@18.2.0) + '@radix-ui/react-presence': 1.0.1(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0) + '@radix-ui/react-primitive': 1.0.3(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0) + '@radix-ui/react-use-controllable-state': 1.0.1(@types/react@18.2.58)(react@18.2.0) + '@radix-ui/react-use-layout-effect': 1.0.1(@types/react@18.2.58)(react@18.2.0) + '@types/react': 18.2.58 + '@types/react-dom': 18.2.19 + react: 18.2.0 + react-dom: 18.2.0(react@18.2.0) + dev: false + '@radix-ui/react-collection@1.0.3(@types/react-dom@18.2.19)(@types/react@18.2.58)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)': dependencies: '@babel/runtime': 7.23.9 |
