From e0999f701cd1834c3d940113cd8dd5247c5fe95f Mon Sep 17 00:00:00 2001 From: Mohamed Bassem Date: Fri, 19 Apr 2024 00:09:27 +0100 Subject: feature: Nested lists (#110). Fixes #62 * feature: Add support for nested lists * prevent moving the parent to a subtree --- apps/web/app/dashboard/lists/[listId]/page.tsx | 11 +- .../dashboard/bookmarks/AddToListModal.tsx | 79 +- .../components/dashboard/lists/AllListsView.tsx | 113 ++- .../dashboard/lists/BookmarkListSelector.tsx | 63 ++ .../dashboard/lists/CollapsibleBookmarkLists.tsx | 111 +++ .../dashboard/lists/DeleteListButton.tsx | 53 -- .../lists/DeleteListConfirmationDialog.tsx | 61 ++ .../components/dashboard/lists/EditListModal.tsx | 276 ++++++ apps/web/components/dashboard/lists/ListHeader.tsx | 46 + .../web/components/dashboard/lists/ListOptions.tsx | 71 ++ apps/web/components/dashboard/sidebar/AllLists.tsx | 79 +- .../components/dashboard/sidebar/NewListModal.tsx | 174 ---- .../components/dashboard/sidebar/SidebarItem.tsx | 22 +- .../web/components/ui/action-confirming-dialog.tsx | 13 +- apps/web/components/ui/collapsible.tsx | 55 ++ apps/web/package.json | 1 + packages/db/drizzle/0019_many_vertigo.sql | 2 + packages/db/drizzle/meta/0019_snapshot.json | 986 +++++++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/schema.ts | 8 +- packages/shared-react/hooks/bookmarks.ts | 10 +- packages/shared-react/hooks/lists.ts | 78 +- packages/shared/utils/listUtils.ts | 55 ++ packages/trpc/routers/lists.ts | 79 +- pnpm-lock.yaml | 33 + 25 files changed, 2084 insertions(+), 402 deletions(-) create mode 100644 apps/web/components/dashboard/lists/BookmarkListSelector.tsx create mode 100644 apps/web/components/dashboard/lists/CollapsibleBookmarkLists.tsx delete mode 100644 apps/web/components/dashboard/lists/DeleteListButton.tsx create mode 100644 apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx create mode 100644 apps/web/components/dashboard/lists/EditListModal.tsx create mode 100644 apps/web/components/dashboard/lists/ListHeader.tsx create mode 100644 apps/web/components/dashboard/lists/ListOptions.tsx delete mode 100644 apps/web/components/dashboard/sidebar/NewListModal.tsx create mode 100644 apps/web/components/ui/collapsible.tsx create mode 100644 packages/db/drizzle/0019_many_vertigo.sql create mode 100644 packages/db/drizzle/meta/0019_snapshot.json create mode 100644 packages/shared/utils/listUtils.ts 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={ -
- - {list.icon} {list.name} - - -
- } + header={} /> ); } 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 ( @@ -98,42 +83,20 @@ export default function AddToListModal({
- {lists ? ( - { - return ( - - - - - - - ); - }} - /> - ) : ( - - )} + { + return ( + + + + + + + ); + }} + />
@@ -144,7 +107,7 @@ export default function AddToListModal({ Add 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 ( - -
-

- {icon} {name} -

-
- +
  • + + {collapsible && ( + + )} + +

    + {icon} {name} +

    + +
    + {list && ( + + + + )} +
  • ); } @@ -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 ( -
    - - - - {lists.lists.map((l) => ( - - ))} -
    +
      + + + + + + ( + 0} + open={open} + style={{ marginLeft: `${level * 1}rem` }} + /> + )} + /> +
    ); } 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 ; + } + + allPaths = allPaths?.filter((path) => { + if (!hideSubtreeOf) { + return true; + } + return !path.map((p) => p.id).includes(hideSubtreeOf); + }); + + return ( + + ); +} 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 ( + + {render({ + item: node, + level, + open, + })} + + {node.children.map((l) => ( + + ))} + + + ); +} + +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 ; + } + + const { root } = data; + + return ( +
    + {Object.values(root).map((l) => ( + false)} + /> + ))} +
    + ); +} diff --git a/apps/web/components/dashboard/lists/DeleteListButton.tsx b/apps/web/components/dashboard/lists/DeleteListButton.tsx deleted file mode 100644 index 774b79ac..00000000 --- a/apps/web/components/dashboard/lists/DeleteListButton.tsx +++ /dev/null @@ -1,53 +0,0 @@ -"use client"; - -import { 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"; - -export default function DeleteListButton({ list }: { list: ZBookmarkList }) { - const router = useRouter(); - - const listsInvalidationFunction = api.useUtils().lists.list.invalidate; - const { mutate: deleteList, isPending } = api.lists.delete.useMutation({ - onSuccess: () => { - listsInvalidationFunction(); - toast({ - description: `List "${list.icon} ${list.name}" is deleted!`, - }); - router.push("/"); - }, - onError: () => { - toast({ - variant: "destructive", - description: `Something went wrong`, - }); - }, - }); - return ( - ( - deleteList({ listId: list.id })} - > - Delete - - )} - > - - - ); -} diff --git a/apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx b/apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx new file mode 100644 index 00000000..bf1969bf --- /dev/null +++ b/apps/web/components/dashboard/lists/DeleteListConfirmationDialog.tsx @@ -0,0 +1,61 @@ +import { usePathname, useRouter } from "next/navigation"; +import { ActionButton } from "@/components/ui/action-button"; +import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog"; +import { toast } from "@/components/ui/use-toast"; + +import type { ZBookmarkList } from "@hoarder/shared/types/lists"; +import { useDeleteBookmarkList } from "@hoarder/shared-react/hooks/lists"; + +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 { mutate: deleteList, isPending } = useDeleteBookmarkList({ + onSuccess: () => { + toast({ + description: `List "${list.icon} ${list.name}" is deleted!`, + }); + setOpen(false); + if (currentPath.includes(list.id)) { + router.push("/dashboard/lists"); + } + }, + onError: () => { + toast({ + variant: "destructive", + description: `Something went wrong`, + }); + }, + }); + + return ( + ( + deleteList({ listId: list.id })} + > + Delete + + )} + > + {children} + + ); +} diff --git a/apps/web/components/dashboard/lists/EditListModal.tsx b/apps/web/components/dashboard/lists/EditListModal.tsx new file mode 100644 index 00000000..993c975b --- /dev/null +++ b/apps/web/components/dashboard/lists/EditListModal.tsx @@ -0,0 +1,276 @@ +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { ActionButton } from "@/components/ui/action-button"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogClose, + DialogContent, + 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"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { toast } from "@/components/ui/use-toast"; +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 { + useCreateBookmarkList, + useEditBookmarkList, +} from "@hoarder/shared-react/hooks/lists"; +import { ZBookmarkList } from "@hoarder/shared/types/lists"; + +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>({ + resolver: zodResolver(formSchema), + defaultValues: { + name: list?.name ?? "", + icon: list?.icon ?? "🚀", + parentId: list?.parentId ?? parent?.id, + }, + }); + const [open, setOpen] = [ + userOpen ?? customOpen, + userSetOpen ?? customSetOpen, + ]; + + useEffect(() => { + form.reset({ + name: list?.name ?? "", + icon: list?.icon ?? "🚀", + parentId: list?.parentId ?? parent?.id, + }); + }, [open]); + + const { mutate: createList, isPending: isCreating } = useCreateBookmarkList({ + onSuccess: (resp) => { + toast({ + description: "List has been created!", + }); + setOpen(false); + router.push(`/dashboard/lists/${resp.id}`); + 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 { 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 ( + { + form.reset(); + setOpen(s); + }} + > + {children && {children}} + +
    + { + value.parentId = value.parentId === "" ? null : value.parentId; + isEdit + ? editList({ ...value, listId: list.id }) + : createList(value); + })} + > + + {isEdit ? "Edit" : "New"} List + +
    + { + return ( + + + + + {field.value} + + + + field.onChange(e.native) + } + /> + + + + + + ); + }} + /> + + { + return ( + + + + + + + ); + }} + /> +
    + { + return ( + + Parent +
    + + + + +
    + +
    + ); + }} + /> + + + + + + {list ? "Save" : "Create"} + + + + +
    +
    + ); +} 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 ( +
    + + {list.icon} {list.name} + + + + +
    + ); +} 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 ( + + + + + {children} + + setEditModalOpen(true)} + > + + Edit + + setNewNestedListModalOpen(true)} + > + + New nested list + + setDeleteListDialogOpen(true)} + > + + Delete + + + + ); +} 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 (
      -
    • Lists

      - setOpen(true)}> - - + + + + +
    • 📋} @@ -48,15 +53,45 @@ export default function AllLists({ path={`/dashboard/archive`} className="py-0.5" /> - {lists.lists.map((l) => ( - {l.icon}} - name={l.name} - path={`/dashboard/lists/${l.id}`} - className="py-0.5" + + { + ( + 0 && ( + + ) + } + logo={ + + {node.item.icon} + + } + name={node.item.name} + path={`/dashboard/lists/${node.item.id}`} + right={ + + + + } + className="group py-0.5" + style={{ marginLeft: `${level * 1}rem` }} + /> + )} /> - ))} + }
    ); } diff --git a/apps/web/components/dashboard/sidebar/NewListModal.tsx b/apps/web/components/dashboard/sidebar/NewListModal.tsx deleted file mode 100644 index 5169fbb5..00000000 --- a/apps/web/components/dashboard/sidebar/NewListModal.tsx +++ /dev/null @@ -1,174 +0,0 @@ -"use client"; - -import { ActionButton } from "@/components/ui/action-button"; -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogClose, - DialogContent, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { - Form, - FormControl, - FormField, - FormItem, - FormMessage, -} from "@/components/ui/form"; -import { Input } from "@/components/ui/input"; -import { - Popover, - PopoverContent, - 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 { 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 })), -})); - -export default function NewListModal() { - const { open, setOpen } = useNewListModal(); - - const formSchema = z.object({ - name: z.string(), - icon: z.string(), - }); - const form = useForm>({ - resolver: zodResolver(formSchema), - defaultValues: { - name: "", - icon: "🚀", - }, - }); - - const listsInvalidationFunction = api.useUtils().lists.list.invalidate; - - const { mutate: createList, isPending } = api.lists.create.useMutation({ - onSuccess: () => { - toast({ - description: "List has been created!", - }); - listsInvalidationFunction(); - 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", - }); - } - }, - }); - - return ( - { - form.reset(); - setOpen(s); - }} - > - -
    - { - createList(value); - })} - > - - New List - -
    - { - return ( - - - - - {field.value} - - - - field.onChange(e.native) - } - /> - - - - - - ); - }} - /> - - { - return ( - - - - - - - ); - }} - /> -
    - - - - - - Create - - -
    - -
    -
    - ); -} 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 (
  • - - {logo} - {name} - + {collapseButton} +
    + + {logo} + {name} + + {right} +
  • ); } 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 ( {children} 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 ( + + + + ); +} + +function CollapsibleTriggerChevron({ + open, + className, +}: { + open: boolean; + className?: string; +}) { + return ( + + + + ); +} + +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 +) { + 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 +) { + 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 ) { 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 +) { + 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 +) { + 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; + +export function listsToTree(lists: ZBookmarkList[]) { + const idToList = lists.reduce>((acc, list) => { + acc[list.id] = list; + return acc; + }, {}); + + const root: ZBookmarkListRoot = {}; + + // Prepare all refs + const refIdx = lists.reduce>( + (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 -- cgit v1.2.3-70-g09d2