⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
basic endpoint, drag and drop, and ordering on dashboard
Isaac29d90db9918f
diff --git a/apps/web/components/DashboardLayoutDropdown.tsx b/apps/web/components/DashboardLayoutDropdown.tsxindex 2770acb1..0d50bf27 100644--- a/apps/web/components/DashboardLayoutDropdown.tsx+++ b/apps/web/components/DashboardLayoutDropdown.tsx@@ -11,6 +11,14 @@ import { useCollections } from "@linkwarden/router/collections";import { DashboardSection, DashboardSectionType } from "@linkwarden/prisma/client";import { useUser } from "@linkwarden/router/user";import { useUpdateDashboardLayout } from "@linkwarden/router/dashboardData";+import {+ draggable,+ dropTargetForElements,+ monitorForElements+} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';+import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';+import { reorder } from '@atlaskit/pragmatic-drag-and-drop/reorder';+import { triggerPostMoveFlash } from '@atlaskit/pragmatic-drag-and-drop-flourish/trigger-post-move-flash';interface DashboardSectionOption {type: DashboardSectionType;@@ -26,6 +34,8 @@ export default function DashboardLayoutDropdown() {const { data: collections = [] } = useCollections();const updateDashboardLayout = useUpdateDashboardLayout();const [searchTerm, setSearchTerm] = useState("");+ const [isDraggedOver, setIsDraggedOver] = useState<string | null>(null);+ const [draggedItem, setDraggedItem] = useState<string | null>(null);const dashboardSections: DashboardSection[] = user?.dashboardSections || [];@@ -106,6 +116,52 @@ export default function DashboardLayoutDropdown() {return [...enabledSections, ...disabledSections];}, [allSections, searchTerm]);+ const getSectionId = (section: DashboardSectionOption) =>+ `${section.type}-${section.collectionId || 'default'}`;++ // Set up drag and drop+ useEffect(() => {+ return monitorForElements({+ onDrop({ source, location }) {+ const destination = location.current.dropTargets[0];+ if (!destination) return;++ const sourceId = source.data?.sectionId as string;+ const destinationId = destination.data?.sectionId as string;++ if (!sourceId || !destinationId || sourceId === destinationId) return;++ const sourceIndex = filteredSections.findIndex(s => getSectionId(s) === sourceId);+ const destinationIndex = filteredSections.findIndex(s => getSectionId(s) === destinationId);++ if (sourceIndex === -1 || destinationIndex === -1) return;++ // Only allow reordering within enabled sections+ const sourceSection = filteredSections[sourceIndex];+ const destinationSection = filteredSections[destinationIndex];++ if (!sourceSection.enabled || !destinationSection.enabled) return;++ const reorderedSections = reorder({+ list: filteredSections,+ startIndex: sourceIndex,+ finishIndex: destinationIndex,+ });++ // Update orders for enabled sections only+ const updatedSections = reorderedSections.map((section, index) => {+ if (section.enabled) {+ return { ...section, order: index };+ }+ return section;+ });++ console.log("Reordered sections:", updatedSections);++ updateDashboardLayout.mutateAsync(updatedSections);+ },+ });+ }, [filteredSections, updateDashboardLayout]);const handleCheckboxChange = (section: DashboardSectionOption) => {const updatedSections = allSections.map((s) => {@@ -118,7 +174,7 @@ export default function DashboardLayoutDropdown() {return s;});- updateDashboardLayout.mutateAsync(updatedSections)+ updateDashboardLayout.mutateAsync(updatedSections);};return (@@ -142,28 +198,15 @@ export default function DashboardLayoutDropdown() {<ul className="max-h-60 overflow-y-auto">{filteredSections.map((section) => (- <li- key={section.type + (section.collectionId || 'default')}- className="py-1 px-2 flex items-center justify-between cursor-pointer"- >- <div className="flex items-center gap-2">- <input- id={`section-${section.type}-${section.collectionId || 'default'}`}- className="checkbox checkbox-primary"- type="checkbox"- checked={section.enabled}- onChange={() => handleCheckboxChange(section)}- />- <label- htmlFor={`section-${section.type}-${section.collectionId || 'default'}`}- className="text-sm cursor-pointer"- >- {section.name}- </label>- </div>-- <i className="bi-grip-vertical text-neutral" />- </li>+ <DraggableListItem+ key={getSectionId(section)}+ section={section}+ onCheckboxChange={handleCheckboxChange}+ isDraggedOver={isDraggedOver === getSectionId(section)}+ isDragged={draggedItem === getSectionId(section)}+ setIsDraggedOver={setIsDraggedOver}+ setDraggedItem={setDraggedItem}+ />))}{filteredSections.length === 0 && (@@ -176,4 +219,79 @@ export default function DashboardLayoutDropdown() {</DropdownMenuContent></DropdownMenu>);+}++interface DraggableListItemProps {+ section: DashboardSectionOption;+ onCheckboxChange: (section: DashboardSectionOption) => void;+ isDraggedOver: boolean;+ isDragged: boolean;+ setIsDraggedOver: (id: string | null) => void;+ setDraggedItem: (id: string | null) => void;+}++function DraggableListItem({+ section,+ onCheckboxChange,+ isDraggedOver,+ isDragged,+ setIsDraggedOver,+ setDraggedItem+}: DraggableListItemProps) {+ const [element, setElement] = useState<HTMLElement | null>(null);+ const sectionId = `${section.type}-${section.collectionId || 'default'}`;++ useEffect(() => {+ const el = element;+ if (!el || !section.enabled) return;++ return combine(+ draggable({+ element: el,+ getInitialData: () => ({ sectionId }),+ onDragStart: () => setDraggedItem(sectionId),+ onDrop: () => setDraggedItem(null),+ }),+ dropTargetForElements({+ element: el,+ getData: () => ({ sectionId }),+ onDragEnter: () => setIsDraggedOver(sectionId),+ onDragLeave: () => setIsDraggedOver(null),+ onDrop: () => setIsDraggedOver(null),+ })+ );+ }, [element, section.enabled, sectionId, setDraggedItem, setIsDraggedOver]);++ return (+ <li+ ref={setElement}+ data-section-id={sectionId}+ className={`+ py-1 px-2 flex items-center justify-between cursor-pointer rounded+ ${section.enabled ? 'cursor-grab active:cursor-grabbing' : ''}+ ${isDragged ? 'opacity-50' : ''}+ `}+ >+ <div className="flex items-center gap-2">+ <input+ id={`section-${section.type}-${section.collectionId || 'default'}`}+ className="checkbox checkbox-primary"+ type="checkbox"+ checked={section.enabled}+ onChange={() => onCheckboxChange(section)}+ />+ <label+ htmlFor={`section-${section.type}-${section.collectionId || 'default'}`}+ className="text-sm cursor-pointer"+ >+ {section.name}+ </label>+ </div>++ <i+ className={`bi-grip-vertical text-neutral ${section.enabled ? 'cursor-grab' : 'opacity-50'+ }`}+ />+ </li>+ );}\ No newline at end of filediff --git a/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts b/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.tsindex 8a9d8fd5..528148be 100644--- a/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts+++ b/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts@@ -18,6 +18,7 @@ export default async function updateDashboardLayout(const data = dataValidation.data;+ // This can be improved - less queries and not in a loopfor (const section of data) {const existingSection = await prisma.dashboardSection.findFirst({@@ -34,8 +35,15 @@ export default async function updateDashboardLayout(id: existingSection.id}})- } else if (existingSection) {- // update+ } else if (existingSection && section.enabled) {+ await prisma.dashboardSection.update({+ where: {+ id: existingSection.id+ },+ data: {+ order: section.order+ }+ });} else if (section.enabled) {await prisma.dashboardSection.create({data: {@@ -46,10 +54,8 @@ export default async function updateDashboardLayout(}});}-}-return {status: 200,response: datadiff --git a/apps/web/pages/dashboard.tsx b/apps/web/pages/dashboard.tsxindex d69543d1..54d4f196 100644--- a/apps/web/pages/dashboard.tsx+++ b/apps/web/pages/dashboard.tsx@@ -20,7 +20,7 @@ import SurveyModal from "@/components/ModalContent/SurveyModal";import ImportDropdown from "@/components/ImportDropdown";import { Button } from "@/components/ui/button";import DashboardLayoutDropdown from "@/components/DashboardLayoutDropdown";-import { DashboardSection } from "@linkwarden/prisma/client";+import { DashboardSection, DashboardSectionType } from "@linkwarden/prisma/client";export default function Dashboard() {const { t } = useTranslation();@@ -46,7 +46,6 @@ export default function Dashboard() {);}, [collections]);-useEffect(() => {if (process.env.NEXT_PUBLIC_STRIPE === "true" &&@@ -63,7 +62,20 @@ export default function Dashboard() {}}, [user]);- const dashboardSections: DashboardSection[] | [] = user?.dashboardSections || [];+ const dashboardSections: DashboardSection[] = user?.dashboardSections || [];++ // Sort sections by order and filter enabled ones+ const orderedSections = useMemo(() => {+ return dashboardSections+ .sort((a, b) => {+ if (a.order !== undefined && b.order !== undefined) {+ return a.order - b.order;+ }+ if (a.order !== undefined) return -1;+ if (b.order !== undefined) return 1;+ return 0;+ });+ }, [dashboardSections]);const showRecentLinks = dashboardSections.some(section => section.type === 'RECENT_LINKS');const showPinnedLinks = dashboardSections.some(section => section.type === 'PINNED_LINKS');@@ -127,188 +139,271 @@ export default function Dashboard() {);};- return (- <MainLayout>- <div style={{ flex: "1 1 auto" }} className="p-5 flex flex-col gap-5">- <div className="flex items-center justify-between">+ // Component renderers for each section type+ const renderStatsSection = () => (+ <div className="xl:flex flex flex-col sm:grid grid-cols-2 gap-3 xl:flex-row xl:justify-evenly xl:w-full">+ <DashboardItem+ name={numberOfLinks === 1 ? t("link") : t("links")}+ value={numberOfLinks}+ icon={"bi-link-45deg"}+ />++ <DashboardItem+ name={collections.length === 1 ? t("collection") : t("collections")}+ value={collections.length}+ icon={"bi-folder"}+ />++ <DashboardItem+ name={tags.length === 1 ? t("tag") : t("tags")}+ value={tags.length}+ icon={"bi-hash"}+ />++ <DashboardItem+ name={t("pinned")}+ value={numberOfPinnedLinks}+ icon={"bi-pin-angle"}+ />+ </div>+ );++ const renderRecentLinksSection = () => (+ <>+ <div className="flex justify-between items-center">+ <div className="flex gap-2 items-center"><PageHeader- icon={"bi-house "}- title={t("dashboard")}- description={t("dashboard_desc")}+ icon={"bi-clock-history"}+ title={t("recent")}+ description={t("recent_links_desc")}/>- <div className="flex items-center gap-3">- <DashboardLayoutDropdown />- <ViewDropdown viewMode={viewMode} setViewMode={setViewMode} />- </div></div>+ <Link+ href="/links"+ className="flex items-center text-sm text-black/75 dark:text-white/75 gap-2 cursor-pointer"+ >+ {t("view_all")}+ <i className="bi-chevron-right text-sm"></i>+ </Link>+ </div>- <div className="xl:flex flex flex-col sm:grid grid-cols-2 gap-3 xl:flex-row xl:justify-evenly xl:w-full">- <DashboardItem- name={numberOfLinks === 1 ? t("link") : t("links")}- value={numberOfLinks}- icon={"bi-link-45deg"}- />+ <div+ style={{+ flex:+ links || dashboardData.isLoading ? "0 1 auto" : "1 1 auto",+ }}+ className="flex flex-col 2xl:flex-row items-start 2xl:gap-2"+ >+ {dashboardData.isLoading ? (+ <div className="w-full">+ <Links+ layout={viewMode}+ placeholderCount={settings.columns || 1}+ useData={dashboardData}+ />+ </div>+ ) : links && links[0] && !dashboardData.isLoading ? (+ <div className="w-full">+ <Links+ links={links.slice(+ 0,+ settings.columns &&+ showRecentLinks &&+ showPinnedLinks+ ? settings.columns * 2+ : numberOfLinksToShow+ )}+ layout={viewMode}+ />+ </div>+ ) : (+ <div className="flex flex-col justify-center h-full border border-solid border-neutral-content w-full mx-auto p-10 rounded-xl bg-base-200 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200">+ <p className="text-center text-xl">+ {t("view_added_links_here")}+ </p>+ <p className="text-center mx-auto max-w-96 w-fit text-neutral text-sm mt-2">+ {t("view_added_links_here_desc")}+ </p>- <DashboardItem- name={collections.length === 1 ? t("collection") : t("collections")}- value={collections.length}- icon={"bi-folder"}- />+ <div className="text-center w-full mt-4 flex flex-wrap gap-4 justify-center">+ <Button+ onClick={() => {+ setNewLinkModal(true);+ }}+ variant="accent"+ >+ <i className="bi-plus-lg text-xl"></i>+ {t("add_link")}+ </Button>- <DashboardItem- name={tags.length === 1 ? t("tag") : t("tags")}- value={tags.length}- icon={"bi-hash"}- />+ <ImportDropdown />+ </div>+ </div>+ )}+ </div>+ </>+ );- <DashboardItem- name={t("pinned")}- value={numberOfPinnedLinks}+ const renderPinnedLinksSection = () => (+ <>+ <div className="flex justify-between items-center">+ <div className="flex gap-2 items-center">+ <PageHeadericon={"bi-pin-angle"}+ title={t("pinned")}+ description={t("pinned_links_desc")}/></div>+ <Link+ href="/links/pinned"+ className="flex items-center text-sm text-black/75 dark:text-white/75 gap-2 cursor-pointer"+ >+ {t("view_all")}+ <i className="bi-chevron-right text-sm "></i>+ </Link>+ </div>- {showRecentLinks && (- <>- <div className="flex justify-between items-center">- <div className="flex gap-2 items-center">- <PageHeader- icon={"bi-clock-history"}- title={t("recent")}- description={t("recent_links_desc")}- />- </div>- <Link- href="/links"- className="flex items-center text-sm text-black/75 dark:text-white/75 gap-2 cursor-pointer"- >- {t("view_all")}- <i className="bi-chevron-right text-sm"></i>- </Link>- </div>-- <div- style={{- flex:- links || dashboardData.isLoading ? "0 1 auto" : "1 1 auto",- }}- className="flex flex-col 2xl:flex-row items-start 2xl:gap-2"- >- {dashboardData.isLoading ? (- <div className="w-full">- <Links- layout={viewMode}- placeholderCount={settings.columns || 1}- useData={dashboardData}- />- </div>- ) : links && links[0] && !dashboardData.isLoading ? (- <div className="w-full">- <Links- links={links.slice(- 0,- settings.columns &&- showRecentLinks &&- showPinnedLinks- ? settings.columns * 2- : numberOfLinksToShow- )}- layout={viewMode}- />- </div>- ) : (- <div className="flex flex-col justify-center h-full border border-solid border-neutral-content w-full mx-auto p-10 rounded-xl bg-base-200 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200">- <p className="text-center text-xl">- {t("view_added_links_here")}- </p>- <p className="text-center mx-auto max-w-96 w-fit text-neutral text-sm mt-2">- {t("view_added_links_here_desc")}- </p>-- <div className="text-center w-full mt-4 flex flex-wrap gap-4 justify-center">- <Button- onClick={() => {- setNewLinkModal(true);- }}- variant="accent"- >- <i className="bi-plus-lg text-xl"></i>- {t("add_link")}- </Button>-- <ImportDropdown />- </div>- </div>- )}- </div>- </>+ <div+ style={{ flex: "1 1 auto" }}+ className="flex flex-col 2xl:flex-row items-start 2xl:gap-2"+ >+ {dashboardData.isLoading ? (+ <div className="w-full">+ <Links+ layout={viewMode}+ placeholderCount={settings.columns || 1}+ useData={dashboardData}+ />+ </div>+ ) : links?.some((e: any) => e.pinnedBy && e.pinnedBy[0]) ? (+ <div className="w-full">+ <Links+ links={links+ .filter((e: any) => e.pinnedBy && e.pinnedBy[0])+ .slice(+ 0,+ settings.columns &&+ showRecentLinks &&+ showPinnedLinks+ ? settings.columns * 2+ : numberOfLinksToShow+ )}+ layout={viewMode}+ />+ </div>+ ) : (+ <div+ style={{ flex: "1 1 auto" }}+ className="flex flex-col gap-2 justify-center h-full border border-solid border-neutral-content w-full mx-auto p-10 rounded-xl bg-base-200 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200"+ >+ <i className="bi-pin mx-auto text-6xl text-primary"></i>+ <p className="text-center text-xl">+ {t("pin_favorite_links_here")}+ </p>+ <p className="text-center mx-auto max-w-96 w-fit text-neutral text-sm">+ {t("pin_favorite_links_here_desc")}+ </p>+ </div>)}+ </div>+ </>+ );- {showPinnedLinks && (- <>- <div className="flex justify-between items-center">- <div className="flex gap-2 items-center">- <PageHeader- icon={"bi-pin-angle"}- title={t("pinned")}- description={t("pinned_links_desc")}- />- </div>- <Link- href="/links/pinned"- className="flex items-center text-sm text-black/75 dark:text-white/75 gap-2 cursor-pointer"- >- {t("view_all")}- <i className="bi-chevron-right text-sm "></i>- </Link>- </div>+ const renderCollectionSection = (section: DashboardSection) => {+ const collection = collections.find(c => c.id === section.collectionId);+ if (!collection) return null;- <div- style={{ flex: "1 1 auto" }}- className="flex flex-col 2xl:flex-row items-start 2xl:gap-2"- >- {dashboardData.isLoading ? (- <div className="w-full">- <Links- layout={viewMode}- placeholderCount={settings.columns || 1}- useData={dashboardData}- />- </div>- ) : links?.some((e: any) => e.pinnedBy && e.pinnedBy[0]) ? (- <div className="w-full">- <Links- links={links- .filter((e: any) => e.pinnedBy && e.pinnedBy[0])- .slice(- 0,- settings.columns &&- showRecentLinks &&- showPinnedLinks- ? settings.columns * 2- : numberOfLinksToShow- )}- layout={viewMode}- />- </div>- ) : (- <div- style={{ flex: "1 1 auto" }}- className="flex flex-col gap-2 justify-center h-full border border-solid border-neutral-content w-full mx-auto p-10 rounded-xl bg-base-200 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200"- >- <i className="bi-pin mx-auto text-6xl text-primary"></i>- <p className="text-center text-xl">- {t("pin_favorite_links_here")}- </p>- <p className="text-center mx-auto max-w-96 w-fit text-neutral text-sm">- {t("pin_favorite_links_here_desc")}- </p>- </div>- )}+ return (+ <>+ <div className="flex justify-between items-center">+ <div className="flex gap-2 items-center">+ <PageHeader+ icon={"bi-folder"}+ title={collection.name}+ description={`${collection._count?.links || 0} ${t("links")}`}+ />+ </div>+ <Link+ href={`/collections/${collection.id}`}+ className="flex items-center text-sm text-black/75 dark:text-white/75 gap-2 cursor-pointer"+ >+ {t("view_all")}+ <i className="bi-chevron-right text-sm"></i>+ </Link>+ </div>++ <div className="flex flex-col 2xl:flex-row items-start 2xl:gap-2">+ {dashboardData.isLoading ? (+ <div className="w-full">+ <Links+ layout={viewMode}+ placeholderCount={settings.columns || 1}+ useData={dashboardData}+ /></div>- </>- )}+ ) : links?.filter((link: any) => link.collection.id === collection.id).length > 0 ? (+ <div className="w-full">+ <Links+ links={links+ .filter((link: any) => link.collection.id === collection.id)+ .slice(0, numberOfLinksToShow)}+ layout={viewMode}+ />+ </div>+ ) : (+ <div className="flex flex-col justify-center h-full border border-solid border-neutral-content w-full mx-auto p-10 rounded-xl bg-base-200 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200">+ <i className="bi-folder mx-auto text-6xl text-primary"></i>+ <p className="text-center text-xl">+ {t("no_links_in_collection")}+ </p>+ <p className="text-center mx-auto max-w-96 w-fit text-neutral text-sm">+ {collection.name} {t("collection_is_empty")}+ </p>+ </div>+ )}+ </div>+ </>+ );+ };++ const renderSection = (section: DashboardSection) => {+ switch (section.type) {+ case DashboardSectionType.STATS:+ return renderStatsSection();+ case DashboardSectionType.RECENT_LINKS:+ return renderRecentLinksSection();+ case DashboardSectionType.PINNED_LINKS:+ return renderPinnedLinksSection();+ case DashboardSectionType.COLLECTION:+ return renderCollectionSection(section);+ default:+ return null;+ }+ };++ return (+ <MainLayout>+ <div style={{ flex: "1 1 auto" }} className="p-5 flex flex-col gap-5">+ <div className="flex items-center justify-between">+ <PageHeader+ icon={"bi-house "}+ title={t("dashboard")}+ description={t("dashboard_desc")}+ />+ <div className="flex items-center gap-3">+ <DashboardLayoutDropdown />+ <ViewDropdown viewMode={viewMode} setViewMode={setViewMode} />+ </div>+ </div>++ {/* Render sections in their specified order */}+ {orderedSections.map((section, index) => (+ <div key={`${section.type}-${section.collectionId || 'default'}-${index}`}>+ {renderSection(section)}+ </div>+ ))}</div>+{showSurveyModal && (<SurveyModalsubmit={submitSurvey}@@ -322,4 +417,4 @@ export default function Dashboard() {);}-export { getServerSideProps };+export { getServerSideProps };\ No newline at end of filediff --git a/packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sql b/packages/prisma/migrations/20250601213117_add_dashboard_sections/migration.sqlsimilarity index 92%rename from packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sqlrename to packages/prisma/migrations/20250601213117_add_dashboard_sections/migration.sqlindex 493060df..f39cb799 100644--- a/packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sql+++ b/packages/prisma/migrations/20250601213117_add_dashboard_sections/migration.sql@@ -25,9 +25,6 @@ CREATE TABLE "DashboardSection" (CONSTRAINT "DashboardSection_pkey" PRIMARY KEY ("id"));--- CreateIndex-CREATE UNIQUE INDEX "DashboardSection_userId_order_key" ON "DashboardSection"("userId", "order");--- CreateIndexCREATE UNIQUE INDEX "DashboardSection_userId_collectionId_key" ON "DashboardSection"("userId", "collectionId");diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 9a3b9f22..94d7a6d0 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -271,6 +271,5 @@ model DashboardSection {createdAt DateTime @default(now())updatedAt DateTime @default(now()) @updatedAt- @@unique([userId, order])@@unique([userId, collectionId])}