Connect, collaborate, and grow with a community of TypeScript developers
feat: adds reporting UI on challenges (#64)
Jim Burbridge9923138ab2dd
diff --git a/.vscode/extensions.json b/.vscode/extensions.jsonnew file mode 100644index 00000000..8e42285b--- /dev/null+++ b/.vscode/extensions.json@@ -0,0 +1,5 @@+{+ "recommendations": [+ "prisma.prisma"+ ]+}\ No newline at end of filediff --git a/package.json b/package.jsonindex 12f7bc51..d61e6750 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"@next-auth/prisma-adapter": "^1.0.6","@prisma/client": "^4.14.0","@radix-ui/react-avatar": "^1.0.3",+ "@radix-ui/react-checkbox": "^1.0.4","@radix-ui/react-dialog": "^1.0.4","@radix-ui/react-dropdown-menu": "^2.0.5","@radix-ui/react-label": "^2.0.2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b944bad6..e87b80f0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1,9 +1,5 @@lockfileVersion: '6.0'-settings:- autoInstallPeers: true- excludeLinksFromLockfile: false-dependencies:'@clerk/nextjs':specifier: ^4.19.0@@ -23,6 +19,9 @@ dependencies:'@radix-ui/react-avatar':specifier: ^1.0.3version: 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-checkbox':+ specifier: ^1.0.4+ version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-dialog':specifier: ^1.0.4version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -912,6 +911,34 @@ packages:react-dom: 18.2.0([email protected])dev: false+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-CBuGQa52aAYnADZVt/KBQzXrwx6TqnlwtcIPGtVt5JkkzQwMOLJjPukimhfKEr4GQNd43C+djUh5Ikopj8pSLg==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.22.5+ '@radix-ui/primitive': 1.0.1+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-use-controllable-state': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-use-previous': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-use-size': 1.0.1(@types/[email protected])([email protected])+ '@types/react': 18.2.8+ '@types/react-dom': 18.2.4+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):resolution: {integrity: sha512-3SzW+0PW7yBBoQlT8wNcGtaxaD0XSu0uLUFgrtHY08Acx05TaHaOmVLR73c0j/cqpDy53KBMO7s0dx2wmOIDIA==}peerDependencies:@@ -6276,3 +6303,7 @@ packages:resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}dev: false++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: falsediff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 2acfa545..31f81ef7 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -175,6 +175,8 @@ model Report {challenge Challenge @relation(fields: [challengeId], references: [id])challengeId Inttext String+ derogatory Boolean @default(false)+ unclear Boolean @default(false)@@index([userId])@@index([challengeId])diff --git a/src/components/challenge/description-panel.tsx b/src/components/challenge/description-panel.tsxindex bea5173f..3dcd760b 100644--- a/src/components/challenge/description-panel.tsx+++ b/src/components/challenge/description-panel.tsx@@ -17,21 +17,38 @@ import {DialogHeader,DialogTitle,DialogTrigger,+ DialogFooter} from '~/components/ui/dialog';import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '~/components/ui/tooltip';import { TypographyH3 } from '~/components/ui/typography/h3';import type { Challenge } from '.';import { DifficultyBadge } from '../explore/difficulty-badge';+import { ActionMenu } from '../ui/action-menu';+import { Textarea } from '../ui/textarea';import { addOrRemoveBookmark } from './bookmark.action';import { incrementOrDecrementUpvote } from './increment.action';import { ShareForm } from './share-form';import { Solutions } from './solutions';+import { Form, FormField, FormItem } from '../ui/form';+import { useForm } from 'react-hook-form';+import { Checkbox } from '../ui/checkbox';+import { TypographyLarge } from '../ui/typography/large';+import { addReport } from './report.action';+import { toast } from '../ui/use-toast';+interface Props {challenge: NonNullable<Challenge>;}+export type FormValues = {+ comments: string;+ examples: boolean;+ derogatory: boolean;+ other: boolean;+};+export function DescriptionPanel({ challenge }: Props) {const router = useRouter();const [votes, setVotes] = useState(challenge._count.Vote);@@ -63,6 +80,54 @@ export function DescriptionPanel({ challenge }: Props) {}, 500),).current;+ const [dialogOpen, setDialogOpen] = useState(false);++ const form = useForm<FormValues>({+ defaultValues: {+ comments: '',+ other: false,+ examples: false,+ derogatory: false,+ },++ });++ async function onSubmit(data: FormValues) {+ const response = await addReport(challenge.id, session?.data?.user?.id as string, data);+ if (response === 'created') {+ toast({+ title: 'Feedback Sent',+ variant: 'success',+ description: (+ <p>+ Thank you for submitting this feedback. Someone from our moderator+ team will be reviewing it shortly.+ </p>+ )+ });+ } else if(response === 'report_already_made') {+ toast({+ title: 'Report already made',+ description: (+ <p>+ You have already made a report about this challenge. We are still+ reviewing the question.+ </p>+ )+ })+ } else if (response === 'not_logged_in') {+ toast({+ title: 'You are not loggeed in',+ description: (+ <p>Please log in to make this report.</p>+ )+ })+ }++ setDialogOpen(false);++ }+return (<><Tabs defaultValue="description" className="w-full">@@ -76,7 +141,96 @@ export function DescriptionPanel({ challenge }: Props) {</TabsList><TabsContent value="description" className="mt-0"><div className="h-full px-1 pb-0 pt-3 dark:px-4 dark:pb-2">- <TypographyH3 className="mb-2 font-medium">{challenge.name}</TypographyH3>+ <div className="flex justify-between items-baseline">+ <TypographyH3 className="mb-2 font-medium">{challenge.name}</TypographyH3>+ <div>+ <ActionMenu items={[+ {+ key: 'feedback',+ label: 'Feedback',+ icon: 'Flag'+ }+ ]} onChange={() => setDialogOpen(true)} />+ </div>+ </div>++ <Dialog open={dialogOpen} onOpenChange={e => setDialogOpen(!e)}>+ <DialogContent>+ <Form {...form}>+ {/* eslint-disable-next-line @typescript-eslint/no-misused-promises */}+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <DialogHeader>+ <DialogTitle>+ Feedback: {challenge.name}+ </DialogTitle>+ </DialogHeader>++ <div className="flex flex-col gap-4 my-4">+ <TypographyLarge>Issues Encountered</TypographyLarge>+ <FormField+ name='examples'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-4 items-center">+ <Checkbox id="examples" checked={field.value as boolean} onChange={field.onChange} onCheckedChange={field.onChange} />+ <label htmlFor="examples">+ Description or examples are unclear or incorrect+ </label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ name='derogatory'+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-4">+ <Checkbox id="derogatory" checked={field.value as boolean} onCheckedChange={field.onChange} />+ <label htmlFor="derogatory">+ Racist or other derogatory statement+ </label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ name='other'+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-4">+ <Checkbox id="other" checked={field.value as boolean} onCheckedChange={field.onChange} />+ <label htmlFor="other">+ Other+ </label>+ </div>+ </FormItem>+ )}+ />+ <FormField+ name='comments'+ render={({ field }) => (+ <FormItem>+ <TypographyLarge>+ Comments+ </TypographyLarge>+ <Textarea value={field.value as string} onChange={field.onChange} />+ </FormItem>+ )}+ />+ </div>+ <DialogFooter>+ <Button variant='secondary' type="button" onClick={() => setDialogOpen(false)}>+ Close+ </Button>+ <Button type="submit">+ Report+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+<div className="mb-6 flex items-center gap-4"><DifficultyBadge difficulty={challenge.difficulty} />diff --git a/src/components/challenge/report.action.ts b/src/components/challenge/report.action.tsnew file mode 100644index 00000000..ccbd6230--- /dev/null+++ b/src/components/challenge/report.action.ts@@ -0,0 +1,36 @@+'use server';++import { prisma } from '~/server/db';+import type { FormValues } from './description-panel';++export async function doTheThing() {+ await Promise.resolve(0);+ return 'done';+}++export async function addReport(challengeId: number, userId: string, data: FormValues) {+ if(userId === undefined) return 'not_logged_in';++ const report = await prisma.report.findMany({+ where: {+ challengeId,+ userId,+ }+ });+ if(report.length > 0) {+ console.info(report);+ return 'report_already_made';+ }++ await prisma.report.create({+ data: {+ challengeId,+ userId,+ text: data.comments,+ unclear: data.examples,+ derogatory: data.derogatory,+ }+ })++ return 'created';+}\ No newline at end of filediff --git a/src/components/ui/action-menu.tsx b/src/components/ui/action-menu.tsxnew file mode 100644index 00000000..0927580c--- /dev/null+++ b/src/components/ui/action-menu.tsx@@ -0,0 +1,51 @@+'use client';+import React from 'react';+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from './dropdown-menu';++import * as AllIcons from 'lucide-react';+import type { Icon } from 'lucide-react';++export type ActionMenuItem = {+ icon?: keyof typeof AllIcons;+ label: string;+ key: string;+};++export interface ActionMenuProps {+ items: ActionMenuItem[];+ onChange: (e: ActionMenuItem) => void;+}++type OptionalIcon = Icon | null;++export function ActionMenu(props: ActionMenuProps) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <AllIcons.MoreHorizontal size={16} />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ {+ props.items.map(item => {+ const Icon = (item.icon ? AllIcons[item.icon] : null) as OptionalIcon;+ return (+ <DropdownMenuItem onClick={() => props.onChange(item)} key={item.key} className="p-2 flex gap-2 items-center">+ <div>+ {Icon ? <Icon size={16} /> : null}+ </div>+ <div>+ {item.label}+ </div>+ </DropdownMenuItem>+ );+ })+ }+ </DropdownMenuContent>+ </DropdownMenu>+ )+}\ No newline at end of filediff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsxnew file mode 100644index 00000000..09bc0997--- /dev/null+++ b/src/components/ui/checkbox.tsx@@ -0,0 +1,30 @@+'use client'++import * as React from 'react'+import * as CheckboxPrimitive from '@radix-ui/react-checkbox'+import { Check } from 'lucide-react'++import { cn } from '~/utils/cn'++const Checkbox = React.forwardRef<+ React.ElementRef<typeof CheckboxPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>+>(({ className, ...props }, ref) => (+ <CheckboxPrimitive.Root+ ref={ref}+ className={cn(+ 'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',+ className+ )}+ {...props}+ >+ <CheckboxPrimitive.Indicator+ className={cn('flex items-center justify-center text-current')}+ >+ <Check className="h-4 w-4" />+ </CheckboxPrimitive.Indicator>+ </CheckboxPrimitive.Root>+))+Checkbox.displayName = CheckboxPrimitive.Root.displayName++export { Checkbox }diff --git a/src/components/ui/icon-button.tsx b/src/components/ui/icon-button.tsxnew file mode 100644index 00000000..bbb5befe--- /dev/null+++ b/src/components/ui/icon-button.tsx@@ -0,0 +1,24 @@+'use client';++import * as AllIcons from 'lucide-react';+import type { Icon } from 'lucide-react';+import React from 'react';+import { Button, type ButtonProps } from './button';++type IconNames = keyof typeof AllIcons;++export interface IconButtonProps extends ButtonProps {+ icon: IconNames;+ iconSize?: string | number;+}++export function IconButton({ icon, iconSize, ...props }: IconButtonProps) {+ const Icon = AllIcons[icon] as Icon;+ return (+ <Button+ {...props}+ >+ <Icon size={iconSize} />+ </Button>+ )+}diff --git a/src/components/ui/textarea.tsx b/src/components/ui/textarea.tsxnew file mode 100644index 00000000..23d059f8--- /dev/null+++ b/src/components/ui/textarea.tsx@@ -0,0 +1,24 @@+import * as React from 'react'++import { cn } from '~/utils/cn'++export interface TextareaProps+ extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}++const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(+ ({ className, ...props }, ref) => {+ return (+ <textarea+ className={cn(+ 'flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',+ className+ )}+ ref={ref}+ {...props}+ />+ )+ }+)+Textarea.displayName = 'Textarea'++export { Textarea }diff --git a/src/server/auth.ts b/src/server/auth.tsindex 50bc1851..616751f5 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -1,5 +1,5 @@import { PrismaAdapter } from '@next-auth/prisma-adapter';-import { Role } from '@prisma/client';+import type { Role } from '@prisma/client';import { type GetServerSidePropsContext } from 'next';import { getServerSession, type DefaultSession, type NextAuthOptions } from 'next-auth';import GitHubProvider from 'next-auth/providers/github';