Connect, collaborate, and grow with a community of TypeScript developers
wip: AOT challenge view (#1601)
bautistaaac98502c4ee97
diff --git a/apps/aot/package.json b/apps/aot/package.jsonindex d7c942fc..134fe078 100644--- a/apps/aot/package.json+++ b/apps/aot/package.json@@ -2,6 +2,7 @@"name": "aot","version": "0.1.0","private": true,+ "type": "module","packageManager": "[email protected]","scripts": {"build": "dotenv -e ../../.env next build",@@ -15,29 +16,41 @@"typecheck": "tsc --noEmit"},"dependencies": {+ "@hookform/resolvers": "^3.1.1",+ "@radix-ui/react-dialog": "^1.0.4",+ "@repo/auth": "workspace:*",+ "@repo/db": "workspace:*",+ "@repo/monaco": "workspace:*",+ "@repo/ui": "workspace:*","@tanstack/react-query": "5.51.21",+ "@tanstack/react-query-devtools": "5.51.21","@tanstack/react-table": "^8.20.5","@trpc/client": "^11.0.0-rc.446","@trpc/react-query": "^11.0.0-rc.446","@trpc/server": "^11.0.0-rc.446",+ "@uploadthing/react": "^6.2.2","@vercel/edge-config": "^0.2.1",+ "bad-words": "^3.0.4","clsx": "^2.0.0",+ "date-fns": "^2.30.0",+ "lodash": "^4.17.21",+ "lz-string": "^1.5.0",+ "nanoid": "^5.0.7","next": "14.2.5","next-themes": "^0.2.1","react": "18.2.0","react-dom": "18.2.0",+ "react-hook-form": "^7.45.1","server-only": "^0.0.1","superjson": "^2.2.1",- "zod": "3.23.3"+ "uploadthing": "6.3.1",+ "zod": "3.23.3",+ "zustand": "^4.3.9"},"devDependencies": {- "@repo/auth": "workspace:*",- "@repo/db": "workspace:*","@repo/lint": "workspace:*",- "@repo/monaco": "workspace:*","@repo/og-utils": "workspace:*","@repo/tsconfig": "workspace:*",- "@repo/ui": "workspace:*","@tailwindcss/container-queries": "^0.1.1","@tailwindcss/typography": "^0.5.9","@types/node": "^20.4.2",@@ -47,6 +60,8 @@"eslint": "^8.45.0","eslint-config-next": "^13.4.10","postcss": "^8.4.31",+ "prettier": "^3.1.1",+ "prettier-plugin-tailwindcss": "^0.5.9","tailwindcss": "3.4.7","tailwindcss-animate": "^1.0.6","typescript": "^5.3.3"diff --git a/apps/aot/public/next.svg b/apps/aot/public/next.svgdeleted file mode 100644index 5174b28c..00000000--- a/apps/aot/public/next.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>\ No newline at end of filediff --git a/apps/aot/public/vercel.svg b/apps/aot/public/vercel.svgdeleted file mode 100644index d2f84222..00000000--- a/apps/aot/public/vercel.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>\ No newline at end of filediff --git a/apps/aot/src/app/api/uploadthing/core.ts b/apps/aot/src/app/api/uploadthing/core.tsnew file mode 100644index 00000000..ea31f42b--- /dev/null+++ b/apps/aot/src/app/api/uploadthing/core.ts@@ -0,0 +1,65 @@+import { createUploadthing, type FileRouter } from 'uploadthing/next';+import { prisma } from '@repo/db';+import { auth } from '~/server/auth';++const f = createUploadthing({+ /**+ * Log out more information about the error, but don't return it to the client+ * @see https://docs.uploadthing.com/errors#error-formatting+ */+ errorFormatter: (err) => {+ console.log('Error uploading file', err.message);+ console.log(' - Above error caused by:', err.cause);++ return { message: err.message };+ },+});++type ValidFileTypes = 'audio' | 'blob' | 'image' | 'video';+type FileRouterInput =+ | Record<+ ValidFileTypes,+ {+ maxFileSize: '4MB';+ maxFileCount: number;+ }+ >+ | ValidFileTypes[];++// control the file sizes for all image types+const DEFAULT_IMAGE_UPLOAD_PARAMS: FileRouterInput = {+ audio: { maxFileSize: '4MB', maxFileCount: 1 },+ blob: { maxFileSize: '4MB', maxFileCount: 1 },+ image: { maxFileSize: '4MB', maxFileCount: 1 },+ video: { maxFileSize: '4MB', maxFileCount: 1 },+};++// FileRouter for your app, can contain multiple FileRoutes+export const ourFileRouter = {+ // Define as many FileRoutes as you like, each with a unique routeSlug+ imageUploader: f({+ 'image/png': DEFAULT_IMAGE_UPLOAD_PARAMS.image,+ 'image/jpeg': DEFAULT_IMAGE_UPLOAD_PARAMS.image,+ })+ // Set permissions and file types for this FileRoute+ .middleware(async () => {+ const session = await auth();++ // If you throw, the user will not be able to upload+ if (!session?.user?.id) throw new Error('Unauthorized');++ // Whatever is returned here is accessible in onUploadComplete as `metadata`+ return { userId: session.user.id };+ })+ .onUploadComplete(async ({ metadata, file }) => {+ // save to db+ await prisma.imageUpload.create({+ data: {+ url: file.url,+ user: { connect: { id: metadata.userId } },+ },+ });+ }),+} satisfies FileRouter;++export type OurFileRouter = typeof ourFileRouter;diff --git a/apps/aot/src/app/api/uploadthing/route.ts b/apps/aot/src/app/api/uploadthing/route.tsnew file mode 100644index 00000000..82d42abc--- /dev/null+++ b/apps/aot/src/app/api/uploadthing/route.ts@@ -0,0 +1,7 @@+import { createNextRouteHandler } from 'uploadthing/next';+import { ourFileRouter } from './core';++// Export routes for Next App Router+export const { GET, POST } = createNextRouteHandler({+ router: ourFileRouter,+});diff --git a/apps/aot/src/app/events/[year]/[day]/SettingsElements.tsx b/apps/aot/src/app/events/[year]/[day]/SettingsElements.tsxnew file mode 100644index 00000000..47461a96--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/SettingsElements.tsx@@ -0,0 +1,16 @@+'use client';+import { ResetEditorButton } from './_components/reset-editor-button';+import { EditorShortcutsButton } from './_components/editor-shortcuts/editor-shortcuts-button';+import { SettingsButton } from './_components/settings/settings-button';+import { FullscreenButton } from './fullscreen-button';++export function SettingsElements() {+ return (+ <>+ <ResetEditorButton />+ <EditorShortcutsButton />+ <SettingsButton />+ <FullscreenButton />+ </>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/bookmark.action.ts b/apps/aot/src/app/events/[year]/[day]/_components/bookmark.action.tsnew file mode 100644index 00000000..5b3a4de0--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/bookmark.action.ts@@ -0,0 +1,39 @@+'use server';++import { prisma } from '@repo/db';+import { revalidateTag } from 'next/cache';+import { auth } from '~/server/auth';++export const createCacheKeyForBookmarksTab = (userId: string) => `${userId}-bookmarked-challenges`;++export async function addOrRemoveBookmark(+ challengeId: number,+ userId: string,+ shouldBookmark: boolean,+) {+ const session = await auth();+ if (!session?.user?.id || userId !== session.user.id) return 'unauthorized';+ const bookmarkExists = await prisma.bookmark.findFirst({+ where: {+ challengeId,+ userId,+ },+ });+ if (!bookmarkExists && shouldBookmark) {+ await prisma.bookmark.create({+ data: {+ challengeId,+ userId,+ },+ });+ }+ if (bookmarkExists && !shouldBookmark) {+ await prisma.bookmark.delete({+ where: {+ id: bookmarkExists.id,+ },+ });+ }++ revalidateTag(createCacheKeyForBookmarksTab(userId));+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout-wrapper.tsx b/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout-wrapper.tsxnew file mode 100644index 00000000..46989243--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout-wrapper.tsx@@ -0,0 +1,42 @@+'use client';+import { useState, type ReactNode } from 'react';+import { LeftWrapper } from '../left-wrapper';+import { RightWrapper } from '../right-wrapper';+import { ChallengeLayout, MOBILE_BREAKPOINT } from './challenge-layout';+import type { Challenge } from './types';+import usePanelAdjustments from './usePanelAdjustments';++interface Props {+ challenge: Challenge;+ children: ReactNode;+}++export function ChallengeLayoutWrapper({ challenge, children }: Props) {+ const [isDesktop, setIsDesktop] = useState(window.innerWidth > MOBILE_BREAKPOINT);+ const LEFT_PANEL_BREAKPOINT = isDesktop ? 500 : 318;+ const DEFAULT_DESKTOP_WIDTH_PX = `${LEFT_PANEL_BREAKPOINT}px`;+ const { leftSide, adjustPanelSize, expandPanel, collapsePanel, isLeftPanelCollapsed } =+ usePanelAdjustments(DEFAULT_DESKTOP_WIDTH_PX, LEFT_PANEL_BREAKPOINT, isDesktop);++ const props = {+ setIsDesktop,+ isDesktop,+ leftSide,+ adjustPanelSize,+ expandPanel,+ collapsePanel,+ isLeftPanelCollapsed,+ };++ return (+ <ChallengeLayout+ left={+ <LeftWrapper expandPanel={expandPanel} isDesktop={isDesktop}>+ {children}+ </LeftWrapper>+ }+ right={<RightWrapper challenge={challenge} />}+ {...props}+ />+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout.tsx b/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout.tsxnew file mode 100644index 00000000..25d1e5cf--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/challenge-layout.tsx@@ -0,0 +1,315 @@+import { useEffect, useRef, type ReactNode, useState, type MutableRefObject, useMemo } from 'react';+import { create } from 'zustand';+import { persist } from 'zustand/middleware';+import { getEventDeltas } from '@repo/monaco/utils';+import { useFullscreenSettingsStore } from '../fullscreen-button';++export const DEFAULT_SETTINGS = {+ width: '500px',+ height: '300px',+};++type Settings = typeof DEFAULT_SETTINGS;+interface State {+ settings: Settings;+ updateSettings: (settings: Settings) => void;+}++export const useLayoutSettingsStore = create<State>()(+ persist(+ (set, get) => ({+ settings: DEFAULT_SETTINGS,+ updateSettings: (settings) => set({ settings: { ...get().settings, ...settings } }),+ }),+ {+ name: 'challenge-layout-settings',+ },+ ),+);++export interface ChallengeLayoutProps {+ left: ReactNode;+ right: ReactNode;+ setIsDesktop: (bool: boolean) => void;+ isDesktop: boolean;+ leftSide: MutableRefObject<HTMLDivElement | null>;+ collapsePanel: () => void;+ expandPanel: () => void;+ adjustPanelSize: (divideByW: number, divideByH: number, newDimensionValue: number) => void;+ isLeftPanelCollapsed: () => boolean;+ isPlayground?: boolean;+}++export const MOBILE_BREAKPOINT = 1025;+export const COLLAPSED_DESKTOP_WIDTH = 60;+export const COLLAPSED_MOBILE_HEIGHT = 41;++export function ChallengeLayout({+ left,+ right,+ setIsDesktop,+ isDesktop,+ leftSide,+ adjustPanelSize,+ collapsePanel,+ expandPanel,+ isLeftPanelCollapsed,+ isPlayground,+}: ChallengeLayoutProps) {+ const parent = useRef<HTMLDivElement>(null);+ const resizer = useRef<HTMLDivElement>(null);+ const rightSide = useRef<HTMLDivElement>(null);++ const { settings, updateSettings } = useLayoutSettingsStore();+ const { fssettings, updateFSSettings } = useFullscreenSettingsStore();+ const [isCollapsed, setIsCollapsed] = useState(false);++ const LEFT_PANEL_BREAKPOINT = isDesktop ? 500 : 318;+ const COLLAPSE_BREAKPOINT = isCollapsed ? 50 : 300;+ const _COLLAPSED_MOBILE_HEIGHT = isPlayground ? 0 : COLLAPSED_MOBILE_HEIGHT;+ const _COLLAPSED_DESKTOP_WIDTH = isPlayground ? 0 : COLLAPSED_DESKTOP_WIDTH;++ const DEFAULT_DESKTOP_WIDTH_PX = `${LEFT_PANEL_BREAKPOINT}px`;++ const isPanelCollapsed = useMemo(() => {+ const height = parseFloat(settings.height);+ const width = parseFloat(settings.width);++ return height <= _COLLAPSED_MOBILE_HEIGHT || width <= _COLLAPSED_DESKTOP_WIDTH;+ }, [settings.height, settings.width, _COLLAPSED_MOBILE_HEIGHT, _COLLAPSED_DESKTOP_WIDTH]);++ const leftStyle = useMemo(() => {+ const leftStyleIfDesktopCollapsed = {+ width: `${_COLLAPSED_DESKTOP_WIDTH}px`,+ minWidth: `${_COLLAPSED_DESKTOP_WIDTH}px`,+ };+ const leftStyleIfMobileCollapsed = {+ height: `${_COLLAPSED_MOBILE_HEIGHT}px`,+ minHeight: `${_COLLAPSED_MOBILE_HEIGHT}px`,+ };++ if (isDesktop) {+ return isPanelCollapsed+ ? leftStyleIfDesktopCollapsed+ : {+ width: settings.width,+ minWidth: `${LEFT_PANEL_BREAKPOINT}px`,+ };+ }+ return isPanelCollapsed+ ? leftStyleIfMobileCollapsed+ : {+ height: settings.height,+ minHeight: `${LEFT_PANEL_BREAKPOINT}px`,+ };+ }, [+ isDesktop,+ isPanelCollapsed,+ settings.height,+ settings.width,+ LEFT_PANEL_BREAKPOINT,+ _COLLAPSED_MOBILE_HEIGHT,+ _COLLAPSED_DESKTOP_WIDTH,+ ]);++ useEffect(() => {+ const ref = resizer.current;+ const leftRef = leftSide.current;+ const rightRef = rightSide.current;++ if (!leftRef || !rightRef || !ref) return;++ // initialize+ if (isDesktop) {+ leftRef.style.width = settings.width;+ } else {+ leftRef.style.height = settings.height;+ }++ // The current position of mouse+ let x = 0;+ let y = 0;+ // Width of left side on dekstop, height of top side on mobile;+ let leftWidth = 0;+ let topHeight = 0;++ const mouseMoveHandler = (e: MouseEvent | TouchEvent) => {+ const { dx, dy, currPosX, currPosY } = getEventDeltas(e, { x, y });+ const currPos = isDesktop ? currPosX : currPosY;+ const { width: divideByW, height: divideByH } = parent.current?.getBoundingClientRect() || {+ width: 0,+ height: 0,+ };++ const newDimensionValue = isDesktop+ ? ((leftWidth + dx) * 100) / divideByW+ : ((topHeight + dy) * 100) / divideByH;++ if (currPos <= COLLAPSE_BREAKPOINT) {+ collapsePanel();+ } else {+ adjustPanelSize(divideByW, divideByH, newDimensionValue);+ }++ // prevent cursor from blinking when you move mouse too fast (leaving resizer area)+ const cursorStyle = isDesktop ? 'col-resize' : 'row-resize';++ document.body.style.cursor = cursorStyle;++ [rightRef, leftRef].forEach((ref) => {+ ref.style.pointerEvents = 'none';+ ref.style.userSelect = 'none';+ });+ };++ const mouseDownHandler = (e: MouseEvent | TouchEvent) => {+ if (e instanceof MouseEvent) {+ // Get the current mouse position+ isDesktop ? (x = e.clientX) : (y = e.clientY);+ } else if (e instanceof TouchEvent) {+ // Get the current finger position+ isDesktop ? (x = e.touches[0]?.clientX ?? 0) : (y = e.touches[0]?.clientY ?? 0);+ }++ isDesktop+ ? (leftWidth = leftSide.current?.getBoundingClientRect().width!)+ : (topHeight = leftSide.current?.getBoundingClientRect().height!);++ // Attach the listeners to `document`+ if (e instanceof MouseEvent) {+ document.addEventListener('mousemove', mouseMoveHandler);+ document.addEventListener('mouseup', mouseUpHandler);+ } else if (e instanceof TouchEvent) {+ document.addEventListener('touchmove', mouseMoveHandler);+ document.addEventListener('touchend', mouseUpHandler, false);+ }+ };++ const mouseUpHandler = function () {+ setIsCollapsed(isLeftPanelCollapsed());++ // undo cursor col-resize from above+ document.body.style.removeProperty('cursor');++ // undo text selection prevention+ leftRef.style.removeProperty('user-select');+ rightRef.style.removeProperty('user-select');+ leftRef.style.removeProperty('pointer-events');+ rightRef.style.removeProperty('pointer-events');++ // Remove the handlers of `mousemove` and `mouseup` or `touchmove` and `touchend` from the `document`+ document.removeEventListener('touchmove', mouseMoveHandler);+ document.removeEventListener('mousemove', mouseMoveHandler);+ document.removeEventListener('touchend', mouseUpHandler);+ document.removeEventListener('mouseup', mouseUpHandler);++ isDesktop+ ? updateSettings({ width: `${leftRef.offsetWidth}px`, height: settings.height })+ : updateSettings({ width: settings.width, height: `${leftRef.offsetHeight}px` });+ };++ // handle window resize+ const resizeHandler = () => {+ const isDesktop = window.innerWidth > MOBILE_BREAKPOINT;+ setIsDesktop(isDesktop);++ const leftRef = leftSide.current;+ if (!leftRef) return;++ const height = parseFloat(leftRef.style.height);+ const width = parseFloat(leftRef.style.width);++ if (height <= _COLLAPSED_MOBILE_HEIGHT || width <= _COLLAPSED_DESKTOP_WIDTH) {+ if (isDesktop) {+ leftRef.style.width = `${_COLLAPSED_DESKTOP_WIDTH}px`;+ updateSettings({ width: `${_COLLAPSED_DESKTOP_WIDTH}px`, height: '300px' });+ } else {+ leftRef.style.height = `${_COLLAPSED_MOBILE_HEIGHT}px`;+ updateSettings({ width: '500px', height: `${_COLLAPSED_MOBILE_HEIGHT}px` });+ }+ }+ };++ const handleResizerDoubleClick = () => {+ setIsCollapsed(isLeftPanelCollapsed());++ if (!leftSide.current || !rightSide.current) return;++ const currentSize = isDesktop+ ? parseInt(getComputedStyle(leftSide.current).width)+ : parseInt(getComputedStyle(leftSide.current).height);++ if (currentSize < LEFT_PANEL_BREAKPOINT) {+ expandPanel();+ } else {+ collapsePanel();+ }++ isDesktop+ ? updateSettings({ width: `${leftRef.offsetWidth}px`, height: settings.height })+ : updateSettings({ width: settings.width, height: `${leftRef.offsetHeight}px` });+ };++ window.addEventListener('resize', resizeHandler);+ ref.addEventListener('mousedown', mouseDownHandler);+ ref.addEventListener('touchstart', mouseDownHandler, false);+ ref.addEventListener('dblclick', handleResizerDoubleClick);++ return () => {+ window.removeEventListener('resize', resizeHandler);+ ref.removeEventListener('mousedown', mouseDownHandler);+ ref.removeEventListener('touchstart', mouseDownHandler);+ ref.removeEventListener('dblclick', handleResizerDoubleClick);+ };+ }, [+ COLLAPSE_BREAKPOINT,+ DEFAULT_DESKTOP_WIDTH_PX,+ LEFT_PANEL_BREAKPOINT,+ adjustPanelSize,+ collapsePanel,+ expandPanel,+ isCollapsed,+ isDesktop,+ setIsDesktop,+ isLeftPanelCollapsed,+ leftSide,+ settings,+ updateSettings,+ _COLLAPSED_DESKTOP_WIDTH,+ _COLLAPSED_MOBILE_HEIGHT,+ ]);++ return (+ <div+ className="flex flex-col px-4 pb-4 lg:flex-row"+ ref={parent}+ style={{ height: fssettings.isFullscreen ? '100vh' : 'calc(100vh - 3.5rem)' }}+ >+ <div+ className={`w-full overflow-hidden rounded-2xl border-zinc-300 bg-white dark:border-zinc-700 dark:bg-zinc-800 ${+ !isPlayground && 'border'+ }`}+ ref={leftSide}+ style={{ ...leftStyle }}+ >+ {left}+ </div>+ <div+ className={+ isDesktop+ ? 'resizer group relative cursor-col-resize p-2'+ : 'resizer relative cursor-row-resize p-2'+ }+ ref={resizer}+ >+ <div className="group-hover:bg-primary group-active:bg-primary group-hover:dark:bg-primary absolute left-1/2 top-1/2 h-1 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full bg-neutral-400 duration-300 group-active:duration-75 lg:h-24 lg:w-1 dark:bg-neutral-700" />+ </div>+ <div+ className="flex min-h-[90px] w-full flex-1 flex-grow flex-col overflow-hidden rounded-2xl border border-zinc-300 lg:min-w-[500px] dark:border-zinc-700"+ ref={rightSide}+ >+ {right}+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/challenge-store.ts b/apps/aot/src/app/events/[year]/[day]/_components/challenge-store.tsnew file mode 100644index 00000000..1c2366e4--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/challenge-store.ts@@ -0,0 +1,30 @@+import type { Difficulty } from '@repo/db/types';+import { create } from 'zustand';+import { persist } from 'zustand/middleware';++interface ChallengeState {+ data:+ | {+ name: string;+ difficulty: Difficulty;+ shortDescription: string;+ description: string;+ prompt: string;+ }+ | undefined;+ setData: (data: NonNullable<ChallengeState['data']>) => void;+ clear: () => void;+}++export const useChallengeStore = create<ChallengeState>()(+ persist(+ (set, _get) => ({+ data: undefined,+ clear: () => set({ data: undefined }),+ setData: (data) => set({ data }),+ }),+ {+ name: 'create-challenge-data',+ },+ ),+);diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-input.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-input.tsxnew file mode 100644index 00000000..eb787ecd--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-input.tsx@@ -0,0 +1,135 @@+import { zodResolver } from '@hookform/resolvers/zod';+import { useSession } from '@repo/auth/react';+import { Button } from '@repo/ui/components/button';+import { Form, FormField, FormItem, FormMessage } from '@repo/ui/components/form';+import { Markdown } from '@repo/ui/components/markdown';+import { Loader2 } from '@repo/ui/icons';+import { useEffect, useRef, useState, type RefObject } from 'react';+import { useForm } from 'react-hook-form';+import { MentionInput } from '~/components/mention/mention-input';+import { singleFieldSchema, type SingleFieldSchema } from '~/utils/zodSingleStringField';++interface Props {+ mode: 'create' | 'edit' | 'reply';+ onCancel?: () => void;+ placeholder?: string;+ onSubmit: (text: string) => Promise<void>;+ defaultValue?: string;+}++export function CommentInput({ mode, onCancel, placeholder, onSubmit, defaultValue }: Props) {+ const { data: session } = useSession();+ const [commentMode, setCommentMode] = useState<'editor' | 'preview'>('editor');++ const textAreaRef = useRef<HTMLTextAreaElement>(null);++ const form = useForm<SingleFieldSchema>({+ resolver: zodResolver(singleFieldSchema),+ defaultValues: { text: defaultValue ?? '' },+ });+ const formValid = form.formState.isValid;+ const value = form.watch('text');+ useAutosizeTextArea(textAreaRef, value, commentMode);++ const submitComment = async ({ text }: { text: string }) => {+ try {+ await onSubmit(text);+ } catch (e) {+ console.error(e);+ } finally {+ form.reset();+ setCommentMode('editor');+ }+ };++ const isSubmitting = form.formState.isSubmitting;++ return (+ <div className="relative flex flex-col">+ {commentMode === 'editor' && (+ <div className="rounded-xl rounded-br-lg bg-neutral-100 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">+ <Form {...form}>+ <FormField+ control={form.control}+ name="text"+ render={({ field }) => (+ <FormItem>+ <MentionInput+ disabled={!session?.user}+ autoFocus+ className="resize-none border-0 px-3 py-2 focus-visible:ring-0 md:max-h-[calc(100vh_-_232px)]"+ onChange={(e) => {+ field.onChange(e);+ form.trigger();+ }}+ onKeyDown={(e) => {+ if (isSubmitting) {+ e.preventDefault();+ }+ }}+ placeholder={+ placeholder ?? !session?.user+ ? 'You need to be logged in to comment.'+ : 'Enter your comment here.'+ }+ forwardedref={textAreaRef}+ value={value}+ />+ <FormMessage className="absolute h-8 pl-3 leading-8" />+ </FormItem>+ )}+ />+ </Form>+ </div>+ )}+ {commentMode === 'preview' && (+ <div className="min-h-[5rem] overflow-y-auto break-words px-3 pt-2 text-sm md:max-h-[calc(100vh_-_232px)]">+ <Markdown>{value}</Markdown>+ </div>+ )}+ <div className="flex justify-end">+ <div className="flex gap-2 p-2 pl-0">+ <Button+ className="h-8"+ disabled={isSubmitting || value.length === 0}+ onClick={() => setCommentMode(commentMode === 'editor' ? 'preview' : 'editor')}+ variant={mode === 'create' ? 'secondary' : 'ghost'}+ >+ {commentMode === 'editor' ? 'Preview' : 'Edit'}+ </Button>+ {mode !== 'create' && (+ <Button className="h-8" onClick={() => onCancel?.()} variant="secondary">+ Cancel+ </Button>+ )}+ <Button+ className="h-8 w-[5.5rem] rounded-lg rounded-br-sm"+ disabled={value.length === 0 || isSubmitting || !formValid}+ onClick={form.handleSubmit(submitComment)}+ >+ {isSubmitting ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Comment'}+ </Button>+ </div>+ </div>+ </div>+ );+}++function useAutosizeTextArea(+ textAreaRef: RefObject<HTMLTextAreaElement>,+ value: string,+ commentMode: string,+) {+ useEffect(() => {+ if (textAreaRef.current) {+ // We need to reset the height momentarily to get the correct scrollHeight for the textarea+ textAreaRef.current.style.height = '0px';+ const scrollHeight = textAreaRef.current.scrollHeight;++ // We then set the height directly, outside of the render loop+ // Trying to set this with state or a ref will product an incorrect value.+ textAreaRef.current.style.height = `${scrollHeight}px`;+ }+ // eslint-disable-next-line+ }, [textAreaRef.current, value, commentMode]);+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-skeleton.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-skeleton.tsxnew file mode 100644index 00000000..927969bb--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment-skeleton.tsx@@ -0,0 +1,23 @@+import { Skeleton } from '@repo/ui/components/skeleton';++const SKELETONS = Array.from({ length: 3 }, (_, i) => i + 1);+export function CommentSkeleton() {+ return (+ <>+ {SKELETONS.map((id) => (+ <div key={id} className="space-y-2 px-4 py-2">+ <div className="flex justify-between ">+ <div className="flex items-center gap-2">+ <Skeleton className="h-10 w-10 rounded-full bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-5 w-20 bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div>+ <Skeleton className="h-5 w-16 bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ <Skeleton className=" h-16 w-full bg-zinc-300 px-3 dark:bg-zinc-700" />+ </div>+ ))}+ </>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/comment.action.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment.action.tsnew file mode 100644index 00000000..fb833d83--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment.action.ts@@ -0,0 +1,398 @@+'use server';++import { prisma } from '@repo/db';+import { auth } from '~/server/auth';+import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';+import type { PaginatedComments } from './getCommentRouteData';+import { getMentionsFromComment } from './getMentionsFromComment';+import type { ChallengeRouteData } from '../../getChallengeRouteData';+import type { SolutionRouteData } from '../../solutions/[solutionId]/getSolutionIdRouteData';++/**+ * @param comment a Challenge or Solution-based comment.+ * @returns the prisma create response.+ */+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';++ const commentToCreate = {+ text: comment.text,+ rootType: comment.rootType,+ ...(comment.rootType === 'CHALLENGE'+ ? { rootChallengeId: comment.root.id }+ : { rootSolutionId: comment.root.id }),+ };++ 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,+ parentComment: PaginatedComments['comments'][number],+) {+ const session = await auth();++ if (!session?.user?.id) return 'unauthorized';+ if (comment.text.length === 0) return 'text_is_empty';++ const replyToCreate = {+ text: comment.text,+ rootType: comment.rootType,+ ...(comment.rootType === 'CHALLENGE'+ ? { rootChallengeId: comment.root.id }+ : { rootSolutionId: comment.root.id }),+ };++ const replyThatWasCreated = await prisma.comment.create({+ data: {+ ...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) {+ const session = await auth();++ if (!session || !session.user) return 'unauthorized';+ 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,+ },+ });++ const isAuthorized = isAdminOrModerator(session) || isAuthor(session, comment.userId);+ if (!isAuthorized) {+ 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,+ userId: session.user.id,+ },+ data: {+ text,+ },+ });+}+/**+ * Deletes a comment given a comment ID. The user must be the author of the comment or have the role of 'ADMIN' or 'MODERATOR'.+ * @param comment_id The ID of the comment to be deleted.+ * @param author The ID of the user who authored the comment.+ * @returns 'unauthorized' if the user is not authorized, 'invalid_comment' if the comment ID is not provided, or undefined if the comment is successfully deleted.+ */+export async function deleteComment(comment_id: number) {+ const session = await auth();++ if (!session) return 'unauthorized';++ const rootComment = await prisma.comment.findFirstOrThrow({+ where: {+ id: comment_id,+ },+ });++ const isAuthorized = isAdminOrModerator(session) || isAuthor(session, rootComment.userId);+ if (!isAuthorized) {+ return 'unauthorized';+ }++ const children = await prisma.comment.findMany({+ where: {+ parentId: rootComment.id,+ },+ select: {+ id: true,+ },+ });++ // have to delete noti before original comment is gone+ await prisma.notification.deleteMany({+ where: {+ 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/aot/src/app/events/[year]/[day]/_components/comments/comment.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment.tsxnew file mode 100644index 00000000..47878a39--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comment.tsx@@ -0,0 +1,493 @@+'use client';++import { useSession } from '@repo/auth/react';+import { type CommentRoot } from '@repo/db/types';+import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';+import { Button } from '@repo/ui/components/button';+import { Markdown } from '@repo/ui/components/markdown';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { toast } from '@repo/ui/components/use-toast';+import {+ Calendar,+ ChevronDown,+ ChevronUp,+ Flag,+ MoreHorizontal,+ Pencil,+ Reply,+ Share,+ Trash2,+} from '@repo/ui/icons';+import clsx from 'clsx';+import { useParams, useSearchParams } from 'next/navigation';+import { useEffect, useRef, useState } from 'react';+import { z } from 'zod';+import { ReportDialog } from '~/components/report-dialog';+import { isAdminOrModerator } from '~/utils/auth-guards';+import { DefaultAvatar } from '~/utils/default-avatar';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import type { SolutionRouteData } from '../../solutions/[solutionId]/getSolutionIdRouteData';+import type { Challenge } from '../types';+import { Vote } from '../vote';+import { CommentInput } from './comment-input';+import { CommentSkeleton } from './comment-skeleton';+import { useCommentsReplies } from './comments.hooks';+import { CommentDeleteDialog } from './delete';+import { UserBadge } from './enhanced-user-badge';+import { type PaginatedComments, type PreselectedCommentMetadata } from './getCommentRouteData';++interface SingleCommentProps {+ comment: PaginatedComments['comments'][number];+ readonly?: boolean;+ isReply?: boolean;+ isToggleReply?: boolean;+ onClickReply?: () => void;+ onClickToggleReply?: () => void;+ preselectedCommentMetadata?: PreselectedCommentMetadata;+ deleteComment: (commentId: number) => Promise<void>;+ updateComment: (text: string, commentId: number) => Promise<void>;+}++type CommentProps = SingleCommentProps & {+ preselectedCommentMetadata?: PreselectedCommentMetadata;+ root: Challenge | SolutionRouteData;+ type: CommentRoot;+ deleteComment: (commentId: number) => Promise<void>;+ updateComment: (text: string, commentId: number) => Promise<void>;+};++const commentReportSchema = z+ .object({+ spam: z.boolean().optional(),+ threat: z.boolean().optional(),+ hate_speech: z.boolean().optional(),+ bullying: z.boolean().optional(),+ text: z.string().optional(),+ })+ .refine(+ (obj) => {+ const { spam, threat, hate_speech, bullying, text } = obj;+ return spam || threat || hate_speech || bullying || (text !== undefined && text !== '');+ },+ {+ path: ['text'],+ message: 'Your report should include an issue or a reason.',+ },+ );++export type CommentReportSchemaType = z.infer<typeof commentReportSchema>;++// million-ignore+export function Comment({+ comment,+ preselectedCommentMetadata,+ readonly = false,+ root,+ type,+ deleteComment,+ updateComment,+}: CommentProps) {+ const params = useSearchParams();+ const replyId = params.get('replyId');++ const hasPreselectedReply =+ preselectedCommentMetadata?.selectedComment?.id === comment.id && Boolean(replyId);++ const [showReplies, setShowReplies] = useState(hasPreselectedReply);+ const [isReplying, setIsReplying] = useState(false);++ const {+ status,+ data,+ fetchNextPage,+ addReplyComment,+ updateReplyComment,+ deleteReplyComment,+ showLoadMoreRepliesBtn,+ // @ts-ignore+ } = useCommentsReplies({+ enabled: showReplies,+ root,+ type,+ parentComment: comment,+ preselectedReplyId: hasPreselectedReply ? Number(replyId) : undefined,+ });++ const toggleReplies = () => setShowReplies(!showReplies);+ const toggleIsReplying = () => setIsReplying(!isReplying);++ return (+ <div className="flex flex-col px-2 py-1">+ <SingleComment+ preselectedCommentMetadata={preselectedCommentMetadata}+ comment={comment}+ isToggleReply={showReplies}+ onClickReply={toggleIsReplying}+ onClickToggleReply={toggleReplies}+ readonly={readonly}+ deleteComment={deleteComment}+ updateComment={updateComment}+ />+ {isReplying ? (+ <div className="relative mt-2 pb-2 pl-8">+ <Reply className="absolute left-2 top-2 h-4 w-4 opacity-50" />+ <CommentInput+ mode="edit"+ onCancel={() => {+ setIsReplying(false);+ }}+ onSubmit={async (text) => {+ await addReplyComment(text);+ setShowReplies(true);+ setIsReplying(false);+ }}+ />+ </div>+ ) : null}++ {showReplies && status === 'pending' ? <CommentSkeleton /> : null}+ {showReplies ? (+ <>+ <div className="flex flex-col gap-1 pl-6 pt-1">+ {data?.pages.flatMap((page) =>+ page.replies.map((reply) => (+ // this is a reply+ <SingleComment+ comment={reply}+ isReply+ key={reply.id}+ preselectedCommentMetadata={preselectedCommentMetadata}+ deleteComment={deleteReplyComment}+ updateComment={updateReplyComment}+ />+ )),+ )}+ </div>+ {showLoadMoreRepliesBtn ? (+ <Button+ variant="ghost"+ className="gap-1 text-xs text-neutral-500 duration-200 hover:text-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-300"+ onClick={() => fetchNextPage()}+ >+ <MoreHorizontal size={24} />+ Load More+ <span className="sr-only">Load More</span>+ </Button>+ ) : null}+ </>+ ) : null}+ </div>+ );+}++const SELECTED_CLASSES = 'rounded-md bg-sky-300/20';++// million-ignore+function SingleComment({+ comment,+ isReply,+ isToggleReply,+ onClickReply,+ onClickToggleReply,+ readonly = false,+ preselectedCommentMetadata,+ deleteComment,+ updateComment,+}: SingleCommentProps) {+ const { year, day } = useParams();+ const searchParams = useSearchParams();+ const replyId = searchParams.get('replyId');+ const [isEditing, setIsEditing] = useState(false);+ const elRef = useRef<HTMLDivElement | null>(null);+ const session = useSession();++ const isHighlighted = replyId+ ? Number(replyId) === comment.id+ : preselectedCommentMetadata?.selectedComment?.id === comment.id;++ async function copyPathNotifyUser(isReply: boolean) {+ try {+ await copyCommentUrlToClipboard(isReply);+ toast({+ title: 'Success!',+ variant: 'success',+ description: <p>Copied comment URL to clipboard!</p>,+ });+ } catch (error) {+ console.error(error);+ toast({+ title: 'Failure!',+ variant: 'destructive',+ description: <p>Something went wrong!</p>,+ });+ }+ }++ async function copyCommentUrlToClipboard(isReply: boolean) {+ const commentId = isReply ? comment.parentId : comment.id;+ const paramsObj = { replyId: String(comment.id) };+ const searchParams = new URLSearchParams(paramsObj);++ const { rootType, rootSolutionId } = comment;+ const baseURL = `${window.location.origin}/events/${year}/${day}`;+ const hasGetParams = isReply ? `?${searchParams.toString()}` : '';++ const shareUrl =+ rootType === 'CHALLENGE'+ ? `${baseURL}/comments/${commentId}${hasGetParams}`+ : `${baseURL}/solutions/${rootSolutionId}/comments/${commentId}${hasGetParams}`;++ await navigator.clipboard.writeText(shareUrl);+ }++ const loggedinUser = useSession();++ const isAuthor = loggedinUser.data?.user?.id === comment.user.id;+ const isAdminAndModerator = isAdminOrModerator(loggedinUser.data);++ const hasBeenEdited = comment.updatedAt.getTime() > comment.createdAt.getTime();++ useEffect(() => {+ if (!isHighlighted) return;+ const timeout = setTimeout(() => {+ elRef.current?.classList.remove(...SELECTED_CLASSES.split(' '));+ }, 5000);+ window.requestAnimationFrame(() => elRef.current?.scrollIntoView({ block: 'nearest' }));+ return () => {+ clearTimeout(timeout);+ };+ }, [isHighlighted]);++ return (+ <div+ id={`comment-${comment.id}`}+ className={clsx(+ 'relative p-2 pl-3',+ isHighlighted && SELECTED_CLASSES,+ 'transition-colors',+ 'duration-150',+ )}+ ref={elRef}+ >+ <div className="flex items-start justify-between gap-4 pr-[0.4rem]">+ <div className="mb-2 flex w-full items-center justify-between gap-1">+ <div className="flex items-center gap-2">+ <Avatar className="h-7 w-7">+ <AvatarImage alt="github profile picture" src={comment.user?.image ?? ''} />+ <AvatarFallback>+ <DefaultAvatar />+ </AvatarFallback>+ </Avatar>+ <UserBadge+ user={{+ name: comment.user?.name ?? '',+ image: comment.user?.image ?? '',+ bio: comment.user?.bio ?? '',+ roles: comment.user?.roles ?? [],+ }}+ hideLinks+ />+ </div>++ <Tooltip delayDuration={0.05}>+ <TooltipTrigger asChild>+ <div className="text-muted-foreground flex items-center gap-2 whitespace-nowrap text-xs">+ <Calendar className="h-4 w-4" />+ <span>{getRelativeTimeStrict(comment.createdAt)}</span>+ </div>+ </TooltipTrigger>+ <TooltipContent align="start" alignOffset={-55} className="rounded-xl">+ <span className="text-foreground text-xs">{comment.createdAt.toLocaleString()}</span>+ </TooltipContent>+ </Tooltip>+ </div>+ </div>+ {!isEditing && (+ <div className="-mb-1">+ <ExpandableContent content={comment.text} />+ {hasBeenEdited ? (+ <div className="text-muted-foreground flex items-center gap-2 whitespace-nowrap text-xs">+ Last edited at{' '}+ {new Intl.DateTimeFormat(undefined, {+ timeStyle: 'short',+ dateStyle: 'short',+ }).format(comment.updatedAt)}+ </div>+ ) : null}+ </div>+ )}+ {isEditing ? (+ <div className="mb-2">+ <CommentInput+ mode="edit"+ defaultValue={comment.text}+ onCancel={() => {+ setIsEditing(false);+ }}+ onSubmit={async (text) => {+ await updateComment(text, comment.id);+ setIsEditing(false);+ }}+ />+ </div>+ ) : null}+ <div className="my-auto mt-3 flex items-center gap-2">+ {!readonly && (+ <>+ <Vote+ voteCount={comment._count.vote}+ initialHasVoted={comment.vote.length > 0}+ disabled={!session?.data?.user?.id || comment.userId === session?.data?.user?.id}+ rootType="COMMENT"+ rootId={comment.id}+ onVote={(didUpvote: boolean) => {+ comment.vote = didUpvote+ ? [+ {+ userId: session?.data?.user?.id ?? '',+ },+ ]+ : [];+ comment._count.vote += didUpvote ? 1 : -1;+ }}+ />+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="secondary"+ size="xs"+ className="gap-2"+ onClick={() => {+ copyPathNotifyUser(Boolean(isReply));+ }}+ >+ <Share className="h-3 w-3" />+ <span className="sr-only">Share this comment</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Share</p>+ </TooltipContent>+ </Tooltip>+ {!isReply && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs" onClick={onClickReply}>+ <Reply className="h-3 w-3" />+ <span className="sr-only">Create a reply</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Reply</p>+ </TooltipContent>+ </Tooltip>+ )}+ {isAuthor ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs" onClick={() => setIsEditing(!isEditing)}>+ <Pencil className="h-3 w-3" />+ <span className="sr-only">Edit this comment</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Edit</p>+ </TooltipContent>+ </Tooltip>+ ) : null}+ {isAuthor || isAdminAndModerator ? (+ <Tooltip>+ <CommentDeleteDialog asChild comment={comment} deleteComment={deleteComment}>+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs">+ <Trash2 className="h-3 w-3" />+ <span className="sr-only">Delete this comment</span>+ </Button>+ </TooltipTrigger>+ </CommentDeleteDialog>+ <TooltipContent>+ <p>Delete</p>+ </TooltipContent>+ </Tooltip>+ ) : (+ <Tooltip>+ <ReportDialog triggerAsChild commentId={comment.id} reportType="COMMENT">+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs">+ <Flag className="h-3 w-3" />+ <span className="sr-only">Report this comment</span>+ </Button>+ </TooltipTrigger>+ </ReportDialog>+ <TooltipContent>+ <p>Report</p>+ </TooltipContent>+ </Tooltip>+ )}+ {comment._count.replies > 0 && (+ <Button+ variant="ghost"+ size="xs"+ className="z-50 ml-auto gap-1"+ onClick={onClickToggleReply}+ >+ {isToggleReply ? (+ <ChevronDown className="h-4 w-4" />+ ) : (+ <ChevronUp className="h-4 w-4" />+ )}++ <div className="text-xs">+ {comment._count.replies === 1 ? '1 reply' : `${comment._count.replies} replies`}+ </div>+ <span className="sr-only">Toggle replies view</span>+ </Button>+ )}+ </>+ )}+ </div>+ </div>+ );+}++function ExpandableContent({ content }: { content: string }) {+ const [expanded, setExpanded] = useState(true);+ const contentWrapperRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const handleResize = () => {+ if ((contentWrapperRef.current?.clientHeight ?? 0) > 300) {+ setExpanded(false);+ }+ };++ window.addEventListener('resize', handleResize);+ handleResize();++ return () => {+ window.removeEventListener('resize', handleResize);+ };+ }, [content]);++ return (+ <div+ className={clsx(+ { 'h-full': expanded, 'max-h-[300px]': !expanded },+ 'relative w-full overflow-hidden break-words pl-[1px] text-sm',+ )}+ ref={contentWrapperRef}+ >+ <Markdown>{content}</Markdown>+ {!expanded && (+ <div+ className="absolute top-0 flex h-full w-full cursor-pointer items-end bg-gradient-to-b from-transparent to-white dark:to-zinc-800"+ onClick={() => setExpanded(true)}+ >+ <div className="text-md text-label-1 dark:text-dark-label-1 flex w-full items-center justify-center hover:bg-transparent">+ Read more+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.constants.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.constants.tsnew file mode 100644index 00000000..5f943ed5--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.constants.ts@@ -0,0 +1,36 @@+export const sortKeys = [+ {+ label: 'Newest Comments',+ value: 'newest',+ key: 'createdAt',+ order: 'desc',+ },+ {+ label: 'Oldest Comments',+ value: 'oldest',+ key: 'createdAt',+ order: 'asc',+ },+ {+ label: 'Most Votes',+ value: 'votes',+ key: 'vote',+ order: 'desc',+ },+ {+ label: 'Most Replies',+ value: 'replies',+ key: 'replies',+ order: 'desc',+ },+] as const;++export const commentErrors = {+ empty: { title: 'Empty Comment', description: 'You cannot post an empty comment.' },+ unauthorized: { title: 'Unauthorized', description: 'You must be logged in to post a comment.' },+ unexpected: {+ title: 'Uh Oh!',+ description: 'An error occurred while trying to delete the comment.',+ },+ invalidId: { title: 'Invalid Comment', description: 'The comment id is invalid.' },+};diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.hooks.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.hooks.tsxnew file mode 100644index 00000000..d5185e7e--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/comments.hooks.tsx@@ -0,0 +1,332 @@+import {+ keepPreviousData,+ useInfiniteQuery,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query';+import { useEffect, useReducer } from 'react';++import { commentErrors, sortKeys } from './comments.constants';+import {+ getAllComments,+ getPaginatedComments,+ type PaginatedComments,+} from './getCommentRouteData';+import type { CommentRoot } from '@repo/db/types';+import {+ addComment as addCommentAction,+ deleteComment as deleteCommentAction,+ replyComment,+ updateComment as updateCommentAction,+} from './comment.action';+import { toast } from '@repo/ui/components/use-toast';+import type { ChallengeRouteData } from '../../getChallengeRouteData';+import type { SolutionRouteData } from '../../solutions/[solutionId]/getSolutionIdRouteData';++const getRootQueryKey = (rootId: number, type: CommentRoot) =>+ `${type.toLowerCase()}-${rootId}-comments`;++export type SortItem = (typeof sortKeys)[number];++interface CommentsMeta {+ page: number;+ sort: SortItem;+}++type UseCommentsProps =+ | {+ root: ChallengeRouteData['challenge'];+ rootType: 'CHALLENGE';+ initialPage?: number;+ }+ | {+ root: SolutionRouteData;+ rootType: 'SOLUTION';+ initialPage?: number;+ };++export function useComments(props: UseCommentsProps) {+ const { rootType, root, initialPage } = props;+ const queryClient = useQueryClient();+ const [commentsMeta, updateCommentsMeta] = useReducer(+ (state: CommentsMeta, action: Partial<CommentsMeta>) => ({ ...state, ...action }),+ {+ page: initialPage ?? 1,+ sort: sortKeys[0],+ },+ );++ const getQueryKey = ({ sort, page }: { sort: string; page: number }) => [+ getRootQueryKey(root.id, rootType),+ sort,+ page,+ ];++ const { status, data } = useQuery({+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: commentsMeta.page }),+ queryFn: () => {+ return getPaginatedComments({+ rootId: root.id,+ page: commentsMeta.page,+ rootType,+ sortKey: commentsMeta.sort.key,+ sortOrder: commentsMeta.sort.order,+ });+ },+ placeholderData: keepPreviousData,+ staleTime: 60000, // one minute+ refetchOnWindowFocus: false,+ });++ const changePage = (page: number) => {+ updateCommentsMeta({ page });+ };++ const changeSorting = (sort: string) => {+ updateCommentsMeta({+ sort: sortKeys.find((key) => key.value === sort) ?? sortKeys[0],+ page: 1,+ });+ };++ const deleteComment = async (commentId: number) => {+ try {+ const res = await deleteCommentAction(commentId);+ if (res === 'unauthorized') {+ toast(commentErrors.unauthorized);+ } else {+ toast({+ title: 'Comment Deleted',+ variant: 'success',+ description: 'The comment was successfully deleted.',+ });+ }+ const newPage =+ data?.comments.length === 1 && commentsMeta.page > 1+ ? commentsMeta.page - 1+ : commentsMeta.page;+ changePage(newPage);+ queryClient.invalidateQueries({+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: newPage }),+ });+ } catch (e) {+ toast({+ ...commentErrors.unexpected,+ variant: 'destructive',+ });+ }+ };++ const addComment = async (text: string) => {+ try {+ const { initialPage: _, ...rest } = props;+ const res = await addCommentAction({+ ...rest,+ text,+ });+ if (res === 'text_is_empty') {+ toast(commentErrors.empty);+ } else if (res === 'unauthorized') {+ toast({+ ...commentErrors.unauthorized,+ variant: 'destructive',+ });+ }+ const newPage = 1;+ changePage(newPage);+ queryClient.invalidateQueries({+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: newPage }),+ });+ } catch (e) {+ toast({+ ...commentErrors.unauthorized,+ variant: 'destructive',+ });+ }+ };++ const updateComment = async (text: string, commentId: number) => {+ try {+ const res = await updateCommentAction(text, commentId);+ if (res === 'text_is_empty') {+ toast(commentErrors.empty);+ } else if (res === 'unauthorized') {+ toast(commentErrors.unauthorized);+ }+ queryClient.invalidateQueries({+ queryKey: getQueryKey({ sort: commentsMeta.sort.value, page: commentsMeta.page }),+ });+ } catch (e) {+ toast({+ ...commentErrors.unauthorized,+ variant: 'destructive',+ });+ }+ };++ return {+ data,+ status,+ commentsMeta,+ changePage,+ changeSorting,+ deleteComment,+ addComment,+ updateComment,+ };+}++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({+ root,+ type,+ parentComment,+ enabled,+ preselectedReplyId,+}: UseCommentRepliesProps) {+ const queryClient = useQueryClient();+ const rootQueryKey = [getRootQueryKey(root.id, type)];+ const queryKey = [...rootQueryKey, `comment-${parentComment.id}-replies`];++ const { data: replies } = useQuery({+ queryKey,+ queryFn: () => getAllComments({ rootId: root.id, rootType: type, parentId: parentComment.id }),+ staleTime: 5000,+ enabled,+ });++ const {+ data,+ fetchNextPage,+ isFetching: isFetchingMoreReplies,+ hasNextPage: hasMoreReplies,+ refetch,+ status,+ } = useInfiniteQuery({+ initialPageParam: 0,+ queryKey: [...queryKey, 'paginated'],+ queryFn: ({ pageParam }) => {+ // `cursor` is the start index of the current page+ const cursor = Number(pageParam);++ let take = REPLIES_PAGESIZE;+ if (preselectedReplyId && cursor === 0) {+ const preselectedReplyIndex = replies!.findIndex(+ (reply) => preselectedReplyId === reply.id,+ );+ take = Math.ceil((preselectedReplyIndex + 1) / REPLIES_PAGESIZE) * REPLIES_PAGESIZE;+ }+ // `end` is exclusive, and therefore also the next cursor+ const end = cursor + take;++ return {+ // if the current page is the last, don't return the next cursor+ cursor: end < replies!.length ? end : undefined,+ replies: replies!.slice(cursor, end),+ };+ },+ enabled: Boolean(replies?.length),+ getNextPageParam: (_, pages) => pages.at(-1)?.cursor,+ });++ useEffect(() => {+ if (replies) {+ refetch();+ }+ }, [replies, refetch]);++ const addReplyComment = async (text: string) => {+ try {+ // @ts-ignore+ const res = await replyComment(+ // @ts-ignore+ {+ text,+ root,+ rootType: type,+ },+ parentComment,+ );+ if (res === 'text_is_empty') {+ toast(commentErrors.empty);+ } else if (res === 'unauthorized') {+ toast(commentErrors.unauthorized);+ }+ //Invalidate the root query to refetch the comments+ queryClient.invalidateQueries({ queryKey: rootQueryKey });+ } catch (e) {+ toast({+ ...commentErrors.unauthorized,+ variant: 'destructive',+ });+ }+ };++ const updateReplyComment = async (text: string, commentId: number) => {+ try {+ const res = await updateCommentAction(text, commentId);+ if (res === 'text_is_empty') {+ toast(commentErrors.empty);+ } else if (res === 'unauthorized') {+ toast(commentErrors.unauthorized);+ }+ queryClient.invalidateQueries({ queryKey });+ } catch (e) {+ toast({+ ...commentErrors.unauthorized,+ variant: 'destructive',+ });+ }+ };++ const deleteReplyComment = async (commentId: number) => {+ try {+ const res = await deleteCommentAction(commentId);+ if (res === 'unauthorized') {+ toast(commentErrors.unauthorized);+ } else {+ toast({+ title: 'Comment Deleted',+ variant: 'success',+ description: 'The comment was successfully deleted.',+ });+ }+ //Invalidate the root query to refetch the comments+ queryClient.invalidateQueries({ queryKey: rootQueryKey });+ } catch (e) {+ toast({+ ...commentErrors.unexpected,+ variant: 'destructive',+ });+ }+ };++ const showLoadMoreRepliesBtn = hasMoreReplies || isFetchingMoreReplies;++ return {+ data,+ status,+ fetchNextPage,+ addReplyComment,+ updateReplyComment,+ deleteReplyComment,+ showLoadMoreRepliesBtn,+ };+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/delete/index.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/delete/index.tsxnew file mode 100644index 00000000..ec3dc5c7--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/delete/index.tsx@@ -0,0 +1,79 @@+import type { DialogTriggerProps } from '@radix-ui/react-dialog';+import { Button } from '@repo/ui/components/button';+import { Dialog, DialogContent, DialogTrigger } from '@repo/ui/components/dialog';+import { Markdown } from '@repo/ui/components/markdown';+import { TypographyP } from '@repo/ui/components/paragraph';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { TypographyLarge } from '@repo/ui/components/typography/large';++import { useState } from 'react';+import { getRelativeTimeStrict } from '~/utils/relativeTime';++import { type PaginatedComments } from '../getCommentRouteData';++interface CommentDeleteDialogProps extends DialogTriggerProps {+ comment: PaginatedComments['comments'][number];+ deleteComment: (commentId: number) => Promise<void>;+}++export function CommentDeleteDialog({+ children,+ comment,+ deleteComment,+ ...props+}: CommentDeleteDialogProps) {+ const [isOpen, setIsOpen] = useState(false);++ async function handleDeleteComment() {+ await deleteComment(comment.id);+ setIsOpen(!isOpen);+ }++ return (+ <Dialog onOpenChange={() => setIsOpen(!isOpen)} open={isOpen}>+ <DialogTrigger {...props}>{children}</DialogTrigger>+ <DialogContent className="flex flex-col space-y-2">+ <TypographyLarge>Are you sure?</TypographyLarge>++ <div className="flex flex-col gap-1 p-3 pt-2">+ <div className="flex items-start justify-between pr-[0.4rem]">+ <div className="flex items-center gap-1">+ <span className="-ml-[0.33rem] flex h-auto w-fit items-center rounded-full bg-transparent py-1 pl-[0.33rem] pr-2 text-xs font-bold text-neutral-700 hover:bg-black/10 dark:text-white dark:hover:bg-white/20">+ @{comment.user.name}+ </span>+ <Tooltip delayDuration={0.05}>+ <TooltipTrigger asChild>+ <span className="mr-2 whitespace-nowrap text-sm text-neutral-500">+ {getRelativeTimeStrict(comment.createdAt)}+ </span>+ </TooltipTrigger>+ <TooltipContent align="start" className="rounded-xl">+ <span className="text-white-500 text-xs">+ {comment.createdAt.toLocaleString()}+ </span>+ </TooltipContent>+ </Tooltip>+ </div>+ </div>+ <div className="w-full break-words pl-[1px] text-sm">+ <Markdown>{comment.text}</Markdown>+ </div>+ </div>+ <TypographyP>The following comment will be permanently deleted.</TypographyP>+ <div className="flex flex-row gap-2">+ <Button onClick={() => setIsOpen(!isOpen)} variant="outline">+ Cancel+ </Button>+ <Button+ onClick={() => {+ void handleDeleteComment();+ }}+ variant="destructive"+ >+ Delete+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getProfileData.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getProfileData.tsnew file mode 100644index 00000000..9cfaead7--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getProfileData.ts@@ -0,0 +1,28 @@+'use server';++import { prisma } from '@repo/db';+import { getTitles } from './enhanced-user-badge.getTitles';+import { getBadges } from '~/components/_actions';++export async function getProfileData(username: string) {+ const user = await prisma.user.findFirstOrThrow({+ where: {+ name: username,+ },+ select: {+ image: true,+ bio: true,+ id: true,+ name: true,+ roles: true,+ },+ });++ const badges = await getBadges(user.id);+ const titles = getTitles(user.roles);+ return {+ ...user,+ titles,+ badges: badges.slice(0, 3),+ };+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getTitles.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getTitles.tsnew file mode 100644index 00000000..cf1057d1--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.getTitles.ts@@ -0,0 +1,28 @@+import { RoleTypes, type Role } from '@repo/db/types';++export type TitleInfo = ReturnType<typeof getTitles>[number];+export function getTitles(roles: Role[]) {+ const flairs: {+ type: 'admin' | 'contributor' | 'supporter';+ label: string;+ description?: string;+ }[] = [];+ if (roles.find((r) => r.role === RoleTypes.ADMIN)) {+ flairs.push({ type: 'admin', label: 'Admin' });+ }+ if (roles.find((r) => r.role === RoleTypes.CONTRIBUTOR)) {+ flairs.push({+ type: 'contributor',+ label: 'Contributor',+ description: 'Contributed to the project',+ });+ }+ if (roles.find((r) => r.role === RoleTypes.SUPPORTER)) {+ flairs.push({+ type: 'supporter',+ label: 'Supporter',+ description: 'Donated money to the project',+ });+ }+ return flairs;+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.tsxnew file mode 100644index 00000000..bd92f6dd--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/enhanced-user-badge.tsx@@ -0,0 +1,257 @@+'use client';++import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';+import Link from 'next/link';+import { Badge } from '@repo/ui/components/badge';+import { Shield, Sword, Wand2, type LucideIcon } from '@repo/ui/icons';+import { useQuery } from '@tanstack/react-query';+import { getProfileData } from './enhanced-user-badge.getProfileData';+import { useState } from 'react';+import { cn } from '@repo/ui/cn';+import { type Role } from '@repo/db/types';+import { Button } from '@repo/ui/components/button';+import { HoverCard, HoverCardContent, HoverCardTrigger } from '@repo/ui/components/hover-card';+import { getTitles, type TitleInfo } from './enhanced-user-badge.getTitles';+import { Skeleton } from '@repo/ui/components/skeleton';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { DefaultAvatar } from '~/utils/default-avatar';+import type { BadgeInfo } from '~/components/_actions';+import { SlugToBadgeIcon } from '~/components/badges';++interface UserBadgeProps {+ user: {+ name: string;+ roles: Role[];+ bio: string;+ image: string;+ };+ hideLinks?: boolean;+}++export function UserBadge(props: UserBadgeProps) {+ const [queryEnabled, setQueryEnabled] = useState(false);+ const query = useQuery({+ queryKey: ['profile-hover-card', props.user.name],+ queryFn: () => getProfileData(props.user.name),+ enabled: queryEnabled,+ staleTime: 60 * 1000,+ initialData: {+ ...props.user,+ id: '',+ badges: [],+ titles: getTitles(props.user.roles),+ },+ initialDataUpdatedAt: 0,+ });+ const onMouseOver = () => {+ setQueryEnabled(true);+ };++ const gradient = getGradient(props.user.roles);+ const shouldShowHoverCard = props.user.bio !== '' || query.data.titles.length > 0;++ if (props.hideLinks) {+ return (+ <HoverCardWrapper+ enabled={shouldShowHoverCard}+ usernameComponent={+ <Button+ className="-ml-2 font-bold "+ asChild+ variant="ghost"+ size="xs"+ onMouseOver={onMouseOver}+ >+ <span+ className={cn('bg-gradient-to-r bg-clip-text font-bold text-transparent', gradient)}+ >+ @{props.user.name}+ </span>+ </Button>+ }+ onHoverComponent={+ //When a user does not have a bio & they have no titles, then a compact version is shown+ <div className="flex flex-row space-x-2">+ <div className="flex min-w-20 flex-col items-center justify-center space-y-2">+ <div className={cn('w-min rounded-full bg-gradient-to-r p-0.5', gradient)}>+ <Avatar className="h-14 w-14">+ <AvatarImage src={query.data.image ?? ''} />+ <AvatarFallback>+ <DefaultAvatar />+ </AvatarFallback>+ </Avatar>+ </div>++ {query.isRefetching ? (+ <Skeleton className="h-full w-full" />+ ) : query.data.badges.length > 0 ? (+ <Badges data={query.data.badges} />+ ) : null}+ </div>+ <div className="flex w-max max-w-[calc(39ch)] flex-col space-y-2 ">+ <h1+ className={cn(+ 'bg-gradient-to-r bg-clip-text font-extrabold text-transparent',+ gradient,+ )}+ >+ @{props.user.name}+ </h1>++ <Titles data={query.data.titles} />+ <p className="line-clamp-2 text-sm font-light text-zinc-700 dark:text-zinc-300">+ {query.data.bio === '' ? 'This user has no bio' : query.data.bio}+ </p>+ </div>+ </div>+ }+ />+ );+ }+ return (+ <HoverCardWrapper+ enabled={shouldShowHoverCard}+ usernameComponent={+ <Link href={`/@${props.user.name}`} className="focus:outline-none focus-visible:ring-0">+ <Button+ className="-ml-2 font-bold "+ asChild+ variant="ghost"+ size="xs"+ onMouseOver={onMouseOver}+ >+ <span+ className={cn('bg-gradient-to-r bg-clip-text font-bold text-transparent', gradient)}+ >+ @{props.user.name}+ </span>+ </Button>+ </Link>+ }+ onHoverComponent={+ //When a user does not have a bio & they have no titles, then a compact version is shown+ <Link href={`/@${props.user.name}`}>+ <div className="flex flex-row space-x-2">+ <div className="flex min-w-20 flex-col items-center justify-center space-y-2">+ <div className={cn('w-min rounded-full bg-gradient-to-r p-0.5', gradient)}>+ <Avatar className="h-14 w-14">+ <AvatarImage src={query.data.image ?? ''} />+ <AvatarFallback>+ <DefaultAvatar />+ </AvatarFallback>+ </Avatar>+ </div>++ {query.isRefetching ? (+ <Skeleton className="h-full w-full" />+ ) : query.data.badges.length > 0 ? (+ <Badges data={query.data.badges} />+ ) : null}+ </div>+ <div className="flex w-max max-w-[calc(39ch)] flex-col space-y-2 ">+ <h1+ className={cn(+ 'bg-gradient-to-r bg-clip-text font-extrabold text-transparent',+ gradient,+ )}+ >+ @{props.user.name}+ </h1>++ <Titles data={query.data.titles} />+ <p className="line-clamp-2 text-sm font-light text-zinc-700 dark:text-zinc-300">+ {query.data.bio === '' ? 'This user has no bio' : query.data.bio}+ </p>+ </div>+ </div>+ </Link>+ }+ />+ );+}++const TITLE_TO_ICON: Record<TitleInfo['type'], LucideIcon> = {+ admin: Shield,+ supporter: Sword,+ contributor: Wand2,+};++const TITLE_TO_CLASSNAME: Record<TitleInfo['type'], string> = {+ admin: 'bg-gradient-to-r from-rose-400 to-orange-500 dark:from-rose-400 dark:to-orange-300',+ contributor: 'bg-gradient-to-r from-sky-400 to-cyan-600 dark:from-sky-400 dark:to-cyan-300',+ supporter:+ 'bg-gradient-to-r from-yellow-500 to-yellow-600 dark:from-yellow-200 dark:to-yellow-500',+};++function getGradient(roles: Role[]) {+ if (roles.find((r) => r.role === 'ADMIN')) {+ return TITLE_TO_CLASSNAME.admin;+ }+ if (roles.find((r) => r.role === 'CONTRIBUTOR')) {+ return TITLE_TO_CLASSNAME.contributor;+ }+ if (roles.find((r) => r.role === 'SUPPORTER')) {+ return TITLE_TO_CLASSNAME.supporter;+ }+ return 'text-foreground';+}++function Titles(props: { data: TitleInfo[] }) {+ return (+ <div className="flex flex-row space-x-2">+ {props.data.map((t) => {+ const Icon = TITLE_TO_ICON[t.type];+ return (+ <Tooltip key={t.type}>+ <TooltipTrigger asChild>+ <Badge className="rounded-full bg-gradient-to-br from-sky-600 to-sky-700 px-2 ">+ <Icon className="h-5 w-5 pr-1" />+ {t.label}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>{t.description}</TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ );+}++function Badges(props: { data: BadgeInfo[] }) {+ return (+ <div className="flex flex-row space-x-[-15px]">+ {props.data.map((b) => {+ const Icon = SlugToBadgeIcon[b.slug];+ return <Icon className="h-10 w-10" key={b.slug} />;+ })}+ </div>+ );+}++function HoverCardWrapper(props: {+ usernameComponent: React.ReactElement;+ onHoverComponent: React.ReactElement;+ enabled: boolean;+}) {+ const [open, setOpen] = useState(false);+ return (+ <HoverCard+ open={open}+ onOpenChange={(nextState) => {+ if (props.enabled) {+ setOpen(nextState);+ }+ }}+ >+ <HoverCardTrigger asChild>{props.usernameComponent}</HoverCardTrigger>+ <HoverCardContent+ align="start"+ side="bottom"+ avoidCollisions+ className="w-min rounded-lg bg-zinc-100 dark:bg-zinc-900"+ >+ {props.onHoverComponent}+ </HoverCardContent>+ </HoverCard>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/getCommentRouteData.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/getCommentRouteData.tsnew file mode 100644index 00000000..12a572b0--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/getCommentRouteData.ts@@ -0,0 +1,265 @@+'use server';+import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import type { CommentRoot } from '@repo/db/types';+import { orderBy, type SortKey, type SortOrder } from '~/utils/sorting';++const PAGESIZE = 10;++export type PaginatedComments = NonNullable<Awaited<ReturnType<typeof getPaginatedComments>>>;+export type PreselectedCommentMetadata =+ | NonNullable<Awaited<ReturnType<typeof getPreselectedCommentMetadata>>>+ | NonNullable<Awaited<ReturnType<typeof getPreselectedSolutionCommentMetadata>>>;++export async function getPreselectedCommentMetadata(challengeId: number, commentId: number) {+ const challengeComments = await prisma.comment.findMany({+ where: {+ rootType: 'CHALLENGE',+ rootChallengeId: challengeId,+ visible: true,+ parentId: null,+ },+ orderBy: {+ createdAt: 'desc',+ },+ select: {+ id: true,+ parentId: true,+ },+ });++ const index = challengeComments.findIndex((comment) => comment.id === commentId);++ // this `commentId` couldn't be found (perhaps it was deleted)+ if (index === -1) return;++ const selectedComment = challengeComments[index];+ const page = Math.ceil((index + 1) / PAGESIZE);++ return {+ page,+ selectedComment,+ index,+ challengeComments: challengeComments.map((comment) => comment.id),+ };+}++export async function getPreselectedSolutionCommentMetadata(+ solutionId: number,+ commentId: number,+ challengeId: number,+) {+ const solution = await prisma.sharedSolution.findFirst({+ where: {+ id: solutionId,+ challengeId,+ },+ select: {+ id: true,+ solutionComment: {+ orderBy: { createdAt: 'desc' },+ },+ },+ });++ if (!solution || !solution.solutionComment) return;++ const comments = solution.solutionComment;+ const index = comments.findIndex((comment) => comment.id === commentId);++ // this `commentId` couldn't be found (perhaps it was deleted)+ if (index === -1) return;++ const selectedComment = comments[index];+ const page = Math.ceil((index + 1) / PAGESIZE);++ return {+ page,+ selectedComment,+ index,+ challengeComments: comments.map((comment) => comment.id),+ };+}++async function getCommentsCount({+ rootType,+ rootId,+ parentId = null,+}: {+ rootType: CommentRoot;+ rootId: number;+ parentId?: number | null;+}) {+ return prisma.comment.count({+ where: {+ rootType,+ parentId,+ visible: true,+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),+ },+ });+}++export async function getPaginatedComments({+ page,+ rootId,+ rootType,+ parentId = null,+ sortKey = 'createdAt',+ sortOrder = 'desc',+ take = PAGESIZE,+}: {+ page: number;+ rootId: number;+ rootType: CommentRoot;+ parentId?: number | null;+ sortKey?: SortKey;+ sortOrder?: SortOrder;+ take?: number;+}) {+ const session = await auth();++ const totalComments = await getCommentsCount({ rootType, rootId, parentId });++ const totalReplies = await prisma.comment.count({+ where: {+ rootType,+ parentId: {+ not: null,+ },+ visible: true,+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),+ },+ });++ const comments = await prisma.comment.findMany({+ skip: ((page || 1) - 1) * take,+ take,+ where: {+ rootType,+ parentId,+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),+ visible: true,+ },+ orderBy: orderBy(sortKey, sortOrder),+ include: {+ user: {+ select: {+ id: true,+ name: true,+ image: true,+ roles: true,+ bio: true,+ },+ },+ _count: {+ select: {+ replies: true,+ vote: true,+ },+ },+ vote: {+ select: {+ userId: true,+ },+ where: {+ userId: session?.user?.id || '',+ },+ },+ rootChallenge: {+ select: {+ slug: true,+ name: true,+ },+ },+ rootSolution: {+ select: {+ title: true,+ challenge: {+ select: {+ slug: true,+ },+ },+ },+ },+ },+ });++ const totalPages = Math.ceil(totalComments / take);++ return {+ totalComments: totalReplies + totalComments,+ totalPages,+ hasMore: page < totalPages,+ comments,+ };+}++export async function getAllComments({+ rootId,+ rootType,+ parentId = null,+ sortKey = 'createdAt',+ sortOrder = 'desc',+}: {+ rootId: number;+ rootType: CommentRoot;+ parentId?: number | null;+ sortKey?: SortKey;+ sortOrder?: SortOrder;+}) {+ const session = await auth();++ const comments = await prisma.comment.findMany({+ where: {+ rootType,+ parentId,+ ...(rootType === 'CHALLENGE' ? { rootChallengeId: rootId } : { rootSolutionId: rootId }),+ visible: true,+ },+ orderBy: orderBy(sortKey, sortOrder),+ include: {+ user: {+ select: {+ id: true,+ name: true,+ image: true,+ roles: true,+ bio: true,+ },+ },+ _count: {+ select: {+ replies: true,+ vote: true,+ },+ },+ vote: {+ select: {+ userId: true,+ },+ where: {+ userId: session?.user?.id || '',+ },+ },+ rootChallenge: {+ select: {+ slug: true,+ name: true,+ },+ },+ rootSolution: {+ select: {+ title: true,+ challenge: {+ select: {+ slug: true,+ },+ },+ },+ },+ },+ });++ return comments;+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/getMentionsFromComment.ts b/apps/aot/src/app/events/[year]/[day]/_components/comments/getMentionsFromComment.tsnew file mode 100644index 00000000..71613311--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_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-zA-Z\d](?:[a-zA-Z\d]|-(?=[a-zA-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/aot/src/app/events/[year]/[day]/_components/comments/index.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/index.tsxnew file mode 100644index 00000000..39631feb--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/index.tsx@@ -0,0 +1,139 @@+'use client';++import type { CommentRoot } from '@repo/db/types';+import { ChevronDown, MessageCircle } from '@repo/ui/icons';+import clsx from 'clsx';+import { useRef, useState } from 'react';+import type { SolutionRouteData } from '../../solutions/[solutionId]/getSolutionIdRouteData';+import { useTrackNavigationVisiblity } from '../../use-track-visibility.hook';+import { Pagination } from '../pagination';+import { SortSelect } from '../sort-select';+import type { Challenge } from '../types';+import { Comment } from './comment';+import { CommentInput } from './comment-input';+import { CommentSkeleton } from './comment-skeleton';+import { sortKeys } from './comments.constants';+import { useComments } from './comments.hooks';+import { type PreselectedCommentMetadata } from './getCommentRouteData';+import NoComments from './nocomments';++interface Props {+ preselectedCommentMetadata?: PreselectedCommentMetadata;+ expanded?: boolean;+ root: Challenge | SolutionRouteData;+ type: CommentRoot;+}++// million-ignore+export function Comments({ preselectedCommentMetadata, root, type, expanded = false }: Props) {+ const { isTrackTitleVisible } = useTrackNavigationVisiblity();+ const [showComments, setShowComments] = useState(expanded);+ const commentContainerRef = useRef<HTMLDivElement>(null);+ const {+ data,+ addComment,+ commentsMeta,+ status,+ changePage,+ changeSorting,+ deleteComment,+ updateComment,+ } = useComments({+ rootType: type,+ root,+ initialPage: preselectedCommentMetadata?.page,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any);++ const handleChangePage = (page: number) => {+ changePage(page);+ commentContainerRef.current?.scroll({+ top: 128,+ behavior: 'smooth',+ });+ };++ return (+ <div+ className={clsx(+ 'bg-background/90 dark:border-b-muted dark:bg-muted/90 absolute bottom-0 max-h-full w-full overflow-hidden border-t border-zinc-300 backdrop-blur-sm duration-300 dark:border-zinc-700 ',+ {+ 'lg:border-t-none': showComments,+ },+ )}+ >+ <div className="relative">+ <button+ className="flex w-full items-center justify-between gap-2 p-3 font-medium text-neutral-500 duration-300 hover:text-neutral-700 focus:outline-none dark:hover:text-zinc-300"+ onClick={() => {+ setShowComments(!showComments);+ commentContainerRef.current?.scroll({ top: 0 });+ }}+ >+ <div className="flex items-center gap-2">+ <MessageCircle className="h-5 w-5" />+ Comments+ {data?.totalComments != null ? <span>({data.totalComments})</span> : null}+ </div>+ <ChevronDown+ className={clsx('h-4 w-4 duration-300', {+ '-rotate-180': !showComments,+ })}+ />+ </button>+ <div+ className={clsx(+ 'custom-scrollable-element flex flex-col overscroll-contain duration-300',+ {+ 'h-0 overflow-y-hidden': !showComments,+ 'h-64 pb-4 lg:h-[calc(100vh_-_164px)]': showComments && !isTrackTitleVisible, // no title+ 'h-[calc(256px_-_46px)] pb-4 lg:h-[calc(100vh_-_210px)]':+ showComments && isTrackTitleVisible, // with title+ 'overflow-y-auto ': showComments && (data?.comments.length ?? 0) > 0,+ },+ )}+ ref={commentContainerRef}+ >+ <div className="m-2 mb-4 mt-0">+ <CommentInput mode="create" onSubmit={addComment} />+ </div>+ {(data?.comments.length ?? 0) > 0 && (+ <SortSelect+ currentSortKey={commentsMeta.sort}+ totalSortKeys={sortKeys}+ onValueChange={changeSorting}+ />+ )}+ {status === 'pending' && <CommentSkeleton />}+ <div className="flex-1">+ {status === 'success' &&+ (data?.comments.length === 0 ? (+ <NoComments />+ ) : (+ data?.comments.map((comment) => (+ <Comment+ key={comment.id}+ preselectedCommentMetadata={preselectedCommentMetadata}+ comment={comment}+ root={root}+ type={type}+ deleteComment={deleteComment}+ updateComment={updateComment}+ />+ ))+ ))}+ </div>+ {(data?.totalPages ?? 0) > 1 && (+ <div className="mt-2 flex justify-center">+ <Pagination+ currentPage={commentsMeta.page}+ onClick={handleChangePage}+ totalPages={data?.totalPages ?? 0}+ />+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/comments/nocomments.tsx b/apps/aot/src/app/events/[year]/[day]/_components/comments/nocomments.tsxnew file mode 100644index 00000000..55a0c727--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/comments/nocomments.tsx@@ -0,0 +1,53 @@+function NoComments() {+ return (+ <div className="flex h-full items-center justify-center">+ <p className="flex flex-col items-center gap-2 text-center text-neutral-500 dark:text-zinc-400">+ <svg+ className="mr-6 h-28 w-28"+ data-name="Layer 1"+ viewBox="0 0 647.63626 632.17383"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M687.3279,276.08691H512.81813a15.01828,15.01828,0,0,0-15,15v387.85l-2,.61005-42.81006,13.11a8.00676,8.00676,0,0,1-9.98974-5.31L315.678,271.39691a8.00313,8.00313,0,0,1,5.31006-9.99l65.97022-20.2,191.25-58.54,65.96972-20.2a7.98927,7.98927,0,0,1,9.99024,5.3l32.5498,106.32Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M725.408,274.08691l-39.23-128.14a16.99368,16.99368,0,0,0-21.23-11.28l-92.75,28.39L380.95827,221.60693l-92.75,28.4a17.0152,17.0152,0,0,0-11.28028,21.23l134.08008,437.93a17.02661,17.02661,0,0,0,16.26026,12.03,16.78926,16.78926,0,0,0,4.96972-.75l63.58008-19.46,2-.62v-2.09l-2,.61-64.16992,19.65a15.01489,15.01489,0,0,1-18.73-9.95l-134.06983-437.94a14.97935,14.97935,0,0,1,9.94971-18.73l92.75-28.4,191.24024-58.54,92.75-28.4a15.15551,15.15551,0,0,1,4.40966-.66,15.01461,15.01461,0,0,1,14.32032,10.61l39.0498,127.56.62012,2h2.08008Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M398.86279,261.73389a9.0157,9.0157,0,0,1-8.61133-6.3667l-12.88037-42.07178a8.99884,8.99884,0,0,1,5.9712-11.24023l175.939-53.86377a9.00867,9.00867,0,0,1,11.24072,5.9707l12.88037,42.07227a9.01029,9.01029,0,0,1-5.9707,11.24072L401.49219,261.33887A8.976,8.976,0,0,1,398.86279,261.73389Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="190.15351" cy="24.95465" fill="#888a" r="20" />+ <circle cx="190.15351" cy="24.95465" fill="#444a" r="12.66462" />+ <path+ d="M878.81836,716.08691h-338a8.50981,8.50981,0,0,1-8.5-8.5v-405a8.50951,8.50951,0,0,1,8.5-8.5h338a8.50982,8.50982,0,0,1,8.5,8.5v405A8.51013,8.51013,0,0,1,878.81836,716.08691Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M723.31813,274.08691h-210.5a17.02411,17.02411,0,0,0-17,17v407.8l2-.61v-407.19a15.01828,15.01828,0,0,1,15-15H723.93825Zm183.5,0h-394a17.02411,17.02411,0,0,0-17,17v458a17.0241,17.0241,0,0,0,17,17h394a17.0241,17.0241,0,0,0,17-17v-458A17.02411,17.02411,0,0,0,906.81813,274.08691Zm15,475a15.01828,15.01828,0,0,1-15,15h-394a15.01828,15.01828,0,0,1-15-15v-458a15.01828,15.01828,0,0,1,15-15h394a15.01828,15.01828,0,0,1,15,15Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M801.81836,318.08691h-184a9.01015,9.01015,0,0,1-9-9v-44a9.01016,9.01016,0,0,1,9-9h184a9.01016,9.01016,0,0,1,9,9v44A9.01015,9.01015,0,0,1,801.81836,318.08691Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="433.63626" cy="105.17383" fill="#888a" r="20" />+ <circle cx="433.63626" cy="105.17383" fill="#444a" r="12.18187" />+ </svg>+ No comments yet,+ <br /> be the first to comment!+ </p>+ </div>+ );+}++export default NoComments;diff --git a/apps/aot/src/app/events/[year]/[day]/_components/description/description-skeleton.tsx b/apps/aot/src/app/events/[year]/[day]/_components/description/description-skeleton.tsxnew file mode 100644index 00000000..fecb089a--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/description/description-skeleton.tsx@@ -0,0 +1,26 @@+import { Skeleton } from '@repo/ui/components/skeleton';++export function DescriptionSkeleton() {+ return (+ <div className="flex flex-col space-y-10 px-4 py-3">+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ {/* TITLE */}+ <Skeleton className="h-4 w-2/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ {/* BUTTONS */}+ <Skeleton className="h-4 w-2/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ {/* DESCRIPTION */}+ <Skeleton className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ {/* FOR EXAMPLE */}+ <Skeleton className="h-4 w-1/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ {/* FOR EXAMPLE BOX */}+ <Skeleton className="h-36 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/description/index.tsx b/apps/aot/src/app/events/[year]/[day]/_components/description/index.tsxnew file mode 100644index 00000000..a65237be--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/description/index.tsx@@ -0,0 +1,187 @@+'use client';++import { useSession } from '@repo/auth/react';+import { cn } from '@repo/ui/cn';+import { ActionMenu } from '@repo/ui/components/action-menu';+import { Button, buttonVariants } from '@repo/ui/components/button';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@repo/ui/components/dialog';+import { Markdown } from '@repo/ui/components/markdown';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { TypographyH3 } from '@repo/ui/components/typography/h3';+import { Bookmark as BookmarkIcon, Calendar, CheckCircle, Flag, Share } from '@repo/ui/icons';+import clsx from 'clsx';+import { debounce } from 'lodash';+import { useRef, useState } from 'react';+import { ReportDialog } from '~/components/report-dialog';+import { ShareUrl } from '~/components/share-url';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import { addOrRemoveBookmark } from '../bookmark.action';+import { UserBadge } from '../comments/enhanced-user-badge';+import type { Challenge } from '../types';+import { Vote } from '../vote';++interface Props {+ challenge: Challenge;+}++export interface FormValues {+ comments: string;+ examples: boolean;+ derogatory: boolean;+ other: boolean;+}++export function Description({ challenge }: Props) {+ const [hasBookmarked, setHasBookmarked] = useState(challenge.bookmark.length > 0);+ const session = useSession();++ const debouncedBookmark = useRef(+ debounce(async (challengeId: number, userId: string, shouldBookmark: boolean) => {+ try {+ await addOrRemoveBookmark(challengeId, userId, shouldBookmark);+ setHasBookmarked(shouldBookmark);+ } catch (e) {+ console.error(e);+ // it errored so reverse the intended changes+ setHasBookmarked(!shouldBookmark);+ }+ }, 500),+ ).current;++ return (+ <div+ // eslint-disable-next-line+ tabIndex={0}+ className="custom-scrollable-element h-full overflow-y-auto px-4 pb-36 pt-3 outline-none"+ >+ <div className="flex items-center">+ <TypographyH3 className="mr-auto max-w-[75%] items-center truncate text-2xl font-bold">+ {challenge.name}+ </TypographyH3>+ <ReportDialog challengeId={challenge.id} reportType="CHALLENGE">+ <ActionMenu+ items={[+ {+ key: 'feedback',+ label: 'Feedback',+ icon: Flag,+ },+ ]}+ onChange={() => {+ // do nothing+ }}+ />+ </ReportDialog>+ </div>+ {/* Author & Time */}+ <div className="mt-2 flex items-center gap-4">+ <UserBadge+ user={{+ name: challenge.user?.name ?? '',+ image: challenge.user?.image ?? '',+ bio: challenge.user?.bio ?? '',+ roles: challenge.user?.roles ?? [],+ }}+ hideLinks+ />+ <div className="text-muted-foreground flex items-center gap-2">+ <Calendar className=" h-4 w-4" />+ <span className="text-xs">Last updated {getRelativeTimeStrict(challenge.updatedAt)}</span>+ </div>+ </div>+ {/* Difficulty & Action Buttons */}+ <div className="mt-3 flex items-center gap-3">+ {challenge.hasSolved ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <CheckCircle className="stroke-green-600 dark:stroke-green-300" size={20} />+ </TooltipTrigger>+ <TooltipContent>+ <p>Solved</p>+ </TooltipContent>+ </Tooltip>+ ) : null}+ <Vote+ voteCount={challenge._count.vote}+ initialHasVoted={challenge.vote.length > 0}+ disabled={!session?.data?.user?.id}+ rootType="CHALLENGE"+ rootId={challenge?.id}+ />+ <Dialog>+ <DialogTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <div+ className={cn(+ buttonVariants({ variant: 'secondary', size: 'xs' }),+ 'rounded-full',+ )}+ >+ <Share className="h-4 w-4" />+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>Share</p>+ </TooltipContent>+ </Tooltip>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Share</DialogTitle>+ </DialogHeader>+ <div className="pt-4">+ <ShareUrl />+ </div>+ </DialogContent>+ </Dialog>++ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="secondary"+ size="xs"+ className={clsx(+ 'border border-transparent [&:not(:disabled)]:hover:border-blue-500 [&:not(:disabled)]:hover:text-blue-500',+ {+ 'border-blue-500 text-blue-500': hasBookmarked,+ },+ )}+ disabled={!session.data?.user?.id}+ onClick={() => {+ let shouldBookmark = false;+ if (hasBookmarked) {+ shouldBookmark = false;+ setHasBookmarked(false);+ } else {+ shouldBookmark = true;+ setHasBookmarked(true);+ }+ debouncedBookmark(challenge.id, session.data?.user?.id!, shouldBookmark)?.catch(+ (e) => {+ console.error(e);+ },+ );+ }}+ >+ <BookmarkIcon className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>{session.data?.user?.id ? 'Bookmark' : 'Login to Bookmark'}</p>+ </TooltipContent>+ </Tooltip>+ </div>+ {/* Challenge Description */}+ <div className="prose-invert prose-h3:text-xl mt-6 leading-7">+ <Markdown>{challenge.description}</Markdown>+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-button.tsx b/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-button.tsxnew file mode 100644index 00000000..5fe1f835--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-button.tsx@@ -0,0 +1,33 @@+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@repo/ui/components/dialog';+import { EditorShortcuts } from './editor-shortcuts-form';+import { SquareSlash } from '@repo/ui/icons';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';++export function EditorShortcutsButton() {+ return (+ <Dialog>+ <DialogTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <SquareSlash className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" size={20} />+ </TooltipTrigger>+ <TooltipContent className="px-2 py-1">Shortcuts</TooltipContent>+ </Tooltip>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Shortcuts</DialogTitle>+ </DialogHeader>+ <div className="pt-4">+ <EditorShortcuts />+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-form.tsx b/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-form.tsxnew file mode 100644index 00000000..e30d7239--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/editor-shortcuts/editor-shortcuts-form.tsx@@ -0,0 +1,93 @@+'use client';++import type { PropsWithChildren } from 'react';++interface Props {+ title: string;+ description: React.ReactNode;+}++function EditorShortcut(props: Props) {+ return (+ <div className="grid grid-cols-2 gap-2">+ <h1>{props.title}</h1>+ {props.description}+ </div>+ );+}++const Key = (props: PropsWithChildren) => {+ return (+ <kbd className="rounded-md border border-zinc-300 bg-neutral-200 p-1 py-0.5 font-mono text-xs text-zinc-600 dark:border-zinc-600 dark:bg-zinc-700 dark:text-zinc-300">+ {props.children}+ </kbd>+ );+};+function isMacOS() {+ return navigator.platform.toLowerCase().includes('mac');+}+export function EditorShortcuts() {+ const isMac = isMacOS();+ const cmdOrCtrl = isMac ? 'Cmd' : 'Ctrl';+ const optionOrAlt = isMac ? 'Option' : 'Alt';+ return (+ <div className="flex flex-col gap-2">+ <EditorShortcut+ title="To indent one level"+ description={+ <p>+ <Key>Tab</Key> or <Key>{cmdOrCtrl}</Key> + <Key>[</Key>+ </p>+ }+ />+ <EditorShortcut+ title="To indent one fewer levels"+ description={+ <p>+ <Key>Shift</Key> + <Key>Tab</Key> or <Key>{cmdOrCtrl}</Key> + <Key>]</Key>+ </p>+ }+ />+ <EditorShortcut+ title="To move lines up/down"+ description={+ <p>+ <Key>{optionOrAlt}</Key> + <Key>Up/Down</Key>+ </p>+ }+ />+ <EditorShortcut+ title="Delete line and copy to buffer"+ description={+ <p>+ <Key>{cmdOrCtrl}</Key> + <Key>X</Key>+ </p>+ }+ />+ <EditorShortcut+ title="Comment/uncomment current selection"+ description={+ <p>+ <Key>{cmdOrCtrl}</Key> + <Key>/</Key>+ </p>+ }+ />+ <EditorShortcut+ title="Undo action"+ description={+ <p>+ <Key>{cmdOrCtrl}</Key> + <Key>Z</Key>+ </p>+ }+ />+ <EditorShortcut+ title="Redo action"+ description={+ <p>+ <Key>{cmdOrCtrl}</Key> + <Key>Shift</Key> + <Key>Z</Key>+ </p>+ }+ />+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/left-panel-skeleton.tsx b/apps/aot/src/app/events/[year]/[day]/_components/left-panel-skeleton.tsxnew file mode 100644index 00000000..65042f76--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/left-panel-skeleton.tsx@@ -0,0 +1,94 @@+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@repo/ui/components/tabs';++export function DescriptionPanelSkeleton() {+ return (+ <Tabs className="w-full" defaultValue="description">+ <TabsList className="bg-background dark:bg-muted sticky top-0 grid h-auto w-full grid-cols-3 rounded-none border-b border-zinc-300 dark:border-zinc-700">+ <TabsTrigger+ className="rounded-md rounded-tl-xl duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"+ value="description"+ >+ Description+ </TabsTrigger>+ <TabsTrigger+ className="rounded-md duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"+ value="solutions"+ >+ Solutions+ </TabsTrigger>+ <TabsTrigger+ className="rounded-md rounded-tr-lg duration-300 data-[state=active]:bg-neutral-200 dark:data-[state=active]:bg-neutral-700"+ value="submissions"+ >+ Submissions+ </TabsTrigger>+ </TabsList>+ <TabsContent className="dark:bg-muted mt-0" value="description">+ <div className="h-full p-5">+ <div className="mb-2 h-8 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700"> </div>+ <div className="mb-6 flex items-center gap-6 py-4">+ <div className="h-6 w-10 rounded-full bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-6 w-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-6 w-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-6 w-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="flex flex-col space-y-10">+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ </div>+ </TabsContent>+ <TabsContent className="flex h-full flex-col space-y-2 p-5" value="solutions">+ <div className="flex flex-col space-y-10">+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ </TabsContent>+ <TabsContent className="flex h-full flex-col space-y-2 p-5" value="submissions">+ <div className="flex flex-col space-y-10">+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <div className="h-4 w-1/2 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ </TabsContent>+ </Tabs>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/pagination.tsx b/apps/aot/src/app/events/[year]/[day]/_components/pagination.tsxnew file mode 100644index 00000000..44a757cf--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/pagination.tsx@@ -0,0 +1,62 @@+import { Button } from '@repo/ui/components/button';+import { ChevronLeft, ChevronRight } from '@repo/ui/icons';+import clsx from 'clsx';++export function Pagination({+ currentPage,+ totalPages,+ onClick,+}: {+ totalPages: number;+ currentPage: number;+ onClick: (page: number) => void;+}) {+ const maxVisiblePages = 5;+ const halfVisiblePages = Math.floor(maxVisiblePages / 2);++ let startPage = currentPage - halfVisiblePages;+ let endPage = currentPage + halfVisiblePages;++ if (startPage <= 0) {+ startPage = 1;+ endPage = Math.min(totalPages, maxVisiblePages);+ }++ if (endPage > totalPages) {+ endPage = totalPages;+ startPage = Math.max(1, totalPages - maxVisiblePages + 1);+ }++ const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);++ return (+ <nav className="justify-space-between flex items-center gap-2">+ <Button+ disabled={currentPage === 1}+ onClick={() => onClick(Math.max(0, currentPage - 1))}+ variant="ghost"+ >+ <ChevronLeft />+ </Button>+ {pages.map((page) => (+ <Button+ className={clsx('border-border dark:border-ring border', {+ 'bg-border dark:bg-neutral-700': page === currentPage,+ })}+ key={`pagination-${page}`}+ onClick={() => onClick(page)}+ variant="ghost"+ >+ {page}+ </Button>+ ))}+ <Button+ disabled={currentPage === totalPages}+ onClick={() => onClick(Math.min(totalPages, currentPage + 1))}+ variant="ghost"+ >+ <ChevronRight />+ </Button>+ </nav>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/reset-editor-button.tsx b/apps/aot/src/app/events/[year]/[day]/_components/reset-editor-button.tsxnew file mode 100644index 00000000..0f5d56e6--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/reset-editor-button.tsx@@ -0,0 +1,41 @@+import { useResetEditor } from '@repo/monaco/editor-hooks';+import {+ AlertDialog,+ AlertDialogTrigger,+ AlertDialogContent,+ AlertDialogCancel,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogAction,+ AlertDialogFooter,+} from '@repo/ui/components/alert-dialog';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { RotateCcw } from '@repo/ui/icons';++const ResetEditorButton = () => {+ const { dispatch } = useResetEditor();+ return (+ <AlertDialog>+ <AlertDialogTrigger name="reset">+ <Tooltip>+ <TooltipTrigger asChild>+ <RotateCcw className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" size={20} />+ </TooltipTrigger>+ <TooltipContent side="left">+ <p>Reset to default code definition</p>+ </TooltipContent>+ </Tooltip>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Reset code?</AlertDialogTitle>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction onClick={() => dispatch('resetCode')}>Continue</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};+export { ResetEditorButton };diff --git a/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-button.tsx b/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-button.tsxnew file mode 100644index 00000000..1396d2c1--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-button.tsx@@ -0,0 +1,31 @@+import { Settings } from '@repo/ui/icons';+import { SettingsForm } from './settings-form';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@repo/ui/components/dialog';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';++export function SettingsButton() {+ return (+ <Dialog>+ <DialogTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <Settings className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" size={20} />+ </TooltipTrigger>+ <TooltipContent className="px-2 py-1">Settings</TooltipContent>+ </Tooltip>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Settings</DialogTitle>+ </DialogHeader>+ <SettingsForm />+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-form.tsx b/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-form.tsxnew file mode 100644index 00000000..f92a7b58--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/settings/settings-form.tsx@@ -0,0 +1,157 @@+'use client';++import { zodResolver } from '@hookform/resolvers/zod';+import * as DialogPrimitive from '@radix-ui/react-dialog';+import { useForm } from 'react-hook-form';+import * as z from 'zod';+import { DEFAULT_SETTINGS, useEditorSettingsStore } from '@repo/monaco/settings-store';+import { useToast } from '@repo/ui/components/use-toast';+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@repo/ui/components/form';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@repo/ui/components/select';+import { DialogFooter } from '@repo/ui/components/dialog';+import { Button } from '@repo/ui/components/button';+import { Textarea } from '@repo/ui/components/textarea';++const formSchema = z.object({+ fontSize: z.string(),+ bindings: z.string(),+ tabSize: z.string(),+ vimConfig: z.string(),+});++export type FormSchema = z.infer<typeof formSchema>;++export function SettingsForm() {+ const { toast } = useToast();++ const { settings, updateSettings } = useEditorSettingsStore();+ const form = useForm<FormSchema>({+ resolver: zodResolver(formSchema),+ defaultValues: settings,+ });+ const isVimBindings = form.getValues().bindings === 'vim';++ function onSubmit(data: FormSchema) {+ updateSettings({ ...settings, ...data });+ toast({+ title: 'Settings updated!',+ variant: 'success',+ });+ }++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">+ <FormField+ control={form.control}+ name="fontSize"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Font Size</FormLabel>+ <Select defaultValue={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a font size" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="12">12px</SelectItem>+ <SelectItem value="13">13px</SelectItem>+ <SelectItem value="14">14px</SelectItem>+ <SelectItem value="15">15px</SelectItem>+ <SelectItem value="16">16px</SelectItem>+ <SelectItem value="17">17px</SelectItem>+ <SelectItem value="18">18px</SelectItem>+ <SelectItem value="19">19px</SelectItem>+ <SelectItem value="20">20px</SelectItem>+ <SelectItem value="21">21px</SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="tabSize"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Tab Size</FormLabel>+ <Select defaultValue={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a tab size" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="2">2 spaces</SelectItem>+ <SelectItem value="4">4 spaces</SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="bindings"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Key Bindings</FormLabel>+ <Select defaultValue={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select Key Binding Style" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="standard">Standard</SelectItem>+ <SelectItem value="vim">Vim</SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ {isVimBindings ? (+ <FormField+ control={form.control}+ name="vimConfig"+ render={({ field: { value, ...field } }) => (+ <FormItem>+ <FormLabel>Vim Config</FormLabel>+ <Textarea+ value={value || DEFAULT_SETTINGS.vimConfig}+ className="h-60 resize-none font-mono"+ {...field}+ />+ <FormMessage />+ </FormItem>+ )}+ />+ ) : null}++ <DialogFooter className="mt-3">+ <DialogPrimitive.Close asChild>+ <Button type="submit" disabled={form.formState.isSubmitting}>+ Save+ </Button>+ </DialogPrimitive.Close>+ </DialogFooter>+ </form>+ </Form>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/sort-select.tsx b/apps/aot/src/app/events/[year]/[day]/_components/sort-select.tsxnew file mode 100644index 00000000..3013f5e3--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/sort-select.tsx@@ -0,0 +1,39 @@+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@repo/ui/components/select';++interface SortKey {+ label: string;+ value: string;+ key: string;+ order: string;+}++interface Props {+ currentSortKey: SortKey;+ totalSortKeys: readonly SortKey[];+ onValueChange: (value: string) => void;+}++export function SortSelect({ currentSortKey, totalSortKeys, onValueChange }: Props) {+ return (+ <div className="flex items-center gap-2 px-3 py-2">+ <Select value={currentSortKey.value} defaultValue="newest" onValueChange={onValueChange}>+ <SelectTrigger className="w-[180px]">+ <SelectValue placeholder="Sort Key" />+ </SelectTrigger>+ <SelectContent>+ {totalSortKeys.map((sortKey, index) => (+ <SelectItem key={index} value={sortKey.value}>+ {sortKey.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/_components/types.ts b/apps/aot/src/app/events/[year]/[day]/_components/types.tsnew file mode 100644index 00000000..50272746--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/types.ts@@ -0,0 +1,4 @@+import type { inferRouterOutputs } from '@trpc/server';+import type { AppRouter } from '~/server/api/root';++export type Challenge = inferRouterOutputs<AppRouter>['event']['getEventChallengeBySlug'];diff --git a/apps/aot/src/app/events/[year]/[day]/_components/usePanelAdjustments.ts b/apps/aot/src/app/events/[year]/[day]/_components/usePanelAdjustments.tsnew file mode 100644index 00000000..064636c1--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/usePanelAdjustments.ts@@ -0,0 +1,86 @@+import { useCallback, useRef } from 'react';+import { COLLAPSED_DESKTOP_WIDTH, COLLAPSED_MOBILE_HEIGHT } from './challenge-layout';++const usePanelAdjustments = (+ DEFAULT_DESKTOP_WIDTH_PX: string,+ LEFT_PANEL_BREAKPOINT: number,+ isDesktop: boolean,+ isPlayground?: boolean,+) => {+ const leftSide = useRef<HTMLDivElement | null>(null);++ const expandPanel = useCallback(() => {+ if (!leftSide.current) return;++ if (isDesktop) {+ leftSide.current.style.width = DEFAULT_DESKTOP_WIDTH_PX;+ leftSide.current.style.minWidth = DEFAULT_DESKTOP_WIDTH_PX;+ } else {+ leftSide.current.style.height = DEFAULT_DESKTOP_WIDTH_PX;+ leftSide.current.style.minHeight = DEFAULT_DESKTOP_WIDTH_PX;+ }+ leftSide.current.style.opacity = '100%';+ }, [DEFAULT_DESKTOP_WIDTH_PX, isDesktop]);++ const collapsePanel = useCallback(() => {+ if (!leftSide.current) return;+ if (isDesktop) {+ leftSide.current.style.width = `${isPlayground ? '0' : COLLAPSED_DESKTOP_WIDTH}px`;+ leftSide.current.style.minWidth = `${isPlayground ? '0' : COLLAPSED_DESKTOP_WIDTH}px`;+ } else {+ leftSide.current.style.height = `${isPlayground ? '0' : COLLAPSED_MOBILE_HEIGHT}px`;+ leftSide.current.style.minHeight = `${isPlayground ? '0' : COLLAPSED_MOBILE_HEIGHT}px`;+ }++ if (isPlayground) {+ leftSide.current.style.opacity = '0%';+ }+ }, [isDesktop, isPlayground]);++ const isLeftPanelCollapsed = useCallback(() => {+ if (!leftSide.current) return false;++ const actualWidthInPixels = parseFloat(getComputedStyle(leftSide.current).width);+ const actualHeightInPixels = parseFloat(getComputedStyle(leftSide.current).height);++ return (+ (isDesktop && actualWidthInPixels < LEFT_PANEL_BREAKPOINT) ||+ (!isDesktop && actualHeightInPixels < LEFT_PANEL_BREAKPOINT)+ );+ }, [LEFT_PANEL_BREAKPOINT, isDesktop]);++ const adjustPanelSize = useCallback(+ (divideByW: number, divideByH: number, newDimensionValue: number) => {+ if (!leftSide.current) return;++ const isCollapsed = isLeftPanelCollapsed();++ if (isCollapsed) {+ expandPanel();+ return;+ }++ const panelSize = (newDimensionValue / 100) * (isDesktop ? divideByW : divideByH);+ const breakpointSize = isDesktop+ ? (LEFT_PANEL_BREAKPOINT / divideByW) * 100+ : (LEFT_PANEL_BREAKPOINT / divideByH) * 100;++ const sizeValue = panelSize < LEFT_PANEL_BREAKPOINT ? breakpointSize : newDimensionValue;++ isDesktop+ ? (leftSide.current.style.width = `${sizeValue}%`)+ : (leftSide.current.style.height = `${sizeValue}%`);+ },+ [LEFT_PANEL_BREAKPOINT, expandPanel, isDesktop, isLeftPanelCollapsed],+ );++ return {+ leftSide,+ adjustPanelSize,+ expandPanel,+ collapsePanel,+ isLeftPanelCollapsed,+ };+};++export default usePanelAdjustments;diff --git a/apps/aot/src/app/events/[year]/[day]/_components/vote.tsx b/apps/aot/src/app/events/[year]/[day]/_components/vote.tsxnew file mode 100644index 00000000..917abe8f--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/_components/vote.tsx@@ -0,0 +1,89 @@+'use client';++import { useSession } from '@repo/auth/react';+import type { VoteType } from '@repo/db/types';+import { Button } from '@repo/ui/components/button';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { ThumbsUp } from '@repo/ui/icons';+import clsx from 'clsx';+import { debounce } from 'lodash';+import { useRef, useState } from 'react';+import { incrementOrDecrementUpvote } from '../increment.action';++interface VoteProps {+ voteCount: number;+ initialHasVoted?: boolean;+ rootId: number;+ rootType: VoteType;+ disabled?: boolean;+ onVote?: (didUpvote: boolean) => void;+}++export function Vote({+ voteCount,+ initialHasVoted,+ rootId,+ rootType,+ disabled,+ onVote,+}: 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,+ });+ }, 500),+ ).current;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ className={clsx(+ 'gap-2 border border-transparent [&:not(:disabled)]:hover:border-emerald-600 [&:not(:disabled)]:hover:text-emerald-600',+ {+ 'border-emerald-600 text-emerald-600': hasVoted,+ },+ )}+ variant="secondary"+ size="xs"+ disabled={disabled}+ onClick={() => {+ let shouldIncrement = false;+ const previousVotes = votes;++ if (hasVoted) {+ setVotes((v) => v - 1);+ shouldIncrement = false;+ setHasVoted(false);+ } else {+ setVotes((v) => v + 1);+ shouldIncrement = true;+ setHasVoted(true);+ }++ if (onVote) {+ onVote(shouldIncrement);+ }++ debouncedIncrement(shouldIncrement)?.catch((e) => {+ setVotes(previousVotes);+ console.error(e);+ });+ }}+ >+ <ThumbsUp className="h-4 w-4" />+ <span className="font-bold">{votes}</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>{session.data?.user?.id ? 'Upvote' : 'Login to Upvote'}</p>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/comments/[commentId]/page.tsx b/apps/aot/src/app/events/[year]/[day]/comments/[commentId]/page.tsxnew file mode 100644index 00000000..b57de518--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/comments/[commentId]/page.tsx@@ -0,0 +1,35 @@+import { auth } from '~/server/auth';+import { getChallengeRouteData } from '../../getChallengeRouteData';+import { getPreselectedCommentMetadata } from '../../_components/comments/getCommentRouteData';+import { Description } from '../../_components/description';+import { Comments } from '../../_components/comments';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ params: {+ year: string;+ day: string;+ commentId: string;+ };+}++export default async function CommentPage({ params: { year, day, commentId } }: Props) {+ const session = await auth();+ const { challenge } = await getChallengeRouteData(getAotSlug({ year, day }), session);+ const preselectedCommentMetadata = await getPreselectedCommentMetadata(+ challenge.id,+ Number(commentId),+ );++ return (+ <div className="relative h-full">+ <Description challenge={challenge} />+ <Comments+ root={challenge}+ preselectedCommentMetadata={preselectedCommentMetadata}+ type="CHALLENGE"+ expanded+ />+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/error.tsx b/apps/aot/src/app/events/[year]/[day]/error.tsxnew file mode 100644index 00000000..222be9e1--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/error.tsx@@ -0,0 +1,18 @@+'use client'; // Error components must be Client Components++import { Button } from '@repo/ui/components/button';+import { Text } from '@repo/ui/components/typography/typography';+import Link from 'next/link';++export default function Error() {+ return (+ <div className="container flex h-full flex-col items-center justify-center">+ <Text className="mb-6" intent="h2">+ Uh oh! We couldn't find the challenge you were looking for.+ </Text>+ <Link href="/explore">+ <Button>Explore Challenges</Button>+ </Link>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/fullscreen-button.tsx b/apps/aot/src/app/events/[year]/[day]/fullscreen-button.tsxnew file mode 100644index 00000000..8c11311c--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/fullscreen-button.tsx@@ -0,0 +1,63 @@+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { Maximize2, Minimize2 } from '@repo/ui/icons';+import { useEffect } from 'react';+import { create } from 'zustand';++export const FS_SETTINGS = {+ isFullscreen: false,+};++type FSSettings = typeof FS_SETTINGS;++interface FSState {+ fssettings: FSSettings;+ updateFSSettings: (settings: Partial<FSSettings>) => void;+}++export const useFullscreenSettingsStore = create<FSState>()((set, get) => ({+ fssettings: FS_SETTINGS,+ updateFSSettings: (fssettings) => set({ fssettings: { ...get().fssettings, ...fssettings } }),+}));++export function FullscreenButton() {+ const { fssettings, updateFSSettings } = useFullscreenSettingsStore();++ const handleToggleFullscreen = () => {+ if (!document.fullscreenElement) {+ document.documentElement.requestFullscreen();+ } else if (document.exitFullscreen) {+ document.exitFullscreen();+ }+ updateFSSettings({ ...fssettings, isFullscreen: !fssettings.isFullscreen });+ };++ useEffect(() => {+ const fullscreenchanged = () => {+ if (!document.fullscreenElement) {+ updateFSSettings({ ...fssettings, isFullscreen: false });+ }+ };+ document.addEventListener('fullscreenchange', fullscreenchanged);+ return () => document.removeEventListener('fullscreenchange', fullscreenchanged);+ }, [fssettings, updateFSSettings]);++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ className="focus:outline-none focus-visible:ring-2"+ onClick={handleToggleFullscreen}+ >+ {fssettings.isFullscreen ? (+ <Minimize2 className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" size={20} />+ ) : (+ <Maximize2 className="stroke-zinc-500 stroke-1 hover:stroke-zinc-400" size={20} />+ )}+ </button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Maximize Editor</p>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/getChallengeRouteData.ts b/apps/aot/src/app/events/[year]/[day]/getChallengeRouteData.tsnew file mode 100644index 00000000..229a7244--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/getChallengeRouteData.ts@@ -0,0 +1,123 @@+import { type Session } from '@repo/auth/server';+import { prisma } from '@repo/db';+import { cache } from 'react';+import { validateCompilerOptions } from '~/utils/validateCompilerOptions';++export type ChallengeRouteData = NonNullable<Awaited<ReturnType<typeof getChallengeRouteData>>>;++/**+ *this is data to populate the description tab (default tab on challenge page)+ */+export const getChallengeRouteData = cache(async (slug: string, session: Session | null) => {+ const challenge = await prisma.challenge.findFirstOrThrow({+ where: {+ slug,+ status: 'ACTIVE',+ },+ include: {+ user: {+ select: {+ id: true,+ name: true,+ roles: true,+ bio: true,+ image: true,+ },+ },+ _count: {+ select: {+ vote: true,+ },+ },+ vote: {+ where: {+ userId: session?.user?.id || '',+ },+ },+ bookmark: {+ where: {+ userId: session?.user?.id || '',+ },+ },+ submission: {+ where: {+ userId: session?.user?.id || '',+ isSuccessful: true,+ },+ take: 1,+ },+ },+ });++ const tsconfig = challenge.tsconfig;+ if (!validateCompilerOptions(tsconfig)) {+ throw new Error(`Challenge "${challenge.slug}" has an invalid tsconfig`);+ }++ return {+ challenge: {+ ...challenge,+ hasSolved: challenge.submission.length > 0,+ tsconfig,+ },+ };+});+export const getCurrentChallenge = cache(async (slug: string, session: Session | null) => {+ return prisma.challenge.findFirstOrThrow({+ where: {+ slug,+ status: 'ACTIVE',+ },+ include: {+ user: {+ select: {+ name: true,+ },+ },+ _count: {+ select: {+ vote: true,+ },+ },+ vote: {+ where: {+ userId: session?.user?.id || '',+ },+ },+ bookmark: {+ where: {+ userId: session?.user?.id || '',+ },+ },+ submission: {+ where: {+ userId: session?.user?.id || '',+ isSuccessful: true,+ },+ take: 1,+ },+ },+ });+});++export type GetCurrentChallengeType = Awaited<ReturnType<typeof getCurrentChallenge>>;++export const isEnrolledInAnyTrack = cache(async (session: Session | null) => {+ if (!session) {+ return false;+ }+ const userWithTrackCount = await prisma.user.findUnique({+ where: { id: session?.user?.id },+ select: {+ _count: {+ select: { tracks: true },+ },+ },+ });++ const numberOfTrack = userWithTrackCount?._count.tracks;+ if (!numberOfTrack) {+ return false;+ }+ return true;+});diff --git a/apps/aot/src/app/events/[year]/[day]/increment.action.ts b/apps/aot/src/app/events/[year]/[day]/increment.action.tsnew file mode 100644index 00000000..65cb1ed0--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/increment.action.ts@@ -0,0 +1,51 @@+'use server';+import { prisma } from '@repo/db';+import type { VoteType } from '@repo/db/types';+import { auth } from '~/server/auth';++export async function incrementOrDecrementUpvote({+ rootId,+ rootType,+ shouldIncrement,+}: {+ rootId: number;+ rootType: VoteType;+ shouldIncrement: boolean;+}) {+ const session = await auth();++ if (!session) {+ throw new Error('User not authenticated');+ }++ const voteExists = await prisma.vote.findFirst({+ where: {+ rootType,+ 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) {+ await prisma.vote.create({+ data: {+ rootType,+ challengeId: rootType === 'CHALLENGE' ? rootId : undefined,+ commentId: rootType === 'COMMENT' ? rootId : undefined,+ sharedSolutionId: rootType === 'SHAREDSOLUTION' ? rootId : undefined,+ userId: session.user.id,+ },+ });+ }++ if (session?.user && voteExists && !shouldIncrement) {+ await prisma.vote.delete({+ where: {+ id: voteExists.id,+ },+ });+ }+}diff --git a/apps/aot/src/app/events/[year]/[day]/layout.tsx b/apps/aot/src/app/events/[year]/[day]/layout.tsxindex 582f0d49..e99f5bcc 100644--- a/apps/aot/src/app/events/[year]/[day]/layout.tsx+++ b/apps/aot/src/app/events/[year]/[day]/layout.tsx@@ -1,12 +1,25 @@-export default function EventsByYearLayout({- children, // will be a page or nested layout+import { ForceRenderUntilClient } from '@repo/ui/components/force-render-until-client';++import { api } from '~/trpc/server';+import { ChallengeLayoutWrapper } from './_components/challenge-layout-wrapper';+import { TrackVisibiltyProvider } from './use-track-visibility.hook';++export default async function LayoutData({+ children,+ params: { year, day },}: {children: React.ReactNode;+ params: { year: string; day: string };}) {+ // we do the same query in page.tsx..+ // confirm its reusing the cache or doing two duplicate queries+ const challenge = await api.event.getEventChallengeBySlug({ slug: `${year}-${day}` });+return (- <section>- Layout for DAY- {children}- </section>+ <ForceRenderUntilClient>+ <TrackVisibiltyProvider>+ <ChallengeLayoutWrapper challenge={challenge}>{children}</ChallengeLayoutWrapper>+ </TrackVisibiltyProvider>+ </ForceRenderUntilClient>);}diff --git a/apps/aot/src/app/events/[year]/[day]/left-wrapper.tsx b/apps/aot/src/app/events/[year]/[day]/left-wrapper.tsxnew file mode 100644index 00000000..c19729bd--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/left-wrapper.tsx@@ -0,0 +1,170 @@+'use client';++import { useParams, usePathname, useRouter } from 'next/navigation';+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';++import { cn } from '@repo/ui/cn';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@repo/ui/components/tabs';+import { FlaskConical, History, Text } from '@repo/ui/icons';++type Tab = 'description' | 'solutions' | 'submissions';+interface Props {+ children: ReactNode;+ expandPanel: () => void;+ isDesktop: boolean;+}++export function LeftWrapper({ children, expandPanel, isDesktop }: Props) {+ const pathname = usePathname();+ const router = useRouter();+ const { year, day } = useParams();+ const [isCollapsed, setIsCollapsed] = useState(false);++ const isCollapsedRef = useRef(isCollapsed);+ const isDesktopRef = useRef(isDesktop);+ isDesktopRef.current = isDesktop;+ isCollapsedRef.current = isCollapsed;++ const tabsRef = useRef<HTMLDivElement | null>(null);+ const tabsListRef = useRef<HTMLDivElement | null>(null);+ const tabsContentRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ const tabsElement = tabsRef.current;+ const tabsContentElement = tabsContentRef.current;+ const tabsListElement = tabsListRef.current;++ if (!tabsElement || !tabsContentElement || !tabsListElement) return;++ const handleResize = (entries: ResizeObserverEntry[]) => {+ for (const entry of entries) {+ if (entry.target !== tabsElement) continue;+ const isDesktopCollapsed = isDesktopRef.current && entry.contentRect.width <= 60;+ const isMobileCollapsed = !isDesktopRef.current && entry.contentRect.height <= 41;++ if (isDesktopCollapsed || isMobileCollapsed) {+ setIsCollapsed(true);+ tabsContentElement.style.display = 'none';+ if (isDesktopRef.current && !isCollapsedRef.current) {+ tabsListElement.style.display = 'none';+ }+ } else {+ tabsContentElement.style.display = '';+ setIsCollapsed(false);+ }+ }+ };++ const resizeObserver = new ResizeObserver(handleResize);+ resizeObserver.observe(tabsElement);++ return () => {+ resizeObserver.unobserve(tabsElement);+ };+ }, []);++ useEffect(() => {+ const tabsListElement = tabsListRef.current;+ if (tabsListElement) {+ tabsListElement.style.display = '';+ }+ }, [isCollapsed]);++ const selectedTab: Tab = useMemo(() => {+ const splitPath = pathname.split('/');++ if (splitPath.includes('submissions')) {+ return 'submissions';+ }+ if (splitPath.includes('solutions')) {+ return 'solutions';+ }++ return 'description';+ }, [pathname]);++ const isIconOnly = isCollapsed && isDesktop;++ return (+ <div className="flex h-full w-full flex-col">+ <Tabs+ ref={tabsRef}+ className="flex h-full w-full flex-col overflow-hidden"+ value={selectedTab}+ >+ <TabsList+ className={cn(+ 'bg-background/90 dark:bg-muted/90 sticky top-0 grid h-auto w-full border-b border-zinc-300 backdrop-blur-sm dark:border-zinc-700',+ {+ 'grid-rows-3 gap-2': isIconOnly,+ 'grid-cols-3 gap-0.5': !isIconOnly,+ },+ )}+ ref={tabsListRef}+ >+ <TabsTrigger+ className={cn(+ 'rounded-md duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',+ {+ 'p-4': isIconOnly,+ 'rounded-bl-xl': isCollapsed && !isDesktop,+ },+ )}+ onClick={() => {+ router.push(`/events/${year}/${day}`);+ isCollapsed && expandPanel();+ }}+ onFocus={(e) => {+ e.target.click();+ }}+ value="description"+ >+ {isIconOnly ? <Text className="h-4 w-4" /> : 'Description'}+ </TabsTrigger>+ <TabsTrigger+ className={cn(+ 'rounded-md duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',+ { 'p-4': isIconOnly },+ )}+ onClick={() => {+ router.push(`/events/${year}/${day}/solutions`);+ isCollapsed && expandPanel();+ }}+ onFocus={(e) => {+ e.target.click();+ }}+ value="solutions"+ >+ {isIconOnly ? <FlaskConical className="h-4 w-4" /> : 'Solutions'}+ </TabsTrigger>+ <TabsTrigger+ className={cn(+ 'rounded-md rounded-tr-lg duration-300 hover:bg-neutral-200/50 data-[state=active]:bg-neutral-200 dark:hover:bg-neutral-700/50 dark:data-[state=active]:bg-neutral-700',+ {+ 'p-4': isIconOnly,+ 'rounded-br-xl': isCollapsed && !isDesktop,+ },+ )}+ onClick={() => {+ router.push(`/events/${year}/${day}/submissions`);+ isCollapsed && expandPanel();+ }}+ onFocus={(e) => {+ e.target.click();+ }}+ value="submissions"+ >+ {isIconOnly ? <History className="h-4 w-4" /> : 'Submissions'}+ </TabsTrigger>+ </TabsList>+ <TabsContent+ className="mt-0 h-[calc(100%_-_44px)]"+ value={selectedTab}+ ref={tabsContentRef}+ >+ {children}+ </TabsContent>+ </Tabs>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/loading.tsx b/apps/aot/src/app/events/[year]/[day]/loading.tsxnew file mode 100644index 00000000..bac659b7--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/loading.tsx@@ -0,0 +1 @@+export { DescriptionSkeleton as default } from './_components/description/description-skeleton';diff --git a/apps/aot/src/app/events/[year]/[day]/page.tsx b/apps/aot/src/app/events/[year]/[day]/page.tsxindex 1737bc9d..e79ad09d 100644--- a/apps/aot/src/app/events/[year]/[day]/page.tsx+++ b/apps/aot/src/app/events/[year]/[day]/page.tsx@@ -1,4 +1,8 @@+import { type Session } from '@repo/auth/server';import { api } from '~/trpc/server';+import { Comments } from './_components/comments';+import { Description } from './_components/description';+import { buildMetaForEventPage } from '~/utils/metadata';interface Props {params: {@@ -7,8 +11,24 @@ interface Props {};}+export async function generateMetadata({ params: { year } }: Props) {+ return buildMetaForEventPage({+ title: `Advent of Typescript ${year}`,+ description: `Advent of Typescript ${year}`,+ });+}+export default async function Challenges({ params: { year, day } }: Props) {const challenge = await api.event.getEventChallengeBySlug({ slug: `${year}-${day}` });- return <pre>{JSON.stringify(challenge, null, 2)}</pre>;+ return (+ <div className="relative h-full ">+ <Description challenge={challenge} />+ <Comments root={challenge} type="CHALLENGE" />+ </div>+ );+}++export function isAuthor(session: Session | null, userId?: string | null) {+ return userId && session?.user?.id && userId === session?.user?.id;}diff --git a/apps/aot/src/app/events/[year]/[day]/right-wrapper.tsx b/apps/aot/src/app/events/[year]/[day]/right-wrapper.tsxnew file mode 100644index 00000000..acb4c550--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/right-wrapper.tsx@@ -0,0 +1,53 @@+'use client';+import { useSession } from '@repo/auth/react';+import { CodePanel } from '@repo/monaco';+import { useParams, useRouter, useSelectedLayoutSegments } from 'next/navigation';+import type { Challenge } from './_components/types';+import { SubmissionOverview } from './submissions/[[...catchAll]]/_components/overview';+import { saveSubmission } from './submissions/[[...catchAll]]/save-submission.action';+import { SettingsElements } from './SettingsElements';++interface Props {+ challenge: Challenge;+}++export function RightWrapper({ challenge }: Props) {+ const router = useRouter();+ const { year, day } = useParams();+ const segments = useSelectedLayoutSegments();+ const { data: session } = useSession();++ if (!challenge) return null;++ if (segments[0] === 'submissions' && typeof segments[1] === 'string') {+ return <SubmissionOverview submissionId={segments[1]} />;+ }++ // Redirect to solution on successful submission and show suggestions+ async function handleSuccessfulSubmission(+ isSuccessful: boolean,+ submissionId: number,+ slug?: string,+ ) {+ const query = slug ? `&slug=${slug}` : '';+ isSuccessful &&+ router.push(`/events/${year}/${day}/submissions/${submissionId}?success=true${query}`);+ }++ return (+ <CodePanel+ challenge={challenge}+ saveSubmission={async (code, isSuccessful) => {+ const submission = await saveSubmission({+ challenge,+ code,+ isSuccessful,+ });++ return handleSuccessfulSubmission(submission.isSuccessful, submission.id, '');+ }}+ submissionDisabled={!session?.user}+ settingsElement={<SettingsElements />}+ />+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/comments/[commentId]/page.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/comments/[commentId]/page.tsxnew file mode 100644index 00000000..ffac16e8--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/comments/[commentId]/page.tsx@@ -0,0 +1,39 @@+import { auth } from '~/server/auth';+import { getSolutionIdRouteData } from '../../getSolutionIdRouteData';+import { getPreselectedSolutionCommentMetadata } from '../../../../_components/comments/getCommentRouteData';+import { SolutionDetails } from '../../../_components/solution-detail';+import { Comments } from '../../../../_components/comments';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ params: {+ year: string;+ day: string;+ commentId: string;+ solutionId: string;+ };+}++export default async function SolutionPageComments({+ params: { solutionId, commentId, year, day },+}: Props) {+ const session = await auth();+ const solution = await getSolutionIdRouteData(getAotSlug({ year, day }), solutionId, session);+ const preselectedCommentMetadata = await getPreselectedSolutionCommentMetadata(+ Number(solutionId),+ Number(commentId),+ Number(solution.challengeId),+ );++ return (+ <div className="relative h-full">+ <SolutionDetails solution={solution} />+ <Comments+ root={solution}+ type="SOLUTION"+ preselectedCommentMetadata={preselectedCommentMetadata}+ expanded+ />+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/error.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/error.tsxnew file mode 100644index 00000000..d9ecdc13--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/error.tsx@@ -0,0 +1,13 @@+'use client'; // Error components must be Client Components++import { Text } from '@repo/ui/components/typography/typography';++export default function Error() {+ return (+ <div className="container flex h-full flex-col items-center justify-center">+ <Text className="mb-6" intent="h2">+ Uh oh! We couldn't find the solution you were looking for.+ </Text>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/getSolutionIdRouteData.ts b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/getSolutionIdRouteData.tsnew file mode 100644index 00000000..4f097380--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/getSolutionIdRouteData.ts@@ -0,0 +1,54 @@+import { cache } from 'react';+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({+ where: { slug },+ select: { id: true },+ });+ const solution = await prisma.sharedSolution.findFirst({+ where: {+ id: Number(solutionId),+ challengeId: challenge.id,+ },+ include: {+ user: {+ select: {+ id: true,+ name: true,+ image: true,+ roles: true,+ bio: true,+ },+ },+ _count: {+ select: { vote: true },+ },+ vote: {+ where: {+ userId: session?.user?.id || '',+ },+ select: {+ userId: true,+ },+ },+ challenge: {+ select: {+ slug: true,+ },+ },+ },+ });++ if (!solution) {+ redirect(`/challenge/${challenge.id}/solutions`);+ }++ return solution;+ },+);diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/page.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/page.tsxnew file mode 100644index 00000000..b7ad89a6--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/[solutionId]/page.tsx@@ -0,0 +1,48 @@+import { prisma } from '@repo/db';+import { SolutionDetails } from '../_components/solution-detail';+import { auth } from '~/server/auth';+import { getSolutionIdRouteData } from './getSolutionIdRouteData';+import { Comments } from '../../_components/comments';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ params: {+ year: string;+ day: string;+ solutionId: string;+ };+}++export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionIdRouteData>>>;+export default async function SolutionPage({ params: { solutionId, year, day } }: Props) {+ const session = await auth();++ const solution = await getSolutionIdRouteData(getAotSlug({ year, day }), solutionId, session);++ return (+ <div className="relative h-full">+ <SolutionDetails solution={solution} />+ <Comments root={solution} type="SOLUTION" />+ </div>+ );+}++export async function generateMetadata({ params: { solutionId } }: Props) {+ const solution = await prisma.sharedSolution.findFirstOrThrow({+ where: {+ id: Number(solutionId),+ },+ include: {+ challenge: {+ select: {+ name: true,+ },+ },+ },+ });++ return {+ title: `${solution.title}, solution to ${solution.challenge?.name} | TypeHero`,+ description: `View this solution to ${solution.challenge?.name} on TypeHero.`,+ };+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/_actions.ts b/apps/aot/src/app/events/[year]/[day]/solutions/_components/_actions.tsnew file mode 100644index 00000000..7e0971e9--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/_actions.ts@@ -0,0 +1,98 @@+'use server';++import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import { revalidateTag } from 'next/cache';+import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';+import type { ChallengeSolution } from '../[solutionId]/page';++interface Args {+ challengeId: number;+ description: string;+ slug: string;+ title: string;+ userId: string;+}++interface SolutionUpdateArgs {+ id: number;+ description: string;+ slug: string;+ title: string;+ userId: string;+}++export const createCacheKeyForSolutions = (slug: string) => `challenge-${slug}-solutions`;+export const createCacheKeyForSharedSolutionsTab = (userId: string) => `${userId}-shared-solutions`;++export async function updateSolution({ id, description, slug, title }: SolutionUpdateArgs) {+ const session = await auth();++ const solution = await prisma.sharedSolution.findFirstOrThrow({+ where: {+ id,+ },+ });++ if (!isAuthor(session, solution.userId) && !isAdminOrModerator(session)) {+ throw new Error('Not authorized to edit this solution.');+ }++ await prisma.sharedSolution.update({+ where: { id },+ data: {+ title,+ description,+ },+ });++ revalidateTag(createCacheKeyForSolutions(slug));+}++export async function postSolution({ challengeId, description, slug, title, userId }: Args) {+ const session = await auth();+ if (!session) throw new Error('You must be logged in to submit a solution');++ await prisma.sharedSolution.create({+ data: {+ challengeId,+ description,+ title,+ userId,+ },+ });+ revalidateTag(createCacheKeyForSolutions(slug));+ revalidateTag(createCacheKeyForSharedSolutionsTab(userId));+}++export async function deleteSolution(solutionToDelete: ChallengeSolution) {+ const session = await auth();+ const solution = await prisma.sharedSolution.findFirstOrThrow({+ where: {+ id: solutionToDelete.id,+ },+ });++ if (!isAuthor(session, solution.userId) && !isAdminOrModerator(session)) {+ throw new Error('Not authorized to delete this solution.');+ }++ await prisma.sharedSolution.delete({+ where: { id: solutionToDelete.id },+ });++ revalidateTag(createCacheKeyForSolutions(solutionToDelete.challenge?.slug ?? ''));+}++export async function pinOrUnpinSolution(id: number, isPinned: boolean, slug: string) {+ const session = await auth();++ if (!isAdminOrModerator(session))+ throw new Error('You are not authorized to pin/unpin solutions');++ await prisma.sharedSolution.update({+ where: { id },+ data: { isPinned },+ });+ revalidateTag(createCacheKeyForSolutions(slug));+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/delete/index.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/delete/index.tsxnew file mode 100644index 00000000..df660e61--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/delete/index.tsx@@ -0,0 +1,75 @@+import type { DialogTriggerProps } from '@radix-ui/react-dialog';+import { useState } from 'react';+import { Dialog, DialogContent, DialogTrigger } from '@repo/ui/components/dialog';+import { TypographyLarge } from '@repo/ui/components/typography/large';+import { Button } from '@repo/ui/components/button';+import { TypographyP } from '@repo/ui/components/paragraph';+import { deleteSolution } from '../_actions';+import { toast } from '@repo/ui/components/use-toast';+import { useRouter } from 'next/navigation';+import { useQueryClient } from '@tanstack/react-query';+import type { ChallengeSolution } from '../../[solutionId]/page';++interface SolutionDeleteDialogProps extends DialogTriggerProps {+ solution: ChallengeSolution;+ slug: string[] | string | undefined;+}++export function SolutionDeleteDialog({+ children,+ slug,+ solution,+ ...props+}: SolutionDeleteDialogProps) {+ const queryClient = useQueryClient();+ const [isOpen, setIsOpen] = useState(false);+ const router = useRouter();++ async function handleDeleteSolution() {+ try {+ await deleteSolution(solution);+ toast({+ title: 'Solution Deleted',+ variant: 'success',+ description: 'The solution was successfully deleted.',+ });+ // invalidate cache on deleting a solution successfully+ queryClient.invalidateQueries({+ queryKey: ['challenge-solutions', slug],+ });+ queryClient.refetchQueries({+ queryKey: ['challenge-solutions', slug],+ });+ router.back();+ } catch (e) {+ toast({+ title: 'Uh Oh!',+ variant: 'destructive',+ description: 'An error occurred while trying to delete the comment.',+ });+ }+ }++ return (+ <Dialog onOpenChange={() => setIsOpen(!isOpen)} open={isOpen}>+ <DialogTrigger {...props}>{children}</DialogTrigger>+ <DialogContent className="flex flex-col space-y-2">+ <TypographyLarge>Delete solution</TypographyLarge>+ <TypographyP>Are you sure you want to delete this solution?</TypographyP>+ <div className="flex flex-row gap-2">+ <Button onClick={() => setIsOpen(!isOpen)} variant="outline">+ Cancel+ </Button>+ <Button+ onClick={() => {+ void handleDeleteSolution();+ }}+ variant="destructive"+ >+ Delete+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/edit-solution.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/edit-solution.tsxnew file mode 100644index 00000000..3ee5dc5a--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/edit-solution.tsx@@ -0,0 +1,131 @@+import { zodResolver } from '@hookform/resolvers/zod';+import { useSession } from '@repo/auth/react';+import { Button } from '@repo/ui/components/button';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';+import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';+import { Input } from '@repo/ui/components/input';+import { useToast } from '@repo/ui/components/use-toast';+import { useTheme } from 'next-themes';+import { useParams } from 'next/navigation';+import { useForm } from 'react-hook-form';+import { z } from 'zod';+import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';+import { updateSolution } from './_actions';+import { useUploadThing } from '~/utils/useUploadthing';+import type { ChallengeSolution } from '../[solutionId]/page';++const formSchema = z.object({+ title: createNoProfanitySchemaWithValidate((zodString) =>+ zodString.min(5, 'The title must be longer than 5 characters'),+ ),+ content: createNoProfanitySchemaWithValidate((zodString) =>+ zodString.min(30, 'Content must be longer than 30 characters'),+ ),+});++export type FormSchema = z.infer<typeof formSchema>;++interface Props {+ solution: ChallengeSolution;+ setIsEditing: (isEditing: boolean) => void;+}++export function EditSolution({ solution, setIsEditing }: Props) {+ const { slug } = useParams();+ const session = useSession();+ const form = useForm<FormSchema>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ title: solution.title,+ content: solution.description,+ },+ });+ const { toast } = useToast();++ const onSubmit = async (data: FormSchema) => {+ try {+ await updateSolution({+ id: solution.id,+ description: data.content ?? '',+ slug: slug as string,+ title: data.title ?? '',+ userId: session.data?.user?.id!,+ });++ toast({+ variant: 'success',+ title: 'Your solution has been updated!',+ });+ } catch (error) {+ toast({+ variant: 'destructive',+ title: 'Uh oh! Something went wrong. Please try again.',+ });+ } finally {+ setIsEditing(false);+ }+ };++ const { theme } = useTheme();+ theme !== undefined+ ? document.documentElement.setAttribute('data-color-mode', theme)+ : document.documentElement.setAttribute('data-color-mode', 'system');++ return (+ <Form {...form}>+ <form className="relative flex h-full flex-col" onSubmit={form.handleSubmit(onSubmit)}>+ <div className="bg-background/90 dark:bg-muted/90 sticky right-0 top-0 flex w-full items-center justify-between gap-2 border-b border-zinc-300 bg-opacity-20 p-1 pr-2 backdrop-blur-sm dark:border-zinc-700">+ <div className="flex-1">+ <FormField+ control={form.control}+ name="title"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ className="rounded-xl border-zinc-300 bg-zinc-100 focus-visible:ring-0 dark:border-zinc-700 dark:bg-zinc-900"+ {...field}+ placeholder="Enter a title for your solution."+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <Button+ className="h-8 rounded-lg bg-white px-3 py-2 text-black hover:bg-zinc-200 focus-visible:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:focus-visible:bg-zinc-700"+ onClick={() => setIsEditing(false)}+ type="button"+ >+ Cancel+ </Button>+ <Button+ className="h-8 rounded-lg px-3 py-2"+ type="submit"+ disabled={form.formState.isSubmitting}+ >+ Update+ </Button>+ </div>+ <div className="flex flex-1 flex-col">+ <FormField+ control={form.control}+ name="content"+ render={({ field }) => (+ <FormItem className="flex flex-1 flex-col">+ <RichMarkdownEditor+ allowImageUpload+ value={field.value}+ onChange={field.onChange}+ useUploadThing={useUploadThing}+ />+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </form>+ </Form>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/index.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/index.tsxnew file mode 100644index 00000000..ab990595--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/index.tsx@@ -0,0 +1,191 @@+'use client';++import { Calendar, MessageCircle, ThumbsUp } from '@repo/ui/icons';+import { useSession } from '@repo/auth/react';+import Link from 'next/link';+import { useRef, useState } from 'react';+import { SolutionEditor } from './solution-editor';+import { NoSolutions } from './nosolutions';+import { SubmitSolution } from './submit-solution';+import { type PaginatedSolution, getPaginatedSolutions } from '../getSolutionRouteData';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import { Badge } from '@repo/ui/components/badge';+import { useParams } from 'next/navigation';+import { useQuery } from '@tanstack/react-query';+import { SolutionsSkeleton } from './solution-skeleton';+import { useGetQueryString } from './useGetQueryString';+import { useQueryParamState } from './useQueryParamState';+import { useLocalStorage } from '~/utils/useLocalStorage';+import { SortSelect } from '../../_components/sort-select';+import { Pagination } from '../../_components/pagination';+import { UserBadge } from '../../_components/comments/enhanced-user-badge';++interface Props {+ slug: string;+}++export const SORT_KEYS = [+ {+ label: 'Newest Solutions',+ value: 'newest',+ key: 'createdAt',+ order: 'desc',+ },+ {+ label: 'Most Votes',+ value: 'votes',+ key: 'vote',+ order: 'desc',+ },+ {+ label: 'Most Replies',+ value: 'solutionComment',+ key: 'solutionComment',+ order: 'desc',+ },+] as const;++type View = 'details' | 'editor' | 'list';++export function Solutions({ slug }: Props) {+ const [view, setView] = useState<View>('list');+ const commentContainerRef = useRef<HTMLDivElement>(null);+ const [storageKey, setStorageKey] = useLocalStorage('sortKey', 'newest');+ const [sortKey, setSortKey] = useState<(typeof SORT_KEYS)[number]>(+ SORT_KEYS.find((sk) => sk.value === storageKey) ?? SORT_KEYS[0],+ );+ const [page, setPage] = useQueryParamState<number>('page', 1);+ const queryKey = ['challenge-solutions', slug, page, sortKey.key, sortKey.order];+ const session = useSession();++ const handleChangePage = (page: number) => {+ setPage(page);+ commentContainerRef.current?.scroll({+ top: 0,+ behavior: 'smooth',+ });+ };++ const handleValueChange = (value: string) => {+ setSortKey(SORT_KEYS.find((sk) => sk.value === value) ?? SORT_KEYS[0]);+ setStorageKey(value);+ setPage(1);+ };++ const { status, data: pageData } = useQuery({+ queryKey,+ queryFn: () =>+ getPaginatedSolutions({ slug, page, sortKey: sortKey.key, sortOrder: sortKey.order }),+ staleTime: 60000, // one minute+ refetchOnWindowFocus: false,+ });++ const loggedInUserHasSolution = pageData?.submission?.length ?? 0;++ return (+ <div className="flex h-full flex-col">+ {view === 'editor' && pageData?.id ? (+ <SolutionEditor+ challengeId={pageData.id}+ code={pageData?.submission?.[0]?.code}+ dismiss={() => setView('list')}+ />+ ) : null}++ {view === 'list' && (+ <>+ {pageData?.sharedSolution?.length !== 0 ? (+ <>+ {status === 'pending' && <SolutionsSkeleton />}+ {status === 'success' && (+ <div className="bg-background/70 dark:bg-muted/70 flex w-full justify-end border-b border-zinc-300 p-2 backdrop-blur-sm dark:border-zinc-700">+ <SubmitSolution disabled={Boolean(!loggedInUserHasSolution)} setView={setView} />+ </div>+ )}+ <div+ className="custom-scrollable-element relative flex h-full flex-col overflow-y-auto"+ ref={commentContainerRef}+ >+ <div>+ {(pageData?.sharedSolution?.length ?? 0) > 0 && (+ <SortSelect+ currentSortKey={sortKey}+ totalSortKeys={SORT_KEYS}+ onValueChange={handleValueChange}+ />+ )}+ </div>+ <div className="flex-1">+ {status === 'success' &&+ pageData?.sharedSolution?.map((solution) => (+ <SolutionRow key={solution.id} solution={solution} />+ ))}+ </div>+ {(pageData?.totalPages ?? 0) > 1 && (+ <div className="mb-2 flex justify-center">+ <Pagination+ currentPage={page}+ onClick={handleChangePage}+ totalPages={pageData?.totalPages ?? 0}+ />+ </div>+ )}+ </div>+ </>+ ) : (+ <NoSolutions+ loggedInUser={Boolean(session.data?.user)}+ loggedInUserHasSolution={loggedInUserHasSolution > 0}+ setView={setView}+ />+ )}+ </>+ )}+ </div>+ );+}++function SolutionRow({+ solution,+}: {+ solution: NonNullable<PaginatedSolution['sharedSolution']>[number];+}) {+ const { year, day } = useParams();+ const queryString = useGetQueryString();+ return (+ <Link+ href={`/events/${year}/${day}/solutions/${solution.id}?${queryString}`}+ className="flex cursor-pointer flex-col gap-2 p-4 duration-300 hover:bg-neutral-100 dark:hover:bg-zinc-700/50"+ >+ <h3 className="truncate font-bold">{solution.title}</h3>+ <div className="flex items-center gap-2">+ <UserBadge+ user={{+ name: solution.user?.name ?? '',+ image: solution.user?.image ?? '',+ bio: solution.user?.bio ?? '',+ roles: solution.user?.roles ?? [],+ }}+ hideLinks+ />+ <div className="text-muted-foreground flex flex-1 items-center gap-2">+ <Calendar className=" h-4 w-4" />+ <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">+ Pinned+ </Badge>+ ) : null}+ <Badge variant="secondary" size="xs" className="gap-1">+ <ThumbsUp className="h-4 w-4" />+ <span>{solution._count.vote}</span>+ </Badge>+ <Badge variant="secondary" size="xs" className="gap-1">+ <MessageCircle className="h-4 w-4" />+ <span>{solution._count.solutionComment}</span>+ </Badge>+ </div>+ </Link>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/nosolutions.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/nosolutions.tsxnew file mode 100644index 00000000..f52657f0--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/nosolutions.tsx@@ -0,0 +1,65 @@+import { SubmitSolution } from './submit-solution';++interface Props {+ loggedInUser: boolean;+ loggedInUserHasSolution: boolean;+ setView: (view: 'editor' | 'list') => void;+}++export function NoSolutions({ setView, loggedInUser, loggedInUserHasSolution }: Props) {+ return (+ <div className="flex h-full items-center justify-center">+ <p className="flex flex-col items-center gap-2 text-center text-neutral-500 dark:text-zinc-400">+ <svg+ className="mr-6 h-28 w-28"+ data-name="Layer 1"+ viewBox="0 0 647.63626 632.17383"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M687.3279,276.08691H512.81813a15.01828,15.01828,0,0,0-15,15v387.85l-2,.61005-42.81006,13.11a8.00676,8.00676,0,0,1-9.98974-5.31L315.678,271.39691a8.00313,8.00313,0,0,1,5.31006-9.99l65.97022-20.2,191.25-58.54,65.96972-20.2a7.98927,7.98927,0,0,1,9.99024,5.3l32.5498,106.32Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M725.408,274.08691l-39.23-128.14a16.99368,16.99368,0,0,0-21.23-11.28l-92.75,28.39L380.95827,221.60693l-92.75,28.4a17.0152,17.0152,0,0,0-11.28028,21.23l134.08008,437.93a17.02661,17.02661,0,0,0,16.26026,12.03,16.78926,16.78926,0,0,0,4.96972-.75l63.58008-19.46,2-.62v-2.09l-2,.61-64.16992,19.65a15.01489,15.01489,0,0,1-18.73-9.95l-134.06983-437.94a14.97935,14.97935,0,0,1,9.94971-18.73l92.75-28.4,191.24024-58.54,92.75-28.4a15.15551,15.15551,0,0,1,4.40966-.66,15.01461,15.01461,0,0,1,14.32032,10.61l39.0498,127.56.62012,2h2.08008Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M398.86279,261.73389a9.0157,9.0157,0,0,1-8.61133-6.3667l-12.88037-42.07178a8.99884,8.99884,0,0,1,5.9712-11.24023l175.939-53.86377a9.00867,9.00867,0,0,1,11.24072,5.9707l12.88037,42.07227a9.01029,9.01029,0,0,1-5.9707,11.24072L401.49219,261.33887A8.976,8.976,0,0,1,398.86279,261.73389Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="190.15351" cy="24.95465" fill="#888a" r="20" />+ <circle cx="190.15351" cy="24.95465" fill="#444a" r="12.66462" />+ <path+ d="M878.81836,716.08691h-338a8.50981,8.50981,0,0,1-8.5-8.5v-405a8.50951,8.50951,0,0,1,8.5-8.5h338a8.50982,8.50982,0,0,1,8.5,8.5v405A8.51013,8.51013,0,0,1,878.81836,716.08691Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M723.31813,274.08691h-210.5a17.02411,17.02411,0,0,0-17,17v407.8l2-.61v-407.19a15.01828,15.01828,0,0,1,15-15H723.93825Zm183.5,0h-394a17.02411,17.02411,0,0,0-17,17v458a17.0241,17.0241,0,0,0,17,17h394a17.0241,17.0241,0,0,0,17-17v-458A17.02411,17.02411,0,0,0,906.81813,274.08691Zm15,475a15.01828,15.01828,0,0,1-15,15h-394a15.01828,15.01828,0,0,1-15-15v-458a15.01828,15.01828,0,0,1,15-15h394a15.01828,15.01828,0,0,1,15,15Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M801.81836,318.08691h-184a9.01015,9.01015,0,0,1-9-9v-44a9.01016,9.01016,0,0,1,9-9h184a9.01016,9.01016,0,0,1,9,9v44A9.01015,9.01015,0,0,1,801.81836,318.08691Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="433.63626" cy="105.17383" fill="#888a" r="20" />+ <circle cx="433.63626" cy="105.17383" fill="#444a" r="12.18187" />+ </svg>+ No solutions yet, <br />+ {loggedInUser && loggedInUserHasSolution ? (+ <>+ be the first to submit one! <SubmitSolution disabled={false} setView={setView} />+ </>+ ) : (+ 'complete the challenge to submit one!'+ )}+ </p>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-detail.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-detail.tsxnew file mode 100644index 00000000..fde7ddeb--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-detail.tsx@@ -0,0 +1,198 @@+'use client';++import { useSession } from '@repo/auth/react';+import { ActionMenu } from '@repo/ui/components/action-menu';+import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/avatar';+import { Button } from '@repo/ui/components/button';+import { Markdown } from '@repo/ui/components/markdown';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { TypographyLarge } from '@repo/ui/components/typography/large';+import { toast } from '@repo/ui/components/use-toast';+import { Calendar, Flag, Pin, Share, Trash, ArrowLeft, Pencil } from '@repo/ui/icons';+import clsx from 'clsx';+import Link from 'next/link';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import { pinOrUnpinSolution } from './_actions';+import { isAdminOrModerator, isAuthor } from '~/utils/auth-guards';+import { SolutionDeleteDialog } from './delete';+import { useParams } from 'next/navigation';+import { useState } from 'react';+import { EditSolution } from './edit-solution';+import { useGetQueryString } from './useGetQueryString';+import { useQueryClient } from '@tanstack/react-query';+import type { ChallengeSolution } from '../[solutionId]/page';+import { DefaultAvatar } from '~/utils/default-avatar';+import { ReportDialog } from '~/components/report-dialog';+import { UserBadge } from '../../_components/comments/enhanced-user-badge';+import { Vote } from '../../_components/vote';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ solution: ChallengeSolution;+}++export function SolutionDetails({ solution }: Props) {+ const { year, day } = useParams<Record<string, string>>();+ const slug = getAotSlug({ year: year!, day: day! });+ const { data: session } = useSession();+ const showPin = isAdminOrModerator(session);+ const [isEditing, setIsEditing] = useState(false);+ const queryString = useGetQueryString();+ const queryClient = useQueryClient();++ const handlePinClick = async () => {+ await pinOrUnpinSolution(solution.id, !solution.isPinned, slug);+ queryClient.invalidateQueries({+ queryKey: ['challenge-solutions', slug],+ });+ };+ const handleShareClick = async () => {+ if (navigator.clipboard) {+ const url = window.location.href;+ await navigator.clipboard.writeText(url);+ toast({+ variant: 'success',+ description: 'Link To Solution Copied!',+ });+ }+ };+ return (+ <div className="relative h-full">+ <div className="relative flex h-full flex-col">+ <div className="custom-scrollable-element flex-1 overflow-y-auto px-4 pb-16 pt-3">+ <div className="mb-5 flex flex-col gap-3">+ <div className="flex items-center gap-3">+ <Link href={`/events/${year}/${day}/solutions?${queryString}`} className="h-7 w-7">+ <div className="rounded-full p-1 hover:bg-gray-200 hover:bg-opacity-10">+ <ArrowLeft className="stroke-gray-500" size={20} />+ </div>+ </Link>+ <div className="flex items-center gap-2">+ <Avatar className="h-7 w-7">+ <AvatarImage alt="github profile picture" src={solution.user?.image ?? ''} />+ <AvatarFallback>+ <DefaultAvatar />+ </AvatarFallback>+ </Avatar>+ <TypographyLarge>{solution.title}</TypographyLarge>+ </div>+ <div className="flex items-center gap-2">+ <ReportDialog reportType="SOLUTION" solutionId={solution.id}>+ <ActionMenu+ items={[+ {+ key: 'report',+ label: 'Report',+ icon: Flag,+ },+ ]}+ onChange={() => {+ // do nothing+ }}+ />+ </ReportDialog>+ </div>+ </div>+ {/* Author, Time, Action Buttons */}+ <div className="flex items-center gap-4">+ <UserBadge+ user={{+ name: solution.user?.name ?? '',+ image: solution.user?.image ?? '',+ bio: solution.user?.bio ?? '',+ roles: solution.user?.roles ?? [],+ }}+ hideLinks+ />+ <div className="text-muted-foreground flex items-center gap-2">+ <Calendar className="h-4 w-4" />+ <span className="text-xs">{getRelativeTimeStrict(solution.createdAt)}</span>+ </div>+ </div>+ <div className="flex items-center gap-3">+ <Vote+ voteCount={solution._count.vote}+ initialHasVoted={solution.vote.length > 0}+ disabled={!session?.user?.id || solution.userId === session?.user?.id}+ rootType="SHAREDSOLUTION"+ rootId={solution.id}+ onVote={(didUpvote: boolean) => {+ solution.vote = didUpvote+ ? [+ {+ userId: session?.user?.id ?? '',+ },+ ]+ : [];+ solution._count.vote += didUpvote ? 1 : -1;+ }}+ />+ <Tooltip>+ <TooltipTrigger asChild>+ <Button onClick={handleShareClick} variant="secondary" size="xs">+ <Share className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Share</p>+ </TooltipContent>+ </Tooltip>+ {showPin ? (+ <Button+ onClick={handlePinClick}+ variant="secondary"+ size="xs"+ className={clsx(+ 'gap-2 border border-transparent [&:not(:disabled)]:hover:border-emerald-600 [&:not(:disabled)]:hover:text-emerald-600',+ {+ 'border-emerald-600 text-emerald-600': solution.isPinned,+ },+ )}+ >+ <Pin className={clsx('h-4 w-4')} />+ </Button>+ ) : null}++ {isAuthor(session, solution.userId) || isAdminOrModerator(session) ? (+ <>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={() => setIsEditing(!isEditing)}+ variant="secondary"+ size="xs"+ >+ <Pencil className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Edit</p>+ </TooltipContent>+ </Tooltip>+ <SolutionDeleteDialog solution={solution} slug={slug}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="secondary" size="xs">+ <Trash className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Delete</p>+ </TooltipContent>+ </Tooltip>+ </SolutionDeleteDialog>+ </>+ ) : null}+ </div>+ </div>+ {!isEditing && (+ <div className="prose-invert prose-h3:text-xl mt-6 leading-7">+ <Markdown>{solution.description || ''}</Markdown>{' '}+ </div>+ )}+ {isEditing ? <EditSolution solution={solution} setIsEditing={setIsEditing} /> : null}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-editor.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-editor.tsxnew file mode 100644index 00000000..daf62dd7--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-editor.tsx@@ -0,0 +1,157 @@+import { zodResolver } from '@hookform/resolvers/zod';+import { useSession } from '@repo/auth/react';+import { Button } from '@repo/ui/components/button';+import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';+import { Input } from '@repo/ui/components/input';+import { useToast } from '@repo/ui/components/use-toast';+import { useTheme } from 'next-themes';+import { useParams } from 'next/navigation';+import { useForm } from 'react-hook-form';+import { z } from 'zod';+import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';+import { postSolution } from './_actions';+import { useQueryClient } from '@tanstack/react-query';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';+import { useUploadThing } from '~/utils/useUploadthing';+import { getAotSlug } from '~/utils/getAotSlug';++const getDefaultMarkdown = (solution: string) => `+## Thoughts+<!-- Any thoughts you might like to share about the problem (within ToS, of course). -->++## Approach+<!-- Provide some details on how you approached this challenge. -->+++## Code+\`\`\`ts+${solution}+\`\`\`+`;++const formSchema = z.object({+ title: createNoProfanitySchemaWithValidate((zodString) =>+ zodString.min(5, 'The title must be longer than 5 characters'),+ ),+ content: createNoProfanitySchemaWithValidate((zodString) =>+ zodString.min(30, 'Content must be longer than 30 characters'),+ ),+});++export type FormSchema = z.infer<typeof formSchema>;++interface Props {+ challengeId: number;+ code?: string;+ dismiss: () => void;+}++export function SolutionEditor({ dismiss, challengeId, code }: Props) {+ const { year, day } = useParams();+ const slug = getAotSlug({ year: year as string, day: day as string });+ const queryClient = useQueryClient();+ const session = useSession();+ const form = useForm<FormSchema>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ title: `${session.data?.user?.name}'s Solution`,+ content: getDefaultMarkdown(code ?? ''),+ },+ });+ const { toast } = useToast();++ const onSubmit = async (data: FormSchema) => {+ try {+ await postSolution({+ challengeId,+ description: data.content ?? '',+ slug,+ title: data.title ?? `${session.data?.user?.name}'s Solution`,+ userId: session.data?.user?.id!,+ });++ toast({+ variant: 'success',+ title: 'Your solution has been posted!',+ });++ // invalidate cache on adding a solution successfully+ queryClient.invalidateQueries({+ queryKey: [`challenge-solutions`, slug],+ });+ queryClient.refetchQueries({+ queryKey: ['challenge-solutions', slug],+ });+ } catch (error) {+ toast({+ variant: 'destructive',+ title: 'Uh oh! Something went wrong. Please try again.',+ });+ } finally {+ dismiss();+ }+ };++ const { theme } = useTheme();+ theme !== undefined+ ? document.documentElement.setAttribute('data-color-mode', theme)+ : document.documentElement.setAttribute('data-color-mode', 'system');++ return (+ <Form {...form}>+ <form className="relative flex h-full flex-col" onSubmit={form.handleSubmit(onSubmit)}>+ <div className="bg-background/90 dark:bg-muted/90 sticky right-0 top-0 z-10 flex w-full items-start justify-between gap-2 border-b border-zinc-300 bg-opacity-20 p-1 pr-2 backdrop-blur-sm dark:border-zinc-700">+ <div className="flex-1">+ <FormField+ control={form.control}+ name="title"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Input+ className="rounded-xl border-zinc-300 bg-zinc-100 focus-visible:ring-0 dark:border-zinc-700 dark:bg-zinc-900"+ {...field}+ placeholder="Enter a title for your solution."+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <Button+ className="my-1 h-8 rounded-lg bg-white px-3 py-2 text-black hover:bg-zinc-200 focus-visible:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:focus-visible:bg-zinc-700"+ onClick={dismiss}+ type="button"+ >+ Cancel+ </Button>+ <Button+ className="my-1 h-8 rounded-lg px-3 py-2"+ type="submit"+ disabled={form.formState.isSubmitting}+ >+ Post+ </Button>+ </div>+ <div className="flex flex-1 flex-col overflow-auto">+ <FormField+ control={form.control}+ name="content"+ render={({ field }) => (+ <FormItem className="flex flex-1 flex-col">+ <RichMarkdownEditor+ allowImageUpload+ value={field.value}+ onChange={field.onChange}+ useUploadThing={useUploadThing}+ />+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ </form>+ </Form>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-skeleton.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-skeleton.tsxnew file mode 100644index 00000000..0fbea07a--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/solution-skeleton.tsx@@ -0,0 +1,26 @@+import { Skeleton } from '@repo/ui/components/skeleton';++export function SolutionsSkeleton() {+ return (+ <div className="flex flex-col space-y-10 px-4 py-3">+ {/* SOLUTION BUTTON */}+ <div className="flex justify-end">+ <Skeleton className="h-9 w-1/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ {/* DIVIDER */}+ <div className="flex flex-col">+ <Skeleton className="w-6/6 h-1 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ {/* SOLUTIONS */}+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <Skeleton className="h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="w-6/6 h-10 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/submit-solution.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/submit-solution.tsxnew file mode 100644index 00000000..d05ff5f8--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/submit-solution.tsx@@ -0,0 +1,19 @@+import { Button } from '@repo/ui/components/button';+import { Plus } from '@repo/ui/icons';++interface Props {+ disabled: boolean;+ setView: (view: 'editor' | 'list') => void;+}++export function SubmitSolution({ disabled, setView }: Props) {+ return (+ <Button+ className="h-8 rounded-lg px-3 py-2"+ disabled={disabled}+ onClick={() => setView('editor')}+ >+ <Plus className="mr-2 h-4 w-4" /> Solution+ </Button>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/useGetQueryString.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/_components/useGetQueryString.tsxnew file mode 100644index 00000000..cfb53884--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/useGetQueryString.tsx@@ -0,0 +1,7 @@+import { useSearchParams } from 'next/navigation';++export const useGetQueryString = () => {+ const searchParams = useSearchParams();+ const params = new URLSearchParams(searchParams);+ return params.toString();+};diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/_components/useQueryParamState.ts b/apps/aot/src/app/events/[year]/[day]/solutions/_components/useQueryParamState.tsnew file mode 100644index 00000000..c25181c0--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/_components/useQueryParamState.ts@@ -0,0 +1,25 @@+'use client';++import { useSearchParams, useRouter, usePathname } from 'next/navigation';++export const useQueryParamState = <T extends number | string>(key: string, defaultValue: T) => {+ const router = useRouter();+ const searchParams = useSearchParams();+ const pathname = usePathname();+ const getValue = (): T => {+ const value = searchParams.get(key);+ if (!value) {+ return defaultValue;+ }+ return (typeof defaultValue === 'number' ? Number(value) : value) as T;+ };+ const value = getValue();++ const setQueryParam = (value: T) => {+ const params = new URLSearchParams(searchParams);+ params.set(key, value.toString());+ router.push(`${pathname}?${params.toString()}`);+ };++ return [value, setQueryParam] as const;+};diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/getSolutionRouteData.ts b/apps/aot/src/app/events/[year]/[day]/solutions/getSolutionRouteData.tsnew file mode 100644index 00000000..f187825e--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/getSolutionRouteData.ts@@ -0,0 +1,78 @@+'use server';+import { prisma } from '@repo/db';+import { auth } from '~/server/auth';+import type { SortKey, SortOrder } from '~/utils/sorting';+import { orderBy } from '~/utils/sorting';++const PAGESIZE = 10;++export type PaginatedSolution = NonNullable<Awaited<ReturnType<typeof getPaginatedSolutions>>>;+export async function getPaginatedSolutions({+ slug,+ page,+ sortKey = 'createdAt',+ sortOrder = 'desc',+}: {+ slug: string;+ page: number;+ sortKey?: SortKey;+ sortOrder?: SortOrder;+}) {+ const session = await auth();+ const data = await prisma.challenge.findFirst({+ where: { slug },+ select: {+ _count: {+ select: {+ sharedSolution: true,+ },+ },+ id: true,+ submission: {+ where: {+ userId: session?.user?.id || '',+ isSuccessful: true,+ },+ orderBy: [+ {+ createdAt: 'desc',+ },+ ],+ take: 1,+ },+ sharedSolution: {+ skip: (page - 1) * PAGESIZE,+ take: PAGESIZE,+ orderBy: [+ {+ isPinned: 'desc' as SortOrder,+ },+ orderBy(sortKey, sortOrder),+ ],+ include: {+ user: {+ select: {+ name: true,+ roles: true,+ image: true,+ bio: true,+ },+ },+ _count: {+ select: { vote: true, solutionComment: true },+ },+ },+ },+ },+ });++ const totalSolutions = data?._count?.sharedSolution || 0;++ const totalPages = Math.ceil(totalSolutions / PAGESIZE);++ return {+ ...data,+ totalPages,+ hasMore: page < totalPages,+ };+}diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/loading.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/loading.tsxnew file mode 100644index 00000000..4e32872a--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/loading.tsx@@ -0,0 +1 @@+export { SolutionsSkeleton as default } from './_components/solution-skeleton';diff --git a/apps/aot/src/app/events/[year]/[day]/solutions/page.tsx b/apps/aot/src/app/events/[year]/[day]/solutions/page.tsxnew file mode 100644index 00000000..168ef71b--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/solutions/page.tsx@@ -0,0 +1,24 @@+import { buildMetaForDefault } from '~/utils/metadata';+import { getChallengeRouteData } from '../getChallengeRouteData';+import { Solutions } from './_components';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ params: {+ year: string;+ day: string;+ };+}++export async function generateMetadata({ params: { year, day } }: Props) {+ const { challenge } = await getChallengeRouteData(getAotSlug({ year, day }), null);+ return buildMetaForDefault({+ title: `Solutions to ${challenge.name} | TypeHero`,+ description: challenge.shortDescription,+ });+}++export default async function SolutionPage({ params: { year, day } }: Props) {+ const slug = getAotSlug({ year, day });+ return <Solutions slug={slug} />;+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/index.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/index.tsxnew file mode 100644index 00000000..f9a631a3--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/index.tsx@@ -0,0 +1,98 @@+'use client';++import type { Submission } from '@repo/db/types';+import { Calendar } from '@repo/ui/icons';+import clsx from 'clsx';+import Link from 'next/link';+import { useMemo, useState } from 'react';+import NoSubmissions from './nosubmissions';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import type { ChallengeSubmissions } from '../page';+import { useParams } from 'next/navigation';++interface Props {+ submissions: ChallengeSubmissions;+}++type Status = 'accepted' | 'all' | 'rejected';+export function Submissions({ submissions }: Props) {+ const [selectedStatus, setSelectStatus] = useState<Status>('all');++ const filteredSubmissions = useMemo(() => {+ const predicate = (submission: Submission) => {+ if (selectedStatus === 'all') return true;+ if (selectedStatus === 'accepted') return submission.isSuccessful;+ return !submission.isSuccessful;+ };+ return submissions.filter(predicate);+ }, [selectedStatus, submissions]);+ return (+ <div className="relative h-full">+ {submissions.length !== 0 ? (+ <div className="bg-background/70 dark:bg-muted/70 absolute right-0 top-0 flex w-full gap-2 border-b border-zinc-300 p-2 px-4 backdrop-blur-sm dark:border-zinc-700">+ <div+ className={`flex cursor-pointer gap-2 rounded-lg px-4 py-1 duration-300 ${+ selectedStatus === 'all'+ ? 'text-background bg-blue-600 dark:bg-blue-400'+ : 'bg-blue-600/10 text-blue-600 hover:bg-blue-600/30 dark:bg-blue-400/10 dark:text-blue-400 dark:hover:bg-blue-400/30'+ }+ `}+ onClick={() => setSelectStatus('all')}+ >+ All+ </div>+ <div+ className={`flex cursor-pointer gap-2 rounded-lg px-4 py-1 duration-300 ${+ selectedStatus === 'accepted'+ ? 'text-background bg-emerald-600 dark:bg-emerald-400'+ : 'bg-emerald-600/10 text-emerald-600 hover:bg-emerald-600/30 dark:bg-emerald-400/10 dark:text-emerald-400 dark:hover:bg-emerald-400/30'+ }`}+ onClick={() => setSelectStatus('accepted')}+ >+ Accepted+ </div>+ <div+ className={`flex cursor-pointer gap-2 rounded-lg px-4 py-1 duration-300 ${+ selectedStatus === 'rejected'+ ? 'text-background bg-rose-600 dark:bg-rose-400'+ : 'bg-rose-600/10 text-rose-600 hover:bg-rose-600/30 dark:bg-rose-400/10 dark:text-rose-400 dark:hover:bg-rose-400/30'+ }`}+ onClick={() => setSelectStatus('rejected')}+ >+ Rejected+ </div>+ </div>+ ) : (+ <NoSubmissions />+ )}++ <ul className="custom-scrollable-element flex h-full flex-col overflow-y-auto pt-12">+ {filteredSubmissions.map((submission) => {+ return <SubmissionRow key={submission.id} submission={submission} />;+ })}+ </ul>+ </div>+ );+}++function SubmissionRow({ submission }: { submission: Submission }) {+ const { year, day } = useParams();+ return (+ <li className="flex cursor-pointer items-center justify-between px-4 py-2 duration-300 hover:bg-neutral-100 dark:rounded-none dark:hover:bg-zinc-700/50">+ <Link className="w-full" href={`/events/${year}/${day}/submissions/${submission.id}`}>+ <div+ className={clsx({+ 'text-emerald-600 dark:text-emerald-400': submission.isSuccessful,+ 'text-rose-600 dark:text-rose-400': !submission.isSuccessful,+ })}+ >+ {submission.isSuccessful ? 'Accepted' : 'Rejected'}+ </div>+ <div className="text-muted-foreground flex items-center gap-2">+ <Calendar className=" h-4 w-4" />+ <span className="text-xs">{getRelativeTimeStrict(submission.createdAt)}</span>+ </div>+ </Link>+ </li>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/nosubmissions.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/nosubmissions.tsxnew file mode 100644index 00000000..e12c19a7--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/nosubmissions.tsx@@ -0,0 +1,53 @@+function NoSubmissions() {+ return (+ <div className="flex h-full items-center justify-center">+ <p className="flex flex-col items-center gap-2 text-center text-neutral-500 dark:text-zinc-400">+ <svg+ className="mr-6 h-28 w-28"+ data-name="Layer 1"+ viewBox="0 0 647.63626 632.17383"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M687.3279,276.08691H512.81813a15.01828,15.01828,0,0,0-15,15v387.85l-2,.61005-42.81006,13.11a8.00676,8.00676,0,0,1-9.98974-5.31L315.678,271.39691a8.00313,8.00313,0,0,1,5.31006-9.99l65.97022-20.2,191.25-58.54,65.96972-20.2a7.98927,7.98927,0,0,1,9.99024,5.3l32.5498,106.32Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M725.408,274.08691l-39.23-128.14a16.99368,16.99368,0,0,0-21.23-11.28l-92.75,28.39L380.95827,221.60693l-92.75,28.4a17.0152,17.0152,0,0,0-11.28028,21.23l134.08008,437.93a17.02661,17.02661,0,0,0,16.26026,12.03,16.78926,16.78926,0,0,0,4.96972-.75l63.58008-19.46,2-.62v-2.09l-2,.61-64.16992,19.65a15.01489,15.01489,0,0,1-18.73-9.95l-134.06983-437.94a14.97935,14.97935,0,0,1,9.94971-18.73l92.75-28.4,191.24024-58.54,92.75-28.4a15.15551,15.15551,0,0,1,4.40966-.66,15.01461,15.01461,0,0,1,14.32032,10.61l39.0498,127.56.62012,2h2.08008Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M398.86279,261.73389a9.0157,9.0157,0,0,1-8.61133-6.3667l-12.88037-42.07178a8.99884,8.99884,0,0,1,5.9712-11.24023l175.939-53.86377a9.00867,9.00867,0,0,1,11.24072,5.9707l12.88037,42.07227a9.01029,9.01029,0,0,1-5.9707,11.24072L401.49219,261.33887A8.976,8.976,0,0,1,398.86279,261.73389Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="190.15351" cy="24.95465" fill="#888a" r="20" />+ <circle cx="190.15351" cy="24.95465" fill="#444a" r="12.66462" />+ <path+ d="M878.81836,716.08691h-338a8.50981,8.50981,0,0,1-8.5-8.5v-405a8.50951,8.50951,0,0,1,8.5-8.5h338a8.50982,8.50982,0,0,1,8.5,8.5v405A8.51013,8.51013,0,0,1,878.81836,716.08691Z"+ fill="#4444"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M723.31813,274.08691h-210.5a17.02411,17.02411,0,0,0-17,17v407.8l2-.61v-407.19a15.01828,15.01828,0,0,1,15-15H723.93825Zm183.5,0h-394a17.02411,17.02411,0,0,0-17,17v458a17.0241,17.0241,0,0,0,17,17h394a17.0241,17.0241,0,0,0,17-17v-458A17.02411,17.02411,0,0,0,906.81813,274.08691Zm15,475a15.01828,15.01828,0,0,1-15,15h-394a15.01828,15.01828,0,0,1-15-15v-458a15.01828,15.01828,0,0,1,15-15h394a15.01828,15.01828,0,0,1,15,15Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <path+ d="M801.81836,318.08691h-184a9.01015,9.01015,0,0,1-9-9v-44a9.01016,9.01016,0,0,1,9-9h184a9.01016,9.01016,0,0,1,9,9v44A9.01015,9.01015,0,0,1,801.81836,318.08691Z"+ fill="#888a"+ transform="translate(-276.18187 -133.91309)"+ />+ <circle cx="433.63626" cy="105.17383" fill="#888a" r="20" />+ <circle cx="433.63626" cy="105.17383" fill="#444a" r="12.18187" />+ </svg>+ No submissions yet,+ <br /> submit the challenge!+ </p>+ </div>+ );+}++export default NoSubmissions;diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/overview.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/overview.tsxnew file mode 100644index 00000000..7fa67530--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/overview.tsx@@ -0,0 +1,126 @@+import { Button } from '@repo/ui/components/button';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@repo/ui/components/dialog';+import { Markdown } from '@repo/ui/components/markdown';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';+import { CheckCircle2, Share, Twitter, X, XCircle } from '@repo/ui/icons';+import { useQuery } from '@tanstack/react-query';+import Link from 'next/link';+import { useParams, useSearchParams } from 'next/navigation';+import { ShareUrl } from '~/components/share-url';+import { getRelativeTimeStrict } from '~/utils/relativeTime';+import { getChallengeSubmissionById } from '../getChallengeSubmissions';++interface Props {+ submissionId: string;+}+const codifyForMarkdown = (code: string) => {+ return `\`\`\`ts+${code}`;+};++export function SubmissionOverview({ submissionId }: Props) {+ const { year, day } = useParams();+ const searchParams = useSearchParams();++ const showSuggestions = searchParams.get('success') === 'true';+ const { data: submission } = useQuery({+ queryKey: [`submission`, submissionId],+ queryFn: () => getChallengeSubmissionById(submissionId),+ });++ const code = codifyForMarkdown(submission?.code.trimStart() ?? '');++ const track = searchParams.get('slug');++ const tweet = `https://twitter.com/intent/tweet?text=${encodeURIComponent(+ `I've completed ${submission?.challenge.name} - Advent of TypeScript ${year}`,+ )}&url=https://adventofts.com/events/${year}/${day}&hashtags=AdventOfTypescript`;++ if (!submission) return null;++ return (+ <>+ <div className="sticky top-0 flex h-[40px] items-center justify-between border-b border-zinc-300 px-3 py-2 dark:border-zinc-700 dark:bg-[#1e1e1e]">+ <Link href={`/events/${year}/${day}/submissions`}>+ <X className="stroke-gray-500 hover:stroke-gray-400" size={20} />+ </Link>+ </div>+ <div className="custom-scrollable-element h-fit overflow-y-scroll p-2">+ <div className="mb-2 flex items-center justify-between">+ <div>+ <div+ className={`flex items-center gap-1 px-3 py-1 text-xl ${+ submission.isSuccessful+ ? ' text-emerald-600 dark:text-emerald-400 '+ : ' text-rose-600 dark:text-rose-400 '+ }`}+ >+ {submission.isSuccessful ? (+ <CheckCircle2 size={22} className="mb-0.5" />+ ) : (+ <XCircle size={22} className="mb-0.5" />+ )}+ {submission.isSuccessful ? 'Accepted' : 'Rejected'}+ </div>+ <div className="px-3 text-sm text-neutral-500">+ Submitted {getRelativeTimeStrict(submission.createdAt)}+ </div>+ </div>+ </div>+ <div className="mb-3 px-3">+ <Markdown>{code}</Markdown>+ </div>+ <div className="mb-3 flex gap-2 px-3">+ <Dialog>+ <DialogTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ className="flex items-center gap-2 rounded-xl border-2 px-4 py-2 dark:text-white"+ variant="outline"+ >+ <Share className="h-4 w-4" />+ Share Code on Playground+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Share Challenge with Code</p>+ </TooltipContent>+ </Tooltip>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Share</DialogTitle>+ </DialogHeader>+ <div className="pt-4">+ <ShareUrl+ code={submission.code}+ description="Click Copy to Share code on Playground."+ />+ </div>+ </DialogContent>+ </Dialog>+ <Button+ asChild+ className="flex items-center gap-2 rounded-xl border-2 px-4 py-2 dark:text-white"+ variant="outline"+ >+ <a target="_blank" rel="noreferrer" className="gap-1 md:inline-flex" href={tweet}>+ <Twitter className="h-4 w-4" />+ Share on Twitter+ </a>+ </Button>+ <Button asChild variant="outline" className="fancy-border-gradient relative border-none">+ <Link href={`/events/${year}`}>Back to Advent of TypeScript</Link>+ </Button>+ </div>+ </div>+ </>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsxnew file mode 100644index 00000000..9eac730c--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/submissions-skeleton.tsx@@ -0,0 +1,29 @@+import { Skeleton } from '@repo/ui/components/skeleton';++export function SubmissionsSkeleton() {+ return (+ <div className="mb-0 flex flex-col space-y-10 px-4 pt-3">+ {/* ALL / ACCEPTED / REJECTED */}+ <div className="align-center prose-invert prose-h3:text-xl flex">+ <Skeleton className="mr-2 h-8 w-1/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="mr-2 h-8 w-1/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="mr-2 h-8 w-1/6 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ {/* DIVIDER */}+ <div className="flex flex-col">+ <Skeleton className=" h-1 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ {/* SUBMISSIONS */}+ <div className="prose-invert prose-h3:text-xl flex flex-col space-y-2">+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ <Skeleton className="h-12 rounded-lg bg-zinc-300 dark:bg-zinc-700" />+ </div>+ </div>+ );+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/suggestions.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/suggestions.tsxnew file mode 100644index 00000000..20b456a4--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/_components/suggestions.tsx@@ -0,0 +1,93 @@+'use client';++interface SuggestionsProps {+ track: string | null;+ challengeId: number;+}++export function Suggestions({ track, challengeId }: SuggestionsProps) {+ // // Get suggested challenges+ // const { data: similarChallenges } = useQuery({+ // queryKey: ['similar-challenges', challengeId],+ // queryFn: () => {+ // return getSimilarChallenges(challengeId);+ // },+ // });+ //+ // const currentIndex = useMemo(() => {+ // if (trackDetails === null || trackDetails === undefined) return null;+ //+ // const index = trackDetails.trackChallenges.findIndex((x) => x.challengeId === challengeId);+ // return index === -1 ? null : index;+ // }, [trackDetails, challengeId]);+ //+ // // Get next challenge in Track+ // const next = useMemo(() => {+ // if (currentIndex === null) return null;+ //+ // const index = currentIndex + 1;+ // return index < trackDetails!.trackChallenges.length+ // ? trackDetails!.trackChallenges[index]+ // : null;+ // }, [currentIndex, trackDetails]);+ //+ // return (+ // <div className="w-full max-w-[1000px] md:py-4 md:pb-8">+ // {trackDetails && next ? (+ // <>+ // <div className="flex items-center justify-between p-3">+ // <h3 className="text-foreground/70 flex items-center gap-2 text-lg font-semibold md:text-xl">+ // <Swords size={26} />+ // {`Next Up in ${trackDetails?.name}`}+ // </h3>+ // <Link href={`/tracks/${track}`}>+ // <Button size="sm" className="gap-1 rounded-full" variant="outline">+ // More <ChevronRight size={13} />+ // </Button>+ // </Link>+ // </div>+ // <div className="px-3">+ // <Link href={`/challenge/${next.challenge.slug}`}>+ // <TrackChallenge+ // challenge={next.challenge}+ // isInProgress={false}+ // hideSubmissionStatus+ // isCompleted={false}+ // />+ // </Link>+ // </div>+ // </>+ // ) : null}+ //+ // {similarChallenges ? (+ // <>+ // <div className="flex items-center justify-between p-3">+ // <h3 className="text-foreground/70 text-lg font-semibold md:text-xl">More Challenges</h3>+ // <Link href="/explore">+ // <Button size="sm" className="gap-1 rounded-full" variant="outline">+ // Explore <ChevronRight size={13} />+ // </Button>+ // </Link>+ // </div>+ // <div className="px-3">+ // {similarChallenges?.map((challenge, idx) => {+ // return (+ // <Link href={`/challenge/${challenge.slug}`} key={idx}>+ // <TrackChallenge+ // challenge={{ ...challenge, submission: [] }}+ // hideSubmissionStatus+ // isCompleted={false}+ // isInProgress={false}+ // />+ // </Link>+ // );+ // })}+ // </div>+ // </>+ // ) : null}+ // </div>+ // );+ //+ //+ return <div>TODO: Suggestions</div>;+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/cache-keys.ts b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/cache-keys.tsnew file mode 100644index 00000000..21e7248c--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/cache-keys.ts@@ -0,0 +1,11 @@+export const createChallengeSubmissionCacheKey = (slug: string) => {+ return `${slug}-challenge-submissions`;+};++export const createCompletedSubmissionCacheKey = (userId: string) => {+ return `${userId}-completed-challenges`;+};++export const createInProgressSubmissionCacheKey = (userId: string) => {+ return `${userId}-in-progress-challenges`;+};diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/getChallengeSubmissions.ts b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/getChallengeSubmissions.tsnew file mode 100644index 00000000..a3add10f--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/getChallengeSubmissions.ts@@ -0,0 +1,19 @@+'use server';++import { cache } from 'react';+import { prisma } from '@repo/db';++export const getChallengeSubmissionById = cache((id: string) => {+ return prisma.submission.findFirst({+ where: {+ id: Number(id),+ },+ include: {+ challenge: {+ select: {+ name: true,+ },+ },+ },+ });+});diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/page.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/page.tsxnew file mode 100644index 00000000..d8921796--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/page.tsx@@ -0,0 +1,55 @@+import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import { notFound } from 'next/navigation';+import { cache } from 'react';+import { Submissions } from './_components';+import { createChallengeSubmissionCacheKey } from './cache-keys';+import { withUnstableCache } from '~/utils/withUnstableCache';+import { getAotSlug } from '~/utils/getAotSlug';++interface Props {+ params: {+ year: string;+ day: string;+ };+}++export const metadata = {+ title: 'Submissions | TypeHero',+ description: 'View your submissions to this challenge on TypeHero.',+};++export default async function SubmissionPage({ params: { year, day } }: Props) {+ const session = await auth();++ const slug = getAotSlug({ year, day });++ const submissions = await withUnstableCache({+ fn: getChallengeSubmissions,+ args: [session?.user?.id ?? '', slug],+ keys: ['all-challenge-submissions'],+ tags: [createChallengeSubmissionCacheKey(slug)],+ });++ if (!submissions) {+ return notFound();+ }++ return <Submissions submissions={submissions} />;+}++export type ChallengeSubmissions = NonNullable<Awaited<ReturnType<typeof getChallengeSubmissions>>>;+const getChallengeSubmissions = cache(async (userId: string, slug: string) => {+ const challenge = await prisma.challenge.findFirstOrThrow({+ where: { slug },+ select: { id: true },+ });+ return prisma.submission.findMany({+ where: { challengeId: challenge.id, userId },+ orderBy: [+ {+ createdAt: 'desc',+ },+ ],+ });+});diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/save-submission.action.ts b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/save-submission.action.tsnew file mode 100644index 00000000..e3c1d948--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/[[...catchAll]]/save-submission.action.ts@@ -0,0 +1,39 @@+'use server';+import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import { revalidateTag } from 'next/cache';+import type { ChallengeRouteData } from '../../getChallengeRouteData';+import {+ createChallengeSubmissionCacheKey,+ createCompletedSubmissionCacheKey,+ createInProgressSubmissionCacheKey,+} from './cache-keys';+import { createCacheKeyForSolutions } from '../../solutions/_components/_actions';++interface Args {+ challenge: ChallengeRouteData['challenge'];+ code: string;+ isSuccessful: boolean;+}+export async function saveSubmission({ challenge, code, isSuccessful }: Args) {+ const session = await auth();+ if (!session?.user) {+ throw new Error('Not Authorized');+ }+ const userId = session.user.id;++ const submission = await prisma.submission.create({+ data: {+ challengeId: challenge.id,+ userId,+ code,+ isSuccessful,+ },+ });+ // @TODO: we should be able to just invalidate by the challenge slug+ revalidateTag(createChallengeSubmissionCacheKey(challenge.slug));+ revalidateTag(createCacheKeyForSolutions(challenge.slug));+ revalidateTag(createInProgressSubmissionCacheKey(userId));+ revalidateTag(createCompletedSubmissionCacheKey(userId));+ return submission;+}diff --git a/apps/aot/src/app/events/[year]/[day]/submissions/loading.tsx b/apps/aot/src/app/events/[year]/[day]/submissions/loading.tsxnew file mode 100644index 00000000..858a68fb--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/submissions/loading.tsx@@ -0,0 +1 @@+export { SubmissionsSkeleton as default } from './[[...catchAll]]/_components/submissions-skeleton';diff --git a/apps/aot/src/app/events/[year]/[day]/use-track-visibility.hook.tsx b/apps/aot/src/app/events/[year]/[day]/use-track-visibility.hook.tsxnew file mode 100644index 00000000..22c0d998--- /dev/null+++ b/apps/aot/src/app/events/[year]/[day]/use-track-visibility.hook.tsx@@ -0,0 +1,27 @@+'use client';+import { createContext, useState, useContext, type PropsWithChildren } from 'react';++interface TrackVisibilityContextType {+ isTrackTitleVisible: boolean;+ setIsTrackTitleVisible: React.Dispatch<React.SetStateAction<boolean>>;+}++export const TrackVisibilityContext = createContext({} as TrackVisibilityContextType);++export const TrackVisibiltyProvider = ({ children }: PropsWithChildren) => {+ const [isTrackTitleVisible, setIsTrackTitleVisible] = useState<boolean>(false);++ return (+ <TrackVisibilityContext.Provider value={{ isTrackTitleVisible, setIsTrackTitleVisible }}>+ {children}+ </TrackVisibilityContext.Provider>+ );+};++export const useTrackNavigationVisiblity = () => {+ const context = useContext(TrackVisibilityContext);+ if (context === undefined) {+ throw new Error('use useTrackVisiblity hook within TrackVisibiltyProvider');+ }+ return context;+};diff --git a/apps/aot/src/app/events/[year]/layout.tsx b/apps/aot/src/app/events/[year]/layout.tsxdeleted file mode 100644index 35b42a86..00000000--- a/apps/aot/src/app/events/[year]/layout.tsx+++ /dev/null@@ -1,12 +0,0 @@-export default function EventsByYearLayout({- children, // will be a page or nested layout-}: {- children: React.ReactNode;-}) {- return (- <section>- Layout for events/year- {children}- </section>- );-}diff --git a/apps/aot/src/app/globals.css b/apps/aot/src/app/globals.cssindex 7a067936..acaeb49b 100644--- a/apps/aot/src/app/globals.css+++ b/apps/aot/src/app/globals.css@@ -2,10 +2,505 @@@tailwind components;@tailwind utilities;-/* TODO: upgrade tailwind to latest & remove this */-@layer utilities {- .text-balance {- text-wrap: balance;+@layer base {+ :root {+ --gradient-angle: 360deg;++ --background: 0 0% 100%;+ --foreground: 240 10% 3.9%;++ --muted: 240 4.8% 95.9%;+ --muted-foreground: 240 3.8% 45%;++ --popover: 0 0% 100%;+ --popover-foreground: 240 10% 3.9%;++ --card: 0 0% 100%;+ --card-hovered: 0 0% 98%;+ --card-foreground: 240 10% 3.9%;++ --border: 240 5.9% 90%;+ --input: 240 5.9% 90%;++ --primary: 211 61% 48%;+ --primary-foreground: 0 0% 98%;++ --secondary: 240 4.8% 95.9%;+ --secondary-foreground: 240 5.9% 10%;++ --accent: 240 4.8% 95.9%;+ --accent-foreground: ;++ --destructive: 0 84.2% 60.2%;+ --destructive-foreground: 0 0% 98%;++ --error-label: 0 84.2% 60.2%;++ --ring: 240 5% 64.9%;++ --radius: 0.5rem;++ --difficulty-beginner: 201 96% 32%;+ --difficulty-easy: 150 100% 25%;+ --difficulty-medium: 35 92% 33%;+ --difficulty-hard: 0 72% 51%;+ --difficulty-extreme: 262 83% 58%;++ --difficulty-beginner-dark: 199 69% 72%;+ --difficulty-easy-dark: 142 77% 73%;+ --difficulty-medium-dark: 31 86% 60%;+ --difficulty-hard-dark: 0 91% 71%;+ --difficulty-extreme-dark: 269 97% 85%;+ }++ .dark {+ --background: 240 10% 3.9%;+ --foreground: 0 0% 98%;++ --muted: 240 3.7% 15.9%;+ --muted-foreground: 240 5% 64.9%;++ --popover: 240 10% 3.9%;+ --popover-foreground: 0 0% 98%;++ --card: 240 10% 3.9%;+ --card-hovered: 240 10% 6.9%;+ --card-foreground: 0 0% 98%;++ --border: 240 3.7% 15.9%;+ --input: 240 3.7% 15.9%;++ --primary: 211 61% 48%;+ --primary-foreground: 0 0% 98%;++ --secondary: 240 3.7% 15.9%;+ --secondary-foreground: 0 0% 98%;++ --accent: 240 3.7% 15.9%;+ --accent-foreground: ;++ --destructive: 0 62.8% 30.6%;+ --destructive-foreground: 0 85.7% 97.3%;++ --error-label: 0 92.2% 64.9%;++ --ring: 240 3.7% 15.9%;+ }+}++@layer base {+ * {+ @apply border-border;+ }+ body {+ @apply bg-background text-foreground;+ }+}++html,+body,+#__next,+main {+ scroll-padding-top: 64px;+ scroll-behavior: smooth;+ height: 100%;+}++.from-background {+ --tw-gradient-from: hsl(var(--background)) var(--tw-gradient-from-position);+}++.w-md-editor-content {+ @apply bg-background dark:bg-muted;+}++.w-md-editor-toolbar {+ @apply flex w-full gap-2;+ /* border-b border-b-zinc-300 */+ border-bottom: 1px solid rgb(212 212 216) !important;+ /* bg-background (in light mode) */+ background: #fff !important;+}++/* dark:border-b-zinc-300 dark:bg-muted */+.dark .w-md-editor-toolbar {+ border-bottom: 1px solid rgb(63 63 70) !important;+ background: hsl(240 3.7% 15.9%) !important;+}++.w-md-editor-toolbar-divider {+ @apply bg-zinc-300 dark:bg-zinc-700;+ /* TODO: not aligned center vertically */+ height: 1.5rem !important;+}+.w-md-editor-toolbar ul {+ @apply flex items-center;+}+.w-md-editor-toolbar ul li.active button {+ @apply text-black dark:text-white;+}+.w-md-editor-toolbar ul li button {+ @apply flex h-8 w-auto min-w-[2rem] items-center justify-center rounded-md p-1 text-neutral-500 hover:bg-neutral-200 hover:text-black dark:hover:bg-zinc-700 dark:hover:text-white;+}+.w-md-editor-toolbar ul li button[disabled] {+ @apply cursor-default text-neutral-700 hover:bg-transparent hover:text-neutral-700;+}+.w-md-editor-toolbar ul li button svg {+ @apply h-4 w-4;+}+.w-md-editor {+ background: var(--muted) !important;+}++.w-md-editor-preview {+ padding: 1rem !important;+ box-shadow: inset 1px 0 0 0 rgb(212 212 216) !important;+}+.dark .w-md-editor-preview {+ box-shadow: inset 1px 0 0 0 rgb(63 63 70) !important;+}++.w-md-editor-preview .wmde-markdown {+ @apply bg-muted;+}+.wmde-markdown ol {+ list-style: null !important;+}++.wmde-markdown ul {+ list-style: unset !important;+}+.custom-scrollable-element::-webkit-scrollbar {+ width: 0.6rem;+}+.custom-scrollable-element::-webkit-scrollbar-track {+ background-color: transparent;+}+.custom-scrollable-element::-webkit-scrollbar-thumb {+ @apply rounded-l-xl bg-neutral-300/50 dark:bg-zinc-700/50;+}++.custom-scrollable-element::-webkit-scrollbar-thumb:hover {+ @apply bg-neutral-300 dark:bg-zinc-600;+}++#container {+ mask: linear-gradient(90deg, #0000, #000 10% 80%, #0000);+ -webkit-mask: linear-gradient(90deg, #0000, #000 10% 80%, #0000);+}++@media (min-width: 1400px) {+ #container {+ /* here we calculate the diffrence between screen width and the container width (1400px)+ then split that on half to make carousel align left with the rest of the content and i added some rems to aligned perfectly */+ padding-left: calc(((100vw - 1400px) + 12rem) / 2);+ }+}++@media (max-width: 768px) {+ .animated-feature-cards::before {+ background: none !important;+ }+}++@keyframes movingbackground {+ 0% {+ transform: translate(0, 0);+ }+ 100% {+ transform: translate(0, -50%);+ }+}++@media (prefers-reduced-motion: reduce) {+ .moving-grid-background {+ animation: none !important;+ }+}++.container {+ @apply mx-auto max-w-[1400px] px-4 md:px-24;+}++@property --gradient-angle {+ syntax: '<angle>'; /* <- defined as type angle for the transition to work */+ initial-value: 360deg;+ inherits: false;+}++.hero-join-button {+ background: linear-gradient(+ var(--gradient-angle),+ hsla(211, 60%, 48%, 0.7),+ hsla(211, 60%, 48%, 0.3),+ #3178c6,+ hsla(211, 60%, 48%, 0.5)+ );+ animation: gradient-rotate 5s linear infinite reverse;+}++.hero-join-button-dark {+ background: linear-gradient(+ var(--gradient-angle),+ hsla(0, 0%, 100%, 0.5),+ hsla(0, 0%, 100%, 0.1),+ #fff,+ hsla(0, 0%, 100%, 0.3)+ ) !important;+ animation: gradient-rotate 5s linear infinite reverse;+}++.wl-form-button {+ background: linear-gradient(var(--gradient-angle), #34d399, #60a5fa, #ff88ff, #ff8844);+ animation: gradient-rotate 5s linear infinite reverse;+}++.animate-beam {+ opacity: 0;+ transform: translate(-72%, -62%) scale(0.5);+ animation: beam 2s 0.75s ease 1 forwards;+}++@keyframes beam {+ to {+ opacity: 1;+ transform: translate(-50%, -40%) scale(1);+ }+}++.animate-newstar {+ opacity: 0;+ animation: newstar 1.5s 0.95s ease 1 forwards;+}+.animate-oldstar {+ opacity: 1;+ animation: oldstar 1.5s 0.95s ease 1 forwards;+}++@keyframes newstar {+ to {+ opacity: 1;+ }+}+@keyframes oldstar {+ to {+ opacity: 0;+ }+}++.animate-bg-gradient-to-center {+ animation: bg-to-center 1s 0.75s ease 1 forwards;+}+.animate-bg-gradient-to-center-title {+ animation: bg-to-center 1s 0.95s ease 1 forwards;+}++@keyframes bg-to-center {+ to {+ background-position: center;+ }+}++.animate-logo-light {+ filter: brightness(90%);+ animation: logo-light 1.25s 0.85s ease 1 forwards;+}+@keyframes logo-light {+ to {+ filter: brightness(110%);+ }+}++.animate-3d-logo {+ opacity: 0.1;+ animation: logo-3d 1.25s 0.85s ease 1 forwards;+}+@keyframes logo-3d {+ to {+ opacity: 1;+ }+}++@keyframes gradient-rotate {+ 0% {+ --gradient-angle: 360deg;+ }++ 100% {+ --gradient-angle: 0deg;+ }+}++.hide-scrollbar::-webkit-scrollbar {+ display: none; /* Chrome Safari */+ scrollbar-width: none; /* Firefox */+}++* {+ @apply focus:ring-blue-600 group-focus:ring-blue-600;+}++a {+ @apply focus:outline-none focus-visible:ring-2;+}++.infinite-scroll-x-container {+ overflow: hidden;+ mask: linear-gradient(to right, transparent, white 20%, white 80%, transparent);+ -webkit-mask: linear-gradient(to right, transparent, white 20%, white 80%, transparent);+}+.infinite-scroll-x {+ animation: infinite-scroll-x 120s linear infinite;+}++.infinite-scroll-x-reverse {+ animation: infinite-scroll-x 120s linear infinite reverse;+}++.infinite-scroll-x:hover,+.infinite-scroll-x-reverse:hover {+ animation-play-state: paused;+}++@keyframes infinite-scroll-x {+ to {+ transform: translateX(-50%);+ }+}++.fancy-border-gradient::before {+ inset: 0;+ content: '';+ --angle: 0deg;+ position: absolute;+ border-radius: inherit;+ padding: 1.5px; /* control the border thickness */+ background: conic-gradient(+ from var(--angle),+ #3178c622,+ #3178c644 35%,+ #3178c688 39%,+ #3178c6,+ #3178c688 61%,+ #3178c644 65%,+ #3178c622+ );+ -webkit-mask-composite: xor;+ -webkit-mask:+ linear-gradient(#fff 0 0) content-box,+ linear-gradient(#fff 0 0);+ animation: 3s rotate linear infinite;+ mask-composite: exclude;+ pointer-events: none;+}++@keyframes rotate {+ to {+ --angle: 360deg;+ }+}++@property --angle {+ syntax: '<angle>';+ initial-value: 0deg;+ inherits: false;+}++.animate-amogup {+ opacity: 0;+ transform: translateY(50%);+ animation: amogup 1s 0.25s ease 1 forwards;+}++@keyframes amogup {+ to {+ opacity: 0.5;+ transform: translateY(0%);+ }+}++.ReactQueryDevtools > button {+ margin-bottom: 5rem !important;+}++/* overrides silly annoying shadcn default */+/* it doesn't transition shadows by default */+.shadcnoverridetransition {+ transition: all 0.3s ease !important;+}+.shadcnoverridetransition:active {+ transition: all 0.075s ease !important;+}++.hamburger .line {+ width: 20px;+ height: 2px;+ background-color: hsl(var(--foreground));+ display: block;+ -webkit-transition: all 0.3s ease-in-out;+ -o-transition: all 0.3s ease-in-out;+ transition: all 0.3s ease-in-out;+}++.hamburger {+ padding: 5px;+}++.hamburger:hover {+ cursor: pointer;+}++.hamburger .line:nth-child(1) {+ height: 2px;+}++.hamburger.is-active .line:nth-child(1) {+ height: 2px;+ -webkit-transform: translateY(5px) rotate(45deg);+ -ms-transform: translateY(5px) rotate(45deg);+ -o-transform: translateY(5px) rotate(45deg);+ transform: translateY(5px) rotate(45deg);+}++.hamburger.is-active .line:nth-child(2) {+ -webkit-transform: translateY(-5px) rotate(-45deg);+ -ms-transform: translateY(-5px) rotate(-45deg);+ -o-transform: translateY(-5px) rotate(-45deg);+ transform: translateY(-5px) rotate(-45deg);+}++body.mobile-nav-active {+ overflow: hidden;+}++.donate-btn:before {+ content: '';+ background: #ffffff80;+ filter: blur(8px);+ width: 150%;+ height: 1rem;+ position: absolute;+ top: 50%;+ transform: rotate(-30deg) translateX(-100%) translateY(-25%);+ opacity: 0;+}++.donate-btn:hover:before {+ animation: shimmer 1.69s linear infinite;+}++@keyframes shimmer {+ 0% {+ opacity: 1;+ transform: translateX(-100%) translateY(0rem) rotate(-30deg);+ }+ 42% {+ opacity: 1;+ transform: translateX(0%) translateY(0rem) rotate(-30deg);+ }+ 69% {+ opacity: 0;+ transform: translateX(100%) translateY(-1rem) rotate(-30deg);}}diff --git a/apps/aot/src/app/layout.tsx b/apps/aot/src/app/layout.tsxindex 86b3b4b0..3d9d855a 100644--- a/apps/aot/src/app/layout.tsx+++ b/apps/aot/src/app/layout.tsx@@ -1,11 +1,12 @@import './globals.css';+import { Toaster } from '@repo/ui/components/toaster';import type { Metadata } from 'next';import { Inter } from 'next/font/google';import { Navigation } from '~/components/navigation';-import { Providers } from './providers';import { getAllFlags } from '~/utils/feature-flag';import { ComingSoon } from './coming-soon';+import { Providers } from './providers';const inter = Inter({ subsets: ['latin'] });@@ -20,24 +21,18 @@ export default async function RootLayout({}>) {const { enableAotPlatform } = await getAllFlags();- if (!enableAotPlatform) {- return (- <html lang="en">- <body className={inter.className}>- <main>- <ComingSoon />- </main>- </body>- </html>- );- }return (<html lang="en"><body className={inter.className}>- <Providers>- <Navigation />- <main>{children}</main>- </Providers>+ {enableAotPlatform ? (+ <Providers>+ <Navigation />+ <main>{children}</main>+ </Providers>+ ) : (+ <ComingSoon />+ )}+ <Toaster /></body></html>);diff --git a/apps/aot/src/app/page.tsx b/apps/aot/src/app/page.tsxindex d6c46610..1bb43c82 100644--- a/apps/aot/src/app/page.tsx+++ b/apps/aot/src/app/page.tsx@@ -1,5 +1,3 @@-// import { CodeXml, ExternalLink } from 'lucide-react';-export default function Home() {return <div>Some landing page</div>;}diff --git a/apps/aot/src/app/providers.tsx b/apps/aot/src/app/providers.tsxindex 6c913ae1..dc4e712b 100644--- a/apps/aot/src/app/providers.tsx+++ b/apps/aot/src/app/providers.tsx@@ -13,7 +13,7 @@ export function Providers({ children }: Props) {return (<SessionProvider><TRPCReactProvider>- <ThemeProvider attribute="class">+ <ThemeProvider attribute="class" enableSystem disableTransitionOnChange><TooltipProvider>{children}</TooltipProvider></ThemeProvider></TRPCReactProvider>diff --git a/apps/aot/src/components/_actions.ts b/apps/aot/src/components/_actions.tsnew file mode 100644index 00000000..0a7bce90--- /dev/null+++ b/apps/aot/src/components/_actions.ts@@ -0,0 +1,139 @@+'use server';++import { prisma } from '@repo/db';++export type HistoricalChallenge = Awaited<ReturnType<typeof getChallengeHistoryByCategory>>[0];++type HistoryType = 'completed' | 'in-progress';+const getPredicateByType = (type: HistoryType, userId: string) => {+ switch (type) {+ case 'in-progress':+ return {+ AND: [+ {+ submission: {+ none: {+ userId,+ isSuccessful: true,+ },+ },+ },+ // Make sure there is at least one submission+ { submission: { some: { userId, isSuccessful: false } } },+ ],+ };+ case 'completed':+ return {+ submission: {+ some: {+ userId,+ isSuccessful: true,+ },+ },+ };+ }+};++export async function getChallengeHistoryByCategory(type: HistoryType, userId: string) {+ const challenges = await prisma.challenge.findMany({+ where: getPredicateByType(type, userId),+ select: {+ id: true,+ slug: true,+ name: true,+ submission: {+ where: {+ userId,+ },+ orderBy: {+ createdAt: 'desc',+ },+ take: 1,+ select: {+ createdAt: true,+ },+ },+ },+ });++ return challenges+ .map((challenge) => ({+ ...challenge,+ submissionDate: challenge.submission[0]?.createdAt,+ }))+ .sort(+ (challengeA, challengeB) =>+ new Date(challengeB.submissionDate!).getTime() -+ new Date(challengeA.submissionDate!).getTime(),+ );+}++export interface BadgeInfo {+ // eslint-disable-next-line @typescript-eslint/sort-type-constituents+ slug: 'aot-2023-bronze' | 'aot-2023-silver' | 'aot-2023-gold' | 'aot-2023-platinum';+ name: string;+}++export async function getBadges(userId: string): Promise<BadgeInfo[]> {+ const badges: BadgeInfo[] = [];++ const holidayTrack = await prisma.track.findFirst({+ where: {+ slug: 'advent-of-typescript-2023',+ },+ include: {+ trackChallenges: {+ orderBy: {+ orderId: 'asc',+ },+ include: {+ challenge: {+ include: {+ submission: {+ where: {+ userId,+ },+ },+ },+ },+ },+ },+ enrolledUsers: {+ where: {+ id: userId,+ },+ select: {+ id: true,+ },+ },+ },+ });++ const numberOfAttemptedHolidayChallenges =+ holidayTrack?.trackChallenges.filter((trackChallenge) => {+ return (trackChallenge.challenge.submission?.length ?? 0) > 0;+ }).length ?? 0;++ if (numberOfAttemptedHolidayChallenges > 0) {+ badges.push({ slug: 'aot-2023-bronze', name: 'Advent of TypeScript 2023 Bronze' });+ }++ const numberOfCompletedHolidayChallenges =+ holidayTrack?.trackChallenges.filter((trackChallenge) => {+ return trackChallenge.challenge.submission?.some((submission) => submission.isSuccessful);+ }).length ?? 0;++ if (numberOfCompletedHolidayChallenges >= 5) {+ badges.push({ slug: 'aot-2023-silver', name: 'Advent of TypeScript 2023 Silver' });+ }++ if (numberOfCompletedHolidayChallenges >= 15) {+ badges.push({ slug: 'aot-2023-gold', name: 'Advent of TypeScript 2023 Gold' });+ }++ if (numberOfCompletedHolidayChallenges >= 25) {+ badges.push({ slug: 'aot-2023-platinum', name: 'Advent of TypeScript 2023 Platinum' });+ }++ return badges;+}diff --git a/apps/aot/src/components/aot-2023-badge.tsx b/apps/aot/src/components/aot-2023-badge.tsxnew file mode 100644index 00000000..c69c3cb7--- /dev/null+++ b/apps/aot/src/components/aot-2023-badge.tsx@@ -0,0 +1,280 @@+export function HolidayBronzeBadge({ className }: { className?: string }) {+ return (+ <svg+ className={className}+ width="250"+ height="250"+ viewBox="0 0 250 250"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <mask+ id="mask0_16_29"+ style={{ maskType: 'alpha' }}+ maskUnits="userSpaceOnUse"+ x="16"+ y="3"+ width="218"+ height="244"+ >+ <path+ d="M112.5 7.21688C120.235 2.75106 129.765 2.75106 137.5 7.21688L220.753 55.2831C228.488 59.7489 233.253 68.0021 233.253 76.9338V173.066C233.253 181.998 228.488 190.251 220.753 194.717L137.5 242.783C129.765 247.249 120.235 247.249 112.5 242.783L29.2468 194.717C21.5118 190.251 16.7468 181.998 16.7468 173.066V76.9338C16.7468 68.0021 21.5118 59.7489 29.2468 55.2831L112.5 7.21688Z"+ fill="black"+ />+ </mask>+ <g mask="url(#mask0_16_29)">+ <rect width="250" height="250" fill="#D9D9D9" />+ <rect width="250" height="250" fill="url(#paint0_linear_16_29)" />+ <path+ d="M74.3309 80.3861L92.2816 71.0789L110.232 80.3861L106.8 60.6722L121.326 46.7073L101.257 43.8349L92.2816 25.899L83.3068 43.8349L63.2314 46.7073L77.7586 60.6722L74.3309 80.3861Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M152.246 217.662L45.0404 189.04L29.4744 224.046L172 262.101L152.246 217.662Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M123.966 154.044L67.3196 138.92L51.7542 173.926L143.72 198.488L123.966 154.044Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M74.034 123.81L115.44 134.864L92.2816 82.7655L74.034 123.81Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M232 187.682L225.182 187.682L214.409 174.659C213.693 173.795 213.023 173.057 212.398 172.443C211.761 171.818 211.108 171.341 210.437 171.011C209.767 170.67 209.023 170.5 208.205 170.5C207.307 170.5 206.54 170.693 205.903 171.08C205.267 171.455 204.778 171.977 204.437 172.648C204.085 173.318 203.909 174.091 203.909 174.966C203.909 175.841 204.085 176.614 204.437 177.284C204.79 177.943 205.307 178.455 205.989 178.818C206.67 179.182 207.5 179.364 208.477 179.364L208.477 188.364C206.023 188.364 203.909 187.812 202.136 186.71C200.364 185.608 199 184.051 198.045 182.04C197.091 180.028 196.614 177.67 196.614 174.966C196.614 172.17 197.062 169.75 197.96 167.705C198.847 165.648 200.097 164.062 201.71 162.949C203.324 161.824 205.216 161.261 207.386 161.261C208.727 161.261 210.062 161.54 211.392 162.097C212.71 162.653 214.17 163.653 215.773 165.097C217.375 166.54 219.284 168.591 221.5 171.25L224.227 174.523L224.432 174.523L224.432 160.886L232 160.886L232 187.682ZM232.955 141.446C232.943 144.616 232.21 147.355 230.756 149.662C229.301 151.969 227.205 153.747 224.466 154.997C221.727 156.247 218.443 156.866 214.614 156.855C210.773 156.844 207.511 156.219 204.83 154.98C202.148 153.73 200.108 151.957 198.71 149.662C197.312 147.355 196.614 144.616 196.614 141.446C196.614 138.276 197.318 135.537 198.727 133.23C200.125 130.923 202.165 129.145 204.847 127.895C207.528 126.645 210.784 126.026 214.614 126.037C218.466 126.037 221.761 126.662 224.5 127.912C227.239 129.162 229.335 130.94 230.79 133.247C232.233 135.543 232.955 138.276 232.955 141.446ZM225.25 141.446C225.25 139.81 224.398 138.469 222.693 137.423C220.977 136.366 218.284 135.844 214.614 135.855C212.216 135.855 210.256 136.094 208.733 136.571C207.21 137.048 206.085 137.707 205.358 138.548C204.619 139.389 204.25 140.355 204.25 141.446C204.25 143.082 205.08 144.418 206.739 145.452C208.398 146.486 211.023 147.014 214.614 147.037C217.057 147.048 219.068 146.815 220.648 146.338C222.216 145.861 223.375 145.202 224.125 144.361C224.875 143.509 225.25 142.537 225.25 141.446ZM232 121.588L225.182 121.588L214.409 108.565C213.693 107.702 213.023 106.963 212.398 106.349C211.761 105.724 211.108 105.247 210.437 104.918C209.767 104.577 209.023 104.406 208.205 104.406C207.307 104.406 206.54 104.599 205.903 104.986C205.267 105.361 204.778 105.884 204.437 106.554C204.085 107.224 203.909 107.997 203.909 108.872C203.909 109.747 204.085 110.52 204.437 111.19C204.79 111.849 205.307 112.361 205.989 112.724C206.67 113.088 207.5 113.27 208.477 113.27L208.477 122.27C206.023 122.27 203.909 121.719 202.136 120.616C200.364 119.514 199 117.957 198.045 115.946C197.091 113.935 196.614 111.577 196.614 108.872C196.614 106.077 197.062 103.656 197.96 101.611C198.847 99.554 200.097 97.9688 201.71 96.8551C203.324 95.7301 205.216 95.1676 207.386 95.1676C208.727 95.1676 210.062 95.446 211.392 96.0028C212.71 96.5597 214.17 97.5597 215.773 99.0028C217.375 100.446 219.284 102.497 221.5 105.156L224.227 108.429L224.432 108.429L224.432 94.7926L232 94.7926L232 121.588ZM232.477 76.9205C232.477 79.6705 232.006 82.1136 231.062 84.25C230.108 86.375 228.795 88.0455 227.125 89.2614C225.455 90.4773 223.534 91.0909 221.364 91.1023L221.364 81.5568C222.034 81.5455 222.636 81.3409 223.17 80.9432C223.693 80.5341 224.102 79.9773 224.398 79.2727C224.693 78.5682 224.841 77.7614 224.841 76.8523C224.841 75.9773 224.687 75.2045 224.381 74.5341C224.062 73.8636 223.625 73.3409 223.068 72.9659C222.511 72.5909 221.875 72.4091 221.159 72.4205C220.455 72.4091 219.83 72.625 219.284 73.0682C218.739 73.5 218.312 74.108 218.006 74.8921C217.699 75.6761 217.545 76.5796 217.545 77.6023L217.545 81.1477L211 81.1477L211 77.6023C211 76.6591 210.847 75.8296 210.54 75.1136C210.233 74.3864 209.807 73.8239 209.261 73.4261C208.716 73.0171 208.091 72.8182 207.386 72.8296C206.705 72.8182 206.102 72.983 205.58 73.3239C205.057 73.6648 204.648 74.1421 204.352 74.7557C204.057 75.358 203.909 76.0568 203.909 76.8523C203.909 77.7159 204.062 78.4886 204.369 79.1705C204.676 79.8409 205.102 80.3693 205.648 80.7557C206.193 81.1421 206.818 81.3409 207.523 81.3523L207.523 90.4205C205.386 90.4091 203.5 89.8239 201.864 88.6648C200.227 87.4943 198.943 85.8921 198.011 83.858C197.08 81.8239 196.614 79.4886 196.614 76.8523C196.614 74.2727 197.051 71.9943 197.926 70.0171C198.801 68.0284 200.006 66.4773 201.54 65.3636C203.062 64.2386 204.807 63.6818 206.773 63.6932C208.727 63.6705 210.33 64.3409 211.58 65.7046C212.83 67.0568 213.568 68.7727 213.795 70.8523L214.068 70.8523C214.375 68.0341 215.239 65.9148 216.659 64.4943C218.068 63.0739 219.841 62.375 221.977 62.3977C224.023 62.3864 225.835 63 227.415 64.2386C228.994 65.4659 230.233 67.1761 231.131 69.3693C232.028 71.5511 232.477 74.0682 232.477 76.9205Z"+ fill="white"+ fillOpacity="0.62"+ />+ </g>+ <defs>+ <linearGradient+ id="paint0_linear_16_29"+ x1="63.5081"+ y1="26.6204"+ x2="197.998"+ y2="210.54"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#714F24" />+ <stop offset="0.5625" stopColor="#D27D13" />+ <stop offset="1" stopColor="#5E3D13" />+ </linearGradient>+ </defs>+ </svg>+ );+}++export function HolidaySilverBadge({ className }: { className?: string }) {+ return (+ <svg+ className={className}+ width="250"+ height="250"+ viewBox="0 0 250 250"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <mask+ id="mask0_13_495"+ style={{ maskType: 'alpha' }}+ maskUnits="userSpaceOnUse"+ x="16"+ y="3"+ width="218"+ height="244"+ >+ <path+ d="M112.5 7.21688C120.235 2.75106 129.765 2.75106 137.5 7.21688L220.753 55.2831C228.488 59.7489 233.253 68.0021 233.253 76.9338V173.066C233.253 181.998 228.488 190.251 220.753 194.717L137.5 242.783C129.765 247.249 120.235 247.249 112.5 242.783L29.2468 194.717C21.5118 190.251 16.7468 181.998 16.7468 173.066V76.9338C16.7468 68.0021 21.5118 59.7489 29.2468 55.2831L112.5 7.21688Z"+ fill="black"+ />+ </mask>+ <g mask="url(#mask0_13_495)">+ <rect width="250" height="250" fill="url(#paint0_linear_13_495)" />+ <path+ d="M74.3309 80.3861L92.2815 71.0789L110.232 80.3861L106.8 60.6722L121.326 46.7073L101.257 43.8349L92.2815 25.899L83.3068 43.8349L63.2314 46.7073L77.7586 60.6722L74.3309 80.3861Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M152.246 217.662L45.0404 189.04L29.4744 224.046L172 262.101L152.246 217.662Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M123.966 154.044L67.3196 138.92L51.7542 173.926L143.72 198.488L123.966 154.044Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M74.034 123.81L115.44 134.864L92.2816 82.7655L74.034 123.81Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M232 187.682L225.182 187.682L214.409 174.659C213.693 173.795 213.023 173.057 212.398 172.443C211.761 171.818 211.108 171.341 210.437 171.011C209.767 170.67 209.023 170.5 208.205 170.5C207.307 170.5 206.54 170.693 205.903 171.08C205.267 171.455 204.778 171.977 204.437 172.648C204.085 173.318 203.909 174.091 203.909 174.966C203.909 175.841 204.085 176.614 204.437 177.284C204.79 177.943 205.307 178.455 205.989 178.818C206.67 179.182 207.5 179.364 208.477 179.364L208.477 188.364C206.023 188.364 203.909 187.812 202.136 186.71C200.364 185.608 199 184.051 198.045 182.04C197.091 180.028 196.614 177.67 196.614 174.966C196.614 172.17 197.062 169.75 197.96 167.705C198.847 165.648 200.097 164.062 201.71 162.949C203.324 161.824 205.216 161.261 207.386 161.261C208.727 161.261 210.062 161.54 211.392 162.097C212.71 162.653 214.17 163.653 215.773 165.097C217.375 166.54 219.284 168.591 221.5 171.25L224.227 174.523L224.432 174.523L224.432 160.886L232 160.886L232 187.682ZM232.955 141.446C232.943 144.616 232.21 147.355 230.756 149.662C229.301 151.969 227.205 153.747 224.466 154.997C221.727 156.247 218.443 156.866 214.614 156.855C210.773 156.844 207.511 156.219 204.83 154.98C202.148 153.73 200.108 151.957 198.71 149.662C197.312 147.355 196.614 144.616 196.614 141.446C196.614 138.276 197.318 135.537 198.727 133.23C200.125 130.923 202.165 129.145 204.847 127.895C207.528 126.645 210.784 126.026 214.614 126.037C218.466 126.037 221.761 126.662 224.5 127.912C227.239 129.162 229.335 130.94 230.79 133.247C232.233 135.543 232.955 138.276 232.955 141.446ZM225.25 141.446C225.25 139.81 224.398 138.469 222.693 137.423C220.977 136.366 218.284 135.844 214.614 135.855C212.216 135.855 210.256 136.094 208.733 136.571C207.21 137.048 206.085 137.707 205.358 138.548C204.619 139.389 204.25 140.355 204.25 141.446C204.25 143.082 205.08 144.418 206.739 145.452C208.398 146.486 211.023 147.014 214.614 147.037C217.057 147.048 219.068 146.815 220.648 146.338C222.216 145.861 223.375 145.202 224.125 144.361C224.875 143.509 225.25 142.537 225.25 141.446ZM232 121.588L225.182 121.588L214.409 108.565C213.693 107.702 213.023 106.963 212.398 106.349C211.761 105.724 211.108 105.247 210.437 104.918C209.767 104.577 209.023 104.406 208.205 104.406C207.307 104.406 206.54 104.599 205.903 104.986C205.267 105.361 204.778 105.884 204.437 106.554C204.085 107.224 203.909 107.997 203.909 108.872C203.909 109.747 204.085 110.52 204.437 111.19C204.79 111.849 205.307 112.361 205.989 112.724C206.67 113.088 207.5 113.27 208.477 113.27L208.477 122.27C206.023 122.27 203.909 121.719 202.136 120.616C200.364 119.514 199 117.957 198.045 115.946C197.091 113.935 196.614 111.577 196.614 108.872C196.614 106.077 197.062 103.656 197.96 101.611C198.847 99.554 200.097 97.9688 201.71 96.8551C203.324 95.7301 205.216 95.1676 207.386 95.1676C208.727 95.1676 210.062 95.446 211.392 96.0028C212.71 96.5597 214.17 97.5597 215.773 99.0028C217.375 100.446 219.284 102.497 221.5 105.156L224.227 108.429L224.432 108.429L224.432 94.7926L232 94.7926L232 121.588ZM232.477 76.9205C232.477 79.6705 232.006 82.1136 231.062 84.25C230.108 86.375 228.795 88.0455 227.125 89.2614C225.455 90.4773 223.534 91.0909 221.364 91.1023L221.364 81.5568C222.034 81.5455 222.636 81.3409 223.17 80.9432C223.693 80.5341 224.102 79.9773 224.398 79.2727C224.693 78.5682 224.841 77.7614 224.841 76.8523C224.841 75.9773 224.687 75.2045 224.381 74.5341C224.062 73.8636 223.625 73.3409 223.068 72.9659C222.511 72.5909 221.875 72.4091 221.159 72.4205C220.455 72.4091 219.83 72.625 219.284 73.0682C218.739 73.5 218.312 74.108 218.006 74.8921C217.699 75.6761 217.545 76.5796 217.545 77.6023L217.545 81.1477L211 81.1477L211 77.6023C211 76.6591 210.847 75.8296 210.54 75.1136C210.233 74.3864 209.807 73.8239 209.261 73.4261C208.716 73.0171 208.091 72.8182 207.386 72.8296C206.705 72.8182 206.102 72.983 205.58 73.3239C205.057 73.6648 204.648 74.1421 204.352 74.7557C204.057 75.358 203.909 76.0568 203.909 76.8523C203.909 77.7159 204.062 78.4886 204.369 79.1705C204.676 79.8409 205.102 80.3693 205.648 80.7557C206.193 81.1421 206.818 81.3409 207.523 81.3523L207.523 90.4205C205.386 90.4091 203.5 89.8239 201.864 88.6648C200.227 87.4943 198.943 85.8921 198.011 83.858C197.08 81.8239 196.614 79.4886 196.614 76.8523C196.614 74.2727 197.051 71.9943 197.926 70.0171C198.801 68.0284 200.006 66.4773 201.54 65.3636C203.062 64.2386 204.807 63.6818 206.773 63.6932C208.727 63.6705 210.33 64.3409 211.58 65.7046C212.83 67.0568 213.568 68.7727 213.795 70.8523L214.068 70.8523C214.375 68.0341 215.239 65.9148 216.659 64.4943C218.068 63.0739 219.841 62.375 221.977 62.3977C224.023 62.3864 225.835 63 227.415 64.2386C228.994 65.4659 230.233 67.1761 231.131 69.3693C232.028 71.5511 232.477 74.0682 232.477 76.9205Z"+ fill="white"+ fillOpacity="0.62"+ />+ </g>+ <defs>+ <linearGradient+ id="paint0_linear_13_495"+ x1="64.5161"+ y1="22.5694"+ x2="188.641"+ y2="215.658"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#3D5954" />+ <stop offset="0.614583" stopColor="#9BCBC2" />+ <stop offset="1" stopColor="#48625D" />+ </linearGradient>+ </defs>+ </svg>+ );+}++export function HolidayGoldBadge({ className }: { className?: string }) {+ return (+ <svg+ className={className}+ width="250"+ height="250"+ viewBox="0 0 250 250"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <mask+ id="mask0_16_56"+ style={{ maskType: 'alpha' }}+ maskUnits="userSpaceOnUse"+ x="16"+ y="3"+ width="218"+ height="244"+ >+ <path+ d="M112.5 7.21688C120.235 2.75106 129.765 2.75106 137.5 7.21688L220.753 55.2831C228.488 59.7489 233.253 68.0021 233.253 76.9338V173.066C233.253 181.998 228.488 190.251 220.753 194.717L137.5 242.783C129.765 247.249 120.235 247.249 112.5 242.783L29.2468 194.717C21.5118 190.251 16.7468 181.998 16.7468 173.066V76.9338C16.7468 68.0021 21.5118 59.7489 29.2468 55.2831L112.5 7.21688Z"+ fill="black"+ />+ </mask>+ <g mask="url(#mask0_16_56)">+ <rect width="250" height="250" fill="url(#paint0_linear_16_56)" />+ <path+ d="M74.3309 80.3861L92.2816 71.0789L110.232 80.3861L106.8 60.6722L121.326 46.7073L101.257 43.8349L92.2816 25.899L83.3068 43.8349L63.2314 46.7073L77.7586 60.6722L74.3309 80.3861Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M152.246 217.662L45.0404 189.04L29.4744 224.046L172 262.101L152.246 217.662Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M123.966 154.044L67.3196 138.92L51.7542 173.926L143.72 198.488L123.966 154.044Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M74.0339 123.81L115.44 134.864L92.2815 82.7655L74.0339 123.81Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M232 187.682L225.182 187.682L214.409 174.659C213.693 173.795 213.023 173.057 212.398 172.443C211.761 171.818 211.108 171.341 210.437 171.011C209.767 170.67 209.023 170.5 208.205 170.5C207.307 170.5 206.54 170.693 205.903 171.08C205.267 171.455 204.778 171.977 204.437 172.648C204.085 173.318 203.909 174.091 203.909 174.966C203.909 175.841 204.085 176.614 204.437 177.284C204.79 177.943 205.307 178.455 205.989 178.818C206.67 179.182 207.5 179.364 208.477 179.364L208.477 188.364C206.023 188.364 203.909 187.812 202.136 186.71C200.364 185.608 199 184.051 198.045 182.04C197.091 180.028 196.614 177.67 196.614 174.966C196.614 172.17 197.062 169.75 197.96 167.705C198.847 165.648 200.097 164.062 201.71 162.949C203.324 161.824 205.216 161.261 207.386 161.261C208.727 161.261 210.062 161.54 211.392 162.097C212.71 162.653 214.17 163.653 215.773 165.097C217.375 166.54 219.284 168.591 221.5 171.25L224.227 174.523L224.432 174.523L224.432 160.886L232 160.886L232 187.682ZM232.955 141.446C232.943 144.616 232.21 147.355 230.756 149.662C229.301 151.969 227.205 153.747 224.466 154.997C221.727 156.247 218.443 156.866 214.614 156.855C210.773 156.844 207.511 156.219 204.83 154.98C202.148 153.73 200.108 151.957 198.71 149.662C197.312 147.355 196.614 144.616 196.614 141.446C196.614 138.276 197.318 135.537 198.727 133.23C200.125 130.923 202.165 129.145 204.847 127.895C207.528 126.645 210.784 126.026 214.614 126.037C218.466 126.037 221.761 126.662 224.5 127.912C227.239 129.162 229.335 130.94 230.79 133.247C232.233 135.543 232.955 138.276 232.955 141.446ZM225.25 141.446C225.25 139.81 224.398 138.469 222.693 137.423C220.977 136.366 218.284 135.844 214.614 135.855C212.216 135.855 210.256 136.094 208.733 136.571C207.21 137.048 206.085 137.707 205.358 138.548C204.619 139.389 204.25 140.355 204.25 141.446C204.25 143.082 205.08 144.418 206.739 145.452C208.398 146.486 211.023 147.014 214.614 147.037C217.057 147.048 219.068 146.815 220.648 146.338C222.216 145.861 223.375 145.202 224.125 144.361C224.875 143.509 225.25 142.537 225.25 141.446ZM232 121.588L225.182 121.588L214.409 108.565C213.693 107.702 213.023 106.963 212.398 106.349C211.761 105.724 211.108 105.247 210.437 104.918C209.767 104.577 209.023 104.406 208.205 104.406C207.307 104.406 206.54 104.599 205.903 104.986C205.267 105.361 204.778 105.884 204.437 106.554C204.085 107.224 203.909 107.997 203.909 108.872C203.909 109.747 204.085 110.52 204.437 111.19C204.79 111.849 205.307 112.361 205.989 112.724C206.67 113.088 207.5 113.27 208.477 113.27L208.477 122.27C206.023 122.27 203.909 121.719 202.136 120.616C200.364 119.514 199 117.957 198.045 115.946C197.091 113.935 196.614 111.577 196.614 108.872C196.614 106.077 197.062 103.656 197.96 101.611C198.847 99.554 200.097 97.9688 201.71 96.8551C203.324 95.7301 205.216 95.1676 207.386 95.1676C208.727 95.1676 210.062 95.446 211.392 96.0028C212.71 96.5597 214.17 97.5597 215.773 99.0028C217.375 100.446 219.284 102.497 221.5 105.156L224.227 108.429L224.432 108.429L224.432 94.7926L232 94.7926L232 121.588ZM232.477 76.9205C232.477 79.6705 232.006 82.1136 231.062 84.25C230.108 86.375 228.795 88.0455 227.125 89.2614C225.455 90.4773 223.534 91.0909 221.364 91.1023L221.364 81.5568C222.034 81.5455 222.636 81.3409 223.17 80.9432C223.693 80.5341 224.102 79.9773 224.398 79.2727C224.693 78.5682 224.841 77.7614 224.841 76.8523C224.841 75.9773 224.687 75.2045 224.381 74.5341C224.062 73.8636 223.625 73.3409 223.068 72.9659C222.511 72.5909 221.875 72.4091 221.159 72.4205C220.455 72.4091 219.83 72.625 219.284 73.0682C218.739 73.5 218.312 74.108 218.006 74.8921C217.699 75.6761 217.545 76.5796 217.545 77.6023L217.545 81.1477L211 81.1477L211 77.6023C211 76.6591 210.847 75.8296 210.54 75.1136C210.233 74.3864 209.807 73.8239 209.261 73.4261C208.716 73.0171 208.091 72.8182 207.386 72.8296C206.705 72.8182 206.102 72.983 205.58 73.3239C205.057 73.6648 204.648 74.1421 204.352 74.7557C204.057 75.358 203.909 76.0568 203.909 76.8523C203.909 77.7159 204.062 78.4886 204.369 79.1705C204.676 79.8409 205.102 80.3693 205.648 80.7557C206.193 81.1421 206.818 81.3409 207.523 81.3523L207.523 90.4205C205.386 90.4091 203.5 89.8239 201.864 88.6648C200.227 87.4943 198.943 85.8921 198.011 83.858C197.08 81.8239 196.614 79.4886 196.614 76.8523C196.614 74.2727 197.051 71.9943 197.926 70.0171C198.801 68.0284 200.006 66.4773 201.54 65.3636C203.062 64.2386 204.807 63.6818 206.773 63.6932C208.727 63.6705 210.33 64.3409 211.58 65.7046C212.83 67.0568 213.568 68.7727 213.795 70.8523L214.068 70.8523C214.375 68.0341 215.239 65.9148 216.659 64.4943C218.068 63.0739 219.841 62.375 221.977 62.3977C224.023 62.3864 225.835 63 227.415 64.2386C228.994 65.4659 230.233 67.1761 231.131 69.3693C232.028 71.5511 232.477 74.0682 232.477 76.9205Z"+ fill="white"+ fillOpacity="0.62"+ />+ </g>+ <defs>+ <linearGradient+ id="paint0_linear_16_56"+ x1="65.0202"+ y1="26.6204"+ x2="197.809"+ y2="209.652"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#BC9B28" />+ <stop offset="0.619792" stopColor="#FFC700" />+ <stop offset="1" stopColor="#B59112" />+ </linearGradient>+ </defs>+ </svg>+ );+}++export function HolidayPlatinumBadge({ className }: { className?: string }) {+ return (+ <svg+ className={className}+ width="250"+ height="250"+ viewBox="0 0 250 250"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <mask+ id="mask0_16_74"+ style={{ maskType: 'alpha' }}+ maskUnits="userSpaceOnUse"+ x="16"+ y="3"+ width="218"+ height="244"+ >+ <path+ d="M112.5 7.21688C120.235 2.75106 129.765 2.75106 137.5 7.21688L220.753 55.2831C228.488 59.7489 233.253 68.0021 233.253 76.9338V173.066C233.253 181.998 228.488 190.251 220.753 194.717L137.5 242.783C129.765 247.249 120.235 247.249 112.5 242.783L29.2468 194.717C21.5118 190.251 16.7468 181.998 16.7468 173.066V76.9338C16.7468 68.0021 21.5118 59.7489 29.2468 55.2831L112.5 7.21688Z"+ fill="black"+ />+ </mask>+ <g mask="url(#mask0_16_74)">+ <rect width="250" height="250" fill="url(#paint0_linear_16_74)" />+ <path+ d="M74.3309 80.3861L92.2816 71.0789L110.232 80.3861L106.8 60.6722L121.326 46.7073L101.257 43.8349L92.2816 25.899L83.3068 43.8349L63.2314 46.7073L77.7586 60.6722L74.3309 80.3861Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M152.246 217.662L45.0404 189.04L29.4744 224.046L172 262.101L152.246 217.662Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M123.966 154.044L67.3196 138.92L51.7542 173.926L143.72 198.488L123.966 154.044Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M74.0339 123.81L115.44 134.864L92.2815 82.7655L74.0339 123.81Z"+ fill="white"+ fillOpacity="0.62"+ />+ <path+ d="M232 187.682L225.182 187.682L214.409 174.659C213.693 173.795 213.023 173.057 212.398 172.443C211.761 171.818 211.108 171.341 210.437 171.011C209.767 170.67 209.023 170.5 208.205 170.5C207.307 170.5 206.54 170.693 205.903 171.08C205.267 171.455 204.778 171.977 204.437 172.648C204.085 173.318 203.909 174.091 203.909 174.966C203.909 175.841 204.085 176.614 204.437 177.284C204.79 177.943 205.307 178.455 205.989 178.818C206.67 179.182 207.5 179.364 208.477 179.364L208.477 188.364C206.023 188.364 203.909 187.812 202.136 186.71C200.364 185.608 199 184.051 198.045 182.04C197.091 180.028 196.614 177.67 196.614 174.966C196.614 172.17 197.062 169.75 197.96 167.705C198.847 165.648 200.097 164.062 201.71 162.949C203.324 161.824 205.216 161.261 207.386 161.261C208.727 161.261 210.062 161.54 211.392 162.097C212.71 162.653 214.17 163.653 215.773 165.097C217.375 166.54 219.284 168.591 221.5 171.25L224.227 174.523L224.432 174.523L224.432 160.886L232 160.886L232 187.682ZM232.955 141.446C232.943 144.616 232.21 147.355 230.756 149.662C229.301 151.969 227.205 153.747 224.466 154.997C221.727 156.247 218.443 156.866 214.614 156.855C210.773 156.844 207.511 156.219 204.83 154.98C202.148 153.73 200.108 151.957 198.71 149.662C197.312 147.355 196.614 144.616 196.614 141.446C196.614 138.276 197.318 135.537 198.727 133.23C200.125 130.923 202.165 129.145 204.847 127.895C207.528 126.645 210.784 126.026 214.614 126.037C218.466 126.037 221.761 126.662 224.5 127.912C227.239 129.162 229.335 130.94 230.79 133.247C232.233 135.543 232.955 138.276 232.955 141.446ZM225.25 141.446C225.25 139.81 224.398 138.469 222.693 137.423C220.977 136.366 218.284 135.844 214.614 135.855C212.216 135.855 210.256 136.094 208.733 136.571C207.21 137.048 206.085 137.707 205.358 138.548C204.619 139.389 204.25 140.355 204.25 141.446C204.25 143.082 205.08 144.418 206.739 145.452C208.398 146.486 211.023 147.014 214.614 147.037C217.057 147.048 219.068 146.815 220.648 146.338C222.216 145.861 223.375 145.202 224.125 144.361C224.875 143.509 225.25 142.537 225.25 141.446ZM232 121.588L225.182 121.588L214.409 108.565C213.693 107.702 213.023 106.963 212.398 106.349C211.761 105.724 211.108 105.247 210.437 104.918C209.767 104.577 209.023 104.406 208.205 104.406C207.307 104.406 206.54 104.599 205.903 104.986C205.267 105.361 204.778 105.884 204.437 106.554C204.085 107.224 203.909 107.997 203.909 108.872C203.909 109.747 204.085 110.52 204.437 111.19C204.79 111.849 205.307 112.361 205.989 112.724C206.67 113.088 207.5 113.27 208.477 113.27L208.477 122.27C206.023 122.27 203.909 121.719 202.136 120.616C200.364 119.514 199 117.957 198.045 115.946C197.091 113.935 196.614 111.577 196.614 108.872C196.614 106.077 197.062 103.656 197.96 101.611C198.847 99.554 200.097 97.9688 201.71 96.8551C203.324 95.7301 205.216 95.1676 207.386 95.1676C208.727 95.1676 210.062 95.446 211.392 96.0028C212.71 96.5597 214.17 97.5597 215.773 99.0028C217.375 100.446 219.284 102.497 221.5 105.156L224.227 108.429L224.432 108.429L224.432 94.7926L232 94.7926L232 121.588ZM232.477 76.9205C232.477 79.6705 232.006 82.1136 231.062 84.25C230.108 86.375 228.795 88.0455 227.125 89.2614C225.455 90.4773 223.534 91.0909 221.364 91.1023L221.364 81.5568C222.034 81.5455 222.636 81.3409 223.17 80.9432C223.693 80.5341 224.102 79.9773 224.398 79.2727C224.693 78.5682 224.841 77.7614 224.841 76.8523C224.841 75.9773 224.687 75.2045 224.381 74.5341C224.062 73.8636 223.625 73.3409 223.068 72.9659C222.511 72.5909 221.875 72.4091 221.159 72.4205C220.455 72.4091 219.83 72.625 219.284 73.0682C218.739 73.5 218.312 74.108 218.006 74.8921C217.699 75.6761 217.545 76.5796 217.545 77.6023L217.545 81.1477L211 81.1477L211 77.6023C211 76.6591 210.847 75.8296 210.54 75.1136C210.233 74.3864 209.807 73.8239 209.261 73.4261C208.716 73.0171 208.091 72.8182 207.386 72.8296C206.705 72.8182 206.102 72.983 205.58 73.3239C205.057 73.6648 204.648 74.1421 204.352 74.7557C204.057 75.358 203.909 76.0568 203.909 76.8523C203.909 77.7159 204.062 78.4886 204.369 79.1705C204.676 79.8409 205.102 80.3693 205.648 80.7557C206.193 81.1421 206.818 81.3409 207.523 81.3523L207.523 90.4205C205.386 90.4091 203.5 89.8239 201.864 88.6648C200.227 87.4943 198.943 85.8921 198.011 83.858C197.08 81.8239 196.614 79.4886 196.614 76.8523C196.614 74.2727 197.051 71.9943 197.926 70.0171C198.801 68.0284 200.006 66.4773 201.54 65.3636C203.062 64.2386 204.807 63.6818 206.773 63.6932C208.727 63.6705 210.33 64.3409 211.58 65.7046C212.83 67.0568 213.568 68.7727 213.795 70.8523L214.068 70.8523C214.375 68.0341 215.239 65.9148 216.659 64.4943C218.068 63.0739 219.841 62.375 221.977 62.3977C224.023 62.3864 225.835 63 227.415 64.2386C228.994 65.4659 230.233 67.1761 231.131 69.3693C232.028 71.5511 232.477 74.0682 232.477 76.9205Z"+ fill="white"+ fillOpacity="0.62"+ />+ </g>+ <defs>+ <linearGradient+ id="paint0_linear_16_74"+ x1="75.1008"+ y1="21.412"+ x2="188.982"+ y2="212.197"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#2EECEC" />+ <stop offset="0.677083" stopColor="#00A184" />+ <stop offset="1" stopColor="#0F7562" />+ </linearGradient>+ </defs>+ </svg>+ );+}diff --git a/apps/aot/src/components/badges.tsx b/apps/aot/src/components/badges.tsxnew file mode 100644index 00000000..4c72fd6f--- /dev/null+++ b/apps/aot/src/components/badges.tsx@@ -0,0 +1,68 @@+import { type FC } from 'react';++import { cn } from '@repo/ui/cn';+import { Text } from '@repo/ui/components/typography/typography';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';++import { type BadgeInfo } from './_actions';+import { toast } from '@repo/ui/components/use-toast';+import {+ HolidayBronzeBadge,+ HolidayGoldBadge,+ HolidayPlatinumBadge,+ HolidaySilverBadge,+} from './aot-2023-badge';++export const SlugToBadgeIcon: Record<BadgeInfo['slug'], FC<{ className: string }>> = {+ 'aot-2023-bronze': HolidayBronzeBadge,+ 'aot-2023-silver': HolidaySilverBadge,+ 'aot-2023-gold': HolidayGoldBadge,+ 'aot-2023-platinum': HolidayPlatinumBadge,+};++const Badge = ({ slug, name }: BadgeInfo) => {+ const Icon = SlugToBadgeIcon[slug];++ if (Icon === undefined) return null;++ return (+ <Tooltip>+ <TooltipTrigger>+ <span+ onClick={(e) => {+ navigator.clipboard.writeText(e.currentTarget.innerHTML);+ toast({+ title: 'Copied to clipboard',+ variant: 'success',+ });+ }}+ >+ <Icon className="h-12 w-12" />+ </span>+ </TooltipTrigger>+ <TooltipContent side="bottom">+ <span>{name}</span>+ </TooltipContent>+ </Tooltip>+ );+};++interface BadgesProps {+ badges: BadgeInfo[];+ className?: string;+}++export const Badges = ({ badges, className }: BadgesProps) => {+ if (badges.length === 0) return null;++ return (+ <div className={cn('border-border flex flex-col gap-4 border-t py-4', className)}>+ <Text intent="leading">Badges</Text>+ <div className="flex flex-wrap gap-2">+ {badges.map((badge) => (+ <Badge key={badge.slug} {...badge} />+ ))}+ </div>+ </div>+ );+};diff --git a/apps/aot/src/components/loader.tsx b/apps/aot/src/components/loader.tsxnew file mode 100644index 00000000..9f780573--- /dev/null+++ b/apps/aot/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/aot/src/components/mention/actions.ts b/apps/aot/src/components/mention/actions.tsnew file mode 100644index 00000000..92d6323c--- /dev/null+++ b/apps/aot/src/components/mention/actions.ts@@ -0,0 +1,26 @@+'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,+ },+ },+ select: {+ id: true,+ name: true,+ image: true,+ },+ orderBy: {+ name: 'desc',+ },+ take: 10,+ });+}diff --git a/apps/aot/src/components/mention/mention-input.tsx b/apps/aot/src/components/mention/mention-input.tsxnew file mode 100644index 00000000..028f153c--- /dev/null+++ b/apps/aot/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 { UserResults } from './user-results';+import { useDebouncedValue } from '~/utils/useDebouncedValue';++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/aot/src/components/mention/user-results.tsx b/apps/aot/src/components/mention/user-results.tsxnew file mode 100644index 00000000..634370e4--- /dev/null+++ b/apps/aot/src/components/mention/user-results.tsx@@ -0,0 +1,166 @@+'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';+import { DefaultAvatar } from '~/utils/default-avatar';++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-400 bg-zinc-100 p-0 dark:border-gray-700 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-500 dark:border-gray-700">+ <AvatarImage src={user.image ?? ''} alt="user avatar" />+ <AvatarFallback>+ <DefaultAvatar />+ </AvatarFallback>+ </Avatar>+ <div className="flex flex-col">+ <span className="text-sm font-bold text-gray-900 dark:text-white">+ {user.name}+ </span>+ <span className="text-xs text-gray-600 dark: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/aot/src/components/report-dialog/index.tsx b/apps/aot/src/components/report-dialog/index.tsxnew file mode 100644index 00000000..1bbffa3c--- /dev/null+++ b/apps/aot/src/components/report-dialog/index.tsx@@ -0,0 +1,319 @@+import { type IssueType } from '@repo/db/types';+import React from 'react';+import { useForm } from 'react-hook-form';+import {+ type ChallengeReport,+ type UserReport,+ type CommentReport,+ addReport,+ type SolutionReport,+} from './report-dialog.action';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@repo/ui/components/dialog';+import { toast } from '@repo/ui/components/use-toast';+import { Text } from '@repo/ui/components/typography/typography';+import { FormField, FormItem } from '@repo/ui/components/form';+import { Checkbox } from '@repo/ui/components/checkbox';+import { Textarea } from '@repo/ui/components/textarea';+import { Button } from '@repo/ui/components/button';++export interface ReportDialogPropsBase {+ triggerAsChild?: boolean;+}++export interface ReportUserDialogProps extends ReportDialogPropsBase {+ reportType: 'USER';+ userId: string;+}++export interface ReportChallengeDialogProps extends ReportDialogPropsBase {+ reportType: 'CHALLENGE';+ challengeId: number;+}++export interface ReportCommentDialogProps extends ReportDialogPropsBase {+ reportType: 'COMMENT';+ commentId: number;+}++export interface ReportSolutionDialogProps extends ReportDialogPropsBase {+ reportType: 'SOLUTION';+ solutionId: number;+}++export function ReportDialog({+ children,+ triggerAsChild = false,+ reportType = 'COMMENT',+ ...props+}: React.PropsWithChildren<+ | ReportChallengeDialogProps+ | ReportCommentDialogProps+ | ReportSolutionDialogProps+ | ReportUserDialogProps+>) {+ const {+ handleSubmit,+ formState: { errors },+ register,+ control,+ setValue,+ } = useForm({+ defaultValues: {+ derogatory: false,+ unclear: false,+ bullying: false,+ spam: false,+ hateSpeech: false,+ threat: false,+ comments: '',+ },+ });++ const [show, setShow] = React.useState(false);++ let desc = '';+ switch (reportType) {+ case 'CHALLENGE':+ desc = 'Report Challenge';+ break;+ case 'COMMENT':+ desc = 'Report Comment';+ break;+ case 'USER':+ desc = 'Report User';+ break;+ case 'SOLUTION':+ desc = 'Report Solution';+ break;+ }++ return (+ <Dialog+ onOpenChange={(e) => {+ setShow(e);+ }}+ open={show}+ >+ <DialogTrigger asChild={triggerAsChild} className="focus:outline-none focus-visible:ring-2">+ {children}+ </DialogTrigger>+ <DialogContent>+ <form+ onSubmit={handleSubmit(async (e) => {+ let args = {} as ChallengeReport | CommentReport | SolutionReport | UserReport;+ switch (reportType) {+ case 'CHALLENGE':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as ChallengeReport;+ break;+ case 'COMMENT':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as CommentReport;+ break;+ case 'USER':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as UserReport;+ break;+ case 'SOLUTION':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as SolutionReport;+ }++ // This shit is like... extra jank.+ const issues = Object.entries(e).reduce<{ type: IssueType }[]>((all, [key, value]) => {+ if (key === 'comments') return all;+ if (value)+ all.push({+ type: key.toUpperCase() as IssueType,+ });+ return all;+ }, []);++ const value = await addReport({+ ...args,+ issues,+ });++ switch (value) {+ case 'already_exists':+ toast({+ title: 'Already reported',+ description: <p>You have already made a report with this information.</p>,+ });+ break;+ case 'created':+ toast({+ title: 'Created',+ variant: 'success',+ description: <p>A report has been made.</p>,+ });+ break;+ case 'not_logged_in':+ toast({+ title: 'Not Logged In',+ variant: 'destructive',+ description: <p>You must be logged in to make a report.</p>,+ });+ }+ setShow(false);+ })}+ >+ <DialogHeader>+ <DialogTitle>{desc}</DialogTitle>+ <DialogDescription>Please be as thorough in your report as you can.</DialogDescription>+ </DialogHeader>+ <div className="mt-4 flex flex-col gap-2">+ <Text intent="leading">Please select all that apply:</Text>+ <FormField+ control={control}+ name="derogatory"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="derogatory"+ {...register('derogatory')}+ onCheckedChange={(e) => setValue('derogatory', e as boolean)}+ />+ <label htmlFor="derogatory">Derogatory</label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name="derogatory"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="bullying"+ {...register('bullying')}+ onCheckedChange={(e) => setValue('bullying', e as boolean)}+ />+ <label htmlFor="bullying">Bullying</label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name="hateSpeech"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="hateSpeech"+ {...register('hateSpeech')}+ onCheckedChange={(e) => setValue('hateSpeech', e as boolean)}+ />+ <label htmlFor="hateSpeech">Hate speech</label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name="spam"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="spam"+ {...register('spam')}+ onCheckedChange={(e) => setValue('spam', e as boolean)}+ />+ <label htmlFor="spam">Spam</label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name="threat"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="threat"+ {...register('threat')}+ onCheckedChange={(e) => setValue('threat', e as boolean)}+ />+ <label htmlFor="threat">Threat of violence</label>+ </div>+ </FormItem>+ )}+ />+ {reportType === 'CHALLENGE' && (+ <FormField+ control={control}+ name="unclear"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="unclear"+ {...register('unclear')}+ onCheckedChange={(e) => setValue('unclear', e as boolean)}+ />+ <label htmlFor="unclear">Unclear</label>+ </div>+ </FormItem>+ )}+ />+ )}++ <FormField+ control={control}+ name="comments"+ render={({ field }) => (+ <FormItem className="my-3">+ <div className="flex flex-col gap-3">+ <div>Other information</div>+ <Textarea+ {...register('comments')}+ placeholder="Any extra information to help our moderator team when reviewing this report."+ />+ </div>+ </FormItem>+ )}+ />+ </div>++ <DialogFooter>+ <Button+ onClick={(e) => {+ e.preventDefault();+ setShow(false);+ }}+ variant="outline"+ >+ Cancel+ </Button>+ <Button type="submit">Send report</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/aot/src/components/report-dialog/report-dialog.action.ts b/apps/aot/src/components/report-dialog/report-dialog.action.tsnew file mode 100644index 00000000..ab795a83--- /dev/null+++ b/apps/aot/src/components/report-dialog/report-dialog.action.ts@@ -0,0 +1,126 @@+'use server';++import { auth } from '~/server/auth';+import { prisma } from '@repo/db';+import { type Prisma, type Report } from '@repo/db/types';++export interface ReportBase {+ issues: Prisma.ReportIssueCreateWithoutReportInput[];+}++export type ChallengeReport = Omit<+ Report,+ | 'commentId'+ | 'createdAt'+ | 'id'+ | 'reporterId'+ | 'solutionId'+ | 'status'+ | 'type'+ | 'updatedAt'+ | 'userId'+> &+ ReportBase & { type: 'CHALLENGE' };++export type UserReport = Omit<+ Report,+ | 'challengeId'+ | 'commentId'+ | 'createdAt'+ | 'id'+ | 'reporterId'+ | 'solutionId'+ | 'status'+ | 'type'+ | 'updatedAt'+> &+ ReportBase & { type: 'USER' };++export type CommentReport = Omit<+ Report,+ | 'challengeId'+ | 'createdAt'+ | 'id'+ | 'reporterId'+ | 'solutionId'+ | 'status'+ | 'type'+ | 'updatedAt'+ | 'userId'+> &+ ReportBase & { type: 'COMMENT' };++export type SolutionReport = Omit<+ Report,+ | 'challengeId'+ | 'commentId'+ | 'createdAt'+ | 'id'+ | 'reporterId'+ | 'status'+ | 'type'+ | 'updatedAt'+ | 'userId'+> &+ ReportBase & { type: 'SOLUTION' };+/**+ * @param report a report object specific to a user, challenge, or comment report type+ * @returns 'created' if successful, 'not_logged_in' if the user is not logged in, and 'already_exists' if there's a pending report of the same type by the same user.+ */+export async function addReport(+ report: ChallengeReport | CommentReport | SolutionReport | UserReport,+) {+ const reporter = await auth();+ if (!reporter?.user?.id) return 'not_logged_in';++ let filterData;+ switch (report.type) {+ case 'CHALLENGE':+ filterData = {+ challengeId: report.challengeId,+ };+ break;+ case 'COMMENT':+ filterData = {+ commentId: report.commentId,+ };+ break;+ case 'USER':+ filterData = {+ userId: report.userId,+ };+ break;+ case 'SOLUTION':+ filterData = {+ solutionId: report.solutionId,+ };+ break;+ }++ const alreadyReported = await prisma.report.findFirst({+ where: {+ type: report.type,+ status: 'PENDING',+ reporterId: reporter.user.id,+ ...filterData,+ },+ });++ if (alreadyReported) return 'already_exists';++ await prisma.report.create({+ data: {+ reporterId: reporter.user.id,+ updatedAt: new Date(),+ ...report,+ issues: {+ createMany: {+ data: report.issues,+ },+ },+ status: 'PENDING',+ },+ });++ return 'created';+}diff --git a/apps/aot/src/components/share-url.tsx b/apps/aot/src/components/share-url.tsxnew file mode 100644index 00000000..09215505--- /dev/null+++ b/apps/aot/src/components/share-url.tsx@@ -0,0 +1,99 @@+'use client';+import { Checkbox } from '@repo/ui/components/checkbox';+import { DialogFooter } from '@repo/ui/components/dialog';+import { useToast } from '@repo/ui/components/use-toast';+import { CheckCircle2, Clipboard } from '@repo/ui/icons';+import lzstring from 'lz-string';+import { useParams } from 'next/navigation';+import { useCallback, useState } from 'react';+import { useLocalStorage } from '~/utils/useLocalStorage';++export function ShareUrl({ code, description }: { code?: string; description?: string }) {+ const { year, day } = useParams();+ const { toast } = useToast();+ const [state, setState] = useState<'copied' | 'idle' | 'loading'>('idle');+ // enable copy with code by default on playground, or we are provided with code+ const [copyWithCode, setCopyWithCode] = useState(Boolean(code));+ const [localStorageCode] = useLocalStorage(`challenge-${year}-${day}`, '');+ const url = `${window.location.origin}/events/${year}/${day}`;++ const genShortUrl = useCallback(async () => {+ let long = url;+ const codeToCopy = code ?? localStorageCode;+ if (copyWithCode && codeToCopy) {+ const compressedCode = lzstring.compressToEncodedURIComponent(codeToCopy);+ long += `?code=${compressedCode}`;+ }+ return long;+ }, [url, localStorageCode, code, copyWithCode]);++ const copyToClipboard = useCallback(async () => {+ setState('loading');+ const short = await genShortUrl();+ try {+ if (navigator.clipboard) {+ await navigator.clipboard.writeText(short);+ setState('copied');+ toast({+ title: 'URL Copied!!',+ description: 'Share url is copied to your clipboard.',+ });+ window.setTimeout(() => setState('idle'), 3000);+ }+ } catch (e) {+ console.error('copyToClipboard', e);+ setState('idle');+ toast({+ title: 'Copy Failed!!',+ variant: 'destructive',+ });+ }+ }, [genShortUrl, toast]);++ const onCopyWithCodeChange = useCallback((checked: boolean) => {+ setCopyWithCode(checked);+ }, []);++ return (+ <div className="flex flex-col space-y-4">+ <p>{description ?? 'Copy this url to share with your friends!'}</p>+ <code+ aria-disabled={state === 'loading'}+ className="break-all rounded-lg border border-black/20 bg-white px-4 py-2 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 dark:border-white/20 dark:bg-black"+ >+ {url}+ </code>+ <DialogFooter>+ <div className="flex items-center justify-end gap-2">+ {localStorageCode && !code ? (+ <div className="flex h-fit items-center justify-center gap-2 text-xs">+ <Checkbox+ id="copy-with-code"+ checked={copyWithCode}+ onCheckedChange={onCopyWithCodeChange}+ />+ <label htmlFor="copy-with-code">Copy with code</label>+ </div>+ ) : null}+ <button+ disabled={state === 'loading'}+ className={`flex items-center justify-between space-x-2 rounded-lg px-2 py-1 duration-300 active:scale-75 disabled:cursor-not-allowed disabled:opacity-50+ ${+ state === 'copied'+ ? 'border border-green-500 text-green-500 dark:border-green-700 dark:bg-green-700 dark:text-white'+ : 'border border-black/20 text-black hover:bg-gray-100 dark:bg-white'+ }`}+ onClick={copyToClipboard}+ >+ <span>{state === 'copied' ? 'Copied!' : 'Copy'}</span>+ {state === 'copied' ? (+ <CheckCircle2 className="h-4 w-4" />+ ) : (+ <Clipboard className="h-4 w-4" />+ )}+ </button>+ </div>+ </DialogFooter>+ </div>+ );+}diff --git a/apps/aot/src/server/api/routers/event.ts b/apps/aot/src/server/api/routers/event.tsindex 326d7cbb..91e8a78b 100644--- a/apps/aot/src/server/api/routers/event.ts+++ b/apps/aot/src/server/api/routers/event.ts@@ -1,5 +1,6 @@import { z } from 'zod';import { createTRPCRouter, publicProcedure } from '~/server/api/trpc';+import { validateCompilerOptions } from '~/utils/validateCompilerOptions';const AOT_TRACKS = ['advent-of-typescript-2023', 'advent-of-typescript-2024'];export const eventRouter = createTRPCRouter({@@ -13,6 +14,7 @@ export const eventRouter = createTRPCRouter({});return aotEvents;}),+ // todo: make a challenge routegetEventChallengeBySlug: publicProcedure.input(z.object({@@ -21,13 +23,55 @@ export const eventRouter = createTRPCRouter({).query(async ({ ctx, input }) => {// @TODO: actually select fields- const challenges = await ctx.db.challenge.findFirstOrThrow({+ const challenge = await ctx.db.challenge.findFirstOrThrow({where: {slug: input.slug,},+ include: {+ user: {+ select: {+ id: true,+ name: true,+ roles: true,+ bio: true,+ image: true,+ },+ },+ _count: {+ select: {+ vote: true,+ },+ },+ vote: {+ where: {+ userId: ctx.session?.user?.id || '',+ },+ },+ bookmark: {+ where: {+ userId: ctx.session?.user?.id || '',+ },+ },+ submission: {+ where: {+ userId: ctx.session?.user?.id || '',+ isSuccessful: true,+ },+ take: 1,+ },+ },});- return challenges;+ const tsconfig = challenge.tsconfig;+ if (!validateCompilerOptions(tsconfig)) {+ throw new Error(`Challenge "${challenge.slug}" has an invalid tsconfig`);+ }++ return {+ ...challenge,+ tsconfig,+ hasSolved: challenge.submission.length > 0,+ };}),getEventChallengesByYear: publicProcedure.input(diff --git a/apps/aot/src/trpc/react.tsx b/apps/aot/src/trpc/react.tsxindex 96cbfa63..a01459b0 100644--- a/apps/aot/src/trpc/react.tsx+++ b/apps/aot/src/trpc/react.tsx@@ -1,6 +1,7 @@'use client';import { QueryClientProvider, type QueryClient } from '@tanstack/react-query';+import { ReactQueryDevtools } from '@tanstack/react-query-devtools';import { loggerLink, unstable_httpBatchStreamLink } from '@trpc/client';import { createTRPCReact } from '@trpc/react-query';import { type inferRouterInputs, type inferRouterOutputs } from '@trpc/server';@@ -62,6 +63,7 @@ export function TRPCReactProvider(props: { children: React.ReactNode }) {return (<QueryClientProvider client={queryClient}>+ <ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" /><api.Provider client={trpcClient} queryClient={queryClient}>{props.children}</api.Provider>diff --git a/apps/aot/src/utils/antiProfanityZod.ts b/apps/aot/src/utils/antiProfanityZod.tsnew file mode 100644index 00000000..198e45f8--- /dev/null+++ b/apps/aot/src/utils/antiProfanityZod.ts@@ -0,0 +1,13 @@+import type { ZodString } from 'zod';+import { z } from 'zod';+import { containsProfanity } from './profanity';++// throws if string contains profanity, uses custom validate function+export function createNoProfanitySchemaWithValidate(validate: (zodString: ZodString) => ZodString) {+ return validate(z.string()).refine((str) => !containsProfanity(str), "Don't use profanity.");+}++// throws if string contains profanity, no other checks+export function createNoProfanitySchema() {+ return z.string().refine((str) => !containsProfanity(str), "Don't use profanity.");+}diff --git a/apps/aot/src/utils/auth-guards.ts b/apps/aot/src/utils/auth-guards.tsnew file mode 100644index 00000000..8d20af78--- /dev/null+++ b/apps/aot/src/utils/auth-guards.ts@@ -0,0 +1,15 @@+import type { Session } from '@repo/auth/server';+import { RoleTypes } from '@repo/db/types';++export function isAdminOrModerator(session: Session | null) {+ return [RoleTypes.ADMIN, RoleTypes.MODERATOR].some((i) => session?.user?.role.includes(i));+}++export function isAuthor(session: Session | null, userId?: string | null) {+ return Boolean(userId && session?.user?.id && userId === session?.user?.id);+}++export function isAdmin(session: Session | null) {+ if (!session) return false;+ return session.user.role.includes(RoleTypes.ADMIN);+}diff --git a/apps/aot/src/utils/bad-word-overrides.json b/apps/aot/src/utils/bad-word-overrides.jsonnew file mode 100644index 00000000..e7e82f71--- /dev/null+++ b/apps/aot/src/utils/bad-word-overrides.json@@ -0,0 +1 @@+["sh!t", "h3ll", "f*ck", "fucki"]diff --git a/apps/aot/src/utils/default-avatar.tsx b/apps/aot/src/utils/default-avatar.tsxnew file mode 100644index 00000000..65b32323--- /dev/null+++ b/apps/aot/src/utils/default-avatar.tsx@@ -0,0 +1,34 @@+import type { ComponentProps } from 'react';++export function DefaultAvatar(props: ComponentProps<'svg'>) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 200 200"+ fill="none"+ shape-rendering="auto"+ width={50}+ height={50}+ {...props}+ >+ <mask id="viewboxMask">+ <rect width="200" height="200" rx="0" ry="0" x="0" y="0" fill="#fff" />+ </mask>+ <g mask="url(#viewboxMask)">+ <rect fill="#71cf62" width="200" height="200" x="0" y="0" />+ <g transform="matrix(1.5625 0 0 1.5625 37.5 110.94)">+ <path+ d="M40.54 30h-.75c-9.7-.22-20.8-5.3-23.7-16.15a1.36 1.36 0 0 1 .44-1.55 1.41 1.41 0 0 1 2.26.86c2.55 9.46 12.42 13.89 21.06 14.08 8.24.16 19.04-3.84 22.46-14.57a1.47 1.47 0 0 1 1.65-.55A1.44 1.44 0 0 1 65 13.5C61.85 23.31 52.3 30 40.54 30Z"+ fill="#000"+ />+ </g>+ <g transform="matrix(1.5625 0 0 1.5625 31.25 59.38)">+ <path+ d="M75.84 21.11c-2.9.04-5.72-.89-8.04-2.63a13.47 13.47 0 0 1-4.85-7.03 1.75 1.75 0 0 1 1.1-2.26 1.68 1.68 0 0 1 1.86.61c.14.2.24.4.3.64.6 2.11 1.87 3.97 3.61 5.28a9.84 9.84 0 0 0 6.04 1.98c2.17.01 4.29-.68 6.03-2a10.17 10.17 0 0 0 3.65-5.26c.15-.42.46-.75.85-.95a1.68 1.68 0 0 1 2.23.7c.21.38.27.83.17 1.26a13.48 13.48 0 0 1-4.87 7.04 13.17 13.17 0 0 1-8.08 2.62ZM13.84 21.11c-2.9.03-5.73-.9-8.06-2.65a13.54 13.54 0 0 1-4.85-7.05 1.78 1.78 0 0 1 .51-1.88 1.67 1.67 0 0 1 2.4.22c.15.17.25.38.32.6.62 2.1 1.9 3.96 3.64 5.28a9.93 9.93 0 0 0 6.02 2c2.18.03 4.3-.67 6.06-1.99a10.21 10.21 0 0 0 3.66-5.3 1.68 1.68 0 0 1 3.08-.25c.21.4.27.85.17 1.27a13.57 13.57 0 0 1-4.86 7.1 13.19 13.19 0 0 1-8.1 2.65Z"+ fill="#000"+ />+ </g>+ </g>+ </svg>+ );+}diff --git a/apps/aot/src/utils/getAotSlug.ts b/apps/aot/src/utils/getAotSlug.tsnew file mode 100644index 00000000..b47be290--- /dev/null+++ b/apps/aot/src/utils/getAotSlug.ts@@ -0,0 +1,3 @@+export function getAotSlug({ year, day }: { year: string; day: string }) {+ return `${year}-${day}`;+}diff --git a/apps/aot/src/utils/getBaseUrl.ts b/apps/aot/src/utils/getBaseUrl.tsnew file mode 100644index 00000000..a12d2cae--- /dev/null+++ b/apps/aot/src/utils/getBaseUrl.ts@@ -0,0 +1,19 @@+export function getBaseUrl() {+ if (typeof window !== 'undefined') {+ // In the browser, we return a relative URL+ return '';+ }+ // When rendering on the server, we return an absolute URL++ // reference: https://vercel.com/docs/projects/environment-variables/system-environment-variables#system-environment-variables+ if (process.env.VERCEL_PROJECT_PRODUCTION_URL && process.env.VERCEL_ENV === 'production') {+ return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;+ }++ if (process.env.VERCEL_URL && process.env.VERCEL_ENV === 'preview') {+ return `https://${process.env.VERCEL_URL}`;+ }++ // assume localhost+ return `http://localhost:${process.env.PORT ?? 3000}`;+}diff --git a/apps/aot/src/utils/metadata.ts b/apps/aot/src/utils/metadata.tsnew file mode 100644index 00000000..b19b315d--- /dev/null+++ b/apps/aot/src/utils/metadata.ts@@ -0,0 +1,170 @@+import type { Metadata } from 'next';+import { challengeParam, userParam } from '@repo/og-utils';++export const OG_URL =+ process.env.NODE_ENV !== 'production' ? 'http://localhost:4200' : 'https://og.typehero.dev';++export const tagline = 'Level up and learn TypeScript with interactive exercises';+export const baseMetadata: Metadata = {+ metadataBase: new URL(OG_URL),+ title: {+ default: 'TypeHero',+ template: '%s',+ },+ robots: {+ index: true,+ follow: true,+ },+ description: tagline,+ openGraph: {+ title: 'TypeHero',+ description: tagline,+ siteName: 'TypeHero',+ images: [+ {+ url: `${OG_URL}/api/default`,+ width: 1920,+ height: 1080,+ },+ ],+ locale: 'en-US',+ type: 'website',+ },+ twitter: {+ title: 'TypeHero',+ card: 'summary_large_image',+ images: [+ {+ url: `${OG_URL}/api/default`,+ width: 1920,+ height: 1080,+ },+ ],+ },+ icons: {+ shortcut: '/favicon.ico',+ },+};++// TODO: infer from ZOD+interface MetaParamsForChallenge {+ title: string;+ description: string;+ username: string;+ difficulty: 'BEGINNER' | 'EASY' | 'EVENT' | 'EXTREME' | 'HARD' | 'MEDIUM';+ date: string;+}++interface MetaParamsForUser {+ title: string;+ description: string;+ username: string;+ avatar: string;+ dateSince: string;+}+/** Helper to build opengraph metadata for a user, you should call this in generateMetadata() next function */+export const buildMetaForUser = async ({+ title,+ description,+ username,+ dateSince,+ avatar,+}: MetaParamsForUser): Promise<Metadata> => {+ const params = `${userParam.toSearchString({+ username,+ avatar,+ dateSince,+ })}`;++ const ogImageUrl = `${OG_URL}/api/user?${params}`;++ return buildMeta({+ ogImageUrl,+ title,+ description,+ });+};++/** Helper to build opengraph metadata for a challenge, you should call this in generateMetadata() next function */+export const buildMetaForChallenge = async ({+ title,+ description,+ username,+ difficulty,+ date,+}: MetaParamsForChallenge): Promise<Metadata> => {+ const params = `${challengeParam.toSearchString({+ description,+ title,+ username,+ difficulty,+ date,+ })}`;++ const ogImageUrl = `${OG_URL}/api/challenge?${params}`;++ return buildMeta({+ ogImageUrl,+ title,+ description,+ });+};++/** Helper to build opengraph metadata with defaults, you should call this in generateMetadata() next function */+export const buildMetaForDefault = async ({+ title,+ description,+}: {+ title?: string;+ description?: string;+}): Promise<Metadata> => {+ return buildMeta({+ ogImageUrl: `${OG_URL}/api/default?cache-bust=${new Date().getDate()}`,+ title,+ description,+ });+};++export const buildMetaForEventPage = async ({+ title,+ description,+}: {+ title?: string;+ description?: string;+}): Promise<Metadata> => {+ return buildMeta({+ ogImageUrl: `${OG_URL}/api/aot-2023`,+ title,+ description,+ });+};++/** update the metadata for og */+const buildMeta = async ({+ ogImageUrl,+ description,+ title,+}: {+ ogImageUrl: string;+ description?: string;+ title?: string;+}): Promise<Metadata> => {+ baseMetadata.openGraph!.images = ogImageUrl;+ baseMetadata.twitter!.images = ogImageUrl;++ if (description) {+ baseMetadata.description = description;+ baseMetadata.twitter!.description = description;+ baseMetadata.openGraph!.description = description;+ }++ if (title) {+ baseMetadata.title = title;+ baseMetadata.twitter!.title = title;+ baseMetadata.openGraph!.title = title;+ }++ return baseMetadata;+};++export default baseMetadata;diff --git a/apps/aot/src/utils/profanity.ts b/apps/aot/src/utils/profanity.tsnew file mode 100644index 00000000..c58cf17e--- /dev/null+++ b/apps/aot/src/utils/profanity.ts@@ -0,0 +1,9 @@+import Filter from 'bad-words';+import overrideWords from './bad-word-overrides.json';++const f = new Filter();+f.addWords(...overrideWords);++export function containsProfanity(str: string): boolean {+ return f.isProfane(str);+}diff --git a/apps/aot/src/utils/rateLimit.ts b/apps/aot/src/utils/rateLimit.tsnew file mode 100644index 00000000..1d8fedc0--- /dev/null+++ b/apps/aot/src/utils/rateLimit.ts@@ -0,0 +1,31 @@+const idToRequestCount = new Map<string, number>(); // keeps track of individual users+const rateLimiter = {+ windowStart: Date.now(),+ windowSize: 60 * 60 * 1000,+ maxRequests: 30,+};+// Max 30 requests per hour per user by default++interface RateLimiterConfig {+ windowStart?: number;+ windowSize?: number;+ maxRequests?: number;+}++export const rateLimit = (ip: string, config = {} as RateLimiterConfig) => {+ const { windowStart, windowSize, maxRequests } = { ...rateLimiter, ...config };+ // Check and update current window+ const now = Date.now();+ const isNewWindow = now - windowStart > windowSize;+ if (isNewWindow) {+ config.windowStart = now;+ idToRequestCount.set(ip, 0);+ }++ // Check and update current request limits+ const currentRequestCount = idToRequestCount.get(ip) ?? 0;+ if (currentRequestCount >= maxRequests) return true;+ idToRequestCount.set(ip, currentRequestCount + 1);++ return false;+};diff --git a/apps/aot/src/utils/relativeTime.ts b/apps/aot/src/utils/relativeTime.tsnew file mode 100644index 00000000..40450ef6--- /dev/null+++ b/apps/aot/src/utils/relativeTime.ts@@ -0,0 +1,15 @@+import { formatDistanceToNow, formatDistanceToNowStrict } from 'date-fns';++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/aot/src/utils/sorting.ts b/apps/aot/src/utils/sorting.tsnew file mode 100644index 00000000..05ea3d03--- /dev/null+++ b/apps/aot/src/utils/sorting.ts@@ -0,0 +1,32 @@+const sortingKeys = ['createdAt', 'vote', 'replies', 'solutionComment'] as const;+const sortingOrders = ['asc', 'desc'] as const;++export type SortKey = (typeof sortingKeys)[number];+export type SortOrder = (typeof sortingOrders)[number];++export function orderBy(sortKey: SortKey, sortOrder: SortOrder) {+ switch (sortKey) {+ case 'vote':+ return {+ vote: {+ _count: sortOrder,+ },+ };+ case 'replies':+ return {+ replies: {+ _count: sortOrder,+ },+ };+ case 'createdAt':+ return {+ [sortKey]: sortOrder,+ };+ case 'solutionComment':+ return {+ solutionComment: {+ _count: sortOrder,+ },+ };+ }+}diff --git a/apps/aot/src/utils/useDebouncedValue.ts b/apps/aot/src/utils/useDebouncedValue.tsnew file mode 100644index 00000000..c9303a35--- /dev/null+++ b/apps/aot/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/apps/aot/src/utils/useLocalStorage.ts b/apps/aot/src/utils/useLocalStorage.tsnew file mode 100644index 00000000..4966ed9d--- /dev/null+++ b/apps/aot/src/utils/useLocalStorage.ts@@ -0,0 +1,28 @@+import { useState } from 'react';++export function useLocalStorage(key: string, initialValue: string): [string, (v: string) => void] {+ const [storedValue, setStoredValue] = useState<string>(() => {+ try {+ if (typeof window !== 'undefined') {+ return window.localStorage.getItem(key) || initialValue;+ }+ return initialValue;+ } catch (error) {+ console.error(error);+ return initialValue;+ }+ });++ const setValue = (value: string) => {+ try {+ setStoredValue(value);+ window.localStorage.setItem(key, value);++ localStorage.setItem(key, value);+ } catch (error) {+ console.error(error);+ }+ };++ return [storedValue, setValue];+}diff --git a/apps/aot/src/utils/useUploadthing.ts b/apps/aot/src/utils/useUploadthing.tsnew file mode 100644index 00000000..bece044c--- /dev/null+++ b/apps/aot/src/utils/useUploadthing.ts@@ -0,0 +1,4 @@+import { generateReactHelpers } from '@uploadthing/react/hooks';+import type { OurFileRouter } from '~/app/api/uploadthing/core';++export const { useUploadThing, uploadFiles } = generateReactHelpers<OurFileRouter>();diff --git a/apps/aot/src/utils/validateCompilerOptions.ts b/apps/aot/src/utils/validateCompilerOptions.tsnew file mode 100644index 00000000..e0c98666--- /dev/null+++ b/apps/aot/src/utils/validateCompilerOptions.ts@@ -0,0 +1,6 @@+import type * as monaco from 'monaco-editor';++export const validateCompilerOptions = (value: unknown): value is TSCompilerOptions =>+ value == null || (typeof value === 'object' && !Array.isArray(value));++export type TSCompilerOptions = monaco.languages.typescript.CompilerOptions | undefined;diff --git a/apps/aot/src/utils/withUnstableCache.ts b/apps/aot/src/utils/withUnstableCache.tsnew file mode 100644index 00000000..2a4e13cf--- /dev/null+++ b/apps/aot/src/utils/withUnstableCache.ts@@ -0,0 +1,20 @@+import { unstable_cache } from 'next/cache';++// eslint-disable-next-line+export async function withUnstableCache<T extends (...args: any[]) => Promise<any>>(opts: {+ fn: T;+ args: Parameters<T>;+ keys: string[];+ tags: string[];+}) {+ const cachedResult = await unstable_cache(+ async (...args) => {+ const result = await opts.fn(...args);+ return result;+ },+ [...opts.keys],+ { tags: opts.tags },+ )(...opts.args);++ return cachedResult as Awaited<ReturnType<T>>;+}diff --git a/apps/aot/src/utils/zodSingleStringField.ts b/apps/aot/src/utils/zodSingleStringField.tsnew file mode 100644index 00000000..03865f60--- /dev/null+++ b/apps/aot/src/utils/zodSingleStringField.ts@@ -0,0 +1,8 @@+import { createNoProfanitySchemaWithValidate } from './antiProfanityZod';+import { z } from 'zod';++export const singleFieldSchema = z.object({+ text: createNoProfanitySchemaWithValidate((zed) => zed.min(1, 'Too short.')),+});++export type SingleFieldSchema = z.infer<typeof singleFieldSchema>;diff --git a/apps/aot/tailwind.config.ts b/apps/aot/tailwind.config.tsindex ac0ff7f7..d8aed1b0 100644--- a/apps/aot/tailwind.config.ts+++ b/apps/aot/tailwind.config.ts@@ -5,11 +5,7 @@ const { fontFamily } =/** @type {import('tailwindcss').Config} */module.exports = {darkMode: ['class'],- content: [- './app/**/*.{js,ts,jsx,tsx,mdx}',- 'src/**/*.{ts,tsx}',- '../../packages/{ui,monaco}/**/*.{ts,tsx}',- ],+ content: ['src/**/*.{ts,tsx}', '../../packages/{ui,monaco}/**/*.{ts,tsx}'],theme: {extend: {screens: {diff --git a/apps/aot/tsconfig.json b/apps/aot/tsconfig.jsonindex 35c50780..8d5f2805 100644--- a/apps/aot/tsconfig.json+++ b/apps/aot/tsconfig.json@@ -25,8 +25,7 @@// to make sure `@repo/monaco` doesn't break"../../packages/monaco/monaco-editor.d.ts","../../packages/monaco/monaco-vim.d.ts",- "postcss.config.mjs","postcss.config.mjs"],- "exclude": ["node_modules", ".next", "public", "playwright-report"]+ "exclude": ["node_modules", ".next", "public"]}diff --git a/apps/web/src/app/(playgrounds)/challenge-playground/description.tsx b/apps/web/src/app/(playgrounds)/challenge-playground/description.tsxindex 6bcc599f..b42005d8 100644--- a/apps/web/src/app/(playgrounds)/challenge-playground/description.tsx+++ b/apps/web/src/app/(playgrounds)/challenge-playground/description.tsx@@ -1,7 +1,8 @@'use client';-import { RichMarkdownEditor } from '~/components/rich-markdown-editor';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';import { useChallengePlaygroundStore } from './challenge-playground-store';+import { useUploadThing } from '~/utils/useUploadthing';export function Description() {const { values, updateValues } = useChallengePlaygroundStore();@@ -9,6 +10,7 @@ export function Description() {<RichMarkdownEditoronChange={(v) => updateValues({ ...values, prompt: v as string })}value={values.prompt}+ useUploadThing={useUploadThing}/>);}diff --git a/apps/web/src/app/challenge/[slug]/solutions/_components/edit-solution.tsx b/apps/web/src/app/challenge/[slug]/solutions/_components/edit-solution.tsxindex 0a3c9bdf..d890cf1c 100644--- a/apps/web/src/app/challenge/[slug]/solutions/_components/edit-solution.tsx+++ b/apps/web/src/app/challenge/[slug]/solutions/_components/edit-solution.tsx@@ -8,10 +8,11 @@ import { useTheme } from 'next-themes';import { useParams } from 'next/navigation';import { useForm } from 'react-hook-form';import { z } from 'zod';-import { RichMarkdownEditor } from '~/components/rich-markdown-editor';import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';import type { ChallengeSolution } from '~/app/challenge/[slug]/solutions/[solutionId]/page';import { updateSolution } from './_actions';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';+import { useUploadThing } from '~/utils/useUploadthing';const formSchema = z.object({title: createNoProfanitySchemaWithValidate((zodString) =>@@ -118,6 +119,7 @@ export function EditSolution({ solution, setIsEditing }: Props) {value={field.value}// non-split-screen by defaultonChange={field.onChange}+ useUploadThing={useUploadThing}/><FormMessage /></FormItem>diff --git a/apps/web/src/app/challenge/[slug]/solutions/_components/solution-editor.tsx b/apps/web/src/app/challenge/[slug]/solutions/_components/solution-editor.tsxindex e855a65c..1d3b983f 100644--- a/apps/web/src/app/challenge/[slug]/solutions/_components/solution-editor.tsx+++ b/apps/web/src/app/challenge/[slug]/solutions/_components/solution-editor.tsx@@ -8,10 +8,11 @@ import { useTheme } from 'next-themes';import { useParams } from 'next/navigation';import { useForm } from 'react-hook-form';import { z } from 'zod';-import { RichMarkdownEditor } from '~/components/rich-markdown-editor';import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';import { postSolution } from './_actions';import { useQueryClient } from '@tanstack/react-query';+import { useUploadThing } from '~/utils/useUploadthing';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';const getDefaultMarkdown = (solution: string) => `## Thoughts@@ -142,6 +143,7 @@ export function SolutionEditor({ dismiss, challengeId, code }: Props) {value={field.value}// non-split-screen by defaultonChange={field.onChange}+ useUploadThing={useUploadThing}/><FormMessage /></FormItem>diff --git a/apps/web/src/app/challenge/_components/vote.tsx b/apps/web/src/app/challenge/_components/vote.tsxindex 6a3b34b1..066054d7 100644--- a/apps/web/src/app/challenge/_components/vote.tsx+++ b/apps/web/src/app/challenge/_components/vote.tsx@@ -1,31 +1,16 @@'use client';import { useSession } from '@repo/auth/react';-import type { Comment, VoteType } from '@repo/db/types';+import type { VoteType } from '@repo/db/types';+import { Button } from '@repo/ui/components/button';+import { Tooltip, TooltipContent, TooltipTrigger } from '@repo/ui/components/tooltip';import { ThumbsUp } from '@repo/ui/icons';import clsx from 'clsx';import { debounce } from 'lodash';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;diff --git a/apps/web/src/app/wizard/_components/DescriptionEditor.tsx b/apps/web/src/app/wizard/_components/DescriptionEditor.tsxindex 8f6b8414..8a770d63 100644--- a/apps/web/src/app/wizard/_components/DescriptionEditor.tsx+++ b/apps/web/src/app/wizard/_components/DescriptionEditor.tsx@@ -1,11 +1,12 @@'use client';-import { useWatch } from 'react-hook-form';import { FormField, FormItem, FormMessage } from '@repo/ui/components/form';-import { TypographyH3 } from '@repo/ui/components/typography/h3';import { Markdown } from '@repo/ui/components/markdown';+import { RichMarkdownEditor } from '@repo/ui/components/rich-markdown-editor';+import { TypographyH3 } from '@repo/ui/components/typography/h3';+import { useWatch } from 'react-hook-form';+import { useUploadThing } from '~/utils/useUploadthing';import { type WizardForm } from '.';-import { RichMarkdownEditor } from '~/components/rich-markdown-editor';interface Props {form: WizardForm;@@ -30,6 +31,7 @@ export function DescriptionEditor({ form }: Props) {allowImageUploadonChange={field.onChange}value={field.value}+ useUploadThing={useUploadThing}/></FormItem><FormMessage className="p-2 pt-0" />diff --git a/apps/web/src/utils/domUtils.ts b/apps/web/src/utils/domUtils.tsdeleted file mode 100644index 81184439..00000000--- a/apps/web/src/utils/domUtils.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * This will insert the given text at the caret position into the textarea element- */-export function insertText(newText: string, textarea: HTMLTextAreaElement) {- // @ts-ignore - i don't care that you error- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(- window.HTMLTextAreaElement.prototype,- 'value',- ).set;-- if (!nativeInputValueSetter) return;-- // get left value of the textarea- const left = textarea.value.substring(0, textarea.selectionStart);-- // get right value of the textarea- const right = textarea.value.substring(textarea.selectionEnd, textarea.value.length);- nativeInputValueSetter.call(textarea, left + newText + right);-- // set the caret position to the end of the new text- const newCaretPosition = left.length + newText.length;-- // make sure to keep focus on the textarea- textarea.focus();- textarea.setSelectionRange(newCaretPosition, newCaretPosition);-- const inputEvent = new Event('input', { bubbles: true });- textarea.dispatchEvent(inputEvent);-}diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.tsindex ac0ff7f7..d8aed1b0 100644--- a/apps/web/tailwind.config.ts+++ b/apps/web/tailwind.config.ts@@ -5,11 +5,7 @@ const { fontFamily } =/** @type {import('tailwindcss').Config} */module.exports = {darkMode: ['class'],- content: [- './app/**/*.{js,ts,jsx,tsx,mdx}',- 'src/**/*.{ts,tsx}',- '../../packages/{ui,monaco}/**/*.{ts,tsx}',- ],+ content: ['src/**/*.{ts,tsx}', '../../packages/{ui,monaco}/**/*.{ts,tsx}'],theme: {extend: {screens: {diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 811be583..4e8677b6 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -59,6 +59,8 @@"@radix-ui/react-tooltip": "^1.0.6","@repo/db": "workspace:*","@tanstack/react-table": "^8.20.5",+ "@uiw/react-md-editor": "^3.23.3",+ "@uploadthing/react": "^6.2.2","class-variance-authority": "^0.7.0","clsx": "^2.0.0","lucide-react": "^0.453.0",diff --git a/apps/web/src/components/rich-markdown-editor.tsx b/packages/ui/src/components/rich-markdown-editor.tsxsimilarity index 85%rename from apps/web/src/components/rich-markdown-editor.tsxrename to packages/ui/src/components/rich-markdown-editor.tsxindex 8d4630a1..4f2af4f8 100644--- a/apps/web/src/components/rich-markdown-editor.tsx+++ b/packages/ui/src/components/rich-markdown-editor.tsx@@ -1,10 +1,9 @@import { useTheme } from 'next-themes';+import type { generateReactHelpers } from '@uploadthing/react/hooks';import type { ChangeEvent } from 'react';import { useContext, useEffect, useRef, useState } from 'react';import MDEditor, { EditorContext, commands, type ICommand } from '@uiw/react-md-editor';-import { insertText } from '~/utils/domUtils';-import { useUploadThing } from '~/utils/useUploadthing';-import { toast } from '@repo/ui/components/use-toast';+import { toast } from './use-toast';const codePreview: ICommand = {name: 'preview',@@ -23,6 +22,9 @@ interface Props {* @default false*/allowImageUpload?: boolean;+ // @TODO: make the type for this+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ useUploadThing: ReturnType<typeof generateReactHelpers<any>>['useUploadThing'];}export function RichMarkdownEditor({@@ -30,6 +32,7 @@ export function RichMarkdownEditor({value,onChange,allowImageUpload = false,+ useUploadThing,}: Props) {const editorRef = useRef<typeof MDEditor>(null);const fileInputRef = useRef<HTMLInputElement>(null);@@ -266,3 +269,33 @@ function PreviewToggle() {</button>);}++/**+ * This will insert the given text at the caret position into the textarea element+ */+function insertText(newText: string, textarea: HTMLTextAreaElement) {+ // @ts-ignore - i don't care that you error+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(+ window.HTMLTextAreaElement.prototype,+ 'value',+ ).set;++ if (!nativeInputValueSetter) return;++ // get left value of the textarea+ const left = textarea.value.substring(0, textarea.selectionStart);++ // get right value of the textarea+ const right = textarea.value.substring(textarea.selectionEnd, textarea.value.length);+ nativeInputValueSetter.call(textarea, left + newText + right);++ // set the caret position to the end of the new text+ const newCaretPosition = left.length + newText.length;++ // make sure to keep focus on the textarea+ textarea.focus();+ textarea.setSelectionRange(newCaretPosition, newCaretPosition);++ const inputEvent = new Event('input', { bubbles: true });+ textarea.dispatchEvent(inputEvent);+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f60f38f7..deed8d7c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -91,10 +91,10 @@ importers:version: 2.6.0-beta.12next:specifier: 14.2.5- version: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ version: 14.2.5(@babel/[email protected])([email protected]([email protected]))([email protected])next-themes:specifier: ^0.2.1- version: 0.2.1([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 0.2.1([email protected](@babel/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])react:specifier: 18.2.0version: 18.2.0@@ -158,7 +158,7 @@ importers:version: 13.4.10([email protected])([email protected])eslint-plugin-import:specifier: ^2.27.5- version: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])+ version: 2.27.5([email protected])postcss:specifier: ^8.4.31version: 8.4.31@@ -177,9 +177,30 @@ importers:apps/aot:dependencies:+ '@hookform/resolvers':+ specifier: ^3.1.1+ version: 3.1.1([email protected]([email protected]))+ '@radix-ui/react-dialog':+ specifier: ^1.0.4+ version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ '@repo/auth':+ specifier: workspace:*+ version: link:../../packages/auth+ '@repo/db':+ specifier: workspace:*+ version: link:../../packages/db+ '@repo/monaco':+ specifier: workspace:*+ version: link:../../packages/monaco+ '@repo/ui':+ specifier: workspace:*+ version: link:../../packages/ui'@tanstack/react-query':specifier: 5.51.21version: 5.51.21([email protected])+ '@tanstack/react-query-devtools':+ specifier: 5.51.21'@tanstack/react-table':specifier: ^8.20.5@@ -192,15 +213,33 @@ importers:'@trpc/server':specifier: ^11.0.0-rc.446version: 11.0.0-rc.477+ '@uploadthing/react':+ specifier: ^6.2.2+ version: 6.2.2(@uploadthing/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])'@vercel/edge-config':specifier: ^0.2.1version: 0.2.1+ bad-words:+ specifier: ^3.0.4+ version: 3.0.4clsx:specifier: ^2.0.0version: 2.0.0+ date-fns:+ specifier: ^2.30.0+ version: 2.30.0+ lodash:+ specifier: ^4.17.21+ version: 4.17.21+ lz-string:+ specifier: ^1.5.0+ version: 1.5.0+ nanoid:+ specifier: ^5.0.7+ version: 5.0.7next:specifier: 14.2.5- version: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ version: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])next-themes:specifier: ^0.2.1version: 0.2.1([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])@@ -210,37 +249,34 @@ importers:react-dom:specifier: 18.2.0version: 18.2.0([email protected])+ react-hook-form:+ specifier: ^7.45.1+ version: 7.45.1([email protected])server-only:specifier: ^0.0.1version: 0.0.1superjson:specifier: ^2.2.1version: 2.2.1+ uploadthing:+ specifier: 6.3.1+ version: 6.3.1zod:specifier: 3.23.3version: 3.23.3+ zustand:+ specifier: ^4.3.9+ version: 4.3.9([email protected])devDependencies:- '@repo/auth':- specifier: workspace:*- version: link:../../packages/auth- '@repo/db':- specifier: workspace:*- version: link:../../packages/db'@repo/lint':specifier: workspace:*version: link:../../tooling/config-eslint- '@repo/monaco':- specifier: workspace:*- version: link:../../packages/monaco'@repo/og-utils':specifier: workspace:*version: link:../../packages/og-utils'@repo/tsconfig':specifier: workspace:*version: link:../../tooling/config-typescript- '@repo/ui':- specifier: workspace:*- version: link:../../packages/ui'@tailwindcss/container-queries':specifier: ^0.1.1version: 0.1.1([email protected])@@ -268,6 +304,12 @@ importers:postcss:specifier: ^8.4.31version: 8.4.31+ prettier:+ specifier: ^3.1.1+ version: 3.1.1+ prettier-plugin-tailwindcss:+ specifier: ^0.5.9+ version: 0.5.9([email protected])tailwindcss:specifier: 3.4.7version: 3.4.7@@ -310,7 +352,7 @@ importers:version: 1.0.0next:specifier: 14.2.5- version: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ version: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react:specifier: 18.2.0version: 18.2.0@@ -386,7 +428,7 @@ importers:version: link:../../packages/ui'@sentry/nextjs':specifier: ^7.73.0- version: 7.73.0([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 7.73.0([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])'@stripe/react-stripe-js':specifier: ^2.8.0@@ -410,7 +452,7 @@ importers:'@uploadthing/react':specifier: ^6.2.2- version: 6.2.2(@uploadthing/[email protected])([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 6.2.2(@uploadthing/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])'@vercel/analytics':specifier: ^1.1.1version: 1.1.1@@ -419,10 +461,10 @@ importers:version: 0.2.1'@vercel/speed-insights':specifier: ^1.0.12- version: 1.0.12([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 1.0.12([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/toolbar':specifier: ^0.1.18- version: 0.1.22([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))+ version: 0.1.22([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])algoliasearch:specifier: ^4.20.0version: 4.20.0@@ -461,10 +503,10 @@ importers:version: 5.0.7next:specifier: 14.2.5- version: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ version: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])next-themes:specifier: ^0.2.1- version: 0.2.1([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 0.2.1([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])react:specifier: 18.2.0version: 18.2.0@@ -491,7 +533,7 @@ importers:react-instantsearch-nextjs:specifier: ^0.1.5- version: 0.1.5([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected]))+ version: 0.1.5([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected]))react-intersection-observer:specifier: ^9.5.2version: 9.5.2([email protected])@@ -588,7 +630,7 @@ importers:version: 13.4.10([email protected])([email protected])eslint-plugin-import:specifier: ^2.27.5- version: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])+ version: 2.27.5([email protected])postcss:specifier: ^8.4.31version: 8.4.31@@ -618,7 +660,7 @@ importers:version: link:../dbnext-auth:specifier: 5.0.0-beta.4- version: 5.0.0-beta.4([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.4([email protected]([email protected]([email protected]))([email protected]))([email protected])devDependencies:'@repo/lint':specifier: workspace:*@@ -719,10 +761,10 @@ importers:version: 0.4.0(patch_hash=j3oqxjoadtct3pc6tokddngzsm)([email protected])next:specifier: 14.2.5- version: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])next-themes:specifier: ^0.2.1- version: 0.2.1([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 0.2.1([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])prettier:specifier: ^3.1.1version: 3.1.1@@ -842,6 +884,12 @@ importers:'@tanstack/react-table':specifier: ^8.20.5+ '@uiw/react-md-editor':+ specifier: ^3.23.3+ version: 3.23.3(@types/[email protected])([email protected]([email protected]))([email protected])+ '@uploadthing/react':+ specifier: ^6.2.2+ version: 6.2.2(@uploadthing/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])class-variance-authority:specifier: ^0.7.0version: 0.7.0@@ -856,7 +904,7 @@ importers:version: 3.0.1next-themes:specifier: ^0.2.1- version: 0.2.1([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 0.2.1([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])react:specifier: 18.2.0version: 18.2.0@@ -911,7 +959,7 @@ importers:dependencies:'@next/eslint-plugin-next':specifier: canary- version: 15.0.2-canary.3+ version: 15.0.2-canary.9'@repo/tsconfig':specifier: workspace:*version: link:../config-typescript@@ -923,7 +971,7 @@ importers:version: 5.62.0([email protected])([email protected])'@vercel/style-guide':specifier: ^4.0.2eslint:specifier: ^8.45.0version: 8.45.0@@ -2026,8 +2074,8 @@ packages:'@next/[email protected]':resolution: {integrity: sha512-YJqyq6vk39JQfvaNtN83t/p5Jy45+bazRL+V4QI8FPd3FBqFYMEsULiwRLgSJMgFqkk4t4JbeZurz+gILEAFpA==}- '@next/[email protected]':- resolution: {integrity: sha512-PWI+EwalZZ/t2NMsSgq4Ixo1OhXAy8edBDVBW+WvLPTg5BkhO7+BLrsV8aE8U0y93zdUtqa3Fm472dM5cSSQwQ==}+ '@next/[email protected]':+ resolution: {integrity: sha512-mE9uZfzhmaCotUjKmg+GVu/r/xH5FdKVlUMTG9QYqd5E6UbRsz9aHE+XkBOsFaILDmMjSVBRveit8moyw4F5Fg==}'@next/[email protected]':resolution: {integrity: sha512-/9zVxJ+K9lrzSGli1///ujyRfon/ZneeZ+v4ptpiPoOU+GKZnm8Wj8ELWU1Pm7GHltYRBklmXMTUqM/DqQ99FQ==}@@ -7922,7 +7970,7 @@ packages:resolution: {integrity: sha512-VMBFLYgFuRdfeNQSMLbxGSLfmXL/xc+OO+BZp41Za/NRDBet/BNbkRJrYzCUu0u4GU0i/ml2dtT8b9qgkw9z6Q==}engines: {node: '>= 4.0'}- deprecated: Please upgrade to v9.0.0+ as we have fixed a public vulnerability with formidable dependency. Note that v9.0.0+ requires Node.js v14.18.0+. See https://github.com/ladjs/superagent/pull/1800 for insight. This project is supported and maintained by the team at Forward Email @ https://forwardemail.net+ deprecated: Please upgrade to v7.0.2+ of superagent. We have fixed numerous issues with streams, form-data, attach(), filesystem errors not bubbling up (ENOENT on attach()), and all tests are now passing. See the releases tab for more information at <https://github.com/visionmedia/superagent/releases>.resolution: {integrity: sha512-8iGv75BYOa0xRJHK5vRLEjE2H/i4lulTjzpUXic3Eg8akftYjkmQDa8JARQ42rlczXyFR3IeRoeFCc7RxHsYZA==}@@ -9597,7 +9645,7 @@ snapshots:dependencies:glob: 7.1.7- '@next/[email protected]':+ '@next/[email protected]':dependencies:fast-glob: 3.3.1@@ -11092,7 +11140,7 @@ snapshots:localforage: 1.10.0tslib: 2.6.0- '@sentry/[email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])':+ '@sentry/[email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])':dependencies:'@rollup/plugin-commonjs': 24.0.0([email protected])'@sentry/core': 7.73.0@@ -11104,7 +11152,7 @@ snapshots:'@sentry/vercel-edge': 7.73.0'@sentry/webpack-plugin': 1.20.0chalk: 3.0.0- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.2.0rollup: 2.78.0stacktrace-parser: 0.1.10@@ -11629,6 +11677,26 @@ snapshots:- '@types/react'- supports-color+ '@uiw/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.22.6+ '@uiw/copy-to-clipboard': 1.0.15+ react: 18.2.0+ react-dom: 18.3.1([email protected])+ react-markdown: 8.0.7(@types/[email protected])([email protected])+ rehype-attr: 2.1.4+ rehype-autolink-headings: 6.1.1+ rehype-ignore: 1.0.5+ rehype-prism-plus: 1.5.1+ rehype-raw: 6.1.1+ rehype-rewrite: 3.0.6+ rehype-slug: 5.1.0+ remark-gfm: 3.0.1+ unist-util-visit: 4.1.2+ transitivePeerDependencies:+ - '@types/react'+ - supports-color+'@uiw/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.22.6@@ -11640,6 +11708,17 @@ snapshots:- '@types/react'- supports-color+ '@uiw/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.22.6+ '@uiw/react-markdown-preview': 4.1.13(@types/[email protected])([email protected]([email protected]))([email protected])+ react: 18.2.0+ react-dom: 18.3.1([email protected])+ rehype: 12.0.1+ transitivePeerDependencies:+ - '@types/react'+ - supports-color+'@ungap/[email protected]': {}'@uploadthing/[email protected]':@@ -11649,7 +11728,7 @@ snapshots:'@uploadthing/[email protected]': {}- '@uploadthing/[email protected](@uploadthing/[email protected])([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])':+ '@uploadthing/[email protected](@uploadthing/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])':dependencies:'@uploadthing/dropzone': 0.1.1'@uploadthing/shared': 6.2.0(@uploadthing/[email protected])@@ -11659,7 +11738,21 @@ snapshots:tailwind-merge: 1.14.0uploadthing: 6.3.1optionalDependencies:- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])+ transitivePeerDependencies:+ - '@uploadthing/mime-types'++ '@uploadthing/[email protected](@uploadthing/[email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])':+ dependencies:+ '@uploadthing/dropzone': 0.1.1+ '@uploadthing/shared': 6.2.0(@uploadthing/[email protected])+ attr-accept: 2.2.2+ file-selector: 0.6.0+ react: 18.2.0+ tailwind-merge: 1.14.0+ uploadthing: 6.3.1+ optionalDependencies:transitivePeerDependencies:- '@uploadthing/mime-types'@@ -11702,12 +11795,12 @@ snapshots:satori: 0.0.46yoga-wasm-web: 0.3.0- '@vercel/[email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':+ '@vercel/[email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':optionalDependencies:- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.2.0- '@vercel/[email protected](@next/[email protected])([email protected])([email protected])([email protected])':+ '@vercel/[email protected](@next/[email protected])([email protected])([email protected])([email protected])':dependencies:'@babel/core': 7.22.10'@babel/eslint-parser': 7.22.10(@babel/[email protected])([email protected])@@ -11715,7 +11808,7 @@ snapshots:'@typescript-eslint/eslint-plugin': 5.59.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/parser': 5.62.0([email protected])([email protected])eslint-config-prettier: 8.10.0([email protected])- eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))+ eslint-import-resolver-alias: 1.1.2([email protected])eslint-import-resolver-typescript: 3.5.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])eslint-plugin-eslint-comments: 3.2.0([email protected])eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])@@ -11729,7 +11822,7 @@ snapshots:eslint-plugin-unicorn: 43.0.2([email protected])prettier-plugin-packagejson: 2.4.3([email protected])optionalDependencies:- '@next/eslint-plugin-next': 15.0.2-canary.3+ '@next/eslint-plugin-next': 15.0.2-canary.9eslint: 8.45.0prettier: 3.1.1typescript: 5.3.3@@ -11739,7 +11832,7 @@ snapshots:- jest- supports-color- '@vercel/[email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))':+ '@vercel/[email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':dependencies:'@tinyhttp/app': 1.3.0chokidar: 3.5.3@@ -11748,9 +11841,8 @@ snapshots:get-port: 5.1.1strip-ansi: 6.0.1optionalDependencies:- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.2.0- vite: 4.5.0(@types/[email protected])([email protected])'@vitest/[email protected]':dependencies:@@ -13043,8 +13135,8 @@ snapshots:'@typescript-eslint/parser': 5.62.0([email protected])([email protected])eslint: 8.45.0eslint-import-resolver-node: 0.3.7- eslint-import-resolver-typescript: 3.5.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])- eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-import-resolver-typescript: 3.5.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected])+ eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected])eslint-plugin-jsx-a11y: 6.7.1([email protected])eslint-plugin-react: 7.32.2([email protected])eslint-plugin-react-hooks: 5.0.0-canary-7118f5dd7-20230705([email protected])@@ -13081,7 +13173,7 @@ snapshots:eslint: 8.45.0eslint-plugin-turbo: 2.0.12([email protected])- [email protected]([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])):dependencies:eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])@@ -13093,13 +13185,13 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]):dependencies:debug: 4.3.4enhanced-resolve: 5.15.0eslint: 8.45.0- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])- eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected])+ eslint-plugin-import: 2.27.5([email protected])get-tsconfig: 4.6.2globby: 13.2.2is-core-module: 2.12.1@@ -13116,7 +13208,7 @@ snapshots:debug: 4.3.4enhanced-resolve: 5.15.0eslint: 8.45.0- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])get-tsconfig: 4.6.2globby: 13.2.2@@ -13134,7 +13226,7 @@ snapshots:debug: 4.3.4enhanced-resolve: 5.15.0eslint: 8.56.0- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])eslint-plugin-import: 2.27.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])get-tsconfig: 4.6.2globby: 13.2.2@@ -13147,18 +13239,18 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:debug: 3.2.7optionalDependencies:'@typescript-eslint/parser': 5.62.0([email protected])([email protected])eslint: 8.45.0eslint-import-resolver-node: 0.3.7- eslint-import-resolver-typescript: 3.5.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])+ eslint-import-resolver-typescript: 3.5.5(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected])transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]):dependencies:debug: 3.2.7optionalDependencies:@@ -13169,7 +13261,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]):dependencies:debug: 3.2.7optionalDependencies:@@ -13186,7 +13278,7 @@ snapshots:eslint: 8.45.0ignore: 5.2.4- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:array-includes: 3.1.6array.prototype.flat: 1.3.1@@ -13195,7 +13287,7 @@ snapshots:doctrine: 2.1.0eslint: 8.45.0eslint-import-resolver-node: 0.3.7- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected])has: 1.0.3is-core-module: 2.12.1is-glob: 4.0.3@@ -13211,7 +13303,7 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]):+ [email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]):dependencies:array-includes: 3.1.6array.prototype.flat: 1.3.1@@ -13220,7 +13312,7 @@ snapshots:doctrine: 2.1.0eslint: 8.45.0eslint-import-resolver-node: 0.3.7- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])has: 1.0.3is-core-module: 2.12.1is-glob: 4.0.3@@ -13245,7 +13337,7 @@ snapshots:doctrine: 2.1.0eslint: 8.56.0eslint-import-resolver-node: 0.3.7- eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])has: 1.0.3is-core-module: 2.12.1is-glob: 4.0.3@@ -13261,6 +13353,29 @@ snapshots:- eslint-import-resolver-webpack- supports-color+ dependencies:+ array-includes: 3.1.6+ array.prototype.flat: 1.3.1+ array.prototype.flatmap: 1.3.1+ debug: 3.2.7+ doctrine: 2.1.0+ eslint: 8.45.0+ eslint-import-resolver-node: 0.3.7+ eslint-module-utils: 2.8.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])+ has: 1.0.3+ is-core-module: 2.12.1+ is-glob: 4.0.3+ minimatch: 3.1.2+ object.values: 1.1.6+ resolve: 1.22.2+ semver: 6.3.1+ tsconfig-paths: 3.14.2+ transitivePeerDependencies:+ - eslint-import-resolver-typescript+ - eslint-import-resolver-webpack+ - supports-color+[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected]):dependencies:'@typescript-eslint/utils': 5.59.1([email protected])([email protected])@@ -15126,15 +15241,15 @@ snapshots:- [email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]):+ [email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@auth/core': 0.19.0- next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.3.1- [email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected](@babel/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.2.0react-dom: 18.2.0([email protected])@@ -15144,13 +15259,13 @@ snapshots:react: 18.2.0react-dom: 18.2.0([email protected])- [email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:- next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 18.2.0react-dom: 18.3.1([email protected])- [email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@babel/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 14.2.5'@swc/helpers': 0.5.5@@ -15171,7 +15286,6 @@ snapshots:'@next/swc-win32-arm64-msvc': 14.2.5'@next/swc-win32-ia32-msvc': 14.2.5'@next/swc-win32-x64-msvc': 14.2.5- '@playwright/test': 1.38.0transitivePeerDependencies:- '@babel/core'- babel-plugin-macros@@ -15202,7 +15316,7 @@ snapshots:- '@babel/core'- babel-plugin-macros- [email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 14.2.5'@swc/helpers': 0.5.5@@ -15223,12 +15337,11 @@ snapshots:'@next/swc-win32-arm64-msvc': 14.2.5'@next/swc-win32-ia32-msvc': 14.2.5'@next/swc-win32-x64-msvc': 14.2.5- '@playwright/test': 1.38.0transitivePeerDependencies:- '@babel/core'- babel-plugin-macros- [email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 14.2.5'@swc/helpers': 0.5.5@@ -15249,7 +15362,6 @@ snapshots:'@next/swc-win32-arm64-msvc': 14.2.5'@next/swc-win32-ia32-msvc': 14.2.5'@next/swc-win32-x64-msvc': 14.2.5- '@playwright/test': 1.38.0transitivePeerDependencies:- '@babel/core'- babel-plugin-macros@@ -15862,9 +15974,9 @@ snapshots:react: 18.2.0use-sync-external-store: 1.2.0([email protected])- [email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected])):+ [email protected]([email protected](@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected])([email protected]([email protected]))([email protected])):dependencies:- next: 14.2.5(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])+ next: 14.2.5(@playwright/[email protected])([email protected]([email protected]))([email protected])react-instantsearch: 7.3.0([email protected])([email protected]([email protected]))([email protected])@@ -17226,17 +17338,6 @@ snapshots:fsevents: 2.3.3terser: 5.36.0- dependencies:- esbuild: 0.18.20- postcss: 8.4.31- rollup: 3.28.1- optionalDependencies:- '@types/node': 20.4.2- fsevents: 2.3.3- terser: 5.36.0- optional: true-dependencies:'@types/chai': 4.3.9