From 974b5f66f6644d188cff7ced5a7824e0d8189235 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A1udio=20Silva?= <38473739+GarliqBread@users.noreply.github.com> Date: Wed, 30 Sep 2026 14:00:13 +0200 Subject: [PATCH] redesign host and join pages --- apps/api/src/sessions/routes.test.ts | 44 ++++ apps/api/src/sessions/routes.ts | 15 +- apps/api/src/sessions/service.test.ts | 27 ++ apps/api/src/sessions/service.ts | 25 +- apps/web/index.html | 2 +- apps/web/src/features/entry/entry-layout.ts | 7 + apps/web/src/features/host/HostDesktop.tsx | 61 +++++ apps/web/src/features/host/HostPhone.tsx | 56 ++++ apps/web/src/features/host/HostScreen.tsx | 73 ++++++ apps/web/src/features/host/host-layout.ts | 2 + apps/web/src/features/join/JoinDesktop.tsx | 61 +++++ apps/web/src/features/join/JoinFields.tsx | 52 ++++ apps/web/src/features/join/JoinPhone.tsx | 38 +++ apps/web/src/features/join/JoinScreen.tsx | 105 +++----- apps/web/src/features/join/join-layout.ts | 2 + apps/web/src/lib/sessions.ts | 7 +- apps/web/src/lib/use-media-query.ts | 15 ++ apps/web/src/routes/host.index.tsx | 53 +--- packages/games/src/setup-schema.ts | 8 + packages/messages/src/locales/en.json | 23 +- packages/ui/src/entry/Entry.stories.tsx | 153 +++++++++++ packages/ui/src/entry/EntryHero.tsx | 66 +++++ packages/ui/src/entry/EntryShell.tsx | 22 ++ packages/ui/src/entry/HowItWorksSteps.tsx | 59 +++++ packages/ui/src/entry/TvMock.tsx | 64 +++++ packages/ui/src/icons/Icons.stories.tsx | 1 + packages/ui/src/icons/Logo.tsx | 15 +- packages/ui/src/icons/icons.tsx | 7 + packages/ui/src/index.ts | 4 + packages/ui/src/layout/Layouts.stories.tsx | 3 +- packages/ui/src/layout/PhoneShell.tsx | 11 +- packages/ui/src/lib/cn.ts | 6 +- packages/ui/src/primitives/FieldFrame.tsx | 9 +- .../ui/src/primitives/Heading.stories.tsx | 1 + packages/ui/src/primitives/Heading.tsx | 1 + .../src/primitives/RoomCodeInput.stories.tsx | 33 ++- packages/ui/src/primitives/RoomCodeInput.tsx | 245 +++++++++++++++--- .../ui/src/primitives/TrustNote.stories.tsx | 8 +- packages/ui/src/primitives/TrustNote.tsx | 44 ++-- packages/ui/src/screens/Phone.stories.tsx | 49 +--- packages/ui/src/theme.css | 5 + packages/ui/src/workshop/Sticker.tsx | 1 + packages/ui/src/workshop/Workshop.stories.tsx | 3 + 43 files changed, 1259 insertions(+), 227 deletions(-) create mode 100644 apps/web/src/features/entry/entry-layout.ts create mode 100644 apps/web/src/features/host/HostDesktop.tsx create mode 100644 apps/web/src/features/host/HostPhone.tsx create mode 100644 apps/web/src/features/host/HostScreen.tsx create mode 100644 apps/web/src/features/host/host-layout.ts create mode 100644 apps/web/src/features/join/JoinDesktop.tsx create mode 100644 apps/web/src/features/join/JoinFields.tsx create mode 100644 apps/web/src/features/join/JoinPhone.tsx create mode 100644 apps/web/src/features/join/join-layout.ts create mode 100644 apps/web/src/lib/use-media-query.ts create mode 100644 packages/ui/src/entry/Entry.stories.tsx create mode 100644 packages/ui/src/entry/EntryHero.tsx create mode 100644 packages/ui/src/entry/EntryShell.tsx create mode 100644 packages/ui/src/entry/HowItWorksSteps.tsx create mode 100644 packages/ui/src/entry/TvMock.tsx diff --git a/apps/api/src/sessions/routes.test.ts b/apps/api/src/sessions/routes.test.ts index 011a9d8..90b3690 100644 --- a/apps/api/src/sessions/routes.test.ts +++ b/apps/api/src/sessions/routes.test.ts @@ -1,3 +1,4 @@ +import { SESSION_NAME_MAX_LENGTH } from "@gamemash/games/config"; import type { CreateSessionResponse } from "@gamemash/shared"; import { describe, expect, it } from "vitest"; import { buildApp } from "../app.js"; @@ -24,6 +25,49 @@ describe("POST /api/sessions", () => { expect(body.sessionId).toMatch(/^[0-9a-f-]{36}$/); expect(body.hostToken).toBeTruthy(); }); + + it("starts the setup with the session name it was given", async () => { + const app = setup(); + + const created = ( + await app.inject({ method: "POST", url: "/api/sessions", payload: { name: " Friday team mash " } }) + ).json(); + const loaded = await app.inject({ + method: "GET", + url: `/api/sessions/${created.sessionId}/setup`, + headers: { authorization: `Bearer ${created.hostToken}` }, + }); + + expect(loaded.json().setup).toEqual({ name: "Friday team mash", games: [] }); + }); + + it("leaves the setup empty when the name is blank", async () => { + const app = setup(); + + const created = ( + await app.inject({ method: "POST", url: "/api/sessions", payload: { name: " " } }) + ).json(); + const loaded = await app.inject({ + method: "GET", + url: `/api/sessions/${created.sessionId}/setup`, + headers: { authorization: `Bearer ${created.hostToken}` }, + }); + + expect(loaded.json().setup).toEqual({ name: "", games: [] }); + }); + + it.each([ + ["a name that is too long", { name: "x".repeat(SESSION_NAME_MAX_LENGTH + 1) }], + ["hidden characters", { name: "Friday\u200Bmash" }], + ["unknown fields", { name: "Friday", extra: true }], + ])("rejects %s", async (_label, payload) => { + const app = setup(); + + const response = await app.inject({ method: "POST", url: "/api/sessions", payload }); + + expect(response.statusCode).toBe(400); + expect(response.json()).toEqual({ code: "bad_request" }); + }); }); describe("GET /api/sessions/by-code/:code", () => { diff --git a/apps/api/src/sessions/routes.ts b/apps/api/src/sessions/routes.ts index b809ee9..030d716 100644 --- a/apps/api/src/sessions/routes.ts +++ b/apps/api/src/sessions/routes.ts @@ -1,4 +1,5 @@ import type { FastifyPluginAsyncTypebox } from "@fastify/type-provider-typebox"; +import { CreateSessionBodySchema } from "@gamemash/games/schemas"; import { type ErrorCode, isRoomCode, normalizeRoomCode, PLAYER_NAME_MAX_LENGTH } from "@gamemash/shared"; import { ApiErrorSchema, @@ -57,9 +58,19 @@ export const sessionRoutes = "/api/sessions", { config: { rateLimit: { max: limits.sessionsPerMinute, timeWindow: MINUTE_MS, keyGenerator: byClient } }, - schema: { response: { 201: CreateSessionResponseSchema } }, + schema: { + body: CreateSessionBodySchema, + response: { 201: CreateSessionResponseSchema, 400: ApiErrorSchema }, + }, + preValidation: async (request) => { + request.body ??= {}; + }, + }, + async (request, reply) => { + const result = await sessions.createNamed(request.body.name ?? ""); + if (!result.ok) return reply.code(400).send({ code: result.error }); + return reply.code(201).send(result.value); }, - async (_request, reply) => reply.code(201).send(await sessions.create()), ); app.get( diff --git a/apps/api/src/sessions/service.test.ts b/apps/api/src/sessions/service.test.ts index 398ee14..ec2b4a9 100644 --- a/apps/api/src/sessions/service.test.ts +++ b/apps/api/src/sessions/service.test.ts @@ -40,6 +40,33 @@ describe("createSessionService", () => { await expect(service.create()).rejects.toBeInstanceOf(RoomCodesExhaustedError); }); + + it("refuses a session name with hidden characters", async () => { + const service = createSessionService({ store: createMemorySessionStore() }); + + const result = await service.createNamed("Friday\u200Bmash"); + + expect(result).toEqual({ ok: false, error: "bad_request" }); + }); + + it("still creates the session when its name cannot be saved", async () => { + const store = createMemorySessionStore(); + const warnings: unknown[] = []; + const service = createSessionService({ + store: { + ...store, + saveSetup: async () => { + throw new Error("redis down"); + }, + }, + log: { warn: (details: unknown) => warnings.push(details) }, + }); + + const result = await service.createNamed("Friday team mash"); + + expect(result.ok).toBe(true); + expect(warnings).toHaveLength(1); + }); }); describe("sessionExpiresAt", () => { diff --git a/apps/api/src/sessions/service.ts b/apps/api/src/sessions/service.ts index c691230..37d4868 100644 --- a/apps/api/src/sessions/service.ts +++ b/apps/api/src/sessions/service.ts @@ -111,9 +111,25 @@ export const createSessionService = ({ const touch = async (session: SessionRecord) => store.touch(session, sessionExpiresAt(session.createdAt, now())); - const create = async (): Promise => { + const nameSession = async (session: SessionRecord, name: string) => { + const setup: SessionSetup = { ...emptySetup(), name }; + const summary: LobbySummary = { ...EMPTY_SUMMARY, name }; + try { + await store.saveSetup( + session.id, + JSON.stringify(setup), + JSON.stringify(summary), + sessionExpiresAt(session.createdAt, session.createdAt), + ); + } catch (error) { + log?.warn({ sessionId: session.id, error }, "could not save the session name"); + } + }; + + const create = async (name = ""): Promise => { const hostToken = createSecret(); const createdAt = now(); + const sessionName = name.trim(); for (let attempt = 0; attempt < MAX_ROOM_CODE_ATTEMPTS; attempt += 1) { const session: SessionRecord = { id: createId(), @@ -123,12 +139,18 @@ export const createSessionService = ({ createdAt, }; if ((await store.create(session, sessionExpiresAt(createdAt, createdAt))) === "created") { + if (sessionName) await nameSession(session, sessionName); return { sessionId: session.id, roomCode: session.roomCode, hostToken }; } } throw new RoomCodesExhaustedError(); }; + const createNamed = async (name: string): Promise> => { + if (hasHiddenCharacters(name)) return fail("bad_request"); + return { ok: true, value: await create(name) }; + }; + const join = async (sessionId: string, rawName: string): Promise> => { const name = normalizePlayerName(rawName); if (!isValidName(name)) return fail("invalid_name"); @@ -348,6 +370,7 @@ export const createSessionService = ({ return { create, + createNamed, findByRoomCode: (code: string) => store.findByRoomCode(code), join, authenticateHost, diff --git a/apps/web/index.html b/apps/web/index.html index e08d5ea..ff0c2fd 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,7 +2,7 @@ - + GameMash diff --git a/apps/web/src/features/entry/entry-layout.ts b/apps/web/src/features/entry/entry-layout.ts new file mode 100644 index 0000000..336a311 --- /dev/null +++ b/apps/web/src/features/entry/entry-layout.ts @@ -0,0 +1,7 @@ +import type { FormEvent, ReactNode } from "react"; + +export type EntryLayoutProps = { + fields: ReactNode; + submit: ReactNode; + onSubmit: (event: FormEvent) => void; +}; diff --git a/apps/web/src/features/host/HostDesktop.tsx b/apps/web/src/features/host/HostDesktop.tsx new file mode 100644 index 0000000..a6fcc3d --- /dev/null +++ b/apps/web/src/features/host/HostDesktop.tsx @@ -0,0 +1,61 @@ +import { + buttonVariants, + EntryShell, + Heading, + HowItWorksSteps, + Logo, + PhoneIcon, + Sticker, + TrustNote, +} from "@gamemash/ui"; +import { Link } from "@tanstack/react-router"; +import { FormattedMessage } from "react-intl"; +import type { EntryLayoutProps } from "../entry/entry-layout"; +import { HOST_FORM_ID, HOST_STEPS } from "./host-layout"; + +export const HostDesktop = ({ fields, submit, onSubmit }: EntryLayoutProps) => ( + } + action={ + + + + + } + mainClassName="flex-col items-center gap-10" + > +
+
+ + + + + + +

+ +

+ {fields} +
{submit}
+
+
+ + + + + + +
+
+ )} + /> +
+); diff --git a/apps/web/src/features/host/HostPhone.tsx b/apps/web/src/features/host/HostPhone.tsx new file mode 100644 index 0000000..fa19cc9 --- /dev/null +++ b/apps/web/src/features/host/HostPhone.tsx @@ -0,0 +1,56 @@ +import { buttonVariants, Heading, HowItWorksSteps, Logo, PhoneShell, TrustNote, TvMock } from "@gamemash/ui"; +import { Link } from "@tanstack/react-router"; +import { FormattedMessage, useIntl } from "react-intl"; +import type { EntryLayoutProps } from "../entry/entry-layout"; +import { HOST_FORM_ID, HOST_STEPS } from "./host-layout"; + +const SAMPLE_ROOM_CODE = "KWPX"; + +export const HostPhone = ({ fields, submit, onSubmit }: EntryLayoutProps) => { + const intl = useIntl(); + return ( + + + + + + + } + footer={ + + + + } + bottomAction={ + <> + {submit} +

+ +

+ + } + > + + + + + )} /> +
+ {fields} +
+
+ ); +}; diff --git a/apps/web/src/features/host/HostScreen.tsx b/apps/web/src/features/host/HostScreen.tsx new file mode 100644 index 0000000..68a6bf0 --- /dev/null +++ b/apps/web/src/features/host/HostScreen.tsx @@ -0,0 +1,73 @@ +import { SESSION_NAME_MAX_LENGTH } from "@gamemash/games/config"; +import { stripHiddenCharacters } from "@gamemash/shared"; +import { Button, PlayIcon, TextField } from "@gamemash/ui"; +import { useMutation } from "@tanstack/react-query"; +import { useNavigate } from "@tanstack/react-router"; +import { type FormEvent, useState } from "react"; +import { FormattedMessage, useIntl } from "react-intl"; +import { saveCredentials } from "../../lib/credentials"; +import { toApiError, useErrorMessage } from "../../lib/errors"; +import { createSession } from "../../lib/sessions"; +import { DESKTOP_QUERY, useMediaQuery } from "../../lib/use-media-query"; +import { HostDesktop } from "./HostDesktop"; +import { HostPhone } from "./HostPhone"; +import { HOST_FORM_ID } from "./host-layout"; + +export const HostScreen = () => { + const intl = useIntl(); + const navigate = useNavigate(); + const formatError = useErrorMessage(); + const isDesktop = useMediaQuery(DESKTOP_QUERY); + const [name, setName] = useState(""); + const create = useMutation({ + mutationFn: createSession, + onSuccess: ({ sessionId, roomCode, hostToken }) => { + saveCredentials({ role: "host", sessionId, roomCode, hostToken }); + void navigate({ to: "/host/$sessionId/setup", params: { sessionId } }); + }, + }); + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + create.mutate(name); + }; + + const fields = ( + <> + {chunks} }} + /> + } + placeholder={intl.formatMessage({ id: "host.namePlaceholder" })} + maxLength={SESSION_NAME_MAX_LENGTH} + value={name} + onValueChange={(value: string) => setName(stripHiddenCharacters(value))} + controlClassName="workshop:h-14 workshop:rounded-control workshop:shadow-brutal-sm" + /> + {create.isError && ( +

+ {formatError(toApiError(create.error))} +

+ )} + + ); + + const submit = ( + + ); + + const Layout = isDesktop ? HostDesktop : HostPhone; + return ; +}; diff --git a/apps/web/src/features/host/host-layout.ts b/apps/web/src/features/host/host-layout.ts new file mode 100644 index 0000000..be316f9 --- /dev/null +++ b/apps/web/src/features/host/host-layout.ts @@ -0,0 +1,2 @@ +export const HOST_FORM_ID = "host"; +export const HOST_STEPS = ["host.step1", "host.step2", "host.step3"]; diff --git a/apps/web/src/features/join/JoinDesktop.tsx b/apps/web/src/features/join/JoinDesktop.tsx new file mode 100644 index 0000000..b0c1162 --- /dev/null +++ b/apps/web/src/features/join/JoinDesktop.tsx @@ -0,0 +1,61 @@ +import { + buttonVariants, + EntryHero, + EntryShell, + Heading, + HowItWorksSteps, + Logo, + MonitorIcon, + Sticker, +} from "@gamemash/ui"; +import { Link } from "@tanstack/react-router"; +import { FormattedMessage } from "react-intl"; +import type { EntryLayoutProps } from "../entry/entry-layout"; +import { JOIN_FORM_ID, JOIN_STEPS } from "./join-layout"; + +export const JoinDesktop = ({ fields, submit, onSubmit }: EntryLayoutProps) => ( + } + action={ + + + + + } + mainClassName="max-[1099px]:flex-col min-[1100px]:flex-row-reverse" + > +
+
+ + + + {fields} +
{submit}
+
+
+ + + +
+
+
+ + + + + + + )} + /> + +
+
+); diff --git a/apps/web/src/features/join/JoinFields.tsx b/apps/web/src/features/join/JoinFields.tsx new file mode 100644 index 0000000..c0b2422 --- /dev/null +++ b/apps/web/src/features/join/JoinFields.tsx @@ -0,0 +1,52 @@ +import { PLAYER_NAME_MAX_LENGTH, ROOM_CODE_LENGTH } from "@gamemash/shared"; +import { RoomCodeInput, TextField } from "@gamemash/ui"; +import { FormattedMessage, useIntl } from "react-intl"; + +export type JoinFieldErrors = { + code?: string | undefined; + name?: string | undefined; + form?: string | undefined; +}; + +export type JoinFieldsProps = { + size: "phone" | "desktop"; + code: string; + name: string; + errors: JoinFieldErrors; + onCodeChange: (code: string) => void; + onNameChange: (name: string) => void; +}; + +export const JoinFields = ({ size, code, name, errors, onCodeChange, onNameChange }: JoinFieldsProps) => { + const intl = useIntl(); + return ( + <> + } + description={} + value={code} + onValueChange={onCodeChange} + letterLabel={(position, length) => intl.formatMessage({ id: "join.codeLetter" }, { position, length })} + error={errors.code} + length={ROOM_CODE_LENGTH} + /> + } + placeholder={intl.formatMessage({ id: "join.namePlaceholder" })} + autoComplete="nickname" + maxLength={PLAYER_NAME_MAX_LENGTH} + value={name} + onValueChange={onNameChange} + error={errors.name} + className={size === "phone" ? "mt-2" : "mt-2.5"} + controlClassName="workshop:h-14 workshop:rounded-control workshop:shadow-none" + /> + {errors.form && ( +

+ {errors.form} +

+ )} + + ); +}; diff --git a/apps/web/src/features/join/JoinPhone.tsx b/apps/web/src/features/join/JoinPhone.tsx new file mode 100644 index 0000000..13f73aa --- /dev/null +++ b/apps/web/src/features/join/JoinPhone.tsx @@ -0,0 +1,38 @@ +import { EntryHero, Heading, Logo, PhoneShell } from "@gamemash/ui"; +import { Link } from "@tanstack/react-router"; +import { FormattedMessage } from "react-intl"; +import type { EntryLayoutProps } from "../entry/entry-layout"; +import { JOIN_FORM_ID } from "./join-layout"; + +export const JoinPhone = ({ fields, submit, onSubmit }: EntryLayoutProps) => ( + } + bottomAction={ + <> + {submit} + + + + + } + > + + + + +
+ {fields} +
+
+); diff --git a/apps/web/src/features/join/JoinScreen.tsx b/apps/web/src/features/join/JoinScreen.tsx index 509328f..ff6cd1e 100644 --- a/apps/web/src/features/join/JoinScreen.tsx +++ b/apps/web/src/features/join/JoinScreen.tsx @@ -6,25 +6,24 @@ import { PLAYER_NAME_MAX_LENGTH, ROOM_CODE_LENGTH, } from "@gamemash/shared"; -import { Button, Heading, Logo, PhoneShell, RoomCodeInput, TextField, TrustNote } from "@gamemash/ui"; +import { Button } from "@gamemash/ui"; import { useMutation } from "@tanstack/react-query"; -import { Link, useNavigate } from "@tanstack/react-router"; +import { useNavigate } from "@tanstack/react-router"; import { type FormEvent, useState } from "react"; import { FormattedMessage, useIntl } from "react-intl"; import { saveCredentials } from "../../lib/credentials"; import { toApiError, useErrorMessage } from "../../lib/errors"; +import { DESKTOP_QUERY, useMediaQuery } from "../../lib/use-media-query"; +import { JoinDesktop } from "./JoinDesktop"; +import { type JoinFieldErrors, JoinFields } from "./JoinFields"; +import { JoinPhone } from "./JoinPhone"; +import { JOIN_FORM_ID } from "./join-layout"; import { joinRoom } from "./join-session"; -type FieldErrors = { - code?: string | undefined; - name?: string | undefined; - form?: string | undefined; -}; - const CODE_ERRORS: ErrorCode[] = ["room_not_found"]; const NAME_ERRORS: ErrorCode[] = ["invalid_name", "name_taken"]; -const fieldFor = (error: ApiError): keyof FieldErrors => { +const fieldFor = (error: ApiError): keyof JoinFieldErrors => { if (CODE_ERRORS.includes(error.code)) return "code"; if (NAME_ERRORS.includes(error.code)) return "name"; return "form"; @@ -38,9 +37,10 @@ export const JoinScreen = ({ initialCode }: JoinScreenProps) => { const intl = useIntl(); const formatError = useErrorMessage(); const navigate = useNavigate(); + const isDesktop = useMediaQuery(DESKTOP_QUERY); const [code, setCode] = useState(initialCode); const [name, setName] = useState(""); - const [errors, setErrors] = useState({}); + const [errors, setErrors] = useState({}); const join = useMutation({ mutationFn: joinRoom, @@ -58,7 +58,7 @@ export const JoinScreen = ({ initialCode }: JoinScreenProps) => { event.preventDefault(); const roomCode = normalizeRoomCode(code); const playerName = normalizePlayerName(name); - const nextErrors: FieldErrors = { + const nextErrors: JoinFieldErrors = { code: roomCode.length === ROOM_CODE_LENGTH ? undefined @@ -70,60 +70,35 @@ export const JoinScreen = ({ initialCode }: JoinScreenProps) => { join.mutate({ roomCode, name: playerName }); }; - return ( - } - footer={ -
- - - - - - -
- } - bottomAction={ - - } + const fields = ( + { + setCode(value); + setErrors((current) => ({ ...current, code: undefined })); + }} + onNameChange={(value) => { + setName(value); + setErrors((current) => ({ ...current, name: undefined })); + }} + /> + ); + + const submit = ( + ); + + const Layout = isDesktop ? JoinDesktop : JoinPhone; + return ; }; diff --git a/apps/web/src/features/join/join-layout.ts b/apps/web/src/features/join/join-layout.ts new file mode 100644 index 0000000..d35e051 --- /dev/null +++ b/apps/web/src/features/join/join-layout.ts @@ -0,0 +1,2 @@ +export const JOIN_FORM_ID = "join"; +export const JOIN_STEPS = ["join.step1", "join.step2", "join.step3"]; diff --git a/apps/web/src/lib/sessions.ts b/apps/web/src/lib/sessions.ts index 1b05715..a62b67f 100644 --- a/apps/web/src/lib/sessions.ts +++ b/apps/web/src/lib/sessions.ts @@ -1,7 +1,12 @@ import type { CreateSessionResponse, JoinSessionResponse, RoomLookupResponse } from "@gamemash/shared"; import { fetchJson } from "./api"; -export const createSession = () => fetchJson("/api/sessions", { method: "POST" }); +export const createSession = (name: string) => + fetchJson("/api/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(name.trim() ? { name } : {}), + }); export const lookupRoom = (code: string) => fetchJson(`/api/sessions/by-code/${encodeURIComponent(code)}`); diff --git a/apps/web/src/lib/use-media-query.ts b/apps/web/src/lib/use-media-query.ts new file mode 100644 index 0000000..979ca6f --- /dev/null +++ b/apps/web/src/lib/use-media-query.ts @@ -0,0 +1,15 @@ +import { useCallback, useMemo, useSyncExternalStore } from "react"; + +export const useMediaQuery = (query: string) => { + const media = useMemo(() => window.matchMedia(query), [query]); + const subscribe = useCallback( + (onChange: () => void) => { + media.addEventListener("change", onChange); + return () => media.removeEventListener("change", onChange); + }, + [media], + ); + return useSyncExternalStore(subscribe, () => media.matches); +}; + +export const DESKTOP_QUERY = "(min-width: 900px)"; diff --git a/apps/web/src/routes/host.index.tsx b/apps/web/src/routes/host.index.tsx index 4eae630..f0a16ca 100644 --- a/apps/web/src/routes/host.index.tsx +++ b/apps/web/src/routes/host.index.tsx @@ -1,53 +1,6 @@ -import { Button, Heading, Logo, PhoneShell, TrustNote } from "@gamemash/ui"; -import { useMutation } from "@tanstack/react-query"; -import { createFileRoute, useNavigate } from "@tanstack/react-router"; -import { FormattedMessage } from "react-intl"; -import { saveCredentials } from "../lib/credentials"; -import { toApiError, useErrorMessage } from "../lib/errors"; -import { createSession } from "../lib/sessions"; - -const HostStartPage = () => { - const navigate = useNavigate(); - const formatError = useErrorMessage(); - const create = useMutation({ - mutationFn: createSession, - onSuccess: ({ sessionId, roomCode, hostToken }) => { - saveCredentials({ role: "host", sessionId, roomCode, hostToken }); - void navigate({ to: "/host/$sessionId/setup", params: { sessionId } }); - }, - }); - - return ( - } - footer={ - - - - } - bottomAction={ - - } - > - - - -

- -

- {create.isError && ( -

- {formatError(toApiError(create.error))} -

- )} -
- ); -}; +import { createFileRoute } from "@tanstack/react-router"; +import { HostScreen } from "../features/host/HostScreen"; export const Route = createFileRoute("/host/")({ - component: HostStartPage, + component: HostScreen, }); diff --git a/packages/games/src/setup-schema.ts b/packages/games/src/setup-schema.ts index c33476e..43b9582 100644 --- a/packages/games/src/setup-schema.ts +++ b/packages/games/src/setup-schema.ts @@ -34,6 +34,14 @@ export const SessionSetupSchema = Type.Object( ); export type SessionSetup = Static; +export const CreateSessionBodySchema = Type.Object( + { + name: Type.Optional(Type.String({ maxLength: SESSION_NAME_MAX_LENGTH })), + }, + { additionalProperties: false }, +); +export type CreateSessionBody = Static; + export const HostSetupResponseSchema = Type.Object( { setup: SessionSetupSchema, diff --git a/packages/messages/src/locales/en.json b/packages/messages/src/locales/en.json index cdd3896..072d76c 100644 --- a/packages/messages/src/locales/en.json +++ b/packages/messages/src/locales/en.json @@ -9,17 +9,36 @@ "join.title": "Join the game", "join.codeLabel": "Room code", "join.codeDescription": "It's shown on the big screen", + "join.codeLetter": "Letter {position, number} of {length, number}", "join.codeIncomplete": "Enter all {length} letters of the room code", "join.nameLabel": "Your name", "join.namePlaceholder": "e.g. Potato", "join.submit": "Join", "join.submitting": "Joining..", - "join.trust": "No account needed. Your name and photo are deleted when the session ends", + "join.trust": "Your name and photo are deleted when the session ends", "join.hostLink": "Hosting? Start a session on the big screen", + "join.hostLinkShort": "Hosting instead?", + "join.hostSession": "Host a session", + "join.tag": "Party games for work", + "join.tagline": "One big screen. Everyone's phone", + "join.step1": "The host opens GameMash on the TV or shares their screen", + "join.step2": "Everyone joins with the room code", + "join.step3": "Play a few rounds. Nothing is saved afterwards", "host.title": "Host a session", "host.body": "Open this on the screen everyone can see, like the meeting-room TV or your shared screen. Players join from their phones", "host.create": "Create session", "host.creating": "Creating..", + "host.trust": "No accounts. Nothing is saved after the game", + "host.tag": "For the host", + "host.nameLabel": "Session name (optional)", + "host.namePlaceholder": "e.g. Friday team mash", + "host.step1": "Open this on the TV or share your screen", + "host.step2": "Players join with the code on their phones", + "host.step3": "Pick your games and press Start", + "host.laptopHint": "Works best on a laptop you can connect to the TV", + "host.joinInstead": "Join instead", + "host.joinLink": "Joining? Enter a code", + "host.joinGame": "Join a game", "setup.sessionLabel": "Session", "setup.sessionPlaceholder": "Name this session", "setup.openLobby": "Open lobby", @@ -45,7 +64,7 @@ "setup.removeGameTitle": "Remove this game from the lineup?", "setup.cannotUndo": "This can't be undone", "setup.keep": "Keep it", - "setup.saving": "Saving..", + "setup.saving": "Saving...", "setup.saved": "Auto-saved", "setup.saveFailed": "Not saved, retry", "setup.needGame": "Add at least one game before opening the lobby", diff --git a/packages/ui/src/entry/Entry.stories.tsx b/packages/ui/src/entry/Entry.stories.tsx new file mode 100644 index 0000000..21e8b74 --- /dev/null +++ b/packages/ui/src/entry/Entry.stories.tsx @@ -0,0 +1,153 @@ +import { useState } from "react"; +import { useCopy } from "../../.ladle/pseudo"; +import { BothThemes, Frame, WITH_WORKSHOP } from "../../.ladle/story-kit"; +import type { Story, StoryDefault } from "../../.ladle/types"; +import { Logo } from "../icons/Logo"; +import { buttonVariants } from "../primitives/Button"; +import { RoomCodeInput } from "../primitives/RoomCodeInput"; +import { TextField } from "../primitives/TextField"; +import { EntryHero } from "./EntryHero"; +import { EntryShell } from "./EntryShell"; +import { HowItWorksSteps } from "./HowItWorksSteps"; +import { TvMock } from "./TvMock"; + +export default { title: "Entry" } satisfies StoryDefault; + +const JOIN_STEPS = [ + "The host opens GameMash on the TV or shares their screen", + "Everyone joins with the room code", + "Play a few rounds. Nothing is saved afterwards", +]; + +const HOST_STEPS = [ + "Open this on the TV or share your screen", + "Players join with the code on their phones", + "Pick your games and press Start", +]; + +export const Hero: Story = () => ( + + {() => ( + <> + + + + + + +
+ +
+ + )} +
+); + +export const Steps: Story = () => { + const t = useCopy(); + return ( + + {() => ( + <> + + + +
+ +
+
+ +
+ + )} +
+ ); +}; + +export const Tv: Story = () => { + const t = useCopy(); + return ( + + {() => ( + <> + + + + + + + + )} + + ); +}; + +const PhoneCodeCard = () => { + const t = useCopy(); + const [code, setCode] = useState("KW"); + return ( +
+ t(`Letter ${position} of ${length}`)} + /> + +
+ ); +}; + +export const InContext: Story = () => { + const t = useCopy(); + return ( +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ + +
+
+ +
+
+
+ ); +}; + +export const Shell: Story = () => { + const t = useCopy(); + return ( + } + action={ + + {t("Host a session")} + + } + mainClassName="flex-col items-center justify-center" + > +
+ {t("Page content")} +
+
+ ); +}; diff --git a/packages/ui/src/entry/EntryHero.tsx b/packages/ui/src/entry/EntryHero.tsx new file mode 100644 index 0000000..9e4ab5c --- /dev/null +++ b/packages/ui/src/entry/EntryHero.tsx @@ -0,0 +1,66 @@ +import type { ComponentProps, CSSProperties } from "react"; +import { ANSWERS, type AnswerShapeName } from "../lib/answers.js"; +import { cn } from "../lib/cn.js"; + +const FILLS: Record = { + squircle: "text-answer-squircle", + triangle: "text-answer-triangle", + plus: "text-answer-plus", + dome: "text-answer-dome", +}; + +type StickerSpec = { + shape: AnswerShapeName; + rotate: number; + style: CSSProperties; +}; + +const PHONE_STICKERS: StickerSpec[] = [ + { shape: "squircle", rotate: -10, style: { left: "1.7%", top: "11.9%", width: "26.3%" } }, + { shape: "triangle", rotate: 8, style: { left: "27.4%", top: "1.7%", width: "24%" } }, + { shape: "plus", rotate: -6, style: { left: "51.4%", top: "25.4%", width: "22.9%" } }, + { shape: "dome", rotate: 12, style: { left: "74.9%", top: "6.8%", width: "25.1%" } }, +]; + +const DESKTOP_STICKERS: StickerSpec[] = [ + { shape: "squircle", rotate: -12, style: { right: 150, bottom: 120, width: 190 } }, + { shape: "triangle", rotate: 10, style: { right: 10, bottom: 150, width: 170 } }, + { shape: "plus", rotate: 6, style: { right: 190, bottom: 0, width: 160 } }, + { shape: "dome", rotate: -8, style: { right: 30, bottom: 0, width: 180 } }, +]; + +const VARIANTS = { + phone: { stickers: PHONE_STICKERS, stroke: 1.1, offset: 1.3, box: "aspect-[350/118] w-full" }, + desktop: { stickers: DESKTOP_STICKERS, stroke: 0.8, offset: 1, box: "h-[330px] w-[380px]" }, +}; + +const StickerShape = ({ spec, stroke, offset }: { spec: StickerSpec; stroke: number; offset: number }) => { + const { path } = ANSWERS[spec.shape]; + return ( + + ); +}; + +export type EntryHeroProps = Omit, "children"> & { + variant: "phone" | "desktop"; +}; + +export const EntryHero = ({ variant, className, ...props }: EntryHeroProps) => { + const { stickers, stroke, offset, box } = VARIANTS[variant]; + return ( + + ); +}; diff --git a/packages/ui/src/entry/EntryShell.tsx b/packages/ui/src/entry/EntryShell.tsx new file mode 100644 index 0000000..40bcd9b --- /dev/null +++ b/packages/ui/src/entry/EntryShell.tsx @@ -0,0 +1,22 @@ +import type { ComponentProps, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; + +export type EntryShellProps = ComponentProps<"div"> & { + logo: ReactNode; + action: ReactNode; + mainClassName?: string | undefined; +}; + +export const EntryShell = ({ logo, action, mainClassName, className, children, ...props }: EntryShellProps) => ( +
+
+ {logo} + {action} +
+
{children}
+
+); diff --git a/packages/ui/src/entry/HowItWorksSteps.tsx b/packages/ui/src/entry/HowItWorksSteps.tsx new file mode 100644 index 0000000..2eb7226 --- /dev/null +++ b/packages/ui/src/entry/HowItWorksSteps.tsx @@ -0,0 +1,59 @@ +import { cva } from "class-variance-authority"; +import type { ComponentProps, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; + +type StepsVariant = "phone" | "violet" | "cards"; + +const listVariants = cva("m-0 list-none p-0", { + variants: { + variant: { + phone: "flex flex-col gap-2", + violet: "flex max-w-[380px] flex-col gap-3", + cards: "grid w-full grid-cols-[repeat(auto-fit,minmax(9rem,1fr))] gap-4", + }, + }, +}); + +const itemVariants = cva("flex min-w-0", { + variants: { + variant: { + phone: "items-center gap-3 text-base/[1.3]", + violet: "items-center gap-3.5 text-xl/[1.3]", + cards: + "flex-col gap-2.5 rounded-field border-3 border-ink-950 bg-paper-white px-[18px] py-4 text-body/[1.35] font-bold text-ink-950 shadow-brutal", + }, + }, +}); + +const keyVariants = cva( + "flex shrink-0 items-center justify-center rounded-key border-2 border-ink-950 font-display font-extrabold text-ink-950", + { + variants: { + variant: { + phone: "size-[38px] bg-paper-white text-lg shadow-brutal-sm", + violet: "size-[42px] bg-cream text-xl", + cards: "size-10 bg-sun text-key", + }, + }, + }, +); + +const numberedSteps = (steps: ReactNode[]) => steps.map((content, position) => ({ content, number: position + 1 })); + +export type HowItWorksStepsProps = Omit, "children"> & { + steps: ReactNode[]; + variant: StepsVariant; +}; + +export const HowItWorksSteps = ({ steps, variant, className, ...props }: HowItWorksStepsProps) => ( +
    + {numberedSteps(steps).map((step) => ( +
  1. + + {step.content} +
  2. + ))} +
+); diff --git a/packages/ui/src/entry/TvMock.tsx b/packages/ui/src/entry/TvMock.tsx new file mode 100644 index 0000000..797f64c --- /dev/null +++ b/packages/ui/src/entry/TvMock.tsx @@ -0,0 +1,64 @@ +import type { ComponentProps } from "react"; +import { ANSWER_SHAPES, type AnswerShapeName } from "../lib/answers.js"; +import { cn } from "../lib/cn.js"; + +const DROPS = ["shadow-drop-coral", "shadow-drop-violet", "shadow-drop-lime", "shadow-drop-sky"]; + +const BARS: Record = { + squircle: "bg-answer-squircle", + triangle: "bg-answer-triangle", + plus: "bg-answer-plus ring-[1.5px] ring-ink-950 ring-inset", + dome: "bg-answer-dome", +}; + +const PhoneMock = ({ className }: { className: string }) => ( + + {ANSWER_SHAPES.map((shape) => ( + + ))} + +); + +export type TvMockProps = Omit, "children"> & { + title: string; + code: string; +}; + +export const TvMock = ({ title, code, className, ...props }: TvMockProps) => ( + +); diff --git a/packages/ui/src/icons/Icons.stories.tsx b/packages/ui/src/icons/Icons.stories.tsx index 5e4efb7..85922c5 100644 --- a/packages/ui/src/icons/Icons.stories.tsx +++ b/packages/ui/src/icons/Icons.stories.tsx @@ -14,6 +14,7 @@ export const Logos: Story = () => ( + )} diff --git a/packages/ui/src/icons/Logo.tsx b/packages/ui/src/icons/Logo.tsx index 8d0324c..ad19405 100644 --- a/packages/ui/src/icons/Logo.tsx +++ b/packages/ui/src/icons/Logo.tsx @@ -21,10 +21,18 @@ const SIZES: Record & { size?: LogoSize | undefined; showWordmark?: boolean | undefined; + hasOutline?: boolean | undefined; label?: string | undefined; }; -export const Logo = ({ size = "sm", showWordmark = true, label, className, ...props }: LogoProps) => { +export const Logo = ({ + size = "sm", + showWordmark = true, + hasOutline = true, + label, + className, + ...props +}: LogoProps) => { const sizing = SIZES[size]; const imageProps = !showWordmark && label ? { role: "img", "aria-label": label } : {}; return ( @@ -35,7 +43,10 @@ export const Logo = ({ size = "sm", showWordmark = true, label, className, ...pr key={shape} shape={shape} size={sizing.shape} - className={cn(FILLS[shape], "workshop:stroke-ink-950 workshop:stroke-2 workshop:[stroke-linejoin:round]")} + className={cn( + FILLS[shape], + hasOutline && "workshop:stroke-ink-950 workshop:stroke-2 workshop:[stroke-linejoin:round]", + )} /> ))} diff --git a/packages/ui/src/icons/icons.tsx b/packages/ui/src/icons/icons.tsx index 6ebf82b..4a7873c 100644 --- a/packages/ui/src/icons/icons.tsx +++ b/packages/ui/src/icons/icons.tsx @@ -37,6 +37,13 @@ export const MonitorIcon = (props: IconProps) => ( ); +export const PhoneIcon = (props: IconProps) => ( + + + + +); + export const PlayIcon = (props: IconProps) => ( diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 91bc84a..a06e283 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -5,6 +5,10 @@ export * from "./draw/DrawingToolbar.js"; export * from "./draw/RatingScale.js"; export * from "./draw/RatingScalePreview.js"; export * from "./draw/useDrawing.js"; +export * from "./entry/EntryHero.js"; +export * from "./entry/EntryShell.js"; +export * from "./entry/HowItWorksSteps.js"; +export * from "./entry/TvMock.js"; export * from "./game/AvatarPartPicker.js"; export * from "./game/CountStat.js"; export * from "./game/DecorativeShapes.js"; diff --git a/packages/ui/src/layout/Layouts.stories.tsx b/packages/ui/src/layout/Layouts.stories.tsx index 69ad48b..aae9d24 100644 --- a/packages/ui/src/layout/Layouts.stories.tsx +++ b/packages/ui/src/layout/Layouts.stories.tsx @@ -48,7 +48,7 @@ export const PhonePaper: Story = () => { } - footer={{t("No account needed. Your name and photo are deleted when the session ends.")}} + footer={{t("Your name and photo are deleted when the session ends.")}} bottomAction={} >

@@ -59,6 +59,7 @@ export const PhonePaper: Story = () => { description={t("It's shown on the big screen")} value={code} onValueChange={setCode} + letterLabel={(position, length) => t(`Letter ${position} of ${length}`)} /> diff --git a/packages/ui/src/layout/PhoneShell.tsx b/packages/ui/src/layout/PhoneShell.tsx index aadccb7..cf54e76 100644 --- a/packages/ui/src/layout/PhoneShell.tsx +++ b/packages/ui/src/layout/PhoneShell.tsx @@ -2,7 +2,7 @@ import type { ComponentProps, ReactNode } from "react"; import { cn } from "../lib/cn.js"; export type PhoneShellProps = ComponentProps<"div"> & { - theme: "stage" | "paper"; + theme: "stage" | "paper" | "workshop"; header?: ReactNode; footer?: ReactNode; bottomAction?: ReactNode; @@ -23,7 +23,11 @@ export const PhoneShell = ({ mainClassName, ...props }: PhoneShellProps) => ( -
+
{bottomAction} diff --git a/packages/ui/src/lib/cn.ts b/packages/ui/src/lib/cn.ts index 4165c3f..25f46fe 100644 --- a/packages/ui/src/lib/cn.ts +++ b/packages/ui/src/lib/cn.ts @@ -28,7 +28,7 @@ const twMerge = extendTailwindMerge({ "stage-display", "stage-word", ], - radius: ["control", "field", "button", "card", "tile", "panel", "sticker", "key"], + radius: ["control", "field", "button", "card", "tile", "panel", "sticker", "key", "bar"], shadow: [ "press-sun", "press-sm", @@ -41,6 +41,10 @@ const twMerge = extendTailwindMerge({ "tile-lime", "tile-sky", "card-word", + "drop-coral", + "drop-violet", + "drop-lime", + "drop-sky", "brutal-xs", "brutal-sm", "brutal", diff --git a/packages/ui/src/primitives/FieldFrame.tsx b/packages/ui/src/primitives/FieldFrame.tsx index 85acd03..6e1b0e0 100644 --- a/packages/ui/src/primitives/FieldFrame.tsx +++ b/packages/ui/src/primitives/FieldFrame.tsx @@ -24,7 +24,14 @@ export const FieldFrame = ({ children, }: FieldFrameProps) => ( - {label} + + {label} + {children} {description && {description}} {hasError(error) && ( diff --git a/packages/ui/src/primitives/Heading.stories.tsx b/packages/ui/src/primitives/Heading.stories.tsx index 34de685..bf4300f 100644 --- a/packages/ui/src/primitives/Heading.stories.tsx +++ b/packages/ui/src/primitives/Heading.stories.tsx @@ -11,6 +11,7 @@ export const Sizes: Story = () => { {() => ( <> + {t("Host a session")} {t("Edit questions")} {t("Join the game")} diff --git a/packages/ui/src/primitives/Heading.tsx b/packages/ui/src/primitives/Heading.tsx index c69bc15..e2fb78f 100644 --- a/packages/ui/src/primitives/Heading.tsx +++ b/packages/ui/src/primitives/Heading.tsx @@ -13,6 +13,7 @@ const headingVariants = cva("font-display font-extrabold text-balance", { "phone-sm": "text-3xl/[1.1]", host: "text-3xl/[1.1] tracking-[-0.01em] workshop:text-stage-xl/[1] workshop:tracking-display-tight", panel: "text-2xl/[1.2]", + display: "text-stage-2xl/none tracking-display-tight", }, }, defaultVariants: { diff --git a/packages/ui/src/primitives/RoomCodeInput.stories.tsx b/packages/ui/src/primitives/RoomCodeInput.stories.tsx index 368f427..69c0f98 100644 --- a/packages/ui/src/primitives/RoomCodeInput.stories.tsx +++ b/packages/ui/src/primitives/RoomCodeInput.stories.tsx @@ -1,35 +1,60 @@ import { useState } from "react"; import { useCopy } from "../../.ladle/pseudo"; -import { BothThemes, Frame } from "../../.ladle/story-kit"; +import { BothThemes, Frame, WITH_WORKSHOP } from "../../.ladle/story-kit"; import type { Story, StoryDefault } from "../../.ladle/types"; import { RoomCodeInput } from "./RoomCodeInput"; export default { title: "Primitives / RoomCodeInput" } satisfies StoryDefault; -const Example = ({ initial, error }: { initial: string; error?: string }) => { +type ExampleProps = { + initial: string; + error?: string; + size?: "phone" | "desktop"; + width?: number; +}; + +const Example = ({ initial, error, size = "phone", width = 350 }: ExampleProps) => { const t = useCopy(); const [code, setCode] = useState(initial); return ( - + t(`Letter ${position} of ${length}`)} error={error ? t(error) : undefined} + size={size} /> ); }; export const Default: Story = () => ( - + {() => ( <> + )} ); + +export const Desktop: Story = () => ( + + {() => ( + <> + + + + )} + +); + +export const NarrowPhone: Story = () => ( + {() => } +); diff --git a/packages/ui/src/primitives/RoomCodeInput.tsx b/packages/ui/src/primitives/RoomCodeInput.tsx index ffd102e..73c6394 100644 --- a/packages/ui/src/primitives/RoomCodeInput.tsx +++ b/packages/ui/src/primitives/RoomCodeInput.tsx @@ -1,49 +1,220 @@ -import { Field } from "@base-ui/react/field"; -import type { ComponentProps } from "react"; -import { FieldFrame, type FieldFrameProps } from "./FieldFrame.js"; +import { cva } from "class-variance-authority"; +import { + type ChangeEvent, + type ClipboardEvent, + type KeyboardEvent, + type PointerEvent, + type ReactNode, + useId, + useRef, + useState, +} from "react"; +import { cn } from "../lib/cn.js"; const DEFAULT_LENGTH = 4; -const normalizeRoomCode = (raw: string, length: number) => - raw - .toUpperCase() - .replace(/[^A-Z]/g, "") - .slice(0, length); - -export type RoomCodeInputProps = Omit< - ComponentProps, - "className" | "value" | "defaultValue" | "onValueChange" | "onChange" | "size" | "maxLength" -> & - Omit & { - value: string; - onValueChange: (value: string) => void; - length?: number | undefined; - }; +const lettersOnly = (raw: string) => raw.toUpperCase().replace(/[^A-Z]/g, ""); + +const hasError = (error: ReactNode) => error !== undefined && error !== null && error !== false && error !== ""; + +const boxVariants = cva( + [ + "focus-ring w-full min-w-0 border-3 border-ink-950 text-center font-display font-extrabold text-ink-950 caret-transparent selection:bg-transparent", + "transition-[background-color,box-shadow] duration-100 ease-out disabled:cursor-not-allowed disabled:opacity-50", + ], + { + variants: { + size: { + phone: "h-[70px] rounded-control text-stage-lg", + desktop: "h-[84px] rounded-field text-stage-xl", + }, + state: { + filled: "bg-paper-white", + current: "bg-sun", + empty: "border-dashed border-ink-400 bg-cream", + }, + invalid: { + true: "border-danger", + false: "", + }, + }, + compoundVariants: [ + { size: "phone", state: "filled", className: "shadow-brutal-sm" }, + { size: "desktop", state: "filled", className: "shadow-brutal" }, + ], + }, +); + +type BoxState = "filled" | "current" | "empty"; + +const boxState = (position: number, code: string, focused: number | null): BoxState => { + if (position === focused) return "current"; + return position < code.length ? "filled" : "empty"; +}; + +const typedLetters = (raw: string, previous: string) => { + const letters = lettersOnly(raw); + if (!previous || letters.length !== 2) return letters; + return letters.startsWith(previous) ? letters.slice(1) : letters.slice(0, 1); +}; + +export type RoomCodeInputProps = { + label: ReactNode; + description?: ReactNode; + error?: ReactNode; + disabled?: boolean | undefined; + className?: string | undefined; + value: string; + onValueChange: (value: string) => void; + letterLabel: (position: number, length: number) => string; + length?: number | undefined; + size?: "phone" | "desktop" | undefined; +}; export const RoomCodeInput = ({ label, description, error, - disabled, + disabled = false, className, value, onValueChange, + letterLabel, length = DEFAULT_LENGTH, - ...props -}: RoomCodeInputProps) => ( - - onValueChange(normalizeRoomCode(next, length))} - pattern={`[A-Za-z]{${length}}`} - inputMode="text" - autoComplete="off" - autoCorrect="off" - autoCapitalize="characters" - spellCheck={false} - enterKeyHint="go" - className="focus-ring h-[76px] w-full min-w-0 rounded-button border-2 border-fg bg-field pl-[0.35em] text-center font-display text-stage-xl font-extrabold uppercase tracking-[0.35em] text-fg data-[invalid]:border-danger data-[disabled]:opacity-50" - {...props} - /> - -); + size = "phone", +}: RoomCodeInputProps) => { + const id = useId(); + const inputs = useRef<(HTMLInputElement | null)[]>([]); + const [focused, setFocused] = useState(null); + const code = lettersOnly(value).slice(0, length); + const positions = Array.from({ length }, (_, position) => position); + const nextPosition = Math.min(code.length, length - 1); + const isInvalid = hasError(error); + const labelId = `${id}-label`; + const descriptionId = `${id}-description`; + const errorId = `${id}-error`; + const describedBy = [description ? descriptionId : null, isInvalid ? errorId : null].filter(Boolean).join(" "); + + const focusBox = (position: number) => { + const target = inputs.current[Math.max(0, Math.min(position, length - 1))]; + target?.focus(); + target?.select(); + }; + + const fillFrom = (position: number, letters: string) => { + if (!letters) return; + if (letters.length >= length) { + onValueChange(letters.slice(0, length)); + focusBox(length - 1); + return; + } + const start = Math.min(position, code.length); + onValueChange((code.slice(0, start) + letters + code.slice(start + letters.length)).slice(0, length)); + focusBox(start + letters.length); + }; + + const handleChange = (position: number) => (event: ChangeEvent) => { + fillFrom(position, typedLetters(event.currentTarget.value, code[position] ?? "")); + }; + + const handlePaste = (position: number) => (event: ClipboardEvent) => { + event.preventDefault(); + fillFrom(position, lettersOnly(event.clipboardData.getData("text"))); + }; + + const handleKeyDown = (position: number) => (event: KeyboardEvent) => { + if (event.key === "Delete") { + event.preventDefault(); + onValueChange(code.slice(0, position) + code.slice(position + 1)); + return; + } + if (event.key === "Backspace") { + event.preventDefault(); + if (position < code.length) { + onValueChange(code.slice(0, position) + code.slice(position + 1)); + return; + } + if (position > 0) { + onValueChange(code.slice(0, position - 1)); + focusBox(position - 1); + } + return; + } + if (event.key === "ArrowLeft") { + event.preventDefault(); + focusBox(position - 1); + return; + } + if (event.key === "ArrowRight") { + event.preventDefault(); + focusBox(Math.min(position + 1, code.length)); + } + }; + + const handleFocus = (position: number) => { + setFocused(position); + inputs.current[position]?.select(); + }; + + const handlePointerDown = (position: number) => (event: PointerEvent) => { + if (position <= code.length) return; + event.preventDefault(); + focusBox(code.length); + }; + + return ( +
+ +
+ {positions.map((position) => ( + { + inputs.current[position] = element; + }} + value={code[position] ?? ""} + onChange={handleChange(position)} + onPaste={handlePaste(position)} + onKeyDown={handleKeyDown(position)} + onPointerDown={handlePointerDown(position)} + onFocus={() => handleFocus(position)} + onBlur={() => setFocused((current) => (current === position ? null : current))} + tabIndex={position === nextPosition ? 0 : -1} + aria-label={letterLabel(position + 1, length)} + aria-invalid={isInvalid || undefined} + disabled={disabled} + autoComplete="off" + autoCorrect="off" + autoCapitalize="characters" + spellCheck={false} + inputMode="text" + enterKeyHint={position === length - 1 ? "go" : "next"} + className={cn(boxVariants({ size, state: boxState(position, code, focused), invalid: isInvalid }))} + /> + ))} +
+ {description && ( + + {description} + + )} + {isInvalid && ( + + {error} + + )} +
+ ); +}; diff --git a/packages/ui/src/primitives/TrustNote.stories.tsx b/packages/ui/src/primitives/TrustNote.stories.tsx index 35167a5..62f462d 100644 --- a/packages/ui/src/primitives/TrustNote.stories.tsx +++ b/packages/ui/src/primitives/TrustNote.stories.tsx @@ -12,13 +12,19 @@ export const Variants: Story = () => { {() => ( <> - {t("No account needed. Your name and photo are deleted when the session ends.")} + {t("Your name and photo are deleted when the session ends.")} {t("You gave it an 8. You can change it until time runs out. Nobody sees who voted what.")} + + + {t("No accounts. Nothing is saved after the game.")} + + + {t("No accounts. Nothing is saved after the game.")} {t("Nothing is saved after the game")} diff --git a/packages/ui/src/primitives/TrustNote.tsx b/packages/ui/src/primitives/TrustNote.tsx index 817e5b1..585f049 100644 --- a/packages/ui/src/primitives/TrustNote.tsx +++ b/packages/ui/src/primitives/TrustNote.tsx @@ -3,34 +3,46 @@ import type { ComponentProps } from "react"; import { EyeOffIcon, ShieldCheckIcon } from "../icons/icons.js"; import { cn } from "../lib/cn.js"; -const trustNoteVariants = cva( - "flex bg-surface text-fg-muted workshop:brutal workshop:rounded-field workshop:bg-brand-lime workshop:font-bold workshop:text-ink-950 workshop:shadow-brutal", - { - variants: { - size: { - phone: - "items-start gap-3 rounded-field px-4 py-3.5 text-caption workshop:gap-2.5 workshop:px-3.5 workshop:py-3 workshop:text-sm/[1.45]", - stage: "items-center gap-3 rounded-full border-2 border-border px-6 py-3.5 text-stage-caption", - }, +const trustNoteVariants = cva("flex", { + variants: { + size: { + phone: + "items-start gap-3 rounded-field bg-surface px-4 py-3.5 text-caption text-fg-muted workshop:brutal workshop:gap-2.5 workshop:bg-brand-lime workshop:px-3.5 workshop:py-3 workshop:text-sm/[1.45] workshop:font-bold workshop:text-ink-950 workshop:shadow-brutal", + stage: + "items-center gap-3 rounded-full border-2 border-border bg-surface px-6 py-3.5 text-stage-caption text-fg-muted", + note: "items-center gap-2.5 rounded-control border-2 border-ink-950 px-3.5 py-2.5 text-sm/[1.35] font-bold text-ink-950", + inline: "items-center gap-2 text-caption font-bold text-fg", }, - defaultVariants: { - size: "phone", + tone: { + lime: "", + white: "", }, }, -); + compoundVariants: [ + { size: "note", tone: "lime", className: "bg-brand-lime" }, + { size: "note", tone: "white", className: "bg-paper-white" }, + ], + defaultVariants: { + size: "phone", + tone: "lime", + }, +}); -const ICON_SIZES = { phone: 24, stage: 28 }; +const ICON_SIZES = { phone: 24, stage: 28, note: 22, inline: 20 }; export type TrustNoteProps = ComponentProps<"div"> & VariantProps & { icon?: "shield" | "eye-off" | undefined; }; -export const TrustNote = ({ icon = "shield", size, className, children, ...props }: TrustNoteProps) => { +export const TrustNote = ({ icon = "shield", size, tone, className, children, ...props }: TrustNoteProps) => { const IconComponent = icon === "shield" ? ShieldCheckIcon : EyeOffIcon; return ( -
- +
+ {children}
); diff --git a/packages/ui/src/screens/Phone.stories.tsx b/packages/ui/src/screens/Phone.stories.tsx index 05e48d3..9b56284 100644 --- a/packages/ui/src/screens/Phone.stories.tsx +++ b/packages/ui/src/screens/Phone.stories.tsx @@ -30,13 +30,7 @@ export const Join: Story = () => { theme="paper" mainClassName="gap-7" header={} - footer={ - - {t( - "No account needed. Your name and photo are deleted when the session ends.", - )} - - } + footer={{t("Your name and photo are deleted when the session ends.")}} bottomAction={