Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add annotations to documents
Marc Seitz919a1505da95
diff --git a/components/documents/annotations/annotation-form.tsx b/components/documents/annotations/annotation-form.tsxnew file mode 100644index 00000000..7473498b--- /dev/null+++ b/components/documents/annotations/annotation-form.tsx@@ -0,0 +1,230 @@+"use client";++import { useEffect, useState } from "react";++import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import { z } from "zod";++import { uploadImage } from "@/lib/utils";++import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form-hook";+import { Input } from "@/components/ui/input";+import LoadingSpinner from "@/components/ui/loading-spinner";+import { RichTextEditor } from "@/components/ui/rich-text-editor";+import { Switch } from "@/components/ui/switch";++const formSchema = z.object({+ title: z+ .string()+ .min(1, "Title is required")+ .max(100, "Title must be less than 100 characters"),+ content: z.any().optional(),+ pages: z.array(z.number()).min(1, "At least one page must be selected"),+ isVisible: z.boolean().default(true),+});++type FormValues = z.infer<typeof formSchema>;++interface AnnotationFormProps {+ documentId: string;+ teamId: string;+ numPages: number;+ annotation?: any;+ onSuccess: () => void;+}++export function AnnotationForm({+ documentId,+ teamId,+ numPages,+ annotation,+ onSuccess,+}: AnnotationFormProps) {+ const [isLoading, setIsLoading] = useState(false);+ const [editorContent, setEditorContent] = useState(+ annotation?.content || null,+ );++ const form = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ title: annotation?.title || "",+ content: annotation?.content || null,+ pages: annotation?.pages || [],+ isVisible: annotation?.isVisible ?? true,+ },+ });++ const pageOptions = Array.from({ length: numPages }, (_, i) => i + 1);++ const handleImageUpload = async (file: File): Promise<string> => {+ try {+ // Upload the image using the existing uploadImage utility+ const imageUrl = await uploadImage(file, "assets");++ // Don't save to database here - let the form submission handle it+ // Images will be embedded in the rich text content and parsed when saving++ return imageUrl;+ } catch (error) {+ console.error("Failed to upload image:", error);+ throw new Error("Failed to upload image");+ }+ };++ const onSubmit = async (values: FormValues) => {+ setIsLoading(true);+ try {+ const url = annotation+ ? `/api/teams/${teamId}/documents/${documentId}/annotations/${annotation.id}`+ : `/api/teams/${teamId}/documents/${documentId}/annotations`;++ const method = annotation ? "PUT" : "POST";++ const response = await fetch(url, {+ method,+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...values,+ content: editorContent,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to save annotation");+ }++ toast.success(+ annotation+ ? "Annotation updated successfully"+ : "Annotation created successfully",+ );+ onSuccess();+ } catch (error) {+ console.error("Error saving annotation:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to save annotation",+ );+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">+ <FormField+ control={form.control}+ name="title"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Title</FormLabel>+ <FormControl>+ <Input placeholder="Enter annotation title" {...field} />+ </FormControl>+ <FormDescription>+ A brief title for this annotation that viewers will see.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="pages"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Pages</FormLabel>+ <FormDescription>+ Select which pages this annotation should appear on.+ </FormDescription>+ <div className="mt-2 grid grid-cols-10 gap-2">+ {pageOptions.map((page) => (+ <div key={page} className="flex items-center space-x-2">+ <Checkbox+ id={`page-${page}`}+ checked={field.value.includes(page)}+ onCheckedChange={(checked) => {+ if (checked) {+ field.onChange([...field.value, page]);+ } else {+ field.onChange(field.value.filter((p) => p !== page));+ }+ }}+ />+ <label+ htmlFor={`page-${page}`}+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ >+ {page}+ </label>+ </div>+ ))}+ </div>+ <FormMessage />+ </FormItem>+ )}+ />++ <div className="space-y-2">+ <FormLabel>Content</FormLabel>+ <FormDescription>+ Add rich text content and images to help explain this part of the+ document.+ </FormDescription>+ <RichTextEditor+ content={editorContent}+ onChange={setEditorContent}+ placeholder="Add your annotation content here..."+ onImageUpload={handleImageUpload}+ />+ </div>++ <FormField+ control={form.control}+ name="isVisible"+ render={({ field }) => (+ <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">+ <div className="space-y-0.5">+ <FormLabel className="text-base">Visible to viewers</FormLabel>+ <FormDescription>+ When enabled, viewers will be able to see this annotation when+ viewing the document.+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ )}+ />++ <div className="flex justify-end space-x-2">+ <Button type="submit" disabled={isLoading}>+ {isLoading && <LoadingSpinner className="mr-2 h-4 w-4" />}+ {annotation ? "Update Annotation" : "Create Annotation"}+ </Button>+ </div>+ </form>+ </Form>+ );+}diff --git a/components/documents/annotations/annotation-sheet.tsx b/components/documents/annotations/annotation-sheet.tsxnew file mode 100644index 00000000..d7077798--- /dev/null+++ b/components/documents/annotations/annotation-sheet.tsx@@ -0,0 +1,340 @@+"use client";++import { useState } from "react";++import { Edit2, Eye, EyeOff, Plus, Trash2 } from "lucide-react";+import { toast } from "sonner";++import { useAnnotations } from "@/lib/swr/use-annotations";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+ SheetTrigger,+} from "@/components/ui/sheet";++import { AnnotationForm } from "./annotation-form";++interface AnnotationSheetProps {+ documentId: string;+ teamId: string;+ numPages?: number;+ trigger?: React.ReactNode;+}++export function AnnotationSheet({+ documentId,+ teamId,+ numPages = 1,+ trigger,+}: AnnotationSheetProps) {+ const { annotations, mutate } = useAnnotations(documentId, teamId);+ const [isSheetOpen, setIsSheetOpen] = useState(false);+ const [isCreateOpen, setIsCreateOpen] = useState(false);+ const [editingAnnotation, setEditingAnnotation] = useState<any>(null);++ const handleDelete = async (annotationId: string) => {+ try {+ const response = await fetch(+ `/api/teams/${teamId}/documents/${documentId}/annotations/${annotationId}`,+ {+ method: "DELETE",+ },+ );++ if (!response.ok) {+ throw new Error("Failed to delete annotation");+ }++ toast.success("Annotation deleted successfully");+ mutate();+ } catch (error) {+ console.error("Error deleting annotation:", error);+ toast.error("Failed to delete annotation");+ }+ };++ const handleToggleVisibility = async (+ annotationId: string,+ isVisible: boolean,+ ) => {+ try {+ const response = await fetch(+ `/api/teams/${teamId}/documents/${documentId}/annotations/${annotationId}`,+ {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ isVisible: !isVisible,+ }),+ },+ );++ if (!response.ok) {+ throw new Error("Failed to update annotation");+ }++ toast.success(+ `Annotation ${!isVisible ? "shown" : "hidden"} successfully`,+ );+ mutate();+ } catch (error) {+ console.error("Error updating annotation:", error);+ toast.error("Failed to update annotation");+ }+ };++ const handleFormSuccess = () => {+ setIsCreateOpen(false);+ setEditingAnnotation(null);+ mutate();+ };++ return (+ <Sheet open={isSheetOpen} onOpenChange={setIsSheetOpen}>+ <SheetTrigger asChild>+ {trigger || (+ <Button variant="outline" size="sm">+ Add Annotations+ </Button>+ )}+ </SheetTrigger>+ <SheetContent className="w-[600px] sm:max-w-[600px]">+ <SheetHeader>+ <SheetTitle>Document Annotations</SheetTitle>+ <SheetDescription>+ Manage annotations that viewers can see when viewing this document.+ </SheetDescription>+ </SheetHeader>++ <div className="mt-6 space-y-4">+ <div className="flex items-center justify-between">+ <div className="text-sm text-muted-foreground">+ {annotations?.length || 0} annotation+ {annotations?.length !== 1 ? "s" : ""}+ </div>+ <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>+ <DialogTrigger asChild>+ <Button>+ <Plus className="mr-2 h-4 w-4" />+ Add Annotation+ </Button>+ </DialogTrigger>+ <DialogContent className="max-h-[90vh] max-w-4xl overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Create Annotation</DialogTitle>+ <DialogDescription>+ Add a new annotation that viewers can see when viewing this+ document.+ </DialogDescription>+ </DialogHeader>+ <AnnotationForm+ documentId={documentId}+ teamId={teamId}+ numPages={numPages}+ onSuccess={handleFormSuccess}+ />+ </DialogContent>+ </Dialog>+ </div>++ <ScrollArea className="h-[calc(100vh-200px)]">+ {annotations && annotations.length === 0 ? (+ <div className="flex flex-col items-center justify-center py-12 text-center">+ <div className="mb-4 rounded-full bg-muted p-3">+ <Plus className="h-6 w-6 text-muted-foreground" />+ </div>+ <h3 className="mb-2 text-lg font-medium">No annotations yet</h3>+ <p className="mb-4 max-w-sm text-sm text-muted-foreground">+ Create your first annotation to help viewers understand your+ document better.+ </p>+ <Button onClick={() => setIsCreateOpen(true)}>+ <Plus className="mr-2 h-4 w-4" />+ Create First Annotation+ </Button>+ </div>+ ) : (+ <div className="space-y-3">+ {annotations?.map((annotation) => (+ <div+ key={annotation.id}+ className="space-y-3 rounded-lg border p-4"+ >+ <div className="flex items-start justify-between">+ <div className="flex-1 space-y-1">+ <div className="flex items-center gap-2">+ <h4 className="font-medium">{annotation.title}</h4>+ {!annotation.isVisible && (+ <Badge variant="secondary">Hidden</Badge>+ )}+ </div>+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <span>Pages: {annotation.pages.join(", ")}</span>+ <span>•</span>+ <span>+ Created by{" "}+ {annotation.createdBy?.name ||+ annotation.createdBy?.email}+ </span>+ <span>•</span>+ <span>+ {new Date(+ annotation.createdAt,+ ).toLocaleDateString()}+ </span>+ </div>+ </div>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ handleToggleVisibility(+ annotation.id,+ annotation.isVisible,+ )+ }+ >+ {annotation.isVisible ? (+ <Eye className="h-4 w-4" />+ ) : (+ <EyeOff className="h-4 w-4" />+ )}+ </Button>+ <Dialog+ open={editingAnnotation?.id === annotation.id}+ onOpenChange={(open) =>+ setEditingAnnotation(open ? annotation : null)+ }+ >+ <DialogTrigger asChild>+ <Button variant="ghost" size="sm">+ <Edit2 className="h-4 w-4" />+ </Button>+ </DialogTrigger>+ <DialogContent className="max-h-[90vh] max-w-4xl overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Edit Annotation</DialogTitle>+ <DialogDescription>+ Update this annotation.+ </DialogDescription>+ </DialogHeader>+ <AnnotationForm+ documentId={documentId}+ teamId={teamId}+ numPages={numPages}+ annotation={annotation}+ onSuccess={handleFormSuccess}+ />+ </DialogContent>+ </Dialog>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="ghost" size="sm">+ <Trash2 className="h-4 w-4" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ Delete Annotation+ </AlertDialogTitle>+ <AlertDialogDescription>+ Are you sure you want to delete this annotation?+ This action cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => handleDelete(annotation.id)}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ </div>++ {/* Preview of annotation content */}+ {annotation.content && (+ <div className="rounded bg-muted/50 p-3 text-sm text-muted-foreground">+ <div className="line-clamp-3">+ {/* Simple text preview */}+ {typeof annotation.content === "object" &&+ annotation.content.content+ ? annotation.content.content+ .filter(+ (node: any) => node.type === "paragraph",+ )+ .map((node: any) =>+ node.content+ ?.filter(+ (textNode: any) =>+ textNode.type === "text",+ )+ .map((textNode: any) => textNode.text)+ .join(" "),+ )+ .join(" ")+ : "No content"}+ </div>+ {annotation.images && annotation.images.length > 0 && (+ <div className="mt-2 flex gap-1">+ {annotation.images.slice(0, 3).map((image) => (+ <img+ key={image.id}+ src={image.url}+ alt={image.filename}+ className="h-8 w-8 rounded border object-cover"+ />+ ))}+ {annotation.images.length > 3 && (+ <div className="flex h-8 w-8 items-center justify-center rounded border bg-muted text-xs">+ +{annotation.images.length - 3}+ </div>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </ScrollArea>+ </div>+ </SheetContent>+ </Sheet>+ );+}diff --git a/components/ui/form-hook.tsx b/components/ui/form-hook.tsxnew file mode 100644index 00000000..c03b0ac4--- /dev/null+++ b/components/ui/form-hook.tsx@@ -0,0 +1,181 @@+"use client";++import * as React from "react";++import * as LabelPrimitive from "@radix-ui/react-label";+import { Slot } from "@radix-ui/react-slot";+import {+ Controller,+ ControllerProps,+ FieldPath,+ FieldValues,+ FormProvider,+ useFormContext,+} from "react-hook-form";++import { cn } from "@/lib/utils";++import { Label } from "@/components/ui/label";++const Form = FormProvider;++type FormFieldContextValue<+ TFieldValues extends FieldValues = FieldValues,+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,+> = {+ name: TName;+};++const FormFieldContext = React.createContext<FormFieldContextValue>(+ {} as FormFieldContextValue,+);++const FormField = <+ TFieldValues extends FieldValues = FieldValues,+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,+>({+ ...props+}: ControllerProps<TFieldValues, TName>) => {+ return (+ <FormFieldContext.Provider value={{ name: props.name }}>+ <Controller {...props} />+ </FormFieldContext.Provider>+ );+};++const useFormField = () => {+ const fieldContext = React.useContext(FormFieldContext);+ const itemContext = React.useContext(FormItemContext);+ const { getFieldState, formState } = useFormContext();++ const fieldState = getFieldState(fieldContext.name, formState);++ if (!fieldContext) {+ throw new Error("useFormField should be used within <FormField>");+ }++ const { id } = itemContext;++ return {+ id,+ name: fieldContext.name,+ formItemId: `${id}-form-item`,+ formDescriptionId: `${id}-form-item-description`,+ formMessageId: `${id}-form-item-message`,+ ...fieldState,+ };+};++type FormItemContextValue = {+ id: string;+};++const FormItemContext = React.createContext<FormItemContextValue>(+ {} as FormItemContextValue,+);++const FormItem = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => {+ const id = React.useId();++ return (+ <FormItemContext.Provider value={{ id }}>+ <div ref={ref} className={cn("space-y-2", className)} {...props} />+ </FormItemContext.Provider>+ );+});+FormItem.displayName = "FormItem";++const FormLabel = React.forwardRef<+ React.ElementRef<typeof LabelPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>+>(({ className, ...props }, ref) => {+ const { error, formItemId } = useFormField();++ return (+ <Label+ ref={ref}+ className={cn(error && "text-destructive", className)}+ htmlFor={formItemId}+ {...props}+ />+ );+});+FormLabel.displayName = "FormLabel";++const FormControl = React.forwardRef<+ React.ElementRef<typeof Slot>,+ React.ComponentPropsWithoutRef<typeof Slot>+>(({ ...props }, ref) => {+ const { error, formItemId, formDescriptionId, formMessageId } =+ useFormField();++ return (+ <Slot+ ref={ref}+ id={formItemId}+ aria-describedby={+ !error+ ? `${formDescriptionId}`+ : `${formDescriptionId} ${formMessageId}`+ }+ aria-invalid={!!error}+ {...props}+ />+ );+});+FormControl.displayName = "FormControl";++const FormDescription = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, ...props }, ref) => {+ const { formDescriptionId } = useFormField();++ return (+ <p+ ref={ref}+ id={formDescriptionId}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+ );+});+FormDescription.displayName = "FormDescription";++const FormMessage = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, children, ...props }, ref) => {+ const { error, formMessageId } = useFormField();+ const body = error ? String(error?.message) : children;++ if (!body) {+ return null;+ }++ return (+ <p+ ref={ref}+ id={formMessageId}+ className={cn("text-sm font-medium text-destructive", className)}+ {...props}+ >+ {body}+ </p>+ );+});+FormMessage.displayName = "FormMessage";++export {+ useFormField,+ Form,+ FormItem,+ FormLabel,+ FormControl,+ FormDescription,+ FormMessage,+ FormField,+};diff --git a/components/ui/resizable.tsx b/components/ui/resizable.tsxnew file mode 100644index 00000000..765b840d--- /dev/null+++ b/components/ui/resizable.tsx@@ -0,0 +1,45 @@+"use client";++import { GripVertical } from "lucide-react";+import * as ResizablePrimitive from "react-resizable-panels";++import { cn } from "@/lib/utils";++const ResizablePanelGroup = ({+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (+ <ResizablePrimitive.PanelGroup+ className={cn(+ "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",+ className,+ )}+ {...props}+ />+);++const ResizablePanel = ResizablePrimitive.Panel;++const ResizableHandle = ({+ withHandle,+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {+ withHandle?: boolean;+}) => (+ <ResizablePrimitive.PanelResizeHandle+ className={cn(+ "relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",+ className,+ )}+ {...props}+ >+ {withHandle && (+ <div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">+ <GripVertical className="h-2.5 w-2.5" />+ </div>+ )}+ </ResizablePrimitive.PanelResizeHandle>+);++export { ResizablePanelGroup, ResizablePanel, ResizableHandle };diff --git a/components/ui/rich-text-editor.tsx b/components/ui/rich-text-editor.tsxnew file mode 100644index 00000000..8bc19ce5--- /dev/null+++ b/components/ui/rich-text-editor.tsx@@ -0,0 +1,246 @@+"use client";++import { useCallback } from "react";++import Image from "@tiptap/extension-image";+import Placeholder from "@tiptap/extension-placeholder";+import { EditorContent, useEditor } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import {+ Bold,+ ImageIcon,+ Italic,+ List,+ ListOrdered,+ Quote,+ Redo,+ Undo,+} from "lucide-react";++import { Button } from "@/components/ui/button";++interface RichTextEditorProps {+ content?: any;+ onChange?: (content: any) => void;+ placeholder?: string;+ onImageUpload?: (file: File) => Promise<string>;+}++export function RichTextEditor({+ content,+ onChange,+ placeholder = "Start typing...",+ onImageUpload,+}: RichTextEditorProps) {+ const editor = useEditor({+ extensions: [+ StarterKit,+ Image.configure({+ inline: true,+ allowBase64: true,+ HTMLAttributes: {+ class: "rounded-lg max-w-full h-auto",+ },+ }),+ Placeholder.configure({+ placeholder,+ }),+ ],+ content,+ immediatelyRender: false, // Fix SSR hydration issues+ onUpdate: ({ editor }) => {+ onChange?.(editor.getJSON());+ },+ editorProps: {+ handleDrop: (view, event, slice, moved) => {+ if (+ !moved &&+ event.dataTransfer &&+ event.dataTransfer.files &&+ event.dataTransfer.files[0]+ ) {+ const file = event.dataTransfer.files[0];++ // Check if it's an image file+ if (file.type.startsWith("image/") && onImageUpload) {+ event.preventDefault();++ // Upload the image+ onImageUpload(file)+ .then((url) => {+ const { state } = view;+ const { selection } = state;+ const position = selection.$cursor+ ? selection.$cursor.pos+ : selection.$to.pos;++ const node = state.schema.nodes.image.create({ src: url });+ const transaction = state.tr.insert(position, node);+ view.dispatch(transaction);+ })+ .catch((error) => {+ console.error("Failed to upload dropped image:", error);+ });++ return true;+ }+ }+ return false;+ },+ handlePaste: (view, event, slice) => {+ const items = event.clipboardData?.items;+ if (items && onImageUpload) {+ for (let i = 0; i < items.length; i++) {+ const item = items[i];+ if (item.type.startsWith("image/")) {+ event.preventDefault();++ const file = item.getAsFile();+ if (file) {+ onImageUpload(file)+ .then((url) => {+ const { state } = view;+ const { selection } = state;+ const position = selection.$cursor+ ? selection.$cursor.pos+ : selection.$to.pos;++ const node = state.schema.nodes.image.create({ src: url });+ const transaction = state.tr.insert(position, node);+ view.dispatch(transaction);+ })+ .catch((error) => {+ console.error("Failed to upload pasted image:", error);+ });+ }++ return true;+ }+ }+ }+ return false;+ },+ },+ });++ const addImage = useCallback(+ async (e?: React.MouseEvent) => {+ if (e) {+ e.preventDefault();+ e.stopPropagation();+ }++ if (!editor || !onImageUpload) return;++ const input = document.createElement("input");+ input.type = "file";+ input.accept = "image/*";+ input.onchange = async (e) => {+ const file = (e.target as HTMLInputElement).files?.[0];+ if (file) {+ try {+ const url = await onImageUpload(file);+ editor.chain().focus().setImage({ src: url }).run();+ } catch (error) {+ console.error("Failed to upload image:", error);+ }+ }+ };+ input.click();+ },+ [editor, onImageUpload],+ );++ if (!editor) {+ return null;+ }++ return (+ <div className="rounded-md border border-input">+ {/* Toolbar */}+ <div className="flex flex-wrap gap-1 border-b border-input p-2">+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().toggleBold().run()}+ className={editor.isActive("bold") ? "bg-muted" : ""}+ >+ <Bold className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().toggleItalic().run()}+ className={editor.isActive("italic") ? "bg-muted" : ""}+ >+ <Italic className="h-4 w-4" />+ </Button>+ <div className="mx-1 h-6 w-px bg-border" />+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().toggleBulletList().run()}+ className={editor.isActive("bulletList") ? "bg-muted" : ""}+ >+ <List className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().toggleOrderedList().run()}+ className={editor.isActive("orderedList") ? "bg-muted" : ""}+ >+ <ListOrdered className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().toggleBlockquote().run()}+ className={editor.isActive("blockquote") ? "bg-muted" : ""}+ >+ <Quote className="h-4 w-4" />+ </Button>+ {onImageUpload && (+ <>+ <div className="mx-1 h-6 w-px bg-border" />+ <Button variant="ghost" size="sm" onClick={addImage} type="button">+ <ImageIcon className="h-4 w-4" />+ </Button>+ </>+ )}+ <div className="mx-1 h-6 w-px bg-border" />+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().undo().run()}+ disabled={!editor.can().undo()}+ >+ <Undo className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ type="button"+ onClick={() => editor.chain().focus().redo().run()}+ disabled={!editor.can().redo()}+ >+ <Redo className="h-4 w-4" />+ </Button>+ </div>++ {/* Editor */}+ <div className="min-h-[200px] p-3">+ <EditorContent+ editor={editor}+ className="prose prose-sm max-w-none focus:outline-none [&_.ProseMirror]:min-h-[150px] [&_.ProseMirror]:focus:outline-none"+ />+ </div>+ </div>+ );+}diff --git a/components/view/annotations/annotation-panel.tsx b/components/view/annotations/annotation-panel.tsxnew file mode 100644index 00000000..bcc59200--- /dev/null+++ b/components/view/annotations/annotation-panel.tsx@@ -0,0 +1,280 @@+"use client";++import { useMemo, useState } from "react";++import { Brand, DataroomBrand } from "@prisma/client";+import { ChevronDown, ChevronRight } from "lucide-react";++import { useViewerAnnotations } from "@/lib/swr/use-annotations";+import { determineTextColor } from "@/lib/utils/determine-text-color";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable";+import { ScrollArea } from "@/components/ui/scroll-area";++interface AnnotationPanelProps {+ brand?: Partial<Brand> | Partial<DataroomBrand> | null;+ linkId: string;+ documentId?: string;+ viewId?: string;+ currentPage: number;+ isVisible: boolean;+ onResize?: (size: number) => void;+}++export function AnnotationPanel({+ brand,+ linkId,+ documentId,+ viewId,+ currentPage,+ isVisible,+ onResize,+}: AnnotationPanelProps) {+ const { annotations, loading } = useViewerAnnotations(+ linkId,+ documentId,+ viewId,+ );+ const [expandedAnnotations, setExpandedAnnotations] = useState<Set<string>>(+ new Set(),+ );++ // Filter annotations for current page+ const currentPageAnnotations = useMemo(() => {+ if (!annotations) return [];+ return annotations.filter((annotation) =>+ annotation.pages.includes(currentPage),+ );+ }, [annotations, currentPage]);++ const toggleAnnotation = (annotationId: string) => {+ const newExpanded = new Set(expandedAnnotations);+ if (newExpanded.has(annotationId)) {+ newExpanded.delete(annotationId);+ } else {+ newExpanded.add(annotationId);+ }+ setExpandedAnnotations(newExpanded);+ };++ const renderContent = (content: any) => {+ if (!content) return null;++ // Properly render Tiptap JSON content+ if (typeof content === "object" && content.content) {+ return (+ <div className="prose prose-sm max-w-none text-gray-700">+ {content.content.map((node: any, index: number) => {+ if (node.type === "paragraph") {+ return (+ <p+ key={index}+ className="mb-2 text-sm leading-relaxed text-gray-700"+ >+ {node.content?.map((textNode: any, textIndex: number) => {+ if (textNode.type === "text") {+ let text = textNode.text;+ // Apply formatting if marks exist+ if (textNode.marks) {+ textNode.marks.forEach((mark: any) => {+ if (mark.type === "bold") {+ text = (+ <strong key={textIndex} className="font-semibold">+ {text}+ </strong>+ );+ } else if (mark.type === "italic") {+ text = (+ <em key={textIndex} className="italic">+ {text}+ </em>+ );+ }+ });+ }+ return text;+ } else if (textNode.type === "image") {+ return (+ <img+ key={textIndex}+ src={textNode.attrs?.src}+ alt={textNode.attrs?.alt || ""}+ className="my-2 h-auto max-w-full rounded-md"+ />+ );+ }+ return null;+ })}+ </p>+ );+ } else if (node.type === "bulletList") {+ return (+ <ul+ key={index}+ className="mb-2 list-inside list-disc text-sm text-gray-700"+ >+ {node.content?.map((listItem: any, listIndex: number) => (+ <li key={listIndex} className="mb-1">+ {listItem.content?.[0]?.content?.[0]?.text}+ </li>+ ))}+ </ul>+ );+ } else if (node.type === "orderedList") {+ return (+ <ol+ key={index}+ className="mb-2 list-inside list-decimal text-sm text-gray-700"+ >+ {node.content?.map((listItem: any, listIndex: number) => (+ <li key={listIndex} className="mb-1">+ {listItem.content?.[0]?.content?.[0]?.text}+ </li>+ ))}+ </ol>+ );+ } else if (node.type === "blockquote") {+ return (+ <blockquote+ key={index}+ className="mb-2 border-l-2 border-gray-300 pl-3 text-sm italic text-gray-600"+ >+ {node.content?.[0]?.content?.[0]?.text}+ </blockquote>+ );+ } else if (node.type === "image") {+ return (+ <img+ key={index}+ src={node.attrs?.src}+ alt={node.attrs?.alt || ""}+ className="my-2 h-auto max-w-full rounded-md"+ />+ );+ }+ return null;+ })}+ </div>+ );+ }++ return <p className="text-sm text-gray-500">No content</p>;+ };++ if (!isVisible) return null;++ return (+ <div className="h-full w-full bg-transparent">+ <ScrollArea className="h-full">+ <div className="space-y-3 p-4">+ {loading ? (+ <div className="flex items-center justify-center py-6">+ <div+ className="text-xs opacity-70"+ style={{ color: determineTextColor(brand?.accentColor) }}+ >+ Loading annotations...+ </div>+ </div>+ ) : currentPageAnnotations.length === 0 ? (+ <div className="flex flex-col items-center justify-center py-6 text-center">+ <p+ className="mb-1 text-xs opacity-70"+ style={{ color: determineTextColor(brand?.accentColor) }}+ >+ No annotations on this page+ </p>+ </div>+ ) : (+ currentPageAnnotations.map((annotation) => (+ <div+ key={annotation.id}+ className="rounded-lg border border-gray-300/50 bg-white/95 shadow-sm backdrop-blur-sm transition-all hover:border-gray-400/60 hover:bg-white"+ >+ <Collapsible+ open={expandedAnnotations.has(annotation.id)}+ onOpenChange={() => toggleAnnotation(annotation.id)}+ >+ <CollapsibleTrigger asChild>+ <div className="w-full cursor-pointer">+ <div className="flex w-full items-center justify-between p-3">+ <div className="min-w-0 flex-1">+ <h4 className="truncate text-sm font-medium text-gray-800">+ {annotation.title}+ </h4>+ <p className="mt-1 text-xs text-gray-500">+ Page{annotation.pages.length > 1 ? "s" : ""}{" "}+ {annotation.pages.join(", ")}+ </p>+ </div>+ <button+ className="ml-2 shrink-0 rounded-md p-1 transition-colors hover:bg-gray-100"+ onClick={(e) => {+ e.stopPropagation();+ toggleAnnotation(annotation.id);+ }}+ >+ {expandedAnnotations.has(annotation.id) ? (+ <ChevronDown className="h-4 w-4 text-gray-600" />+ ) : (+ <ChevronRight className="h-4 w-4 text-gray-600" />+ )}+ </button>+ </div>+ </div>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="border-t border-gray-200 px-3 pb-3 pt-3">+ <div className="text-sm text-gray-700">+ {renderContent(annotation.content)}+ </div>++ {annotation.images && annotation.images.length > 0 && (+ <div+ className="mt-3 grid gap-2"+ style={{+ gridTemplateColumns:+ annotation.images.length === 1+ ? "1fr"+ : annotation.images.length === 2+ ? "repeat(2, 1fr)"+ : "repeat(auto-fit, minmax(120px, 1fr))",+ }}+ >+ {annotation.images.map((image) => (+ <div+ key={image.id}+ className="overflow-hidden rounded-md border border-gray-200"+ >+ <img+ src={image.url}+ alt={image.filename}+ className="h-auto max-h-32 w-full object-contain"+ loading="lazy"+ />+ </div>+ ))}+ </div>+ )}+ </div>+ </CollapsibleContent>+ </Collapsible>+ </div>+ ))+ )}+ </div>+ </ScrollArea>+ </div>+ );+}diff --git a/components/view/annotations/annotation-toggle.tsx b/components/view/annotations/annotation-toggle.tsxnew file mode 100644index 00000000..be93936f--- /dev/null+++ b/components/view/annotations/annotation-toggle.tsx@@ -0,0 +1,56 @@+"use client";++import { MessageSquare, MessageSquareOff } from "lucide-react";++import { Button } from "@/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";++interface AnnotationToggleProps {+ enabled: boolean;+ onToggle: (enabled: boolean) => void;+ hasAnnotations?: boolean;+}++export function AnnotationToggle({+ enabled,+ onToggle,+ hasAnnotations = false,+}: AnnotationToggleProps) {+ return (+ <TooltipProvider delayDuration={100}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onToggle(!enabled)}+ className={`${+ enabled ? "bg-muted text-foreground" : "text-muted-foreground"+ } ${!hasAnnotations ? "cursor-not-allowed opacity-50" : ""}`}+ disabled={!hasAnnotations}+ >+ {enabled ? (+ <MessageSquare className="h-4 w-4" />+ ) : (+ <MessageSquareOff className="h-4 w-4" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {!hasAnnotations+ ? "No annotations available"+ : enabled+ ? "Hide annotations"+ : "Show annotations"}+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 8ef61a0d..73a84cd9 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -65,6 +65,7 @@ export default function DocumentView({useCustomAccessForm,logoOnAccessForm,isEmbedded,+ annotationsEnabled,}: {link: LinkWithDocument;userEmail: string | null | undefined;@@ -86,6 +87,7 @@ export default function DocumentView({useCustomAccessForm?: boolean;isEmbedded?: boolean;logoOnAccessForm?: boolean;+ annotationsEnabled?: boolean;}) {useDisablePrint();const {@@ -299,6 +301,7 @@ export default function DocumentView({showAccountCreationSlide={showAccountCreationSlide}useAdvancedExcelViewer={useAdvancedExcelViewer}viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}+ annotationsEnabled={annotationsEnabled}/>) : (<div className="flex h-screen items-center justify-center">diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex 0c69e735..ac51cff0 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -43,6 +43,7 @@ import {BreadcrumbSeparator,} from "../ui/breadcrumb";import { Button } from "../ui/button";+import { AnnotationToggle } from "./annotations/annotation-toggle";import { ConversationSidebar } from "./conversations/sidebar";import ReportForm from "./report-form";@@ -60,6 +61,10 @@ export type TNavData = {conversationsEnabled?: boolean;assistantEnabled?: boolean;isTeamMember?: boolean;+ annotationsEnabled?: boolean;+ hasAnnotations?: boolean;+ annotationsFeatureEnabled?: boolean;+ onToggleAnnotations?: (enabled: boolean) => void;};export default function Nav({@@ -99,6 +104,10 @@ export default function Nav({conversationsEnabled,assistantEnabled,isTeamMember,+ annotationsEnabled,+ hasAnnotations,+ annotationsFeatureEnabled,+ onToggleAnnotations,} = navData;const [showConversations, setShowConversations] = useState(false);@@ -298,6 +307,14 @@ export default function Nav({View FAQ</Button>)}+ {/* Annotations toggle button */}+ {onToggleAnnotations && annotationsFeatureEnabled && (+ <AnnotationToggle+ enabled={annotationsEnabled || false}+ onToggle={onToggleAnnotations}+ hasAnnotations={hasAnnotations}+ />+ )}{embeddedLinks && embeddedLinks.length > 0 ? (<DropdownMenu><DropdownMenuTrigger>diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex 60eb3e99..a972629b 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -58,6 +58,7 @@ export default function ViewData({viewerEmail,dataroomId,canDownload,+ annotationsEnabled,}: {viewData: DEFAULT_DOCUMENT_VIEW_TYPE | DEFAULT_DATAROOM_DOCUMENT_VIEW_TYPE;link: LinkWithDocument | LinkWithDataroomDocument;@@ -74,6 +75,7 @@ export default function ViewData({viewerEmail?: string;dataroomId?: string;canDownload?: boolean;+ annotationsEnabled?: boolean;}) {const { isMobile } = useMediaQuery();@@ -97,6 +99,7 @@ export default function ViewData({document.downloadOnly ||isDownloadAllowed(canDownload, link.allowDownload ?? false),isTeamMember: viewData.isTeamMember,+ annotationsFeatureEnabled: annotationsEnabled,};// Calculate allowDownload once for all componentsdiff --git a/components/view/viewer/pages-horizontal-viewer.tsx b/components/view/viewer/pages-horizontal-viewer.tsxindex cd5c2983..3fde0dcb 100644--- a/components/view/viewer/pages-horizontal-viewer.tsx+++ b/components/view/viewer/pages-horizontal-viewer.tsx@@ -5,13 +5,22 @@ import React from "react";import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";import { useSession } from "next-auth/react";+import useSWR from "swr";+import { useViewerAnnotations } from "@/lib/swr/use-annotations";import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";-import { cn } from "@/lib/utils";+import { cn, fetcher } from "@/lib/utils";++import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable";import { ScreenProtector } from "../ScreenProtection";+import { AnnotationPanel } from "../annotations/annotation-panel";import Nav, { TNavData } from "../nav";import { PoweredBy } from "../powered-by";import Question from "../question";@@ -93,6 +102,11 @@ export default function PagesHorizontalViewer({const [submittedFeedback, setSubmittedFeedback] = useState<boolean>(false);const [accountCreated, setAccountCreated] = useState<boolean>(false);+ const [annotationsEnabled, setAnnotationsEnabled] = useState(false);++ // Fetch annotations for this link+ const { annotations } = useViewerAnnotations(linkId, documentId, viewId);+ const hasAnnotations = annotations && annotations.length > 0;const [scale, setScale] = useState<number>(1);const initialViewedPages = Array.from({ length: numPages }, (_, index) => ({@@ -563,6 +577,17 @@ export default function PagesHorizontalViewer({return () => window.removeEventListener("keydown", handleKeyDown);}, [containerRef.current, pageNumber, imageDimensions]);+ const handleToggleAnnotations = (enabled: boolean) => {+ setAnnotationsEnabled(enabled);+ };++ const navDataWithAnnotations = {+ ...navData,+ annotationsEnabled,+ hasAnnotations,+ onToggleAnnotations: handleToggleAnnotations,+ };+return (<><Nav@@ -572,267 +597,304 @@ export default function PagesHorizontalViewer({hasWatermark={!!watermarkConfig}handleZoomIn={handleZoomIn}handleZoomOut={handleZoomOut}- navData={navData}+ navData={navDataWithAnnotations}/><divstyle={{ height: "calc(100dvh - 64px)" }}- className={cn("relative flex items-center overflow-hidden")}+ className="relative overflow-hidden">- <div- className={cn(- "relative h-full w-full",- !isWindowFocused &&- screenshotProtectionEnabled &&- "blur-xl transition-all duration-300",- )}- ref={containerRef}- >- <div className={cn("h-full w-full", scale > 1 && "overflow-auto")}>- <div- className="flex min-h-full w-full items-center justify-center"- style={{- transform: `scale(${scale})`,- transition: "transform 0.2s ease-out",- transformOrigin: scale <= 1 ? "center center" : "left top",- minWidth: scale > 1 ? `${100 * scale}%` : "100%",- }}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- >- {pageNumber <= numPagesWithAccountCreation &&- pages &&- loadedImages[pageNumber - 1]- ? pages.map((page, index) => (- <div- key={index}- className={cn(- "viewer-container relative mx-auto w-full",- pageNumber - 1 === index- ? "flex justify-center"- : "hidden",- )}- >- <img- className={cn(- "viewer-image-mobile !pointer-events-auto max-h-[calc(100dvh-64px)] object-contain",- )}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- ref={(ref) => {- imageRefs.current[index] = ref;- if (ref) {- ref.onload = () =>- setImageDimensions((prev) => ({- ...prev,- [index]: {- width: ref.clientWidth,- height: ref.clientHeight,- },- }));- }- }}- useMap={`#page-map-${index + 1}`}- src={- loadedImages[index]- ? page.file- : "https://www.papermark.com/_static/blank.gif"- }- alt={`Page ${index + 1}`}- />-- {/* Add Watermark Component */}- {watermarkConfig ? (- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,- }}- documentDimensions={- imageDimensions[index] || {- width: 0,- height: 0,- }- }- pageIndex={index}- />- ) : null}-- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.endsWith(".gif"))- .map((link, index) => (- <area- key={index}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )}- href={link.href}- onClick={(e) => handleLinkClick(link.href, e)}- target={- link.href.startsWith("#") ? "_self" : "_blank"+ <ResizablePanelGroup direction="horizontal">+ {/* Document Content */}+ <ResizablePanel+ defaultSize={annotationsEnabled && hasAnnotations ? 75 : 100}+ >+ <div className="flex h-full w-full items-center">+ <div+ className={cn(+ "relative h-full w-full",+ !isWindowFocused &&+ screenshotProtectionEnabled &&+ "blur-xl transition-all duration-300",+ )}+ ref={containerRef}+ >+ <div+ className={cn("h-full w-full", scale > 1 && "overflow-auto")}+ >+ <div+ className="flex min-h-full w-full items-center justify-center"+ style={{+ transform: `scale(${scale})`,+ transition: "transform 0.2s ease-out",+ transformOrigin:+ scale <= 1 ? "center center" : "left top",+ minWidth: scale > 1 ? `${100 * scale}%` : "100%",+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ >+ {pageNumber <= numPagesWithAccountCreation &&+ pages &&+ loadedImages[pageNumber - 1]+ ? pages.map((page, index) => (+ <div+ key={index}+ className={cn(+ "viewer-container relative mx-auto w-full",+ pageNumber - 1 === index+ ? "flex justify-center"+ : "hidden",+ )}+ >+ <img+ className={cn(+ "viewer-image-mobile !pointer-events-auto max-h-[calc(100dvh-64px)] object-contain",+ )}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ ref={(ref) => {+ imageRefs.current[index] = ref;+ if (ref) {+ ref.onload = () =>+ setImageDimensions((prev) => ({+ ...prev,+ [index]: {+ width: ref.clientWidth,+ height: ref.clientHeight,+ },+ }));}- rel={- link.href.startsWith("#")- ? undefined- : "noopener noreferrer"+ }}+ useMap={`#page-map-${index + 1}`}+ src={+ loadedImages[index]+ ? page.file+ : "https://www.papermark.com/_static/blank.gif"+ }+ alt={`Page ${index + 1}`}+ />++ {/* Add Watermark Component */}+ {watermarkConfig ? (+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress: ipAddress,+ }}+ documentDimensions={+ imageDimensions[index] || {+ width: 0,+ height: 0,+ }}+ pageIndex={index}/>- ))}- </map>- ) : null}-- {/** Automatically Render Overlays **/}- {page.pageLinks- ? page.pageLinks- .filter((link) => link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href} // Assuming the href points to a GIF or overlay image- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none", // To ensure the overlay doesn't interfere with interaction- }}- />- );- })- : null}- </div>- ))- : null}-- {enableQuestion &&- feedback &&- pageNumber === numPagesWithFeedback ? (+ ) : null}++ {page.pageLinks ? (+ <map name={`page-map-${index + 1}`}>+ {page.pageLinks+ .filter((link) => !link.href.endsWith(".gif"))+ .map((link, index) => (+ <area+ key={index}+ shape="rect"+ coords={scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor:+ page.metadata.scaleFactor,+ }),+ )}+ href={link.href}+ onClick={(e) =>+ handleLinkClick(link.href, e)+ }+ target={+ link.href.startsWith("#")+ ? "_self"+ : "_blank"+ }+ rel={+ link.href.startsWith("#")+ ? undefined+ : "noopener noreferrer"+ }+ />+ ))}+ </map>+ ) : null}++ {/** Automatically Render Overlays **/}+ {page.pageLinks+ ? page.pageLinks+ .filter((link) => link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const [x1, y1, x2, y2] = scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ }),+ )+ .split(",")+ .map(Number);++ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;++ return (+ <img+ key={`overlay-${index}-${linkIndex}`}+ src={link.href} // Assuming the href points to a GIF or overlay image+ alt={`Overlay ${index + 1}`}+ style={{+ position: "absolute",+ top: y1,+ left: x1,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ pointerEvents: "none", // To ensure the overlay doesn't interfere with interaction+ }}+ />+ );+ })+ : null}+ </div>+ ))+ : null}++ {enableQuestion &&+ feedback &&+ pageNumber === numPagesWithFeedback ? (+ <div+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}+ >+ <Question+ accentColor={brand?.accentColor}+ feedback={feedback}+ viewId={viewId}+ submittedFeedback={submittedFeedback}+ setSubmittedFeedback={setSubmittedFeedback}+ isPreview={isPreview}+ />+ </div>+ ) : null}++ {showStatsSlideWithAccountCreation &&+ pageNumber === numPagesWithAccountCreation ? (+ <div+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}+ >+ <ViewDurationSummary+ linkId={linkId}+ viewedPages={viewedPages}+ viewerEmail={viewerEmail}+ accountCreated={accountCreated}+ setAccountCreated={setAccountCreated}+ />+ </div>+ ) : null}+ </div>+ </div>+ </div>++ {/* Navigation arrows with hover zones */}+ {pageNumber > 1 && (<div- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}+ className={cn(+ "group absolute left-0 top-0 z-[1] flex h-full items-center",+ isMobile ? "w-1/6" : "w-32",+ isMobile ? "justify-start pl-1" : "justify-start pl-4",+ )}+ onClick={isMobile ? goToPreviousPage : undefined}>- <Question- accentColor={brand?.accentColor}- feedback={feedback}- viewId={viewId}- submittedFeedback={submittedFeedback}- setSubmittedFeedback={setSubmittedFeedback}- isPreview={isPreview}- />+ <button+ onClick={!isMobile ? goToPreviousPage : undefined}+ className={cn(+ "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",+ "opacity-50 group-hover:opacity-100",+ )}+ >+ <ChevronLeftIcon+ className={cn("size-10 text-white", isMobile && "size-8")}+ />+ </button></div>- ) : null}+ )}- {showStatsSlideWithAccountCreation &&- pageNumber === numPagesWithAccountCreation ? (+ {pageNumber < numPagesWithAccountCreation && (<div- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}+ className={cn(+ "group absolute right-0 top-0 z-[1] flex h-full items-center",+ isMobile ? "w-1/6" : "w-32",+ isMobile ? "justify-end pr-1" : "justify-end pr-4",+ )}+ onClick={isMobile ? goToNextPage : undefined}>- <ViewDurationSummary- linkId={linkId}- viewedPages={viewedPages}- viewerEmail={viewerEmail}- accountCreated={accountCreated}- setAccountCreated={setAccountCreated}- />+ <button+ onClick={!isMobile ? goToNextPage : undefined}+ className={cn(+ "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",+ "opacity-50 group-hover:opacity-100",+ )}+ >+ <ChevronRightIcon+ className={cn("size-10 text-white", isMobile && "size-8")}+ />+ </button></div>- ) : null}- </div>- </div>- </div>-- {/* Navigation arrows with hover zones */}- {pageNumber > 1 && (- <div- className={cn(- "group absolute left-0 top-0 z-[1] flex h-full items-center",- isMobile ? "w-1/6" : "w-32",- isMobile ? "justify-start pl-1" : "justify-start pl-4",- )}- onClick={isMobile ? goToPreviousPage : undefined}- >- <button- onClick={!isMobile ? goToPreviousPage : undefined}- className={cn(- "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",- "opacity-50 group-hover:opacity-100",)}- >- <ChevronLeftIcon- className={cn("size-10 text-white", isMobile && "size-8")}++ {feedbackEnabled && pageNumber <= numPages ? (+ <Toolbar+ viewId={viewId}+ pageNumber={pageNumber}+ isPreview={isPreview}+ />+ ) : null}++ {screenshotProtectionEnabled ? <ScreenProtector /> : null}+ {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={getTrackingOptions().inactivityThreshold}+ onDismiss={updateActivity}/>- </button>- </div>- )}-- {pageNumber < numPagesWithAccountCreation && (- <div- className={cn(- "group absolute right-0 top-0 z-[1] flex h-full items-center",- isMobile ? "w-1/6" : "w-32",- isMobile ? "justify-end pr-1" : "justify-end pr-4",+ </div>+ {/* </div> */}+ </ResizablePanel>++ {/* Annotation Panel - Right Side */}+ {navData.annotationsFeatureEnabled &&+ annotationsEnabled &&+ hasAnnotations && (+ <>+ <ResizableHandle className="w-1 bg-transparent transition-colors hover:bg-white/20" />+ <ResizablePanel defaultSize={25} minSize={20} maxSize={40}>+ <AnnotationPanel+ brand={brand}+ linkId={linkId}+ documentId={documentId}+ viewId={viewId}+ currentPage={pageNumber}+ isVisible={true}+ />+ </ResizablePanel>+ </>)}- onClick={isMobile ? goToNextPage : undefined}- >- <button- onClick={!isMobile ? goToNextPage : undefined}- className={cn(- "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",- "opacity-50 group-hover:opacity-100",- )}- >- <ChevronRightIcon- className={cn("size-10 text-white", isMobile && "size-8")}- />- </button>- </div>- )}-- {feedbackEnabled && pageNumber <= numPages ? (- <Toolbar- viewId={viewId}- pageNumber={pageNumber}- isPreview={isPreview}- />- ) : null}-- {screenshotProtectionEnabled ? <ScreenProtector /> : null}- {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}- <AwayPoster- isVisible={isInactive}- inactivityThreshold={getTrackingOptions().inactivityThreshold}- onDismiss={updateActivity}- />+ </ResizablePanelGroup></div></>);diff --git a/components/view/viewer/pages-vertical-viewer.tsx b/components/view/viewer/pages-vertical-viewer.tsxindex e453f199..473dfbf5 100644--- a/components/view/viewer/pages-vertical-viewer.tsx+++ b/components/view/viewer/pages-vertical-viewer.tsx@@ -5,13 +5,21 @@ import React from "react";import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";+import { useViewerAnnotations } from "@/lib/swr/use-annotations";import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";import { cn } from "@/lib/utils";import { useMediaQuery } from "@/lib/utils/use-media-query";+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable";+import { ScreenProtector } from "../ScreenProtection";+import { AnnotationPanel } from "../annotations/annotation-panel";import Nav, { TNavData } from "../nav";import { PoweredBy } from "../powered-by";import Question from "../question";@@ -109,6 +117,11 @@ export default function PagesVerticalViewer({const [submittedFeedback, setSubmittedFeedback] = useState<boolean>(false);const [accountCreated, setAccountCreated] = useState<boolean>(false);const [scale, setScale] = useState<number>(1);+ const [annotationsEnabled, setAnnotationsEnabled] = useState(false);++ // Fetch annotations for this link+ const { annotations } = useViewerAnnotations(linkId, documentId, viewId);+ const hasAnnotations = annotations && annotations.length > 0;const initialViewedPages = Array.from({ length: numPages }, (_, index) => ({pageNumber: index + 1,@@ -736,6 +749,17 @@ export default function PagesVerticalViewer({return () => window.removeEventListener("keydown", handleKeyDown);}, []);+ const handleToggleAnnotations = (enabled: boolean) => {+ setAnnotationsEnabled(enabled);+ };++ const navDataWithAnnotations = {+ ...navData,+ annotationsEnabled,+ hasAnnotations,+ onToggleAnnotations: handleToggleAnnotations,+ };+return (<><Nav@@ -745,273 +769,305 @@ export default function PagesVerticalViewer({hasWatermark={watermarkConfig ? true : false}handleZoomIn={handleZoomIn}handleZoomOut={handleZoomOut}- navData={navData}+ navData={navDataWithAnnotations}/><divstyle={{ height: "calc(100dvh - 64px)" }}- className={cn("relative h-dvh overflow-hidden")}+ className="relative overflow-hidden">- <div- className={cn(- "h-full w-full",- "overflow-auto scroll-smooth",- !isWindowFocused &&- screenshotProtectionEnabled &&- "blur-xl transition-all duration-300",- )}- ref={containerRef}- >- <div className="flex min-h-full min-w-full justify-center">- <div className="flex w-full max-w-[1400px] justify-center">- <div- className="transform-container w-full"- style={{- transform: `scale(${scale})`,- transition: "transform 0.2s ease-out",- transformOrigin: scale <= 1 ? "center top" : "left top",- }}- >- <div- className="flex flex-col items-center gap-2"- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- >- {pages.map((page, index) =>- loadedImages[index] ? (- <div- key={index}- className="relative w-full px-4 md:px-8"- style={{- width: containerWidth- ? `${calculateOptimalWidth(containerWidth, page.metadata, isMobile, isTablet)}px`- : undefined,- }}- >- <div className="viewer-container relative border-b border-t border-gray-100">- <div- className="pointer-events-none absolute bottom-0 left-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to top, #f3f4f6, transparent)",- }}- />- <div- className="pointer-events-none absolute bottom-0 right-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to top, #f3f4f6, transparent)",- }}- />- <div- className="pointer-events-none absolute left-0 top-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to bottom, #f3f4f6, transparent)",- }}- />+ <ResizablePanelGroup direction="horizontal">+ {/* Document Content */}+ <ResizablePanel+ defaultSize={annotationsEnabled && hasAnnotations ? 75 : 100}+ >+ <div+ className={cn(+ "h-full w-full",+ "overflow-auto scroll-smooth",+ !isWindowFocused &&+ screenshotProtectionEnabled &&+ "blur-xl transition-all duration-300",+ )}+ ref={containerRef}+ >+ <div className="flex min-h-full min-w-full justify-center">+ <div className="flex w-full max-w-[1400px] justify-center">+ <div+ className="transform-container w-full"+ style={{+ transform: `scale(${scale})`,+ transition: "transform 0.2s ease-out",+ transformOrigin: scale <= 1 ? "center top" : "left top",+ }}+ >+ <div+ className="flex flex-col items-center gap-2"+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ >+ {pages.map((page, index) =>+ loadedImages[index] ? (<div- className="pointer-events-none absolute right-0 top-0 w-px"+ key={index}+ className="relative w-full px-4 md:px-8"style={{- height: "10%",- background:- "linear-gradient(to bottom, #f3f4f6, transparent)",- }}- />- <img- className="viewer-image-mobile h-auto w-full object-contain"- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();+ width: containerWidth+ ? `${calculateOptimalWidth(containerWidth, page.metadata, isMobile, isTablet)}px`+ : undefined,}}- ref={(ref) => {- imageRefs.current[index] = ref;- if (ref) {- ref.onload = () =>- setImageDimensions((prev) => ({- ...prev,- [index]: {- width: ref.clientWidth,- height: ref.clientHeight,- },- }));- }- }}- useMap={`#page-map-${index + 1}`}- src={- loadedImages[index]- ? page.file- : "https://www.papermark.com/_static/blank.gif"- }- alt={`Page ${index + 1}`}- />-- {watermarkConfig && imageDimensions[index] ? (- <div className="absolute left-0 top-0">- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,+ >+ <div className="viewer-container relative border-b border-t border-gray-100">+ <div+ className="pointer-events-none absolute bottom-0 left-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to top, #f3f4f6, transparent)",}}- documentDimensions={imageDimensions[index]}- pageIndex={index}/>- </div>- ) : null}- </div>-- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.endsWith(".gif"))- .map((link, linkIndex) => (- <area- key={linkIndex}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )}- href={link.href}- onClick={(e) => handleLinkClick(link.href, e)}- target={- link.href.startsWith("#")- ? "_self"- : "_blank"- }- rel={- link.href.startsWith("#")- ? undefined- : "noopener noreferrer"+ <div+ className="pointer-events-none absolute bottom-0 right-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to top, #f3f4f6, transparent)",+ }}+ />+ <div+ className="pointer-events-none absolute left-0 top-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to bottom, #f3f4f6, transparent)",+ }}+ />+ <div+ className="pointer-events-none absolute right-0 top-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to bottom, #f3f4f6, transparent)",+ }}+ />+ <img+ className="viewer-image-mobile h-auto w-full object-contain"+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ ref={(ref) => {+ imageRefs.current[index] = ref;+ if (ref) {+ ref.onload = () =>+ setImageDimensions((prev) => ({+ ...prev,+ [index]: {+ width: ref.clientWidth,+ height: ref.clientHeight,+ },+ }));}- />- ))}- </map>- ) : null}-- {page.pageLinks- ? page.pageLinks- .filter((link) => link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href}- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none",+ }}+ useMap={`#page-map-${index + 1}`}+ src={+ loadedImages[index]+ ? page.file+ : "https://www.papermark.com/_static/blank.gif"+ }+ alt={`Page ${index + 1}`}+ />++ {watermarkConfig && imageDimensions[index] ? (+ <div className="absolute left-0 top-0">+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress: ipAddress,}}+ documentDimensions={imageDimensions[index]}+ pageIndex={index}/>- );- })- : null}- </div>- ) : null,- )}-- {enableQuestion &&- feedback &&- pageNumber >= numPagesWithFeedback - 1 && (- <div- id="feedback-question"- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}- >- <Question- accentColor={brand?.accentColor}- feedback={feedback}- viewId={viewId}- submittedFeedback={submittedFeedback}- setSubmittedFeedback={setSubmittedFeedback}- isPreview={isPreview}- />- </div>- )}+ </div>+ ) : null}+ </div>++ {page.pageLinks ? (+ <map name={`page-map-${index + 1}`}>+ {page.pageLinks+ .filter((link) => !link.href.endsWith(".gif"))+ .map((link, linkIndex) => (+ <area+ key={linkIndex}+ shape="rect"+ coords={scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor:+ page.metadata.scaleFactor,+ }),+ )}+ href={link.href}+ onClick={(e) =>+ handleLinkClick(link.href, e)+ }+ target={+ link.href.startsWith("#")+ ? "_self"+ : "_blank"+ }+ rel={+ link.href.startsWith("#")+ ? undefined+ : "noopener noreferrer"+ }+ />+ ))}+ </map>+ ) : null}++ {page.pageLinks+ ? page.pageLinks+ .filter((link) => link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const [x1, y1, x2, y2] = scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ }),+ )+ .split(",")+ .map(Number);++ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;++ return (+ <img+ key={`overlay-${index}-${linkIndex}`}+ src={link.href}+ alt={`Overlay ${index + 1}`}+ style={{+ position: "absolute",+ top: y1,+ left: x1,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ pointerEvents: "none",+ }}+ />+ );+ })+ : null}+ </div>+ ) : null,+ )}++ {enableQuestion &&+ feedback &&+ pageNumber >= numPagesWithFeedback - 1 && (+ <div+ id="feedback-question"+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}+ >+ <Question+ accentColor={brand?.accentColor}+ feedback={feedback}+ viewId={viewId}+ submittedFeedback={submittedFeedback}+ setSubmittedFeedback={setSubmittedFeedback}+ isPreview={isPreview}+ />+ </div>+ )}+ </div>+ </div></div></div></div>- </div>- </div>- {/* Up arrow - hide on first page */}- <div- className={cn(- "absolute left-0 right-0 top-0 flex h-24 items-start justify-center pt-4 transition-opacity duration-200",- pageNumber <= 1 ? "hidden" : "opacity-0 hover:opacity-100",- )}- onClick={goToPreviousPage}- >- <button- disabled={pageNumber <= 1}- className="rounded-full bg-gray-950/50 p-1 hover:bg-gray-950/75"- >- <ChevronUpIcon className="h-10 w-10 text-white" />- </button>- </div>-- {/* Down arrow - hide on last page unless there's an account creation page */}- <div- className={cn(- "absolute bottom-0 left-0 right-0 flex h-24 items-end justify-center pb-4 transition-opacity duration-200",- pageNumber >= numPagesWithAccountCreation- ? "hidden"- : "opacity-0 hover:opacity-100",- )}- onClick={goToNextPage}- >- <button- disabled={pageNumber >= numPagesWithAccountCreation}- className="rounded-full bg-gray-950/50 p-1 hover:bg-gray-950/75"- >- <ChevronDownIcon className="h-10 w-10 text-white" />- </button>- </div>-- {feedbackEnabled && pageNumber <= numPages ? (- <Toolbar- viewId={viewId}- pageNumber={pageNumber}- isPreview={isPreview}- />- ) : null}-- {screenshotProtectionEnabled ? <ScreenProtector /> : null}- {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}- <AwayPoster- isVisible={isInactive}- inactivityThreshold={- getTrackingOptions().inactivityThreshold || 20000- }- onDismiss={updateActivity}- />++ {/* Up arrow - hide on first page */}+ <div+ className={cn(+ "absolute left-0 right-0 top-0 flex h-24 items-start justify-center pt-4 transition-opacity duration-200",+ pageNumber <= 1 ? "hidden" : "opacity-0 hover:opacity-100",+ )}+ onClick={goToPreviousPage}+ >+ <button+ disabled={pageNumber <= 1}+ className="rounded-full bg-gray-950/50 p-1 hover:bg-gray-950/75"+ >+ <ChevronUpIcon className="h-10 w-10 text-white" />+ </button>+ </div>++ {/* Down arrow - hide on last page unless there's an account creation page */}+ <div+ className={cn(+ "absolute bottom-0 left-0 right-0 flex h-24 items-end justify-center pb-4 transition-opacity duration-200",+ pageNumber >= numPagesWithAccountCreation+ ? "hidden"+ : "opacity-0 hover:opacity-100",+ )}+ onClick={goToNextPage}+ >+ <button+ disabled={pageNumber >= numPagesWithAccountCreation}+ className="rounded-full bg-gray-950/50 p-1 hover:bg-gray-950/75"+ >+ <ChevronDownIcon className="h-10 w-10 text-white" />+ </button>+ </div>++ {feedbackEnabled && pageNumber <= numPages ? (+ <Toolbar+ viewId={viewId}+ pageNumber={pageNumber}+ isPreview={isPreview}+ />+ ) : null}++ {screenshotProtectionEnabled ? <ScreenProtector /> : null}+ {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={+ getTrackingOptions().inactivityThreshold || 20000+ }+ onDismiss={updateActivity}+ />+ {/* </div> */}+ {/* </div> */}+ </ResizablePanel>++ {/* Annotation Panel - Right Side */}+ {navData.annotationsFeatureEnabled &&+ annotationsEnabled &&+ hasAnnotations && (+ <>+ <ResizableHandle className="w-1 bg-transparent transition-colors hover:bg-white/10" />+ <ResizablePanel defaultSize={25} minSize={20} maxSize={40}>+ <AnnotationPanel+ brand={brand}+ linkId={linkId}+ documentId={documentId}+ viewId={viewId}+ currentPage={pageNumber}+ isVisible={true}+ />+ </ResizablePanel>+ </>+ )}+ </ResizablePanelGroup></div></>);diff --git a/components/view/viewer/pdf-default-viewer.tsx b/components/view/viewer/pdf-default-viewer.tsxindex 02d5feb7..91bf3aa9 100644--- a/components/view/viewer/pdf-default-viewer.tsx+++ b/components/view/viewer/pdf-default-viewer.tsx@@ -1,22 +1,14 @@import { useEffect, useRef, useState } from "react";--import { useTeam } from "@/context/team-context";import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";import { Document, Page, pdfjs } from "react-pdf";--import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";--import Nav from "@/components/view/nav";--import { AwayPoster } from "./away-poster";pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;@@ -319,12 +311,10 @@ export default function PDFViewer(props: any) {</div><AwayPosterisVisible={isInactive}- inactivityThreshold={- getTrackingOptions().inactivityThreshold- }+ inactivityThreshold={getTrackingOptions().inactivityThreshold}onDismiss={updateActivity}/></div></>);-}\ No newline at end of file+}diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsindex 60343352..47d50691 100644--- a/lib/featureFlags/index.ts+++ b/lib/featureFlags/index.ts@@ -10,7 +10,8 @@ export type BetaFeatures =| "inDocumentLinks"| "usStorage"| "dataroomIndex"- | "slack";+ | "slack"+ | "annotations";type BetaFeaturesRecord = Record<BetaFeatures, string[]>;@@ -26,6 +27,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {usStorage: false,dataroomIndex: false,slack: false,+ annotations: false,};// Return all features as true if edge config is not availablediff --git a/lib/swr/use-annotations.ts b/lib/swr/use-annotations.tsnew file mode 100644index 00000000..8f42480b--- /dev/null+++ b/lib/swr/use-annotations.ts@@ -0,0 +1,72 @@+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++export interface Annotation {+ id: string;+ title: string;+ content: any;+ pages: number[];+ isVisible: boolean;+ createdAt: string;+ updatedAt: string;+ createdBy: {+ id: string;+ name: string | null;+ email: string | null;+ };+ images: {+ id: string;+ filename: string;+ url: string;+ size: number | null;+ mimeType: string | null;+ createdAt: string;+ }[];+}++export function useAnnotations(documentId: string, teamId: string) {+ const { data, error, mutate } = useSWR<Annotation[]>(+ `/api/teams/${teamId}/documents/${documentId}/annotations`,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ },+ );++ return {+ annotations: data,+ loading: !error && !data,+ error,+ mutate,+ };+}++export function useViewerAnnotations(+ linkId: string,+ documentId?: string,+ viewId?: string,+) {+ // For dataroom document links, use the specific document endpoint+ // For regular document links, use the general link endpoint+ const endpoint = documentId+ ? `/api/links/${linkId}/documents/${documentId}/annotations?viewId=${viewId}`+ : `/api/links/${linkId}/annotations?viewId=${viewId}`;++ const { data, error, mutate } = useSWR<Omit<Annotation, "createdBy">[]>(+ endpoint,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ },+ );++ return {+ annotations: data,+ loading: !error && !data,+ error,+ mutate,+ };+}diff --git a/package-lock.json b/package-lock.jsonindex 62b030dc..2f062281 100644--- a/package-lock.json+++ b/package-lock.json@@ -20,6 +20,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@github/webauthn-json": "^2.1.1",+ "@hookform/resolvers": "^5.2.2","@jitsu/js": "^1.10.4","@next-auth/prisma-adapter": "^1.0.7","@next/third-parties": "^15.5.2",@@ -53,6 +54,10 @@"@tailwindcss/typography": "^0.5.16","@tanstack/react-table": "^8.21.3","@teamhanko/passkeys-next-auth-provider": "^0.3.1",+ "@tiptap/extension-image": "^3.4.2",+ "@tiptap/extension-placeholder": "^3.4.2",+ "@tiptap/react": "^3.4.2",+ "@tiptap/starter-kit": "^3.4.2","@tremor/react": "^3.18.7","@trigger.dev/react-hooks": "^3.3.17","@trigger.dev/sdk": "^3.3.17",@@ -107,11 +112,13 @@"react-draggable": "^4.5.0","react-dropzone": "^14.3.8","react-email": "^4.2.8",+ "react-hook-form": "^7.62.0","react-hotkeys-hook": "^5.1.0","react-intersection-observer": "^9.16.0","react-notion-x": "^7.3.0","react-pdf": "^8.0.2","react-phone-number-input": "^3.4.12",+ "react-resizable-panels": "^3.0.6","react-textarea-autosize": "^8.5.9","react-zoom-pan-pinch": "^3.7.0","resend": "^6.0.1",@@ -2281,6 +2288,18 @@"react-dom": ">=16.8.0"}},+ "node_modules/@hookform/resolvers": {+ "version": "5.2.2",+ "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",+ "integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/utils": "^0.3.0"+ },+ "peerDependencies": {+ "react-hook-form": "^7.55.0"+ }+ },"node_modules/@humanwhocodes/config-array": {"version": "0.11.14","resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz",@@ -7059,6 +7078,12 @@"node": ">=14"}},+ "node_modules/@remirror/core-constants": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@remirror/core-constants/-/core-constants-3.0.0.tgz",+ "integrity": "sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==",+ "license": "MIT"+ },"node_modules/@rollup/rollup-darwin-arm64": {"version": "4.34.9","resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.34.9.tgz",@@ -7924,6 +7949,12 @@"integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==","license": "MIT"},+ "node_modules/@standard-schema/utils": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",+ "license": "MIT"+ },"node_modules/@stripe/stripe-js": {"version": "4.10.0","resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-4.10.0.tgz",@@ -8051,6 +8082,466 @@"openapi-fetch": "^0.8.1"}},+ "node_modules/@tiptap/core": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.4.2.tgz",+ "integrity": "sha512-OYU0VoFiMoIsMfQibyuNf1dk3ERvUK/eBKsfMnEr8Tr3+l0ltg+xxjiLe/U0NHR/A0myvNXqc2zyVxtyDRYPGg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-blockquote": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.4.2.tgz",+ "integrity": "sha512-v7tONi9eTVHK8s6ligSMz1ATy72zQNNrI0A7EmX9kTcUodVl44i0Tw+mgGyeMEKo+oSX88yPhD+lKXKUVleRHA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-bold": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.4.2.tgz",+ "integrity": "sha512-/TYN0jFlXul/D9TSqh4i5vnZR5AmptOc6SJCYZAoi/U7qF4D2xtuAic+lkW0p60Gtrgqgap666scvVCnpnJlzQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-bubble-menu": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.4.2.tgz",+ "integrity": "sha512-N8rbb6H5qfXMRdudB3Uz4kUjfGf3bcIbu20/4emRFajILvhnbobvmYGPsWxVVS4UL0tKETCfEuTVaflWy+ZrmQ==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@floating-ui/dom": "^1.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-bullet-list": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.4.2.tgz",+ "integrity": "sha512-j7hPCaULln7w90KMyvcubM51bQrmmzHKQJcs/EccN6rhsL3hqJ4fIiyGRKhGbv4QVXzqwLJXNkQusOKDchi8pw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extension-list": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-code": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.4.2.tgz",+ "integrity": "sha512-7A/ihn8ayA7K6CzETmWFVzixyOVRVSviRMIleNGknBtF6C4bmqfuwBa2KAonylv5ws0JZfQRQU7itrHE8FVdEg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-code-block": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.4.2.tgz",+ "integrity": "sha512-H5Y8Rs3EnH9u5gkxEikUWTyBf1WmttPSmEsEmBh0a6Lj9m3NxAbOEvKszibkqJNvfQdpomKCMQU6w/OXiZC/DQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-document": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.4.2.tgz",+ "integrity": "sha512-y6XfihmKYrqUEAeyZkkF39/dBqvjf7TavCPVPaN42agjFYukiZExgtDb+xkagxdbDzf1F8327CyoAqNajhj79Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-dropcursor": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.4.2.tgz",+ "integrity": "sha512-BHjfpusRvxsa8aV1C0O0mNNjBGWfa1uwolHflCOb4PNkh9nGU0htuaPYTS4fGEVVKOhOC9qsp0hUHSejWL1E6g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extensions": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-floating-menu": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.4.2.tgz",+ "integrity": "sha512-2jDugvR7e506fDfmO22cHU0XnRyBsvig8XNSBPEcXyP3xy53kxiaCF4CzRC8DyzuC7u1NilII27TnwV5iM+9Pg==",+ "license": "MIT",+ "optional": true,+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@floating-ui/dom": "^1.0.0",+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-gapcursor": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.4.2.tgz",+ "integrity": "sha512-cn85HNyqaZpY0QPmETyB0QS/B24rFQxvtOLL1gf0hLFvTp7kuMYTFcU6CgDibr4uDu2hBBXhgTRTOl2e3bN8Xw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extensions": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-hard-break": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.4.2.tgz",+ "integrity": "sha512-h5CfGZyUrhzUCXwYgmxUaQKsu+zZC2iDpJkJK9TH7PobWkN3fFPfmc1D2LrDyYI24G8ozzqHQissAQl4JEag5w==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-heading": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.4.2.tgz",+ "integrity": "sha512-8Gbc52jjDVhVbXoNNVXeIkfMP3sHCfqW/GqYjZ9onYPYk1GD4DkSAMH9naRJ8g/+Z6lOkKM+ySF/gtdAVOnBTQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-horizontal-rule": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.4.2.tgz",+ "integrity": "sha512-LK56R4ZR/B6nMxdyiDWuV6nk5akX8/2OXp29ZuX34BBYkFNjLBF9evGCHDy60az43JrSi/wwTUDafAxdO9S2Ig==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-image": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-3.4.2.tgz",+ "integrity": "sha512-76pWwe2WEPw/LMEh+QTEJRGKM5YLAJfmt64DOlO887YH6uXjTn5tKJ3gedz+0ZM4NhHh61JbfXcdTFEhkMxMZA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-italic": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.4.2.tgz",+ "integrity": "sha512-X+ySvBlO2bpJJWgaZKVesh/GV5VtBchYZizEBUaPvkgYsS+s0Ujwz3YQvszX/JnfJ4k239D9S+bpJi4dTN5Utw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-link": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.4.2.tgz",+ "integrity": "sha512-BNewJ6A6sHWzOlRhTtCp5ZLy8IguH54eEidntIbjSqV1nXwZot60PVdB+d53Mbz2SJJkdSrfbI7Kj0V1BTh6gA==",+ "license": "MIT",+ "dependencies": {+ "linkifyjs": "^4.3.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-list": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.4.2.tgz",+ "integrity": "sha512-ribIYMre1EB6TdyNhEBbO23p2f+UQj5KghbtcI4wYmthjnN+LOag+dUM5sBAiUhUyBlmc4MC1As06yWTu2hzqQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-list-item": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.4.2.tgz",+ "integrity": "sha512-OrRKIYih4Wc+TofAAgukpMEzq8k3BH6WY7QzPtxti58aji+euNYznt2YQm8m1oJdMECYOaREV4cwXvmES6rk8A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extension-list": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-list-keymap": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.4.2.tgz",+ "integrity": "sha512-VbtrCeoN64ByHL2jQUx2Zya+u8JxEvsRTelr8hksSGRrrZyahG1JESpu7Z2Y8Qjo5NEfSivWuEw9kbLCXsjvjw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extension-list": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-ordered-list": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.4.2.tgz",+ "integrity": "sha512-q9w7fQ26PZkbS3iD4h4HpoFoI5ap5jyYeGBugyhgGdHeF3luKiorleSY7m8NNmLlB6FWfDZZqPBWhrZgzPdFiQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extension-list": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-paragraph": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.4.2.tgz",+ "integrity": "sha512-M4M+N5Sit82HUK9rp662ZL1X/MMkD3zMnD8i5gV0Gj1T+YwToAGBIdte7n9QoAcNZr1cOdjAveI+HzOw6UA6SQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-placeholder": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-placeholder/-/extension-placeholder-3.4.2.tgz",+ "integrity": "sha512-it4BIl2quDLIBM3I1y618kvOHYgcWBaf9VvLTN2SzTAt35cn5ySOFBOxM2eSr8HG1WigdL9eIL/y1hENsdQrqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/extensions": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-strike": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.4.2.tgz",+ "integrity": "sha512-bgdq2eW5omli+rv6PHErDME1YocT1BHkiWvRV5pRYyTz5TZTgYujA0Qn2DjsW1baFike0oG3ToLAxH5RnViDoQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-text": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.4.2.tgz",+ "integrity": "sha512-g7F1utUaVibr0ohnvfj4zJh6lofP5mQY+6sE2CDsHD1IE5VcBGh7ONWUMzAAGzi9oHtKSqpzPiUfw1BtmF8/+Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extension-underline": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.4.2.tgz",+ "integrity": "sha512-kOOYE81n7w8yFt63UDjPq3hFoPXIGwcIbXOZCaB77tmLy4Cfy7ewa0oVnzunCXsGJs1Je4NbIqFnJq0H2KyUPw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2"+ }+ },+ "node_modules/@tiptap/extensions": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.4.2.tgz",+ "integrity": "sha512-0EOPKVU0whK4tw7TenmJe0M+DfV8Fjj0b6ZO0hqq2rOFWtBRUdRd7QLdg8XUk70D1BbZ52kO0ggM4zZqhW/57A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ }+ },+ "node_modules/@tiptap/pm": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.4.2.tgz",+ "integrity": "sha512-cU1DYb1vnpAZhe7R578PfSCh9FbZDf/zR3wuhc6QOkZjGertTgG9ge7pn0RZnJeX4U9hO1WWJ5eOIPoalotlcA==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-changeset": "^2.3.0",+ "prosemirror-collab": "^1.3.1",+ "prosemirror-commands": "^1.6.2",+ "prosemirror-dropcursor": "^1.8.1",+ "prosemirror-gapcursor": "^1.3.2",+ "prosemirror-history": "^1.4.1",+ "prosemirror-inputrules": "^1.4.0",+ "prosemirror-keymap": "^1.2.2",+ "prosemirror-markdown": "^1.13.1",+ "prosemirror-menu": "^1.2.4",+ "prosemirror-model": "^1.24.1",+ "prosemirror-schema-basic": "^1.2.3",+ "prosemirror-schema-list": "^1.5.0",+ "prosemirror-state": "^1.4.3",+ "prosemirror-tables": "^1.6.4",+ "prosemirror-trailing-node": "^3.0.0",+ "prosemirror-transform": "^1.10.2",+ "prosemirror-view": "^1.38.1"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ }+ },+ "node_modules/@tiptap/react": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/react/-/react-3.4.2.tgz",+ "integrity": "sha512-kNcn+uNMs76GXYLBtEwR5pE357MdCKvIAQ3Oobq+//rrynRK/RP2IlRpybTWhrn/y7d4nD0DfHbFnhDpokoJIQ==",+ "license": "MIT",+ "dependencies": {+ "@types/use-sync-external-store": "^0.0.6",+ "fast-deep-equal": "^3.1.3",+ "use-sync-external-store": "^1.4.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "optionalDependencies": {+ "@tiptap/extension-bubble-menu": "^3.4.2",+ "@tiptap/extension-floating-menu": "^3.4.2"+ },+ "peerDependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/pm": "^3.4.2",+ "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",+ "@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/@tiptap/starter-kit": {+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.4.2.tgz",+ "integrity": "sha512-qfw9RljtZNLpqj+lnkgxok+ksCV/OR4rBX7QSJXaQYVJuid2tXejFj7vqsJQaf1Z6zT9swdk7js92qlwjCO0BQ==",+ "license": "MIT",+ "dependencies": {+ "@tiptap/core": "^3.4.2",+ "@tiptap/extension-blockquote": "^3.4.2",+ "@tiptap/extension-bold": "^3.4.2",+ "@tiptap/extension-bullet-list": "^3.4.2",+ "@tiptap/extension-code": "^3.4.2",+ "@tiptap/extension-code-block": "^3.4.2",+ "@tiptap/extension-document": "^3.4.2",+ "@tiptap/extension-dropcursor": "^3.4.2",+ "@tiptap/extension-gapcursor": "^3.4.2",+ "@tiptap/extension-hard-break": "^3.4.2",+ "@tiptap/extension-heading": "^3.4.2",+ "@tiptap/extension-horizontal-rule": "^3.4.2",+ "@tiptap/extension-italic": "^3.4.2",+ "@tiptap/extension-link": "^3.4.2",+ "@tiptap/extension-list": "^3.4.2",+ "@tiptap/extension-list-item": "^3.4.2",+ "@tiptap/extension-list-keymap": "^3.4.2",+ "@tiptap/extension-ordered-list": "^3.4.2",+ "@tiptap/extension-paragraph": "^3.4.2",+ "@tiptap/extension-strike": "^3.4.2",+ "@tiptap/extension-text": "^3.4.2",+ "@tiptap/extension-underline": "^3.4.2",+ "@tiptap/extensions": "^3.4.2",+ "@tiptap/pm": "^3.4.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ }+ },"node_modules/@tremor/react": {"version": "3.18.7","resolved": "https://registry.npmjs.org/@tremor/react/-/react-3.18.7.tgz",@@ -8419,6 +8910,22 @@"@types/node": "*"}},+ "node_modules/@types/linkify-it": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",+ "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==",+ "license": "MIT"+ },+ "node_modules/@types/markdown-it": {+ "version": "14.1.2",+ "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz",+ "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==",+ "license": "MIT",+ "dependencies": {+ "@types/linkify-it": "^5",+ "@types/mdurl": "^2"+ }+ },"node_modules/@types/mdast": {"version": "4.0.4","resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",@@ -8428,6 +8935,12 @@"@types/unist": "*"}},+ "node_modules/@types/mdurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz",+ "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==",+ "license": "MIT"+ },"node_modules/@types/mime-types": {"version": "3.0.1","resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-3.0.1.tgz",@@ -8482,14 +8995,12 @@"node_modules/@types/prop-types": {"version": "15.7.12","resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.12.tgz",- "integrity": "sha512-5zvhXYtRNRluoE/jAp4GVsSduVUzNWKkOZrCDBWYtE7biZywwdC2AcEzg+cSMLFRfVgeAFqpfNabiPjxFddV1Q==",- "devOptional": true+ "integrity": "sha512-5zvhXYtRNRluoE/jAp4GVsSduVUzNWKkOZrCDBWYtE7biZywwdC2AcEzg+cSMLFRfVgeAFqpfNabiPjxFddV1Q=="},"node_modules/@types/react": {"version": "18.3.18","resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.18.tgz","integrity": "sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==",- "devOptional": true,"dependencies": {"@types/prop-types": "*","csstype": "^3.0.2"@@ -8499,7 +9010,6 @@"version": "18.3.7","resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz","integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",- "devOptional": true,"license": "MIT","peerDependencies": {"@types/react": "^18.0.0"@@ -8532,6 +9042,12 @@"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==","license": "MIT"},+ "node_modules/@types/use-sync-external-store": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",+ "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",+ "license": "MIT"+ },"node_modules/@types/uuid": {"version": "9.0.8","resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz",@@ -10683,6 +11199,12 @@"node": ">= 10"}},+ "node_modules/crelt": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",+ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",+ "license": "MIT"+ },"node_modules/cronstrue": {"version": "2.51.0","resolved": "https://registry.npmjs.org/cronstrue/-/cronstrue-2.51.0.tgz",@@ -14241,6 +14763,21 @@"resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz","integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="},+ "node_modules/linkify-it": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz",+ "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==",+ "license": "MIT",+ "dependencies": {+ "uc.micro": "^2.0.0"+ }+ },+ "node_modules/linkifyjs": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz",+ "integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==",+ "license": "MIT"+ },"node_modules/listenercount": {"version": "1.0.1","resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz",@@ -14548,6 +15085,23 @@"url": "https://github.com/wojtekmaj/make-event-props?sponsor=1"}},+ "node_modules/markdown-it": {+ "version": "14.1.0",+ "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz",+ "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==",+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1",+ "entities": "^4.4.0",+ "linkify-it": "^5.0.0",+ "mdurl": "^2.0.0",+ "punycode.js": "^2.3.1",+ "uc.micro": "^2.1.0"+ },+ "bin": {+ "markdown-it": "bin/markdown-it.mjs"+ }+ },"node_modules/marked": {"version": "7.0.4","resolved": "https://registry.npmjs.org/marked/-/marked-7.0.4.tgz",@@ -14617,6 +15171,12 @@"url": "https://opencollective.com/unified"}},+ "node_modules/mdurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz",+ "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==",+ "license": "MIT"+ },"node_modules/memoize": {"version": "10.1.0","resolved": "https://registry.npmjs.org/memoize/-/memoize-10.1.0.tgz",@@ -15829,6 +16389,12 @@"url": "https://github.com/chalk/strip-ansi?sponsor=1"}},+ "node_modules/orderedmap": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",+ "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",+ "license": "MIT"+ },"node_modules/p-limit": {"version": "3.1.0","resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",@@ -16548,6 +17114,213 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/prosemirror-changeset": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.3.1.tgz",+ "integrity": "sha512-j0kORIBm8ayJNl3zQvD1TTPHJX3g042et6y/KQhZhnPrruO8exkTgG8X+NRpj7kIyMMEx74Xb3DyMIBtO0IKkQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-transform": "^1.0.0"+ }+ },+ "node_modules/prosemirror-collab": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz",+ "integrity": "sha512-4SnynYR9TTYaQVXd/ieUvsVV4PDMBzrq2xPUWutHivDuOshZXqQ5rGbZM84HEaXKbLdItse7weMGOUdDVcLKEQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0"+ }+ },+ "node_modules/prosemirror-commands": {+ "version": "1.7.1",+ "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz",+ "integrity": "sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.10.2"+ }+ },+ "node_modules/prosemirror-dropcursor": {+ "version": "1.8.2",+ "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.2.tgz",+ "integrity": "sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.1.0",+ "prosemirror-view": "^1.1.0"+ }+ },+ "node_modules/prosemirror-gapcursor": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.3.2.tgz",+ "integrity": "sha512-wtjswVBd2vaQRrnYZaBCbyDqr232Ed4p2QPtRIUK5FuqHYKGWkEwl08oQM4Tw7DOR0FsasARV5uJFvMZWxdNxQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-keymap": "^1.0.0",+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-view": "^1.0.0"+ }+ },+ "node_modules/prosemirror-history": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.4.1.tgz",+ "integrity": "sha512-2JZD8z2JviJrboD9cPuX/Sv/1ChFng+xh2tChQ2X4bB2HeK+rra/bmJ3xGntCcjhOqIzSDG6Id7e8RJ9QPXLEQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.2.2",+ "prosemirror-transform": "^1.0.0",+ "prosemirror-view": "^1.31.0",+ "rope-sequence": "^1.3.0"+ }+ },+ "node_modules/prosemirror-inputrules": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.0.tgz",+ "integrity": "sha512-K0xJRCmt+uSw7xesnHmcn72yBGTbY45vm8gXI4LZXbx2Z0jwh5aF9xrGQgrVPu0WbyFVFF3E/o9VhJYz6SQWnA==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.0.0"+ }+ },+ "node_modules/prosemirror-keymap": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",+ "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-state": "^1.0.0",+ "w3c-keyname": "^2.2.0"+ }+ },+ "node_modules/prosemirror-markdown": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/prosemirror-markdown/-/prosemirror-markdown-1.13.2.tgz",+ "integrity": "sha512-FPD9rHPdA9fqzNmIIDhhnYQ6WgNoSWX9StUZ8LEKapaXU9i6XgykaHKhp6XMyXlOWetmaFgGDS/nu/w9/vUc5g==",+ "license": "MIT",+ "dependencies": {+ "@types/markdown-it": "^14.0.0",+ "markdown-it": "^14.0.0",+ "prosemirror-model": "^1.25.0"+ }+ },+ "node_modules/prosemirror-menu": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/prosemirror-menu/-/prosemirror-menu-1.2.5.tgz",+ "integrity": "sha512-qwXzynnpBIeg1D7BAtjOusR+81xCp53j7iWu/IargiRZqRjGIlQuu1f3jFi+ehrHhWMLoyOQTSRx/IWZJqOYtQ==",+ "license": "MIT",+ "dependencies": {+ "crelt": "^1.0.0",+ "prosemirror-commands": "^1.0.0",+ "prosemirror-history": "^1.0.0",+ "prosemirror-state": "^1.0.0"+ }+ },+ "node_modules/prosemirror-model": {+ "version": "1.25.3",+ "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.3.tgz",+ "integrity": "sha512-dY2HdaNXlARknJbrManZ1WyUtos+AP97AmvqdOQtWtrrC5g4mohVX5DTi9rXNFSk09eczLq9GuNTtq3EfMeMGA==",+ "license": "MIT",+ "dependencies": {+ "orderedmap": "^2.0.0"+ }+ },+ "node_modules/prosemirror-schema-basic": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/prosemirror-schema-basic/-/prosemirror-schema-basic-1.2.4.tgz",+ "integrity": "sha512-ELxP4TlX3yr2v5rM7Sb70SqStq5NvI15c0j9j/gjsrO5vaw+fnnpovCLEGIcpeGfifkuqJwl4fon6b+KdrODYQ==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.25.0"+ }+ },+ "node_modules/prosemirror-schema-list": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz",+ "integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.7.3"+ }+ },+ "node_modules/prosemirror-state": {+ "version": "1.4.3",+ "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.3.tgz",+ "integrity": "sha512-goFKORVbvPuAQaXhpbemJFRKJ2aixr+AZMGiquiqKxaucC6hlpHNZHWgz5R7dS4roHiwq9vDctE//CZ++o0W1Q==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.0.0",+ "prosemirror-transform": "^1.0.0",+ "prosemirror-view": "^1.27.0"+ }+ },+ "node_modules/prosemirror-tables": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.1.tgz",+ "integrity": "sha512-DAgDoUYHCcc6tOGpLVPSU1k84kCUWTWnfWX3UDy2Delv4ryH0KqTD6RBI6k4yi9j9I8gl3j8MkPpRD/vWPZbug==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-keymap": "^1.2.2",+ "prosemirror-model": "^1.25.0",+ "prosemirror-state": "^1.4.3",+ "prosemirror-transform": "^1.10.3",+ "prosemirror-view": "^1.39.1"+ }+ },+ "node_modules/prosemirror-trailing-node": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/prosemirror-trailing-node/-/prosemirror-trailing-node-3.0.0.tgz",+ "integrity": "sha512-xiun5/3q0w5eRnGYfNlW1uU9W6x5MoFKWwq/0TIRgt09lv7Hcser2QYV8t4muXbEr+Fwo0geYn79Xs4GKywrRQ==",+ "license": "MIT",+ "dependencies": {+ "@remirror/core-constants": "3.0.0",+ "escape-string-regexp": "^4.0.0"+ },+ "peerDependencies": {+ "prosemirror-model": "^1.22.1",+ "prosemirror-state": "^1.4.2",+ "prosemirror-view": "^1.33.8"+ }+ },+ "node_modules/prosemirror-trailing-node/node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/prosemirror-transform": {+ "version": "1.10.4",+ "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.10.4.tgz",+ "integrity": "sha512-pwDy22nAnGqNR1feOQKHxoFkkUtepoFAd3r2hbEDsnf4wp57kKA36hXsB3njA9FtONBEwSDnDeCiJe+ItD+ykw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.21.0"+ }+ },+ "node_modules/prosemirror-view": {+ "version": "1.41.0",+ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.41.0.tgz",+ "integrity": "sha512-FatMIIl0vRHMcNc3sPy3cMw5MMyWuO1nWQxqvYpJvXAruucGvmQ2tyyjT2/Lbok77T9a/qZqBVCq4sj43V2ihw==",+ "license": "MIT",+ "dependencies": {+ "prosemirror-model": "^1.20.0",+ "prosemirror-state": "^1.0.0",+ "prosemirror-transform": "^1.1.0"+ }+ },"node_modules/protobufjs": {"version": "7.4.0","resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.4.0.tgz",@@ -16579,6 +17352,15 @@"node": ">=6"}},+ "node_modules/punycode.js": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz",+ "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/qs": {"version": "6.12.3","resolved": "https://registry.npmjs.org/qs/-/qs-6.12.3.tgz",@@ -16874,6 +17656,22 @@"resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz","integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ=="},+ "node_modules/react-hook-form": {+ "version": "7.62.0",+ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.62.0.tgz",+ "integrity": "sha512-7KWFejc98xqG/F4bAxpL41NB3o1nnvQO1RWZT3TqRZYL8RryQETGfEdVnJN2fy1crCiBLLjkRBVK05j24FxJGA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/react-hook-form"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17 || ^18 || ^19"+ }+ },"node_modules/react-hotkeys-hook": {"version": "5.1.0","resolved": "https://registry.npmjs.org/react-hotkeys-hook/-/react-hotkeys-hook-5.1.0.tgz",@@ -17102,6 +17900,16 @@}}},+ "node_modules/react-resizable-panels": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/react-resizable-panels/-/react-resizable-panels-3.0.6.tgz",+ "integrity": "sha512-b3qKHQ3MLqOgSS+FRYKapNkJZf5EQzuf6+RLiq1/IlTHw99YrZ2NJZLk4hQIzTnnIkRg2LUqyVinu6YWWpUYew==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },"node_modules/react-smooth": {"version": "4.0.1","resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.1.tgz",@@ -17531,6 +18339,12 @@"url": "https://github.com/sponsors/isaacs"}},+ "node_modules/rope-sequence": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",+ "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",+ "license": "MIT"+ },"node_modules/run-exclusive": {"version": "2.2.19","resolved": "https://registry.npmjs.org/run-exclusive/-/run-exclusive-2.2.19.tgz",@@ -19237,6 +20051,12 @@"node": "*"}},+ "node_modules/uc.micro": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz",+ "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==",+ "license": "MIT"+ },"node_modules/ufo": {"version": "1.5.4","resolved": "https://registry.npmjs.org/ufo/-/ufo-1.5.4.tgz",@@ -19680,6 +20500,12 @@}}},+ "node_modules/w3c-keyname": {+ "version": "2.2.8",+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",+ "license": "MIT"+ },"node_modules/warning": {"version": "4.0.3","resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz",diff --git a/package.json b/package.jsonindex 80cd5c93..8678a6c7 100644--- a/package.json+++ b/package.json@@ -31,6 +31,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@github/webauthn-json": "^2.1.1",+ "@hookform/resolvers": "^5.2.2","@jitsu/js": "^1.10.4","@next-auth/prisma-adapter": "^1.0.7","@next/third-parties": "^15.5.2",@@ -64,6 +65,10 @@"@tailwindcss/typography": "^0.5.16","@tanstack/react-table": "^8.21.3","@teamhanko/passkeys-next-auth-provider": "^0.3.1",+ "@tiptap/extension-image": "^3.4.2",+ "@tiptap/extension-placeholder": "^3.4.2",+ "@tiptap/react": "^3.4.2",+ "@tiptap/starter-kit": "^3.4.2","@tremor/react": "^3.18.7","@trigger.dev/react-hooks": "^3.3.17","@trigger.dev/sdk": "^3.3.17",@@ -118,11 +123,13 @@"react-draggable": "^4.5.0","react-dropzone": "^14.3.8","react-email": "^4.2.8",+ "react-hook-form": "^7.62.0","react-hotkeys-hook": "^5.1.0","react-intersection-observer": "^9.16.0","react-notion-x": "^7.3.0","react-pdf": "^8.0.2","react-phone-number-input": "^3.4.12",+ "react-resizable-panels": "^3.0.6","react-textarea-autosize": "^8.5.9","react-zoom-pan-pinch": "^3.7.0","resend": "^6.0.1",diff --git a/pages/api/links/[id]/annotations.ts b/pages/api/links/[id]/annotations.tsnew file mode 100644index 00000000..4215a05d--- /dev/null+++ b/pages/api/links/[id]/annotations.ts@@ -0,0 +1,90 @@+import { NextApiRequest, NextApiResponse } from "next";++import { AnnotationImage, DocumentAnnotation } from "@prisma/client";++import { errorhandler } from "@/lib/errorHandler";+import { getFeatureFlags } from "@/lib/featureFlags";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const { id: linkId, viewId } = req.query as { id: string; viewId: string };++ try {+ const view = await prisma.view.findUnique({+ where: { id: viewId, linkId: linkId },+ include: {+ link: true,+ document: {+ include: {+ annotations: {+ where: {+ isVisible: true, // Only return visible annotations for viewers+ },+ include: {+ images: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ },+ },+ },+ },+ });++ if (!view) {+ return res.status(404).json({ error: "Annotation not found" });+ }++ if (view.viewedAt > new Date(Date.now() - 1000 * 60 * 60 * 23)) {+ // if view is older than 23 hours, we should not allow the annotations to be accessed+ return res.status(404).json({ error: "Annotation not found" });+ }++ // Check if annotations feature is enabled for this team+ const featureFlags = await getFeatureFlags({+ teamId: view.teamId || undefined,+ });+ if (!featureFlags.annotations) {+ return res.status(200).json([]); // Return empty array if feature is disabled+ }++ // This endpoint only handles DOCUMENT_LINK types+ // For DATAROOM_LINK types, use /api/links/[id]/documents/[documentId]/annotations+ let annotations: (DocumentAnnotation & { images: AnnotationImage[] })[] =+ [];+ if (view.link.linkType === "DOCUMENT_LINK" && view.document) {+ annotations = view.document.annotations || [];+ } else if (view.link.linkType === "DATAROOM_LINK") {+ // For dataroom links, return empty array - they should use the specific document endpoint+ annotations = [];+ }++ // Remove sensitive information (don't expose createdBy details to viewers)+ const sanitizedAnnotations = annotations.map((annotation) => ({+ id: annotation.id,+ title: annotation.title,+ content: annotation.content,+ pages: annotation.pages,+ images: annotation.images,+ createdAt: annotation.createdAt,+ }));++ return res.status(200).json(sanitizedAnnotations);+ } catch (error) {+ log({+ message: `Failed to get annotations for link: _${linkId}_. \n\n ${error}`,+ type: "error",+ });+ errorhandler(error, res);+ }+}diff --git a/pages/api/links/[id]/documents/[documentId]/annotations.ts b/pages/api/links/[id]/documents/[documentId]/annotations.tsnew file mode 100644index 00000000..06b88c1a--- /dev/null+++ b/pages/api/links/[id]/documents/[documentId]/annotations.ts@@ -0,0 +1,118 @@+import { NextApiRequest, NextApiResponse } from "next";++import { errorhandler } from "@/lib/errorHandler";+import { getFeatureFlags } from "@/lib/featureFlags";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const {+ id: linkId,+ documentId: dataroomDocumentId,+ viewId,+ } = req.query as {+ id: string;+ documentId: string;+ viewId: string;+ };++ try {+ const view = await prisma.view.findUnique({+ where: { id: viewId, linkId: linkId },+ select: { id: true, link: true },+ });++ if (!view) {+ return res.status(404).json({ error: "View not found" });+ }++ // Check if annotations feature is enabled for this team+ const featureFlags = await getFeatureFlags({+ teamId: view.link.teamId || undefined,+ });+ if (!featureFlags.annotations) {+ return res.status(200).json([]); // Return empty array if feature is disabled+ }++ let document = null;++ if (view.link.linkType === "DOCUMENT_LINK") {+ // For document links, get the document directly+ document = await prisma.document.findUnique({+ where: { id: view.link.documentId! },+ include: {+ annotations: {+ where: {+ isVisible: true, // Only return visible annotations for viewers+ },+ include: {+ images: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ },+ },+ });+ } else if (view.link.linkType === "DATAROOM_LINK") {+ // For dataroom links, get the specific dataroom document+ const dataroomDocument = await prisma.dataroomDocument.findFirst({+ where: {+ id: dataroomDocumentId,+ dataroomId: view.link.dataroomId!,+ },+ include: {+ document: {+ include: {+ annotations: {+ where: {+ isVisible: true, // Only return visible annotations for viewers+ },+ include: {+ images: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ },+ },+ },+ },+ });++ document = dataroomDocument?.document;+ }++ if (!document) {+ return res.status(404).json({ error: "Document not found" });+ }++ const annotations = document.annotations || [];++ // Remove sensitive information (don't expose createdBy details to viewers)+ const sanitizedAnnotations = annotations.map((annotation) => ({+ id: annotation.id,+ title: annotation.title,+ content: annotation.content,+ pages: annotation.pages,+ images: annotation.images,+ createdAt: annotation.createdAt,+ }));++ return res.status(200).json(sanitizedAnnotations);+ } catch (error) {+ log({+ message: `Failed to get annotations for link: _${linkId}_ and document: _${dataroomDocumentId}_. \n\n ${error}`,+ type: "error",+ });+ errorhandler(error, res);+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId].ts b/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId].tsnew file mode 100644index 00000000..31106de2--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId].ts@@ -0,0 +1,131 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";+import { z } from "zod";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++const updateAnnotationSchema = z.object({+ title: z+ .string()+ .min(1, "Title is required")+ .max(100, "Title must be less than 100 characters")+ .optional(),+ content: z.record(z.any()).optional(), // Rich text content as JSON+ pages: z+ .array(z.number().min(1))+ .min(1, "At least one page must be selected")+ .optional(),+ isVisible: z.boolean().optional(),+});++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const {+ teamId,+ id: docId,+ annotationId,+ } = req.query as {+ teamId: string;+ id: string;+ annotationId: string;+ };++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const userId = (session.user as CustomUser).id;++ try {+ // Verify user has access to document+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ });++ // Verify annotation exists and belongs to document+ const annotation = await prisma.documentAnnotation.findFirst({+ where: {+ id: annotationId,+ documentId: docId,+ teamId,+ },+ });++ if (!annotation) {+ return res.status(404).json({ error: "Annotation not found" });+ }++ if (req.method === "GET") {+ // GET /api/teams/:teamId/documents/:id/annotations/:annotationId+ const fullAnnotation = await prisma.documentAnnotation.findUnique({+ where: { id: annotationId },+ include: {+ images: true,+ createdBy: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ },+ });++ return res.status(200).json(fullAnnotation);+ } else if (req.method === "PUT") {+ // PUT /api/teams/:teamId/documents/:id/annotations/:annotationId+ const validatedData = updateAnnotationSchema.parse(req.body);++ const updatedAnnotation = await prisma.documentAnnotation.update({+ where: { id: annotationId },+ data: validatedData,+ include: {+ images: true,+ createdBy: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ },+ });++ return res.status(200).json(updatedAnnotation);+ } else if (req.method === "DELETE") {+ // DELETE /api/teams/:teamId/documents/:id/annotations/:annotationId+ await prisma.documentAnnotation.delete({+ where: { id: annotationId },+ });++ return res.status(204).end();+ } else {+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+ } catch (error) {+ if (error instanceof z.ZodError) {+ return res.status(400).json({+ error: "Invalid input",+ details: error.errors,+ });+ }++ log({+ message: `Failed to handle annotation ${req.method} for document: _${docId}_ and annotation: _${annotationId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId]/images.ts b/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId]/images.tsnew file mode 100644index 00000000..a5d6c2e0--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/annotations/[annotationId]/images.ts@@ -0,0 +1,91 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: docId,+ annotationId,+ } = req.query as {+ teamId: string;+ id: string;+ annotationId: string;+ };++ const userId = (session.user as CustomUser).id;++ try {+ // Verify user has access to document+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ });++ // Verify annotation exists and belongs to document+ const annotation = await prisma.documentAnnotation.findFirst({+ where: {+ id: annotationId,+ documentId: docId,+ teamId,+ },+ });++ if (!annotation) {+ return res.status(404).json({ error: "Annotation not found" });+ }++ const { filename, url, size, mimeType } = req.body;++ if (!filename || !url || !mimeType) {+ return res.status(400).json({+ error: "Missing required fields: filename, url, mimeType",+ });+ }++ // Validate file type+ if (!mimeType.startsWith("image/")) {+ return res.status(400).json({ error: "Only image files are allowed" });+ }++ // Save image record to database+ const image = await prisma.annotationImage.create({+ data: {+ filename,+ url,+ size,+ mimeType,+ annotationId,+ },+ });++ return res.status(201).json(image);+ } catch (error) {+ log({+ message: `Failed to upload image for annotation: _${annotationId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}, docId: ${docId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/annotations/index.ts b/pages/api/teams/[teamId]/documents/[id]/annotations/index.tsnew file mode 100644index 00000000..28776823--- /dev/null+++ b/pages/api/teams/[teamId]/documents/[id]/annotations/index.ts@@ -0,0 +1,133 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";+import { z } from "zod";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++const createAnnotationSchema = z.object({+ title: z+ .string()+ .min(1, "Title is required")+ .max(100, "Title must be less than 100 characters"),+ content: z.record(z.any()), // Rich text content as JSON+ pages: z+ .array(z.number().min(1))+ .min(1, "At least one page must be selected"),+ isVisible: z.boolean().default(true),+});++const updateAnnotationSchema = createAnnotationSchema.partial();++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/documents/:id/annotations+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: docId } = req.query as { teamId: string; id: string };+ const userId = (session.user as CustomUser).id;++ try {+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ options: {+ include: {+ annotations: {+ include: {+ images: true,+ createdBy: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ },+ },+ },+ });++ return res.status(200).json(document?.annotations || []);+ } catch (error) {+ log({+ message: `Failed to get annotations for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+ } else if (req.method === "POST") {+ // POST /api/teams/:teamId/documents/:id/annotations+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: docId } = req.query as { teamId: string; id: string };+ const userId = (session.user as CustomUser).id;++ try {+ const validatedData = createAnnotationSchema.parse(req.body);++ // Verify user has access to document+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ });++ const annotation = await prisma.documentAnnotation.create({+ data: {+ ...validatedData,+ documentId: docId,+ teamId,+ createdById: userId,+ },+ include: {+ images: true,+ createdBy: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ },+ });++ return res.status(201).json(annotation);+ } catch (error) {+ if (error instanceof z.ZodError) {+ return res.status(400).json({+ error: "Invalid input",+ details: error.errors,+ });+ }++ log({+ message: `Failed to create annotation for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+ } else {+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 1d66eb48..c2cbad91 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -4,12 +4,15 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { PlanEnum } from "@/ee/stripe/constants";+import useSWR from "swr";import { usePlan } from "@/lib/swr/use-billing";import { useDocument, useDocumentLinks } from "@/lib/swr/use-document";import useLimits from "@/lib/swr/use-limits";+import { fetcher } from "@/lib/utils";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";+import { AnnotationSheet } from "@/components/documents/annotations/annotation-sheet";import DocumentHeader from "@/components/documents/document-header";import { DocumentPreviewButton } from "@/components/documents/document-preview-button";import NotionAccessibilityIndicator from "@/components/documents/notion-accessibility-indicator";@@ -35,6 +38,14 @@ export default function DocumentPage() {const { canAddLinks } = useLimits();+ // Get feature flags+ const { data: featureFlags } = useSWR<{ annotations: boolean }>(+ teamInfo?.currentTeam?.id+ ? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`+ : null,+ fetcher,+ );+const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);if (error && error.status === 400) {@@ -82,6 +93,15 @@ export default function DocumentPage() {primaryVersion={primaryVersion}onUrlUpdate={mutateDocument}/>,+ <>+ {featureFlags?.annotations && (+ <AnnotationSheet+ documentId={prismaDocument.id}+ teamId={teamInfo?.currentTeam?.id!}+ numPages={primaryVersion.numPages || 1}+ />+ )}+ </>,<DocumentPreviewButtonkey={"preview"}documentId={prismaDocument.id}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex b88f9ddf..cc61bc39 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -59,6 +59,7 @@ export interface ViewPageProps {useCustomAccessForm: boolean;logoOnAccessForm: boolean;dataroomIndexEnabled?: boolean;+ annotationsEnabled?: boolean;}export const getStaticProps = async (context: GetStaticPropsContext) => {@@ -115,6 +116,10 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {link.document;const teamPlan = team?.plan || "free";+ // Check feature flags for document links+ const featureFlags = await getFeatureFlags({ teamId });+ const annotationsEnabled = featureFlags.annotations;+return {props: {linkData: {@@ -155,6 +160,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {logoOnAccessForm:teamId === "cm7nlkrhm0000qgh0nvyrrywr" ||teamId === "clup33by90000oewh4rfvp2eg",+ annotationsEnabled,},revalidate: brand || recordMap ? 10 : 60,};@@ -188,9 +194,10 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {const { teamId } = link.dataroom;- // Check if dataroomIndex feature flag is enabled+ // Check feature flagsconst featureFlags = await getFeatureFlags({ teamId });const dataroomIndexEnabled = featureFlags.dataroomIndex;+ const annotationsEnabled = featureFlags.annotations;const lastUpdatedAt = link.dataroom.documents.reduce((max, doc) => {return Math.max(@@ -234,6 +241,7 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {teamId === "cm7nlkrhm0000qgh0nvyrrywr" ||teamId === "clup33by90000oewh4rfvp2eg",dataroomIndexEnabled,+ annotationsEnabled,},revalidate: 10,};@@ -261,6 +269,7 @@ export default function ViewPage({useCustomAccessForm,logoOnAccessForm,dataroomIndexEnabled,+ annotationsEnabled,error,notionError,}: ViewPageProps & { error?: boolean; notionError?: boolean }) {@@ -391,6 +400,7 @@ export default function ViewPage({logoOnAccessForm={logoOnAccessForm}token={storedToken}verifiedEmail={verifiedEmail}+ annotationsEnabled={annotationsEnabled}/></>);diff --git a/prisma/migrations/20250915000000_add_annotations/migration.sql b/prisma/migrations/20250915000000_add_annotations/migration.sqlnew file mode 100644index 00000000..1a446f88--- /dev/null+++ b/prisma/migrations/20250915000000_add_annotations/migration.sql@@ -0,0 +1,53 @@+-- CreateTable+CREATE TABLE "AnnotationImage" (+ "id" TEXT NOT NULL,+ "filename" TEXT NOT NULL,+ "url" TEXT NOT NULL,+ "size" INTEGER,+ "mimeType" TEXT,+ "annotationId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "AnnotationImage_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "DocumentAnnotation" (+ "id" TEXT NOT NULL,+ "title" TEXT NOT NULL,+ "content" JSONB NOT NULL,+ "pages" INTEGER[],+ "documentId" TEXT NOT NULL,+ "teamId" TEXT NOT NULL,+ "createdById" TEXT NOT NULL,+ "isVisible" BOOLEAN NOT NULL DEFAULT true,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "DocumentAnnotation_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "AnnotationImage_annotationId_idx" ON "AnnotationImage"("annotationId" ASC);++-- CreateIndex+CREATE INDEX "DocumentAnnotation_createdById_idx" ON "DocumentAnnotation"("createdById" ASC);++-- CreateIndex+CREATE INDEX "DocumentAnnotation_documentId_idx" ON "DocumentAnnotation"("documentId" ASC);++-- CreateIndex+CREATE INDEX "DocumentAnnotation_teamId_idx" ON "DocumentAnnotation"("teamId" ASC);++-- AddForeignKey+ALTER TABLE "AnnotationImage" ADD CONSTRAINT "AnnotationImage_annotationId_fkey" FOREIGN KEY ("annotationId") REFERENCES "DocumentAnnotation"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "DocumentAnnotation" ADD CONSTRAINT "DocumentAnnotation_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "DocumentAnnotation" ADD CONSTRAINT "DocumentAnnotation_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "Document"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "DocumentAnnotation" ADD CONSTRAINT "DocumentAnnotation_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;+diff --git a/prisma/schema/annotation.prisma b/prisma/schema/annotation.prismanew file mode 100644index 00000000..9a891b07--- /dev/null+++ b/prisma/schema/annotation.prisma@@ -0,0 +1,33 @@+model DocumentAnnotation {+ id String @id @default(cuid())+ title String+ content Json // Rich text content stored as JSON (Tiptap/ProseMirror format)+ pages Int[] // Array of page numbers this annotation applies to+ documentId String+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)+ teamId String+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ createdById String+ createdBy User @relation(fields: [createdById], references: [id], onDelete: Cascade)+ isVisible Boolean @default(true) // Allow admin to hide/show annotations+ images AnnotationImage[] // Images attached to this annotation+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([documentId])+ @@index([teamId])+ @@index([createdById])+}++model AnnotationImage {+ id String @id @default(cuid())+ filename String+ url String+ size Int?+ mimeType String?+ annotationId String+ annotation DocumentAnnotation @relation(fields: [annotationId], references: [id], onDelete: Cascade)+ createdAt DateTime @default(now())++ @@index([annotationId])+}diff --git a/prisma/schema/document.prisma b/prisma/schema/document.prismaindex df36886d..73d2512b 100644--- a/prisma/schema/document.prisma+++ b/prisma/schema/document.prisma@@ -27,6 +27,7 @@ model Document {datarooms DataroomDocument[] // Datarooms associated with this documenttags TagItem[]+ annotations DocumentAnnotation[] // Annotations for this document// upload external documentsuploadedDocument DocumentUpload[]diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 034198b1..57f89f17 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -65,6 +65,7 @@ model User {// FAQ systempublishedFaqItems DataroomFaqItem[]+ createdAnnotations DocumentAnnotation[] // Annotations created by this userinstalledIntegrations InstalledIntegration[]}diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prismaindex 45d991e6..54014def 100644--- a/prisma/schema/team.prisma+++ b/prisma/schema/team.prisma@@ -22,6 +22,7 @@ model Team {dataroomFaqItems DataroomFaqItem[]uploadedDocuments DocumentUpload[]Tag Tag[]+ annotations DocumentAnnotation[] // Annotations created by team membersinstalledIntegrations InstalledIntegration[]