Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add reactions
Marc Seitz468c4ed161a7
diff --git a/components/documents/stats-card.tsx b/components/documents/stats-card.tsxindex ec3770b1..06232578 100644--- a/components/documents/stats-card.tsx+++ b/components/documents/stats-card.tsx@@ -20,6 +20,13 @@ export default function StatsCard() {);}+ const groupedReactionsTotal =+ stats?.groupedReactions+ .reduce((accumulator, item) => {+ return accumulator + item._count.type;+ }, 0)+ .toString() ?? "0";+const statistics = [{name: "Number of visits",@@ -27,8 +34,8 @@ export default function StatsCard() {active: true,},{- name: "Number of unique visitors",- value: stats?.groupedViews.length.toString() ?? "0",+ name: "Number of reactions",+ value: groupedReactionsTotal,active: true,},{diff --git a/components/view/PagesViewer.tsx b/components/view/PagesViewer.tsxindex bfd9f30d..d174d94f 100644--- a/components/view/PagesViewer.tsx+++ b/components/view/PagesViewer.tsx@@ -4,6 +4,7 @@ import Image from "next/image";import LoadingSpinner from "../ui/loading-spinner";import BlankImg from "@/public/_static/blank.gif";import Nav from "./nav";+import Toolbar from "./toolbar";const DEFAULT_PRELOADED_IMAGES_NUM = 10;@@ -196,6 +197,7 @@ export default function PagesViewer({<LoadingSpinner className="h-20 w-20 text-foreground" />)}</div>+ <Toolbar viewId={viewId} pageNumber={pageNumber} /></div></>);diff --git a/components/view/access-form/index.tsx b/components/view/access-form/index.tsxindex 5422f274..0b975c07 100644--- a/components/view/access-form/index.tsx+++ b/components/view/access-form/index.tsx@@ -2,6 +2,7 @@ import { useEffect } from "react";import PasswordSection from "./password-section";import EmailSection from "./email-section";import { Button } from "@/components/ui/button";+import Toolbar from "../toolbar";export const DEFAULT_ACCESS_FORM_DATA = {email: null,diff --git a/components/view/toolbar.tsx b/components/view/toolbar.tsxnew file mode 100644index 00000000..1c4f4833--- /dev/null+++ b/components/view/toolbar.tsx@@ -0,0 +1,84 @@+import { useState } from "react";+import { Avatar, AvatarFallback } from "../ui/avatar";+import UserRound from "../shared/icons/user-round";+import { REACTIONS } from "@/lib/constants";++function getKeyByValue(object: { [x: string]: any }, value: any) {+ return Object.keys(object).find((key) => object[key] === value);+}++export default function Toolbar({+ viewId,+ pageNumber,+}: {+ viewId: string;+ pageNumber: number;+}) {+ const [flyEmojis, setFlyEmojis] = useState<string>("");++ const handleEmojiClick = async (emoji: string) => {+ // First, reset the state to ensure the same emoji can reappear+ setFlyEmojis("");++ await fetch("/api/record_reaction", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ viewId: viewId,+ type: getKeyByValue(REACTIONS, emoji) as string,+ pageNumber: pageNumber,+ }),+ });++ // Use setTimeout to allow the state reset to take effect before setting the new emoji+ setTimeout(() => {+ setFlyEmojis(emoji);+ }, 10); // Short delay to allow the state reset to take effect+ };++ const Emoji = (props: any) => (+ <button+ className="emoji text-2xl leading-6 hover:bg-gray-800 rounded-full p-2"+ role="img"+ aria-label={props.label ? props.label : ""}+ aria-hidden={props.label ? "false" : "true"}+ onClick={() => handleEmojiClick(props.symbol)}+ >+ {(props.symbol === "π" ||+ props.symbol === "π" ||+ props.symbol === "β€οΈ" ||+ props.symbol === "πΈ") &&+ flyEmojis === props.symbol && (+ <span+ className={`absolute -top-10 left-0 right-0 mx-auto animate-flyEmoji duration-3000`}+ >+ {flyEmojis}+ </span>+ )}+ {props.symbol}+ </button>+ );++ return (+ <>+ <div className="fixed bottom-10 left-1/2 transform -translate-x-1/2 bg-[#333] rounded-full py-1 px-4 flex items-center justify-start space-x-2 shadow-lg z-10">+ <div className="p-1 rounded-full bg-emerald-500 -ml-2">+ <Avatar className="h-6 w-6">+ {/* <AvatarImage src= /> */}+ <AvatarFallback>+ <UserRound />+ </AvatarFallback>+ </Avatar>+ </div>+ <div className="flex items-center">+ <Emoji symbol="β€οΈ" label="heart" />+ <Emoji symbol="πΈ" label="money" />+ <Emoji symbol="π" label="thumbs-up" />+ <Emoji symbol="π" label="thumbs-down" />+ </div>+ </div>+ </>+ );+}diff --git a/lib/constants.ts b/lib/constants.tsindex 9d757293..3475c2e9 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -16,3 +16,10 @@ export const PAPERMARK_HEADERS = {"Papermark.io - Document sharing infrastructure for the modern web",},};++export const REACTIONS = {+ heart: "β€οΈ",+ money: "πΈ",+ thumbsUp: "π",+ thumbsDown: "π",+};diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.tsindex 3d812904..d08507f3 100644--- a/lib/swr/use-stats.ts+++ b/lib/swr/use-stats.ts@@ -12,6 +12,7 @@ interface GroupedView {interface StatsData {views: View[];groupedViews: GroupedView[];+ groupedReactions: { type: string; _count: { type: number } }[];duration: {data: { versionNumber: number; pageNumber: string; avg_duration: number }[];};diff --git a/pages/api/record_reaction.ts b/pages/api/record_reaction.tsnew file mode 100644index 00000000..440e243f--- /dev/null+++ b/pages/api/record_reaction.ts@@ -0,0 +1,45 @@+import { NextApiRequest, NextApiResponse } from "next";+import prisma from "@/lib/prisma";+import { checkPassword, log } from "@/lib/utils";+import { trackAnalytics } from "@/lib/analytics";+import { client } from "@/trigger";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ // We only allow POST requests+ if (req.method !== "POST") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ // POST /api/record_reaction++ const { viewId, pageNumber, type } = req.body as {+ viewId: string;+ pageNumber: number;+ type: string;+ };++ try {+ const reaction = await prisma.reaction.create({+ data: {+ viewId,+ pageNumber,+ type,+ },+ });++ if (!reaction) {+ res.status(500).json({ message: "Internal Server Error" });+ return;+ }++ res.status(200).json({ message: "Reaction recorded" });+ return;+ } catch (error) {+ res.status(500).json({ message: "Internal Server Error" });+ return;+ }+}diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex db62a49f..a0fc6032 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -9,7 +9,7 @@ import { errorhandler } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,- res: NextApiResponse+ res: NextApiResponse,) {if (req.method === "GET") {// GET /api/teams/:teamId/documents/:id/stats@@ -43,6 +43,14 @@ export default async function handle(_count: { id: true },});+ const groupedReactions = await prisma.reaction.groupBy({+ by: ["type"],+ where: { view: { documentId: docId } },+ _count: { type: true },+ });++ console.log("groupedReactions", groupedReactions);+const duration = await getTotalAvgPageDuration({documentId: docId,since: 0,@@ -50,10 +58,16 @@ export default async function handle(const total_duration = duration.data.reduce((totalDuration, data) => totalDuration + data.avg_duration,- 0+ 0,);- const stats = { views, groupedViews, duration, total_duration };+ const stats = {+ views,+ groupedViews,+ duration,+ total_duration,+ groupedReactions,+ };return res.status(200).json(stats);} catch (error) {diff --git a/prisma/migrations/20231207081407_add_reactions/migration.sql b/prisma/migrations/20231207081407_add_reactions/migration.sqlnew file mode 100644index 00000000..ded6bfc3--- /dev/null+++ b/prisma/migrations/20231207081407_add_reactions/migration.sql@@ -0,0 +1,16 @@+-- CreateTable+CREATE TABLE "Reaction" (+ "id" TEXT NOT NULL,+ "viewId" TEXT NOT NULL,+ "pageNumber" INTEGER NOT NULL,+ "type" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "Reaction_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "Reaction_viewId_idx" ON "Reaction"("viewId");++-- AddForeignKey+ALTER TABLE "Reaction" ADD CONSTRAINT "Reaction_viewId_fkey" FOREIGN KEY ("viewId") REFERENCES "View"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 3ec594a0..96b345a8 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -98,7 +98,7 @@ model VerificationToken {@@unique([identifier, token])}-model Document {+model Document {id String @id @default(cuid())name Stringdescription String?@@ -196,18 +196,30 @@ model Domain {}model View {- id String @id @default(cuid())- link Link @relation(fields: [linkId], references: [id])+ id String @id @default(cuid())+ link Link @relation(fields: [linkId], references: [id])linkId String- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)documentId StringviewerEmail String? // Email of the viewer if known- viewedAt DateTime @default(now())+ viewedAt DateTime @default(now())+ reactions Reaction[]@@index([linkId])@@index([documentId])}+model Reaction {+ id String @id @default(cuid())+ view View @relation(fields: [viewId], references: [id], onDelete: Cascade)+ viewId String+ pageNumber Int+ type String // e.g., "like", "dislike", "love", "hate", etc.+ createdAt DateTime @default(now())++ @@index([viewId])+}+model Invitation {email Stringexpires DateTime@@ -250,7 +262,7 @@ model Conversation {createdAt DateTime @default(now())lastMessageAt DateTime? // This is the last time a message was sent in the thread- @@index([threadId])@@unique([userId, documentId])@@unique([threadId, documentId])+ @@index([threadId])}diff --git a/tailwind.config.js b/tailwind.config.jsindex ea6005d0..43e4bc72 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -159,10 +159,21 @@ module.exports = {from: { "stroke-dashoffset": "332", opacity: "0" },to: { opacity: "1" },},+ flyEmoji: {+ "0%": {+ transform: "translateY(0) scale(1)",+ opacity: "0.7",+ },+ "100%": {+ transform: "translateY(-150px) scale(2)",+ opacity: "0",+ },+ },},animation: {gauge_fadeIn: "gauge_fadeIn 1s ease forwards",gauge_fill: "gauge_fill 1s ease forwards",+ flyEmoji: "flyEmoji 1s forwards",},},},@@ -203,4 +214,4 @@ module.exports = {require("tailwindcss-animate"),require("@tailwindcss/typography"),],-};\ No newline at end of file+};