From ca2a0fdcef0b08e15e62438a99d1c874c68d7a01 Mon Sep 17 00:00:00 2001 From: Nicolay Bennett Rennemo Date: Tue, 27 Oct 2026 21:43:43 +0100 Subject: [PATCH 1/4] WIP: venue detail and city venue list --- apps/backend/src/schema/schema.ts | 11 ++ apps/frontend/src/components/Breadcrumbs.tsx | 47 +++++ apps/frontend/src/components/VenueMap.tsx | 27 +++ apps/frontend/src/components/ViewVenue.tsx | 29 ++- apps/frontend/src/routeTree.gen.ts | 61 ++++++- .../src/routes/$cityId/venues/$venueId.tsx | 166 ++++++++++++++++++ .../src/routes/$cityId/venues/index.tsx | 80 +++++++++ apps/frontend/src/types/venue.ts | 13 +- .../20261027201007_add_reviews/migration.sql | 14 ++ packages/db/prisma/schema.prisma | 14 ++ packages/db/prisma/seed.ts | 139 ++++++++++++++- 11 files changed, 587 insertions(+), 14 deletions(-) create mode 100644 apps/frontend/src/components/Breadcrumbs.tsx create mode 100644 apps/frontend/src/components/VenueMap.tsx create mode 100644 apps/frontend/src/routes/$cityId/venues/$venueId.tsx create mode 100644 apps/frontend/src/routes/$cityId/venues/index.tsx create mode 100644 packages/db/prisma/migrations/20261027201007_add_reviews/migration.sql diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index b008812..7c7e9f1 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -18,6 +18,7 @@ builder.prismaObject('Venue', { openingHours: t.relation('openingHours'), city: t.relation('city'), pricesSighted: t.relation('pricesSighted'), + reviews: t.relation('reviews'), }), }) @@ -59,6 +60,16 @@ const priceSightingRef = builder.prismaObject('PriceSighting', { }), }) +builder.prismaObject('Review', { + fields: (t) => ({ + id: t.exposeString('id'), + rating: t.exposeFloat('rating'), + comment: t.exposeString('comment'), + author: t.exposeString('author'), + createdAt: t.expose('createdAt', { type: 'DateTime' }), + }), +}) + type SearchResultItem = { type: 'venue' | 'city' name: string diff --git a/apps/frontend/src/components/Breadcrumbs.tsx b/apps/frontend/src/components/Breadcrumbs.tsx new file mode 100644 index 0000000..e73bfe0 --- /dev/null +++ b/apps/frontend/src/components/Breadcrumbs.tsx @@ -0,0 +1,47 @@ +import { Link } from '@tanstack/react-router' + +interface BreadcrumbItem { + label: string + cityId?: string +} + +export default function Breadcrumbs({ items }: { items: BreadcrumbItem[] }) { + return ( + + ) +} diff --git a/apps/frontend/src/components/VenueMap.tsx b/apps/frontend/src/components/VenueMap.tsx new file mode 100644 index 0000000..18ef869 --- /dev/null +++ b/apps/frontend/src/components/VenueMap.tsx @@ -0,0 +1,27 @@ +import { MapContainer, Marker, TileLayer } from 'react-leaflet' + +interface VenueMapProps { + lat: number + lon: number + name: string +} + +export default function VenueMap({ lat, lon, name }: VenueMapProps) { + return ( + + + + + ) +} diff --git a/apps/frontend/src/components/ViewVenue.tsx b/apps/frontend/src/components/ViewVenue.tsx index fb67c63..f84e0aa 100644 --- a/apps/frontend/src/components/ViewVenue.tsx +++ b/apps/frontend/src/components/ViewVenue.tsx @@ -1,22 +1,34 @@ import type { venue } from '#/types/venue' import { useQuery } from '@tanstack/react-query' +import { Link } from '@tanstack/react-router' import { graphqlFetch } from '#/graphql/client' -const GET_VENUE = ` +export const GET_VENUE = ` query GetVenues { venue { id name address + lat + lon city { id name + lat + lon } openingHours { days opening closing } + reviews { + id + rating + comment + author + createdAt + } } } ` @@ -49,6 +61,18 @@ export function ViewVenue(Current: venue) { ) } +export function VenueCard({ current }: { current: venue }) { + return ( + + + + ) +} + export default function VenueLoader() { const { data, isPending, isError } = useQuery({ queryKey: ['venues'], @@ -59,6 +83,5 @@ export default function VenueLoader() { if (isError) return
error
// Hardcoded: show first venue for now if (data.venue.length == 0) return
No venues found
- const first = data.venue[0] - return + return } diff --git a/apps/frontend/src/routeTree.gen.ts b/apps/frontend/src/routeTree.gen.ts index e0e641a..436cbf9 100644 --- a/apps/frontend/src/routeTree.gen.ts +++ b/apps/frontend/src/routeTree.gen.ts @@ -13,6 +13,8 @@ import { Route as IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' import { Route as DemoTanstackQueryRouteImport } from './routes/demo/tanstack-query' import { Route as DemoTodosRouteImport } from './routes/demo/todos' +import { Route as CityIdVenuesIndexRouteImport } from './routes/$cityId/venues/index' +import { Route as CityIdVenuesVenueIdRouteImport } from './routes/$cityId/venues/$venueId' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -34,18 +36,32 @@ const DemoTodosRoute = DemoTodosRouteImport.update({ path: '/demo/todos', getParentRoute: () => rootRouteImport, } as any) +const CityIdVenuesIndexRoute = CityIdVenuesIndexRouteImport.update({ + id: '/$cityId/venues/', + path: '/$cityId/venues/', + getParentRoute: () => rootRouteImport, +} as any) +const CityIdVenuesVenueIdRoute = CityIdVenuesVenueIdRouteImport.update({ + id: '/$cityId/venues/$venueId', + path: '/$cityId/venues/$venueId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/about': typeof AboutRoute '/demo/tanstack-query': typeof DemoTanstackQueryRoute '/demo/todos': typeof DemoTodosRoute + '/$cityId/venues/$venueId': typeof CityIdVenuesVenueIdRoute + '/$cityId/venues/': typeof CityIdVenuesIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/about': typeof AboutRoute '/demo/tanstack-query': typeof DemoTanstackQueryRoute '/demo/todos': typeof DemoTodosRoute + '/$cityId/venues/$venueId': typeof CityIdVenuesVenueIdRoute + '/$cityId/venues': typeof CityIdVenuesIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -53,13 +69,34 @@ export interface FileRoutesById { '/about': typeof AboutRoute '/demo/tanstack-query': typeof DemoTanstackQueryRoute '/demo/todos': typeof DemoTodosRoute + '/$cityId/venues/$venueId': typeof CityIdVenuesVenueIdRoute + '/$cityId/venues/': typeof CityIdVenuesIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' + fullPaths: + | '/' + | '/about' + | '/demo/tanstack-query' + | '/demo/todos' + | '/$cityId/venues/$venueId' + | '/$cityId/venues/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' - id: '__root__' | '/' | '/about' | '/demo/tanstack-query' | '/demo/todos' + to: + | '/' + | '/about' + | '/demo/tanstack-query' + | '/demo/todos' + | '/$cityId/venues/$venueId' + | '/$cityId/venues' + id: + | '__root__' + | '/' + | '/about' + | '/demo/tanstack-query' + | '/demo/todos' + | '/$cityId/venues/$venueId' + | '/$cityId/venues/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -67,6 +104,8 @@ export interface RootRouteChildren { AboutRoute: typeof AboutRoute DemoTanstackQueryRoute: typeof DemoTanstackQueryRoute DemoTodosRoute: typeof DemoTodosRoute + CityIdVenuesVenueIdRoute: typeof CityIdVenuesVenueIdRoute + CityIdVenuesIndexRoute: typeof CityIdVenuesIndexRoute } declare module '@tanstack/react-router' { @@ -99,6 +138,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DemoTodosRouteImport parentRoute: typeof rootRouteImport } + '/$cityId/venues/': { + id: '/$cityId/venues/' + path: '/$cityId/venues' + fullPath: '/$cityId/venues/' + preLoaderRoute: typeof CityIdVenuesIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/$cityId/venues/$venueId': { + id: '/$cityId/venues/$venueId' + path: '/$cityId/venues/$venueId' + fullPath: '/$cityId/venues/$venueId' + preLoaderRoute: typeof CityIdVenuesVenueIdRouteImport + parentRoute: typeof rootRouteImport + } } } @@ -107,6 +160,8 @@ const rootRouteChildren: RootRouteChildren = { AboutRoute: AboutRoute, DemoTanstackQueryRoute: DemoTanstackQueryRoute, DemoTodosRoute: DemoTodosRoute, + CityIdVenuesVenueIdRoute: CityIdVenuesVenueIdRoute, + CityIdVenuesIndexRoute: CityIdVenuesIndexRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/frontend/src/routes/$cityId/venues/$venueId.tsx b/apps/frontend/src/routes/$cityId/venues/$venueId.tsx new file mode 100644 index 0000000..0a77a1a --- /dev/null +++ b/apps/frontend/src/routes/$cityId/venues/$venueId.tsx @@ -0,0 +1,166 @@ +import type { ReactNode } from 'react' +import type { venue } from '#/types/venue' +import { useQuery } from '@tanstack/react-query' +import { Link, createFileRoute } from '@tanstack/react-router' +import { GET_VENUE, ViewVenue } from '#/components/ViewVenue' +import VenueMap from '#/components/VenueMap' +import Breadcrumbs from '#/components/Breadcrumbs' +import { graphqlFetch } from '#/graphql/client' + +export const Route = createFileRoute('/$cityId/venues/$venueId')({ + component: VenuePage, +}) + +function VenuePage() { + const { cityId, venueId } = Route.useParams() + const { data, isPending, isError } = useQuery({ + queryKey: ['venues'], + queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE), + }) + + if (isPending) { + return ( + +

Loading venue…

+
+ ) + } + + if (isError) { + return ( + +

Could not load this venue.

+
+ ) + } + + const current = data.venue.find((candidate) => candidate.id === venueId) + + if (!current || current.city.id !== cityId) { + return ( + +

Venue not found in this city.

+ +
+ ) + } + + const reviews = [...current.reviews].sort((a, b) => + b.createdAt.localeCompare(a.createdAt), + ) + + return ( +
+

{current.name}

+ + +
+ +
+ +
+
+ +
+
+

Guinness reviews

+ + {reviews.length} {reviews.length === 1 ? 'review' : 'reviews'} + +
+ + {reviews.length === 0 ? ( +

+ No Guinness reviews yet. +

+ ) : ( +
    + {reviews.map((review) => ( +
  • +
    +
    +

    {review.author}

    + +
    + +
    +

    + {review.comment} +

    +
  • + ))} +
+ )} +
+
+ ) +} + +function PageShell({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+
+ ) +} + +function BackLink() { + return ( + + ← Back to venues + + ) +} + +function Rating({ rating }: { rating: number }) { + const percent = Math.max(0, Math.min(100, (rating / 5) * 100)) + + return ( + + + + + + + {rating.toFixed(1)} / 5 + + + ) +} + +function formatReviewDate(iso: string) { + return new Intl.DateTimeFormat('en-GB', { + dateStyle: 'medium', + timeZone: 'UTC', + }).format(new Date(iso)) +} diff --git a/apps/frontend/src/routes/$cityId/venues/index.tsx b/apps/frontend/src/routes/$cityId/venues/index.tsx new file mode 100644 index 0000000..b338bb9 --- /dev/null +++ b/apps/frontend/src/routes/$cityId/venues/index.tsx @@ -0,0 +1,80 @@ +import type { ReactNode } from 'react' +import type { venue } from '#/types/venue' +import { useQuery } from '@tanstack/react-query' +import { Link, createFileRoute } from '@tanstack/react-router' +import Breadcrumbs from '#/components/Breadcrumbs' +import { GET_VENUE, VenueCard } from '#/components/ViewVenue' +import { graphqlFetch } from '#/graphql/client' + +export const Route = createFileRoute('/$cityId/venues/')({ + component: CityVenuesPage, +}) + +function CityVenuesPage() { + const { cityId } = Route.useParams() + const { data, isPending, isError } = useQuery({ + queryKey: ['venues'], + queryFn: () => graphqlFetch<{ venue: venue[] }>(GET_VENUE), + }) + + if (isPending) { + return ( + +

Loading venues…

+
+ ) + } + + if (isError) { + return ( + +

Could not load venues.

+
+ ) + } + + const venues = data.venue + .filter((venue) => venue.city.id === cityId) + .sort((a, b) => a.name.localeCompare(b.name)) + const cityName = venues[0]?.city.name + + if (!cityName) { + return ( + +

No venues found in this city.

+ + ← Back to venues + +
+ ) + } + + return ( +
+ +

{cityName}

+

+ {venues.length} {venues.length === 1 ? 'venue' : 'venues'} +

+ +
+ {venues.map((venue) => ( + + ))} +
+
+ ) +} + +function PageShell({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+
+ ) +} diff --git a/apps/frontend/src/types/venue.ts b/apps/frontend/src/types/venue.ts index 47078b4..eda5718 100644 --- a/apps/frontend/src/types/venue.ts +++ b/apps/frontend/src/types/venue.ts @@ -21,11 +21,22 @@ export interface VenuePriceSighting { timeSighted: string } +export interface VenueReview { + id: string + rating: number + comment: string + author: string + createdAt: string +} + export interface venue { id: string name: string address: string + lat: number + lon: number city: VenueCity openingHours: VenueOpeningHours[] - pricesSighted: VenuePriceSighting[] + pricesSighted?: VenuePriceSighting[] + reviews: VenueReview[] } diff --git a/packages/db/prisma/migrations/20261027201007_add_reviews/migration.sql b/packages/db/prisma/migrations/20261027201007_add_reviews/migration.sql new file mode 100644 index 0000000..191c95e --- /dev/null +++ b/packages/db/prisma/migrations/20261027201007_add_reviews/migration.sql @@ -0,0 +1,14 @@ +-- CreateTable +CREATE TABLE "review" ( + "id" UUID NOT NULL DEFAULT uuidv7(), + "rating" DOUBLE PRECISION NOT NULL, + "comment" TEXT NOT NULL, + "author" TEXT NOT NULL, + "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "venue_id" UUID NOT NULL, + + CONSTRAINT "review_pkey" PRIMARY KEY ("id") +); + +-- AddForeignKey +ALTER TABLE "review" ADD CONSTRAINT "review_venue_id_fkey" FOREIGN KEY ("venue_id") REFERENCES "venue"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index f23583e..ab6ec11 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -55,6 +55,7 @@ model Venue { city City @relation(fields: [cityId], references: [id]) pricesSighted PriceSighting[] + reviews Review[] @@map("venue") } @@ -97,3 +98,16 @@ model PriceSighting { @@map("price_sighting") } + +model Review { + id String @id @default(dbgenerated("uuidv7()")) @db.Uuid + rating Float + comment String + author String + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + venueId String @map("venue_id") @db.Uuid + venue Venue @relation(fields: [venueId], references: [id]) + + @@map("review") +} diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts index b39d743..4ce0f7c 100644 --- a/packages/db/prisma/seed.ts +++ b/packages/db/prisma/seed.ts @@ -10,6 +10,7 @@ function at(time: string) { async function main() { console.log('Seeding database...') + await prisma.review.deleteMany() await prisma.priceSighting.deleteMany() await prisma.openingHours.deleteMany() await prisma.venue.deleteMany() @@ -65,6 +66,31 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Ingrid', + rating: 5, + comment: + 'Perfect pour and a proper creamy head. Hard to beat on a sunny afternoon by the river.', + createdAt: '2026-10-12T18:20:00Z', + }, + { + author: 'Jonas', + rating: 4.5, + comment: + 'Consistently good Guinness. A bit busy on Fridays, but worth the wait.', + createdAt: '2026-09-28T20:05:00Z', + }, + { + author: 'Marta', + rating: 4, + comment: + 'Lovely pub, though my pint sat a little too long before it reached the table.', + createdAt: '2026-08-19T19:15:00Z', + }, + ], + }, }, { name: 'Skjenkestua', @@ -101,6 +127,24 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Eirik', + rating: 4.5, + comment: + 'Creamy and cold with a nice bitter finish. The snug atmosphere helps.', + createdAt: '2026-10-03T21:10:00Z', + }, + { + author: 'Hanne', + rating: 3.5, + comment: + 'Decent pint, but the head was thinner than I expected for a Guinness.', + createdAt: '2026-09-11T17:40:00Z', + }, + ], + }, }, { name: 'Baklandet Skydsstation', @@ -132,6 +176,24 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Sofie', + rating: 5, + comment: + 'A genuinely great pour in a beautiful old building. Could have stayed all evening.', + createdAt: '2026-10-18T19:00:00Z', + }, + { + author: 'Anders', + rating: 4, + comment: + 'Smooth and well kept. Slightly warm by the time we got our second round.', + createdAt: '2026-09-22T18:35:00Z', + }, + ], + }, }, { name: 'Trondheim Torg Pub', @@ -171,6 +233,24 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Kari', + rating: 3.5, + comment: + 'Fine lunchtime Guinness. Not the best in town, but reliable and central.', + createdAt: '2026-10-06T13:20:00Z', + }, + { + author: 'Petter', + rating: 4, + comment: + 'Good price for a pint and the staff knows how to pour it.', + createdAt: '2026-08-30T12:45:00Z', + }, + ], + }, }, ], }, @@ -216,6 +296,24 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Niamh', + rating: 5, + comment: + 'As close to a Dublin pint as you will get in Oslo. Great craic too.', + createdAt: '2026-10-20T20:30:00Z', + }, + { + author: 'Lars', + rating: 4.5, + comment: + 'Proper pub, proper Guinness. The live music was a bonus.', + createdAt: '2026-09-14T21:15:00Z', + }, + ], + }, }, { name: 'Tilt', @@ -256,21 +354,48 @@ async function main() { }, ], }, + reviews: { + create: [ + { + author: 'Camilla', + rating: 4, + comment: + 'Good pint and plenty to do. A solid spot for a long evening.', + createdAt: '2026-10-11T20:15:00Z', + }, + { + author: 'Ola', + rating: 3.5, + comment: + 'The Guinness was decent, though I would have liked a thicker head.', + createdAt: '2026-09-05T19:50:00Z', + }, + { + author: 'Thea', + rating: 4.5, + comment: + 'Friendly bartenders and a very clean pour. Will come back.', + createdAt: '2026-08-24T18:10:00Z', + }, + ], + }, }, ], }, }, }) - const [cities, venues, openingHours, priceSightings] = await Promise.all([ - prisma.city.count(), - prisma.venue.count(), - prisma.openingHours.count(), - prisma.priceSighting.count(), - ]) + const [cities, venues, openingHours, priceSightings, reviews] = + await Promise.all([ + prisma.city.count(), + prisma.venue.count(), + prisma.openingHours.count(), + prisma.priceSighting.count(), + prisma.review.count(), + ]) console.log( - `Created ${cities} cities, ${venues} venues, ${openingHours} opening hours entries, and ${priceSightings} price sightings`, + `Created ${cities} cities, ${venues} venues, ${openingHours} opening hours entries, ${priceSightings} price sightings, and ${reviews} reviews`, ) } From 523bfed7cf921186ddda7477e74ae16c5dec747c Mon Sep 17 00:00:00 2001 From: Nicolay Bennett Rennemo Date: Tue, 27 Oct 2026 21:59:39 +0100 Subject: [PATCH 2/4] Fix tailwind warnings --- apps/frontend/src/components/ViewVenue.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/frontend/src/components/ViewVenue.tsx b/apps/frontend/src/components/ViewVenue.tsx index 9b7daa6..0cd088f 100644 --- a/apps/frontend/src/components/ViewVenue.tsx +++ b/apps/frontend/src/components/ViewVenue.tsx @@ -15,10 +15,10 @@ export function ViewVenue({ kicker?: string }) { return ( -
+

{kicker}

{venue.name}

-

{venue.address}

+

{venue.address}

{venue.latestPriceSighting && (

Latest price:{' '} @@ -31,12 +31,12 @@ export function ViewVenue({ {venue.openingHours.map((openingHours, index) => (

  • {openingHours.days.join(', ')} - + {formatTime(openingHours.opening)} -{' '} {formatTime(openingHours.closing)} @@ -44,7 +44,7 @@ export function ViewVenue({ ))} ) : ( -

    +

    No opening hours listed.

    )} From 52449fb8a2f594591df6322079fbdfd3ad69765c Mon Sep 17 00:00:00 2001 From: Nicolay Bennett Rennemo Date: Thu, 29 Oct 2026 13:04:44 +0100 Subject: [PATCH 3/4] Added functionality for adding reviews, user name stored in localstorage --- .../src/components/AddReviewDialog.tsx | 259 ++++++++++++++++++ apps/frontend/src/components/Header.tsx | 9 +- apps/frontend/src/graphql/venues.ts | 12 + .../src/routes/$cityId/venues/$venueId.tsx | 22 +- apps/frontend/src/styles.css | 18 +- 5 files changed, 301 insertions(+), 19 deletions(-) create mode 100644 apps/frontend/src/components/AddReviewDialog.tsx diff --git a/apps/frontend/src/components/AddReviewDialog.tsx b/apps/frontend/src/components/AddReviewDialog.tsx new file mode 100644 index 0000000..9d7cf0d --- /dev/null +++ b/apps/frontend/src/components/AddReviewDialog.tsx @@ -0,0 +1,259 @@ +import type { FormEvent } from 'react' +import { useId, useRef, useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' + +import { graphqlFetch } from '#/graphql/client' +import { CREATE_REVIEW } from '#/graphql/venues' +import type { VenueReview } from '#/types/venue' + +const USERNAME_STORAGE_KEY = 'g-spotter:review-username' +const BODY_MAX_LENGTH = 1000 +const RATING_VALUES = [1, 2, 3, 4, 5] + +interface ReviewInput { + venueId: string + username: string + body: string + rating: number +} + +export default function AddReviewDialog({ + venueId, + venueName, +}: { + venueId: string + venueName: string +}) { + const dialogRef = useRef(null) + const nameInputRef = useRef(null) + const titleId = useId() + const descriptionId = useId() + const nameId = useId() + const bodyId = useId() + const errorId = useId() + + const [username, setUsername] = useState('') + const [rating, setRating] = useState(0) + const [hoveredRating, setHoveredRating] = useState(0) + const [body, setBody] = useState('') + const [error, setError] = useState(null) + + const queryClient = useQueryClient() + + const { mutate, isPending } = useMutation({ + mutationFn: (input: ReviewInput) => + graphqlFetch<{ createReview: VenueReview }>(CREATE_REVIEW, { input }), + onSuccess: () => { + setRating(0) + setHoveredRating(0) + setBody('') + setError(null) + dialogRef.current?.close() + void queryClient.invalidateQueries({ queryKey: ['venues'] }) + }, + onError: () => { + setError('Could not post your review. Please try again.') + }, + }) + + const visibleRating = hoveredRating || rating + + function openDialog() { + const savedName = window.localStorage.getItem(USERNAME_STORAGE_KEY) + if (savedName) { + setUsername(savedName) + } + setError(null) + dialogRef.current?.showModal() + } + + function closeDialog() { + dialogRef.current?.close() + } + + function handleSubmit(event: FormEvent) { + event.preventDefault() + + if (isPending) return + + const trimmedName = username.trim() + const trimmedBody = body.trim() + + if (!trimmedName) { + setError('Please enter your name.') + nameInputRef.current?.focus() + return + } + + if (rating < 1) { + setError('Please choose a rating.') + return + } + + if (!trimmedBody) { + setError('Please write a short review.') + return + } + + setError(null) + window.localStorage.setItem(USERNAME_STORAGE_KEY, trimmedName) + mutate({ + venueId, + username: trimmedName, + body: trimmedBody, + rating, + }) + } + + return ( + <> + + + { + if (event.target === dialogRef.current) { + closeDialog() + } + }} + className="m-auto max-h-[calc(100dvh_-_2rem)] w-[min(30rem,calc(100vw_-_2rem))] overflow-y-auto rounded-2xl border border-(--line) bg-(--surface-strong) p-0 text-(--sea-ink) shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm" + > +
    +

    + Add a review +

    +

    + Share your thoughts about {venueName}. +

    + +
    +
    + + setUsername(event.target.value)} + maxLength={50} + required + autoComplete="nickname" + placeholder="e.g. Kari" + className="w-full rounded-xl border border-(--line) bg-(--chip-bg) px-3 py-2 text-sm text-(--sea-ink) outline-none placeholder:text-(--sea-ink-soft) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--lagoon-deep)" + /> +
    + +
    + Rating +
    setHoveredRating(0)} + > + {RATING_VALUES.map((value) => ( + + ))} + + {rating > 0 ? `${rating} / 5` : 'Select a rating'} + +
    +
    + +
    +
    + + + {body.length}/{BODY_MAX_LENGTH} + +
    +