Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat(mentions): mentions + notifications for comments (#1508)

bautistaaa4cf5b8e7e1d1
diff --git a/apps/web/src/app/(profile)/[username]/_components/dashboard/challenge-history-columns.tsx b/apps/web/src/app/(profile)/[username]/_components/dashboard/challenge-history-columns.tsx
index 52cc5320..b2e6b2e1 100644
--- a/apps/web/src/app/(profile)/[username]/_components/dashboard/challenge-history-columns.tsx
+++ b/apps/web/src/app/(profile)/[username]/_components/dashboard/challenge-history-columns.tsx
@@ -2,7 +2,7 @@
import { type ColumnDef } from '@tanstack/react-table';
import Link from 'next/link';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import type { HistoricalChallenge } from './_actions';
export const columns: ColumnDef<HistoricalChallenge>[] = [
@@ -18,6 +18,6 @@ export const columns: ColumnDef<HistoricalChallenge>[] = [
{
accessorKey: 'submissionDate',
header: 'Last Submission',
- cell: ({ row }) => getRelativeTime(row.original.submissionDate!),
+ cell: ({ row }) => getRelativeTimeStrict(row.original.submissionDate!),
},
];
diff --git a/apps/web/src/app/(profile)/[username]/_components/dashboard/index.tsx b/apps/web/src/app/(profile)/[username]/_components/dashboard/index.tsx
index fcdf5d03..1fef58ac 100644
--- a/apps/web/src/app/(profile)/[username]/_components/dashboard/index.tsx
+++ b/apps/web/src/app/(profile)/[username]/_components/dashboard/index.tsx
@@ -13,7 +13,7 @@ import {
} from '@repo/ui/components/tabs';
import { Bookmark, CheckCircle, ChevronRightSquare, Play, Settings, Text } from '@repo/ui/icons';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { stripProtocolAndWWW } from '~/utils/stringUtils';
import { type BadgeInfo } from './_actions';
@@ -96,7 +96,7 @@ export function Dashboard({ user, isOwnProfile, badges, children }: Props) {
className="text-muted-foreground tracking-tight"
title={`Joined ${user.createdAt.toString()}`}
>
- Joined {getRelativeTime(user.createdAt)}
+ Joined {getRelativeTimeStrict(user.createdAt)}
</span>
</div>
{Boolean(filteredProfileLinks.length > 0) && (
diff --git a/apps/web/src/app/(profile)/[username]/bookmarks/_components/bookmarked-challenges-columns.tsx b/apps/web/src/app/(profile)/[username]/bookmarks/_components/bookmarked-challenges-columns.tsx
index fd4652a3..e6443ec0 100644
--- a/apps/web/src/app/(profile)/[username]/bookmarks/_components/bookmarked-challenges-columns.tsx
+++ b/apps/web/src/app/(profile)/[username]/bookmarks/_components/bookmarked-challenges-columns.tsx
@@ -1,7 +1,7 @@
'use client';
import { type ColumnDef } from '@tanstack/react-table';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import Link from 'next/link';
import type { BookmarkedChallenge } from '../page';
@@ -18,6 +18,6 @@ export const bookmarkedChallengedColumns: ColumnDef<BookmarkedChallenge>[] = [
{
accessorKey: 'createdAt',
header: 'Date',
- cell: ({ row }) => getRelativeTime(row.original.createdAt!),
+ cell: ({ row }) => getRelativeTimeStrict(row.original.createdAt!),
},
];
diff --git a/apps/web/src/app/(profile)/[username]/page.tsx b/apps/web/src/app/(profile)/[username]/page.tsx
index 550dbaf6..8f4c73e7 100644
--- a/apps/web/src/app/(profile)/[username]/page.tsx
+++ b/apps/web/src/app/(profile)/[username]/page.tsx
@@ -2,7 +2,7 @@ import { buildMetaForDefault, buildMetaForUser } from '~/app/metadata';
import { prisma } from '@repo/db';
import { OverviewTab } from './_components/dashboard/overview-tab';
import { notFound } from 'next/navigation';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
interface Props {
params: {
@@ -57,7 +57,7 @@ export async function generateMetadata({ params: { username: usernameFromQuery }
const avatar = user && user.image ? user.image : '';
const date = user?.createdAt!;
- const dateSince = getRelativeTime(date);
+ const dateSince = getRelativeTimeStrict(date);
if (username)
return buildMetaForUser({
diff --git a/apps/web/src/app/(profile)/[username]/shared-solutions/_components/shared-solutions-columns.tsx b/apps/web/src/app/(profile)/[username]/shared-solutions/_components/shared-solutions-columns.tsx
index b498e19a..1ad9e65b 100644
--- a/apps/web/src/app/(profile)/[username]/shared-solutions/_components/shared-solutions-columns.tsx
+++ b/apps/web/src/app/(profile)/[username]/shared-solutions/_components/shared-solutions-columns.tsx
@@ -1,7 +1,7 @@
'use client';
import { type ColumnDef } from '@tanstack/react-table';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import Link from 'next/link';
import type { SharedSolution } from '../page';
@@ -34,6 +34,6 @@ export const sharedSolutionsColumns: ColumnDef<SharedSolution>[] = [
{
accessorKey: 'createdAt',
header: 'Date',
- cell: ({ row }) => getRelativeTime(row.original.createdAt),
+ cell: ({ row }) => getRelativeTimeStrict(row.original.createdAt),
},
];
diff --git a/apps/web/src/app/challenge/[slug]/comments/[commentId]/page.tsx b/apps/web/src/app/challenge/[slug]/comments/[commentId]/page.tsx
index 60b9b602..8ffaa734 100644
--- a/apps/web/src/app/challenge/[slug]/comments/[commentId]/page.tsx
+++ b/apps/web/src/app/challenge/[slug]/comments/[commentId]/page.tsx
@@ -23,7 +23,7 @@ export default async function CommentPage({ params: { slug, commentId } }: Props
<div className="relative h-full">
<Description challenge={challenge} />
<Comments
- rootId={challenge.id}
+ root={challenge}
preselectedCommentMetadata={preselectedCommentMetadata}
type="CHALLENGE"
expanded
diff --git a/apps/web/src/app/challenge/[slug]/page.tsx b/apps/web/src/app/challenge/[slug]/page.tsx
index b16239b8..629a6d70 100644
--- a/apps/web/src/app/challenge/[slug]/page.tsx
+++ b/apps/web/src/app/challenge/[slug]/page.tsx
@@ -1,6 +1,6 @@
import { type Session } from '@repo/auth/server';
import { buildMetaForChallenge, buildMetaForEventPage } from '~/app/metadata';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { Comments } from '../_components/comments';
import { Description } from '../_components/description';
import { AOT_CHALLENGES } from './aot-slugs';
@@ -29,7 +29,7 @@ export async function generateMetadata({ params: { slug } }: Props) {
description,
username: challenge.user.name,
difficulty: challenge.difficulty,
- date: getRelativeTime(challenge.createdAt),
+ date: getRelativeTimeStrict(challenge.createdAt),
});
}
@@ -41,7 +41,7 @@ export default async function Challenges({ params: { slug } }: Props) {
return (
<div className="relative h-full ">
<Description challenge={challenge} />
- <Comments rootId={challenge.id} type="CHALLENGE" />
+ <Comments root={challenge} type="CHALLENGE" />
</div>
);
}
diff --git a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
index 179ebda1..fb69d37a 100644
--- a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
+++ b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/comments/[commentId]/page.tsx
@@ -27,7 +27,7 @@ export default async function SolutionPageComments({
<div className="relative h-full">
<SolutionDetails solution={solution} />
<Comments
- rootId={Number(solutionId)}
+ root={solution}
type="SOLUTION"
preselectedCommentMetadata={preselectedCommentMetadata}
expanded
diff --git a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
index c6d43990..4f097380 100644
--- a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
+++ b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/getSolutionIdRouteData.ts
@@ -3,6 +3,8 @@ import { prisma } from '@repo/db';
import { type Session } from '@repo/auth/server';
import { redirect } from 'next/navigation';
+export type SolutionRouteData = NonNullable<Awaited<ReturnType<typeof getSolutionIdRouteData>>>;
+
export const getSolutionIdRouteData = cache(
async (slug: string, solutionId: string, session: Session | null) => {
const challenge = await prisma.challenge.findFirstOrThrow({
@@ -17,6 +19,7 @@ export const getSolutionIdRouteData = cache(
include: {
user: {
select: {
+ id: true,
name: true,
image: true,
roles: true,
diff --git a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/page.tsx b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/page.tsx
index b51b0688..fbf2a264 100644
--- a/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/page.tsx
+++ b/apps/web/src/app/challenge/[slug]/solutions/[solutionId]/page.tsx
@@ -20,7 +20,7 @@ export default async function SolutionPage({ params: { solutionId, slug } }: Pro
return (
<div className="relative h-full">
<SolutionDetails solution={solution} />
- <Comments rootId={solution.id} type="SOLUTION" />
+ <Comments root={solution} type="SOLUTION" />
</div>
);
}
diff --git a/apps/web/src/app/challenge/[slug]/solutions/_components/index.tsx b/apps/web/src/app/challenge/[slug]/solutions/_components/index.tsx
index f86a7484..d31bc55b 100644
--- a/apps/web/src/app/challenge/[slug]/solutions/_components/index.tsx
+++ b/apps/web/src/app/challenge/[slug]/solutions/_components/index.tsx
@@ -8,7 +8,7 @@ import { SolutionEditor } from './solution-editor';
import { NoSolutions } from './nosolutions';
import { SubmitSolution } from './submit-solution';
import { type PaginatedSolution, getPaginatedSolutions } from '../getSolutionRouteData';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { Badge } from '@repo/ui/components/badge';
import { useParams } from 'next/navigation';
import { Pagination } from '../../../_components/pagination';
@@ -169,7 +169,7 @@ function SolutionRow({
/>
<div className="text-muted-foreground flex flex-1 items-center gap-2">
<Calendar className=" h-4 w-4" />
- <span className="text-xs">{getRelativeTime(solution.createdAt)}</span>
+ <span className="text-xs">{getRelativeTimeStrict(solution.createdAt)}</span>
</div>
{solution.isPinned ? (
<Badge className="dark:bg-difficulty-beginner-dark bg-difficulty-beginner text-white duration-300 dark:text-black">
diff --git a/apps/web/src/app/challenge/[slug]/solutions/_components/solution-detail.tsx b/apps/web/src/app/challenge/[slug]/solutions/_components/solution-detail.tsx
index 450964dc..4a67ce89 100644
--- a/apps/web/src/app/challenge/[slug]/solutions/_components/solution-detail.tsx
+++ b/apps/web/src/app/challenge/[slug]/solutions/_components/solution-detail.tsx
@@ -13,7 +13,7 @@ import clsx from 'clsx';
import Link from 'next/link';
import type { ChallengeSolution } from '~/app/challenge/[slug]/solutions/[solutionId]/page';
import { ReportDialog } from '~/components/ReportDialog';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { Vote } from '../../../_components/vote';
import { pinOrUnpinSolution } from './_actions';
import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';
@@ -97,11 +97,13 @@ export function SolutionDetails({ solution }: Props) {
/>
<div className="text-muted-foreground flex items-center gap-2">
<Calendar className="h-4 w-4" />
- <span className="text-xs">{getRelativeTime(solution.createdAt)}</span>
+ <span className="text-xs">{getRelativeTimeStrict(solution.createdAt)}</span>
</div>
</div>
<div className="flex items-center gap-3">
<Vote
+ challengeSlug={solution.challenge?.slug ?? ''}
+ toUserId={solution.user?.id!}
voteCount={solution._count.vote}
initialHasVoted={solution.vote.length > 0}
disabled={!session?.user?.id || solution.userId === session?.user?.id}
diff --git a/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx b/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
index ddadac28..fd56bbcb 100644
--- a/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
+++ b/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/index.tsx
@@ -6,7 +6,7 @@ import clsx from 'clsx';
import Link from 'next/link';
import { useMemo, useState } from 'react';
import NoSubmissions from './nosubmissions';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import type { ChallengeSubmissions } from '../page';
import { useParams } from 'next/navigation';
@@ -90,7 +90,7 @@ function SubmissionRow({ submission }: { submission: Submission }) {
</div>
<div className="text-muted-foreground flex items-center gap-2">
<Calendar className=" h-4 w-4" />
- <span className="text-xs">{getRelativeTime(submission.createdAt)}</span>
+ <span className="text-xs">{getRelativeTimeStrict(submission.createdAt)}</span>
</div>
</Link>
</li>
diff --git a/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx b/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
index 4725b3e0..11ea9af3 100644
--- a/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
+++ b/apps/web/src/app/challenge/[slug]/submissions/[[...catchAll]]/_components/overview.tsx
@@ -6,7 +6,7 @@ import { useQuery } from '@tanstack/react-query';
import lzstring from 'lz-string';
import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { AOT_CHALLENGES } from '../../../aot-slugs';
import { getChallengeSubmissionById } from '../getChallengeSubmissions';
import { Suggestions } from './suggestions';
@@ -95,7 +95,7 @@ export function SubmissionOverview({ submissionId }: Props) {
{submission.isSuccessful ? 'Accepted' : 'Rejected'}
</div>
<div className="px-3 text-sm text-neutral-500">
- Submitted {getRelativeTime(submission.createdAt)}
+ Submitted {getRelativeTimeStrict(submission.createdAt)}
</div>
</div>
{!isAotChallenge && (
diff --git a/apps/web/src/app/challenge/_components/comments/comment-input.tsx b/apps/web/src/app/challenge/_components/comments/comment-input.tsx
index 93839150..c5ab8cac 100644
--- a/apps/web/src/app/challenge/_components/comments/comment-input.tsx
+++ b/apps/web/src/app/challenge/_components/comments/comment-input.tsx
@@ -2,12 +2,12 @@ import { Loader2 } from '@repo/ui/icons';
import { useSession } from '@repo/auth/react';
import { useEffect, useRef, useState, type RefObject } from 'react';
import { Button } from '@repo/ui/components/button';
-import { Textarea } from '@repo/ui/components/textarea';
import { Markdown } from '@repo/ui/components/markdown';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Form, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
import { singleFieldSchema, type SingleFieldSchema } from '~/utils/zodSingleStringField';
+import { MentionInput } from '~/components/mention/mention-input';
interface Props {
mode: 'create' | 'edit' | 'reply';
@@ -54,7 +54,7 @@ export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultVal
name="text"
render={({ field }) => (
<FormItem>
- <Textarea
+ <MentionInput
disabled={!session?.user}
autoFocus
className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"
@@ -65,11 +65,6 @@ export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultVal
onKeyDown={(e) => {
if (isSubmitting) {
e.preventDefault();
- return;
- }
- if (e.key === 'Enter' && e.shiftKey) {
- form.handleSubmit(submitComment);
- e.preventDefault();
}
}}
placeholder={
@@ -77,7 +72,7 @@ export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultVal
? 'You need to be logged in to comment.'
: 'Enter your comment here.'
}
- ref={textAreaRef}
+ forwardedref={textAreaRef}
value={value}
/>
<FormMessage className="absolute h-8 pl-3 leading-8" />
diff --git a/apps/web/src/app/challenge/_components/comments/comment.action.ts b/apps/web/src/app/challenge/_components/comments/comment.action.ts
index 2714042f..39b55f58 100644
--- a/apps/web/src/app/challenge/_components/comments/comment.action.ts
+++ b/apps/web/src/app/challenge/_components/comments/comment.action.ts
@@ -1,65 +1,187 @@
'use server';
-import { auth } from '~/server/auth';
import { prisma } from '@repo/db';
-import type { Comment, CommentRoot, PrismaClient } from '@repo/db/types';
+import { auth } from '~/server/auth';
import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';
+import type { ChallengeRouteData } from '../../[slug]/getChallengeRouteData';
+import type { SolutionRouteData } from '../../[slug]/solutions/[solutionId]/getSolutionIdRouteData';
+import type { PaginatedComments } from './getCommentRouteData';
+import { getMentionsFromComment } from './getMentionsFromComment';
/**
- *
* @param comment a Challenge or Solution-based comment.
* @returns the prisma create response.
*/
-interface CommentToCreate {
- text: string;
- rootType: CommentRoot;
- rootId: number;
-}
+type CommentToCreate =
+ | {
+ text: string;
+ rootType: 'CHALLENGE';
+ root: ChallengeRouteData['challenge'];
+ }
+ | {
+ text: string;
+ rootType: 'SOLUTION';
+ root: SolutionRouteData;
+ };
+
export async function addComment(comment: CommentToCreate) {
const session = await auth();
if (!session?.user?.id) return 'unauthorized';
if (comment.text.length === 0) return 'text_is_empty';
- if (!session.user.id) return 'unauthorized';
- if (comment.text.length === 0) return 'text_is_empty';
- const { rootId, ...commentToCreate } = {
- ...comment,
+ const commentToCreate = {
+ text: comment.text,
+ rootType: comment.rootType,
...(comment.rootType === 'CHALLENGE'
- ? { rootChallengeId: comment.rootId }
- : { rootSolutionId: comment.rootId }),
+ ? { rootChallengeId: comment.root.id }
+ : { rootSolutionId: comment.root.id }),
};
- return await prisma.comment.create({
+ const commentThatWasCreated = await prisma.comment.create({
data: {
...commentToCreate,
userId: session.user.id,
},
});
+
+ const url =
+ comment.rootType === 'CHALLENGE'
+ ? // /challenge/challenge-slug/comments/26
+ `/challenge/${comment.root?.slug}/comments/${comment.root.id}`
+ : // /challenge/challenge-slug/solutions/1/comments/32
+ `/challenge/${comment.root?.challenge?.slug}/solutions/${comment.root.id}/comments/${commentThatWasCreated.id}`;
+ const replyNotificationPromise =
+ // dont notify yourself by commenting on your own solution/challenge
+ session.user.id !== comment.root.userId
+ ? [
+ prisma.notification.create({
+ data: {
+ type: 'REPLY',
+ url,
+ commentId: commentThatWasCreated.id,
+ fromUserId: session.user.id,
+ toUserId: comment.root.userId!,
+ },
+ }),
+ ]
+ : [];
+ // don't notify the solution/challenge author if they are mentioned to avoid double notifications or the comment author since they
+ // shouldn't be able to notify themselves (e.g: tag themselves in their own comment)
+ const mentions = getMentionsFromComment(commentToCreate.text).filter(
+ (mention) =>
+ mention?.toLowerCase() !== comment.root.user?.name.toLowerCase() &&
+ mention?.toLowerCase() !== session.user.name.toLowerCase(),
+ );
+
+ // don't block on notification logic
+ Promise.all([
+ ...mentions.map(async (mention) => {
+ const validMention = await prisma.user.findFirst({
+ where: {
+ name: mention,
+ },
+ });
+
+ if (!validMention) {
+ return Promise.resolve();
+ }
+
+ return prisma.notification.create({
+ data: {
+ type: 'MENTION',
+ url,
+ commentId: commentThatWasCreated.id,
+ fromUserId: session.user.id,
+ toUserId: validMention.id,
+ },
+ });
+ }),
+ ...replyNotificationPromise,
+ ]).catch(console.error);
}
-export async function replyComment(comment: CommentToCreate, parentId: number) {
+export async function replyComment(
+ comment: CommentToCreate,
+ parentComment: PaginatedComments['comments'][number],
+) {
const session = await auth();
if (!session?.user?.id) return 'unauthorized';
if (comment.text.length === 0) return 'text_is_empty';
- if (!session.user.id) return 'unauthorized';
- if (comment.text.length === 0) return 'text_is_empty';
- const { rootId, ...commentToCreate } = {
- ...comment,
+ const replyToCreate = {
+ text: comment.text,
+ rootType: comment.rootType,
...(comment.rootType === 'CHALLENGE'
- ? { rootChallengeId: comment.rootId }
- : { rootSolutionId: comment.rootId }),
+ ? { rootChallengeId: comment.root.id }
+ : { rootSolutionId: comment.root.id }),
};
- return await prisma.comment.create({
+ const replyThatWasCreated = await prisma.comment.create({
data: {
- ...commentToCreate,
- parentId,
+ ...replyToCreate,
+ parentId: parentComment.id,
userId: session.user.id,
},
});
+
+ const url =
+ parentComment.rootType === 'CHALLENGE'
+ ? // /challenge/challenge-slug/comments/26?replyId=33
+ `/challenge/${parentComment.rootChallenge?.slug}/comments/${parentComment.id}?replyId=${replyThatWasCreated.id}`
+ : // /challenge/challenge-slug/solutions/1/comments/32?replyId=35
+ `/challenge/${parentComment.rootSolution?.challenge?.slug}/solutions/${parentComment.rootSolutionId}/comments/${parentComment.id}?replyId=${replyThatWasCreated.id}`;
+
+ const replyNotificationPromise =
+ // dont notify yourself if you reply to your own comment
+ session.user.id !== parentComment.userId
+ ? [
+ prisma.notification.create({
+ data: {
+ type: 'REPLY',
+ commentId: replyThatWasCreated.id,
+ url,
+ fromUserId: session.user.id,
+ toUserId: parentComment.userId,
+ },
+ }),
+ ]
+ : [];
+
+ // don't notify the parent comment author if they are mentioned to avoid double notifications or the comment author since they
+ // shouldn't be able to notify themselves (e.g: tag themselves in their own comment)
+ const mentions = getMentionsFromComment(replyToCreate.text).filter(
+ (mention) =>
+ mention?.toLowerCase() != parentComment.user.name.toLowerCase() &&
+ mention?.toLowerCase() != session.user.name.toLowerCase(),
+ );
+
+ // dont block on notification logic
+ Promise.allSettled([
+ ...mentions.map(async (mention) => {
+ const validMention = await prisma.user.findFirst({
+ where: {
+ name: mention,
+ },
+ });
+
+ if (!validMention) {
+ return Promise.resolve();
+ }
+
+ return prisma.notification.create({
+ data: {
+ type: 'MENTION',
+ url,
+ commentId: replyThatWasCreated.id,
+ fromUserId: session.user.id,
+ toUserId: validMention.id,
+ },
+ });
+ }),
+ ...replyNotificationPromise,
+ ]).catch(console.error);
}
export async function updateComment(text: string, id: number) {
@@ -69,6 +191,27 @@ export async function updateComment(text: string, id: number) {
if (text.length === 0) return 'text_is_empty';
const comment = await prisma.comment.findFirstOrThrow({
+ include: {
+ parentComment: {
+ include: {
+ rootChallenge: true,
+ rootSolution: true,
+ },
+ },
+ rootSolution: {
+ select: {
+ id: true,
+ user: true,
+ challenge: true,
+ },
+ },
+ rootChallenge: {
+ select: {
+ user: true,
+ slug: true,
+ },
+ },
+ },
where: {
id,
},
@@ -79,6 +222,116 @@ export async function updateComment(text: string, id: number) {
return 'unauthorized';
}
+ // check for mentions in both the previous version of this comment and current comment
+ // anything that was removed should have its notification deleted
+ // anything new should create a new notification
+
+ // don't notify the solution/challenge author if they are mentioned to avoid double notifications or the comment author since they
+ // shouldn't be able to notify themselves (e.g: tag themselves in their own comment)
+
+ const rootUsername =
+ (comment.rootType === 'CHALLENGE'
+ ? comment.rootChallenge?.user.name
+ : comment.rootSolution?.user?.name) ?? '';
+
+ const newCommentMentions = getMentionsFromComment(text).filter(
+ (mention) =>
+ mention?.toLowerCase() !== rootUsername.toLowerCase() &&
+ mention?.toLowerCase() !== session.user.name.toLowerCase(),
+ );
+
+ const originalCommentMentions = getMentionsFromComment(comment.text).filter(
+ (mention) =>
+ mention?.toLowerCase() !== rootUsername.toLowerCase() &&
+ mention?.toLowerCase() !== session.user.name.toLowerCase(),
+ );
+
+ const removed = originalCommentMentions.filter((item) => !newCommentMentions.includes(item));
+ const added = newCommentMentions.filter((item) => !originalCommentMentions.includes(item));
+
+ if (added.length > 0) {
+ // construct url for comment.
+ // we must determine if its a reply or root comment
+
+ let url = '';
+ if (!comment.parentId) {
+ // root comment
+ url =
+ comment.rootType === 'CHALLENGE'
+ ? // /challenge/challenge-slug/comments/26
+ `/challenge/${comment.rootChallenge?.slug}/comments/${comment.id}`
+ : // /challenge/challenge-slug/solutions/1/comments/32
+ `/challenge/${comment.rootSolution?.challenge?.slug}/solutions/${comment.rootSolution?.id}/comments/${comment.id}`;
+ } else {
+ // reply comment
+ url =
+ comment.rootType === 'CHALLENGE'
+ ? // /challenge/challenge-slug/comments/26?replyId=33
+ `/challenge/${comment.parentComment?.rootChallenge?.slug}/comments/${comment.parentComment?.id}?replyId=${comment.id}`
+ : // /challenge/challenge-slug/solutions/1/comments/32?replyId=35
+ `/challenge/${comment.rootSolution?.challenge?.slug}/solutions/${comment.rootSolutionId}/comments/${comment.parentComment?.id}?replyId=${comment.id}`;
+ }
+
+ // don't block on notification logic
+ Promise.all([
+ ...added.map(async (mention) => {
+ const validMention = await prisma.user.findFirst({
+ where: {
+ name: mention,
+ },
+ });
+
+ if (!validMention) {
+ return Promise.resolve();
+ }
+
+ return prisma.notification.create({
+ data: {
+ type: 'MENTION',
+ url,
+ commentId: comment.id,
+ fromUserId: session.user.id,
+ toUserId: validMention.id,
+ },
+ });
+ }),
+ ]).catch(console.error);
+ }
+
+ if (removed.length > 0) {
+ Promise.all([
+ ...removed.map(async (mention) => {
+ const validMention = await prisma.user.findFirst({
+ where: {
+ name: mention,
+ },
+ });
+
+ if (!validMention) {
+ return Promise.resolve();
+ }
+
+ const notificationToDelete = await prisma.notification.findFirst({
+ where: {
+ type: 'MENTION',
+ commentId: comment.id,
+ fromUserId: session.user.id,
+ toUserId: validMention.id,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ return prisma.notification.delete({
+ where: {
+ id: notificationToDelete?.id,
+ },
+ });
+ }),
+ ]).catch(console.error);
+ }
+
return await prisma.comment.update({
where: {
id,
@@ -99,7 +352,6 @@ export async function deleteComment(comment_id: number) {
const session = await auth();
if (!session) return 'unauthorized';
- if (!comment_id) return 'invalid_comment';
const rootComment = await prisma.comment.findFirstOrThrow({
where: {
@@ -112,23 +364,35 @@ export async function deleteComment(comment_id: number) {
return 'unauthorized';
}
- await deleteCommentWithChildren(prisma, rootComment);
-}
-
-async function deleteCommentWithChildren(prisma: PrismaClient, node: Comment) {
const children = await prisma.comment.findMany({
where: {
- parentId: node.id,
+ parentId: rootComment.id,
+ },
+ select: {
+ id: true,
},
});
- for (const child of children) {
- await deleteCommentWithChildren(prisma, child);
- }
-
- await prisma.comment.delete({
+ // have to delete noti before original comment is gone
+ await prisma.notification.deleteMany({
where: {
- id: node.id,
+ commentId: {
+ in: [rootComment.id, ...children.map((c) => c.id)],
+ },
},
});
+ await prisma.$transaction([
+ prisma.comment.deleteMany({
+ where: {
+ id: {
+ in: children.map((c) => c.id),
+ },
+ },
+ }),
+ prisma.comment.delete({
+ where: {
+ id: rootComment.id,
+ },
+ }),
+ ]);
}
diff --git a/apps/web/src/app/challenge/_components/comments/comment.tsx b/apps/web/src/app/challenge/_components/comments/comment.tsx
index 57abb53e..744434c0 100644
--- a/apps/web/src/app/challenge/_components/comments/comment.tsx
+++ b/apps/web/src/app/challenge/_components/comments/comment.tsx
@@ -21,7 +21,7 @@ import { useParams, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { z } from 'zod';
import { ReportDialog } from '~/components/ReportDialog';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { Vote } from '../vote';
import { CommentInput } from './comment-input';
import { CommentDeleteDialog } from './delete';
@@ -32,6 +32,8 @@ import { CommentSkeleton } from './comment-skeleton';
import { isAdminOrModerator } from '~/utils/auth-guards';
import { useCommentsReplies } from './comments.hooks';
import { UserBadge } from './enhanced-user-badge';
+import type { ChallengeRouteData } from '../../[slug]/getChallengeRouteData';
+import type { SolutionRouteData } from '../../[slug]/solutions/[solutionId]/getSolutionIdRouteData';
interface SingleCommentProps {
comment: PaginatedComments['comments'][number];
@@ -47,7 +49,7 @@ interface SingleCommentProps {
type CommentProps = SingleCommentProps & {
preselectedCommentMetadata?: PreselectedCommentMetadata;
- rootId: number;
+ root: ChallengeRouteData['challenge'] | SolutionRouteData;
type: CommentRoot;
deleteComment: (commentId: number) => Promise<void>;
updateComment: (text: string, commentId: number) => Promise<void>;
@@ -79,7 +81,7 @@ export function Comment({
comment,
preselectedCommentMetadata,
readonly = false,
- rootId,
+ root,
type,
deleteComment,
updateComment,
@@ -101,11 +103,12 @@ export function Comment({
updateReplyComment,
deleteReplyComment,
showLoadMoreRepliesBtn,
+ // @ts-ignore
} = useCommentsReplies({
enabled: showReplies,
- rootId,
+ root,
type,
- parentCommentId: comment.id,
+ parentComment: comment,
preselectedReplyId: hasPreselectedReply ? Number(replyId) : undefined,
});
@@ -288,7 +291,7 @@ function SingleComment({
<TooltipTrigger asChild>
<div className="text-muted-foreground flex items-center gap-2 whitespace-nowrap text-xs">
<Calendar className="h-4 w-4" />
- <span>{getRelativeTime(comment.createdAt)}</span>
+ <span>{getRelativeTimeStrict(comment.createdAt)}</span>
</div>
</TooltipTrigger>
<TooltipContent align="start" alignOffset={-55} className="rounded-xl">
@@ -330,6 +333,9 @@ function SingleComment({
{!readonly && (
<>
<Vote
+ comment={comment}
+ toUserId={comment.user.id}
+ challengeSlug={comment.rootChallenge?.slug ?? ''}
voteCount={comment._count.vote}
initialHasVoted={comment.vote.length > 0}
disabled={!session?.data?.user?.id || comment.userId === session?.data?.user?.id}
diff --git a/apps/web/src/app/challenge/_components/comments/comments.hooks.tsx b/apps/web/src/app/challenge/_components/comments/comments.hooks.tsx
index 3231c604..3bde135f 100644
--- a/apps/web/src/app/challenge/_components/comments/comments.hooks.tsx
+++ b/apps/web/src/app/challenge/_components/comments/comments.hooks.tsx
@@ -7,7 +7,11 @@ import {
import { useEffect, useReducer } from 'react';
import { commentErrors, sortKeys } from './comments.constants';
-import { getAllComments, getPaginatedComments } from './getCommentRouteData';
+import {
+ getAllComments,
+ getPaginatedComments,
+ type PaginatedComments,
+} from './getCommentRouteData';
import type { CommentRoot } from '@repo/db/types';
import {
addComment as addCommentAction,
@@ -16,6 +20,8 @@ import {
updateComment as updateCommentAction,
} from './comment.action';
import { toast } from '@repo/ui/components/use-toast';
+import type { ChallengeRouteData } from '../../[slug]/getChallengeRouteData';
+import type { SolutionRouteData } from '../../[slug]/solutions/[solutionId]/getSolutionIdRouteData';
const getRootQueryKey = (rootId: number, type: CommentRoot) =>
`${type.toLowerCase()}-${rootId}-comments`;
@@ -27,16 +33,20 @@ interface CommentsMeta {
sort: SortItem;
}
-interface DefaultCommentsProps {
- rootId: number;
- type: CommentRoot;
-}
-
-interface UseCommentsProps extends DefaultCommentsProps {
- initialPage?: number;
-}
+type UseCommentsProps =
+ | {
+ root: ChallengeRouteData['challenge'];
+ rootType: 'CHALLENGE';
+ initialPage?: number;
+ }
+ | {
+ root: SolutionRouteData;
+ rootType: 'SOLUTION';
+ initialPage?: number;
+ };
-export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
+export function useComments(props: UseCommentsProps) {
+ const { rootType, root, initialPage } = props;
const queryClient = useQueryClient();
const [commentsMeta, updateCommentsMeta] = useReducer(
(state: CommentsMeta, action: Partial<CommentsMeta>) => ({ ...state, ...action }),
@@ -47,7 +57,7 @@ export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
);
const getQueryKey = ({ sort, page }: { sort: string; page: number }) => [
- getRootQueryKey(rootId, type),
+ getRootQueryKey(root.id, rootType),
sort,
page,
];
@@ -56,9 +66,9 @@ export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: commentsMeta.page }),
queryFn: () => {
return getPaginatedComments({
- rootId,
+ rootId: root.id,
page: commentsMeta.page,
- rootType: type,
+ rootType,
sortKey: commentsMeta.sort.key,
sortOrder: commentsMeta.sort.order,
});
@@ -84,8 +94,6 @@ export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
const res = await deleteCommentAction(commentId);
if (res === 'unauthorized') {
toast(commentErrors.unauthorized);
- } else if (res === 'invalid_comment') {
- toast(commentErrors.invalidId);
} else {
toast({
title: 'Comment Deleted',
@@ -111,10 +119,10 @@ export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
const addComment = async (text: string) => {
try {
+ const { initialPage: _, ...rest } = props;
const res = await addCommentAction({
+ ...rest,
text,
- rootId,
- rootType: type,
});
if (res === 'text_is_empty') {
toast(commentErrors.empty);
@@ -168,28 +176,38 @@ export function useComments({ type, rootId, initialPage }: UseCommentsProps) {
};
}
-interface UseCommentRepliesProps extends DefaultCommentsProps {
- parentCommentId: number;
- enabled: boolean;
- preselectedReplyId?: number;
-}
+type UseCommentRepliesProps =
+ | {
+ root: ChallengeRouteData['challenge'];
+ type: 'CHALLENGE';
+ parentComment: PaginatedComments['comments'][number];
+ enabled: boolean;
+ preselectedReplyId?: number;
+ }
+ | {
+ root: SolutionRouteData;
+ type: 'SOLUTION';
+ parentComment: PaginatedComments['comments'][number];
+ enabled: boolean;
+ preselectedReplyId?: number;
+ };
const REPLIES_PAGESIZE = 5;
export function useCommentsReplies({
- rootId,
+ root,
type,
- parentCommentId,
+ parentComment,
enabled,
preselectedReplyId,
}: UseCommentRepliesProps) {
const queryClient = useQueryClient();
- const rootQueryKey = [getRootQueryKey(rootId, type)];
- const queryKey = [...rootQueryKey, `comment-${parentCommentId}-replies`];
+ const rootQueryKey = [getRootQueryKey(root.id, type)];
+ const queryKey = [...rootQueryKey, `comment-${parentComment.id}-replies`];
const { data: replies } = useQuery({
queryKey,
- queryFn: () => getAllComments({ rootId, rootType: type, parentId: parentCommentId }),
+ queryFn: () => getAllComments({ rootId: root.id, rootType: type, parentId: parentComment.id }),
staleTime: 5000,
enabled,
});
@@ -236,13 +254,15 @@ export function useCommentsReplies({
const addReplyComment = async (text: string) => {
try {
+ // @ts-ignore
const res = await replyComment(
+ // @ts-ignore
{
text,
- rootId,
+ root,
rootType: type,
},
- parentCommentId,
+ parentComment,
);
if (res === 'text_is_empty') {
toast(commentErrors.empty);
@@ -281,8 +301,6 @@ export function useCommentsReplies({
const res = await deleteCommentAction(commentId);
if (res === 'unauthorized') {
toast(commentErrors.unauthorized);
- } else if (res === 'invalid_comment') {
- toast(commentErrors.invalidId);
} else {
toast({
title: 'Comment Deleted',
diff --git a/apps/web/src/app/challenge/_components/comments/delete/index.tsx b/apps/web/src/app/challenge/_components/comments/delete/index.tsx
index 2f98cdd8..ec3dc5c7 100644
--- a/apps/web/src/app/challenge/_components/comments/delete/index.tsx
+++ b/apps/web/src/app/challenge/_components/comments/delete/index.tsx
@@ -7,7 +7,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/too
import { TypographyLarge } from '@repo/ui/components/typography/large';
import { useState } from 'react';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { type PaginatedComments } from '../getCommentRouteData';
@@ -44,7 +44,7 @@ export function CommentDeleteDialog({
<Tooltip delayDuration={0.05}>
<TooltipTrigger asChild>
<span className="mr-2 whitespace-nowrap text-sm text-neutral-500">
- {getRelativeTime(comment.createdAt)}
+ {getRelativeTimeStrict(comment.createdAt)}
</span>
</TooltipTrigger>
<TooltipContent align="start" className="rounded-xl">
diff --git a/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts b/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts
index 52859fd7..12a572b0 100644
--- a/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts
+++ b/apps/web/src/app/challenge/_components/comments/getCommentRouteData.ts
@@ -168,12 +168,18 @@ export async function getPaginatedComments({
},
rootChallenge: {
select: {
+ slug: true,
name: true,
},
},
rootSolution: {
select: {
title: true,
+ challenge: {
+ select: {
+ slug: true,
+ },
+ },
},
},
},
@@ -238,12 +244,18 @@ export async function getAllComments({
},
rootChallenge: {
select: {
+ slug: true,
name: true,
},
},
rootSolution: {
select: {
title: true,
+ challenge: {
+ select: {
+ slug: true,
+ },
+ },
},
},
},
diff --git a/apps/web/src/app/challenge/_components/comments/getMentionsFromComment.ts b/apps/web/src/app/challenge/_components/comments/getMentionsFromComment.ts
new file mode 100644
index 00000000..201e5a97
--- /dev/null
+++ b/apps/web/src/app/challenge/_components/comments/getMentionsFromComment.ts
@@ -0,0 +1,13 @@
+export function getMentionsFromComment(text: string) {
+ // Regex pattern to match mentions in the format @username
+ const pattern = /@([a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38})/g;
+
+ const mentions = [];
+
+ let match;
+ while ((match = pattern.exec(text)) !== null) {
+ mentions.push(match[1]);
+ }
+
+ return Array.from(new Set(mentions)).slice(0, 10);
+}
diff --git a/apps/web/src/app/challenge/_components/comments/index.tsx b/apps/web/src/app/challenge/_components/comments/index.tsx
index d2fbb604..36c797da 100644
--- a/apps/web/src/app/challenge/_components/comments/index.tsx
+++ b/apps/web/src/app/challenge/_components/comments/index.tsx
@@ -14,16 +14,18 @@ import { SortSelect } from '../sort-select';
import { useComments } from './comments.hooks';
import { sortKeys } from './comments.constants';
import { useTrackNavigationVisiblity } from '../../[slug]/use-track-visibility.hook';
+import type { ChallengeRouteData } from '../../[slug]/getChallengeRouteData';
+import type { SolutionRouteData } from '../../[slug]/solutions/[solutionId]/getSolutionIdRouteData';
interface Props {
preselectedCommentMetadata?: PreselectedCommentMetadata;
expanded?: boolean;
- rootId: number;
+ root: ChallengeRouteData['challenge'] | SolutionRouteData;
type: CommentRoot;
}
// million-ignore
-export function Comments({ preselectedCommentMetadata, rootId, type, expanded = false }: Props) {
+export function Comments({ preselectedCommentMetadata, root, type, expanded = false }: Props) {
const { isTrackTitleVisible } = useTrackNavigationVisiblity();
const [showComments, setShowComments] = useState(expanded);
const commentContainerRef = useRef<HTMLDivElement>(null);
@@ -37,10 +39,11 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
deleteComment,
updateComment,
} = useComments({
- type,
- rootId,
+ rootType: type,
+ root,
initialPage: preselectedCommentMetadata?.page,
- });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any);
const handleChangePage = (page: number) => {
changePage(page);
@@ -112,7 +115,7 @@ export function Comments({ preselectedCommentMetadata, rootId, type, expanded =
key={comment.id}
preselectedCommentMetadata={preselectedCommentMetadata}
comment={comment}
- rootId={rootId}
+ root={root}
type={type}
deleteComment={deleteComment}
updateComment={updateComment}
diff --git a/apps/web/src/app/challenge/_components/description/index.tsx b/apps/web/src/app/challenge/_components/description/index.tsx
index 3f7fb7cb..f79a1d23 100644
--- a/apps/web/src/app/challenge/_components/description/index.tsx
+++ b/apps/web/src/app/challenge/_components/description/index.tsx
@@ -21,7 +21,7 @@ import { debounce } from 'lodash';
import { useMemo, useRef, useState } from 'react';
import { type ChallengeRouteData } from '~/app/challenge/[slug]/getChallengeRouteData';
import { ReportDialog } from '~/components/ReportDialog';
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
import { addOrRemoveBookmark } from '../bookmark.action';
import { ShareForm } from '../share-form';
import { Vote } from '../vote';
@@ -96,7 +96,7 @@ export function Description({ challenge }: Props) {
/>
<div className="text-muted-foreground flex items-center gap-2">
<Calendar className=" h-4 w-4" />
- <span className="text-xs">Last updated {getRelativeTime(challenge.updatedAt)}</span>
+ <span className="text-xs">Last updated {getRelativeTimeStrict(challenge.updatedAt)}</span>
</div>
</div>
{/* Difficulty & Action Buttons */}
@@ -118,6 +118,8 @@ export function Description({ challenge }: Props) {
disabled={!session?.data?.user?.id}
rootType="CHALLENGE"
rootId={challenge?.id}
+ toUserId={challenge.user.name}
+ challengeSlug={challenge.slug}
/>
<Dialog>
<DialogTrigger>
diff --git a/apps/web/src/app/challenge/_components/vote.tsx b/apps/web/src/app/challenge/_components/vote.tsx
index 70ad3b4c..6a3b34b1 100644
--- a/apps/web/src/app/challenge/_components/vote.tsx
+++ b/apps/web/src/app/challenge/_components/vote.tsx
@@ -1,7 +1,7 @@
'use client';
import { useSession } from '@repo/auth/react';
-import type { VoteType } from '@repo/db/types';
+import type { Comment, VoteType } from '@repo/db/types';
import { ThumbsUp } from '@repo/ui/icons';
import clsx from 'clsx';
import { debounce } from 'lodash';
@@ -9,31 +9,60 @@ import { useRef, useState } from 'react';
import { incrementOrDecrementUpvote } from '../increment.action';
import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';
import { Button } from '@repo/ui/components/button';
+import type { PaginatedComments } from './comments/getCommentRouteData';
+
+interface ChallengeCommentVoteProps {
+ type: 'COMMENT';
+ comment: Comment;
+}
+
+interface ChallengeVoteProps {
+ type: 'CHALLENGE';
+ comment: Comment;
+}
+
+interface SharedSolutionVoteProps {
+ type: 'SHAREDSOLUTION';
+ comment: Comment;
+}
interface VoteProps {
voteCount: number;
initialHasVoted?: boolean;
rootId: number;
+ // user id of the content thats being liked
+ toUserId: string;
+ challengeSlug: string;
rootType: VoteType;
disabled?: boolean;
onVote?: (didUpvote: boolean) => void;
+ comment?: PaginatedComments['comments'][number];
}
export function Vote({
+ challengeSlug,
voteCount,
initialHasVoted,
rootId,
rootType,
disabled,
onVote,
+ toUserId,
+ comment,
}: VoteProps) {
const [votes, setVotes] = useState(voteCount);
const [hasVoted, setHasVoted] = useState(initialHasVoted);
const session = useSession();
-
const debouncedIncrement = useRef(
debounce(async (shouldIncrement: boolean) => {
- await incrementOrDecrementUpvote(rootId, rootType, shouldIncrement);
+ await incrementOrDecrementUpvote({
+ comment,
+ rootId,
+ rootType,
+ shouldIncrement,
+ toUserId,
+ challengeSlug,
+ });
}, 500),
).current;
diff --git a/apps/web/src/app/challenge/increment.action.ts b/apps/web/src/app/challenge/increment.action.ts
index 45ec9e1e..65a84aff 100644
--- a/apps/web/src/app/challenge/increment.action.ts
+++ b/apps/web/src/app/challenge/increment.action.ts
@@ -2,12 +2,23 @@
import { auth } from '~/server/auth';
import { prisma } from '@repo/db';
import type { VoteType } from '@repo/db/types';
+import type { PaginatedComments } from './_components/comments/getCommentRouteData';
-export async function incrementOrDecrementUpvote(
- id: number,
- rootType: VoteType,
- shouldIncrement: boolean,
-) {
+export async function incrementOrDecrementUpvote({
+ rootId,
+ rootType,
+ shouldIncrement,
+ toUserId,
+ challengeSlug,
+ comment,
+}: {
+ rootId: number;
+ rootType: VoteType;
+ shouldIncrement: boolean;
+ toUserId: string;
+ challengeSlug: string;
+ comment?: PaginatedComments['comments'][number];
+}) {
const session = await auth();
if (!session) {
@@ -17,25 +28,59 @@ export async function incrementOrDecrementUpvote(
const voteExists = await prisma.vote.findFirst({
where: {
rootType,
- challengeId: rootType === 'CHALLENGE' ? id : undefined,
- commentId: rootType === 'COMMENT' ? id : undefined,
- sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,
- submissionId: rootType === 'SUBMISSION' ? id : undefined,
+ challengeId: rootType === 'CHALLENGE' ? rootId : undefined,
+ commentId: rootType === 'COMMENT' ? rootId : undefined,
+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? rootId : undefined,
+ submissionId: rootType === 'SUBMISSION' ? rootId : undefined,
userId: session?.user?.id ?? '',
},
});
if (session?.user && !voteExists && shouldIncrement) {
+ const notificationUrl = (rootType: VoteType) => {
+ switch (rootType) {
+ case 'CHALLENGE':
+ // challenge/hello-world
+ return `/challenge/${challengeSlug}`;
+ case 'COMMENT':
+ if (comment?.rootType === 'CHALLENGE') {
+ // challenge/default-generic-arguments/comments/30
+ return `/challenge/${challengeSlug}/comments/${rootId}`;
+ }
+ // challenge/hello-world/solutions/1/comments/32
+ return `/challenge/${comment?.rootSolution?.challenge?.slug}/solutions/${comment?.rootSolutionId}/comments/${rootId}`;
+ case 'SHAREDSOLUTION':
+ // challenge/hello-world/solutions/1
+ return `/challenge/${challengeSlug}/solutions/${rootId}`;
+ default:
+ return '';
+ }
+ };
+
await prisma.vote.create({
data: {
rootType,
- challengeId: rootType === 'CHALLENGE' ? id : undefined,
- commentId: rootType === 'COMMENT' ? id : undefined,
- sharedSolutionId: rootType === 'SHAREDSOLUTION' ? id : undefined,
- submissionId: rootType === 'SUBMISSION' ? id : undefined,
+ challengeId: rootType === 'CHALLENGE' ? rootId : undefined,
+ commentId: rootType === 'COMMENT' ? rootId : undefined,
+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? rootId : undefined,
userId: session.user.id,
},
});
+ // dont care if this fails nor should it block
+ prisma.notification
+ .create({
+ data: {
+ type: 'LIKE',
+ blurb: `liked your ${rootType.toLowerCase()}`,
+ url: notificationUrl(rootType),
+ challengeId: rootType === 'CHALLENGE' ? rootId : undefined,
+ commentId: rootType === 'COMMENT' ? rootId : undefined,
+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? rootId : undefined,
+ fromUserId: session.user.id,
+ toUserId,
+ },
+ })
+ .catch(console.error);
}
if (session?.user && voteExists && !shouldIncrement) {
@@ -44,5 +89,22 @@ export async function incrementOrDecrementUpvote(
id: voteExists.id,
},
});
+
+ const notificationToDelete = await prisma.notification.findFirst({
+ where: {
+ type: 'LIKE',
+ fromUserId: session.user.id,
+ challengeId: rootType === 'CHALLENGE' ? rootId : undefined,
+ commentId: rootType === 'COMMENT' ? rootId : undefined,
+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? rootId : undefined,
+ toUserId,
+ },
+ });
+
+ await prisma.notification.delete({
+ where: {
+ id: notificationToDelete?.id,
+ },
+ });
}
}
diff --git a/apps/web/src/app/explore/_components/index.tsx b/apps/web/src/app/explore/_components/index.tsx
index 99283fa2..beaf2f9b 100644
--- a/apps/web/src/app/explore/_components/index.tsx
+++ b/apps/web/src/app/explore/_components/index.tsx
@@ -1,15 +1,11 @@
-import { auth } from '~/server/auth';
import { Suspense } from 'react';
import { Footsies } from '~/components/footsies';
import { ExploreSection } from './explore-section';
import { ExploreSectionSkeleton } from './explore-section-skeleton';
-// CI fails without this
export const dynamic = 'force-dynamic';
export async function Explore() {
- const session = await auth();
-
return (
<>
<div className="flex flex-col gap-8 py-8 md:gap-10 md:py-8">
diff --git a/apps/web/src/app/explore/_components/relative-time.tsx b/apps/web/src/app/explore/_components/relative-time.tsx
index da671cd4..70fa31a2 100644
--- a/apps/web/src/app/explore/_components/relative-time.tsx
+++ b/apps/web/src/app/explore/_components/relative-time.tsx
@@ -1,5 +1,5 @@
-import { getRelativeTime } from '~/utils/relativeTime';
+import { getRelativeTimeStrict } from '~/utils/relativeTime';
export default function RelativeTime({ date }: { date: Date }) {
- return <>{getRelativeTime(date)}</>;
+ return <>{getRelativeTimeStrict(date)}</>;
}
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
index 83c142e9..68375312 100644
--- a/apps/web/src/app/login/page.tsx
+++ b/apps/web/src/app/login/page.tsx
@@ -9,33 +9,31 @@ export default async function Index({
};
}) {
return (
- <>
- <div className="container -mt-[56px] flex h-screen flex-col items-center justify-center">
- <div className="lg:p-8">
- <div className="mx-auto flex w-full flex-col justify-center space-y-6 text-center sm:w-[450px]">
- <div className="flex flex-col space-y-2 text-center">
- <h1 className="text-4xl font-bold tracking-tight text-neutral-900 dark:text-white">
- Welcome to Public Beta!
- </h1>
- <p className="text-muted-foreground text-sm">
- Start your typescript journey by logging in below.
- </p>
- </div>
- <LoginButton redirectTo={searchParams.redirectTo ?? '/explore'} />
- <p className="text-muted-foreground mx-auto px-8 text-sm sm:w-[350px]">
- By clicking Login, you agree to our <br />
- <Link href="/tos" className="hover:text-primary underline underline-offset-4">
- Terms of Service
- </Link>{' '}
- and{' '}
- <Link href="/privacy" className="hover:text-primary underline underline-offset-4">
- Privacy Policy
- </Link>
- .
+ <div className="container -mt-[56px] flex h-screen flex-col items-center justify-center">
+ <div className="lg:p-8">
+ <div className="mx-auto flex w-full flex-col justify-center space-y-6 text-center sm:w-[450px]">
+ <div className="flex flex-col space-y-2 text-center">
+ <h1 className="text-4xl font-bold tracking-tight text-neutral-900 dark:text-white">
+ Welcome to Public Beta!
+ </h1>
+ <p className="text-muted-foreground text-sm">
+ Start your typescript journey by logging in below.
</p>
</div>
+ <LoginButton redirectTo={searchParams.redirectTo ?? '/explore'} />
+ <p className="text-muted-foreground mx-auto px-8 text-sm sm:w-[350px]">
+ By clicking Login, you agree to our <br />
+ <Link href="/tos" className="hover:text-primary underline underline-offset-4">
+ Terms of Service
+ </Link>{' '}
+ and{' '}
+ <Link href="/privacy" className="hover:text-primary underline underline-offset-4">
+ Privacy Policy
+ </Link>
+ .
+ </p>
</div>
</div>
- </>
+ </div>
);
}
diff --git a/apps/web/src/app/notifications/empty.tsx b/apps/web/src/app/notifications/empty.tsx
new file mode 100644
index 00000000..96d702e8
--- /dev/null
+++ b/apps/web/src/app/notifications/empty.tsx
@@ -0,0 +1,21 @@
+import { AlertCircle, AtSign } from '@repo/ui/icons';
+
+export function Empty({ type }: { type: 'all' | 'mentions' }) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center p-4 text-center">
+ {type === 'all' ? (
+ <AlertCircle className="text-muted-foreground mb-4 h-12 w-12" />
+ ) : (
+ <AtSign className="text-muted-foreground mb-4 h-12 w-12" />
+ )}
+ <h3 className="text-foreground mb-2 text-lg font-semibold">
+ {type === 'all' ? 'No notifications yet' : 'No mentions yet'}
+ </h3>
+ <p className="text-muted-foreground max-w-sm text-sm">
+ {type === 'all'
+ ? "When you get notifications, they'll show up here. Start by engaging with others in the comments."
+ : "When someone mentions you in a comment, you'll see it here"}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/notifications/error.tsx b/apps/web/src/app/notifications/error.tsx
new file mode 100644
index 00000000..b3d22bd4
--- /dev/null
+++ b/apps/web/src/app/notifications/error.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { LoginButton } from '../login/_components/LoginButton';
+
+export default function ErrorBounds() {
+ return (
+ <div className="container -mt-[56px] flex h-screen flex-col items-center justify-center">
+ <div className="lg:p-8">
+ <div className="mx-auto flex w-full flex-col justify-center space-y-6 text-center sm:w-[450px]">
+ <div className="flex flex-col space-y-2 text-center">
+ <h1 className="mb-5 text-4xl font-bold tracking-tight text-neutral-900 dark:text-white">
+ You must be logged in to see notifications.
+ </h1>
+ </div>
+ <LoginButton redirectTo="/notifications" />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/notifications/mentions/page.tsx b/apps/web/src/app/notifications/mentions/page.tsx
new file mode 100644
index 00000000..e69de29b
diff --git a/apps/web/src/app/notifications/notfication-item.tsx b/apps/web/src/app/notifications/notfication-item.tsx
new file mode 100644
index 00000000..1450771e
--- /dev/null
+++ b/apps/web/src/app/notifications/notfication-item.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import type { NotificationType } from '@repo/db/types';
+import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';
+import { Markdown } from '@repo/ui/components/markdown';
+import { AlertCircle, AtSign, Heart, MessageCircle, ShieldAlert } from '@repo/ui/icons';
+import Link from 'next/link';
+import { useRouter } from 'next/navigation';
+import { useInView } from 'react-intersection-observer';
+import { getRelativeTime } from '~/utils/relativeTime';
+import type { Notification } from './notification.actions';
+import { cn } from '@repo/ui/cn';
+
+const BLURBS = {
+ MENTION: 'mentioned you in a comment',
+ LIKE: (type: string) => `liked your ${type}`,
+ SYSTEM: '',
+ MISC: '',
+ REPLY: 'replied to you',
+} satisfies Record<NotificationType, string | ((v: string) => string)>;
+
+export function NotificationItem({
+ notification,
+ onSeen,
+}: {
+ notification: Notification;
+ onSeen: (v: number) => void;
+}) {
+ const { ref } = useInView({
+ triggerOnce: true,
+ threshold: 0.8,
+ onChange(inView) {
+ if (notification.isRead || !inView) return;
+ onSeen(notification.id);
+ },
+ });
+ const router = useRouter();
+ const getBlurb = (notification: Notification) => {
+ if (notification.type === 'LIKE') {
+ const type = notification.comment ? 'comment' : 'solution';
+ return BLURBS.LIKE(type);
+ }
+
+ return BLURBS[notification.type];
+ };
+
+ const buildUrl = () => {
+ throw new Error('the url field should be filled out');
+ };
+ return (
+ <button
+ ref={ref}
+ onClick={() => router.push(notification.url || buildUrl())}
+ className={cn(
+ !notification.isRead ? 'bg-sky-300/20 hover:bg-sky-300/30' : 'hover:bg-muted/50',
+ 'border-border focus:ring-primary w-full border-b p-4 text-left outline-none transition-colors last:border-b-0 focus:outline-none',
+ )}
+ >
+ <div className="flex items-start space-x-4">
+ <Avatar className="h-10 w-10">
+ {notification.fromUser.image ? (
+ <AvatarImage
+ src={notification.fromUser.image}
+ alt={`${notification.fromUser.name} profile photo`}
+ />
+ ) : (
+ <AvatarFallback>{notification.fromUser.name.charAt(0)}</AvatarFallback>
+ )}
+ </Avatar>
+ <div className="flex-grow">
+ <div className="flex items-center space-x-2">
+ <Link
+ href={`/@${notification.fromUser.name}`}
+ className="focus:ring-primary relative z-10 rounded-sm text-sm font-medium hover:underline focus:outline-none focus:ring-2 focus:ring-offset-2"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {notification.fromUser.name}
+ </Link>
+ <div className="flex-shrink-0">
+ {notification.type === 'LIKE' && (
+ <Heart className="h-4 w-4 text-red-500 dark:text-red-400" />
+ )}
+ {notification.type === 'MENTION' && (
+ <AtSign className="h-4 w-4 text-blue-500 dark:text-blue-400" />
+ )}
+ {notification.type === 'REPLY' && (
+ <MessageCircle className="h-4 w-4 text-purple-500 dark:text-purple-400" />
+ )}
+ {notification.type === 'MISC' && (
+ <AlertCircle className="h-4 w-4 text-orange-500 dark:text-orange-400" />
+ )}
+ {notification.type === 'SYSTEM' && (
+ <ShieldAlert className="h-4 w-4 text-yellow-500 dark:text-yellow-400" />
+ )}
+ </div>
+ </div>
+ <p className="text-muted-foreground text-sm">
+ {notification.blurb ?? getBlurb(notification)}
+ </p>
+ </div>
+ <div className="text-muted-foreground flex-shrink-0 text-xs">
+ {' '}
+ {getRelativeTime(notification.createdAt)}
+ </div>
+ </div>
+ {notification.type === 'MENTION' ||
+ notification.type === 'REPLY' ||
+ notification.type === 'LIKE'
+ ? // if a user edits the comment and deletes the contents just hide it
+ notification.comment?.text && (
+ <div className="bg-muted text-foreground ml-14 mt-1 overflow-hidden rounded-md p-3 text-sm">
+ <Markdown
+ disableMentions
+ disableCopy
+ className="m-1 max-h-[300px] overflow-y-auto rounded-md"
+ >
+ {notification.comment.text}
+ </Markdown>
+ </div>
+ )
+ : null}
+ </button>
+ );
+}
diff --git a/apps/web/src/app/notifications/notification-page.tsx b/apps/web/src/app/notifications/notification-page.tsx
new file mode 100644
index 00000000..92fb44a3
--- /dev/null
+++ b/apps/web/src/app/notifications/notification-page.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@repo/ui/components/tabs';
+import { Bell } from '@repo/ui/icons';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { useRef } from 'react';
+import { NOTIFICATION_QUERY_KEY } from '~/components/Navigation/notification-link';
+import { markNotificationsAsRead } from './notification.actions';
+import { NotificationsAll } from './notifications-all';
+import { NotificationsMentions } from './notifications-mentions';
+
+export default function NotificationPage() {
+ const seenNotifications = useRef(new Set<number>());
+ const timeoutRef = useRef<number>();
+ const client = useQueryClient();
+ const mutation = useMutation({
+ mutationFn: markNotificationsAsRead,
+ onSuccess() {},
+ });
+
+ const onSeen = (id: number) => {
+ seenNotifications.current.add(id);
+ const copy = new Set(seenNotifications.current);
+ copy.add(id);
+ clearTimeout(timeoutRef.current);
+
+ timeoutRef.current = window.setTimeout(() => {
+ timeoutRef.current = undefined;
+ mutation.mutate(Array.from(seenNotifications.current), {
+ onSuccess: () => {
+ for (const id of copy) {
+ seenNotifications.current.delete(id);
+ }
+ },
+ });
+ client.setQueryData([NOTIFICATION_QUERY_KEY], 0);
+ }, 500);
+ };
+
+ return (
+ <div className="bg-background mx-auto min-w-[300px] max-w-3xl rounded-lg ">
+ <div className="p-4">
+ <h2 className="text-foreground flex items-center text-xl font-bold">
+ <Bell className="mr-2 h-5 w-5" />
+ Notifications
+ </h2>
+ </div>
+ <Tabs defaultValue="all" className="w-full">
+ <TabsList className="bg-muted grid w-full grid-cols-2">
+ <TabsTrigger value="all">All</TabsTrigger>
+ <TabsTrigger value="mentions">Mentions</TabsTrigger>
+ </TabsList>
+ <TabsContent value="all" className="border-border border">
+ <NotificationsAll onSeen={onSeen} />
+ </TabsContent>
+ <TabsContent value="mentions" className="border-border border">
+ <NotificationsMentions onSeen={onSeen} />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/notifications/notification.actions.ts b/apps/web/src/app/notifications/notification.actions.ts
new file mode 100644
index 00000000..06e0873d
--- /dev/null
+++ b/apps/web/src/app/notifications/notification.actions.ts
@@ -0,0 +1,84 @@
+'use server';
+
+import { auth } from '~/server/auth';
+import { prisma } from '@repo/db';
+
+export async function markNotificationsAsRead(ids: number[]) {
+ const session = await auth();
+
+ if (!session) {
+ throw new Error('User not authenticated');
+ }
+
+ await prisma.notification.updateMany({
+ where: {
+ id: {
+ in: ids,
+ },
+ },
+ data: {
+ isRead: true,
+ },
+ });
+}
+
+export type Notification = Awaited<ReturnType<typeof getNotifications>>['notifications'][0];
+export type GetNotificationsResponse = Awaited<ReturnType<typeof getNotifications>>;
+
+/**
+ * Fetches user enrolled tracks based on current session.
+ */
+export async function getNotifications({
+ cursor,
+ mentionsOnly = false,
+}: {
+ cursor?: number;
+ mentionsOnly?: boolean;
+}) {
+ const session = await auth();
+ if (!session) {
+ throw new Error('not authenticated');
+ }
+
+ const notifications = await prisma.notification.findMany({
+ take: 5,
+ skip: cursor ? 1 : 0,
+ cursor: cursor ? { id: cursor } : undefined,
+ where: {
+ toUserId: session.user.id,
+ type: mentionsOnly ? 'MENTION' : undefined,
+ },
+ select: {
+ id: true,
+ blurb: true,
+ createdAt: true,
+ url: true,
+ comment: {
+ select: {
+ id: true,
+ rootType: true,
+ text: true,
+ },
+ },
+ isRead: true,
+ content: true,
+ fromUser: {
+ select: {
+ image: true,
+ name: true,
+ },
+ },
+ type: true,
+ },
+ orderBy: [
+ {
+ isRead: 'asc',
+ },
+ {
+ createdAt: 'desc',
+ },
+ ],
+ });
+
+ return { notifications, cursor: notifications.at(-1)?.id };
+}
diff --git a/apps/web/src/app/notifications/notifications-all.tsx b/apps/web/src/app/notifications/notifications-all.tsx
new file mode 100644
index 00000000..3b079e27
--- /dev/null
+++ b/apps/web/src/app/notifications/notifications-all.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { Fragment } from 'react';
+import InfiniteList from '~/components/infinite-list';
+import { Empty } from './empty';
+import { NotificationItem } from './notfication-item';
+import { getNotifications } from './notification.actions';
+
+export function NotificationsAll({ onSeen }: { onSeen: (v: number) => void }) {
+ const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery({
+ initialPageParam: 0,
+ queryKey: ['notifications-all'],
+ queryFn: ({ pageParam }) => {
+ return getNotifications({ cursor: pageParam });
+ },
+ getNextPageParam: (lastPage) => {
+ return lastPage?.cursor;
+ },
+ });
+
+ if (isLoading) {
+ return null;
+ }
+
+ if (data?.pages[0]?.notifications.length === 0) {
+ return <Empty type="all" />;
+ }
+
+ return (
+ <>
+ <InfiniteList
+ isLoadingNext={isFetchingNextPage}
+ loader={<div>loading...</div>}
+ hasNext={hasNextPage}
+ next={fetchNextPage}
+ key="mentions"
+ >
+ {data?.pages.map((page, i) => (
+ <Fragment key={i}>
+ {page.notifications.map((notification) => (
+ <NotificationItem key={notification.id} notification={notification} onSeen={onSeen} />
+ ))}
+ </Fragment>
+ ))}
+ </InfiniteList>
+ </>
+ );
+}
diff --git a/apps/web/src/app/notifications/notifications-mentions.tsx b/apps/web/src/app/notifications/notifications-mentions.tsx
new file mode 100644
index 00000000..efd92eeb
--- /dev/null
+++ b/apps/web/src/app/notifications/notifications-mentions.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { Fragment } from 'react';
+import InfiniteList from '~/components/infinite-list';
+import { Empty } from './empty';
+import { NotificationItem } from './notfication-item';
+import { getNotifications } from './notification.actions';
+
+export function NotificationsMentions({ onSeen }: { onSeen: (v: number) => void }) {
+ const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery({
+ initialPageParam: 0,
+ queryKey: ['notifications-mentions'],
+ queryFn: ({ pageParam }) => {
+ return getNotifications({ cursor: pageParam, mentionsOnly: true });
+ },
+ getNextPageParam: (lastPage) => lastPage?.cursor,
+ });
+
+ if (isLoading) {
+ return null;
+ }
+
+ if (data?.pages[0]?.notifications.length === 0) {
+ return <Empty type="mentions" />;
+ }
+
+ return (
+ <>
+ <InfiniteList
+ isLoadingNext={isFetchingNextPage}
+ loader={<div>loading...</div>}
+ hasNext={hasNextPage}
+ next={fetchNextPage}
+ key="mentions"
+ >
+ {data?.pages.map((page, i) => (
+ <Fragment key={i}>
+ {page.notifications.map((notification) => (
+ <NotificationItem key={notification.id} notification={notification} onSeen={onSeen} />
+ ))}
+ </Fragment>
+ ))}
+ </InfiniteList>
+ </>
+ );
+}
diff --git a/apps/web/src/app/notifications/page.tsx b/apps/web/src/app/notifications/page.tsx
new file mode 100644
index 00000000..3b7f089f
--- /dev/null
+++ b/apps/web/src/app/notifications/page.tsx
@@ -0,0 +1,17 @@
+import type { Metadata } from 'next';
+import { auth } from '~/server/auth';
+import NotificationPage from './notification-page';
+
+export const metadata: Metadata = {
+ title: 'Notifications | TypeHero',
+};
+
+export default async function Page() {
+ const session = await auth();
+
+ if (!session) {
+ throw new Error('not authed');
+ }
+
+ return <NotificationPage />;
+}
diff --git a/apps/web/src/app/providers.tsx b/apps/web/src/app/providers.tsx
index 0ee8eecc..13ae47db 100644
--- a/apps/web/src/app/providers.tsx
+++ b/apps/web/src/app/providers.tsx
@@ -14,8 +14,18 @@ interface Props {
}
export function Providers({ children }: Props) {
- const [queryClient] = React.useState(() => new QueryClient());
-
+ const [queryClient] = React.useState(
+ () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ // With SSR, we usually want to set some default staleTime
+ // above 0 to avoid refetching immediately on the client
+ staleTime: 5000,
+ },
+ },
+ }),
+ );
return (
<QueryClientProvider client={queryClient}>
<ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" />
diff --git a/apps/web/src/components/Navigation/index.tsx b/apps/web/src/components/Navigation/index.tsx
index c782ab0d..1daecc16 100644
--- a/apps/web/src/components/Navigation/index.tsx
+++ b/apps/web/src/components/Navigation/index.tsx
@@ -19,6 +19,8 @@ import { NavWrapper } from './nav-wrapper';
import { SignOutLink } from './signout-link';
import { SkipToCodeEditor } from './skip-to-code-editor';
import { auth } from '~/server/auth';
+import { NotificationLink } from './notification-link';
+import { getNotificationCount } from './navigation.actions';
export function getAdminUrl() {
// reference for vercel.com
@@ -31,9 +33,12 @@ export function getAdminUrl() {
}
export async function Navigation() {
- const session = await auth();
+ const [session, featureFlags, notificationCount] = await Promise.all([
+ auth(),
+ getAllFlags(),
+ getNotificationCount(),
+ ]);
const isAdminOrMod = isAdminOrModerator(session);
- const featureFlags = await getAllFlags();
const TopSectionLinks = (
<>
@@ -110,6 +115,7 @@ export async function Navigation() {
<Suspense>
<Search />
</Suspense>
+ {session ? <NotificationLink notificationCount={notificationCount} /> : null}
{featureFlags?.enableLogin ? (
<LoginButton isAdminOrMod={isAdminOrMod} session={session} />
) : null}
diff --git a/apps/web/src/components/Navigation/navigation.actions.ts b/apps/web/src/components/Navigation/navigation.actions.ts
new file mode 100644
index 00000000..78d3fbc9
--- /dev/null
+++ b/apps/web/src/components/Navigation/navigation.actions.ts
@@ -0,0 +1,15 @@
+'use server';
+
+import { prisma } from '@repo/db';
+import { auth } from '~/server/auth';
+
+export async function getNotificationCount() {
+ const session = await auth();
+
+ return prisma.notification.count({
+ where: {
+ isRead: false,
+ toUserId: session?.user.id || '',
+ },
+ });
+}
diff --git a/apps/web/src/components/Navigation/notification-link.tsx b/apps/web/src/components/Navigation/notification-link.tsx
new file mode 100644
index 00000000..c89e0b0c
--- /dev/null
+++ b/apps/web/src/components/Navigation/notification-link.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { Bell } from '@repo/ui/icons';
+import { useQuery } from '@tanstack/react-query';
+import clsx from 'clsx';
+import Link from 'next/link';
+import { getNotificationCount } from './navigation.actions';
+
+export const NOTIFICATION_QUERY_KEY = 'notificationCounts';
+export function NotificationLink({ notificationCount }: { notificationCount: number }) {
+ // eventually lift this higher and pull new data and insert new rows into the notifications
+ // view if user is currently looking at it (example: twitter notif view)
+ const { data: count } = useQuery({
+ initialData: notificationCount,
+ queryKey: [NOTIFICATION_QUERY_KEY],
+ queryFn: () => getNotificationCount(),
+ refetchInterval: 60000, // one minute
+ });
+
+ return (
+ <Link
+ aria-label="notification page link"
+ href={{
+ pathname: '/notifications',
+ }}
+ >
+ <div className="relative flex items-center space-x-2">
+ <Bell className="h-5 w-5" />
+ {count > 0 && (
+ <span
+ className={clsx(
+ "absolute right-[2%] top-[4%] grid min-h-[18px] min-w-[18px] -translate-y-2/4 translate-x-2/4 place-items-center rounded-full bg-red-500 text-xs font-medium leading-none text-white content-['']",
+ count > 9 && 'w-7',
+ count > 20 && 'w-8',
+ )}
+ >
+ {count > 20 ? `${20}+` : count}
+ </span>
+ )}
+ </div>
+ </Link>
+ );
+}
diff --git a/apps/web/src/components/infinite-list.tsx b/apps/web/src/components/infinite-list.tsx
new file mode 100644
index 00000000..38d0f8d6
--- /dev/null
+++ b/apps/web/src/components/infinite-list.tsx
@@ -0,0 +1,67 @@
+import type { ReactNode, RefObject } from 'react';
+import { useEffect, useRef, useState } from 'react';
+
+interface Props {
+ children: ReactNode;
+ isLoadingNext: boolean;
+ next: () => void;
+ hasNext: boolean;
+ loader: ReactNode;
+}
+
+const ROOT_MARGIN = '200px';
+
+const DEFAULT_OPTIONS = {
+ rootMargin: ROOT_MARGIN,
+ threshold: 1,
+};
+
+export function useObserver(ref: RefObject<HTMLDivElement>, options?: IntersectionObserverInit) {
+ const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
+ const observerRef = useRef<IntersectionObserver>();
+
+ if (!observerRef.current && typeof IntersectionObserver !== 'undefined') {
+ observerRef.current = new IntersectionObserver(
+ ([entry]) => {
+ if (entry) {
+ setEntry(entry);
+ }
+ },
+ {
+ ...DEFAULT_OPTIONS,
+ ...options,
+ },
+ );
+ }
+
+ useEffect(() => {
+ const loaderEl = ref.current;
+ const observer = observerRef.current;
+ if (!loaderEl || !observer) return;
+
+ observer.observe(loaderEl);
+ return () => observer.unobserve(loaderEl);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ref.current]);
+
+ return entry;
+}
+
+export default function InfiniteList({ children, hasNext, isLoadingNext, next, loader }: Props) {
+ const loaderRef = useRef<HTMLDivElement>(null);
+ const entry = useObserver(loaderRef);
+
+ useEffect(() => {
+ if (isLoadingNext || !entry?.isIntersecting || !hasNext) return;
+ console.log('call nnext');
+ next();
+ }, [entry?.isIntersecting, isLoadingNext, hasNext, next]);
+
+ return (
+ <>
+ {children}
+ {isLoadingNext ? loader : null}
+ {hasNext ? <div ref={loaderRef} /> : null}
+ </>
+ );
+}
diff --git a/apps/web/src/components/loader.tsx b/apps/web/src/components/loader.tsx
new file mode 100644
index 00000000..9f780573
--- /dev/null
+++ b/apps/web/src/components/loader.tsx
@@ -0,0 +1,12 @@
+import { cn } from '@repo/ui/cn';
+import { Loader2 } from '@repo/ui/icons';
+import React from 'react';
+
+export function Loader({ className }: { className?: string }) {
+ return (
+ <div className="flex items-center justify-center" role="status">
+ <Loader2 className={cn('h-6 w-6 animate-spin ', className)} />
+ <span className="sr-only">Loading...</span>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/mention/actions.ts b/apps/web/src/components/mention/actions.ts
new file mode 100644
index 00000000..2683942c
--- /dev/null
+++ b/apps/web/src/components/mention/actions.ts
@@ -0,0 +1,21 @@
+'use server';
+
+import { prisma } from '@repo/db';
+
+export async function searchUsers(query: string) {
+ if (query.length > 39) {
+ throw new Error('Query limited to 39 characters');
+ }
+
+ return prisma.user.findMany({
+ where: {
+ name: {
+ contains: query,
+ },
+ },
+ orderBy: {
+ name: 'desc',
+ },
+ take: 10,
+ });
+}
diff --git a/apps/web/src/components/mention/mention-input.tsx b/apps/web/src/components/mention/mention-input.tsx
new file mode 100644
index 00000000..bd7d27b0
--- /dev/null
+++ b/apps/web/src/components/mention/mention-input.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import { Textarea, type TextareaProps } from '@repo/ui/components/textarea';
+import { useState, type ChangeEvent, type KeyboardEvent, type RefObject } from 'react';
+import { useDebouncedValue } from '~/utils/useDebouncedValue';
+import { UserResults } from './user-results';
+
+const NO_OP_KEYS = ['ArrowDown', 'ArrowUp', 'Tab', 'Enter'];
+
+type Modify<T, R> = Omit<T, keyof R> & R;
+type Props = Modify<
+ TextareaProps,
+ {
+ forwardedref: RefObject<HTMLTextAreaElement>;
+ onChange: (e: string) => void;
+ }
+>;
+export function MentionInput(props: Props) {
+ const [text, setText] = useState('');
+ const [query, setQuery] = useState('');
+ const [isQuerying, setIsQuerying] = useState(false);
+ const deferredQuery = useDebouncedValue(query, 750);
+
+ const onSelectedUser = (user: string) => {
+ const newText = insert(user);
+ setText(newText);
+ setIsQuerying(false);
+ setQuery('');
+ props.onChange?.(newText);
+ };
+
+ const onChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
+ const text = e.currentTarget.value;
+ setText(text);
+ props.onChange?.(text);
+ };
+
+ const getWordOnCursor = (text: string, cursorPosition: number) => {
+ const textBeforeCursor = text.slice(0, cursorPosition);
+ const textAfterCursor = text.slice(cursorPosition);
+
+ const lastWordBeforeCursor = textBeforeCursor.split(/\s+/).pop();
+ const firstWordAfterCursor = textAfterCursor.split(/\s+/).shift() || '';
+
+ return `${lastWordBeforeCursor}${firstWordAfterCursor}`;
+ };
+
+ const insert = (username: string) => {
+ if (!props.forwardedref.current || !query) {
+ return '';
+ }
+
+ const text = props.forwardedref.current.value;
+ const cursorPosition = props.forwardedref.current.selectionStart;
+
+ const fullWord = getWordOnCursor(text, cursorPosition);
+
+ return `${text.slice(0, cursorPosition - fullWord.length)}@${username}${text.slice(
+ cursorPosition,
+ )}`;
+ };
+
+ // this handles the scenario where a user uses arrow keys
+ // to navigate back to a mention
+ // need to handle case where if hitting arrows while in the same word do not display the
+ // popover unless a down arrow is used. can probably just use current query !== deferredQuery + isQuerying var to decide or
+ const onKeyUp = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Escape') {
+ setIsQuerying(false);
+ return;
+ }
+ const cursorPosition = e.currentTarget.selectionStart;
+
+ const fullWord = getWordOnCursor(text, cursorPosition);
+
+ if (fullWord?.startsWith('@')) {
+ const [, query = ''] = fullWord.split('@');
+ if (query) {
+ setIsQuerying(true);
+ } else {
+ setIsQuerying(false);
+ }
+ setQuery(query);
+ } else {
+ setIsQuerying(false);
+ }
+
+ props.onKeyUp?.(e);
+ };
+
+ const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
+ // when the popover is visible we only want the up and down arrow keys
+ // to select from the user list
+ if (isQuerying && NO_OP_KEYS.includes(e.key)) {
+ e.preventDefault();
+ }
+
+ props.onKeyDown?.(e);
+ };
+
+ return (
+ <div className="relative">
+ <Textarea
+ {...props}
+ autoFocus
+ className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"
+ onChange={onChange}
+ onKeyUp={onKeyUp}
+ onKeyDown={onKeyDown}
+ ref={props.forwardedref}
+ />
+ <UserResults
+ query={deferredQuery}
+ isOpen={isQuerying}
+ onFocusOutside={() => setIsQuerying(false)}
+ onSelectedUser={onSelectedUser}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/mention/user-results.tsx b/apps/web/src/components/mention/user-results.tsx
new file mode 100644
index 00000000..dafebef3
--- /dev/null
+++ b/apps/web/src/components/mention/user-results.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import { cn } from '@repo/ui/cn';
+import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';
+import { Popover, PopoverAnchor, PopoverContent } from '@repo/ui/components/popover';
+import { useQuery } from '@tanstack/react-query';
+import { useEffect, useRef, useState } from 'react';
+import { searchUsers } from './actions';
+import { useToast } from '@repo/ui/components/use-toast';
+import { Loader } from '../loader';
+
+interface Props {
+ isOpen: boolean;
+ query: string;
+ onFocusOutside: () => void;
+ onSelectedUser: (user: string) => void;
+}
+
+export function UserResults({ isOpen, onFocusOutside, onSelectedUser, query }: Props) {
+ const { toast } = useToast();
+ const popoverRef = useRef<HTMLDivElement | null>(null);
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const {
+ data: users,
+ isLoading,
+ error,
+ } = useQuery({
+ retry: false,
+ staleTime: 10000,
+ queryKey: ['search-users', query],
+ queryFn: () => {
+ return searchUsers(query);
+ },
+ enabled: Boolean(query),
+ });
+
+ // when we fetch new users or toggle the popover we want to reset the
+ // index to 0
+ useEffect(() => {
+ setSelectedIndex(0);
+ }, [query]);
+
+ useEffect(() => {
+ if (error) {
+ toast({
+ title: 'Query limit exceeded!',
+ description: 'Usernames are limited to 39 characters.',
+ variant: 'destructive',
+ });
+ }
+ }, [error, toast]);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ const scrollTo = (index: number) => {
+ const node = popoverRef.current?.children[0]?.children[index];
+ node?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'nearest',
+ });
+ };
+
+ window.addEventListener(
+ 'keydown',
+ (e) => {
+ if (!users) {
+ return;
+ }
+
+ if (e.key === 'ArrowDown') {
+ setSelectedIndex((si) => {
+ const index = (si + 1) % users.length;
+ scrollTo(index);
+ return index;
+ });
+ }
+ if (e.key === 'ArrowUp') {
+ setSelectedIndex((si) => {
+ const index = si - 1 < 0 ? users.length - 1 : si - 1;
+ scrollTo(index);
+ return index % users.length;
+ });
+ }
+ },
+ { signal: controller.signal },
+ );
+
+ window.addEventListener(
+ 'keyup',
+ (e) => {
+ if ((e.key === 'Tab' || e.key === 'Enter') && isOpen) {
+ const selectedUser = users?.[selectedIndex];
+ if (selectedUser) {
+ onSelectedUser(selectedUser.name);
+ }
+ }
+ },
+ { signal: controller.signal },
+ );
+
+ return () => controller.abort();
+ }, [onSelectedUser, selectedIndex, isOpen, users]);
+
+ return (
+ <Popover open={isOpen}>
+ <PopoverAnchor className="absolute bottom-0 left-0" />
+ <PopoverContent
+ ref={popoverRef}
+ className="absolute left-0 h-80 w-80 overflow-y-auto border-gray-700 bg-zinc-100 p-0 dark:bg-zinc-900"
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ onInteractOutside={onFocusOutside}
+ >
+ {isLoading ? (
+ <div className="flex h-full items-center justify-center text-lg font-semibold">
+ <Loader className="h-8 w-8" />
+ </div>
+ ) : (
+ <>
+ {(users?.length ?? 0) > 0 ? (
+ <ul>
+ {users?.map((user, index) => {
+ return (
+ <li key={user.id}>
+ <button
+ onClick={() => {
+ const selectedUser = users?.[index];
+ if (selectedUser) {
+ onSelectedUser(selectedUser.name);
+ }
+ }}
+ className={cn(
+ selectedIndex === index ? 'bg-zinc-400/50 dark:bg-zinc-600/50' : '',
+ 'flex w-full cursor-pointer justify-start gap-3 rounded-none px-4 py-3 hover:bg-zinc-400/50 dark:hover:bg-zinc-600/50',
+ )}
+ >
+ <Avatar className="h-10 w-10 border border-gray-700">
+ <AvatarImage src={user.image ?? ''} alt="user avatar" />
+ <AvatarFallback className="bg-gray-700 text-white">
+ {user?.name.charAt(0)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex flex-col">
+ <span className="text-sm font-bold text-white">{user.name}</span>
+ <span className="text-xs text-gray-500">@{user.name}</span>
+ </div>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <div className="flex h-full items-center justify-center text-lg font-semibold">
+ Users not found.
+ </div>
+ )}
+ </>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/components/rich-markdown-editor.tsx b/apps/web/src/components/rich-markdown-editor.tsx
index 4be7f62f..8d4630a1 100644
--- a/apps/web/src/components/rich-markdown-editor.tsx
+++ b/apps/web/src/components/rich-markdown-editor.tsx
@@ -143,8 +143,6 @@ export function RichMarkdownEditor({
}, [startUpload, allowImageUpload]);
const handlePasta = async (event: React.ClipboardEvent<HTMLDivElement>) => {
- event.preventDefault();
-
// only allow image if it's enabled
if (!allowImageUpload) return;
@@ -152,6 +150,8 @@ export function RichMarkdownEditor({
if (!firstImage) return;
if (firstImage.kind !== 'file') return;
+ event.preventDefault();
+
const blob = firstImage.getAsFile();
if (!blob) return;
diff --git a/apps/web/src/components/search/search-bar.tsx b/apps/web/src/components/search/search-bar.tsx
index 8c09901e..6d5908f1 100644
--- a/apps/web/src/components/search/search-bar.tsx
+++ b/apps/web/src/components/search/search-bar.tsx
@@ -22,7 +22,7 @@ export default function SearchBar({ setOpen }: { setOpen: (v: boolean) => void }
{/* Desktop Bar */}
<Button
variant="outline"
- className="text-muted-foreground hidden w-64 justify-between gap-3 text-sm lg:inline-flex"
+ className="text-muted-foreground mr-2 hidden w-64 justify-between gap-3 text-sm lg:inline-flex"
onClick={() => setOpen(true)}
>
<SearchIcon />
diff --git a/apps/web/src/utils/relativeTime.ts b/apps/web/src/utils/relativeTime.ts
index 1a2dafe8..40450ef6 100644
--- a/apps/web/src/utils/relativeTime.ts
+++ b/apps/web/src/utils/relativeTime.ts
@@ -1,8 +1,15 @@
-import { formatDistanceToNowStrict } from 'date-fns';
+import { formatDistanceToNow, formatDistanceToNowStrict } from 'date-fns';
-export const getRelativeTime = (date: Date | string) => {
+export const getRelativeTimeStrict = (date: Date | string) => {
if (typeof date === 'string') date = new Date(date);
return formatDistanceToNowStrict(date, {
addSuffix: true,
});
};
+
+export const getRelativeTime = (date: Date | string) => {
+ if (typeof date === 'string') date = new Date(date);
+ return formatDistanceToNow(date, {
+ addSuffix: true,
+ });
+};
diff --git a/apps/web/src/utils/useDebouncedValue.ts b/apps/web/src/utils/useDebouncedValue.ts
new file mode 100644
index 00000000..c9303a35
--- /dev/null
+++ b/apps/web/src/utils/useDebouncedValue.ts
@@ -0,0 +1,12 @@
+import { useEffect, useState } from 'react';
+
+export const useDebouncedValue = <T>(value: T, threshold = 500) => {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+ useEffect(() => {
+ const id = setTimeout(() => setDebouncedValue(value), threshold);
+
+ return () => clearTimeout(id);
+ }, [value, threshold]);
+
+ return debouncedValue;
+};
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index 9ebc1ba0..182afdf6 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -190,6 +190,7 @@ model Challenge {
sharedSolution SharedSolution[]
Report Report[] @relation("report_challenge")
TrackChallenge TrackChallenge[]
+ Notification Notification[]
@@index([userId])
}
@@ -444,16 +445,22 @@ model Notification {
toUserId String
fromUser User @relation("notificationFromUser", fields: [fromUserId], references: [id])
fromUserId String
- sharedSolutionId Int?
- sharedSolution SharedSolution? @relation(fields: [sharedSolutionId], references: [id])
commentId Int?
comment Comment? @relation(fields: [commentId], references: [id])
/// could be comment text or solution title to avoid having to join to grab this data
content String?
- url String?
+ /// can be used to replace the blurb (eg: mention you in a comment)
+ blurb String?
+ /// use this instead of building the url on the fly (avoids a lot of joins and perf hits to build a string)
+ url String
+ Challenge Challenge? @relation(fields: [challengeId], references: [id])
+ challengeId Int?
+ SharedSolution SharedSolution? @relation(fields: [sharedSolutionId], references: [id])
+ sharedSolutionId Int?
@@index([toUserId])
@@index([fromUserId])
- @@index([sharedSolutionId])
@@index([commentId])
+ @@index([challengeId])
+ @@index([sharedSolutionId])
}
diff --git a/packages/db/seed/prod.ts b/packages/db/seed/prod.ts
index 3c55ce08..6645c213 100644
--- a/packages/db/seed/prod.ts
+++ b/packages/db/seed/prod.ts
@@ -38,7 +38,7 @@ try {
create: {
id: TYPE_CHALLENGE_ID,
- name: 'Type Challenges',
+ name: 'type-challenges',
userLinks: {
create: {
url: 'https://tsch.js.org/',
diff --git a/packages/ui/package.json b/packages/ui/package.json
index defc5bae..aac7da82 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -58,6 +58,7 @@
"clsx": "^2.0.0",
"lucide-react": "^0.260.0",
"next-themes": "^0.2.1",
+ "mdast-util-find-and-replace": "^3.0.1",
"react": "^18.2.0",
"react-day-picker": "^8.8.0",
"react-hook-form": "^7.45.1",
diff --git a/packages/ui/src/components/markdown.tsx b/packages/ui/src/components/markdown.tsx
index 6fe35e2a..522167c7 100644
--- a/packages/ui/src/components/markdown.tsx
+++ b/packages/ui/src/components/markdown.tsx
@@ -1,6 +1,7 @@
'use client';
import clsx from 'clsx';
+import { userMentions } from './utils/mentions';
import { useTheme } from 'next-themes';
import { useState } from 'react';
import ReactMarkdown from 'react-markdown';
@@ -13,7 +14,6 @@ import { vscDarkPlus } from '../themes/vs-dark-plus';
import { Tooltip, TooltipContent, TooltipTrigger } from './tooltip';
import { Button } from './button';
import { Check, Copy } from '../icons';
-// import rehypeRaw from 'rehype-raw';
const HTML_COMMENT_REGEX = new RegExp('<!--([\\s\\S]*?)-->', 'g');
@@ -42,7 +42,17 @@ function removeHtmlComments(): Transformer {
};
}
-export function Markdown({ children, className }: { children: string; className?: string }) {
+export function Markdown({
+ children,
+ className,
+ disableMentions = false,
+ disableCopy = false,
+}: {
+ children: string;
+ className?: string;
+ disableMentions?: boolean;
+ disableCopy?: boolean;
+}) {
const { theme } = useTheme();
const syntaxHighlighterTheme = theme === 'light' ? vs : vscDarkPlus;
@@ -76,7 +86,7 @@ export function Markdown({ children, className }: { children: string; className?
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<div className="relative">
- <CopyButton text={String(children).replace(/\n$/, '')} />
+ {!disableCopy ? <CopyButton text={String(children).replace(/\n$/, '')} /> : null}
<SyntaxHighlighter
PreTag="section" // parent tag
className={clsx(className, 'rounded-xl dark:rounded-md')}
@@ -110,7 +120,7 @@ export function Markdown({ children, className }: { children: string; className?
// FIXME: this is vuln to XSS and I don't know why we use it, let's remove it
// or add in a sanitizer lib like: https://github.com/rehypejs/rehype-sanitize
// rehypePlugins={[rehypeRaw as any]}
- remarkPlugins={[removeHtmlComments, remarkGfm]}
+ remarkPlugins={[removeHtmlComments, remarkGfm, ...(disableMentions ? [] : [userMentions])]}
>
{children}
</ReactMarkdown>
diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx
index 73144fe7..3275c2ca 100644
--- a/packages/ui/src/components/popover.tsx
+++ b/packages/ui/src/components/popover.tsx
@@ -7,6 +7,8 @@ const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
+const PopoverAnchor = PopoverPrimitive.Anchor;
+
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
@@ -26,4 +28,4 @@ const PopoverContent = React.forwardRef<
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
-export { Popover, PopoverTrigger, PopoverContent };
+export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx
index 3d136621..71f55ca1 100644
--- a/packages/ui/src/components/select.tsx
+++ b/packages/ui/src/components/select.tsx
@@ -38,7 +38,7 @@ const SelectContent = React.forwardRef<
<SelectPrimitive.Portal>
<SelectPrimitive.Content
className={cn(
- 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 min-w-[8rem] overflow-hidden rounded-md border shadow-md',
+ 'text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-white shadow-md dark:bg-zinc-900',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
diff --git a/packages/ui/src/components/utils/mentions.ts b/packages/ui/src/components/utils/mentions.ts
new file mode 100644
index 00000000..14ad0e3f
--- /dev/null
+++ b/packages/ui/src/components/utils/mentions.ts
@@ -0,0 +1,60 @@
+// @ts-nocheck
+import { findAndReplace } from 'mdast-util-find-and-replace';
+
+/**
+ * yoinked from https://github.com/remarkjs/remark-github/blob/main/lib/index.js#L177
+ * courtesy of @hacksore
+ */
+export function buildUrl(values) {
+ const base = '';
+
+ if (values.type === 'mention') {
+ return [base, values.user].join('/');
+ }
+
+ const { project, user } = values;
+
+ if (values.type === 'commit') {
+ return [base, user, project, 'commit', values.hash].join('/');
+ }
+
+ if (values.type === 'issue') {
+ return [base, user, project, 'issues', values.no].join('/');
+ }
+
+ // `values.type` is `'compare'`
+ return [base, user, project, 'compare', `${values.base}...${values.compare}`].join('/');
+}
+
+const userGroup = '[\\da-z][-\\da-z]{0,38}';
+const mentionRegex = new RegExp(`(@${userGroup}(?:\\/${userGroup})?)`, 'gi');
+
+export function userMentions() {
+ return function (tree) {
+ findAndReplace(tree, [[mentionRegex, replaceMention]], { ignore: ['link', 'linkReference'] });
+
+ /**
+ * @type {ReplaceFunction}
+ * @param {string} value
+ * @param {string} username
+ * @param {RegExpMatchObject} match
+ */
+ function replaceMention(value, username, match) {
+ if (
+ /[\w`]/.test(match.input.charAt(match.index - 1)) ||
+ /[/\w`]/.test(match.input.charAt(Number(match.index) + Number(value.length)))
+ ) {
+ return false;
+ }
+
+ const url = buildUrl({ type: 'mention', user: username });
+
+ if (!url) return false;
+
+ /** @type {PhrasingContent} */
+ const node = { type: 'text', value };
+
+ return { type: 'link', title: null, url, children: [node] };
+ }
+ };
+}
diff --git a/packages/ui/src/icons.ts b/packages/ui/src/icons.ts
index 04f9bda5..74994581 100644
--- a/packages/ui/src/icons.ts
+++ b/packages/ui/src/icons.ts
@@ -3,7 +3,9 @@ export {
ArrowDownNarrowWide,
ArrowUp,
ArrowUpNarrowWide,
+ AtSign,
BadgeInfo,
+ Bell,
BellRing,
Binary,
Bookmark,
@@ -26,6 +28,7 @@ export {
Diamond,
ExternalLink,
Flag,
+ Heart,
GitBranch,
Github,
Loader,
@@ -52,6 +55,7 @@ export {
Shapes,
Share,
Shield,
+ ShieldAlert,
Sparkle,
Sparkles,
SquareSlash,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ed5e4276..75017de2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -802,6 +802,9 @@ importers:
lucide-react:
specifier: ^0.260.0
version: 0.260.0([email protected])
+ mdast-util-find-and-replace:
+ specifier: ^3.0.1
+ version: 3.0.1
next-themes:
specifier: ^0.2.1
@@ -6102,6 +6105,9 @@ packages:
resolution: {integrity: sha512-MTtdFRz/eMDHXzeK6W3dO7mXUlF82Gom4y0oOgvHhh/HXZAGvIQDUvQ0SuUx+j2tv44b8xTHOm8K/9OoRFnXKw==}
+ resolution: {integrity: sha512-SG21kZHGC3XRTSUhtofZkBzZTJNM5ecCi0SK2IMKmSXR8vO3peL+kb1O0z7Zl83jKtutG4k5Wv/W7V3/YHvzPA==}
+
resolution: {integrity: sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==}
@@ -14147,6 +14153,13 @@ snapshots:
unist-util-is: 5.2.1
unist-util-visit-parents: 5.1.3
+ dependencies:
+ '@types/mdast': 4.0.2
+ escape-string-regexp: 5.0.0
+ unist-util-is: 6.0.0
+ unist-util-visit-parents: 6.0.1
+
dependencies:
'@types/mdast': 3.0.12