Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pin documents #293

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 63 additions & 10 deletions components/documents/document-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { TrashIcon, MoreVertical } from "lucide-react";
import { TrashIcon, MoreVertical, Pin, PinOff } from "lucide-react";
import { mutate } from "swr";
import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";
import Check from "@/components/shared/icons/check";
Expand Down Expand Up @@ -113,6 +113,43 @@ export default function DocumentsCard({
}
};

const pinDocument = async (
document: DocumentWithLinksAndLinkCountAndViewCount,
) => {
const response = await fetch(
`/api/teams/${teamInfo?.currentTeam?.id}/documents/${prismaDocument.id}/pin-document`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
pinned: !document.pinned,
}),
},
);

if (response.ok) {
const { message } = await response.json();
// update document from the cache
mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`, null, {
populateCache: (_, docs) => {
return docs.map((doc: DocumentWithLinksAndLinkCountAndViewCount) => {
if (doc.id === prismaDocument.id) {
return { ...doc, pinned: !doc.pinned };
}
return doc;
});
},
revalidate: false,
});
toast.success(message);
} else {
const { message } = await response.json();
toast.error(message);
}
};

return (
<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-300 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-2 sm:space-x-4">
Expand Down Expand Up @@ -156,7 +193,16 @@ export default function DocumentsCard({
)}
</button>
</div>
{prismaDocument.pinned && (
<div className="ml-2 sm:ml-3 p-[7px] sm:py-[3px] sm:px-2 rounded-full sm:rounded-md opacity-80 bg-gray-200 dark:bg-gray-700 flex items-center">
<Pin className="w-3 h-3 rotate-45" />
<span className="ml-1 text-xs hidden sm:inline-block">
Pinned
</span>
</div>
)}
</div>

<div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">
<p className="truncate">{timeAgo(prismaDocument.createdAt)}</p>
<p>•</p>
Expand Down Expand Up @@ -200,22 +246,29 @@ export default function DocumentsCard({
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" ref={dropdownRef}>
<DropdownMenuContent align="end" ref={dropdownRef} className="w-[180px]">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuSeparator />

<DropdownMenuItem
onClick={(event) => handleButtonClick(event, prismaDocument.id)}
className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
>
{isFirstClick ? (
"Really delete?"
<DropdownMenuItem onClick={() => pinDocument(prismaDocument)}>
{prismaDocument.pinned ? (
<>
<PinOff className="w-4 h-4 mr-2" />
Unpin document
</>
) : (
<>
<TrashIcon className="w-4 h-4 mr-2" /> Delete document
<Pin className="w-4 h-4 mr-2" />
Pin document
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={(event) => handleButtonClick(event, prismaDocument.id)}
className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200"
>
<TrashIcon className="w-4 h-4 mr-2" />
{isFirstClick ? "Really delete?" : "Delete document"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
Expand Down
58 changes: 58 additions & 0 deletions pages/api/teams/[teamId]/documents/[id]/pin-document.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import prisma from "@/lib/prisma";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { CustomUser } from "@/lib/types";
import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { errorhandler } from "@/lib/errorHandler";

export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method === "POST") {
// GET /api/teams/:teamId/documents/:id/pin-document
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 {
await getTeamWithUsersAndDocument({
teamId,
userId,
docId,
checkOwner: true,
options: {
select: {
id: true,
ownerId: true,
},
},
});

await prisma.document.update({
where: {
id: docId,
},
data: {
pinned: req.body.pinned,
},
});

return res.status(200).json({
message: req.body.pinned ? "Pinned document!" : "Unpinned document!",
});
} catch (error) {
errorhandler(error, res);
}
} else {
// We only allow POST requests
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
1 change: 1 addition & 0 deletions pages/api/teams/[teamId]/documents/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export default async function handle(
storageType,
ownerId: (session.user as CustomUser).id,
teamId: teamId,
pinned: false,
links: {
create: {},
},
Expand Down
20 changes: 11 additions & 9 deletions pages/documents/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,17 @@ export default function Documents() {
{/* Documents list */}
<ul role="list" className="space-y-4">
{documents
? documents.map((document) => {
return (
<DocumentCard
key={document.id}
document={document}
teamInfo={teamInfo}
/>
);
})
? documents
.sort((a, b) => (a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1))
.map((document) => {
return (
<DocumentCard
key={document.id}
document={document}
teamInfo={teamInfo}
/>
);
})
: Array.from({ length: 3 }).map((_, i) => (
<li
key={i}
Expand Down
2 changes: 2 additions & 0 deletions prisma/migrations/20240113052250_pin_document/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Document" ADD COLUMN "pinned" BOOLEAN DEFAULT false;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ model Document {
views View[]
versions DocumentVersion[]
conversations Conversation[]
pinned Boolean? @default(false)

@@index([ownerId])
@@index([teamId])
Expand Down