Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ npm-debug.log*
.DS_Store
.idea/
.vscode/

# Windows download metadata
*:Zone.Identifier
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
.github/ISSUE_TEMPLATE/
.next/
coverage/
data/
infrastructure_plan.md
node_modules/
package-lock.json
playwright-report/
test-results/
next-env.d.ts
next-env.d.ts
29 changes: 27 additions & 2 deletions app/Navbar.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@ nav {
color: black;
}

ul {
nav > ul {
list-style-type: none;
margin: 1rem;
padding: 0;
display: flex;
align-items: center;
justify-content: space-around;
}

li {
nav > ul > li {
display: flex;
align-items: center;
padding: 15px;
}

Expand All @@ -24,6 +27,28 @@ a:hover {
text-decoration: underline;
}

.navbar-profile {
display: inline-flex;
align-items: center;
gap: 0.5rem;
}

.navbar-avatar {
display: inline-grid;
width: 2rem;
height: 2rem;
place-items: center;
overflow: hidden;
border-radius: 50%;
font-size: 1.25rem;
}

.navbar-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}

nav form {
margin: 0;
}
Expand Down
32 changes: 30 additions & 2 deletions app/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import Link from 'next/link'
import Image from 'next/image'
import { signOut } from '../auth'
import type { ProfileImageOption } from '../lib/profile-images'

import './Navbar.css'

type NavbarProps = {
displayName?: string | null
session: { user?: { name?: string | null } } | null
avatar?: ProfileImageOption
}

export default function Navbar({ session }: NavbarProps) {
export default function Navbar({ displayName, session, avatar }: NavbarProps) {
return (
<nav>
<ul>
Expand All @@ -23,7 +27,31 @@ export default function Navbar({ session }: NavbarProps) {
{session?.user ? (
<>
<li aria-label="Signed in member">
<Link href="/">{session.user.name ?? 'Member'}</Link>
<Link className="navbar-profile" href="/profile">
<span
aria-hidden="true"
className="navbar-avatar"
style={{
backgroundColor:
avatar && 'color' in avatar ? avatar.color : undefined,
}}
>
{avatar && 'imageUrl' in avatar ? (
<Image
alt=""
height={32}
src={avatar.imageUrl}
unoptimized
width={32}
/>
) : avatar && 'symbol' in avatar ? (
avatar.symbol
) : (
'🌿'
)}
</span>
{displayName ?? session.user.name ?? 'Member'}
</Link>
</li>
<li>
<form
Expand Down
39 changes: 39 additions & 0 deletions app/api/locations/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server'

import { auth } from '../../../auth'
import { normalizeLocationName } from '../../../lib/geomelon'
import { prisma } from '../../../lib/prisma'

const resultLimit = 10

export async function GET(request: Request) {
const session = await auth()
if (!session?.user?.email) {
return NextResponse.json(
{ error: { code: 'UNAUTHENTICATED', message: 'Sign in required' } },
{ status: 401 },
)
}

const query = new URL(request.url).searchParams.get('q') ?? ''
if (query.length > 100) {
return NextResponse.json(
{ error: { code: 'INVALID_QUERY', message: 'Query is too long' } },
{ status: 400 },
)
}

const normalizedQuery = normalizeLocationName(query)
if (normalizedQuery.length < 2) {
return NextResponse.json({ locations: [] })
}

const locations = await prisma.location.findMany({
where: { normalizedName: { startsWith: normalizedQuery } },
orderBy: [{ kind: 'asc' }, { name: 'asc' }],
select: { id: true, kind: true, name: true, regionName: true },
take: resultLimit,
})

return NextResponse.json({ locations })
}
44 changes: 44 additions & 0 deletions app/api/profile/avatar/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server'

import { auth } from '../../../../auth'
import { prisma } from '../../../../lib/prisma'
import { isProfileImageId } from '../../../../lib/profile-images'

export async function POST(request: Request) {
const session = await auth()
if (!session?.user?.email) {
return NextResponse.json(
{ error: { code: 'UNAUTHENTICATED', message: 'Sign in required' } },
{ status: 401 },
)
}

let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: { code: 'INVALID_JSON', message: 'Invalid request body' } },
{ status: 400 },
)
}

const avatarId =
typeof body === 'object' && body !== null && 'avatarId' in body
? body.avatarId
: undefined

if (typeof avatarId !== 'string' || !(await isProfileImageId(avatarId))) {
return NextResponse.json(
{ error: { code: 'INVALID_AVATAR', message: 'Unknown profile image' } },
{ status: 422 },
)
}

await prisma.user.update({
where: { email: session.user.email },
data: { avatarId },
})

return NextResponse.json({ avatarId })
}
16 changes: 15 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { ReactNode } from 'react'
import './globals.css'
import Navbar from './Navbar'
import { auth } from '../auth'
import { prisma } from '../lib/prisma'
import { getProfileImageOptions } from '../lib/profile-images'

export const metadata: Metadata = {
title: 'SideCause',
Expand All @@ -14,12 +16,24 @@ export default async function RootLayout({
children,
}: Readonly<{ children: ReactNode }>) {
const session = await auth()
const user = session?.user?.email
? await prisma.user.findUnique({
where: { email: session.user.email },
select: { avatarId: true, displayName: true },
})
: null
const imageOptions = user ? await getProfileImageOptions() : []
const avatar = imageOptions.find((image) => image.id === user?.avatarId)

return (
<html lang="en">
<body>
<div>
<Navbar session={session} />
<Navbar
avatar={avatar}
displayName={user?.displayName}
session={session}
/>
</div>
{children}
</body>
Expand Down
2 changes: 2 additions & 0 deletions app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Link from 'next/link'
import { redirect } from 'next/navigation'

Check warning on line 2 in app/login/page.tsx

View workflow job for this annotation

GitHub Actions / Quality checks

'redirect' is defined but never used
import { auth } from '../../auth'

Check warning on line 3 in app/login/page.tsx

View workflow job for this annotation

GitHub Actions / Quality checks

'auth' is defined but never used

import { getSafePostReturnTo } from '../../lib/auth/return-to'
import { LoginForm } from './LoginForm'
Expand Down
106 changes: 106 additions & 0 deletions app/profile/LocationCombobox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
'use client'

import { useEffect, useId, useState } from 'react'

import styles from './profile.module.css'

type LocationOption = {
id: string
kind: 'CITY' | 'REGION'
name: string
regionName: string | null
}

function labelFor(location: LocationOption) {
return location.kind === 'CITY' && location.regionName
? `${location.name}, ${location.regionName}`
: location.name
}

export default function LocationCombobox({
initialLocation,
initialLocationId,
}: {
initialLocation: string
initialLocationId: string
}) {
const listId = useId()
const [query, setQuery] = useState(initialLocation)
const [locationId, setLocationId] = useState(initialLocationId)
const [locations, setLocations] = useState<LocationOption[]>([])
const [error, setError] = useState('')

useEffect(() => {
const normalized = query.trim()
if (normalized.length < 2 || locationId) {
return
}

const controller = new AbortController()
const timeout = window.setTimeout(async () => {
try {
const response = await fetch(
`/api/locations?q=${encodeURIComponent(normalized)}`,
{ signal: controller.signal },
)
if (!response.ok) throw new Error('Search failed')
const data: { locations: LocationOption[] } = await response.json()
setLocations(data.locations)
setError('')
} catch (searchError) {
if ((searchError as Error).name !== 'AbortError') {
setLocations([])
setError('Location search is unavailable. Please try again.')
}
}
}, 200)

return () => {
controller.abort()
window.clearTimeout(timeout)
}
}, [locationId, query])

return (
<div className={styles.locationCombobox}>
<input name="locationId" type="hidden" value={locationId} />
<input
aria-autocomplete="list"
aria-controls={locations.length ? listId : undefined}
aria-expanded={locations.length > 0}
autoComplete="off"
id="profile-location"
name="location"
onChange={(event) => {
setQuery(event.target.value)
setLocationId('')
setLocations([])
setError('')
}}
placeholder="Search city or region"
role="combobox"
type="search"
value={query}
/>
{locations.length > 0 && (
<ul className={styles.locationResults} id={listId} role="listbox">
{locations.map((location) => (
<li aria-selected={false} key={location.id} role="option">
<button
onClick={() => {
setQuery(labelFor(location))
setLocationId(location.id)
setLocations([])
}}
type="button"
>
{labelFor(location)}
</button>
</li>
))}
</ul>
)}
{error && <p role="alert">{error}</p>}
</div>
)
}
Loading
Loading