Connect, collaborate, and grow with a community of TypeScript developers
Add profile page and crude server action (#240)
Sean Boult77db68602aff
diff --git a/package.json b/package.jsonindex 214b5150..a7280011 100644--- a/package.json+++ b/package.json@@ -18,6 +18,7 @@},"type": "module","dependencies": {+ "@hookform/error-message": "^2.0.1","@hookform/resolvers": "^3.1.1","@monaco-editor/loader": "^1.3.3","@monaco-editor/react": "^4.5.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fef44657..f22e6883 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -13,6 +13,9 @@ patchedDependencies:path: patches/[email protected]dependencies:+ '@hookform/error-message':+ specifier: ^2.0.1'@hookform/resolvers':specifier: ^3.1.1version: 3.1.1([email protected])@@ -546,6 +549,18 @@ packages:react-dom: 18.2.0([email protected])dev: false+ resolution: {integrity: sha512-U410sAr92xgxT1idlu9WWOVjndxLdgPUHEB8Schr27C9eh7/xUnITWpCMF93s+lGiG++D4JnbSnrb5A21AdSNg==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ react-hook-form: ^7.0.0+ dependencies:+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ react-hook-form: 7.45.1([email protected])+ dev: false+/@hookform/[email protected]([email protected]):resolution: {integrity: sha512-tS16bAUkqjITNSvbJuO1x7MXbn7Oe8ZziDTJdA9mMvsoYthnOOiznOTGBYwbdlYBgU+tgpI/BtTU3paRbCuSlg==}peerDependencies:diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex f63e27b9..30a1bc7b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -78,6 +78,17 @@ model Role {role RoleTypes @unique}+/// This is a table that contains all the user links they can add to profile+model UserLink {+ id String @id @default(uuid())+ user User[]+ url String++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++}+model User {id String @id @default(uuid())@@ -87,6 +98,11 @@ model User {image String?roles Role[]+ /// this is the bio that shows up on the profile page+ bio String @default("") @db.VarChar(255)+ /// this is the twitter URL that shows up on the profile page+ userLinks UserLink[]+status UserStatus @default(PENDING)banReason String? @db.MediumTextdiff --git a/src/app/[username]/page.tsx b/src/app/[username]/page.tsxindex 58420ef2..afff3ab6 100644--- a/src/app/[username]/page.tsx+++ b/src/app/[username]/page.tsx@@ -5,6 +5,7 @@ interface Props {username: string;};}+export default function Page({ params }: Props) {return <Profile username={params.username} />;}diff --git a/src/app/settings/error.tsx b/src/app/settings/error.tsxnew file mode 100644index 00000000..76d24fd6--- /dev/null+++ b/src/app/settings/error.tsx@@ -0,0 +1,11 @@+'use client';+const ErrorBounds = () => {+ return (+ <div>+ <h1>404</h1>+ <p>Page not found</p>+ </div>+ );+};++export default ErrorBounds;diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsxnew file mode 100644index 00000000..4a61cd80--- /dev/null+++ b/src/app/settings/page.tsx@@ -0,0 +1,43 @@+import { getServerSession } from 'next-auth';+import { Settings } from '~/components/settings';+import { authOptions } from '~/server/auth';+import { prisma } from '~/server/db';+export default async function SettingsPage() {+ // NOTE: what's weird about this API is that it should have the+ // param to be required but it's not for some reason+ const session = await getServerSession(authOptions);++ if (!session?.user || !session?.user.name) {+ return null;+ }++ const profileData = await prisma.user.findFirstOrThrow({+ where: {+ id: session.user.id,+ },+ include: {+ userLinks: true,+ },+ orderBy: {+ updatedAt: 'asc',+ },+ });++ // make the user links have 4 at all times+ const userLinks = (profileData.userLinks = [+ ...profileData.userLinks,+ ...Array(4 - profileData.userLinks.length).fill({+ id: null,+ url: '',+ }),+ ]);++ return (+ <Settings+ data={{+ bio: profileData.bio,+ userLinks,+ }}+ />+ );+}diff --git a/src/components/challenge/report.action.ts b/src/components/challenge/report.action.tsindex 483022cf..deb8878e 100644--- a/src/components/challenge/report.action.ts+++ b/src/components/challenge/report.action.ts@@ -3,11 +3,6 @@import { prisma } from '~/server/db';import type { FormValues } from './description';-export async function doTheThing() {- await Promise.resolve(0);- return 'done';-}-export async function addChallengeReport(challengeId: number, userId: string, data: FormValues) {if (userId === undefined) return 'not_logged_in';diff --git a/src/components/settings/index.tsx b/src/components/settings/index.tsxnew file mode 100644index 00000000..a8a6842d--- /dev/null+++ b/src/components/settings/index.tsx@@ -0,0 +1,145 @@+'use client';++import { Controller, useFieldArray, useForm } from 'react-hook-form';+import { Button } from '../ui/button';+import { Input } from '../ui/input';+import { updateProfile } from './settings.action';+import * as z from 'zod';+import { zodResolver } from '@hookform/resolvers/zod';+import { RichMarkdownEditor } from '../ui/rich-markdown-editor';+import { Github, Linkedin, Twitter, Youtube, Link as LinkIcon } from 'lucide-react';+import { toast } from '../ui/use-toast';+import { ToastAction } from '../ui/toast';++import { ErrorMessage } from '@hookform/error-message';++export interface UserLinkType {+ id: string | null;+ url: string;+}++interface FormValues {+ userLinks: UserLinkType[];+ bio: string;+}++export type FormSchema = z.infer<typeof formSchema>;++const formSchema = z.object({+ // TODO: make this have a good typesafe exp+ // userLinks: z.array(+ // z.object({+ // id: z.union([z.string(), z.null()]),+ // url: z.string().url(),+ // }),+ // ),+ userLinks: z.any(),+ bio: z.string().optional(),+});++export const Settings = ({ data }: { data: FormSchema }) => {+ const {+ formState: { isValid, errors },+ control,+ getValues,+ register,+ } = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ ...data,+ },+ });++ const { fields } = useFieldArray({+ control,+ name: 'userLinks',+ });++ const onSubmit = async (values: FormValues) => {+ if (!isValid) {+ toast({+ variant: 'destructive',+ title: 'You must put a valid link',+ action: <ToastAction altText="Error in urls">Error in url</ToastAction>,+ });+ return;+ }++ const userLinks = data.userLinks.map((link: UserLinkType, i: number) => ({+ ...link,+ // @ts-ignore+ url: values.userLinks[i].value,+ }));++ const updateProfileData = {+ bio: values.bio,+ userLinks,+ };++ // call the server action+ await updateProfile(updateProfileData);++ toast({+ variant: 'success',+ title: 'Your settings have been updated',+ action: <ToastAction altText="Settings updated">Settings updated</ToastAction>,+ });+ };++ return (+ <div className="container">+ <h2 className="mt-10 text-3xl font-bold">Profile</h2>+ <form action={() => onSubmit(getValues())}>+ <h4 className="mb-4 text-xl">Tell us about yourself</h4>+ <div className="h-[300px] w-[600px]">+ <Controller+ control={control}+ name="bio"+ render={({ field: { onChange, value } }) => (+ <RichMarkdownEditor value={value} onChange={onChange} />+ )}+ />+ </div>++ <ErrorMessage+ errors={errors}+ name="userLinks"+ render={({ message }) => <p>{message}</p>}+ />++ <div className="mt-8 flex flex-col items-start space-y-3">+ <h4 className="text-xl font-bold">Social accounts</h4>+ {fields.map((val: UserLinkType, i: number) => {+ return (+ <div key={`url-${i}`} className="flex items-center gap-2">+ <MagikcIcon url={val?.url ?? ''} />+ <Input+ defaultValue={val?.url}+ placeholder="Link to social profile"+ className="w-64"+ // @ts-ignore+ {...register(`userLinks.${i}.value`)}+ />+ </div>+ );+ })}+ </div>++ <Button type="submit" className="mt-6">+ Save+ </Button>+ </form>+ </div>+ );+};++function MagikcIcon({ url }: { url: string }) {+ if (url.startsWith('https://github.com/')) return <Github className="h-5 w-5 text-neutral-400" />;+ if (url.startsWith('https://twitter.com/'))+ return <Twitter className="h-5 w-5 text-neutral-400" />;+ if (url.startsWith('https://linked.in/'))+ return <Linkedin className="h-5 w-5 text-neutral-400" />;+ if (url.startsWith('https://youtube.com/'))+ return <Youtube className="h-5 w-5 text-neutral-400" />;+ return <LinkIcon className="h-5 w-5 text-neutral-400" />;+}diff --git a/src/components/settings/settings.action.ts b/src/components/settings/settings.action.tsnew file mode 100644index 00000000..cb6cc936--- /dev/null+++ b/src/components/settings/settings.action.ts@@ -0,0 +1,54 @@+'use server';++import { getServerSession } from 'next-auth';++import { prisma } from '~/server/db';+import { authOptions } from '~/server/auth';+import type { UserLinkType } from '.';+import { revalidatePath } from 'next/cache';++/**+ * This will only let you update your own profile+ * @param profileData+ */+// TODO: add transactions to this update #GFI+export async function updateProfile(profileData: { bio: string; userLinks: UserLinkType[] }) {+ const session = await getServerSession(authOptions);++ // 1. Checks that the user is logged in+ if (!session?.user.id) return 'unauthorized';++ // 2. Update the user bio field in the db+ await prisma.user.update({+ where: { id: session?.user.id },+ data: { bio: profileData.bio },+ });++ // 3. Update the users links in the db if the url is not empty+ await prisma.$transaction(+ profileData.userLinks+ .map((link) =>+ prisma.userLink.upsert({+ where: { id: link.id ?? '' },+ update: { url: link.url },+ create: {+ url: link.url,+ user: { connect: { id: session?.user.id } },+ },+ }),+ ),+ );++ // // 4. Filter for all links that are empty string and delete from db+ // const emptyLinks = profileData.userLinks.filter((link) => link.url === '');+ // await prisma.userLink.deleteMany({+ // where: {+ // id: {+ // in: emptyLinks.map((link) => link.id ?? '-1'),+ // },+ // },+ // });++ // do this after we do the shit+ revalidatePath('/settings');+}diff --git a/src/components/ui/navigation.tsx b/src/components/ui/navigation.tsxindex e2fe3801..019fb9ad 100644--- a/src/components/ui/navigation.tsx+++ b/src/components/ui/navigation.tsx@@ -3,7 +3,7 @@import { useTheme } from 'next-themes';import Link from 'next/link';-import { LogIn, Plus, Settings, User, Bell, Moon, Sun, Loader2 } from 'lucide-react';+import { Settings2, LogIn, Plus, Settings, User, Bell, Moon, Sun, Loader2 } from 'lucide-react';import { useEffect, useState } from 'react';import { useRouter, usePathname } from 'next/navigation';import { signIn, signOut, useSession } from 'next-auth/react';@@ -85,6 +85,12 @@ export function Navigation() {<span>Profile</span></DropdownMenuItem></Link>+ <Link className="block" href="/settings">+ <DropdownMenuItem className="rounded-lg p-2 duration-300 focus:bg-accent focus:outline-none">+ <Settings2 className="mr-2 h-4 w-4" />+ <span>Settings</span>+ </DropdownMenuItem>+ </Link>{isAdminOrMod && (<Link className="block" href="/admin"><DropdownMenuItem className="rounded-lg p-2 duration-300 focus:bg-accent focus:outline-none dark:hover:bg-neutral-700/50">diff --git a/src/components/user/dashboard/index.tsx b/src/components/user/dashboard/index.tsxindex c1ac02f8..3c063864 100644--- a/src/components/user/dashboard/index.tsx+++ b/src/components/user/dashboard/index.tsx@@ -7,6 +7,10 @@ import { SolutionsTab } from '../dashboard/solutions-tab';import type { User } from '@prisma/client';import { getRelativeTime } from '~/utils/relativeTime';import { prisma } from '~/server/db';+import { Button } from '~/components/ui/button';+import Link from 'next/link';+import { getServerSession } from 'next-auth';+import { authOptions } from '~/server/auth';interface Props {user: User;@@ -41,6 +45,7 @@ async function getUserdata(id: string) {export default async function Dashboard({ user }: Props) {const userData = await getUserdata(user.id);+ const session = await getServerSession(authOptions);// TODO: this seems susif (!userData) {@@ -48,7 +53,13 @@ export default async function Dashboard({ user }: Props) {}return (- <div className="container md:px-24">+ <div className="container">+ {session?.user.id === user.id && (+ <Link href="/settings">+ <Button>Edit Profile</Button>+ </Link>+ )}+<div className="flex-1 space-y-4 pt-6"><div className="flex items-center gap-4"><div className="flex items-center space-x-2">