Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
add button to open assistant
Marc Seitz9ad2f8935152
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsxindex daf8f6d5..784869d5 100644--- a/components/documents/document-card.tsx+++ b/components/documents/document-card.tsx@@ -1,21 +1,21 @@-import {- copyToClipboard,- getExtension,- nFormatter,- timeAgo,-} from "@/lib/utils";+import { copyToClipboard, nFormatter, timeAgo } from "@/lib/utils";import Link from "next/link";import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";import Copy from "@/components/shared/icons/copy";import BarChart from "@/components/shared/icons/bar-chart";import Image from "next/image";import NotionIcon from "@/components/shared/icons/notion";+import PapermarkSparkle from "../shared/icons/papermark-sparkle";+import { toast } from "sonner";+import { useRouter } from "next/router";export default function DocumentsCard({document,}: {document: DocumentWithLinksAndLinkCountAndViewCount;}) {+ const router = useRouter();+function handleCopyToClipboard(id: string) {copyToClipboard(`${process.env.NEXT_PUBLIC_BASE_URL}/view/${id}`,@@ -23,8 +23,34 @@ export default function DocumentsCard({);}+ const activateOrRedirectAssistant = async () => {+ if (document.assistantEnabled) {+ router.push(`/documents/${document.id}/chat`);+ } else {+ toast.promise(+ fetch("/api/assistants", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: document.id,+ }),+ }).then(() => {+ // Once the assistant is activated, redirect to the chat+ router.push(`/documents/${document.id}/chat`);+ }),+ {+ loading: "Activating Assistant...",+ success: "Papermark Assistant successfully activated.",+ error: "Activation failed. Please try again.",+ },+ );+ }+ };+return (- <li className="relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-200 dark:ring-gray-700 transition-all hover:ring-gray-400 hover:dark:ring-gray-500 hover:bg-secondary sm:p-4 flex justify-between items-center">+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-200 dark:ring-gray-700 transition-all hover:ring-gray-400 hover:dark:ring-gray-500 hover:bg-secondary sm:p-4 flex justify-between items-center"><div className="min-w-0 flex shrink items-center space-x-4"><div className="w-8 mx-1 text-center flex justify-center items-center">{document.type === "notion" ? (@@ -76,19 +102,34 @@ export default function DocumentsCard({</div></div>- <Link- onClick={(e) => {- e.stopPropagation();- }}- href={`/documents/${document.id}`}- className="flex items-center z-10 space-x-1 rounded-md bg-gray-200 dark:bg-gray-700 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"- >- <BarChart className="h-4 w-4 text-muted-foreground" />- <p className="whitespace-nowrap text-sm text-muted-foreground">- {nFormatter(document._count.views)}- <span className="ml-1 hidden sm:inline-block">views</span>- </p>- </Link>+ <div className="flex flex-row space-x-2">+ <button+ onClick={(e) => {+ e.stopPropagation();+ activateOrRedirectAssistant();+ }}+ className="group/button flex items-center z-10 space-x-1 rounded-md ring-1 ring-gray-200 dark:ring-gray-700 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-95"+ >+ <PapermarkSparkle className="h-4 w-4 text-gray-400 group-hover/row:text-foreground group-hover/row:animate-pulse group-hover/button:text-white group-hover/button:animate-none" />+ <span className="whitespace-nowrap text-sm ml-1 hidden sm:inline-block text-gray-400 group-hover/button:text-white">+ AI Assistant+ </span>+ </button>++ <Link+ onClick={(e) => {+ e.stopPropagation();+ }}+ href={`/documents/${document.id}`}+ className="flex items-center z-10 space-x-1 rounded-md bg-gray-200 dark:bg-gray-700 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"+ >+ <BarChart className="h-4 w-4 text-muted-foreground" />+ <p className="whitespace-nowrap text-sm text-muted-foreground">+ {nFormatter(document._count.views)}+ <span className="ml-1 hidden sm:inline-block">views</span>+ </p>+ </Link>+ </div></li>);}diff --git a/components/ui/button.tsx b/components/ui/button.tsxindex 8c5ebaf0..f8114671 100644--- a/components/ui/button.tsx+++ b/components/ui/button.tsx@@ -6,19 +6,21 @@ import { cn } from "@/lib/utils";import LoadingSpinner from "./loading-spinner";const buttonVariants = cva(- "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",+ "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants: {variant: {- default: "bg-primary text-primary-foreground hover:bg-primary/90",+ default:+ "bg-primary text-primary-foreground hover:bg-primary/90 transition-colors",+ special: "text-white",destructive:- "bg-destructive text-destructive-foreground hover:bg-destructive/90",+ "bg-destructive text-destructive-foreground hover:bg-destructive/90 transition-colors",outline:- "border border-input bg-background hover:bg-accent hover:text-accent-foreground",+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors",secondary:- "bg-secondary text-secondary-foreground hover:bg-secondary/80",- ghost: "hover:bg-accent hover:text-accent-foreground",- link: "text-primary underline-offset-4 hover:underline",+ "bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-colors",+ ghost: "hover:bg-accent hover:text-accent-foreground transition-colors",+ link: "text-primary underline-offset-4 hover:underline transition-colors",},size: {default: "h-10 px-4 py-2",@@ -31,7 +33,7 @@ const buttonVariants = cva(variant: "default",size: "default",},- }+ },);export interface ButtonProps@@ -42,7 +44,10 @@ export interface ButtonProps}const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(- ({ className, variant, size, disabled, loading, asChild = false, ...props }, ref) => {+ (+ { className, variant, size, disabled, loading, asChild = false, ...props },+ ref,+ ) => {const Comp = asChild ? Slot : "button";return (<Comp@@ -55,7 +60,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>({props.children}</Comp>);- }+ },);Button.displayName = "Button";diff --git a/pages/documents/[id]/chat.tsx b/pages/documents/[id]/chat.tsxnew file mode 100644index 00000000..db26a0d6--- /dev/null+++ b/pages/documents/[id]/chat.tsx@@ -0,0 +1,122 @@+import { type Message } from "ai/react";+import prisma from "@/lib/prisma";+import { getServerSession } from "next-auth";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import { Chat } from "@/components/chat/chat";+import Sparkle from "@/components/shared/icons/sparke";++export const getServerSideProps = async (context: any) => {+ const { id } = context.params;+ const session = await getServerSession(context.req, context.res, authOptions);++ if (!session) {+ return {+ redirect: {+ permanent: false,+ destination: `/login?next=/view/${id}/chat`,+ },+ };+ }++ const document = await prisma.document.findUnique({+ where: { id },+ select: {+ id: true,+ versions: {+ where: { isPrimary: true },+ select: {+ pages: {+ where: { pageNumber: 1 },+ select: {+ file: true,+ },+ },+ },+ },+ },+ });++ if (!document) {+ return {+ notFound: true,+ };+ }++ // create or fetch threadId+ const res = await fetch(+ `${process.env.NEXTAUTH_URL}/api/assistants/threads`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: document.id,+ userId: (session.user as CustomUser).id,+ }),+ },+ );++ if (!res.ok) {+ return {+ notFound: true,+ };+ }++ const { threadId, messages } = await res.json();++ return {+ props: {+ threadId,+ messages: messages || [],+ firstPage: document.versions[0].pages[0].file,+ },+ };+};++export default function ChatPage({+ threadId,+ messages,+ firstPage,+}: {+ threadId: string;+ messages: Message[];+ firstPage: string;+}) {+ return (+ <>+ <Nav />+ <Chat+ initialMessages={messages}+ threadId={threadId}+ firstPage={firstPage}+ />+ </>+ );+}++function Nav() {+ return (+ <nav className="bg-black fixed top-0 inset-x-0 z-10">+ <div className="mx-auto px-2 sm:px-6 lg:px-8">+ <div className="relative flex h-16 items-center justify-between">+ <div className="flex flex-1 items-center justify-center sm:items-stretch sm:justify-start">+ <div className="flex flex-shrink-0 items-center gap-x-2">+ <p className="text-2xl font-bold tracking-tighter text-white">+ Papermark+ </p>+ <Sparkle className="h-5 w-5 text-white" />+ </div>+ </div>+ <div className="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0">+ <div className="bg-gray-900 text-white rounded-md px-3 py-2 text-sm font-medium">+ {/* <span>{pageNumber}</span>+ <span className="text-gray-400"> / {numPages}</span> */}+ </div>+ </div>+ </div>+ </div>+ </nav>+ );+}diff --git a/pages/documents/[id].tsx b/pages/documents/[id]/index.tsxsimilarity index 73%rename from pages/documents/[id].tsxrename to pages/documents/[id]/index.tsxindex 1509c43e..6375601a 100644--- a/pages/documents/[id].tsx+++ b/pages/documents/[id]/index.tsx@@ -26,6 +26,8 @@ import MoreVertical from "@/components/shared/icons/more-vertical";import { useTeam } from "@/context/team-context";import ProcessStatusBar from "@/components/documents/process-status-bar";import NotionIcon from "@/components/shared/icons/notion";+import PapermarkSparkle from "@/components/shared/icons/papermark-sparkle";+import { Document } from "@prisma/client";export default function DocumentPage() {const { document: prismaDocument, primaryVersion, error } = useDocument();@@ -159,6 +161,32 @@ export default function DocumentPage() {}};+ const activateOrRedirectAssistant = async (document: Document) => {+ if (document.assistantEnabled) {+ router.push(`/documents/${document.id}/chat`);+ } else {+ toast.promise(+ fetch("/api/assistants", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: document.id,+ }),+ }).then(() => {+ // Once the assistant is activated, redirect to the chat+ router.push(`/documents/${document.id}/chat`);+ }),+ {+ loading: "Activating Assistant...",+ success: "Papermark Assistant successfully activated.",+ error: "Activation failed. Please try again.",+ },+ );+ }+ };+if (error && error.status === 404) {return <ErrorPage statusCode={404} />;}@@ -224,6 +252,53 @@ export default function DocumentPage() {</DropdownMenuTrigger><DropdownMenuContent align="end" ref={dropdownRef}><DropdownMenuLabel>Actions</DropdownMenuLabel>+ {!prismaDocument.assistantEnabled ? (+ <DropdownMenuItem+ onClick={() => {+ const fetchPromise = fetch("/api/assistants", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: prismaDocument.id,+ }),+ });++ toast.promise(fetchPromise, {+ loading: "Activating Assistant...",+ success:+ "Papermark Assistant successfully activated.",+ error: "Activation failed. Please try again.",+ });+ }}+ >+ Activate Assistant+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ onClick={() => {+ const fetchPromise = fetch("/api/assistants", {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: prismaDocument.id,+ }),+ });++ toast.promise(fetchPromise, {+ loading: "Activating Assistant...",+ success:+ "Papermark Assistant successfully activated.",+ error: "Activation failed. Please try again.",+ });+ }}+ >+ Disable Assistant+ </DropdownMenuItem>+ )}<DropdownMenuItemclassName="text-destructive focus:bg-destructive focus:text-destructive-foreground"onClick={(event) =>@@ -233,33 +308,21 @@ export default function DocumentPage() {{isFirstClick ? "Really delete?" : "Delete document"}</DropdownMenuItem>{/* create a dropdownmenuitem that onclick calls a post request to /api/assistants with the documentId */}-- <DropdownMenuItem- className="text-destructive focus:bg-destructive focus:text-destructive-foreground"- onClick={async () =>- await fetch("/api/assistants", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- documentId: prismaDocument.id,- }),- }).then((res) => {- if (res.ok) {- toast.success("Papermark Assistant successfully.");- } else {- toast.error(- "Something went wrong. Please try again.",- );- }- })- }- >- Activate Assistant- </DropdownMenuItem></DropdownMenuContent></DropdownMenu>++ <Button+ className="group space-x-1 bg-gradient-to-r from-[#16222A] via-emerald-500 to-[#16222A] duration-200 ease-linear hover:bg-right"+ variant={"special"}+ style={{+ backgroundSize: "200% auto",+ }}+ onClick={() => activateOrRedirectAssistant(prismaDocument)}+ >+ <PapermarkSparkle className="h-5 w-5 animate-pulse group-hover:animate-none" />{" "}+ <span>AI Assistant</span>+ </Button>+<Button onClick={() => setIsLinkSheetOpen(true)}>Create Link</Button>