⚡️⚡️⚡️ 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
WIP
daniel31x136c75f3ee5887
diff --git a/apps/web/components/DashboardLayoutDropdown.tsx b/apps/web/components/DashboardLayoutDropdown.tsxindex 22191dc0..f1f4088b 100644--- a/apps/web/components/DashboardLayoutDropdown.tsx+++ b/apps/web/components/DashboardLayoutDropdown.tsx@@ -1,4 +1,4 @@-import React, { useState, useMemo, useEffect } from "react";+import React, { useState, useMemo, DragEvent } from "react";import {DropdownMenu,DropdownMenuTrigger,@@ -14,13 +14,6 @@ import {} 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";interface DashboardSectionOption {type: DashboardSectionType;@@ -36,8 +29,11 @@ export default function DashboardLayoutDropdown() {const { data: collections = [] } = useCollections();const updateDashboardLayout = useUpdateDashboardLayout();const [searchTerm, setSearchTerm] = useState("");- const [draggedItem, setDraggedItem] = useState<string | null>(null);- const [dragOverItem, setDragOverItem] = useState<string | null>(null);+ const [draggedId, setDraggedId] = useState<string | null>(null);+ const [dragOverId, setDragOverId] = useState<string | null>(null);+ const [dragOverPosition, setDragOverPosition] = useState<+ "above" | "below" | null+ >(null);const dashboardSections: DashboardSection[] = user?.dashboardSections || [];@@ -138,58 +134,13 @@ export default function DashboardLayoutDropdown() {}, [allSections, searchTerm]);const getSectionId = (section: DashboardSectionOption) =>- `${section.type}-${section.collectionId || "default"}`;-- 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;- });-- updateDashboardLayout.mutateAsync(updatedSections);- },- });- }, [filteredSections]);+ `${section.type}-${section.collectionId ?? "default"}`;const handleCheckboxChange = (section: DashboardSectionOption) => {const enabledSections = allSections.filter((s) => s.enabled);const highestOrder =enabledSections.length > 0- ? Math.max(...enabledSections.map((s) => s.order || 0))+ ? Math.max(...enabledSections.map((s) => s.order ?? 0)): -1;const updatedSections = allSections.map((s) => {@@ -206,8 +157,29 @@ export default function DashboardLayoutDropdown() {updateDashboardLayout.mutateAsync(updatedSections);};+ const handleReorder = (sourceId: string, destId: string) => {+ if (sourceId === destId) return;+ const sourceIndex = filteredSections.findIndex(+ (s) => getSectionId(s) === sourceId+ );+ const destIndex = filteredSections.findIndex(+ (s) => getSectionId(s) === destId+ );+ if (sourceIndex < 0 || destIndex < 0) return;++ const reordered = [...filteredSections];+ const [moved] = reordered.splice(sourceIndex, 1);+ reordered.splice(destIndex, 0, moved);++ const updated = reordered.map((section, idx) =>+ section.enabled ? { ...section, order: idx } : section+ );++ updateDashboardLayout.mutateAsync(updated);+ };+return (- <DropdownMenu modal={true}>+ <DropdownMenu modal><DropdownMenuTrigger asChild><Button variant="ghost" size="icon"><i className="bi-sliders2-vertical text-neutral" />@@ -233,10 +205,13 @@ export default function DashboardLayoutDropdown() {key={getSectionId(section)}section={section}onCheckboxChange={handleCheckboxChange}- isDragged={draggedItem === getSectionId(section)}- isDraggingOver={dragOverItem === getSectionId(section)}- setDraggedItem={setDraggedItem}- setDragOverItem={setDragOverItem}+ onReorder={handleReorder}+ draggedId={draggedId}+ dragOverId={dragOverId}+ dragOverPosition={dragOverPosition}+ setDraggedId={setDraggedId}+ setDragOverId={setDragOverId}+ setDragOverPosition={setDragOverPosition}/>))}@@ -255,61 +230,95 @@ export default function DashboardLayoutDropdown() {interface DraggableListItemProps {section: DashboardSectionOption;onCheckboxChange: (section: DashboardSectionOption) => void;- isDragged: boolean;- isDraggingOver: boolean;- setDraggedItem: (id: string | null) => void;- setDragOverItem: (id: string | null) => void;+ onReorder: (sourceId: string, destId: string) => void;+ draggedId: string | null;+ dragOverId: string | null;+ dragOverPosition: "above" | "below" | null;+ setDraggedId: (id: string | null) => void;+ setDragOverId: (id: string | null) => void;+ setDragOverPosition: (pos: "above" | "below" | null) => void;}function DraggableListItem({section,onCheckboxChange,- isDragged,- isDraggingOver,- setDraggedItem,- setDragOverItem,+ onReorder,+ draggedId,+ dragOverId,+ dragOverPosition,+ setDraggedId,+ setDragOverId,+ setDragOverPosition,}: 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);- setDragOverItem(null);- },- }),- dropTargetForElements({- element: el,- getData: () => ({ sectionId }),- onDragEnter: () => setDragOverItem(sectionId),- onDragLeave: () => setDragOverItem(null),- onDrop: () => setDragOverItem(null),- })- );- }, [element, section.enabled, sectionId, setDraggedItem, setDragOverItem]);+ const sectionId = `${section.type}-${section.collectionId ?? "default"}`;++ const handleDragStart = (e: DragEvent<HTMLLIElement>) => {+ const img = new Image();+ img.src =+ "data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg'/%3e";+ e.dataTransfer.setDragImage(img, 0, 0);++ e.dataTransfer.setData("text/plain", sectionId);+ setDraggedId(sectionId);+ e.dataTransfer.effectAllowed = "move";+ };++ const handleDragOver = (e: DragEvent<HTMLLIElement>) => {+ e.preventDefault();+ const rect = e.currentTarget.getBoundingClientRect();+ const midY = rect.top + rect.height / 2;+ const pos = e.clientY < midY ? "above" : "below";+ setDragOverPosition(pos);+ setDragOverId(sectionId);+ e.dataTransfer.dropEffect = "move";+ };++ const handleDragLeave = () => {+ setDragOverId(null);+ setDragOverPosition(null);+ };++ const handleDrop = (e: DragEvent<HTMLLIElement>) => {+ e.preventDefault();+ const sourceId = e.dataTransfer.getData("text/plain");+ if (sourceId) {+ const destId = dragOverPosition === "below" ? sectionId : sectionId;+ onReorder(sourceId, destId);+ }+ setDraggedId(null);+ setDragOverId(null);+ setDragOverPosition(null);+ };++ const indicatorClass =+ dragOverId === sectionId && dragOverPosition === "above"+ ? "border-t-2 border-primary"+ : dragOverId === sectionId && dragOverPosition === "below"+ ? "border-b-2 border-primary"+ : "";return (<li- ref={setElement}- data-section-id={sectionId}+ draggable={section.enabled}+ onDragStart={handleDragStart}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ onDragEnd={() => {+ setDraggedId(null);+ setDragOverId(null);+ setDragOverPosition(null);+ }}className={`- py-1 px-2 flex items-center justify-between cursor-pointer rounded transition-colors+ py-1 px-2 flex items-center justify-between${section.enabled ? "cursor-grab active:cursor-grabbing" : ""}- ${isDragged ? "opacity-70" : ""}- ${isDraggingOver && !isDragged ? "bg-base-100" : ""}+ ${draggedId === sectionId ? "opacity-70" : ""}+ ${indicatorClass}`}><div className="flex items-center gap-2"><input- id={`section-${section.type}-${section.collectionId || "default"}`}+ id={`section-${section.type}-${section.collectionId ?? "default"}`}className="checkbox checkbox-primary"type="checkbox"checked={section.enabled}@@ -317,7 +326,7 @@ function DraggableListItem({/><labelhtmlFor={`section-${section.type}-${- section.collectionId || "default"+ section.collectionId ?? "default"}`}className="text-sm select-none">diff --git a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.tsindex b6fefc0e..604206ec 100644--- a/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts+++ b/apps/web/lib/api/controllers/dashboard/getDashboardDataV2.ts@@ -1,32 +1,34 @@import { prisma } from "@linkwarden/prisma";-import { DashboardSection } from "@linkwarden/prisma/client";import { LinkRequestQuery, Order, Sort } from "@linkwarden/types";export default async function getDashboardData(userId: number,- query: LinkRequestQuery,- viewRecent: boolean,- viewPinned: boolean,- collectionSections: DashboardSection[]+ query: LinkRequestQuery) {- let pinnedTake = 0;- let recentTake = 0;-- if (viewPinned && viewRecent) {- pinnedTake = 16;- recentTake = 16;- } else if (viewPinned && !viewRecent) {- pinnedTake = 32;- } else if (!viewPinned && viewRecent) {- recentTake = 32;- }-let order: Order = { id: "desc" };if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };else if (query.sort === Sort.NameAZ) order = { name: "asc" };else if (query.sort === Sort.NameZA) order = { name: "desc" };+ const dashboardSections = await prisma.dashboardSection.findMany({+ where: {+ userId,+ },+ });++ const viewPinned = dashboardSections.some(+ (section) => section.type === "PINNED_LINKS"+ );++ const viewRecent = dashboardSections.some(+ (section) => section.type === "RECENT_LINKS"+ );++ const collectionSections = dashboardSections.filter(+ (section) => section.type === "COLLECTION"+ );+const numberOfPinnedLinks = await prisma.link.count({where: {AND: [@@ -65,7 +67,7 @@ export default async function getDashboardData(if (viewPinned) {pinnedLinks = await prisma.link.findMany({- take: pinnedTake,+ take: 16,where: {AND: [{@@ -101,7 +103,7 @@ export default async function getDashboardData(if (viewRecent) {recentlyAddedLinks = await prisma.link.findMany({- take: recentTake,+ take: 16,where: {collection: {OR: [@@ -171,7 +173,6 @@ export default async function getDashboardData(...collectionLinks,].sort((a, b) => new Date(b.id).getTime() - new Date(a.id).getTime());- // Make sure links are uniqueconst uniqueLinks = links.filter((link, index, self) => index === self.findIndex((t) => t.id === link.id));diff --git a/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts b/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.tsindex 9346d9c2..6bdec0dc 100644--- a/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts+++ b/apps/web/lib/api/controllers/dashboard/updateDashboardLayout.ts@@ -8,7 +8,7 @@ import { DashboardSection } from "@linkwarden/prisma/client";export default async function updateDashboardLayout(userId: number,body: UpdateDashboardLayoutSchemaType[]-): Promise<any> {+) {const dataValidation = UpdateDashboardLayoutSchema.safeParse(body);if (!dataValidation.success) {@@ -23,6 +23,27 @@ export default async function updateDashboardLayout(const data = dataValidation.data;+ let collectionIds = data+ .map((section) => section.collectionId)+ .filter((id) => id !== undefined);++ if (collectionIds && collectionIds.length > 0) {+ collectionIds = (+ await prisma.collection.findMany({+ where: {+ id: {+ in: collectionIds,+ },+ OR: [{ ownerId: userId }, { members: { some: { userId } } }],+ },+ })+ ).map((collection) => collection.id);+ }++ let parsedData = data.filter((section) =>+ section.collectionId ? collectionIds.includes(section.collectionId) : true+ );+const existingSections = await prisma.dashboardSection.findMany({where: {userId: userId,@@ -50,7 +71,7 @@ export default async function updateDashboardLayout(order: number;}> = [];- for (const section of data) {+ for (const section of parsedData) {const key = `${section.type}-${section.collectionId || "default"}`;const existingSection = existingSectionsMap.get(key);@@ -159,6 +180,6 @@ export default async function updateDashboardLayout(return {status: 200,- response: data,+ response: parsedData,};}diff --git a/apps/web/lib/api/controllers/users/userId/getUserById.ts b/apps/web/lib/api/controllers/users/userId/getUserById.tsindex 5b56b4a4..1ca6ec96 100644--- a/apps/web/lib/api/controllers/users/userId/getUserById.ts+++ b/apps/web/lib/api/controllers/users/userId/getUserById.ts@@ -1,5 +1,9 @@import { prisma } from "@linkwarden/prisma";-import { Subscription, User } from "@linkwarden/prisma/client";+import {+ DashboardSection,+ Subscription,+ User,+} from "@linkwarden/prisma/client";type GetUserByIdResponse = Omit<User, "password"> &Partial<{ subscription: Pick<Subscription, "active" | "quantity"> }> & {@@ -11,7 +15,8 @@ type GetUserByIdResponse = Omit<User, "password"> &};} & {whitelistedUsers: string[];- }+ dashboardSections: DashboardSection[];+ };export default async function getUserById(userId: number) {const user = await prisma.user.findUnique({@@ -57,7 +62,7 @@ export default async function getUserById(userId: number) {email: parentSubscription?.user.email,},},- }+ };return { response: data, status: 200 };}diff --git a/apps/web/lib/api/verifyUser.ts b/apps/web/lib/api/verifyUser.tsindex 56e08114..c99d2f54 100644--- a/apps/web/lib/api/verifyUser.ts+++ b/apps/web/lib/api/verifyUser.ts@@ -1,15 +1,9 @@import { NextApiRequest, NextApiResponse } from "next";import { prisma } from "@linkwarden/prisma";-import { Prisma } from "@linkwarden/prisma/client";+import { User } 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;@@ -20,7 +14,7 @@ const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;export default async function verifyUser({req,res,-}: Props): Promise<UserWithIncludes | null> {+}: Props): Promise<User | null> {const token = await verifyToken({ req });if (typeof token === "string") {@@ -37,7 +31,6 @@ export default async function verifyUser({include: {subscriptions: true,parentSubscription: true,- dashboardSections: true,},});diff --git a/apps/web/package.json b/apps/web/package.jsonindex e37ca89f..da32b4d7 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,7 +17,6 @@},"dependencies": {"@atlaskit/tree": "^8.8.7",- "@atlaskit/pragmatic-drag-and-drop": "^1.7.2","@auth/prisma-adapter": "^1.0.1","@headlessui/react": "^1.7.15","@linkwarden/filesystem": "*",@@ -106,4 +105,4 @@"tailwindcss": "^3.4.17","typescript": "4.9.4"}-}\ No newline at end of file+}diff --git a/apps/web/pages/api/v2/dashboard/index.ts b/apps/web/pages/api/v2/dashboard/index.tsindex 9f5d2318..9dac0f3f 100644--- a/apps/web/pages/api/v2/dashboard/index.ts+++ b/apps/web/pages/api/v2/dashboard/index.ts@@ -18,24 +18,9 @@ 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 collectionSections = user.dashboardSections.filter(- (section) => section.type === "COLLECTION"- );-const { statusCode, ...data } = await getDashboardDataV2(user.id,- convertedData,- showRecentLinks,- showPinnedLinks,- collectionSections+ convertedData);return res.status(statusCode).json(data);diff --git a/apps/web/styles/globals.css b/apps/web/styles/globals.cssindex 524a3891..194b20de 100644--- a/apps/web/styles/globals.css+++ b/apps/web/styles/globals.css@@ -325,3 +325,12 @@.read-only ul[data-type="taskList"] {pointer-events: none;}++.noselect * {+ -webkit-touch-callout: none !important;+ -webkit-user-select: none !important;+ -khtml-user-select: none !important;+ -moz-user-select: none !important;+ -ms-user-select: none !important;+ user-select: none !important;+}diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex c8762a95..7ee7afaa 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -93,13 +93,6 @@ enum LinksRouteTo {DETAILS}-enum DashboardSectionType {- STATS- RECENT_LINKS- PINNED_LINKS- COLLECTION-}-model WhitelistedUser {id Int @id @default(autoincrement())username String @default("")@@ -284,3 +277,10 @@ model DashboardSection {@@unique([userId, collectionId])}++enum DashboardSectionType {+ STATS+ RECENT_LINKS+ PINNED_LINKS+ COLLECTION+}\ No newline at end of filediff --git a/packages/router/collections.tsx b/packages/router/collections.tsxindex 00cd591e..6b0dce2a 100644--- a/packages/router/collections.tsx+++ b/packages/router/collections.tsx@@ -111,10 +111,13 @@ const useDeleteCollection = () => {return {...oldData,- links: oldData.links?.filter((link: any) => link.collectionId !== id) || [],- numberOfPinnedLinks: oldData.links?.filter((link: any) =>- link.collectionId !== id && link.isPinned- ).length || 0+ links:+ oldData.links?.filter((link: any) => link.collectionId !== id) ||+ [],+ numberOfPinnedLinks:+ oldData.links?.filter(+ (link: any) => link.collectionId !== id && link.isPinned+ ).length || 0,};});},diff --git a/packages/router/dashboardData.tsx b/packages/router/dashboardData.tsxindex 4f772f2d..f174a5d1 100644--- a/packages/router/dashboardData.tsx+++ b/packages/router/dashboardData.tsx@@ -44,7 +44,7 @@ const useUpdateDashboardLayout = () => {queryClient.setQueryData(["user"], (oldData: any) => {return {...oldData,- dashboardSections: newData.filter((section) => section.enabled)+ dashboardSections: newData.filter((section) => section.enabled),};});diff --git a/packages/router/user.tsx b/packages/router/user.tsxindex 96a097ea..7ee1ab5e 100644--- a/packages/router/user.tsx+++ b/packages/router/user.tsx@@ -1,5 +1,9 @@import { UpdateUserPreferenceSchemaType } from "@linkwarden/lib/schemaValidation";-import { DashboardSection, Subscription, User, WhitelistedUser } from "@linkwarden/prisma/client";+import {+ DashboardSection,+ Subscription,+ User,+} from "@linkwarden/prisma/client";import { MobileAuth } from "@linkwarden/types";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { useSession } from "next-auth/react";@@ -28,10 +32,10 @@ const useUser = (auth?: MobileAuth) => {url,auth?.session? {- headers: {- Authorization: `Bearer ${auth.session}`,- },- }+ headers: {+ Authorization: `Bearer ${auth.session}`,+ },+ }: undefined);diff --git a/yarn.lock b/yarn.lockindex 0df00cfb..3842745c 100644--- a/yarn.lock+++ b/yarn.lock@@ -127,15 +127,6 @@"@jridgewell/gen-mapping" "^0.3.5""@jridgewell/trace-mapping" "^0.3.24"-"@atlaskit/pragmatic-drag-and-drop@^1.7.2":- version "1.7.2"- resolved "https://registry.yarnpkg.com/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.7.2.tgz#68a4de4932497941ef4bfac7b08a9a789e37efb1"- integrity sha512-GFlFVusm+PpzNwpk4ju8+w9a9pWD5NIGi4DoJ9g6CXTUMlQ4BCsivvmUk+azsV31luEKZtf2J0tg1y3vdltrTQ==- dependencies:- "@babel/runtime" "^7.0.0"- bind-event-listener "^3.0.0"- raf-schd "^4.0.3"-"@atlaskit/tree@^8.8.7":version "8.8.7"resolved "https://registry.yarnpkg.com/@atlaskit/tree/-/tree-8.8.7.tgz#f895137b063f676a490abb0b5deb939a96f51fd7"@@ -5390,11 +5381,6 @@ binary-extensions@^2.0.0:resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d"integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==-bind-event-listener@^3.0.0:- version "3.0.0"- resolved "https://registry.yarnpkg.com/bind-event-listener/-/bind-event-listener-3.0.0.tgz#c90f9a7fcb65cac21045f810c20ef7e647a74921"- integrity sha512-PJvH288AWQhKs2v9zyfYdPzlPqf5bXbGMmhmUIY9x4dAUGIWgomO771oBQNwJnMQSnUIXhKu6sgzpBRXTlvb8Q==-bmp-js@^0.1.0:version "0.1.0"resolved "https://registry.yarnpkg.com/bmp-js/-/bmp-js-0.1.0.tgz#e05a63f796a6c1ff25f4771ec7adadc148c07233"@@ -11099,7 +11085,7 @@ [email protected]:dependencies:inherits "~2.0.3"-raf-schd@^4.0.0, raf-schd@^4.0.3:+raf-schd@^4.0.0:version "4.0.3"resolved "https://registry.yarnpkg.com/raf-schd/-/raf-schd-4.0.3.tgz#5d6c34ef46f8b2a0e880a8fcdb743efc5bfdbc1a"integrity sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==