⚡️⚡️⚡️ 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
post highlight functionality
daniel31x13c6c8dab5db46
diff --git a/components/Preservation/PreservationContent.tsx b/components/Preservation/PreservationContent.tsxindex 9c5af00b..895ba0c9 100644--- a/components/Preservation/PreservationContent.tsx+++ b/components/Preservation/PreservationContent.tsx@@ -148,7 +148,7 @@ export const PreservationContent: React.FC<Props> = ({ link, format }) => {return (<>{!monolithLoaded && (- <PreservationSkeleton className="max-w-screen-lg" />+ <PreservationSkeleton className="max-w-screen-lg h-screen" />)}<iframesrc={`/api/v1/archives/${link.id}?format=${ArchivedFormat.monolith}&_=${link.updatedAt}`}@@ -164,7 +164,9 @@ export const PreservationContent: React.FC<Props> = ({ link, format }) => {case ArchivedFormat.pdf:return (<>- {!pdfLoaded && <PreservationSkeleton className="max-w-screen-lg" />}+ {!pdfLoaded && (+ <PreservationSkeleton className="max-w-screen-lg h-screen" />+ )}<iframesrc={`/api/v1/archives/${link.id}?format=${ArchivedFormat.pdf}&_=${link.updatedAt}`}className={clsx(@@ -181,7 +183,7 @@ export const PreservationContent: React.FC<Props> = ({ link, format }) => {return (<>{!imageLoaded && (- <PreservationSkeleton className="max-w-screen-lg" />+ <PreservationSkeleton className="max-w-screen-lg h-screen" />)}<divclassName={clsx(diff --git a/components/Preservation/ReadableView.tsx b/components/Preservation/ReadableView.tsxindex 99c1cd2a..8c313964 100644--- a/components/Preservation/ReadableView.tsx+++ b/components/Preservation/ReadableView.tsx@@ -1,19 +1,24 @@-import { formatAvailable } from "@/lib/shared/formatStats";-import {- ArchivedFormat,- LinkIncludingShortenedCollectionAndTags,-} from "@/types/global";+// Uncomment the comments for a basic notetaking functionality... (WIP)+import React, { useEffect, useState, useRef } from "react";import DOMPurify from "dompurify";-import { useRouter } from "next/router";-import React, { useEffect, useState } from "react";-import { useTranslation } from "next-i18next";import clsx from "clsx";-import LinkDate from "../LinkViews/LinkComponents/LinkDate";-import isValidUrl from "@/lib/shared/isValidUrl";+import { PreservationSkeleton } from "../Skeletons";+import { useTranslation } from "next-i18next";+import { useRouter } from "next/router";import Link from "next/link";import unescapeString from "@/lib/client/unescapeString";+import isValidUrl from "@/lib/shared/isValidUrl";+import LinkDate from "../LinkViews/LinkComponents/LinkDate";import usePermissions from "@/hooks/usePermissions";-import { PreservationSkeleton } from "../Skeletons";+import {+ LinkIncludingShortenedCollectionAndTags,+ ArchivedFormat,+} from "@/types/global";+import ClickAwayHandler from "@/components/ClickAwayHandler";+import {+ useGetLinkHighlights,+ usePostHighlight,+} from "@/hooks/store/highlights";type Props = {link: LinkIncludingShortenedCollectionAndTags;@@ -21,26 +26,125 @@ type Props = {export default function ReadableView({ link }: Props) {const { t } = useTranslation();- const [linkContent, setLinkContent] = useState("");-const router = useRouter();const isPublicRoute = router.pathname.startsWith("/public");const permissions = usePermissions(link?.collection?.id as number);+ const postHighlight = usePostHighlight();+ const { data: linkHighlights } = useGetLinkHighlights(link?.id as number);++ const [linkContent, setLinkContent] = useState("");+ const [showSelectionMenu, setShowSelectionMenu] = useState(false);+ const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });+ const contentRef = useRef<HTMLDivElement>(null);++ // const [isCommenting, setIsCommenting] = useState(false);+ // const [commentText, setCommentText] = useState("");+useEffect(() => {const fetchLinkContent = async () => {- if (formatAvailable(link, "readable")) {+ if (link?.readable?.startsWith("archives")) {const response = await fetch(`/api/v1/archives/${link?.id}?format=${ArchivedFormat.readability}&_=${link.updatedAt}`);- const data = await response?.json();- setLinkContent(data?.content || "");+ const data = await response.json();+ setLinkContent(DOMPurify.sanitize(data?.content) || "");}};-fetchLinkContent();}, [link]);+ const handleMouseUp = () => {+ const selection = window.getSelection();+ if (!selection) return;++ if (selection.rangeCount === 0) return;+ const range = selection.getRangeAt(0);+ const rect = range.getBoundingClientRect();++ if (rect && rect.width && rect.height) {+ const scrollTop = window.scrollY || document.documentElement.scrollTop;+ const scrollLeft = window.scrollX || document.documentElement.scrollLeft;++ setMenuPosition({+ x: rect.left + scrollLeft + rect.width / 2,+ y: rect.top + scrollTop - 5,+ });+ setShowSelectionMenu(true);+ }+ };++ const getHighlightedSection = (color: string) => {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return;++ try {+ const content = document.getElementById("readable-view")?.innerText;+ const sel = window.getSelection();+ const range = sel?.getRangeAt(0).cloneRange();+ const markerTextChar = range?.cloneContents();++ const selectedIndex = content?.indexOf(markerTextChar?.textContent || "");++ if (+ selectedIndex !== undefined &&+ markerTextChar?.textContent?.length !== undefined &&+ selectedIndex !== -1 &&+ markerTextChar?.textContent?.length !== -1 &&+ link?.id+ ) {+ return {+ linkId: link.id,+ color,+ text: markerTextChar?.textContent,+ startOffset: selectedIndex,+ endOffset: selectedIndex + markerTextChar.textContent.length,+ };+ }+ return null;+ } catch (err) {+ console.error("Could not highlight selection:", err);+ }+ };++ const handleHighlightSelection = async (+ color: "yellow" | "red" | "blue" | "green"+ ) => {+ const selection = getHighlightedSection(color);+ if (!selection) return;++ postHighlight.mutate(selection);+ };++ // const handleStartCommenting = (+ // event: React.MouseEvent<HTMLButtonElement>+ // ) => {+ // event.preventDefault();+ // const highlighted = getHighlightedSection("yellow");+ // if (!highlighted) return;++ // setIsCommenting(true);+ // };++ // const handleConfirmComment = () => {+ // console.log("Confirming comment:", commentText);+ // setIsCommenting(false);+ // setCommentText("");+ // };++ // const handleCancelComment = () => {+ // setIsCommenting(false);+ // setCommentText("");+ // };++ const handleMenuClickOutside = () => {+ setShowSelectionMenu(false);+ // setIsCommenting(false);+ if (window.getSelection) {+ window.getSelection()?.removeAllRanges();+ }+ };+return (<div className="flex flex-col gap-3 items-start p-3 max-w-screen-lg mx-auto bg-base-200 mt-10"><div className="flex gap-3 items-start">@@ -69,23 +173,112 @@ export default function ReadableView({ link }: Props) {{link?.readable?.startsWith("archives") ? (<>{linkContent ? (- <>+ <div+ ref={contentRef}+ className={clsx("p-3 rounded-md w-full bg-base-200")}+ onMouseUp={handleMouseUp}+ ><div- className={clsx(- "p-3 rounded-md w-full",- linkContent && "bg-base-200"+ id="readable-view"+ className="line-break px-1 reader-view read-only"+ dangerouslySetInnerHTML={{+ __html: DOMPurify.sanitize(linkContent),+ }}+ />++ {showSelectionMenu &&+ !isPublicRoute &&+ (permissions === true || permissions?.canUpdate) && (+ <ClickAwayHandler+ onClickOutside={handleMenuClickOutside}+ className="absolute bg-base-100 p-2 z-[9999]+ whitespace-nowrap -translate-x-1/2+ -translate-y-full rounded-lg shadow-md border border-neutral-content"+ style={{+ left: menuPosition.x,+ top: menuPosition.y,+ }}+ >+ <div className="flex items-center gap-3 justify-between select-none">+ <div className="flex items-center gap-3">+ <button+ onClick={() => handleHighlightSelection("yellow")}+ className="w-5 h-5 rounded-full bg-yellow-300 hover:opacity-70 duration-100"+ title="Yellow Highlight"+ />+ <button+ onClick={() => handleHighlightSelection("red")}+ className="w-5 h-5 rounded-full bg-red-500 hover:opacity-70 duration-100"+ title="Red Highlight"+ />+ <button+ onClick={() => handleHighlightSelection("blue")}+ className="w-5 h-5 rounded-full bg-blue-500 hover:opacity-70 duration-100"+ title="Blue Highlight"+ />+ <button+ onClick={() => handleHighlightSelection("green")}+ className="w-5 h-5 rounded-full bg-green-500 hover:opacity-70 duration-100"+ title="Green Highlight"+ />+ </div>++ <div className="flex items-center gap-3">+ {/* {isCommenting ? (+ <>+ <button+ onClick={handleConfirmComment}+ className="hover:opacity-70 duration-100"+ title="Confirm Comment"+ >+ <i className="bi-check2" />+ </button>+ <button+ onClick={handleCancelComment}+ className="hover:opacity-70 duration-100"+ title="Cancel Comment"+ >+ <i className="bi-x" />+ </button>+ </>+ ) : (+ <>+ <button+ onClick={handleStartCommenting}+ className="hover:opacity-70 duration-100"+ title="Add Comment"+ >+ <i className="bi-chat-text" />+ </button> */}+ <button+ onClick={() => handleHighlightSelection("yellow")}+ className="hover:opacity-70 duration-100"+ title="Delete"+ >+ <i className="bi-trash" />+ </button>+ {/* </>+ )} */}+ </div>+ </div>+ {/* {isCommenting && (+ <div className="mt-2">+ <textarea+ value={commentText}+ onChange={(e) => setCommentText(e.target.value)}+ placeholder="Add your comment..."+ className="resize-none w-full rounded-md p-2 h-28 mt-2+ border-neutral-content bg-base-200+ focus:border-primary border-solid+ border outline-none duration-100"+ />+ </div>+ )} */}+ </ClickAwayHandler>)}- >- <div- className="line-break px-1 reader-view read-only"- dangerouslySetInnerHTML={{- __html: DOMPurify.sanitize(linkContent),- }}- />- </div>- </>+ </div>) : (- <PreservationSkeleton />+ <PreservationSkeleton className="h-fit" />)}</>) : (diff --git a/components/Skeletons.tsx b/components/Skeletons.tsxindex fd035146..ae4ce477 100644--- a/components/Skeletons.tsx+++ b/components/Skeletons.tsx@@ -3,7 +3,7 @@ import clsx from "clsx";export const PreservationSkeleton = ({ className }: { className?: string }) => (<divclassName={clsx(- "p-5 m-auto w-full flex flex-col items-center gap-5 h-screen bg-base-200 justify-center",+ "p-5 m-auto w-full flex flex-col items-center gap-5 bg-base-200 justify-center",className)}>diff --git a/hooks/store/highlights.tsx b/hooks/store/highlights.tsxnew file mode 100644index 00000000..ffcce096--- /dev/null+++ b/hooks/store/highlights.tsx@@ -0,0 +1,121 @@+import {+ useQuery,+ useMutation,+ useQueryClient,+ UseQueryResult,+} from "@tanstack/react-query";+import { useSession } from "next-auth/react";+import { Highlight } from "@prisma/client";+import { PostHighlightSchemaType } from "@/lib/shared/schemaValidation";++const useGetLinkHighlights = (+ linkId: number+): UseQueryResult<Highlight[], Error> => {+ const { status } = useSession();++ return useQuery({+ queryKey: ["highlights", linkId],+ queryFn: async () => {+ const response = await fetch(`/api/v1/links/${linkId}/highlights`);+ if (!response.ok) throw new Error("Failed to fetch highlights.");++ const data = await response.json();+ return data.response;+ },+ enabled: status === "authenticated",+ });+};++const useUpdateHighlight = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (highlight: Highlight) => {+ const response = await fetch(`/api/v1/highlights/${highlight.id}`, {+ body: JSON.stringify(highlight),+ headers: {+ "Content-Type": "application/json",+ },+ method: "PUT",+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.response);++ return data.response;+ },+ onSuccess: (data) => {+ queryClient.setQueryData(["highlights"], (oldData: any) =>+ oldData.map((highlight: Highlight) =>+ highlight.id === data.id ? data : highlight+ )+ );+ },+ });+};++const usePostHighlight = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (highlight: PostHighlightSchemaType) => {+ const response = await fetch("/api/v1/highlights", {+ body: JSON.stringify({ ...highlight }),+ headers: {+ "Content-Type": "application/json",+ },+ method: "POST",+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.response);++ return data.response;+ },+ onSuccess: (data: Highlight[]) => {+ queryClient.setQueryData(["highlights"], (oldData: Highlight[] = []) => {+ const updatedHighlights = oldData.map((highlight) => {+ const updatedHighlight = data.find((t) => t.id === highlight.id);+ return updatedHighlight+ ? { ...highlight, ...updatedHighlight }+ : highlight;+ });++ const newHighlights = data.filter(+ (t) => !oldData.some((highlight) => highlight.id === t.id)+ );++ return [...updatedHighlights, ...newHighlights];+ });+ },+ });+};++const useRemoveHighlight = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (highlightId: number) => {+ const response = await fetch(`/api/v1/highlights/${highlightId}`, {+ method: "DELETE",+ });++ const data = await response.json();+ if (!response.ok) throw new Error(data.response);++ return data.response;+ },+ onSuccess: (data, variables) => {+ queryClient.setQueryData(["highlights"], (oldData: any) =>+ oldData.filter((highlight: Highlight) => highlight.id !== variables)+ );+ },+ });+};++export {+ useGetLinkHighlights,+ useUpdateHighlight,+ usePostHighlight,+ useRemoveHighlight,+};diff --git a/lib/api/controllers/highlights/postHighlight.ts b/lib/api/controllers/highlights/postHighlight.tsnew file mode 100644index 00000000..9fef3db0--- /dev/null+++ b/lib/api/controllers/highlights/postHighlight.ts@@ -0,0 +1,64 @@+import { prisma } from "@/lib/api/db";+import { PostHighlightSchemaType } from "@/lib/shared/schemaValidation";++export default async function postHighlight(+ userId: number,+ body: PostHighlightSchemaType+) {+ // check if user has access to collection+ const collection = await prisma.collection.findFirst({+ where: {+ links: {+ some: {+ id: body.linkId,+ },+ },+ },+ include: {+ members: true,+ },+ });++ if (+ !collection ||+ !collection.members.some((m) => m.userId === userId && m.canUpdate) ||+ !(collection.ownerId === userId)+ ) {+ return {+ status: 400,+ response: "Collection not accessible",+ };+ }++ // check if highlight already exists+ const existingHighlight = await prisma.highlight.findFirst({+ where: {+ linkId: body.linkId,+ userId,+ startOffset: body.startOffset,+ endOffset: body.endOffset,+ },+ });++ if (existingHighlight) {+ return {+ status: 400,+ response: "Highlight already exists",+ };+ }++ // create highlight+ const highlight = await prisma.highlight.create({+ data: {+ userId,+ linkId: body.linkId,+ startOffset: body.startOffset,+ endOffset: body.endOffset,+ color: body.color,+ text: body.text,+ comment: body.comment,+ },+ });++ return highlight;+}diff --git a/lib/api/controllers/links/linkId/highlight/getLinkHighlights.ts b/lib/api/controllers/links/linkId/highlight/getLinkHighlights.tsnew file mode 100644index 00000000..4a165474--- /dev/null+++ b/lib/api/controllers/links/linkId/highlight/getLinkHighlights.ts@@ -0,0 +1,18 @@+import { prisma } from "@/lib/api/db";++export default async function getLinkHighlights({+ userId,+ linkId,+}: {+ userId: number;+ linkId: number;+}) {+ const highlights = await prisma.highlight.findMany({+ where: {+ linkId,+ userId,+ },+ });++ return { response: highlights, status: 200 };+}diff --git a/lib/shared/schemaValidation.ts b/lib/shared/schemaValidation.tsindex 5c046840..7aec786a 100644--- a/lib/shared/schemaValidation.ts+++ b/lib/shared/schemaValidation.ts@@ -241,6 +241,17 @@ export const PostTagSchema = z.object({export type PostTagSchemaType = z.infer<typeof PostTagSchema>;+export const PostHighlightSchema = z.object({+ color: z.string().trim().max(50),+ comment: z.string().trim().max(2048).nullish(),+ startOffset: z.number(),+ endOffset: z.number(),+ text: z.string().trim().max(2048),+ linkId: z.number(),+});++export type PostHighlightSchemaType = z.infer<typeof PostHighlightSchema>;+export const LinkArchiveActionSchema = z.object({action: z.enum(["allAndRePreserve", "allAndIgnore", "allBroken"]),});diff --git a/pages/api/v1/highlights/[id].ts b/pages/api/v1/highlights/[id].tsnew file mode 100644index 00000000..e69de29bdiff --git a/pages/api/v1/highlights/index.ts b/pages/api/v1/highlights/index.tsnew file mode 100644index 00000000..f60530fc--- /dev/null+++ b/pages/api/v1/highlights/index.ts@@ -0,0 +1,30 @@+import type { NextApiRequest, NextApiResponse } from "next";+import verifyUser from "@/lib/api/verifyUser";+import { PostHighlightSchema } from "@/lib/shared/schemaValidation";+import postHighlight from "@/lib/api/controllers/highlights/postHighlight";++export default async function highlights(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const user = await verifyUser({ req, res });+ if (!user) return;++ if (req.method === "POST") {+ const dataValidation = PostHighlightSchema.safeParse(req.body);++ if (!dataValidation.success) {+ return res.status(400).json({+ response: `Error: ${+ dataValidation.error.issues[0].message+ } [${dataValidation.error.issues[0].path.join(", ")}]`,+ });+ }++ const body = dataValidation.data;++ const highlights = await postHighlight(user.id, body);++ return res.status(200).json({ response: highlights });+ }+}diff --git a/pages/api/v1/links/[id]/highlights/index.ts b/pages/api/v1/links/[id]/highlights/index.tsnew file mode 100644index 00000000..89e3b5e8--- /dev/null+++ b/pages/api/v1/links/[id]/highlights/index.ts@@ -0,0 +1,22 @@+import type { NextApiRequest, NextApiResponse } from "next";+import verifyUser from "@/lib/api/verifyUser";+import getLinkHighlights from "@/lib/api/controllers/links/linkId/highlight/getLinkHighlights";++export default async function highlights(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const user = await verifyUser({ req, res });+ if (!user) return;++ if (req.method === "GET") {+ const highlights = await getLinkHighlights({+ userId: user.id,+ linkId: Number(req.query.id as string),+ });++ return res+ .status(highlights?.status || 500)+ .json({ response: highlights?.response });+ }+}diff --git a/prisma/migrations/20250304145909_add_table/migration.sql b/prisma/migrations/20250304145909_add_table/migration.sqlnew file mode 100644index 00000000..5c9d5789--- /dev/null+++ b/prisma/migrations/20250304145909_add_table/migration.sql@@ -0,0 +1,21 @@+-- CreateTable+CREATE TABLE "Highlight" (+ "id" SERIAL NOT NULL,+ "color" TEXT NOT NULL,+ "comment" TEXT,+ "linkId" INTEGER NOT NULL,+ "userId" INTEGER NOT NULL,+ "startOffset" INTEGER NOT NULL,+ "endOffset" INTEGER NOT NULL,+ "text" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "Highlight_pkey" PRIMARY KEY ("id")+);++-- AddForeignKey+ALTER TABLE "Highlight" ADD CONSTRAINT "Highlight_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "Link"("id") ON DELETE RESTRICT ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "Highlight" ADD CONSTRAINT "Highlight_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 8c1f002f..7e86e8ae 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -43,6 +43,7 @@ model User {pinnedLinks Link[] @relation("PinnedLinks")createdLinks Link[] @relation("CreatedLinks")createdCollections Collection[] @relation("CreatedCollections")+ highlights Highlight[]collectionsJoined UsersAndCollections[]collectionOrder Int[] @default([])whitelistedUsers WhitelistedUser[]@@ -153,6 +154,7 @@ model Link {name String @default("")type String @default("url")description String @default("")+ highlight Highlight[]pinnedBy User[] @relation("PinnedLinks")createdBy User? @relation("CreatedLinks", fields: [createdById], references: [id])createdById Int?@@ -235,3 +237,18 @@ model RssSubscription {createdAt DateTime @default(now())updatedAt DateTime @default(now()) @updatedAt}++model Highlight {+ id Int @id @default(autoincrement())+ color String+ comment String?+ link Link @relation(fields: [linkId], references: [id])+ linkId Int+ user User @relation(fields: [userId], references: [id])+ userId Int+ startOffset Int+ endOffset Int+ text String+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt+}\ No newline at end of file