Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

Dropdown, database & start endpoint

Isaac4a66e1ec9c14
diff --git a/apps/web/components/DashboardLayoutDropdown.tsx b/apps/web/components/DashboardLayoutDropdown.tsx
new file mode 100644
index 00000000..e413665f
--- /dev/null
+++ b/apps/web/components/DashboardLayoutDropdown.tsx
@@ -0,0 +1,163 @@
+import React, { useState, useMemo } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+} from "@/components/ui/dropdown-menu";
+import { useTranslation } from "next-i18next";
+import { Button } from "@/components/ui/button";
+import TextInput from "./TextInput";
+import { useCollections } from "@linkwarden/router/collections";
+import { DashboardSection, DashboardSectionType } from "@linkwarden/prisma/client";
+import { useUser } from "@linkwarden/router/user";
+
+interface DashboardSectionOption {
+ type: DashboardSectionType;
+ name: string;
+ collectionId?: number;
+ enabled: boolean;
+ order?: number;
+}
+
+export default function DashboardLayoutDropdown() {
+ const { t } = useTranslation();
+ const { data: user } = useUser();
+ const { data: collections = [] } = useCollections();
+ const [searchTerm, setSearchTerm] = useState("");
+
+ const dashboardSections: DashboardSection[] = user?.dashboardSections || [];
+
+ const getSectionOrder = (type: DashboardSectionType, collectionId?: number): number | undefined => {
+ const section = dashboardSections.find(section =>
+ section.type === type &&
+ (type === DashboardSectionType.COLLECTION ? section.collectionId === collectionId : true)
+ );
+ return section?.order;
+ };
+
+ const isSectionEnabled = (type: DashboardSectionType, collectionId?: number): boolean => {
+ return dashboardSections.some(section =>
+ section.type === type &&
+ (type === DashboardSectionType.COLLECTION ? section.collectionId === collectionId : true)
+ );
+ };
+
+ const defaultSections: DashboardSectionOption[] = [
+ {
+ type: DashboardSectionType.STATS,
+ name: t("dashboard_stats"),
+ enabled: isSectionEnabled(DashboardSectionType.STATS),
+ order: getSectionOrder(DashboardSectionType.STATS)
+ },
+ {
+ type: DashboardSectionType.RECENT_LINKS,
+ name: t("recent_links"),
+ enabled: isSectionEnabled(DashboardSectionType.RECENT_LINKS),
+ order: getSectionOrder(DashboardSectionType.RECENT_LINKS)
+ },
+ {
+ type: DashboardSectionType.PINNED_LINKS,
+ name: t("pinned_links"),
+ enabled: isSectionEnabled(DashboardSectionType.PINNED_LINKS),
+ order: getSectionOrder(DashboardSectionType.PINNED_LINKS)
+ },
+ ];
+
+ const collectionSections: DashboardSectionOption[] = collections.map((collection) => ({
+ type: DashboardSectionType.COLLECTION,
+ name: collection.name,
+ collectionId: collection.id,
+ enabled: isSectionEnabled(DashboardSectionType.COLLECTION, collection.id),
+ order: getSectionOrder(DashboardSectionType.COLLECTION, collection.id)
+ }));
+
+ const allSections = [...defaultSections, ...collectionSections];
+
+ const filteredSections = useMemo(() => {
+ let sections = allSections;
+
+ // Filter by search term
+ if (searchTerm.trim()) {
+ sections = sections.filter((section) =>
+ section.name.toLowerCase().includes(searchTerm.toLowerCase())
+ );
+ }
+
+ // Separate and sort sections
+ const enabledSections = sections
+ .filter(section => section.enabled)
+ .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;
+ });
+
+ const disabledSections = sections.filter(section => !section.enabled);
+
+ return [...enabledSections, ...disabledSections];
+ }, [allSections, searchTerm]);
+
+ const handleCheckboxChange = (section: DashboardSectionOption) => {
+ // TODO: Implement checkbox change logic
+ console.log('Toggle section:', section);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <i className="bi-sliders2-vertical text-neutral" />
+ </Button>
+ </DropdownMenuTrigger>
+
+ <DropdownMenuContent className="min-w-72 py-2" align="end">
+ <div className="px-1 flex flex-col gap-1">
+ <p className="text-sm text-neutral">{t("display_on_dashboard")}</p>
+
+ <TextInput
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ className="py-0"
+ placeholder={t("search")}
+ />
+
+ <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>
+ ))}
+
+ {filteredSections.length === 0 && (
+ <li className="text-sm py-2 text-center text-neutral">
+ {t("no_results_found")}
+ </li>
+ )}
+ </ul>
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
\ No newline at end of file
diff --git a/apps/web/components/DashboardViewDropdown.tsx b/apps/web/components/DashboardViewDropdown.tsx
deleted file mode 100644
index c57f3518..00000000
--- a/apps/web/components/DashboardViewDropdown.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import * as React from "react";
-import {
- DropdownMenu,
- DropdownMenuTrigger,
- DropdownMenuContent,
-} from "@/components/ui/dropdown-menu";
-import { useTranslation } from "next-i18next";
-import { Button } from "@/components/ui/button";
-import TextInput from "./TextInput";
-import { useCollections } from "@linkwarden/router/collections";
-
-export default function DashboardViewDropdown() {
- const { t } = useTranslation();
- const { data: collections = [], isLoading } = useCollections();
- const [searchTerm, setSearchTerm] = React.useState("");
-
- const filteredCollections = React.useMemo(() => {
- if (!searchTerm.trim()) {
- return collections;
- }
-
- return collections.filter((collection) =>
- collection.name.toLowerCase().includes(searchTerm.toLowerCase())
- );
- }, [collections, searchTerm]);
-
- const handleSearchChange = (value: string) => {
- setSearchTerm(value);
- };
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon">
- <i className="bi-sliders2-vertical text-neutral"></i>
- </Button>
- </DropdownMenuTrigger>
-
- <DropdownMenuContent className="min-w-72 py-2" align="end">
- <div className="px-1 flex flex-col gap-1">
- <p className="text-sm text-neutral">{t("display_on_dashboard")}</p>
- <TextInput
- value={searchTerm}
- onChange={(e) => handleSearchChange(e.target.value)}
- className="py-0"
- placeholder={t("search")}
- />
- <ul className="max-h-60 overflow-y-auto">
- {!isLoading &&
- filteredCollections.length > 0 &&
- filteredCollections.map((collection) => (
- <li
- key={collection.id}
- className="py-1 px-2 flex items-center justify-between cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <input
- className="checkbox checkbox-primary"
- type="checkbox"
- checked={false}
- onChange={() => {
- /* Handle checkbox change */
- }}
- />
- <label
- htmlFor={`collection-${collection.id}`}
- className="text-sm"
- >
- {collection.name}
- </label>
- </div>
-
- <i className="bi-grip-vertical text-neutral"></i>
- </li>
- ))}
- {!isLoading && filteredCollections.length === 0 && searchTerm && (
- <li className="py-2 px-2 text-sm text-neutral text-center">
- {t("you_have_no_collections")}
- </li>
- )}
- </ul>
- </div>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
index 3d435c5f..1690f59f 100644
--- a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
+++ b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts
@@ -123,6 +123,7 @@ export default async function getDashboardData(
orderBy: order || { id: "desc" },
});
}
+
const links = [...recentlyAddedLinks, ...pinnedLinks].sort(
(a, b) => new Date(b.id).getTime() - new Date(a.id).getTime()
);
@@ -132,9 +133,26 @@ export default async function getDashboardData(
(link, index, self) => index === self.findIndex((t) => t.id === link.id)
);
+ const pinnedCollections = await prisma.dashboardSection.findMany({
+ where: {
+ userId,
+ type: "COLLECTION",
+ },
+ include: {
+ collection: {
+ include: {
+ links: {
+ take: 16,
+ },
+ }
+ }
+ },
+ });
+
return {
data: {
links: uniqueLinks,
+ pinnedCollections,
numberOfPinnedLinks,
},
message: "Dashboard data fetched successfully.",
diff --git a/apps/web/lib/api/controllers/users/userId/getUserById.ts b/apps/web/lib/api/controllers/users/userId/getUserById.ts
index ce9c53c6..8d0939f7 100644
--- a/apps/web/lib/api/controllers/users/userId/getUserById.ts
+++ b/apps/web/lib/api/controllers/users/userId/getUserById.ts
@@ -17,6 +17,7 @@ export default async function getUserById(userId: number) {
user: true,
},
},
+ dashboardSections: true,
},
});
diff --git a/apps/web/lib/api/controllers/users/userId/updateUserById.ts b/apps/web/lib/api/controllers/users/userId/updateUserById.ts
index 5ae28fd9..d22e303e 100644
--- a/apps/web/lib/api/controllers/users/userId/updateUserById.ts
+++ b/apps/web/lib/api/controllers/users/userId/updateUserById.ts
@@ -17,9 +17,8 @@ export default async function updateUserById(
if (!dataValidation.success) {
return {
- response: `Error: ${
- dataValidation.error.issues[0].message
- } [${dataValidation.error.issues[0].path.join(", ")}]`,
+ response: `Error: ${dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
@@ -31,18 +30,18 @@ export default async function updateUserById(
id: { not: userId },
OR: emailEnabled
? [
- {
- username: data.username.toLowerCase(),
- },
- {
- email: data.email?.toLowerCase(),
- },
- ]
+ {
+ username: data.username.toLowerCase(),
+ },
+ {
+ email: data.email?.toLowerCase(),
+ },
+ ]
: [
- {
- username: data.username.toLowerCase(),
- },
- ],
+ {
+ username: data.username.toLowerCase(),
+ },
+ ],
},
});
@@ -209,8 +208,6 @@ export default async function updateUserById(
archiveAsReadable: data.archiveAsReadable,
archiveAsWaybackMachine: data.archiveAsWaybackMachine,
linksRouteTo: data.linksRouteTo,
- dashboardPinnedLinks: data.dashboardPinnedLinks,
- dashboardRecentLinks: data.dashboardRecentLinks,
preventDuplicateLinks: data.preventDuplicateLinks,
referredBy:
!user?.referredBy && data.referredBy ? data.referredBy : undefined,
diff --git a/apps/web/lib/api/verifyUser.ts b/apps/web/lib/api/verifyUser.ts
index c99d2f54..a478ea2e 100644
--- a/apps/web/lib/api/verifyUser.ts
+++ b/apps/web/lib/api/verifyUser.ts
@@ -1,9 +1,15 @@
import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "@linkwarden/prisma";
-import { User } from "@linkwarden/prisma/client";
+import { Prisma } from "@linkwarden/prisma/client";
import verifySubscription from "./stripe/verifySubscription";
import verifyToken from "./verifyToken";
+type UserWithIncludes = Prisma.UserGetPayload<{
+ include: {
+ dashboardSections: true;
+ };
+}>;
+
type Props = {
req: NextApiRequest;
res: NextApiResponse;
@@ -14,7 +20,7 @@ const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
export default async function verifyUser({
req,
res,
-}: Props): Promise<User | null> {
+}: Props): Promise<UserWithIncludes | null> {
const token = await verifyToken({ req });
if (typeof token === "string") {
@@ -31,6 +37,7 @@ export default async function verifyUser({
include: {
subscriptions: true,
parentSubscription: true,
+ dashboardSections: true
},
});
diff --git a/apps/web/pages/api/v2/dashboard/index.ts b/apps/web/pages/api/v2/dashboard/index.ts
index 23435819..b4c85a88 100644
--- a/apps/web/pages/api/v2/dashboard/index.ts
+++ b/apps/web/pages/api/v2/dashboard/index.ts
@@ -16,11 +16,14 @@ export default async function dashboard(
cursor: req.query.cursor ? Number(req.query.cursor as string) : undefined,
};
+ const showRecentLinks = user.dashboardSections.some(section => section.type === 'RECENT_LINKS');
+ const showPinnedLinks = user.dashboardSections.some(section => section.type === 'PINNED_LINKS');
+
const { statusCode, ...data } = await getDashboardDataV2(
user.id,
convertedData,
- user.dashboardRecentLinks,
- user.dashboardPinnedLinks
+ showRecentLinks,
+ showPinnedLinks
);
return res.status(statusCode).json(data);
diff --git a/apps/web/pages/dashboard.tsx b/apps/web/pages/dashboard.tsx
index b5f46237..d69543d1 100644
--- a/apps/web/pages/dashboard.tsx
+++ b/apps/web/pages/dashboard.tsx
@@ -19,7 +19,8 @@ import { useUpdateUser, useUser } from "@linkwarden/router/user";
import SurveyModal from "@/components/ModalContent/SurveyModal";
import ImportDropdown from "@/components/ImportDropdown";
import { Button } from "@/components/ui/button";
-import DashboardViewDropdown from "@/components/DashboardViewDropdown";
+import DashboardLayoutDropdown from "@/components/DashboardLayoutDropdown";
+import { DashboardSection } from "@linkwarden/prisma/client";
export default function Dashboard() {
const { t } = useTranslation();
@@ -29,7 +30,7 @@ export default function Dashboard() {
...dashboardData
} = useDashboardData();
const { data: tags = [] } = useTags();
- const { data: account = [] } = useUser();
+ const { data: user } = useUser();
const [numberOfLinks, setNumberOfLinks] = useState(0);
@@ -45,24 +46,30 @@ export default function Dashboard() {
);
}, [collections]);
+
useEffect(() => {
if (
process.env.NEXT_PUBLIC_STRIPE === "true" &&
- account &&
- account.id &&
- account.referredBy === null &&
+ user &&
+ user.id &&
+ user.referredBy === null &&
// if user is using Linkwarden for more than 3 days
- new Date().getTime() - new Date(account.createdAt).getTime() >
- 3 * 24 * 60 * 60 * 1000
+ new Date().getTime() - new Date(user.createdAt).getTime() >
+ 3 * 24 * 60 * 60 * 1000
) {
setTimeout(() => {
setShowsSurveyModal(true);
}, 1000);
}
- }, [account]);
+ }, [user]);
+
+ const dashboardSections: DashboardSection[] | [] = user?.dashboardSections || [];
+
+ const showRecentLinks = dashboardSections.some(section => section.type === 'RECENT_LINKS');
+ const showPinnedLinks = dashboardSections.some(section => section.type === 'PINNED_LINKS');
const numberOfLinksToShow = useMemo(() => {
- if (account.dashboardRecentLinks && account.dashboardPinnedLinks) {
+ if (showRecentLinks && showPinnedLinks) {
if (window.innerWidth > 1900) {
return 10;
} else if (window.innerWidth > 1500) {
@@ -77,7 +84,7 @@ export default function Dashboard() {
} else {
return 100;
}
- }, [account.dashboardRecentLinks, account.dashboardPinnedLinks]);
+ }, [showRecentLinks, showPinnedLinks]);
const [newLinkModal, setNewLinkModal] = useState(false);
@@ -87,7 +94,6 @@ export default function Dashboard() {
const [showSurveyModal, setShowsSurveyModal] = useState(false);
- const { data: user } = useUser();
const updateUser = useUpdateUser();
const [submitLoader, setSubmitLoader] = useState(false);
@@ -131,7 +137,7 @@ export default function Dashboard() {
description={t("dashboard_desc")}
/>
<div className="flex items-center gap-3">
- <DashboardViewDropdown />
+ <DashboardLayoutDropdown />
<ViewDropdown viewMode={viewMode} setViewMode={setViewMode} />
</div>
</div>
@@ -162,7 +168,7 @@ export default function Dashboard() {
/>
</div>
- {account.dashboardRecentLinks && (
+ {showRecentLinks && (
<>
<div className="flex justify-between items-center">
<div className="flex gap-2 items-center">
@@ -202,8 +208,8 @@ export default function Dashboard() {
links={links.slice(
0,
settings.columns &&
- account.dashboardRecentLinks &&
- account.dashboardPinnedLinks
+ showRecentLinks &&
+ showPinnedLinks
? settings.columns * 2
: numberOfLinksToShow
)}
@@ -238,7 +244,7 @@ export default function Dashboard() {
</>
)}
- {account.dashboardPinnedLinks && (
+ {showPinnedLinks && (
<>
<div className="flex justify-between items-center">
<div className="flex gap-2 items-center">
@@ -277,8 +283,8 @@ export default function Dashboard() {
.slice(
0,
settings.columns &&
- account.dashboardRecentLinks &&
- account.dashboardPinnedLinks
+ showRecentLinks &&
+ showPinnedLinks
? settings.columns * 2
: numberOfLinksToShow
)}
diff --git a/apps/web/pages/settings/preference.tsx b/apps/web/pages/settings/preference.tsx
index cc2d71ab..2fc2f7a7 100644
--- a/apps/web/pages/settings/preference.tsx
+++ b/apps/web/pages/settings/preference.tsx
@@ -56,9 +56,6 @@ export default function Preference() {
const [dashboardPinnedLinks, setDashboardPinnedLinks] = useState<boolean>(
account.dashboardPinnedLinks || false
);
- const [dashboardRecentLinks, setDashboardRecentLinks] = useState<boolean>(
- account.dashboardRecentLinks || false
- );
const [linksRouteTo, setLinksRouteTo] = useState(account.linksRouteTo);
const [aiTaggingMethod, setAiTaggingMethod] = useState<AiTaggingMethod>(
account.aiTaggingMethod
@@ -84,7 +81,6 @@ export default function Preference() {
aiTaggingMethod,
aiPredefinedTags,
aiTagExistingLinks,
- dashboardRecentLinks,
dashboardPinnedLinks,
});
}, [
@@ -99,8 +95,6 @@ export default function Preference() {
aiTaggingMethod,
aiPredefinedTags,
aiTagExistingLinks,
- dashboardRecentLinks,
- dashboardPinnedLinks,
]);
function objectIsEmpty(obj: object) {
@@ -119,8 +113,6 @@ export default function Preference() {
setAiTaggingMethod(account.aiTaggingMethod);
setAiPredefinedTags(account.aiPredefinedTags);
setAiTagExistingLinks(account.aiTagExistingLinks);
- setDashboardRecentLinks(account.dashboardRecentLinks);
- setDashboardPinnedLinks(account.dashboardPinnedLinks);
}
}, [account]);
@@ -136,8 +128,6 @@ export default function Preference() {
"aiTaggingMethod",
"aiPredefinedTags",
"aiTagExistingLinks",
- "dashboardRecentLinks",
- "dashboardPinnedLinks",
];
const hasChanges = relevantKeys.some((key) => account[key] !== user[key]);
@@ -159,7 +149,7 @@ export default function Preference() {
newTag.archiveAsPDF !== originalTag.archiveAsPDF ||
newTag.archiveAsReadable !== originalTag.archiveAsReadable ||
newTag.archiveAsWaybackMachine !==
- originalTag.archiveAsWaybackMachine ||
+ originalTag.archiveAsWaybackMachine ||
newTag.aiTag !== originalTag.aiTag
);
});
@@ -218,11 +208,10 @@ export default function Preference() {
].map(({ theme, icon, bgColor, textColor, activeColor }) => (
<div
key={theme}
- className={`w-full text-center outline-solid outline-neutral-content outline h-20 duration-100 rounded-xl flex items-center justify-center cursor-pointer select-none ${bgColor} ${
- localStorage.getItem("theme") === theme
- ? `outline-primary ${activeColor}`
- : textColor
- }`}
+ className={`w-full text-center outline-solid outline-neutral-content outline h-20 duration-100 rounded-xl flex items-center justify-center cursor-pointer select-none ${bgColor} ${localStorage.getItem("theme") === theme
+ ? `outline-primary ${activeColor}`
+ : textColor
+ }`}
onClick={() => updateSettings({ theme })}
>
<i className={`${icon} text-3xl`}></i>
@@ -363,9 +352,8 @@ export default function Preference() {
</div>
</div>
<div
- className={`mb-3 ${
- aiTaggingMethod === AiTaggingMethod.DISABLED ? "opacity-50" : ""
- }`}
+ className={`mb-3 ${aiTaggingMethod === AiTaggingMethod.DISABLED ? "opacity-50" : ""
+ }`}
>
<Checkbox
label={t("generate_tags_for_existing_links")}
diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.json
index faa7101d..42045803 100644
--- a/apps/web/public/locales/en/common.json
+++ b/apps/web/public/locales/en/common.json
@@ -474,5 +474,7 @@
"cancel": "Cancel",
"preservation_rules": "Preservation rules:",
"links_being_archived": "Links are being archived...",
- "display_on_dashboard": "Display on Dashboard"
-}
+ "display_on_dashboard": "Display on Dashboard",
+ "dashboard_stats": "Dashboard Stats",
+ "no_results_found": "No results found."
+}
\ No newline at end of file
diff --git a/packages/lib/schemaValidation.ts b/packages/lib/schemaValidation.ts
index caf4477b..656fbe70 100644
--- a/packages/lib/schemaValidation.ts
+++ b/packages/lib/schemaValidation.ts
@@ -76,8 +76,6 @@ export const UpdateUserSchema = () => {
archiveAsPDF: z.boolean().optional(),
archiveAsReadable: z.boolean().optional(),
archiveAsWaybackMachine: z.boolean().optional(),
- dashboardPinnedLinks: z.boolean().optional(),
- dashboardRecentLinks: z.boolean().optional(),
aiTaggingMethod: z.nativeEnum(AiTaggingMethod).optional(),
aiPredefinedTags: z.array(z.string().max(20).trim()).max(20).optional(),
aiTagExistingLinks: z.boolean().optional(),
@@ -258,3 +256,7 @@ export const LinkArchiveActionSchema = z.object({
});
export type LinkArchiveActionSchemaType = z.infer<typeof LinkArchiveActionSchema>;
+
+export const UpdateDashboardLayoutSchema = z.object({
+
+});
\ No newline at end of file
diff --git a/packages/prisma/migrations/20250530041916_add_dashboard_sections_for_users/migration.sql b/packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sql
similarity index 78%
rename from packages/prisma/migrations/20250530041916_add_dashboard_sections_for_users/migration.sql
rename to packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sql
index 346befaf..493060df 100644
--- a/packages/prisma/migrations/20250530041916_add_dashboard_sections_for_users/migration.sql
+++ b/packages/prisma/migrations/20250531210804_add_dashboard_sections/migration.sql
@@ -16,8 +16,8 @@ DROP COLUMN "dashboardRecentLinks";
CREATE TABLE "DashboardSection" (
"id" SERIAL NOT NULL,
"userId" INTEGER NOT NULL,
- "type" "DashboardSectionType" NOT NULL,
"collectionId" INTEGER,
+ "type" "DashboardSectionType" NOT NULL,
"order" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
@@ -28,5 +28,11 @@ CREATE TABLE "DashboardSection" (
-- CreateIndex
CREATE UNIQUE INDEX "DashboardSection_userId_order_key" ON "DashboardSection"("userId", "order");
+-- CreateIndex
+CREATE UNIQUE INDEX "DashboardSection_userId_collectionId_key" ON "DashboardSection"("userId", "collectionId");
+
-- AddForeignKey
ALTER TABLE "DashboardSection" ADD CONSTRAINT "DashboardSection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "DashboardSection" ADD CONSTRAINT "DashboardSection_collectionId_fkey" FOREIGN KEY ("collectionId") REFERENCES "Collection"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 22f58e63..9a3b9f22 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -61,7 +61,7 @@ model User {
archiveAsWaybackMachine Boolean @default(false)
isPrivate Boolean @default(false)
referredBy String?
- DashboardSection DashboardSection[]
+ dashboardSections DashboardSection[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
}
@@ -136,6 +136,7 @@ model Collection {
rssSubscriptions RssSubscription[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
+ DashboardSection DashboardSection[]
@@index([ownerId])
}
@@ -263,8 +264,9 @@ model DashboardSection {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
- type DashboardSectionType
+ collection Collection? @relation(fields: [collectionId], references: [id], onDelete: Cascade)
collectionId Int?
+ type DashboardSectionType
order Int
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
diff --git a/packages/router/dashboardData.tsx b/packages/router/dashboardData.tsx
index bea733a8..07026081 100644
--- a/packages/router/dashboardData.tsx
+++ b/packages/router/dashboardData.tsx
@@ -1,4 +1,4 @@
-import { useQuery } from "@tanstack/react-query";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
const useDashboardData = () => {
@@ -16,4 +16,26 @@ const useDashboardData = () => {
});
};
-export { useDashboardData };
+const useUpdateDashboardLayout = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (layout: any) => {
+ const response = await fetch("/api/v2/dashboard", {
+ method: "UPDATE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(layout),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.response);
+ }
+
+ return data;
+ },
+ });
+}
+
+export { useDashboardData, useUpdateDashboardLayout };
diff --git a/packages/router/user.tsx b/packages/router/user.tsx
index ff5b5feb..e68458f9 100644
--- a/packages/router/user.tsx
+++ b/packages/router/user.tsx
@@ -26,10 +26,10 @@ const useUser = (auth?: MobileAuth) => {
url,
auth?.session
? {
- headers: {
- Authorization: `Bearer ${auth.session}`,
- },
- }
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
: undefined
);