From fccc6733d73934d8fb7d20b045724c199f5717c2 Mon Sep 17 00:00:00 2001 From: koH Date: Tue, 8 Sep 2026 15:51:10 -0500 Subject: [PATCH 01/24] feat(yuhm): shorten onboarding to sign in or browse, then do the task Landing hero carries two doors above the fold: Find food near me (guest, real listings) and Sign in. The login screen is one step, email + password + Continue, which signs a member in or creates the account, so nobody picks log-in versus sign-up first. Signed-in members skip the interstitial sheet entirely; guests sign in inline in the sheet and land on the exact destination (return= now carries a full /app/ path). The world intro collapses from four screens to one. Phone-test fixes: the sign-in form is uncontrolled so password-manager autofill enables Continue, and every text field stays 16px on touch screens so iOS does not zoom on focus and carry the zoom into the next screen. Tests 108 -> 126. New src/AuthFunnel.test.tsx covers the funnel against a mocked Supabase client. Email+password stays the mechanism; passwordless was removed earlier as a product decision. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01LcoUkLVX2KaZWRmz4GJfJW (cherry picked from commit 6e1b31b8ab921867644b015c5a5818a2005ac7dc) --- yuhm/HANDOFF.md | 21 +++++ yuhm/src/App.test.tsx | 36 +++++++- yuhm/src/AuthForm.tsx | 62 ++++++++++++++ yuhm/src/AuthFunnel.test.tsx | 149 +++++++++++++++++++++++++++++++++ yuhm/src/LandingPage.tsx | 3 +- yuhm/src/LoginScreen.tsx | 85 +++++++++---------- yuhm/src/SimpleExperience.tsx | 14 +++- yuhm/src/i18n.tsx | 32 +++---- yuhm/src/lib/auth.test.ts | 81 +++++++++++++++++- yuhm/src/lib/auth.ts | 59 +++++++++++++ yuhm/src/styles.css | 34 ++++++-- yuhm/src/world/World.test.tsx | 21 ++--- yuhm/src/world/views.tsx | 56 +++---------- yuhm/src/world/world.css | 7 +- yuhm/src/world/worldStrings.ts | 18 +--- 15 files changed, 531 insertions(+), 147 deletions(-) create mode 100644 yuhm/src/AuthForm.tsx create mode 100644 yuhm/src/AuthFunnel.test.tsx diff --git a/yuhm/HANDOFF.md b/yuhm/HANDOFF.md index 250b97eb..cfdfe027 100644 --- a/yuhm/HANDOFF.md +++ b/yuhm/HANDOFF.md @@ -8,6 +8,27 @@ This is the working orientation document for `yuhm/`. Read it before changing th Public-facing product behavior and safety boundaries are maintained in `docs/LIVING-DOCS.md`. Keep it current when a feature promise or workflow changes. It is intended to become the source for a future HTML documentation page. +## Onboarding funnel pass, 2026-09-08 + +Goal: the shortest path from arriving to doing the task. Before, a guest who wanted to contribute went landing → scroll to "What brings you here today?" → pick a card → fill the form → Review → interstitial sheet → "Sign in to continue" → login page → choose log in vs sign up → submit → land on the intent tab → redo Review → sheet → "Open secure next step" → dashboard (seven screens). Bare `/app/` also ran a four-step world intro. + +What changed: + +- **Landing hero carries the decision.** Two doors above the fold: **Find food near me** (primary, guest, `/app/?mode=anonymous&intent=food`, real listings) and **Sign in** (`/app/?mode=login`). The "Enter the living map" hero CTA is gone; the world is still reachable from the banner in the paths section and from bare `/app/`. The three path cards remain as optional deep links (tests unchanged). +- **One sign-in step, no mode toggle.** `src/AuthForm.tsx` (`EmailContinueForm`) is email + password + **Continue**. `continueWithEmail` in `src/lib/auth.ts` signs in, and when no account matches it creates one with the same credentials (confirm-email is off, so the session is immediate). A wrong password on an existing account gets an "already has a yuhm account" message rather than a duplicate. `signup=1` still flips autocomplete to `new-password` and labels the button "Create account". Email+password stays the mechanism: passwordless was removed deliberately (see "Product decisions made"). +- **Return to the exact destination.** `return=` now carries a full in-app path (`resolveReturnPath` accepts `/app/...` only, maps legacy intent names, falls back to the finder). The login screen uses `navigate(..., { replace: true })` instead of a full reload. `mode=reset` opens the reset screen directly. +- **No interstitial for members; inline sign-in for guests.** In `SimpleExperience`, `openSimpleAction` navigates members straight to the destination. Guests see the sheet with the title/copy plus the Continue form inline; on success they land on the destination without leaving the page. `simple.sheet.signInToContinue` was retired. +- **World intro is one screen.** `WorldOnboarding` now shows role chips with the matched first invitation previewing inline, then Step in / Skip. The privacy (location) and reveal steps were removed with their strings; `onDone` still receives `(role, null)`. Location can return later as an on-map control. +- **Copy.** "Browse anonymously" → "Browse as a guest" / "Mirar como invitado"; new `login.title`, `login.continue`, `login.continueCopy`, `login.existingAccount`, `login.notConfigured`, `landing.hero.findFood`, `simple.sheet.authCopy` (EN + ES). + +**Same-day fixes from koH's phone test (Brave on iOS):** +- *Autofilled email + password but Continue stayed disabled.* Password managers write straight into the DOM without firing React change events, so a controlled form's state-based `disabled` never cleared (the pre-existing login had the same pattern). `EmailContinueForm` is now uncontrolled: values are read from `FormData` at submit (`readField` helper), the button is disabled only while busy, and the reset / updates forms read the submitted value the same way. Regression test: "accepts browser-autofilled credentials that never fired a change event". +- *"Browse as a guest" opened an oversized map.* iOS zooms the page when a focused field is under 16px, and because routing is client-side the zoom survives into the next screen. Almost every field was 11 to 14px. One rule at the end of `styles.css` (`@media (pointer: coarse), (max-width: 759px)`) holds all text fields, selects, and textareas at 16px on touch screens; desktop keeps the compact sizes. Verified with touch emulation that the map itself has no horizontal overflow at 390px. + +Tests: 126 (was 108). New `src/AuthFunnel.test.tsx` mocks the Supabase client to cover member-skips-sheet, inline sign-in, one-button account creation, existing-account error, and legacy return mapping. `src/lib/auth.test.ts` covers `continueWithEmail`, `resolveReturnPath`, `signInHref`. + +Not changed (candidates for a follow-up): the geolocation consent dialog at `intent=food` still opens as a modal before the map; `AuthPrompt` in the dashboard and the "Sign in" links in MapLab/world panels do not pass a `return`; the hero doors are not yet verified against the live Supabase project (log in / create account on yuhm.handprotocol.org after deploy). + ## Living-map world experience, 2026-08-24 (now the default app) An immersive "cooperative living world" surface that is now the **default app experience**: bare `/app/` and `/app/?mode=anonymous` always open it, on every viewport (`mode=world` is an equivalent alias). The saved `yuhm:experience-mode` preference no longer influences routing; the dashboard is reached only through explicit `mode=advanced` or `workspace=` URLs (one tap away via the world's Command center link), so the flag writes in SimpleExperience, MapLab, and DashboardApp are now vestigial and can be retired in a cleanup pass. The landing hero carries a primary "Enter the living map" CTA into `/app/`, and first entry runs the find-your-yuhm onboarding (stored once in `yuhm:world-intro`; replayable from the profile panel). It presents yuhm as a living neighborhood food ecosystem rather than pins on a map. The focused flows keep their URLs: `intent=food` still opens the zero-friction classic finder (command-bar map on phones), `intent=contribute/gather/request` are unchanged, auth modes are unchanged, and `mode=advanced`/`workspace=` (or the persisted `yuhm:experience-mode`) still open the dashboard. The world links back out through a "More ways to take part" block (Find food, Contribute, Gather, Requests, Sign in) and a "Classic food finder" note on the map. Note: successful login redirects to `/app/`, so signed-in members without the advanced preference now land in the world. diff --git a/yuhm/src/App.test.tsx b/yuhm/src/App.test.tsx index 18f6d3ae..b789f6c4 100644 --- a/yuhm/src/App.test.tsx +++ b/yuhm/src/App.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import App from './App' @@ -183,6 +183,32 @@ describe('yuhm entry points and interaction gates', () => { expect(screen.getByRole('link', { name: /Get yuhm updates/i })).toHaveAttribute('href', '/app/?mode=login&updates=1') }) + it('opens two doors above the fold: browse as a guest or sign in', () => { + render() + expect(screen.getByRole('link', { name: /Find food near me/i })).toHaveAttribute('href', '/app/?mode=anonymous&intent=food') + const signInLinks = screen.getAllByRole('link', { name: /^Sign in/i }) + expect(signInLinks.length).toBeGreaterThanOrEqual(2) + for (const link of signInLinks) expect(link).toHaveAttribute('href', '/app/?mode=login') + }) + + it('signs in or creates the account from one form with no mode toggle', () => { + window.history.replaceState({}, '', '/app/?mode=login') + render() + + expect(screen.getByRole('heading', { level: 1, name: 'Sign in or create your account.' })).toBeInTheDocument() + expect(screen.getByLabelText('Password')).toHaveAttribute('autocomplete', 'current-password') + expect(screen.getByRole('button', { name: /Continue/ })).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /New here\? Create an account/i })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: /Already have an account/i })).not.toBeInTheDocument() + expect(screen.getByRole('link', { name: /Browse as a guest/i })).toHaveAttribute('href', '/app/?mode=anonymous&intent=food') + }) + + it('opens the reset screen directly from mode=reset', () => { + window.history.replaceState({}, '', '/app/?mode=reset') + render() + expect(screen.getByRole('heading', { level: 1, name: 'Reset your password.' })).toBeInTheDocument() + }) + it('routes each landing choice to the relevant workspace', () => { window.history.replaceState({}, '', '/app/?mode=anonymous&intent=contribute') const { unmount } = render() @@ -239,8 +265,12 @@ describe('yuhm entry points and interaction gates', () => { expect(screen.getByText(/Food out, compost back/i)).toBeInTheDocument() expect(screen.getByText(/sealed compost pickup/i)).toBeInTheDocument() await userEvent.click(screen.getByRole('button', { name: /Set up Contributor profile/i })) - expect(screen.getByRole('dialog', { name: /Ready to deliver food and return compost/i })).toBeInTheDocument() - expect(screen.getByRole('link', { name: /Sign in to continue/i })).toHaveAttribute('href', '/app/?mode=login&return=contribute') + const sheet = screen.getByRole('dialog', { name: /Ready to deliver food and return compost/i }) + expect(within(sheet).getByLabelText('Email address')).toBeInTheDocument() + expect(within(sheet).getByLabelText('Password')).toHaveAttribute('autocomplete', 'current-password') + expect(within(sheet).getByRole('button', { name: /Continue/ })).toBeEnabled() + expect(within(sheet).getByRole('link', { name: /Forgot password/i })).toHaveAttribute('href', '/app/?mode=reset') + expect(screen.queryByRole('link', { name: /Sign in to continue/i })).not.toBeInTheDocument() }) it('keeps all four public intents one tap away', async () => { diff --git a/yuhm/src/AuthForm.tsx b/yuhm/src/AuthForm.tsx new file mode 100644 index 00000000..7f2b38cf --- /dev/null +++ b/yuhm/src/AuthForm.tsx @@ -0,0 +1,62 @@ +import { useState, type FormEvent, type ReactNode } from 'react' +import { ArrowUpRight } from 'lucide-react' +import { foodDb } from './lib/foodRepository' +import { continueWithEmail } from './lib/auth' +import { notifyYuhmAccountSignup } from './lib/feedback' +import { useI18n } from './i18n' + +type EmailContinueFormProps = { + /** `signup` asks the browser for a new password and labels the button "Create account"; the logic is the same either way. */ + hint?: 'continue' | 'signup' + onSuccess: (status: 'signed_in' | 'created') => void + /** Rendered inside the form after the submit button (forgot-password, updates links). */ + footer?: ReactNode + className?: string +} + +/** Reads a text field straight from the submitted form, so browser autofill counts even when no change event fired. */ +export function readField(form: HTMLFormElement, name: string) { + return String(new FormData(form).get(name) ?? '').trim() +} + +/** + * The one sign-in step used everywhere: email + password + Continue. It signs + * a member in, or creates the account when none matches, so nobody has to pick + * "log in" versus "sign up" before they can act. + * + * The fields are uncontrolled on purpose: password managers fill them without + * firing React change events, so the button must never depend on React state + * to become clickable. + */ +export function EmailContinueForm({ hint = 'continue', onSuccess, footer, className = '' }: EmailContinueFormProps) { + const { t } = useI18n() + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + + const submit = async (event: FormEvent) => { + event.preventDefault() + const form = event.currentTarget + const email = readField(form, 'email') + const password = String(new FormData(form).get('password') ?? '') + setError('') + if (!email || !password) { setError(t('login.missingFields')); return } + if (!foodDb) { setError(t('login.notConfigured')); return } + setBusy(true) + const result = await continueWithEmail(foodDb.auth, email, password) + setBusy(false) + if (result.status === 'error') { + setError(result.reason === 'existing_account' ? t('login.existingAccount') : result.message) + return + } + if (result.status === 'created') void notifyYuhmAccountSignup(email) + onSuccess(result.status) + } + + return
+ + + {error &&

{error}

} + + {footer} +
+} diff --git a/yuhm/src/AuthFunnel.test.tsx b/yuhm/src/AuthFunnel.test.tsx new file mode 100644 index 00000000..7f84101b --- /dev/null +++ b/yuhm/src/AuthFunnel.test.tsx @@ -0,0 +1,149 @@ +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const member = vi.hoisted(() => ({ id: 'member-1', email: 'neighbor@handprotocol.org', user_metadata: {} })) +const session = vi.hoisted(() => ({ access_token: 'token', user: { id: 'member-1', email: 'neighbor@handprotocol.org', user_metadata: {} } })) +const authState = vi.hoisted(() => ({ signedIn: false })) + +const mockDb = vi.hoisted(() => { + const channel = { on: vi.fn(() => channel), subscribe: vi.fn(() => channel) } + return { + channel: vi.fn(() => channel), + removeChannel: vi.fn(async () => 'ok'), + auth: { + getSession: vi.fn(async () => ({ data: { session: authState.signedIn ? session : null } })), + onAuthStateChange: vi.fn(() => ({ data: { subscription: { unsubscribe: vi.fn() } } })), + signInWithPassword: vi.fn(), + signUp: vi.fn(), + signOut: vi.fn(async () => ({ error: null })), + }, + } +}) + +vi.mock('./lib/foodRepository', async (importOriginal) => ({ + ...(await importOriginal()), + foodDbConfigured: true, + foodDb: mockDb, + loadFoodSpots: vi.fn(async () => ({ data: [], error: null })), + loadFoodAlerts: vi.fn(async () => ({ data: [], error: null })), + loadFoodRequests: vi.fn(async () => ({ data: [], error: null })), + loadFoodDropoffs: vi.fn(async () => ({ data: [], error: null })), +})) + +vi.mock('./FoodMap', () => ({ + FoodMap: ({ locations }: { locations: Array<{ id: string }> }) =>
, +})) + +import App from './App' + +const invalidCredentials = { code: 'invalid_credentials', message: 'Invalid login credentials' } + +describe('onboarding funnel: sign in once, land on the task', () => { + beforeEach(() => { + authState.signedIn = false + mockDb.auth.signInWithPassword.mockReset() + mockDb.auth.signUp.mockReset() + localStorage.clear() + sessionStorage.clear() + Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true }) + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('takes a signed-in member straight to the destination with no interstitial', async () => { + authState.signedIn = true + window.history.replaceState({}, '', '/app/?mode=anonymous&intent=contribute') + render() + await waitFor(() => expect(screen.getByRole('button', { name: 'Open account and display settings' })).toHaveTextContent('N')) + + await userEvent.click(screen.getByRole('tab', { name: /I can deliver/i })) + await userEvent.click(screen.getByRole('button', { name: /Set up Contributor profile/i })) + + expect(screen.queryByRole('dialog', { name: /Ready to deliver/i })).not.toBeInTheDocument() + expect(window.location.search).toContain('mode=advanced') + expect(window.location.search).toContain('workspace=volunteer') + }) + + it('lets a guest sign in inside the sheet and lands them on the destination', async () => { + mockDb.auth.signInWithPassword.mockResolvedValue({ data: { user: member, session }, error: null }) + window.history.replaceState({}, '', '/app/?mode=anonymous&intent=contribute') + render() + + await userEvent.click(screen.getByRole('tab', { name: /I can deliver/i })) + await userEvent.click(screen.getByRole('button', { name: /Set up Contributor profile/i })) + const sheet = await screen.findByRole('dialog', { name: /Ready to deliver food and return compost/i }) + await userEvent.type(within(sheet).getByLabelText('Email address'), 'neighbor@handprotocol.org') + await userEvent.type(within(sheet).getByLabelText('Password'), 'community-food') + await userEvent.click(within(sheet).getByRole('button', { name: /Continue/ })) + + expect(mockDb.auth.signInWithPassword).toHaveBeenCalledWith({ email: 'neighbor@handprotocol.org', password: 'community-food' }) + await waitFor(() => expect(window.location.search).toContain('workspace=volunteer')) + expect(screen.queryByRole('dialog', { name: /Ready to deliver/i })).not.toBeInTheDocument() + expect(mockDb.auth.signUp).not.toHaveBeenCalled() + }) + + it('creates the account from the same Continue button when the email is new', async () => { + mockDb.auth.signInWithPassword.mockResolvedValue({ data: { user: null, session: null }, error: invalidCredentials }) + mockDb.auth.signUp.mockResolvedValue({ data: { user: member, session }, error: null }) + window.history.replaceState({}, '', '/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dadvanced%26workspace%3Drescue%26action%3Dsubmit') + render() + + await userEvent.type(screen.getByLabelText('Email address'), 'new-neighbor@handprotocol.org') + await userEvent.type(screen.getByLabelText('Password'), 'community-food') + await userEvent.click(screen.getByRole('button', { name: /Continue/ })) + + expect(mockDb.auth.signUp).toHaveBeenCalledWith({ email: 'new-neighbor@handprotocol.org', password: 'community-food' }) + await waitFor(() => expect(window.location.search).toContain('workspace=rescue')) + expect(window.location.search).toContain('action=submit') + }) + + it('explains a wrong password on an existing account instead of creating a duplicate', async () => { + mockDb.auth.signInWithPassword.mockResolvedValue({ data: { user: null, session: null }, error: invalidCredentials }) + mockDb.auth.signUp.mockResolvedValue({ data: { user: null, session: null }, error: { code: 'user_already_exists', message: 'User already registered' } }) + window.history.replaceState({}, '', '/app/?mode=login') + render() + + await userEvent.type(screen.getByLabelText('Email address'), 'neighbor@handprotocol.org') + await userEvent.type(screen.getByLabelText('Password'), 'wrong-password') + await userEvent.click(screen.getByRole('button', { name: /Continue/ })) + + expect(await screen.findByRole('alert')).toHaveTextContent(/already has a yuhm account/i) + expect(window.location.search).toContain('mode=login') + expect(screen.getByRole('button', { name: /Forgot password/i })).toBeInTheDocument() + }) + + it('accepts browser-autofilled credentials that never fired a change event', async () => { + mockDb.auth.signInWithPassword.mockResolvedValue({ data: { user: member, session }, error: null }) + window.history.replaceState({}, '', '/app/?mode=login') + render() + + // Password managers write straight to the DOM; React sees no input event. + const emailField = screen.getByLabelText('Email address') as HTMLInputElement + const passwordField = screen.getByLabelText('Password') as HTMLInputElement + emailField.value = 'neighbor@handprotocol.org' + passwordField.value = 'community-food' + + const button = screen.getByRole('button', { name: /Continue/ }) + expect(button).toBeEnabled() + await userEvent.click(button) + + expect(mockDb.auth.signInWithPassword).toHaveBeenCalledWith({ email: 'neighbor@handprotocol.org', password: 'community-food' }) + await waitFor(() => expect(window.location.search).toBe('?intent=food')) + }) + + it('maps a legacy intent return onto the focused flow', async () => { + mockDb.auth.signInWithPassword.mockResolvedValue({ data: { user: member, session }, error: null }) + window.history.replaceState({}, '', '/app/?mode=login&return=contribute') + render() + + await userEvent.type(screen.getByLabelText('Email address'), 'neighbor@handprotocol.org') + await userEvent.type(screen.getByLabelText('Password'), 'community-food') + await userEvent.click(screen.getByRole('button', { name: /Continue/ })) + + await waitFor(() => expect(window.location.search).toBe('?intent=contribute')) + }) +}) diff --git a/yuhm/src/LandingPage.tsx b/yuhm/src/LandingPage.tsx index 3e613575..b1ad11dd 100644 --- a/yuhm/src/LandingPage.tsx +++ b/yuhm/src/LandingPage.tsx @@ -202,7 +202,8 @@ export function LandingPage() { animate={{ opacity: 1, y: 0 }} transition={{ ...springy, delay: 0.92 }} > - {t('landing.world.action')} + {t('landing.hero.findFood')} + {t('common.signIn')} ('login') + const [screen, setScreen] = useState('continue') const [notice, setNotice] = useState('') const [error, setError] = useState('') const [busy, setBusy] = useState(false) + const signupHint = params.get('signup') === '1' useEffect(() => { - const params = new URLSearchParams(window.location.search) const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, '')) - if (params.get('mode') === 'recovery' || hashParams.get('type') === 'recovery') setAuthMode('recovery') - else if (params.get('updates') === '1') setAuthMode('updates') - else if (params.get('signup') === '1') setAuthMode('signup') - }, []) + if (params.get('mode') === 'recovery' || hashParams.get('type') === 'recovery') setScreen('recovery') + else if (params.get('mode') === 'reset') setScreen('reset') + else if (params.get('updates') === '1') setScreen('updates') + }, [params]) - const submitAuth = async (event: React.FormEvent) => { - event.preventDefault() - setError('') - setNotice('') - if (!foodDb) { setError('Login is not configured on this deployment yet. You can still browse anonymously.'); return } - setBusy(true) - const result = authMode === 'signup' - ? await createAccountAndSession(foodDb.auth, email.trim(), password) - : await foodDb.auth.signInWithPassword({ email: email.trim(), password }) - setBusy(false) - if (result.error) setError(getAuthErrorMessage(result.error, authMode === 'signup' ? 'signup' : 'login')) - else if (!result.data.session) setError('Your account was created, but yuhm could not log you in. Please try logging in.') - else { - if (authMode === 'signup') void notifyYuhmAccountSignup(email) - const returnIntent = new URLSearchParams(window.location.search).get('return') - const destination = returnIntent === 'food' || returnIntent === 'contribute' || returnIntent === 'gather' || returnIntent === 'request' - ? `/app/?intent=${returnIntent}` - : '/app/?intent=food' - window.location.assign(destination) - } - } + const switchTo = (next: Screen) => { setScreen(next); setError(''); setNotice('') } + const finishSignIn = () => navigate(resolveReturnPath(params.get('return')), { replace: true }) - const sendReset = async (event: React.FormEvent) => { + const sendReset = async (event: React.FormEvent) => { event.preventDefault() + const address = readField(event.currentTarget, 'email') setError('') setNotice('') + if (!address) { setError(t('login.missingFields')); return } if (!foodDb) { setError('Login is not configured on this deployment yet.'); return } setBusy(true) - const { error: authError } = await foodDb.auth.resetPasswordForEmail(email.trim(), { redirectTo: getRecoveryRedirectUrl(window.location.origin) }) + const { error: authError } = await foodDb.auth.resetPasswordForEmail(address, { redirectTo: getRecoveryRedirectUrl(window.location.origin) }) setBusy(false) if (authError) setError(authError.message) else setNotice('If an account exists for that email, you will receive a password reset link.') } - const joinUpdates = async (event: React.FormEvent) => { + const joinUpdates = async (event: React.FormEvent) => { event.preventDefault() - const website = String(new FormData(event.currentTarget as HTMLFormElement).get('website') || '') + const address = readField(event.currentTarget, 'updates-email') + const website = String(new FormData(event.currentTarget).get('website') || '') setError('') setNotice('') - if (!isValidUpdatesEmail(email)) { setError('Please enter a valid email address.'); return } + if (!isValidUpdatesEmail(address)) { setError('Please enter a valid email address.'); return } setBusy(true) try { - const result = await subscribeForUpdates(email, website) + const result = await subscribeForUpdates(address, website) setNotice(result === 'already_subscribed' ? 'That email is already on the yuhm updates list.' : 'You are on the list. We will email when there is meaningful platform progress or a future offering.') @@ -94,13 +85,23 @@ export function LoginScreen() { else window.location.assign('/app/?mode=login') } - const isRecovery = authMode === 'recovery' - const isReset = authMode === 'reset' - const isUpdates = authMode === 'updates' + const isRecovery = screen === 'recovery' + const isReset = screen === 'reset' + const isUpdates = screen === 'updates' return

{isRecovery ? 'Choose a new password' : isReset ? 'Account recovery' : isUpdates ? 'Stay in the loop' : t('login.enterNetwork')}

-

{isRecovery ? 'Set a new password.' : isReset ? 'Reset your password.' : isUpdates ? 'Get yuhm updates.' : authMode === 'signup' ? t('login.createAccount') : t('login.welcomeBack')}

- {isRecovery ?

Choose a new password for your yuhm account.

{error &&

{error}

}{notice &&

{notice}

}
: isReset ?

Enter your email and we will send a secure link to choose a new password.

{error &&

{error}

}{notice &&

{notice}

}
: isUpdates ?

Hear about meaningful platform progress and future yuhm offerings. This only joins the email list. It does not create an account.

{error &&

{error}

}{notice &&

{notice}

}

We will only use this email for yuhm updates. Unsubscribe in any message.

:

{authMode === 'signup' ? t('login.signupCopy') : t('login.loginCopy')}

{error &&

{error}

}{notice &&

{notice}

}{authMode === 'login' && }
} +

{isRecovery ? 'Set a new password.' : isReset ? 'Reset your password.' : isUpdates ? 'Get yuhm updates.' : signupHint ? t('login.createAccount') : t('login.title')}

+ {isRecovery ?

Choose a new password for your yuhm account.

{error &&

{error}

}{notice &&

{notice}

}
: isReset ?

Enter your email and we will send a secure link to choose a new password.

{error &&

{error}

}{notice &&

{notice}

}
: isUpdates ?

Hear about meaningful platform progress and future yuhm offerings. This only joins the email list. It does not create an account.

{error &&

{error}

}{notice &&

{notice}

}

We will only use this email for yuhm updates. Unsubscribe in any message.

: <> +

{signupHint ? t('login.signupCopy') : t('login.continueCopy')}

+ + + + } + /> + } {!isRecovery && {t('login.browseAnonymously')} }
} diff --git a/yuhm/src/SimpleExperience.tsx b/yuhm/src/SimpleExperience.tsx index f0ac67dd..93b79805 100644 --- a/yuhm/src/SimpleExperience.tsx +++ b/yuhm/src/SimpleExperience.tsx @@ -13,6 +13,7 @@ import { LanguageToggle, useI18n, type MessageKey } from './i18n' import { FoodAlertBanner } from './FoodAlertBanner' import { LocationPrompt } from './prompts' import { useAuth } from './AuthProvider' +import { EmailContinueForm } from './AuthForm' const FoodMap = lazy(() => import('./FoodMap').then((module) => ({ default: module.FoodMap }))) @@ -78,7 +79,16 @@ export function SimpleExperience({ initialIntent }: { initialIntent: ConsumerInt const chooseIntent = (nextIntent: ConsumerIntent) => { navigate(`/app/?mode=anonymous&intent=${nextIntent}`) } - const openSimpleAction = (eyebrow: string, title: string, copy: string, advancedHref: string) => setActionSheet({ eyebrow, title, copy, advancedHref }) + // Members go straight to the destination. Guests get the one sign-in step + // inline in the sheet, then land on that same destination. + const openSimpleAction = (eyebrow: string, title: string, copy: string, advancedHref: string) => { + if (authReady && member) { navigate(advancedHref); return } + setActionSheet({ eyebrow, title, copy, advancedHref }) + } + const continueToAction = (advancedHref: string) => { + setActionSheet(null) + navigate(advancedHref) + } const enableAdvancedMode = () => { localStorage.setItem('yuhm:experience-mode', 'advanced') } @@ -173,6 +183,6 @@ export function SimpleExperience({ initialIntent }: { initialIntent: ConsumerInt
yuhm · Austin{t('simple.footer.advanced')}
{locationPromptOpen && } - {actionSheet &&
setActionSheet(null)}>
event.stopPropagation()}>

{actionSheet.eyebrow}

{actionSheet.title}

{actionSheet.copy}

{!authReady ? : member ? setActionSheet(null)}>{t('simple.sheet.openNext')} : {t('simple.sheet.signInToContinue')} }
} + {actionSheet &&
setActionSheet(null)}>
event.stopPropagation()}>

{actionSheet.eyebrow}

{actionSheet.title}

{actionSheet.copy}

{!authReady ? : member ? setActionSheet(null)}>{t('simple.sheet.openNext')} :

{t('simple.sheet.authCopy')}

continueToAction(actionSheet.advancedHref)} footer={{t('login.forgot')}} />
}
}
} diff --git a/yuhm/src/i18n.tsx b/yuhm/src/i18n.tsx index a87a430d..154d7ca7 100644 --- a/yuhm/src/i18n.tsx +++ b/yuhm/src/i18n.tsx @@ -36,6 +36,7 @@ const en = { 'landing.title': 'Food, shared\nfull circle.', 'landing.intro': 'Find food nearby, ask your community for what is needed, or help good food reach more neighbors. Nothing good goes to waste — what is left returns to the soil.', 'landing.proof': 'Public food information is open to everyone. You only need an account when you are ready to post or coordinate.', + 'landing.hero.findFood': 'Find food near me', 'landing.flow.label': 'How food moves through the network', 'landing.flow.grow': 'Grow', 'landing.flow.pool': 'Pool', @@ -164,7 +165,7 @@ const en = { 'simple.request.offerCopy': 'An account is required to offer food, transportation, storage, or volunteer time. The request stays open in simple mode.', 'simple.sheet.checking': 'Checking your account…', 'simple.sheet.openNext': 'Open secure next step', - 'simple.sheet.signInToContinue': 'Sign in to continue', + 'simple.sheet.authCopy': 'One step: your email and a password. New here? That creates your account.', 'simple.sheet.keepBrowsing': 'Keep browsing', 'simple.account.label': 'Open account and display settings', 'simple.account.eyebrow': 'Your experience', @@ -231,20 +232,21 @@ const en = { // Login 'login.enterNetwork': 'Enter the network', - 'login.welcomeBack': 'Welcome back.', + 'login.title': 'Sign in or create your account.', 'login.createAccount': 'Create your account.', 'login.emailLabel': 'Email address', 'login.passwordLabel': 'Password', - 'login.logIn': 'Log in', + 'login.continue': 'Continue', 'login.create': 'Create account', 'login.wait': 'Please wait…', 'login.forgot': 'Forgot password?', - 'login.switchToLogin': 'Already have an account? Log in', - 'login.switchToSignup': 'New here? Create an account', 'login.updatesSwitch': 'Skip the account. Get email updates', - 'login.browseAnonymously': 'Browse anonymously', - 'login.loginCopy': 'Log in with your email and password.', + 'login.browseAnonymously': 'Browse as a guest', + 'login.continueCopy': 'One step for everyone: your email and a password. New here? That creates your account. Already a member? It signs you in.', 'login.signupCopy': 'Create an account with your email and a password. Your browser can offer to save it on this device.', + 'login.existingAccount': 'That email already has a yuhm account. Check your password or reset it.', + 'login.notConfigured': 'Sign-in is not set up on this deployment yet. You can still browse as a guest.', + 'login.missingFields': 'Enter your email and a password to continue.', } as const export type MessageKey = keyof typeof en @@ -278,6 +280,7 @@ const es: Record = { 'landing.title': 'Comida compartida\nen círculo completo.', 'landing.intro': 'Encuentra comida cerca, pide a tu comunidad lo que hace falta o ayuda a que la buena comida llegue a más vecinos. Nada bueno se desperdicia: lo que sobra vuelve a la tierra.', 'landing.proof': 'La información pública sobre comida está abierta a todos. Solo necesitas una cuenta cuando quieras publicar o coordinar.', + 'landing.hero.findFood': 'Buscar comida cerca', 'landing.flow.label': 'Cómo se mueve la comida por la red', 'landing.flow.grow': 'Cultiva', 'landing.flow.pool': 'Reúne', @@ -405,7 +408,7 @@ const es: Record = { 'simple.request.offerCopy': 'Se necesita una cuenta para ofrecer comida, transporte, almacenamiento o tiempo voluntario. La petición sigue abierta en modo simple.', 'simple.sheet.checking': 'Verificando tu cuenta…', 'simple.sheet.openNext': 'Abrir el siguiente paso seguro', - 'simple.sheet.signInToContinue': 'Inicia sesión para continuar', + 'simple.sheet.authCopy': 'Un solo paso: tu correo y una contraseña. ¿Nuevo aquí? Así se crea tu cuenta.', 'simple.sheet.keepBrowsing': 'Seguir mirando', 'simple.account.label': 'Abrir ajustes de cuenta y pantalla', 'simple.account.eyebrow': 'Tu experiencia', @@ -469,20 +472,21 @@ const es: Record = { 'map.noLive': 'No hay lugares comunitarios en vivo ahora. Mostrando el directorio base de Austin.', 'login.enterNetwork': 'Entra a la red', - 'login.welcomeBack': 'Bienvenido de nuevo.', + 'login.title': 'Inicia sesión o crea tu cuenta.', 'login.createAccount': 'Crea tu cuenta.', 'login.emailLabel': 'Correo electrónico', 'login.passwordLabel': 'Contraseña', - 'login.logIn': 'Iniciar sesión', + 'login.continue': 'Continuar', 'login.create': 'Crear cuenta', 'login.wait': 'Un momento…', 'login.forgot': '¿Olvidaste tu contraseña?', - 'login.switchToLogin': '¿Ya tienes cuenta? Inicia sesión', - 'login.switchToSignup': '¿Primera vez? Crea una cuenta', 'login.updatesSwitch': 'Sin cuenta. Recibir noticias por correo', - 'login.browseAnonymously': 'Navegar de forma anónima', - 'login.loginCopy': 'Inicia sesión con tu correo y contraseña.', + 'login.browseAnonymously': 'Mirar como invitado', + 'login.continueCopy': 'Un solo paso para todos: tu correo y una contraseña. ¿Nuevo aquí? Así se crea tu cuenta. ¿Ya eres miembro? Así entras.', 'login.signupCopy': 'Crea una cuenta con tu correo y una contraseña. Tu navegador puede ofrecer guardarla en este dispositivo.', + 'login.existingAccount': 'Ese correo ya tiene una cuenta de yuhm. Revisa tu contraseña o restablécela.', + 'login.notConfigured': 'El inicio de sesión aún no está configurado en este sitio. Puedes seguir mirando como invitado.', + 'login.missingFields': 'Escribe tu correo y una contraseña para continuar.', } const catalogs: Record> = { en, es } diff --git a/yuhm/src/lib/auth.test.ts b/yuhm/src/lib/auth.test.ts index e9f4c2f8..aba03990 100644 --- a/yuhm/src/lib/auth.test.ts +++ b/yuhm/src/lib/auth.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { createAccountAndSession, getAuthErrorMessage, getMemberIdentity, getRecoveryRedirectUrl, updatePasswordAndSignOut } from './auth' +import { continueWithEmail, createAccountAndSession, getAuthErrorMessage, getMemberIdentity, getRecoveryRedirectUrl, resolveReturnPath, signInHref, updatePasswordAndSignOut } from './auth' const credentials = { email: 'neighbor@example.org', password: 'community-food' } const user = { id: 'member-1' } @@ -101,3 +101,82 @@ describe('getMemberIdentity', () => { expect(getMemberIdentity({ email: 'eastside.kitchen@example.org', user_metadata: {} } as never).displayName).toBe('eastside kitchen') }) }) + +describe('continueWithEmail', () => { + const invalidCredentials = { code: 'invalid_credentials', message: 'Invalid login credentials' } + + it('signs an existing member in with one step', async () => { + const signInWithPassword = vi.fn().mockResolvedValue({ data: { user, session }, error: null }) + const signUp = vi.fn() + + const result = await continueWithEmail({ signUp, signInWithPassword } as never, credentials.email, credentials.password) + + expect(result).toEqual({ status: 'signed_in' }) + expect(signUp).not.toHaveBeenCalled() + }) + + it('creates the account when no member matches the email', async () => { + const signInWithPassword = vi.fn().mockResolvedValue({ data: { user: null, session: null }, error: invalidCredentials }) + const signUp = vi.fn().mockResolvedValue({ data: { user, session }, error: null }) + + const result = await continueWithEmail({ signUp, signInWithPassword } as never, credentials.email, credentials.password) + + expect(signUp).toHaveBeenCalledWith(credentials) + expect(result).toEqual({ status: 'created' }) + }) + + it('explains a wrong password on an existing account instead of creating a duplicate', async () => { + const signInWithPassword = vi.fn().mockResolvedValue({ data: { user: null, session: null }, error: invalidCredentials }) + const signUp = vi.fn().mockResolvedValue({ data: { user: null, session: null }, error: { code: 'user_already_exists', message: 'User already registered' } }) + + const result = await continueWithEmail({ signUp, signInWithPassword } as never, credentials.email, credentials.password) + + expect(result).toMatchObject({ status: 'error', reason: 'existing_account' }) + }) + + it('treats a failed retry after an obfuscated signup as a wrong password', async () => { + const signInWithPassword = vi.fn().mockResolvedValue({ data: { user: null, session: null }, error: invalidCredentials }) + const signUp = vi.fn().mockResolvedValue({ data: { user, session: null }, error: null }) + + const result = await continueWithEmail({ signUp, signInWithPassword } as never, credentials.email, credentials.password) + + expect(signInWithPassword).toHaveBeenCalledTimes(2) + expect(result).toMatchObject({ status: 'error', reason: 'existing_account' }) + }) + + it('surfaces other provider errors without attempting signup', async () => { + const signInWithPassword = vi.fn().mockResolvedValue({ data: { user: null, session: null }, error: { code: 'over_request_rate_limit', message: 'Too many requests' } }) + const signUp = vi.fn() + + const result = await continueWithEmail({ signUp, signInWithPassword } as never, credentials.email, credentials.password) + + expect(signUp).not.toHaveBeenCalled() + expect(result).toEqual({ status: 'error', reason: 'other', message: 'Too many requests' }) + }) +}) + +describe('resolveReturnPath', () => { + it('returns the exact in-app destination the person was headed to', () => { + expect(resolveReturnPath('/app/?mode=advanced&workspace=rescue&action=submit')).toBe('/app/?mode=advanced&workspace=rescue&action=submit') + }) + + it('maps legacy intent names onto the focused flows', () => { + expect(resolveReturnPath('contribute')).toBe('/app/?intent=contribute') + expect(resolveReturnPath('request')).toBe('/app/?intent=request') + }) + + it('falls back to the food finder for missing, foreign, or malformed destinations', () => { + expect(resolveReturnPath(null)).toBe('/app/?intent=food') + expect(resolveReturnPath('https://evil.example/app/')).toBe('/app/?intent=food') + expect(resolveReturnPath('//evil.example/app/')).toBe('/app/?intent=food') + expect(resolveReturnPath('/admin')).toBe('/app/?intent=food') + expect(resolveReturnPath('/app/?x=1 javascript:')).toBe('/app/?intent=food') + }) +}) + +describe('signInHref', () => { + it('carries the destination through the login screen', () => { + expect(signInHref('/app/?mode=advanced&workspace=volunteer')).toBe('/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dadvanced%26workspace%3Dvolunteer') + expect(signInHref()).toBe('/app/?mode=login') + }) +}) diff --git a/yuhm/src/lib/auth.ts b/yuhm/src/lib/auth.ts index 894ea6f1..2ef24c77 100644 --- a/yuhm/src/lib/auth.ts +++ b/yuhm/src/lib/auth.ts @@ -55,3 +55,62 @@ export function getMemberIdentity(user: User | null) { return { displayName, email, initials } } + +type ContinueAuth = Pick + +export type ContinueWithEmailResult = + | { status: 'signed_in' | 'created' } + | { status: 'error'; reason: 'existing_account' | 'other'; message: string } + +const INVALID_CREDENTIALS = /invalid login credentials|invalid_credentials/i +const EXISTING_ACCOUNT = /already (been )?registered|already exists|user_already_exists/i + +function isInvalidCredentials(error: { code?: string; message?: string }) { + return error.code === 'invalid_credentials' || INVALID_CREDENTIALS.test(error.message ?? '') +} + +function isExistingAccount(error: { code?: string; message?: string }) { + return error.code === 'user_already_exists' || EXISTING_ACCOUNT.test(error.message ?? '') +} + +export const EXISTING_ACCOUNT_MESSAGE = 'That email already has a yuhm account. Check your password or reset it.' + +/** + * One "Continue" action for members and newcomers alike: sign in with the + * email and password, and when no account matches, create one with those same + * credentials. Only a wrong password on an existing account needs a second try. + */ +export async function continueWithEmail(auth: ContinueAuth, email: string, password: string): Promise { + const login = await auth.signInWithPassword({ email, password }) + if (login.data.session) return { status: 'signed_in' } + if (login.error && !isInvalidCredentials(login.error)) return { status: 'error', reason: 'other', message: getAuthErrorMessage(login.error, 'login') } + + const signup = await createAccountAndSession(auth, email, password) + if (signup.data.session) return { status: 'created' } + // Signup refused or the retry still failed: the email belongs to an existing + // account and the password did not match it. + if (signup.error && (isExistingAccount(signup.error) || isInvalidCredentials(signup.error))) return { status: 'error', reason: 'existing_account', message: EXISTING_ACCOUNT_MESSAGE } + if (signup.error) return { status: 'error', reason: 'other', message: getAuthErrorMessage(signup.error, 'signup') } + return { status: 'error', reason: 'other', message: 'Your account was created, but yuhm could not sign you in. Please try again.' } +} + +export const DEFAULT_RETURN_PATH = '/app/?intent=food' + +const LEGACY_RETURN_INTENTS = new Set(['food', 'contribute', 'gather', 'request']) +const IN_APP_PATH = /^\/app\/[^\s\\]*$/ + +/** + * Where to land after signing in: the exact in-app destination the person was + * headed to, a legacy intent name, or the food finder. Foreign origins and + * protocol-relative URLs never pass through. + */ +export function resolveReturnPath(raw: string | null | undefined, fallback = DEFAULT_RETURN_PATH) { + if (!raw) return fallback + if (LEGACY_RETURN_INTENTS.has(raw)) return `/app/?intent=${raw}` + return IN_APP_PATH.test(raw) ? raw : fallback +} + +/** Login-screen URL that brings the person back to `returnTo` once signed in. */ +export function signInHref(returnTo?: string) { + return returnTo ? `/app/?mode=login&return=${encodeURIComponent(returnTo)}` : '/app/?mode=login' +} diff --git a/yuhm/src/styles.css b/yuhm/src/styles.css index 42e8c421..1d61ec5c 100644 --- a/yuhm/src/styles.css +++ b/yuhm/src/styles.css @@ -714,6 +714,16 @@ button { border: 0; cursor: pointer; } .simple-sheet h2 { max-width: 400px; margin: 0; padding-right: 30px; font: 700 26px/1.1 'Space Grotesk', sans-serif; letter-spacing: -.035em; } .simple-sheet > p:not(.simple-eyebrow) { color: var(--simple-muted); margin: 12px 0 0; font-size: 12px; line-height: 1.6; } .simple-sheet-secondary { width: 100%; min-height: 45px; color: var(--simple-ink); background: transparent; margin-top: 6px; font-size: 10px; font-weight: 800; } +/* Inline sign-in inside the action sheet: guests finish the step without leaving the page. */ +.sheet-auth { margin-top: 16px; } +.sheet-auth-copy { color: var(--simple-muted); margin: 0 0 12px; font-size: 12px; line-height: 1.6; } +.sheet-auth label { display: block; color: #3c4a42; font-size: 11px; font-weight: 700; } +.sheet-auth input { display: block; width: 100%; margin-top: 7px; padding: 13px 14px; border: 1.5px solid #d5e0d5; border-radius: 12px; background: #fbfcf9; color: var(--simple-ink); font-size: 14px; outline: 0; } +.sheet-auth input:focus { border-color: var(--simple-green); box-shadow: 0 0 0 3px #246b4522; } +.sheet-auth .login-submit { min-height: 50px; border-radius: 12px; background: var(--simple-green); font-size: 11px; font-weight: 800; } +.sheet-auth .login-submit:hover { background: var(--simple-green-dark); } +.sheet-auth .login-error { margin-top: 12px; } +.sheet-auth .login-switch { font-size: 11px; } .entry-path-list-three { grid-template-columns: repeat(3, minmax(0, 1fr)); } .entry-path-list-three .entry-path { min-height: 380px; } .entry-path-list-three .entry-path-copy strong { font-size: clamp(22px, 2.5vw, 32px); } @@ -1545,8 +1555,22 @@ button.food-alert-banner { cursor: pointer; } } /* Landing hero CTA into the living world (the default app at /app/). */ -.hero-cta-row { margin-top: 24px; } -.hero-world-cta { display: inline-flex; align-items: center; gap: 9px; min-height: 54px; padding: 14px 27px; background: #2d6b50; color: #fff8e8; border-radius: 17px; font: 600 17px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .01em; text-decoration: none; box-shadow: 0 4px 0 #1f4a37, 0 10px 22px #2d6b5040; transition: transform .2s var(--ease-out), box-shadow .2s var(--ease-out); } -.hero-world-cta:hover { transform: translateY(-2px); box-shadow: 0 6px 0 #1f4a37, 0 14px 26px #2d6b5045; } -.hero-world-cta:active { transform: translateY(1px); box-shadow: 0 2px 0 #1f4a37; } -@media (prefers-reduced-motion: reduce) { .hero-world-cta { transition: none; } } +/* Hero doors: browse as a guest (primary) or sign in. The decision lives above the fold. */ +.hero-cta-row { margin-top: 24px; display: flex; flex-wrap: wrap; align-items: center; gap: 12px; } +.hero-cta { display: inline-flex; align-items: center; gap: 9px; min-height: 54px; padding: 14px 24px; border-radius: 17px; font: 600 17px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .01em; text-decoration: none; transition: transform .2s var(--ease-out), box-shadow .2s var(--ease-out), background .2s var(--ease-out); } +.hero-cta-primary { background: #2d6b50; color: #fff8e8; box-shadow: 0 4px 0 #1f4a37, 0 10px 22px #2d6b5040; } +.hero-cta-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 0 #1f4a37, 0 14px 26px #2d6b5045; } +.hero-cta-primary:active { transform: translateY(1px); box-shadow: 0 2px 0 #1f4a37; } +.hero-cta-secondary { background: #fffefa; color: #2d6b50; border: 2px solid #2d6b50; box-shadow: 0 4px 0 #c9d8c7; } +.hero-cta-secondary:hover { transform: translateY(-2px); background: #eaf3e8; box-shadow: 0 6px 0 #c9d8c7; } +.hero-cta-secondary:active { transform: translateY(1px); box-shadow: 0 2px 0 #c9d8c7; } +@media (prefers-reduced-motion: reduce) { .hero-cta { transition: none; } } +@media (max-width: 759px) { .hero-cta { width: 100%; justify-content: center; } } + +/* iOS zooms the page when a focused field is smaller than 16px, and because + navigation is client-side the zoom outlives the form: sign in, tap "Browse as + a guest", and the map arrives oversized. Every text field stays at 16px on + touch screens; desktop keeps the compact sizes. */ +@media (pointer: coarse), (max-width: 759px) { + input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), select, textarea { font-size: 16px; } +} diff --git a/yuhm/src/world/World.test.tsx b/yuhm/src/world/World.test.tsx index c5fb4e9d..8459418c 100644 --- a/yuhm/src/world/World.test.tsx +++ b/yuhm/src/world/World.test.tsx @@ -14,24 +14,15 @@ describe('living-map world experience', () => { it('walks the whole cooperative loop: onboard, join, complete, gratitude, regenerate', { timeout: 20000 }, async () => { render() - // Onboarding reaches the map fast and explains the world. + // Onboarding is one screen: pick how to take part, and the first invitation + // it unlocks previews inline before stepping in. expect(await screen.findByRole('heading', { name: 'Find your local yuhm.' })).toBeInTheDocument() - await userEvent.click(screen.getByRole('button', { name: /Step in/ })) - - // Choose how to participate. - expect(screen.getByRole('heading', { name: 'How do you want to take part?' })).toBeInTheDocument() + expect(screen.getByRole('radiogroup', { name: 'How do you want to take part?' })).toBeInTheDocument() + expect(screen.getByText('Morning pickup at Hearthside')).toBeInTheDocument() await userEvent.click(screen.getByRole('radio', { name: /Move/ })) - await userEvent.click(screen.getByRole('button', { name: /Step in/ })) - - // Privacy step keeps location optional and on-device. - expect(screen.getByRole('heading', { name: 'Where should your circle be?' })).toBeInTheDocument() - expect(screen.getByText(/Your location stays on this device/)).toBeInTheDocument() - await userEvent.click(screen.getByRole('button', { name: 'Stay at neighborhood level' })) - - // The circle reveal offers one first action matched to the chosen role. - expect(screen.getByRole('heading', { name: 'Eastside Circle' })).toBeInTheDocument() expect(screen.getByText('Carry a leg of the Saturday Yuhm Run')).toBeInTheDocument() - await userEvent.click(screen.getByRole('button', { name: /Open the living map/ })) + expect(screen.queryByRole('heading', { name: 'Where should your circle be?' })).not.toBeInTheDocument() + await userEvent.click(screen.getByRole('button', { name: /Step in/ })) // The first invitation opens directly as a mission with sample labeling. expect(await screen.findByRole('heading', { name: 'Carry a leg of the Saturday Yuhm Run' })).toBeInTheDocument() diff --git a/yuhm/src/world/views.tsx b/yuhm/src/world/views.tsx index b301204f..447828c7 100644 --- a/yuhm/src/world/views.tsx +++ b/yuhm/src/world/views.tsx @@ -1,10 +1,10 @@ import { useState, type ReactNode } from 'react' -import { ArrowRight, Check, ChefHat, HandHeart, Leaf, MapPin, RefreshCw, Sprout, Truck, Users, UtensilsCrossed } from 'lucide-react' +import { ArrowRight, Check, ChefHat, HandHeart, Leaf, RefreshCw, Sprout, Truck, Users, UtensilsCrossed } from 'lucide-react' import { motion } from 'motion/react' import { BowlMark, usePrefersReducedMotion } from '../LandingDecor' import { Kicker, SampleTag, type MissionProgress } from './panels' import { useWorldText } from './worldStrings' -import { basePulse, circleName, personById, spotById, worldMissions, type WorldMission } from './worldData' +import { basePulse, personById, spotById, worldMissions, type WorldMission } from './worldData' export type WorldRole = 'eat' | 'grow' | 'make' | 'move' | 'share' | 'organize' @@ -29,10 +29,7 @@ type OnboardingProps = { export function WorldOnboarding({ onDone, onSkip }: OnboardingProps) { const w = useWorldText() const reduce = usePrefersReducedMotion() - const [step, setStep] = useState<'intro' | 'role' | 'privacy' | 'reveal'>('intro') const [role, setRole] = useState('eat') - const [locating, setLocating] = useState(false) - const [position, setPosition] = useState<{ latitude: number; longitude: number } | null>(null) const roles: { id: WorldRole; icon: ReactNode; label: string; copy: string }[] = [ { id: 'eat', icon: , label: w('world.role.eat'), copy: w('world.role.eatCopy') }, @@ -43,40 +40,21 @@ export function WorldOnboarding({ onDone, onSkip }: OnboardingProps) { { id: 'organize', icon: , label: w('world.role.organize'), copy: w('world.role.organizeCopy') }, ] - const useLocation = () => { - if (!('geolocation' in navigator)) { setStep('reveal'); return } - setLocating(true) - navigator.geolocation.getCurrentPosition( - (result) => { - setPosition({ latitude: result.coords.latitude, longitude: result.coords.longitude }) - setLocating(false) - setStep('reveal') - }, - () => { setLocating(false); setStep('reveal') }, - { timeout: 8000 }, - ) - } - const firstMission = worldMissions.find((mission) => mission.id === roleMissions[role]) - const stepMotion = reduce + const cardMotion = reduce ? {} : { initial: { opacity: 0, y: 26, scale: 0.985 }, animate: { opacity: 1, y: 0, scale: 1 }, transition: springy } + // One screen, one decision: pick how you take part, see the invitation it + // unlocks, step in. Location stays off the intro; the map works at + // neighborhood level and never needs an address. return
} diff --git a/yuhm/src/world/world.css b/yuhm/src/world/world.css index 2f880f25..5010ca17 100644 --- a/yuhm/src/world/world.css +++ b/yuhm/src/world/world.css @@ -416,15 +416,18 @@ .world-onboard-card { position: relative; width: min(440px, 100%); display: flex; flex-direction: column; gap: 14px; align-items: flex-start; background: var(--w-paper); border: 1.5px solid var(--w-line); border-radius: 26px; - padding: clamp(22px, 5vw, 34px); box-shadow: 0 24px 60px #49312833; margin: auto 0; + padding: clamp(20px, 5vw, 32px); box-shadow: 0 24px 60px #49312833; margin: auto 0; } .world-onboard-card.wide { width: min(560px, 100%); } .world-onboard-card h1 { font-size: clamp(27px, 6vw, 36px); line-height: 1.08; letter-spacing: -.01em; } .world-onboard-card > p { margin: 0; font-size: 14.5px; line-height: 1.6; color: #57453a; } -.world-onboard-bowl { width: 92px; height: 77px; align-self: center; } +.world-onboard-bowl { width: 72px; height: 60px; align-self: center; } .world-circle-name { color: var(--w-green-deep); } .world-role-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; width: 100%; } +.world-onboard-card .world-role { min-height: 76px; padding: 10px 12px; } +.world-onboard-card .world-role-grid { gap: 8px; } +@media (min-width: 520px) { .world-onboard-card .world-role-grid { grid-template-columns: repeat(3, 1fr); } } .world-role { position: relative; display: grid; gap: 3px; justify-items: start; text-align: left; min-height: 88px; padding: 12px 13px; background: #fff; border: 2px solid var(--w-line); border-radius: 16px; diff --git a/yuhm/src/world/worldStrings.ts b/yuhm/src/world/worldStrings.ts index 14783c48..fe902785 100644 --- a/yuhm/src/world/worldStrings.ts +++ b/yuhm/src/world/worldStrings.ts @@ -44,7 +44,7 @@ const en = { 'world.intro.start': 'Step in', 'world.intro.skip': 'Skip to the map', 'world.role.title': 'How do you want to take part?', - 'world.role.copy': 'Pick what fits today. You can do all of it, and change anytime.', + 'world.role.copy': 'Pick what fits today, step in, and your first invitation is waiting. You can do all of it, and change anytime.', 'world.role.eat': 'Eat', 'world.role.eatCopy': 'Find food with a story', 'world.role.grow': 'Grow', @@ -57,14 +57,7 @@ const en = { 'world.role.shareCopy': 'Host tables, stock shelves', 'world.role.organize': 'Organize', 'world.role.organizeCopy': 'Weave the neighborhood', - 'world.privacy.title': 'Where should your circle be?', - 'world.privacy.copy': 'Your location stays on this device. The map only ever shows your approximate neighborhood, never your address.', - 'world.privacy.use': 'Use my location', - 'world.privacy.stay': 'Stay at neighborhood level', - 'world.reveal.kicker': 'You are in', - 'world.reveal.copy': 'Six sample neighbors and the real public food directory are already on your map.', 'world.reveal.first': 'Your first invitation', - 'world.reveal.open': 'Open the living map', // Discover sheet 'world.discover.hello': 'Happening in your circle', @@ -195,7 +188,7 @@ const es: Record = { 'world.intro.start': 'Entrar', 'world.intro.skip': 'Ir directo al mapa', 'world.role.title': '¿Cómo quieres participar?', - 'world.role.copy': 'Elige lo que te quede hoy. Puedes hacerlo todo, y cambiar cuando quieras.', + 'world.role.copy': 'Elige lo que te quede hoy, entra y tu primera invitación te espera. Puedes hacerlo todo, y cambiar cuando quieras.', 'world.role.eat': 'Comer', 'world.role.eatCopy': 'Comida con historia', 'world.role.grow': 'Cultivar', @@ -208,14 +201,7 @@ const es: Record = { 'world.role.shareCopy': 'Mesas y estantes comunitarios', 'world.role.organize': 'Organizar', 'world.role.organizeCopy': 'Teje el vecindario', - 'world.privacy.title': '¿Dónde estará tu círculo?', - 'world.privacy.copy': 'Tu ubicación se queda en este dispositivo. El mapa solo muestra tu vecindario aproximado, nunca tu dirección.', - 'world.privacy.use': 'Usar mi ubicación', - 'world.privacy.stay': 'Quedarme a nivel de vecindario', - 'world.reveal.kicker': 'Estás en', - 'world.reveal.copy': 'Seis vecinos de ejemplo y el directorio público real de comida ya están en tu mapa.', 'world.reveal.first': 'Tu primera invitación', - 'world.reveal.open': 'Abrir el mapa vivo', 'world.discover.hello': 'Pasando en tu círculo', 'world.discover.missions': 'Invitaciones abiertas', From c515ab180925c1ff860898e3c57bdf5f02cf4b13 Mon Sep 17 00:00:00 2001 From: koH Date: Tue, 8 Sep 2026 16:42:59 -0500 Subject: [PATCH 02/24] docs(yuhm): session handoff for the onboarding funnel pass Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01LcoUkLVX2KaZWRmz4GJfJW (cherry picked from commit e8f9d37ff2d3d623024bafce7e82121b75d829ac) --- yuhm/_handoff-2026-09-08-onboarding-funnel.md | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 yuhm/_handoff-2026-09-08-onboarding-funnel.md diff --git a/yuhm/_handoff-2026-09-08-onboarding-funnel.md b/yuhm/_handoff-2026-09-08-onboarding-funnel.md new file mode 100644 index 00000000..d1009916 --- /dev/null +++ b/yuhm/_handoff-2026-09-08-onboarding-funnel.md @@ -0,0 +1,45 @@ +# Handoff — yuhm onboarding funnel (sign in or browse, then do the task) + +Date: 2026-09-08 +Mission: koH asked to cut yuhm's onboarding from "choose a path → find out more → log in → redo the action" to the fastest path: sign in immediately or browse as a guest, then do the task. + +## STATUS: DONE, COMMITTED, DEPLOYED + +- Commit `6e1b31b8a` on `agent/yuhm-network`, pushed to origin (branch in sync). `main` untouched — yuhm deploys from the CLI, not from main. +- Live at https://yuhm.handprotocol.org (Netlify deploy `6aa0756141ee9a9995e19c1c`). Verified on the live host: new hero/login copy in the served JS, the 16px touch-field rule in the served CSS, the Supabase project ref in the bundle, CSP + HSTS headers, wxl → yuhm 301. +- Tests 108 → 126 (`VITE_SUPABASE_URL= VITE_SUPABASE_ANON_KEY= npx vitest run`), `tsc --noEmit` clean, `npm run build` clean. +- Full technical write-up: the "Onboarding funnel pass, 2026-09-08" section at the top of `HANDOFF.md`. Do not redo it. + +## What shipped (one line each) + +- Landing hero = two doors above the fold: **Find food near me** (guest, `/app/?mode=anonymous&intent=food`) and **Sign in** (`/app/?mode=login`). Path cards stay as optional deep links; "Enter the living map" left the hero (world still at bare `/app/` + the banner). +- One sign-in step: `src/AuthForm.tsx` (`EmailContinueForm`) = email + password + Continue. `continueWithEmail` (`src/lib/auth.ts`) signs in, else creates the account with the same credentials; `user_already_exists` → "already has a yuhm account". No log-in/sign-up toggle. Email+password stays (passwordless removed earlier as a product decision — see HANDOFF "Product decisions made"). +- `return=` carries a full `/app/...` path (`resolveReturnPath`); legacy intent names still map; foreign URLs fall back to `/app/?intent=food`. `mode=reset` opens the reset screen directly. +- `SimpleExperience`: members skip the interstitial sheet (straight to the destination); guests get the Continue form inline in the sheet and land on the destination. +- World intro: one screen (role chips + inline first-invitation preview + Step in / Skip). Privacy and reveal steps removed with their strings. +- Phone fixes (Brave/iOS): auth inputs are uncontrolled (`FormData` at submit, `readField`) so password-manager autofill enables Continue; global rule at the end of `styles.css` keeps every text field/select/textarea at 16px under `(pointer: coarse), (max-width: 759px)` so iOS does not zoom on focus and carry the zoom into the next screen. + +## NOT yet verified (first thing next session, or koH on the phone) + +1. Live Supabase behaviour of the one-button auth: sign in with a saved account, then create a brand-new account through the same Continue button. The logic assumes `invalid_credentials` for an unknown email and `user_already_exists` on a duplicate signup, with **Confirm email OFF**. Only exercised against a mocked client so far. +2. On a phone: autofilled fields → Continue tappable; Sign in → Browse as a guest → map at normal size (the zoom bug). + +## Open follow-ups (koH may want next; none started) + +- Make the geolocation consent dialog at `intent=food` non-blocking (show the Austin map, offer "Near me" as a button) — it is the last modal between "Find food near me" and the map. +- Pass `return=` from the dashboard `AuthPrompt` (`src/prompts.tsx`), MapLab account link, and the world "More ways" Sign in link (`signInHref` helper exists in `src/lib/auth.ts`). +- World: location control on the map if wanted (removed from the intro; `onDone(role, null)` for now). +- HANDOFF.md "Current stack" still says "Successful login redirects to `/app/`" and lists `signup=1` as "Account creation" — both are now nuances of the one-step form; tidy when next editing that section. + +## Ground rules / gotchas + +- Another Claude session shares this checkout (unrelated modified files at repo root, `command/`, `clients/`, `threehandshealing/`, untracked `yuhm/tsetup.7.1.3.tar.xz` 78 MB). Stage by explicit path only. Never commit the tarball. +- Tests: a populated `.env.local` flips `foodDbConfigured` and breaks App.test gates — always run with `VITE_SUPABASE_URL= VITE_SUPABASE_ANON_KEY= npx vitest run`. The build, however, NEEDS `.env.local` (Supabase config is baked at build time; verify `grep -o vconmgerblqbworcqkvr dist/assets/index-*.js` before any deploy). +- Deploy = manual CLI with the **cryptokoh** Netlify token (CLI login is zantrra): `NETLIFY_AUTH_TOKEN=$(python3 -c "import json; cfg=json.load(open('$HOME/.config/netlify/config.json')); print([u['auth']['token'] for uid,u in cfg['users'].items() if uid.startswith('65ff678f')][0])") netlify deploy --prod --site 56ee91bf-bf15-472d-8c1c-d6c30af05d6c --dir dist --message "..."`. Headers/redirects ship from `public/_headers` + `public/_redirects`. +- Git push: SSH fails; push over HTTPS as cryptokoh and CLEAR the global gh helper first or it hands git the zantrra account (403): `git -c credential.helper= -c credential.helper='!f() { echo username=cryptokoh; echo password=$(gh auth token -u cryptokoh); }; f' push https://github.com/HandProtocol/handprotocol.git HEAD:agent/yuhm-network`. +- Visual QA: gstack `/browse` daemon is broken here; drive Playwright from `/home/koh/.claude/skills/gstack/node_modules/playwright/index.mjs` with `chromiumSandbox: false, args: ['--no-sandbox']`, Bash with `dangerouslyDisableSandbox: true`, serving `dist` via `npx vite preview --port 4173`. Use `devices['iPhone 13']` to get `pointer: coarse`. +- Vocabulary: Reciprocates / Contributors. Never name specific AI models in public copy. No ultracode / Workflow runs (koH, 2026-09-04). + +## Suggested next-session start + +Read this file, then `HANDOFF.md` top section. If koH reports the phone test passed, pick one follow-up above (the geolocation dialog is the highest-leverage funnel item left). If the live auth misbehaves, start in `src/lib/auth.ts` `continueWithEmail` and check the Supabase project's auth settings (Confirm email must be OFF; see HANDOFF "Important auth and database risks to verify"). From ff818a10bf85d397da8c3670cc9382e9233104d7 Mon Sep 17 00:00:00 2001 From: koH Date: Tue, 8 Sep 2026 17:09:08 -0500 Subject: [PATCH 03/24] feat(yuhm): one theme from landing to task, Sign in at the top of every surface koH's desktop review: the landing looked right, but Sign in dropped into a different-looking product (sage, Space Grotesk, 11px type), and on the living world at bare /app/ the only Sign in link sat ~2100px down the docked panel. - src/YuhmBrand.tsx: shared bowl + Baloo wordmark lockup used by the landing nav, the sign-in card, and the finder header. - styles.css "One yuhm from landing to task" override block: login card, .simple-app finder shell, guest sheet, and the finder's location dialog wear the landing/world tokens (oat, cacao, garden-green CTA, Baloo 2). Layout rules untouched; the coordinator dashboard keeps its tool theme. - World topbar: guests get a Sign in pill (return=/app/?mode=world), members get an initials pill with Find food / Command center / Sign out. Phones keep the pill label and hide the circle name under 480px. - Finder header: guests get a Sign in pill with return= to the current screen; the guest account menu and the WXL-era "WX" avatar are gone; members keep the initials menu, now with Sign out. - Dashboard AuthPrompt (one door + updates link), sidebar guest card, world "More ways" link, and MapLab account link all pass return=. - Sign-in card fits a 640px-tall laptop viewport; shorter continue copy (EN + ES). New strings: common.signOut, world.topbar.*. - Tests 126 -> 130 (AuthFunnel: world topbar, finder pill, member sign out, dashboard prompt return). Two older assertions updated. - HANDOFF.md, DESIGN.md, dated handoff: pass recorded; stale login-route nuances fixed. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01G2r6hMvjqMaTJ5NrqZw5vz (cherry picked from commit d6ed1dccf2ae0ef40e5d5e1c0870fe90cc70ad3c) --- yuhm/DESIGN.md | 9 +- yuhm/HANDOFF.md | 22 ++- yuhm/_handoff-2026-09-08-onboarding-funnel.md | 11 ++ yuhm/src/App.test.tsx | 11 +- yuhm/src/AuthFunnel.test.tsx | 69 +++++++-- yuhm/src/DashboardApp.tsx | 6 +- yuhm/src/LandingPage.tsx | 6 +- yuhm/src/LoginScreen.tsx | 3 +- yuhm/src/SimpleExperience.tsx | 17 ++- yuhm/src/YuhmBrand.tsx | 20 +++ yuhm/src/i18n.tsx | 6 +- yuhm/src/lib/auth.ts | 2 +- yuhm/src/map-lab/MapLab.tsx | 4 +- yuhm/src/prompts.tsx | 7 +- yuhm/src/styles.css | 132 ++++++++++++++++++ yuhm/src/world/WorldExperience.tsx | 21 ++- yuhm/src/world/panels.tsx | 3 +- yuhm/src/world/world.css | 30 ++++ yuhm/src/world/worldStrings.ts | 12 ++ 19 files changed, 350 insertions(+), 41 deletions(-) create mode 100644 yuhm/src/YuhmBrand.tsx diff --git a/yuhm/DESIGN.md b/yuhm/DESIGN.md index bead9d2a..67294b63 100644 --- a/yuhm/DESIGN.md +++ b/yuhm/DESIGN.md @@ -3,6 +3,12 @@ Derived from `src/styles.css` (live code) and `docs/WXLOVE-THEME-OPTIMIZATION.md` (token decision). The landing/public entry is the **brand** surface; the dashboard is **product**. +**2026-09-08:** the sign-in screen, the food finder (`SimpleExperience`), the guest sign-in sheet, and +the finder's location dialog now wear the brand theme too (oat ground `#fbf6ea`/`#fffdf6`, cacao ink +`#46312a`, garden-green actions `#2d6b50` with the hero-CTA offset shadow, Baloo 2 display). A person +sees one yuhm from the landing through signing in and into the task. Only the coordinator dashboard +(`mode=advanced`) keeps the product theme below. The shared lockup is `src/YuhmBrand.tsx`. + ## Color | Token | Value | Role | @@ -22,7 +28,8 @@ Landing is warm cream with forest structure; coral is precious. Dot-grid texture ## Typography -- **Space Grotesk** — display: h1 (clamp 3.5–7.5rem, -.07em tracking, .9 line), card titles. +- **Baloo 2** — display on brand surfaces (landing, world, sign-in, finder): rounded, 700–800 weight, near-zero tracking. +- **Space Grotesk** — display on the dashboard: h1 (clamp 3.5–7.5rem, -.07em tracking, .9 line), card titles. - **DM Sans** — body/UI. - **DM Mono** — eyebrows/kickers/metadata, uppercase, wide tracking, 9–10px. diff --git a/yuhm/HANDOFF.md b/yuhm/HANDOFF.md index cfdfe027..6fe72302 100644 --- a/yuhm/HANDOFF.md +++ b/yuhm/HANDOFF.md @@ -1,6 +1,6 @@ # yuhm Handoff -Last updated: 2026-08-24 +Last updated: 2026-09-08 > **Renamed 2026-08-24.** This product was WXL:FOOD ("W Xtra Love") until 2026-08-24, when it became **yuhm** (the yuhm network) — yum with the om at its center, Austin's regenerative food network. The live host moved from `wxl.handprotocol.org` to `yuhm.handprotocol.org` (the old host 301-redirects). Applied Supabase migrations keep their historical `NNN_wxl_*` filenames, historical plans keep their `plans/00X-wxl-*` names, and docs dated before the rename may still say WXL. @@ -8,6 +8,20 @@ This is the working orientation document for `yuhm/`. Read it before changing th Public-facing product behavior and safety boundaries are maintained in `docs/LIVING-DOCS.md`. Keep it current when a feature promise or workflow changes. It is intended to become the source for a future HTML documentation page. +## One theme from landing to task, 2026-09-08 (same-day follow-up) + +koH's desktop review: the landing looked right, but clicking Sign in dropped into a different-looking product (sage, Space Grotesk, 11px type), and on the living world at bare `/app/` the only Sign in link sat at the bottom of the docked panel (~2100px down). Fixed as one pass: + +- **Shared brand lockup.** `src/YuhmBrand.tsx` (bowl mark + Baloo wordmark + tagline) now heads the landing nav, the sign-in card, and the finder header. The landing keeps its scoped `.landing-brand` rules; other surfaces use the unscoped `.yuhm-lockup` rules. +- **Brand theme on every pre-login and first post-login surface.** An override block at the end of `src/styles.css` ("One yuhm from landing to task") re-skins `.login-page`/`.login-card`, the `.simple-app` shell (header, tabs, finder, action flows, cards, `.simple-primary`), the guest `.simple-sheet` + `.sheet-auth`, and the finder's location dialog (`.simple-app .access-card`) with the world/landing tokens (oat `#fbf6ea`/`#fffdf6`, cacao `#46312a`, garden green actions `#2d6b50` with the hero-CTA 3D shadow, Baloo 2 display). Layout rules are untouched; only colors, type, radii, shadows changed. The coordinator dashboard (`mode=advanced`) deliberately keeps its tool theme. The phone food map (`MapLab` product shell) was not re-skinned. +- **Sign in at the top, everywhere, with a way back.** World topbar: guests get a green **Sign in** pill (`signInHref('/app/?mode=world')`), members get an initials pill with a small menu (Find food, Command center, Sign out); on phones the pill keeps its label while the other topbar buttons stay icon-only, and the circle name hides under 480px so four controls fit. Finder header: guests get a **Sign in** pill carrying the current path as `return=`; the guest account menu (and the stale "WX" avatar) is gone; members keep the initials menu, which now has **Sign out**. Dashboard `AuthPrompt` and the sidebar "Browsing openly" card, the world "More ways" link, and the MapLab account link all pass `return=`. `AuthPrompt` shows one door ("Sign in or create an account") plus the updates link instead of separate Log in / Create an account. +- **Sign-in card fits a 640px-tall laptop viewport** (tighter spacing, 31px title, two-line `login.continueCopy` EN/ES). +- Strings: `common.signOut`, `world.topbar.*` (EN + ES). `getMemberIdentity` initials fallback is no longer `WX`. + +Tests 126 → 130 (`src/AuthFunnel.test.tsx` "sign in is one tap from the top of every pre-login surface": world topbar + panel links, finder header pill, member menu sign-out, dashboard prompt return). Two older assertions updated: the finder's advanced-mode gate now goes through the footer link (guests no longer have a header menu), and the dashboard guest profile link carries `return=`. + +Verified in headless Chromium at 1440×900, 1280×640, 430×932, 390×844. Not changed: the geolocation dialog at `intent=food` still opens as a modal (it is now on-theme); the phone MapLab shell keeps its own look. + ## Onboarding funnel pass, 2026-09-08 Goal: the shortest path from arriving to doing the task. Before, a guest who wanted to contribute went landing → scroll to "What brings you here today?" → pick a card → fill the form → Review → interstitial sheet → "Sign in to continue" → login page → choose log in vs sign up → submit → land on the intent tab → redo Review → sheet → "Open secure next step" → dashboard (seven screens). Bare `/app/` also ran a four-step world intro. @@ -198,7 +212,7 @@ After reviewing those recommendations, choose one bounded target and use `$impro - Posting, replying, supporting, offering help, and nominating sources require an authenticated Supabase session. - When an anonymous visitor attempts a write action, the app opens a clear account prompt with login and account-creation choices. - Write access is determined from the actual Supabase session, not from the `mode` query parameter. -- Successful login redirects to `/app/`. It does not redirect back into anonymous mode. +- Successful sign-in returns to the in-app `return=` path when one was given, otherwise to the food finder (`/app/?intent=food`). It never follows a foreign URL. - Public source information can be read without an account, but a source does not become verified through community nomination alone. - The future source-intelligence agent must remain human-reviewed. See `docs/FOOD-SOURCE-AGENT.md`. @@ -228,8 +242,8 @@ After reviewing those recommendations, choose one bounded target and use `$impro | `/app/` | Always the living-map world experience, on every viewport; the dashboard is explicit only (`mode=advanced` or `workspace=`) | | `/app/?mode=anonymous` | Same living-map world; a valid Supabase session still determines write access on other surfaces | | `/app/?mode=world` | Explicit world alias (same as `/app/`) | -| `/app/?mode=login` | Email and password login | -| `/app/?mode=login&signup=1` | Account creation | +| `/app/?mode=login` | One-step sign in (email + password + Continue; creates the account when none matches). `return=/app/...` brings the person back where they were | +| `/app/?mode=login&signup=1` | Same one-step form; asks the browser for a new password and labels the button Create account | | `/app/?mode=reset` | Request a password-reset email | | `/app/?mode=recovery` | Set a new password after following the recovery link | | `/app/?mode=anonymous&intent=food` | Public food-finding entry; phones open the command-bar map and adaptive result sheet | diff --git a/yuhm/_handoff-2026-09-08-onboarding-funnel.md b/yuhm/_handoff-2026-09-08-onboarding-funnel.md index d1009916..792577aa 100644 --- a/yuhm/_handoff-2026-09-08-onboarding-funnel.md +++ b/yuhm/_handoff-2026-09-08-onboarding-funnel.md @@ -43,3 +43,14 @@ Mission: koH asked to cut yuhm's onboarding from "choose a path → find out mor ## Suggested next-session start Read this file, then `HANDOFF.md` top section. If koH reports the phone test passed, pick one follow-up above (the geolocation dialog is the highest-leverage funnel item left). If the live auth misbehaves, start in `src/lib/auth.ts` `continueWithEmail` and check the Supabase project's auth settings (Confirm email must be OFF; see HANDOFF "Important auth and database risks to verify"). + +--- + +## Same-day follow-up: one theme from landing to task (koH's desktop review) + +koH: "it shows a different style theme before you actually login ... confusing with the flow of signing in as you have to go all the way down. lets make sure to streamline our design." Done in the same session; details in `HANDOFF.md` "One theme from landing to task, 2026-09-08". + +- `src/YuhmBrand.tsx` shared lockup; brand-theme override block at the end of `src/styles.css`; world topbar account control in `src/world/WorldExperience.tsx` + `world.css`. +- Sign in is now at the top of the world, the finder, and the dashboard prompt/sidebar, always with `return=` back to the same screen. Members get Sign out in the finder menu and the world menu. +- Tests 130 (was 126). Build clean. Screens checked at 1440×900, 1280×640, 430×932, 390×844. +- The coordinator dashboard keeps its tool theme on purpose; the phone MapLab shell was not re-skinned (candidate for a later pass if koH wants the phone map on-theme too). diff --git a/yuhm/src/App.test.tsx b/yuhm/src/App.test.tsx index b789f6c4..a0e49e6c 100644 --- a/yuhm/src/App.test.tsx +++ b/yuhm/src/App.test.tsx @@ -328,11 +328,12 @@ describe('yuhm entry points and interaction gates', () => { sessionStorage.setItem('yuhm:location-choice', 'complete') render() - await userEvent.click(screen.getByRole('button', { name: /Open account and display settings/i })) - expect(screen.getByText('Simple mode')).toBeInTheDocument() - const advancedLink = screen.getByRole('link', { name: /Turn on advanced workspace/i }) + // Guests see one clear Sign in control in the header; the coordinator + // workspace stays an explicit choice from the footer. + expect(screen.getByRole('link', { name: /^Sign in/ })).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /Open account and display settings/i })).not.toBeInTheDocument() + const advancedLink = screen.getByRole('link', { name: /^Advanced workspace$/i }) expect(advancedLink).toHaveAttribute('href', '/app/?mode=advanced') - expect(screen.getByText(/Coordination, routes, inventory, and reports/i)).toBeInTheDocument() advancedLink.addEventListener('click', (event) => event.preventDefault()) await userEvent.click(advancedLink) expect(localStorage.getItem('yuhm:experience-mode')).toBe('advanced') @@ -422,7 +423,7 @@ describe('yuhm entry points and interaction gates', () => { window.history.replaceState({}, '', '/app/?mode=advanced') render() - expect(screen.getByRole('link', { name: /Browsing openly/i })).toHaveAttribute('href', '/app/?mode=login') + expect(screen.getByRole('link', { name: /Browsing openly/i })).toHaveAttribute('href', '/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dadvanced') }) it('opens the mobile navigation drawer from the top bar', async () => { diff --git a/yuhm/src/AuthFunnel.test.tsx b/yuhm/src/AuthFunnel.test.tsx index 7f84101b..a6d9b904 100644 --- a/yuhm/src/AuthFunnel.test.tsx +++ b/yuhm/src/AuthFunnel.test.tsx @@ -39,16 +39,19 @@ import App from './App' const invalidCredentials = { code: 'invalid_credentials', message: 'Invalid login credentials' } +function resetHarness() { + authState.signedIn = false + mockDb.auth.signInWithPassword.mockReset() + mockDb.auth.signUp.mockReset() + mockDb.auth.signOut.mockClear() + localStorage.clear() + sessionStorage.clear() + Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true }) + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))) +} + describe('onboarding funnel: sign in once, land on the task', () => { - beforeEach(() => { - authState.signedIn = false - mockDb.auth.signInWithPassword.mockReset() - mockDb.auth.signUp.mockReset() - localStorage.clear() - sessionStorage.clear() - Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true }) - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))) - }) + beforeEach(resetHarness) afterEach(() => { vi.unstubAllGlobals() @@ -147,3 +150,51 @@ describe('onboarding funnel: sign in once, land on the task', () => { await waitFor(() => expect(window.location.search).toBe('?intent=contribute')) }) }) + +describe('sign in is one tap from the top of every pre-login surface', () => { + beforeEach(resetHarness) + afterEach(() => { vi.unstubAllGlobals() }) + + it('offers Sign in at the top of the living world and brings the person back to it', async () => { + localStorage.setItem('yuhm:world-intro', JSON.stringify({ role: 'eat' })) + window.history.replaceState({}, '', '/app/') + render() + + const links = await screen.findAllByRole('link', { name: /^Sign in$/ }) + expect(links.some((link) => link.closest('.world-topbar'))).toBe(true) + for (const link of links) expect(link).toHaveAttribute('href', '/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dworld') + }) + + it('offers Sign in in the finder header and returns to the same screen afterwards', async () => { + sessionStorage.setItem('yuhm:location-choice', 'complete') + window.history.replaceState({}, '', '/app/?mode=anonymous&intent=food') + render() + + expect(await screen.findByRole('link', { name: /^Sign in/ })).toHaveAttribute('href', '/app/?mode=login&return=%2Fapp%2F%3Fmode%3Danonymous%26intent%3Dfood') + expect(screen.queryByRole('button', { name: 'Open account and display settings' })).not.toBeInTheDocument() + }) + + it('gives a signed-in member an account menu with sign out instead of a Sign in button', async () => { + authState.signedIn = true + sessionStorage.setItem('yuhm:location-choice', 'complete') + window.history.replaceState({}, '', '/app/?mode=anonymous&intent=food') + render() + + const account = await screen.findByRole('button', { name: 'Open account and display settings' }) + expect(account).toHaveTextContent('N') + expect(screen.queryByRole('link', { name: /^Sign in/ })).not.toBeInTheDocument() + await userEvent.click(account) + await userEvent.click(screen.getByRole('button', { name: 'Sign out' })) + expect(mockDb.auth.signOut).toHaveBeenCalledTimes(1) + }) + + it('sends the dashboard account prompt back to the same workspace after signing in', async () => { + window.history.replaceState({}, '', '/app/?mode=advanced&workspace=community') + render() + + await userEvent.click(await screen.findByRole('button', { name: /FOOD IS HERE/i })) + const dialog = screen.getByRole('dialog', { name: /Join the network/i }) + expect(within(dialog).getByRole('link', { name: /Sign in or create an account/i })).toHaveAttribute('href', '/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dadvanced%26workspace%3Dcommunity') + expect(within(dialog).queryByRole('link', { name: /^Create an account/i })).not.toBeInTheDocument() + }) +}) diff --git a/yuhm/src/DashboardApp.tsx b/yuhm/src/DashboardApp.tsx index 5cbc9e2f..eb810630 100644 --- a/yuhm/src/DashboardApp.tsx +++ b/yuhm/src/DashboardApp.tsx @@ -1,11 +1,11 @@ import { lazy, Suspense, useEffect, useMemo, useState } from 'react' import { Activity, ArrowUpRight, Bell, Boxes, ChevronDown, ChevronLeft, ChevronRight, CircleHelp, Clock3, - HandHeart, Leaf, MapPin, Menu, MessageCircle, MousePointerClick, Plus, Route, Settings, ShieldCheck, Users, Warehouse, X, Zap, + CircleUserRound, HandHeart, Leaf, MapPin, Menu, MessageCircle, MousePointerClick, Plus, Route, Settings, ShieldCheck, Users, Warehouse, X, Zap, } from 'lucide-react' import { foodDbConfigured, loadFoodDropoffs, loadFoodRequests, loadFoodSpots, foodDb, type FoodSpotRecord } from './lib/foodRepository' import { useEngagement } from './lib/engagement' -import { getMemberIdentity } from './lib/auth' +import { getMemberIdentity, signInHref } from './lib/auth' import { useFoodAlerts } from './lib/useFoodAlerts' import { AddSpotModal, AlertCenter, FoodAlertsBoard, FoodAlertsOverview, FoodHereModal } from './CommunityTools' import { openCommunityContact } from './CommunityContactWidget' @@ -216,7 +216,7 @@ export function DashboardApp() { } label="Inventory" onClick={() => openView('inventory')} /> } label="Drop-off log" onClick={() => openView('dropoffs')} /> -
{clicks} community clicks
{!authReady ?
··Checking sessionRestoring account access
: isAuthenticated ?
{accountOpen &&

{memberIdentity.email}

}
: WXBrowsing openlySign in to coordinate}

Build{__YUHM_BUILD_ID__}

+
{clicks} community clicks
{!authReady ?
··Checking sessionRestoring account access
: isAuthenticated ?
{accountOpen &&

{memberIdentity.email}

}
: Browsing openlySign in to coordinate}

Build{__YUHM_BUILD_ID__}

{menuOpen && {t('common.signIn')}HAND Protocol
diff --git a/yuhm/src/LoginScreen.tsx b/yuhm/src/LoginScreen.tsx index 139a0180..5a45027e 100644 --- a/yuhm/src/LoginScreen.tsx +++ b/yuhm/src/LoginScreen.tsx @@ -6,6 +6,7 @@ import { isValidUpdatesEmail, subscribeForUpdates } from './lib/updates' import { EmailContinueForm, readField } from './AuthForm' import { AppLink, useRoute } from './router' import { LanguageToggle, useI18n } from './i18n' +import { YuhmBrand } from './YuhmBrand' type Screen = 'continue' | 'reset' | 'recovery' | 'updates' @@ -88,7 +89,7 @@ export function LoginScreen() { const isRecovery = screen === 'recovery' const isReset = screen === 'reset' const isUpdates = screen === 'updates' - return
+ return

{isRecovery ? 'Choose a new password' : isReset ? 'Account recovery' : isUpdates ? 'Stay in the loop' : t('login.enterNetwork')}

{isRecovery ? 'Set a new password.' : isReset ? 'Reset your password.' : isUpdates ? 'Get yuhm updates.' : signupHint ? t('login.createAccount') : t('login.title')}

{isRecovery ?

Choose a new password for your yuhm account.

{error &&

{error}

}{notice &&

{notice}

}
: isReset ?

Enter your email and we will send a secure link to choose a new password.

{error &&

{error}

}{notice &&

{notice}

}
: isUpdates ?

Hear about meaningful platform progress and future yuhm offerings. This only joins the email list. It does not create an account.

{error &&

{error}

}{notice &&

{notice}

}

We will only use this email for yuhm updates. Unsubscribe in any message.

: <> diff --git a/yuhm/src/SimpleExperience.tsx b/yuhm/src/SimpleExperience.tsx index 93b79805..7170d0f1 100644 --- a/yuhm/src/SimpleExperience.tsx +++ b/yuhm/src/SimpleExperience.tsx @@ -1,7 +1,7 @@ import { lazy, Suspense, useEffect, useMemo, useState } from 'react' import { ArrowUpRight, CalendarDays, ChevronDown, ChevronRight, Clock3, HandHeart, Leaf, MapPin, MessageCircle, Navigation, Package, Search, Settings, ShieldCheck, Truck, Users, X } from 'lucide-react' -import { foodDbConfigured, loadFoodSpots, type FoodAlertRecord, type FoodSpotRecord } from './lib/foodRepository' -import { getMemberIdentity } from './lib/auth' +import { foodDb, foodDbConfigured, loadFoodSpots, type FoodAlertRecord, type FoodSpotRecord } from './lib/foodRepository' +import { getMemberIdentity, signInHref } from './lib/auth' import { useFoodAlerts } from './lib/useFoodAlerts' import { openCommunityContact } from './CommunityContactWidget' import type { FoodMapLocation } from './FoodMap' @@ -14,6 +14,7 @@ import { FoodAlertBanner } from './FoodAlertBanner' import { LocationPrompt } from './prompts' import { useAuth } from './AuthProvider' import { EmailContinueForm } from './AuthForm' +import { YuhmBrand } from './YuhmBrand' const FoodMap = lazy(() => import('./FoodMap').then((module) => ({ default: module.FoodMap }))) @@ -26,7 +27,7 @@ const filterLabelKeys: Record = { export function SimpleExperience({ initialIntent }: { initialIntent: ConsumerIntent }) { const { t } = useI18n() - const { params, navigate } = useRoute() + const { path, params, navigate } = useRoute() const { member, authReady } = useAuth() const routeIntent = params.get('intent') const intent: ConsumerIntent = routeIntent === 'food' || routeIntent === 'contribute' || routeIntent === 'gather' || routeIntent === 'request' ? routeIntent : initialIntent @@ -76,6 +77,12 @@ export function SimpleExperience({ initialIntent }: { initialIntent: ConsumerInt return matchesQuery && matchesListingFilter(location, foodFilter, alertSpotIds) }), [allLocations, query, foodFilter, alertSpotIds]) + // Signing in from this screen brings the person straight back to it. + const herePath = `${path}${params.toString() ? `?${params.toString()}` : ''}` + const signOut = async () => { + setAccountMenuOpen(false) + await foodDb?.auth.signOut() + } const chooseIntent = (nextIntent: ConsumerIntent) => { navigate(`/app/?mode=anonymous&intent=${nextIntent}`) } @@ -122,9 +129,9 @@ export function SimpleExperience({ initialIntent }: { initialIntent: ConsumerInt return
- yuhmFOOD + -
{accountMenuOpen &&

{t('simple.account.eyebrow')}

{t('simple.account.simpleMode')}{member ? t('simple.account.signedInAs', { name: getMemberIdentity(member).displayName }) : t('simple.account.anonymous')}{authReady && !member && {t('common.signIn')} }{t('simple.account.advanced')}{t('simple.account.advancedDetail')}
}
+
{authReady && !member && {t('common.signIn')} }{member &&
{accountMenuOpen &&

{t('simple.account.eyebrow')}

{getMemberIdentity(member).displayName}{t('simple.account.signedInAs', { name: getMemberIdentity(member).email || getMemberIdentity(member).displayName })}{t('simple.account.advanced')}{t('simple.account.advancedDetail')}
}
}
+ const { path, params } = useRoute() + const herePath = `${path}${params.toString() ? `?${params.toString()}` : ''}` + return
motion.requestClose()}>
event.stopPropagation()}>♥

Account needed

Join the network to take action.

Anonymous browsing is open to everyone. One step with your email and a password signs you in or creates your account, then brings you right back here to post rescues, reply to requests, offer help, and nominate food sources.

Sign in or create an account Email me yuhm updates
Updates do not create an account or unlock posting.
} export function LocationPrompt({ motion, onLocated, onSkip }: { motion: DialogMotionControls; onLocated: (latitude: number, longitude: number) => void; onSkip: () => void }) { diff --git a/yuhm/src/styles.css b/yuhm/src/styles.css index 1d61ec5c..11f6ec8e 100644 --- a/yuhm/src/styles.css +++ b/yuhm/src/styles.css @@ -1574,3 +1574,135 @@ button.food-alert-banner { cursor: pointer; } @media (pointer: coarse), (max-width: 759px) { input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), select, textarea { font-size: 16px; } } + +/* ============================================================ + One yuhm from landing to task (2026-09-08) + The sign-in screen, the food finder, the guest sheet, and the + location dialog now wear the same warm brand theme as the landing + and the living world (oat ground, cacao ink, Baloo 2 display, + garden-green actions). The coordinator dashboard keeps its tool + theme. Overrides only; earlier rules keep layout and behavior. + ============================================================ */ + +/* Shared brand lockup (see src/YuhmBrand.tsx). The landing keeps its own + scoped .landing-brand rules, which win there by specificity. */ +.yuhm-lockup { display: flex; align-items: center; gap: 11px; width: max-content; color: #4a332a; text-decoration: none; } +.yuhm-lockup:hover .yuhm-mark { transform: rotate(-7deg) scale(1.08); } +.yuhm-lockup .yuhm-word { display: block; color: #4a332a; font: 800 22px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .004em; } +.yuhm-lockup small { display: block; color: #7d6b57; font: 500 8.5px 'DM Mono', monospace; letter-spacing: .1em; text-transform: uppercase; margin-top: 3px; } + +/* ---- Sign in ---- */ +.login-page { position: relative; isolation: isolate; color: #3b2a22; background: #fbf6ea; } +.login-page::before { content: ''; position: absolute; inset: 0; z-index: -1; background: radial-gradient(circle at 76% 14%, #f9e3bd 0, #fbf6ea 42%, transparent 70%); } +.login-card { width: min(450px, 100%); background: #fffdf6; border: 1.5px solid #e8dcc0; border-radius: 26px; padding: 22px 28px 24px; box-shadow: 0 18px 44px #4c633318; } +.login-card-top { align-items: center; margin-bottom: 22px; } +.login-card .eyebrow { color: #7d6b57; font: 500 9.5px 'DM Mono', monospace; letter-spacing: .12em; } +.login-card h1 { color: #46312a; font: 700 31px/1.05 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: -.01em; margin: 0 0 8px; } +.login-copy { color: #5d5348; font-size: 13.5px; line-height: 1.5; margin: 0 0 18px; } +.login-card label { color: #4a332a; font-size: 13px; font-weight: 700; } +.login-card input { border: 1.5px solid #e0d3b4; border-radius: 14px; background: #fffdf6; color: #3b2a22; padding: 12px 14px; font-size: 15px; } +.login-card input:focus { border-color: #52734d; box-shadow: 0 0 0 3px #52734d22; } +.login-submit, .login-anonymous { justify-content: center; gap: 8px; min-height: 50px; border-radius: 16px; font: 600 16px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .01em; transition: transform .2s var(--ease-out), box-shadow .2s var(--ease-out), background .2s var(--ease-out); } +.login-submit { color: #fff8e8; background: #2d6b50; margin-top: 16px; box-shadow: 0 4px 0 #1f4a37, 0 10px 22px #2d6b5030; } +.login-submit:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 0 #1f4a37, 0 14px 26px #2d6b5040; } +.login-submit:active:not(:disabled) { transform: translateY(1px); box-shadow: 0 2px 0 #1f4a37; } +.login-anonymous { color: #2d6b50; background: #fffefa; border: 2px solid #2d6b50; margin-top: 10px; box-shadow: 0 4px 0 #c9d8c7; } +.login-anonymous:hover { transform: translateY(-2px); background: #eaf3e8; box-shadow: 0 6px 0 #c9d8c7; } +.login-switch { color: #55763f; font-size: 12.5px; padding-top: 10px; } +.login-switch:hover { color: #3f5d2c; } +.login-updates-switch { margin-top: 8px; padding-top: 12px; border-top: 1.5px dashed #e8dcc0; } +.login-error { color: #a63c1e; background: #fbe6df; border-radius: 12px; padding: 10px 12px; font-size: 13px; line-height: 1.45; margin: 12px 0 0; } +.login-success { color: #3f5d2c; background: #f2f8e8; border: 1.5px solid #c4d8ae; border-radius: 14px; font-size: 13px; } +.login-success span { color: #5c6b49; } +.login-privacy { color: #7d6b57; font-size: 12px; } +@media (prefers-reduced-motion: reduce) { .login-submit, .login-anonymous, .yuhm-lockup .yuhm-mark { transition: none; } } + +/* ---- Food finder shell ---- */ +.simple-app { + --simple-ink: #3b2a22; + --simple-muted: #7d6b57; + --simple-green: #2d6b50; + --simple-green-dark: #1f4a37; + --simple-warm: #fff3dc; + --simple-line: #ecdfc4; + --simple-paper: #fffdf6; + background: #fbf6ea; +} +.simple-header { height: 68px; background: #fbf6eaf0; border-bottom: 1.5px solid #f0e4c8; backdrop-filter: blur(6px); } +.simple-header .yuhm-lockup { justify-self: start; } +.simple-location { color: #4a332a; background: var(--simple-warm); border: 1.5px solid #e8dcc0; font-size: 12.5px; } +.simple-location svg:first-child { color: var(--simple-green); } +.simple-header-tools { display: flex; align-items: center; justify-content: flex-end; gap: 8px; } +.simple-signin { display: inline-flex; align-items: center; gap: 6px; min-height: 40px; padding: 0 16px; border-radius: 999px; color: #fff8e8; background: var(--simple-green); font: 600 14px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .01em; text-decoration: none; white-space: nowrap; box-shadow: 0 3px 0 var(--simple-green-dark); transition: transform .2s var(--ease-out), box-shadow .2s var(--ease-out); } +.simple-signin:hover { transform: translateY(-1px); box-shadow: 0 4px 0 var(--simple-green-dark); } +.simple-signin:active { transform: translateY(1px); box-shadow: 0 1px 0 var(--simple-green-dark); } +.simple-account { width: 40px; height: 40px; color: var(--simple-warm); background: #4a332a; font: 700 11px 'DM Mono', monospace; letter-spacing: .04em; } +.simple-account-menu { background: var(--simple-paper); border: 1.5px solid #e8dcc0; border-radius: 20px; box-shadow: 0 18px 44px #49312833; } +.simple-account-menu > strong { font: 700 19px/1.15 'Baloo 2', 'DM Sans', sans-serif; color: #46312a; letter-spacing: 0; } +.simple-account-menu > span { color: var(--simple-muted); font-size: 12px; word-break: break-word; } +.simple-account-menu > a, .simple-feedback-link { color: var(--simple-green); border-block-color: #f0e4c8; font-size: 12px; } +.simple-account-menu > .simple-advanced-link { color: var(--simple-ink); background: var(--simple-warm); border-radius: 14px; } +.simple-account-menu > .simple-advanced-link b { font-size: 11px; } +.simple-account-menu > .simple-advanced-link small { color: var(--simple-muted); font-size: 9px; } +.simple-signout { width: 100%; min-height: 42px; margin-top: 10px; border-radius: 12px; color: #a63c1e; background: transparent; border: 1.5px solid #f0d9cf; font-size: 12px; font-weight: 700; } +.simple-signout:hover { background: #fbe6df; } +.simple-tabs { background: var(--simple-paper); border: 1.5px solid #e8dcc0; box-shadow: 0 14px 38px #4c633326; } +.simple-tabs button { color: #7d6b57; font-size: 11px; } +.simple-tabs button.active { color: #fff8e8; background: var(--simple-green); } +.simple-eyebrow { color: #8a6d3b; } +.finder-copy h1, .action-hero h1 { color: #46312a; font-family: 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: -.015em; line-height: 1; } +.shelf-heading h2, .quick-form h2, .host-card h2, .simple-sheet h2, .food-result-card strong, .compost-loop strong, .delivery-card strong, .gather-card strong, .simple-request-card h3, .food-map-tooltip strong { font-family: 'Baloo 2', 'DM Sans', sans-serif; color: #46312a; letter-spacing: -.005em; } +.finder-search { background: var(--simple-paper); border: 1.5px solid #e8dcc0; border-radius: 16px; } +.finder-search svg { color: #8a6d3b; } +.finder-filters button { color: #5d5348; background: var(--simple-paper); border: 1.5px solid #e8dcc0; } +.finder-filters button.active { color: #fff3dc; background: #52734d; border-color: #3d5a3a; } +.finder-flow, .finder-map, .food-shelf { border-color: var(--simple-line); } +.finder-flow { background: var(--simple-paper); } +.finder-map-note { color: var(--simple-muted); } +.food-result-card { background: var(--simple-paper); border: 1.5px solid var(--simple-line); border-radius: 20px; box-shadow: 0 10px 26px #4c633312; } +.food-result-card.selected { border-color: #e0b95c; box-shadow: 0 10px 28px #cf924526; } +.contribute-hero { background: #eef3dd; } +.gather-hero { background: var(--simple-warm); } +.request-hero { background: #fbe9dd; } +.action-switch { background: #f3e9d2; } +.action-switch button { color: #7d6b57; } +.action-switch button.active { color: var(--simple-ink); background: var(--simple-paper); box-shadow: 0 3px 12px #49312814; } +.quick-form, .delivery-board, .gather-list, .host-card { background: var(--simple-paper); border: 1.5px solid var(--simple-line); border-radius: 22px; } +.simple-primary { color: #fff8e8; background: var(--simple-green); border-radius: 16px; font: 600 15px/1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: .01em; box-shadow: 0 4px 0 var(--simple-green-dark); transition: transform .2s var(--ease-out), box-shadow .2s var(--ease-out); } +.simple-primary:hover:not(:disabled) { background: var(--simple-green); transform: translateY(-1px); box-shadow: 0 5px 0 var(--simple-green-dark); } +.simple-primary:active:not(:disabled) { transform: translateY(1px); box-shadow: 0 2px 0 var(--simple-green-dark); } +.simple-footer { color: var(--simple-muted); border-top: 1.5px solid #f0e4c8; } +.simple-footer a { color: var(--simple-green); } + +/* Guest sheet: same sign-in step, same look */ +.simple-sheet-backdrop { background: #49312880; } +.simple-sheet { color: var(--simple-ink); background: var(--simple-paper); border: 1.5px solid #e8dcc0; border-radius: 26px; box-shadow: 0 24px 70px #49312852; } +.simple-sheet-close { color: #7d6b57; background: var(--simple-warm); } +.simple-sheet > p:not(.simple-eyebrow) { color: var(--simple-muted); font-size: 13.5px; } +.simple-sheet-secondary { color: #55763f; font-size: 13px; font-weight: 700; } +.sheet-auth-copy { color: var(--simple-muted); font-size: 13.5px; } +.sheet-auth label { color: #4a332a; font-size: 13px; } +.sheet-auth input { border: 1.5px solid #e0d3b4; border-radius: 14px; background: var(--simple-paper); color: var(--simple-ink); font-size: 15px; } +.sheet-auth input:focus { border-color: #52734d; box-shadow: 0 0 0 3px #52734d22; } +.sheet-auth .login-submit { border-radius: 16px; background: var(--simple-green); font: 600 15px/1 'Baloo 2', 'DM Sans', sans-serif; box-shadow: 0 4px 0 var(--simple-green-dark); } +.sheet-auth .login-submit:hover:not(:disabled) { background: var(--simple-green); } +.sheet-auth .login-switch { font-size: 12.5px; } + +/* Location dialog inside the finder */ +.simple-app .access-backdrop { background: #49312899; } +.simple-app .access-card { color: var(--simple-ink); background: var(--simple-paper); border: 1.5px solid #e8dcc0; border-radius: 26px; box-shadow: 0 24px 70px #49312852; } +.simple-app .access-card .eyebrow { color: #8a6d3b; } +.simple-app .access-card h2 { color: #46312a; font: 700 27px/1.1 'Baloo 2', 'DM Sans', sans-serif; letter-spacing: -.01em; } +.simple-app .access-card > p:not(.eyebrow) { color: var(--simple-muted); font-size: 14px; } +.simple-app .location-consent-icon { color: #3d5a3a; background: #e3edcc; } +.simple-app .location-privacy { color: #5d5348; background: var(--simple-warm); border-color: #e8dcc0; } +.simple-app .location-privacy svg { color: #52734d; } +.simple-app .location-allow { color: #fff8e8; background: var(--simple-green); border-radius: 16px; font: 600 15px/1 'Baloo 2', 'DM Sans', sans-serif; box-shadow: 0 4px 0 var(--simple-green-dark); } +.simple-app .location-allow:hover { background: var(--simple-green); } +.simple-app .location-skip { color: #2d6b50; background: #fffefa; border: 2px solid #2d6b50; border-radius: 16px; font: 600 14px/1 'Baloo 2', 'DM Sans', sans-serif; } +.simple-app .location-skip:hover { background: #eaf3e8; } + +@media (max-width: 480px) { + .simple-header .yuhm-lockup small, .login-card .yuhm-lockup small { display: none; } + .simple-signin { padding: 0 13px; font-size: 13px; } +} diff --git a/yuhm/src/world/WorldExperience.tsx b/yuhm/src/world/WorldExperience.tsx index 243c1e91..5163b9a7 100644 --- a/yuhm/src/world/WorldExperience.tsx +++ b/yuhm/src/world/WorldExperience.tsx @@ -1,8 +1,11 @@ import { useCallback, useEffect, useMemo, useState } from 'react' -import { Activity, CircleUserRound } from 'lucide-react' +import { Activity, CircleUserRound, LogIn } from 'lucide-react' import { BowlMark } from '../LandingDecor' import { LanguageToggle } from '../i18n' import { AppLink } from '../router' +import { useAuth } from '../AuthProvider' +import { foodDb } from '../lib/foodRepository' +import { getMemberIdentity, signInHref } from '../lib/auth' import { WorldMap, type LatLng } from './WorldMap' import { WorldSheet, type SheetDetent } from './WorldSheet' import { @@ -58,6 +61,8 @@ function readProgress(): MissionProgress { export function WorldExperience() { const w = useWorldText() const mobile = useMobileViewport() + const { member, authReady } = useAuth() + const [accountOpen, setAccountOpen] = useState(false) const [intro, setIntro] = useState(readIntro) const [panel, setPanel] = useState({ kind: 'discover' }) const [progress, setProgress] = useState(readProgress) @@ -232,6 +237,20 @@ export function WorldExperience() { + {authReady && !member && + {w('world.topbar.signIn')} + } + {member &&
+ + {accountOpen &&
+

{w('world.topbar.signedIn', { name: getMemberIdentity(member).email || getMemberIdentity(member).displayName })}

+ {w('world.topbar.finder')} + {w('world.topbar.commandCenter')} + +
} +
}
diff --git a/yuhm/src/world/panels.tsx b/yuhm/src/world/panels.tsx index 26447bf0..30e6f142 100644 --- a/yuhm/src/world/panels.tsx +++ b/yuhm/src/world/panels.tsx @@ -1,6 +1,7 @@ import type { ReactNode } from 'react' import { ArrowLeft, ArrowUpRight, Bike, CalendarClock, Check, HandHeart, Leaf, MapPin, Navigation, Sparkles, Users } from 'lucide-react' import { AppLink } from '../router' +import { signInHref } from '../lib/auth' import { useWorldText } from './worldStrings' import { journeySteps, layerKinds, missionsAtSpot, personById, poolAtSpot, spotById, @@ -177,7 +178,7 @@ export function DiscoverPanel({ progress, onOpen, poolShareTaken, layer = 'all' {w('world.more.contribute')} {w('world.more.gather')} {w('world.more.requests')} - {w('world.more.signIn')} + {w('world.more.signIn')} {w('world.more.advanced')}
diff --git a/yuhm/src/world/world.css b/yuhm/src/world/world.css index 5010ca17..48b24400 100644 --- a/yuhm/src/world/world.css +++ b/yuhm/src/world/world.css @@ -487,3 +487,33 @@ .world-pulse-dot { animation: none; } .wspot-body, .world-mission-row, .world-primary, .world-role, .world-top-button, .world-layers button, .world-pool-card, .world-run-card { transition: none; } } + +/* ---------------- Account in the top bar ---------------- + Sign in is one tap from the top of the world for guests; members + get their initials with a small menu (finder, command center, sign out). */ +.world-signin.world-top-button { color: var(--w-oat); background: var(--w-green); border-color: var(--w-green-deep); text-decoration: none; box-shadow: 0 3px 0 var(--w-green-deep); } +.world-signin.world-top-button:hover { background: var(--w-green-deep); transform: translateY(-1px); } +.world-account { position: relative; } +.world-account-button { padding-left: 7px; } +.world-avatar { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--w-cacao); color: var(--w-oat); font: 700 10px 'DM Mono', monospace; letter-spacing: .04em; } +.world-account-menu { position: absolute; z-index: 40; top: calc(100% + 8px); right: 0; width: min(280px, calc(100vw - 24px)); display: grid; gap: 3px; padding: 12px; background: var(--w-paper); border: 1.5px solid var(--w-line); border-radius: 18px; box-shadow: 0 18px 44px #49312833; } +.world-account-menu p { margin: 0 0 6px; padding: 2px 8px; color: var(--w-muted); font-size: 12px; line-height: 1.45; word-break: break-word; } +.world-account-menu a, .world-account-menu button { display: flex; align-items: center; min-height: 42px; padding: 8px 12px; border: 0; border-radius: 12px; background: transparent; color: var(--w-green-deep); font-weight: 600; font-size: 13.5px; text-decoration: none; text-align: left; } +.world-account-menu a:hover, .world-account-menu button:hover { background: var(--w-oat); } +.world-account-menu button { color: #a63c1e; } +@media (max-width: 759px) { + /* Icon-only pills on phones, except the two that must stay legible: the + Sign in label and a member's initials. */ + .world-signin.world-top-button span, .world-top-button .world-avatar { display: inline-grid; } + .world-account-button > span:last-child { display: none; } + .world-signin.world-top-button { padding: 8px 12px; } + .world-signin.world-top-button span, .world-brand-copy strong { white-space: nowrap; } + .world-topbar { gap: 6px; padding: 6px 10px; } + .world-top-actions { gap: 5px; } + .world-brand-copy strong { font-size: 15px; } +} +@media (max-width: 480px) { + /* The circle name repeats as the panel heading right below; the bowl mark alone is the home button here. */ + .world-brand-copy { display: none; } + .world-brand { padding: 4px; } +} diff --git a/yuhm/src/world/worldStrings.ts b/yuhm/src/world/worldStrings.ts index fe902785..e86b6ab1 100644 --- a/yuhm/src/world/worldStrings.ts +++ b/yuhm/src/world/worldStrings.ts @@ -78,6 +78,12 @@ const en = { 'world.more.gather': 'Gather', 'world.more.requests': 'Requests', 'world.more.signIn': 'Sign in', + 'world.topbar.signIn': 'Sign in', + 'world.topbar.account': 'Your account', + 'world.topbar.signedIn': 'Signed in as {name}', + 'world.topbar.finder': 'Find food', + 'world.topbar.commandCenter': 'Command center', + 'world.topbar.signOut': 'Sign out', 'world.more.advanced': 'Command center', // Spot card @@ -220,6 +226,12 @@ const es: Record = { 'world.more.gather': 'Reunirse', 'world.more.requests': 'Solicitudes', 'world.more.signIn': 'Iniciar sesión', + 'world.topbar.signIn': 'Iniciar sesión', + 'world.topbar.account': 'Tu cuenta', + 'world.topbar.signedIn': 'Sesión iniciada como {name}', + 'world.topbar.finder': 'Buscar comida', + 'world.topbar.commandCenter': 'Centro de mando', + 'world.topbar.signOut': 'Cerrar sesión', 'world.more.advanced': 'Centro de mando', 'world.spot.offers': 'Disponible o necesario', From b3a26eed429361fa8a40ad2f29808c6c0476a8a5 Mon Sep 17 00:00:00 2001 From: koH Date: Tue, 8 Sep 2026 19:55:31 -0500 Subject: [PATCH 04/24] docs(yuhm): detailed handoff for the one-theme / sign-in-at-the-top pass Adds _handoff-2026-09-08-one-theme.md (status, before/after per surface, file-by-file changes, brand tokens, verification, what is still unverified, follow-ups, gotchas, resume steps) and links it from HANDOFF.md and the same-day funnel handoff. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01G2r6hMvjqMaTJ5NrqZw5vz (cherry picked from commit 04a1a4562559a7530247ea22aab653f7b2a73c41) --- yuhm/HANDOFF.md | 2 + yuhm/_handoff-2026-09-08-onboarding-funnel.md | 2 +- yuhm/_handoff-2026-09-08-one-theme.md | 135 ++++++++++++++++++ 3 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 yuhm/_handoff-2026-09-08-one-theme.md diff --git a/yuhm/HANDOFF.md b/yuhm/HANDOFF.md index 6fe72302..067ce6ed 100644 --- a/yuhm/HANDOFF.md +++ b/yuhm/HANDOFF.md @@ -10,6 +10,8 @@ Public-facing product behavior and safety boundaries are maintained in `docs/LIV ## One theme from landing to task, 2026-09-08 (same-day follow-up) +Detailed session handoff for this pass: `_handoff-2026-09-08-one-theme.md` (status, file-by-file changes, tokens, what is still unverified, how to resume). + koH's desktop review: the landing looked right, but clicking Sign in dropped into a different-looking product (sage, Space Grotesk, 11px type), and on the living world at bare `/app/` the only Sign in link sat at the bottom of the docked panel (~2100px down). Fixed as one pass: - **Shared brand lockup.** `src/YuhmBrand.tsx` (bowl mark + Baloo wordmark + tagline) now heads the landing nav, the sign-in card, and the finder header. The landing keeps its scoped `.landing-brand` rules; other surfaces use the unscoped `.yuhm-lockup` rules. diff --git a/yuhm/_handoff-2026-09-08-onboarding-funnel.md b/yuhm/_handoff-2026-09-08-onboarding-funnel.md index 792577aa..5c55a6e1 100644 --- a/yuhm/_handoff-2026-09-08-onboarding-funnel.md +++ b/yuhm/_handoff-2026-09-08-onboarding-funnel.md @@ -48,7 +48,7 @@ Read this file, then `HANDOFF.md` top section. If koH reports the phone test pas ## Same-day follow-up: one theme from landing to task (koH's desktop review) -koH: "it shows a different style theme before you actually login ... confusing with the flow of signing in as you have to go all the way down. lets make sure to streamline our design." Done in the same session; details in `HANDOFF.md` "One theme from landing to task, 2026-09-08". +koH: "it shows a different style theme before you actually login ... confusing with the flow of signing in as you have to go all the way down. lets make sure to streamline our design." Done in the same session; full handoff in `_handoff-2026-09-08-one-theme.md`, summary in `HANDOFF.md` "One theme from landing to task, 2026-09-08". - `src/YuhmBrand.tsx` shared lockup; brand-theme override block at the end of `src/styles.css`; world topbar account control in `src/world/WorldExperience.tsx` + `world.css`. - Sign in is now at the top of the world, the finder, and the dashboard prompt/sidebar, always with `return=` back to the same screen. Members get Sign out in the finder menu and the world menu. diff --git a/yuhm/_handoff-2026-09-08-one-theme.md b/yuhm/_handoff-2026-09-08-one-theme.md new file mode 100644 index 00000000..92163987 --- /dev/null +++ b/yuhm/_handoff-2026-09-08-one-theme.md @@ -0,0 +1,135 @@ +# Handoff — yuhm: one theme from landing to task, Sign in at the top of every surface + +Date: 2026-09-08 (same day as, and directly after, the onboarding funnel pass in `_handoff-2026-09-08-onboarding-funnel.md`) +Branch: `agent/yuhm-network` · Worktree: `handprotocol/yuhm` + +Mission, in koH's words: "look at our current ux with desktop, its kind of confusing as it shows a different style theme before you actually login, the theme before is okay but its kind of confusing with the flow of signing in as you have to go all the way down. lets make sure to streamline our design." + +## STATUS: DONE, COMMITTED, PUSHED, DEPLOYED + +| Item | State | +|---|---| +| Commit | `d6ed1dccf` on `agent/yuhm-network` (19 files, +350 / -41). `main` untouched; yuhm deploys from the CLI, never from `main`. | +| Push | Pushed over HTTPS as cryptokoh to `HEAD:agent/yuhm-network`; `git ls-remote` confirms the remote head is `d6ed1dccf`. Note: pushing to the explicit URL does not update the local `origin/agent/yuhm-network` tracking ref, so `git status -sb` may still say "ahead". Trust `git ls-remote https://github.com/HandProtocol/handprotocol.git agent/yuhm-network`. | +| Deploy | Netlify production deploy `6aa0879864ea332f04fdb3f2` on site `56ee91bf-bf15-472d-8c1c-d6c30af05d6c`, live at https://yuhm.handprotocol.org. | +| Live check | Served CSS contains `.yuhm-lockup`; served JS contains the one-door prompt copy and `mode=login&return=`; Supabase project ref `vconmgerblqbworcqkvr` is baked in. Live screenshots of `/app/?mode=login` (1440×900) and `/app/?mode=anonymous&intent=food` (1366×768) match the local build. | +| Tests | 130 passing across 16 files (was 126). Run with `VITE_SUPABASE_URL= VITE_SUPABASE_ANON_KEY= npx vitest run`. | +| Checks | `npx tsc --noEmit` clean · `npm run build` clean (the 985 kB main-chunk advisory is pre-existing and non-blocking) · `git diff --check` clean. | + +## The problem, as observed on desktop before the pass + +Headless-Chromium screenshots at 1440×900 and 1366×768 confirmed koH's report exactly: + +| Surface | Before | After | +|---|---|---| +| Landing `/` | Warm yuhm brand theme (oat ground, cacao ink, Baloo 2, coral scribble). Two hero doors: Find food near me / Sign in. **Fine, unchanged.** | Unchanged apart from the shared lockup component. | +| Living world `/app/` (default app, also where the landing banner goes) | Warm theme, so it matched the landing. But the topbar had only Pulse and "Your presence" (a sample-world profile). The only **Sign in** link was in "More ways to take part" at the bottom of the docked panel, measured at ~2110px from the top of the panel's scroll. | Green **Sign in** pill in the topbar for guests; initials pill with a small menu (Find food · Command center · Sign out) for members. Bottom link kept, now also return-aware. | +| Sign in `/app/?mode=login` | Different theme entirely: sage `#eef3ec` page, Space Grotesk headline, DM Mono "yuhm /THE OM IN YUM ♥" wordmark, 11–12px labels and buttons. Felt like leaving the product. | Same brand theme as the landing: oat ground with the landing's radial glow, the shared bowl+wordmark lockup, Baloo 2 title, 15px inputs, green Continue with the hero-CTA offset shadow, outlined "Browse as a guest". Fits a 640px-tall viewport. | +| Food finder `/app/?mode=anonymous&intent=food` (where "Find food near me" and a successful sign-in land) | White/sage product theme, Space Grotesk, a black "WX" avatar (WXL-era initials) that opened a settings menu with no visible sign-in. Location dialog on top in the sage theme. | Oat/cacao theme, shared lockup, green **Sign in** pill for guests (return-aware), member initials menu with Sign out. Filters, cards, tabs, action heroes, forms, sheet, and the location dialog re-skinned. | +| Guest sign-in sheet (Contribute → Set up Contributor profile, etc.) | White card, Space Grotesk. | Oat card, Baloo heading, same green Continue as the sign-in page. | +| Coordinator dashboard `/app/?mode=advanced` | Dark-green sidebar tool theme. | **Deliberately unchanged** (tool surface). Guest sidebar card now shows a user icon instead of "WX" and links to sign-in with a return path. | +| Phone food map (MapLab command-bar shell, ≤759px at `intent=food`) | White shell, own look. | **Not re-skinned.** Only its account link now carries a return path. | + +## What changed, file by file + +### New +- `src/YuhmBrand.tsx` — the one brand lockup: `BowlMark` + rounded "yuhm" wordmark + tagline (default "regenerative food network · Austin"), `aria-label="yuhm home"`, links to `/`. Class `yuhm-lockup` plus any `className` passed in. Used by the landing nav (with `className="landing-brand"` so the landing's scoped rules still win there), the sign-in card, and the finder header. + +### Components +- `src/LandingPage.tsx` — nav brand replaced by ``. No visual change on the landing. +- `src/LoginScreen.tsx` — `.login-wordmark` replaced by ``. No logic change. +- `src/SimpleExperience.tsx` — + - `herePath` = current `path` + `?params` from `useRoute()`; every header sign-in link is `signInHref(herePath)` so the person returns to the same screen. + - Header: ``; guests (`authReady && !member`) get `Sign in`; members get the initials button + menu (display name, "Signed in as {email}", Send feedback, Turn on advanced workspace, **Sign out**). The guest account menu and the "WX" fallback are gone; guests reach the advanced workspace from the footer link, as before. + - `signOut()` calls `foodDb?.auth.signOut()`; `AuthProvider`'s `onAuthStateChange` clears `member`. +- `src/world/WorldExperience.tsx` — `useAuth()` added. Topbar: guest `Sign in` pill → `signInHref('/app/?mode=world')`; member pill (`world-avatar` initials + display name) toggles `#world-account-menu` (Find food → `/app/?mode=anonymous&intent=food`, Command center → `/app/?mode=advanced`, Sign out → `foodDb?.auth.signOut()`). +- `src/world/panels.tsx` — the "More ways" Sign in link is now `signInHref('/app/?mode=world')`. +- `src/world/worldStrings.ts` — new keys (EN + ES): `world.topbar.signIn`, `world.topbar.account`, `world.topbar.signedIn` (`{name}`), `world.topbar.finder`, `world.topbar.commandCenter`, `world.topbar.signOut`. +- `src/prompts.tsx` — `AuthPrompt` reads `useRoute()` and builds `herePath`; actions are now one door "Sign in or create an account" (`signInHref(herePath)`) plus "Email me yuhm updates". The separate "Log in" and "Create an account" links were removed because the one-step form already does both. Copy explains it brings you back here. +- `src/DashboardApp.tsx` — guest sidebar card ("Browsing openly · Sign in to coordinate") links to `signInHref(window.location.pathname + window.location.search)`; avatar is a `CircleUserRound` icon instead of "WX". +- `src/map-lab/MapLab.tsx` — the account link (`map-lab-account`) uses `signInHref(...)` with the current location. + +### Logic and strings +- `src/lib/auth.ts` — `getMemberIdentity` initials fallback `'WX'` → `'Y'` (practically unreachable; display name always falls back to "yuhm member"). `signInHref` and `resolveReturnPath` unchanged and now used everywhere. +- `src/i18n.tsx` — `common.signOut` (EN "Sign out" / ES "Cerrar sesión"); `login.continueCopy` shortened to two lines (EN "Your email and a password. New here? That creates your account. Already a member? It signs you in." / ES equivalent). + +### Styles +- `src/styles.css` lines 1579–1708, block titled **"One yuhm from landing to task (2026-09-08)"**. Override-only, appended at the end so equal-specificity rules win; layout rules earlier in the file are untouched. Sub-sections: + - `.yuhm-lockup` base rules (unscoped; the landing's `.food-entry-page .landing-brand …` rules are more specific and keep the landing as it was). + - Sign in: `.login-page` (oat + radial glow), `.login-card` (450px, 26px radius, `#e8dcc0` border), `.login-card h1` Baloo 31px, 15px inputs with `#52734d` focus ring, `.login-submit` / `.login-anonymous` as hero-CTA twins (green filled / green outlined, offset shadows), `.login-switch`, error/success chips. Reduced-motion guard. + - Finder shell: `.simple-app` token redefinition (`--simple-ink #3b2a22`, `--simple-muted #7d6b57`, `--simple-green #2d6b50`, `--simple-green-dark #1f4a37`, `--simple-warm #fff3dc`, new `--simple-line #ecdfc4`, `--simple-paper #fffdf6`; background `#fbf6ea`), translucent oat sticky header, `.simple-signin` pill, member `.simple-account` + menu + `.simple-signout`, tabs, eyebrows, Baloo on every heading selector that used Space Grotesk, search, filters, finder frame borders, result cards, action heroes (`.contribute-hero`, `.gather-hero`, `.request-hero`), action switch, form cards, `.simple-primary`, footer. + - Guest sheet: `.simple-sheet*` and `.sheet-auth*`. + - Location dialog, scoped as `.simple-app .access-card …` so the dashboard's own `AuthPrompt` (same `.access-card` class) keeps the tool theme. + - `@media (max-width: 480px)`: hide the lockup tagline in the finder header and the sign-in card; tighter `.simple-signin`. +- `src/world/world.css` lines 491–519: `.world-signin`, `.world-account`, `.world-avatar`, `.world-account-menu`; phone rules keep the Sign in label and member initials visible while the other topbar pills stay icon-only (`.world-top-button span { display: none }` from the existing ≤759px block), tighten topbar gaps, and hide `.world-brand-copy` under 480px so four controls fit on one line (the circle name repeats as the panel heading directly below). + +### Tests +- `src/AuthFunnel.test.tsx` — `resetHarness()` extracted (also clears the `signOut` mock); new `describe('sign in is one tap from the top of every pre-login surface')` with four tests: world topbar + panel links carry `return=%2Fapp%2F%3Fmode%3Dworld`; finder header pill carries the current path; a member sees the account menu (initial "N" for neighbor@…) and Sign out calls `auth.signOut` once; the dashboard prompt's single door carries `return=…mode%3Dadvanced%26workspace%3Dcommunity` and there is no separate "Create an account" link. +- `src/App.test.tsx` — "keeps advanced coordination behind an explicit display setting" now asserts the guest header shows Sign in and no account menu, and reaches the advanced workspace via the footer "Advanced workspace" link (still sets `yuhm:experience-mode`). "links anonymous visitors from the profile card to sign in" expects `/app/?mode=login&return=%2Fapp%2F%3Fmode%3Dadvanced`. + +### Docs +- `HANDOFF.md` — new top section "One theme from landing to task, 2026-09-08" (links here); `Last updated` bumped; routes table rows for `mode=login` and `signup=1` rewritten; the "Successful login redirects to `/app/`" product decision corrected to the `return=` behaviour. +- `DESIGN.md` — brand-vs-product paragraph updated; Baloo 2 added to Typography as the brand display face. +- `_handoff-2026-09-08-onboarding-funnel.md` — short "same-day follow-up" stub pointing here. + +## Design decisions to keep consistent + +- **Two themes, one rule.** Brand theme for every surface a member or guest meets on the way to a task: landing, world, sign-in, finder, sheets, dialogs inside the finder. Product/tool theme only for the coordinator dashboard (`mode=advanced` / `workspace=`). New public or member-facing surfaces should use the brand tokens below. +- **Brand tokens** (mirror `.world-app` custom properties in `world.css` and the landing v2 block): oat ground `#fbf6ea`, paper `#fffdf6`, warm `#fff3dc`, line `#e8dcc0` / `#ecdfc4`, cacao heading `#46312a`, ink `#3b2a22`, muted `#7d6b57`, eyebrow `#8a6d3b`, garden green `#52734d` (chips/selected), action green `#2d6b50` with `#1f4a37` offset shadow (`box-shadow: 0 4px 0 #1f4a37`), coral error `#a63c1e` on `#fbe6df`. Display: Baloo 2 700–800, near-zero tracking. Body: DM Sans. Eyebrows: DM Mono uppercase. Radii 16–26px. +- **Sign in is a first-class control in the top bar of every pre-login surface**, always built with `signInHref()` so the person returns exactly where they were. Build the path from `useRoute()` where available (`SimpleExperience`, `AuthPrompt`), or `window.location` where the component already uses it (`DashboardApp`, `MapLab`). `resolveReturnPath` only accepts `/app/...`, so foreign URLs fall back to the finder. +- **Guests never see an account menu**, only Sign in. Members see initials + menu; Sign out lives in that menu (finder and world). The dashboard already had its own sign-out. +- **One door.** With the one-step `EmailContinueForm`, never present separate "Log in" and "Create an account" choices again (`AuthPrompt` was the last place). +- **Email + password stays** (product decision; no magic links). `signup=1` only changes autocomplete and the button label. + +## Verification performed + +- Headless Chromium (Playwright from `/home/koh/.claude/skills/gstack/node_modules/playwright/index.mjs`, `chromiumSandbox: false`, `--no-sandbox`, Bash with `dangerouslyDisableSandbox`) against `npx vite preview --port 4173` serving `dist`: + - 1440×900: landing, sign-in, world after intro (topbar and panel bottom), finder with location dialog dismissed, Contribute tab, guest sheet (I can deliver → Set up Contributor profile), dashboard. + - 1366×768 and 1280×640: landing above the fold, sign-in card (scrollHeight 651 at 640px tall; "Browse as a guest" visible). + - 430×932 and 390×844: world topbar on one line with Sign in labelled; sign-in card; phone finder (MapLab shell, unchanged). +- Live host after deploy: served asset names, CSS/JS content checks, and two live screenshots (see Status). +- Test suite, tsc, build, `git diff --check`. + +Screenshot scripts used this session live only in the session scratchpad (not in the repo). To reproduce: build, run `npx vite preview --port 4173 --strictPort`, then a small Playwright script with `chromium.launch({ chromiumSandbox: false, args: ['--no-sandbox'] })`, `newContext({ viewport })`, `page.goto(url, { waitUntil: 'networkidle' })`, `page.screenshot(...)`. For the world after the intro, click the "Skip to the map" button or seed `localStorage['yuhm:world-intro'] = '{"role":"eat"}'`. For the finder without the location dialog, seed `sessionStorage['yuhm:location-choice'] = 'complete'`. + +## NOT verified (be honest about these first) + +1. **Member-state visuals were only exercised in jsdom tests, not screenshotted.** The finder header initials button + menu (with Sign out) and the world topbar initials pill + menu render correctly in tests, but nobody has looked at them in a browser with a real session. First thing after koH signs in on the live site: check both menus at desktop and phone widths. +2. **Live Supabase auth is still unexercised** (carried from the funnel handoff): sign in with a saved account, then create a brand-new account through the same Continue button. The logic assumes `invalid_credentials` for an unknown email and `user_already_exists` on a duplicate signup, with **Confirm email OFF** in the Supabase project. +3. Dashboard guest sidebar card (icon avatar) sits below the fold at 1440×900 and was not screenshotted; the `.avatar` class is `display: grid; place-items: center`, so the icon should centre. +4. New Spanish strings (`world.topbar.*`, `common.signOut`, shortened `login.continueCopy`) were written by me, not reviewed by a Spanish speaker. +5. Reset / recovery / updates screens on the sign-in card share the restyled `.login-card` rules but were not screenshotted this pass. + +## Open follow-ups (koH may want next; none started) + +1. **Phone food map on-theme.** `MapLab` (`src/map-lab/`, own CSS chunk) is the shell phones get at `intent=food`. It still has its white look; re-skin it with the brand tokens if koH wants the phone path to match desktop. +2. **Geolocation dialog non-blocking.** `intent=food` still opens the location consent modal before the map (now on-theme). Highest-leverage funnel item left: show the Austin map immediately and offer "Near me" as a button. +3. **Vestigial `yuhm:experience-mode` writes** (`enableAdvancedMode` in `SimpleExperience`, flags in MapLab/DashboardApp) can be retired; routing no longer reads them (see HANDOFF "Living-map world experience"). +4. **World member menu destinations** are a judgement call (Find food, Command center, Sign out). If a member-shaped default for the world emerges, revisit. +5. Optional cleanup: the old sage `.login-*`, `.simple-*` base rules earlier in `styles.css` are now overridden rather than replaced. Folding the override block into the base rules would shrink the CSS but is a larger, riskier diff; only do it with screenshots at the same five viewports. + +## Ground rules / gotchas + +- **Shared checkout.** Another Claude session mutates the same repo (root docs, `command/`, `clients/`, `threehandshealing/`, untracked 78 MB `yuhm/tsetup.7.1.3.tar.xz`). Stage by explicit path only. Never commit the tarball. +- **Tests vs build env.** A populated `.env.local` flips `foodDbConfigured` and breaks App.test gates → always `VITE_SUPABASE_URL= VITE_SUPABASE_ANON_KEY= npx vitest run`. The build NEEDS `.env.local` (config is baked at build time) → `grep -o vconmgerblqbworcqkvr dist/assets/index-*.js` before any deploy. +- **Deploy** (manual CLI, cryptokoh token; CLI login is zantrra): + ``` + NETLIFY_AUTH_TOKEN=$(python3 -c "import json; cfg=json.load(open('$HOME/.config/netlify/config.json')); print([u['auth']['token'] for uid,u in cfg['users'].items() if uid.startswith('65ff678f')][0])") netlify deploy --prod --site 56ee91bf-bf15-472d-8c1c-d6c30af05d6c --dir dist --message "..." + ``` + Headers/redirects ship from `public/_headers` + `public/_redirects`. +- **Push** (SSH fails; clear the global gh helper or it hands git the zantrra account and 403s): + ``` + git -c credential.helper= -c credential.helper='!f() { echo username=cryptokoh; echo password=$(gh auth token -u cryptokoh); }; f' push https://github.com/HandProtocol/handprotocol.git HEAD:agent/yuhm-network + ``` + This leaves `origin/agent/yuhm-network` stale locally; verify with `git ls-remote` rather than `git status -sb`. +- **CSS override pattern.** The codebase evolves themes by appending override blocks (landing v2, this pass). Equal-specificity rules win by order, so keep new overrides at the end of the file and match the selector shape of the rule you are overriding. Scope shared dialog classes (`.access-card`) under the surface (`.simple-app …`) so the dashboard is not dragged along. +- **World topbar on phones.** The existing `.world-top-button span { display: none }` rule under 759px hides every pill label; any new topbar control needs an explicit exception if its label must stay visible (see `.world-signin` rules). +- **Visual QA.** gstack `/browse` daemon is broken on this machine; drive Playwright directly as described above. Use `devices['iPhone 13']` when you need `pointer: coarse`. +- **Vocabulary and voice.** Reciprocates / Contributors. Never name specific AI models in public copy. No ultracode / Workflow runs (koH, 2026-09-04). + +## Suggested next-session start + +Read this file, then `HANDOFF.md` top two sections. Then: +1. If koH has signed in on the live site: screenshot the finder header and world topbar in the member state (desktop + 390px), fix anything off, and mark item 1 under "NOT verified" as done. +2. If live auth misbehaves: start in `src/lib/auth.ts` `continueWithEmail` and check the Supabase project's auth settings (Confirm email must be OFF). +3. Otherwise pick one follow-up: the phone MapLab re-skin (design continuity) or the non-blocking geolocation dialog (funnel), and do it as its own bounded pass with the same five-viewport screenshot check. From 28edd2dc30fda7303dedf5aad1d719c240bb88ab Mon Sep 17 00:00:00 2001 From: koH Date: Fri, 11 Sep 2026 13:29:23 -0500 Subject: [PATCH 05/24] Add Legacy Care site with cleaned markup and responsive spacing (cherry picked from commit f25dfdc62a99738cb995bd6a2410223ae81829ca) --- clients/legacy-care-llc/.gitignore | 5 + clients/legacy-care-llc/ENGINE_FILES | 41 + clients/legacy-care-llc/HANDOFF.md | 42 + clients/legacy-care-llc/README.md | 130 ++ clients/legacy-care-llc/netlify.toml | 43 + .../netlify/functions/admin-page.mjs | 18 + .../netlify/functions/admin.mjs | 277 ++++ .../netlify/functions/auth.mjs | 129 ++ .../netlify/functions/content.mjs | 27 + .../netlify/functions/lib/admin-page.mjs | 132 ++ .../netlify/functions/lib/blocks.mjs | 180 +++ .../netlify/functions/lib/config.mjs | 76 + .../netlify/functions/lib/content.mjs | 72 + .../netlify/functions/lib/db.mjs | 131 ++ .../netlify/functions/lib/email.mjs | 52 + .../netlify/functions/lib/html.mjs | 43 + .../netlify/functions/lib/http.mjs | 56 + .../netlify/functions/lib/sanitize.mjs | 78 + .../netlify/functions/lib/session.mjs | 64 + .../netlify/functions/lib/site.mjs | 24 + .../netlify/functions/lib/theme.mjs | 115 ++ .../netlify/functions/render.mjs | 36 + clients/legacy-care-llc/package.json | 14 + .../legacy-care-llc/public/admin/admin.css | 142 ++ clients/legacy-care-llc/public/admin/admin.js | 435 ++++++ .../legacy-care-llc/public/assets/site.css | 358 +++++ clients/legacy-care-llc/public/assets/site.js | 9 + clients/legacy-care-llc/public/favicon.svg | Bin 0 -> 47480 bytes clients/legacy-care-llc/public/favicon.webp | Bin 0 -> 47480 bytes clients/legacy-care-llc/public/img/hands.webp | Bin 0 -> 31276 bytes clients/legacy-care-llc/public/img/hero.webp | Bin 0 -> 80310 bytes clients/legacy-care-llc/public/img/logo.webp | Bin 0 -> 88828 bytes clients/legacy-care-llc/public/img/mark.webp | Bin 0 -> 47480 bytes clients/legacy-care-llc/public/img/meal.webp | Bin 0 -> 54272 bytes .../public/img/placeholder/ph-01.svg | 18 + .../public/img/placeholder/ph-02.svg | 15 + .../public/img/placeholder/ph-03.svg | 17 + .../public/img/placeholder/ph-04.svg | 18 + .../public/img/placeholder/ph-05.svg | 18 + .../public/img/placeholder/ph-06.svg | 16 + .../public/img/placeholder/ph-07.svg | 16 + .../public/img/placeholder/ph-08.svg | 17 + .../public/img/placeholder/ph-09.svg | 17 + .../public/img/placeholder/ph-10.svg | 15 + .../public/img/placeholder/ph-11.svg | 14 + .../public/img/placeholder/ph-12.svg | 15 + .../public/img/placeholder/ph-13.svg | 16 + .../public/img/placeholder/ph-14.svg | 17 + .../public/img/placeholder/ph-15.svg | 17 + clients/legacy-care-llc/public/img/walk.webp | Bin 0 -> 61196 bytes clients/legacy-care-llc/public/robots.txt | 4 + .../legacy-care-llc/scripts/gen-migration.mjs | 163 +++ .../scripts/gen-netlify-toml.mjs | 61 + .../scripts/make-placeholders.mjs | 92 ++ .../legacy-care-llc/scripts/render-static.mjs | 22 + clients/legacy-care-llc/site.config.mjs | 145 ++ clients/legacy-care-llc/site/page.mjs | 323 +++++ clients/legacy-care-llc/site/schema.mjs | 1285 +++++++++++++++++ clients/legacy-care-llc/tests/admin.test.mjs | 41 + clients/legacy-care-llc/tests/blocks.test.mjs | 62 + clients/legacy-care-llc/tests/config.test.mjs | 34 + clients/legacy-care-llc/tests/db.test.mjs | 10 + clients/legacy-care-llc/tests/html.test.mjs | 22 + .../legacy-care-llc/tests/migration.test.mjs | 25 + clients/legacy-care-llc/tests/page.test.mjs | 23 + .../legacy-care-llc/tests/sanitize.test.mjs | 42 + .../legacy-care-llc/tests/session.test.mjs | 28 + 67 files changed, 5357 insertions(+) create mode 100644 clients/legacy-care-llc/.gitignore create mode 100644 clients/legacy-care-llc/ENGINE_FILES create mode 100644 clients/legacy-care-llc/HANDOFF.md create mode 100644 clients/legacy-care-llc/README.md create mode 100644 clients/legacy-care-llc/netlify.toml create mode 100644 clients/legacy-care-llc/netlify/functions/admin-page.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/admin.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/auth.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/content.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/admin-page.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/blocks.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/config.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/content.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/db.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/email.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/html.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/http.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/sanitize.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/session.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/site.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/lib/theme.mjs create mode 100644 clients/legacy-care-llc/netlify/functions/render.mjs create mode 100644 clients/legacy-care-llc/package.json create mode 100644 clients/legacy-care-llc/public/admin/admin.css create mode 100644 clients/legacy-care-llc/public/admin/admin.js create mode 100644 clients/legacy-care-llc/public/assets/site.css create mode 100644 clients/legacy-care-llc/public/assets/site.js create mode 100644 clients/legacy-care-llc/public/favicon.svg create mode 100644 clients/legacy-care-llc/public/favicon.webp create mode 100644 clients/legacy-care-llc/public/img/hands.webp create mode 100644 clients/legacy-care-llc/public/img/hero.webp create mode 100644 clients/legacy-care-llc/public/img/logo.webp create mode 100644 clients/legacy-care-llc/public/img/mark.webp create mode 100644 clients/legacy-care-llc/public/img/meal.webp create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-01.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-02.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-03.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-04.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-05.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-06.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-07.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-08.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-09.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-10.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-11.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-12.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-13.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-14.svg create mode 100644 clients/legacy-care-llc/public/img/placeholder/ph-15.svg create mode 100644 clients/legacy-care-llc/public/img/walk.webp create mode 100644 clients/legacy-care-llc/public/robots.txt create mode 100644 clients/legacy-care-llc/scripts/gen-migration.mjs create mode 100644 clients/legacy-care-llc/scripts/gen-netlify-toml.mjs create mode 100644 clients/legacy-care-llc/scripts/make-placeholders.mjs create mode 100644 clients/legacy-care-llc/scripts/render-static.mjs create mode 100644 clients/legacy-care-llc/site.config.mjs create mode 100644 clients/legacy-care-llc/site/page.mjs create mode 100644 clients/legacy-care-llc/site/schema.mjs create mode 100644 clients/legacy-care-llc/tests/admin.test.mjs create mode 100644 clients/legacy-care-llc/tests/blocks.test.mjs create mode 100644 clients/legacy-care-llc/tests/config.test.mjs create mode 100644 clients/legacy-care-llc/tests/db.test.mjs create mode 100644 clients/legacy-care-llc/tests/html.test.mjs create mode 100644 clients/legacy-care-llc/tests/migration.test.mjs create mode 100644 clients/legacy-care-llc/tests/page.test.mjs create mode 100644 clients/legacy-care-llc/tests/sanitize.test.mjs create mode 100644 clients/legacy-care-llc/tests/session.test.mjs diff --git a/clients/legacy-care-llc/.gitignore b/clients/legacy-care-llc/.gitignore new file mode 100644 index 00000000..e3ec87b8 --- /dev/null +++ b/clients/legacy-care-llc/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.netlify/ +dist-preview/ +.env +.env.* diff --git a/clients/legacy-care-llc/ENGINE_FILES b/clients/legacy-care-llc/ENGINE_FILES new file mode 100644 index 00000000..499133d3 --- /dev/null +++ b/clients/legacy-care-llc/ENGINE_FILES @@ -0,0 +1,41 @@ +# Files owned by the engine. `sync-engine.mjs` copies these from +# clients/_template into a client; everything NOT listed is the site pack +# (site.config.mjs, site/, public/assets/, public/favicon.svg, +# public/img/, tests/page.test.mjs, README.md, HANDOFF.md) and is never +# touched by a sync. +# Generated files (netlify.toml, public/img/placeholder/) are regenerated +# from the client's own config after a sync. +netlify/functions/admin-page.mjs +netlify/functions/admin.mjs +netlify/functions/auth.mjs +netlify/functions/content.mjs +netlify/functions/render.mjs +netlify/functions/lib/admin-page.mjs +netlify/functions/lib/blocks.mjs +netlify/functions/lib/config.mjs +netlify/functions/lib/content.mjs +netlify/functions/lib/db.mjs +netlify/functions/lib/email.mjs +netlify/functions/lib/html.mjs +netlify/functions/lib/http.mjs +netlify/functions/lib/sanitize.mjs +netlify/functions/lib/session.mjs +netlify/functions/lib/site.mjs +netlify/functions/lib/theme.mjs +public/admin/admin.css +public/admin/admin.js +public/robots.txt +scripts/gen-migration.mjs +scripts/gen-netlify-toml.mjs +scripts/make-placeholders.mjs +scripts/render-static.mjs +tests/admin.test.mjs +tests/blocks.test.mjs +tests/config.test.mjs +tests/db.test.mjs +tests/html.test.mjs +tests/migration.test.mjs +tests/sanitize.test.mjs +tests/session.test.mjs +.gitignore +ENGINE_FILES diff --git a/clients/legacy-care-llc/HANDOFF.md b/clients/legacy-care-llc/HANDOFF.md new file mode 100644 index 00000000..cfdb1c39 --- /dev/null +++ b/clients/legacy-care-llc/HANDOFF.md @@ -0,0 +1,42 @@ +# Handoff — Legacy Care LLC · 2026-09-11 + +Client site for Legacy Care LLC (owner: cryptokoh@gmail.com,emarie12202007@gmail.com). Server-rendered single page +with an owner CMS at `/admin/` (passwordless email link) for all copy and +photos. Built from `clients/_template` with the `hand-client-site` skill on +2026-09-11. + +**Status:** LIVE at https://legacy-care-llc.netlify.app since 2026-09-11 (provisioned by provision.mjs). + +## Start here (cold session) + +1. Read this file, then `README.md` (architecture, deploy, env vars). +2. Site pack = `site.config.mjs`, `site/schema.mjs`, `site/page.mjs`, + `public/assets/site.css|site.js`. Everything else is engine — do not edit + it here; fix in `clients/_template` and run `sync-engine.mjs legacy-care-llc`. +3. `npm test` runs with no DB. `npm run preview` renders `dist-preview/`. + +## Who can sign in (all `owner` role) + +| Email | Who | +|---|---| +| cryptokoh@gmail.com | Legacy Care owner | +| emarie12202007@gmail.com | Legacy Care owner | +| hand@handprotocol.org | HAND operator inbox, seeded by migration | + +## Where things are + +- **Code:** `clients/legacy-care-llc/` +- **Database:** HAND's shared Supabase project `vconmgerblqbworcqkvr`, tables + `command.legacy_care_llc_editors / login_tokens / content / media / revisions`; + migration `command/supabase/migrations/045_legacy_care_llc.sql` — applied: **yes** (2026-09-11). +- **Storage:** public bucket `legacy-care-llc`. +- **Netlify:** project `legacy-care-llc`, site id `5a3d778d-9067-470c-82fa-330fbefe5d15`, account **cryptokoh**. + Env vars per README. +- **Custom domain:** none yet. + +## Next steps + +1. Design pass on the site pack (theme, copy, layout) → `npm test` + preview. +2. `node .claude/skills/hand-client-site/scripts/provision.mjs legacy-care-llc` (creates + the Netlify site, sets env, applies the migration, deploys, verifies). +3. Owner signs in at `/admin/`, replaces placeholders, publishes. diff --git a/clients/legacy-care-llc/README.md b/clients/legacy-care-llc/README.md new file mode 100644 index 00000000..8959a34e --- /dev/null +++ b/clients/legacy-care-llc/README.md @@ -0,0 +1,130 @@ +# Legacy Care LLC — owner-editable site + +Scaffolded from `clients/_template` (read that README for the architecture; this copy is identical). + +A single-page client site the owner edits themselves: server-rendered from a +database, with a passwordless `/admin/` (one-time email link) for every line +of copy, all photos (upload, reorder, caption, replace in place, featured +image), extra editors, and publish history with one-click restore. Edits go +live instantly. First built for ZeroBlur (2026-09-05); this directory is the +reusable template — **scaffold a client with the `hand-client-site` skill, +do not copy this by hand.** + +## Engine vs site pack + +Two kinds of files live here. The split is the whole point. + +| | Files | Who edits | +|---|---|---| +| **Engine** | `netlify/functions/**`, `public/admin/**` (css + js; the shell is server-rendered), `scripts/**`, `tests/**`, `netlify.toml` (generated), `package.json`, `.gitignore` — listed in `ENGINE_FILES` | Nobody, per client. Fix once in `clients/_template`, run `sync-engine.mjs` to push to every client. | +| **Site pack** | `site.config.mjs` (identity, theme, fonts, logo, nav, seed media), `site/schema.mjs` (what the owner can edit + default copy), `site/page.mjs` (the layout), `public/assets/site.css` + `site.js` (design + effects), `public/favicon.svg`, `public/img/**`, `tests/page.test.mjs` (the layout's own test) | The person building the client's site. This is the only work per client. | + +The engine reaches the pack only through `netlify/functions/lib/site.mjs` +(schema + renderer) and `lib/config.mjs` (config). A pack is therefore exactly +three contracts: + +1. `site.config.mjs` — default export, validated by `normalizeConfig()`. + Required: `slug`, `name`, `theme.{bg,ink,accent}`. See the file's comments. +2. `site/schema.mjs` — `SECTIONS`, `DEFAULT_CONTENT`, `CONTENT_KEY`. + Validated at startup by `assertSections()`. +3. `site/page.mjs` — `renderPage({ content, media, origin }) → html string`. + Compose from `lib/blocks.mjs` (head tags with theme injection, JSON-LD, + CTA resolution, image tags with srcset, lightbox, footer links). + +Two ways to build a client: + +- **Fast path (same layout, new skin + copy):** edit `site.config.mjs` + (theme, fonts, logo, nav labels) and `site/schema.mjs` defaults. No layout + code. ~80 lines of edits. +- **Bespoke design:** keep the schema (or extend it), replace `site/page.mjs` + + `site.css` + `site.js` with the client's design, composed from blocks. + Porting an existing static design is mechanical: hardcoded copy → + `${e(c.section.field)}`, `` → `B.headTags()`, images → `B.img()`. + +## How it works + +``` +public/ static assets (CSS, JS, seed images, /admin/ app) +netlify/functions/ + render.mjs GET / server-renders the page from the DB (CDN-cached, tag = slug) + content.mjs GET /api/content copy + media + editing schema + site identity (public, read-only) + admin-page.mjs GET /admin/ the owner editor, server-rendered in the site's theme (lib/admin-page.mjs + lib/theme.mjs) + auth.mjs /api/auth/* magic-link sign-in → HttpOnly session cookie + admin.mjs /api/admin/* publish copy, media CRUD + order + in-place replace, editors, revisions + lib/config.mjs normalized site.config.mjs + derived names (tables, bucket, cookie, env prefix) + lib/site.mjs the ONLY import path from engine → pack + lib/blocks.mjs renderer building blocks (escaping, meta, CTA, images, lightbox) + lib/sanitize.mjs schema-driven sanitizer (unknown keys dropped, lengths clipped) + lib/db.mjs Supabase REST/Storage + Netlify cache purge; '/{media}' → '/_media' +scripts/ + gen-migration.mjs the Supabase migration from config (tables, RLS, bucket, seed rows) + gen-netlify-toml.mjs netlify.toml from config (Image CDN allow-list) + make-placeholders.mjs placeholder SVGs in the site palette + render-static.mjs dist-preview/ from defaults for local design review (no DB) +tests/ node --test; runs with no network, no DB +``` + +- **Rendering.** `GET /` loads the copy document + media rows and returns + finished HTML (all owner text escaped). The CDN caches it 10 minutes under + the slug tag; every admin write purges it, so edits are live immediately. + DB unreachable → 503 with `Retry-After`; no DB configured → defaults + seed + media (local preview). +- **Editing schema.** `site/schema.mjs` drives the admin forms and the + sanitizer. Every publish writes a revision row; the History tab restores any. +- **Themed editor.** `/admin/` is rendered with the site's palette and fonts + (`config.theme` + `config.fonts`); missing surfaces are derived from + `bg`/`ink`/`accent` (`lib/theme.mjs`), and `config.theme.admin` sets the + editor's feel (radii, label case, weights, primary-button fill). One + brand's editor is pill-and-glow, another's is square gold hairlines. +- **Photos.** Browser resizes to ≤2400 px WebP, PUTs straight to a signed + Supabase upload URL, then registers the row (after a HEAD check). Served via + the Netlify Image CDN with responsive `srcset`. Replace swaps a file while + keeping the slot. Seed rows are ordinary rows pointing at site-relative + files (`/img/...`); "Remove all placeholders" clears the ones flagged. +- **Database.** Shared HAND Supabase project, tables `command._*`, + RLS on with no policies (service role only). Storage bucket = slug. +- **Auth.** Magic link (20 min, single use, 5/hour/editor), 30-day HttpOnly + cookie, same-origin check on writes, no editor enumeration. Owners manage + editors; `_OWNER_EMAILS` auto-provisions owners on first request. + Supabase Auth is deliberately NOT used (no custom SMTP on the project). + +## Local preview + +```bash +npm test # engine tests, no DB +node scripts/render-static.mjs && python3 -m http.server 8787 -d dist-preview +``` + +## Deploy + +Own Netlify site per client, **not git-linked**; deploy from the CLI from +inside the client dir with the **cryptokoh** token: + +```bash +cd clients/ +NETLIFY_AUTH_TOKEN= netlify deploy --prod --build --site --message "…" +``` + +`--skip-functions-cache` when anything under `netlify/` changed. Bump +`assetVersion` in `site.config.mjs` when CSS/JS change (site and admin +assets both carry it). + +Env vars on the site: `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, +`RESEND_API_KEY`, `EMAIL_FROM`, `_SESSION_SECRET`; optional +`_SITE_NAME`, `_OWNER_EMAILS`. Netlify injects +`NETLIFY_PURGE_API_TOKEN` + `SITE_ID`. `` = slug in UPPER_SNAKE +(or `envPrefix` in config). + +## Gotchas (learned on ZeroBlur, do not re-learn) + +- Supabase signed-upload `data.url` must be **string-concatenated** onto + `/storage/v1`; `new URL(path, base)` with a leading-slash path drops the + prefix → 404 "requested path is invalid". +- Any element with its own `display:` rule ignores the `hidden` attribute; + both stylesheets carry a global `[hidden]{display:none!important}`. +- The generic hero headline is word-split into spans, so grepping the literal + sentence in the HTML fails by design. +- Functions are v2 (`export default (req, context)` + `config.path`); the + admin router parses `/api/admin///` by hand. +- New Netlify sites default `built_with_badge_enabled: true`; provision + disables it. Verify the served HTML has no `/.netlify/scripts/hud`. diff --git a/clients/legacy-care-llc/netlify.toml b/clients/legacy-care-llc/netlify.toml new file mode 100644 index 00000000..1d9576e2 --- /dev/null +++ b/clients/legacy-care-llc/netlify.toml @@ -0,0 +1,43 @@ +# Legacy Care LLC — owner-editable site. Deployed as its OWN Netlify site +# (project `legacy-care-llc`), decoupled from the handprotocol repo's git auto-deploy. +# Generated by scripts/gen-netlify-toml.mjs from site.config.mjs. +# +# cd clients/legacy-care-llc && netlify deploy --prod --build --site +# +# This local toml pins the publish dir and functions dir so a deploy from +# inside the monorepo never inherits the root netlify.toml (the HAND site). +[build] + publish = "public" + command = "" + +[functions] + directory = "netlify/functions" + node_bundler = "esbuild" + +# Owner uploads live in Supabase Storage; Netlify Image CDN resizes them. +[images] + remote_images = ["https://vconmgerblqbworcqkvr\\.supabase\\.co/storage/v1/object/public/legacy-care-llc/.*"] + +[[headers]] + for = "/assets/*" + [headers.values] + Cache-Control = "public, max-age=3600, must-revalidate" + +[[headers]] + for = "/img/*" + [headers.values] + Cache-Control = "public, max-age=31536000, immutable" + +[[headers]] + for = "/admin/*" + [headers.values] + X-Robots-Tag = "noindex, nofollow" + Cache-Control = "no-store" + X-Frame-Options = "DENY" + +[[headers]] + for = "/*" + [headers.values] + X-Content-Type-Options = "nosniff" + Referrer-Policy = "strict-origin-when-cross-origin" + Permissions-Policy = "camera=(), microphone=(), geolocation=()" diff --git a/clients/legacy-care-llc/netlify/functions/admin-page.mjs b/clients/legacy-care-llc/netlify/functions/admin-page.mjs new file mode 100644 index 00000000..5667cd5c --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/admin-page.mjs @@ -0,0 +1,18 @@ +// GET /admin/ — the owner editor, server-rendered with the site's theme. +// (No static public/admin/index.html: a static file would win over this +// route and lose the theme injection.) + +import { renderAdminPage } from './lib/admin-page.mjs'; + +export default async () => + new Response(renderAdminPage(), { + status: 200, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Robots-Tag': 'noindex, nofollow', + 'X-Frame-Options': 'DENY', + }, + }); + +export const config = { path: ['/admin', '/admin/', '/admin/index.html'] }; diff --git a/clients/legacy-care-llc/netlify/functions/admin.mjs b/clients/legacy-care-llc/netlify/functions/admin.mjs new file mode 100644 index 00000000..6f1ecd97 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/admin.mjs @@ -0,0 +1,277 @@ +// Editing API (session cookie required; see auth.mjs). +// +// PUT /api/admin/content { content } → publish copy +// GET /api/admin/revisions → last 30 content snapshots +// POST /api/admin/revisions/:id/restore → publish an old snapshot +// POST /api/admin/media/upload-url { name, type, size } → signed upload +// POST /api/admin/media register an uploaded object +// PATCH /api/admin/media/:id { alt, caption, category, featured } +// POST /api/admin/media/:id/replace swap in a new uploaded object, keep the slot +// DELETE /api/admin/media/:id +// PUT /api/admin/media/order { ids } +// POST /api/admin/media/remove-placeholders +// GET /api/admin/editors (owner) list +// POST /api/admin/editors (owner) { email, role } +// DELETE /api/admin/editors/:id (owner) +// +// Every successful write purges the CDN cache for the home page. + +import crypto from 'node:crypto'; +import { createSignedUpload, deleteObjects, objectExists, purgeSiteCache, sb } from './lib/db.mjs'; +import { CONTENT_KEY, sanitize } from './lib/site.mjs'; +import { loadSite, toView } from './lib/content.mjs'; +import { handleError, json, readJson, requireEditor, sameOrigin } from './lib/http.mjs'; + +const ALLOWED_TYPES = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/avif': 'avif', 'image/gif': 'gif' }; +const MAX_UPLOAD_BYTES = 15 * 1024 * 1024; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const UPLOAD_PATH_RE = /^uploads\/[0-9a-f-]{36}\.(jpg|png|webp|avif|gif)$/i; +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; + +function clip(v, max) { + const s = v == null ? '' : String(v).trim(); + return s.length > max ? s.slice(0, max) : s; +} + +async function publishContent(editor, content, kind = 'content') { + const stored = await sb(`/{content}?key=eq.${CONTENT_KEY}&select=value`); + const base = stored && stored[0] ? stored[0].value : undefined; + const clean = sanitize(content, base ? sanitize(base) : undefined); + await sb('/{content}', { + method: 'POST', + prefer: 'resolution=merge-duplicates,return=minimal', + body: { key: CONTENT_KEY, value: clean, updated_at: new Date().toISOString(), updated_by: editor.id }, + }); + await sb('/{revisions}', { + method: 'POST', + prefer: 'return=minimal', + body: { editor_id: editor.id, kind, snapshot: clean }, + }).catch((err) => console.warn('revision insert failed:', err.message)); + return clean; +} + +async function withPurge(result) { + const purge = await purgeSiteCache(); + return { ...result, purged: purge.ok }; +} + +// --- media ----------------------------------------------------------------- + +async function uploadUrl(req) { + const body = await readJson(req, 4096); + const type = String(body.type || ''); + const ext = ALLOWED_TYPES[type]; + if (!ext) return json(400, { ok: false, error: 'Use a JPG, PNG, WebP, AVIF, or GIF image' }); + const size = Number(body.size) || 0; + if (size > MAX_UPLOAD_BYTES) return json(400, { ok: false, error: 'Images must be under 15 MB' }); + const id = crypto.randomUUID(); + const path = `uploads/${id}.${ext}`; + const signed = await createSignedUpload(path); + return json(200, { ok: true, id, path, uploadUrl: signed.uploadUrl, token: signed.token }); +} + +async function registerMedia(req, editor) { + const body = await readJson(req, 8192); + const path = String(body.path || ''); + if (!UPLOAD_PATH_RE.test(path)) return json(400, { ok: false, error: 'Bad path' }); + if (!(await objectExists(path))) return json(400, { ok: false, error: 'The upload did not finish. Try that photo again.' }); + const existing = await sb('/{media}?select=sort&order=sort.desc&limit=1'); + const sort = existing && existing[0] ? Number(existing[0].sort) + 10 : 10; + const rows = await sb('/{media}', { + method: 'POST', + prefer: 'return=representation', + body: { + path, + is_placeholder: false, + alt: clip(body.alt, 160), + caption: clip(body.caption, 160), + category: clip(body.category, 40), + featured: false, + width: Number(body.width) || null, + height: Number(body.height) || null, + bytes: Number(body.bytes) || null, + mime: clip(body.mime, 40) || null, + sort, + }, + }); + const row = rows && rows[0]; + return json(200, await withPurge({ ok: true, media: { ...row, view: toView(row) } })); +} + +// Swap a new photo into an existing slot: position, caption, category, and +// featured flag stay; the old file is removed from storage. +async function replaceMedia(req, id, editor) { + const body = await readJson(req, 8192); + const path = String(body.path || ''); + if (!UPLOAD_PATH_RE.test(path)) return json(400, { ok: false, error: 'Bad path' }); + if (!(await objectExists(path))) return json(400, { ok: false, error: 'The upload did not finish. Try that photo again.' }); + const current = await sb(`/{media}?id=eq.${id}&select=*`); + const row = current && current[0]; + if (!row) return json(404, { ok: false, error: 'Image not found' }); + await snapshotMedia(editor); + const patch = { + path, + is_placeholder: false, + width: Number(body.width) || null, + height: Number(body.height) || null, + bytes: Number(body.bytes) || null, + mime: clip(body.mime, 40) || null, + updated_at: new Date().toISOString(), + }; + if ('alt' in body) patch.alt = clip(body.alt, 160); + const rows = await sb(`/{media}?id=eq.${id}`, { method: 'PATCH', prefer: 'return=representation', body: patch }); + const updated = rows && rows[0]; + if (!row.is_placeholder && !row.path.startsWith('/') && row.path !== path) await deleteObjects([row.path]); + return json(200, await withPurge({ ok: true, media: { ...updated, view: toView(updated) } })); +} + +async function patchMedia(req, id) { + const body = await readJson(req, 8192); + const patch = { updated_at: new Date().toISOString() }; + if ('alt' in body) patch.alt = clip(body.alt, 160); + if ('caption' in body) patch.caption = clip(body.caption, 160); + if ('category' in body) patch.category = clip(body.category, 40); + if ('featured' in body) patch.featured = Boolean(body.featured); + if (patch.featured) { + await sb('/{media}?featured=eq.true', { method: 'PATCH', prefer: 'return=minimal', body: { featured: false } }); + } + const rows = await sb(`/{media}?id=eq.${id}`, { method: 'PATCH', prefer: 'return=representation', body: patch }); + const row = rows && rows[0]; + if (!row) return json(404, { ok: false, error: 'Image not found' }); + return json(200, await withPurge({ ok: true, media: { ...row, view: toView(row) } })); +} + +async function deleteMedia(id) { + const rows = await sb(`/{media}?id=eq.${id}`, { method: 'DELETE', prefer: 'return=representation' }); + const row = rows && rows[0]; + if (!row) return json(404, { ok: false, error: 'Image not found' }); + if (!row.is_placeholder && !row.path.startsWith('/')) await deleteObjects([row.path]); + return json(200, await withPurge({ ok: true })); +} + +async function reorderMedia(req) { + const body = await readJson(req, 64 * 1024); + const ids = Array.isArray(body.ids) ? body.ids.filter((id) => UUID_RE.test(String(id))) : []; + if (!ids.length) return json(400, { ok: false, error: 'No ids' }); + await Promise.all( + ids.map((id, i) => + sb(`/{media}?id=eq.${id}`, { method: 'PATCH', prefer: 'return=minimal', body: { sort: (i + 1) * 10 } }) + ) + ); + return json(200, await withPurge({ ok: true })); +} + +async function removePlaceholders() { + await sb('/{media}?is_placeholder=eq.true', { method: 'DELETE', prefer: 'return=minimal' }); + return json(200, await withPurge({ ok: true })); +} + +async function snapshotMedia(editor) { + const rows = await sb('/{media}?select=*&order=sort.asc'); + await sb('/{revisions}', { + method: 'POST', + prefer: 'return=minimal', + body: { editor_id: editor.id, kind: 'media', snapshot: rows || [] }, + }).catch(() => {}); +} + +// --- editors (owner only) -------------------------------------------------- + +function requireOwner(editor) { + if (editor.role !== 'owner') throw Object.assign(new Error('Owner access required'), { status: 403 }); +} + +async function listEditors() { + const rows = await sb('/{editors}?select=id,email,role,created_at,last_login_at&order=created_at.asc'); + return json(200, { ok: true, editors: rows || [] }); +} + +async function addEditor(req, editor) { + const body = await readJson(req, 4096); + const email = String(body.email || '').trim().toLowerCase(); + const role = body.role === 'owner' ? 'owner' : 'editor'; + if (!EMAIL_RE.test(email) || email.length > 120) return json(400, { ok: false, error: 'Enter a valid email' }); + const existing = await sb(`/{editors}?email=ilike.${encodeURIComponent(email)}&select=id`); + if (existing && existing.length) return json(409, { ok: false, error: 'That email can already sign in' }); + const rows = await sb('/{editors}', { + method: 'POST', + prefer: 'return=representation', + body: { email, role, invited_by: editor.id }, + }); + return json(200, { ok: true, editor: rows && rows[0] }); +} + +async function removeEditor(id, editor) { + if (id === editor.id) return json(400, { ok: false, error: 'You cannot remove yourself' }); + const owners = await sb('/{editors}?role=eq.owner&select=id'); + const target = await sb(`/{editors}?id=eq.${id}&select=id,role`); + if (!target || !target[0]) return json(404, { ok: false, error: 'Not found' }); + if (target[0].role === 'owner' && owners.length <= 1) return json(400, { ok: false, error: 'Keep at least one owner' }); + await sb(`/{editors}?id=eq.${id}`, { method: 'DELETE', prefer: 'return=minimal' }); + return json(200, { ok: true }); +} + +// --- router ---------------------------------------------------------------- + +export default async (req) => { + try { + const editor = await requireEditor(req); + if (req.method !== 'GET' && !sameOrigin(req)) return json(403, { ok: false, error: 'Cross-origin request blocked' }); + const url = new URL(req.url); + const parts = url.pathname.replace(/^\/api\/admin\/?/, '').split('/').filter(Boolean); + const [head, second, third] = parts; + const m = req.method; + + if (head === 'content' && m === 'PUT') { + const body = await readJson(req); + const content = await publishContent(editor, body.content); + return json(200, await withPurge({ ok: true, content })); + } + if (head === 'revisions' && !second && m === 'GET') { + const rows = await sb( + '/{revisions}?kind=eq.content&select=id,created_at,editor_id,editor:{editors}(email)&order=created_at.desc&limit=30' + ); + return json(200, { ok: true, revisions: rows || [] }); + } + if (head === 'revisions' && second && third === 'restore' && m === 'POST') { + const rows = await sb(`/{revisions}?id=eq.${encodeURIComponent(second)}&kind=eq.content&select=snapshot`); + if (!rows || !rows[0]) return json(404, { ok: false, error: 'Revision not found' }); + const content = await publishContent(editor, rows[0].snapshot); + return json(200, await withPurge({ ok: true, content })); + } + + if (head === 'media') { + if (second === 'upload-url' && m === 'POST') return await uploadUrl(req); + if (!second && m === 'POST') return await registerMedia(req, editor); + if (second === 'order' && m === 'PUT') return await reorderMedia(req); + if (second === 'remove-placeholders' && m === 'POST') { + await snapshotMedia(editor); + return await removePlaceholders(); + } + if (second && UUID_RE.test(second) && third === 'replace' && m === 'POST') return await replaceMedia(req, second, editor); + if (second && UUID_RE.test(second) && m === 'PATCH') return await patchMedia(req, second); + if (second && UUID_RE.test(second) && m === 'DELETE') { + await snapshotMedia(editor); + return await deleteMedia(second); + } + } + + if (head === 'editors') { + requireOwner(editor); + if (!second && m === 'GET') return await listEditors(); + if (!second && m === 'POST') return await addEditor(req, editor); + if (second && UUID_RE.test(second) && m === 'DELETE') return await removeEditor(second, editor); + } + + if (head === 'site' && m === 'GET') { + const site = await loadSite(); + return json(200, { ok: true, ...site }); + } + + return json(404, { ok: false, error: 'Unknown endpoint' }); + } catch (err) { + return handleError(err); + } +}; + +export const config = { path: '/api/admin/*' }; diff --git a/clients/legacy-care-llc/netlify/functions/auth.mjs b/clients/legacy-care-llc/netlify/functions/auth.mjs new file mode 100644 index 00000000..431e6a57 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/auth.mjs @@ -0,0 +1,129 @@ +// Owner sign-in: passwordless magic links. +// +// POST /api/auth/request { email } → always { ok:true } (never leaks who can edit) +// POST /api/auth/verify { token } → sets the session cookie +// GET /api/auth/me → { editor } or 401 +// POST /api/auth/logout → clears the cookie +// +// Bootstrap: emails listed in _OWNER_EMAILS (comma-separated) are +// auto-provisioned as owners the first time they request a link, so a new +// client email can be added without touching the database. + +import { sb } from './lib/db.mjs'; +import { config as site, siteEnv, siteName } from './lib/config.mjs'; +import { hashToken, newLoginToken, sessionCookie, signSession } from './lib/session.mjs'; +import { emailConfigured, sendLoginEmail } from './lib/email.mjs'; +import { clientIp, currentEditor, handleError, json, readJson, sameOrigin } from './lib/http.mjs'; + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; +const TOKEN_TTL_MIN = 20; +const MAX_LINKS_PER_HOUR = 5; + +function ownerAllowlist() { + return (siteEnv('OWNER_EMAILS') || '') + .split(',') + .map((s) => s.trim().toLowerCase()) + .filter(Boolean); +} + +async function findEditor(email) { + const rows = await sb(`/{editors}?email=ilike.${encodeURIComponent(email)}&select=id,email,role`); + if (rows && rows[0]) return rows[0]; + if (ownerAllowlist().includes(email.toLowerCase())) { + const created = await sb('/{editors}', { + method: 'POST', + prefer: 'return=representation', + body: { email: email.toLowerCase(), role: 'owner' }, + }); + return created && created[0] ? created[0] : null; + } + return null; +} + +async function requestLink(req) { + const body = await readJson(req, 4096); + const email = String(body.email || '').trim().toLowerCase(); + if (!EMAIL_RE.test(email) || email.length > 120) return json(400, { ok: false, error: 'Enter a valid email' }); + + const editor = await findEditor(email); + // Same response either way so the endpoint cannot be used to enumerate editors. + if (!editor) return json(200, { ok: true, sent: true }); + + const since = new Date(Date.now() - 3600 * 1000).toISOString(); + const recent = await sb( + `/{login_tokens}?editor_id=eq.${editor.id}&created_at=gte.${encodeURIComponent(since)}&select=id` + ); + if (recent && recent.length >= MAX_LINKS_PER_HOUR) return json(200, { ok: true, sent: true }); + + const token = newLoginToken(); + await sb('/{login_tokens}', { + method: 'POST', + prefer: 'return=minimal', + body: { + editor_id: editor.id, + token_hash: hashToken(token), + expires_at: new Date(Date.now() + TOKEN_TTL_MIN * 60 * 1000).toISOString(), + request_ip: clientIp(req) || null, + }, + }); + + const url = new URL(req.url); + const link = `${url.protocol}//${url.host}/admin/?t=${token}`; + if (!emailConfigured()) { + // Local/dev: no sender configured. The link is only ever logged, never returned. + console.log(`[${site.slug} auth] email not configured; sign-in link for ${email}: ${link}`); + return json(200, { ok: true, sent: false, reason: 'email-unconfigured' }); + } + const sent = await sendLoginEmail({ to: editor.email, link, siteName: siteName() }); + if (!sent.ok) console.warn(`[${site.slug} auth] send failed:`, sent.reason); + return json(200, { ok: true, sent: true }); +} + +async function verify(req) { + const body = await readJson(req, 4096); + const token = String(body.token || ''); + if (!/^[A-Za-z0-9_-]{20,100}$/.test(token)) return json(400, { ok: false, error: 'Invalid link' }); + + const rows = await sb( + `/{login_tokens}?token_hash=eq.${hashToken(token)}&select=id,editor_id,expires_at,used_at` + ); + const row = rows && rows[0]; + if (!row || row.used_at || new Date(row.expires_at).getTime() < Date.now()) { + return json(400, { ok: false, error: 'This link has expired or was already used. Request a new one.' }); + } + await sb(`/{login_tokens}?id=eq.${row.id}`, { + method: 'PATCH', + prefer: 'return=minimal', + body: { used_at: new Date().toISOString() }, + }); + await sb(`/{editors}?id=eq.${row.editor_id}`, { + method: 'PATCH', + prefer: 'return=minimal', + body: { last_login_at: new Date().toISOString() }, + }).catch(() => {}); + const editors = await sb(`/{editors}?id=eq.${row.editor_id}&select=id,email,role`); + const editor = editors && editors[0]; + if (!editor) return json(400, { ok: false, error: 'This account no longer exists.' }); + return json(200, { ok: true, editor }, { 'Set-Cookie': sessionCookie(signSession(editor.id)) }); +} + +export default async (req, context) => { + const action = context.params && context.params.action; + try { + if (action === 'me') { + if (req.method !== 'GET') return json(405, { ok: false, error: 'GET only' }); + const editor = await currentEditor(req); + return editor ? json(200, { ok: true, editor }) : json(401, { ok: false, error: 'Not signed in' }); + } + if (req.method !== 'POST') return json(405, { ok: false, error: 'POST only' }); + if (!sameOrigin(req)) return json(403, { ok: false, error: 'Cross-origin request blocked' }); + if (action === 'request') return await requestLink(req); + if (action === 'verify') return await verify(req); + if (action === 'logout') return json(200, { ok: true }, { 'Set-Cookie': sessionCookie('', { clear: true }) }); + return json(404, { ok: false, error: 'Unknown action' }); + } catch (err) { + return handleError(err); + } +}; + +export const config = { path: '/api/auth/:action' }; diff --git a/clients/legacy-care-llc/netlify/functions/content.mjs b/clients/legacy-care-llc/netlify/functions/content.mjs new file mode 100644 index 00000000..dc420b37 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/content.mjs @@ -0,0 +1,27 @@ +// GET /api/content — the current document, media, the editing schema, and +// the site identity (name, logo, theme) the admin brands itself with. Read by +// the admin UI. Safe to expose: it is exactly what the page shows. + +import { loadSite, toView } from './lib/content.mjs'; +import { schemaForClient } from './lib/site.mjs'; +import { json, handleError } from './lib/http.mjs'; + +export default async (req) => { + if (req.method !== 'GET') return json(405, { ok: false, error: 'GET only' }); + try { + const { content, media, source, updated_at, site } = await loadSite(); + return json(200, { + ok: true, + content, + media: media.map((row) => ({ ...row, view: toView(row) })), + schema: schemaForClient(), + site, + source, + updated_at, + }); + } catch (err) { + return handleError(err); + } +}; + +export const config = { path: '/api/content' }; diff --git a/clients/legacy-care-llc/netlify/functions/lib/admin-page.mjs b/clients/legacy-care-llc/netlify/functions/lib/admin-page.mjs new file mode 100644 index 00000000..a53bb1c0 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/admin-page.mjs @@ -0,0 +1,132 @@ +// The owner editor's HTML, server-rendered so the site's theme, fonts, name +// and logo are in the first byte (no flash of a default look) and the asset +// version comes from site.config.mjs. Behaviour lives in public/admin/admin.js, +// styling in public/admin/admin.css (which reads only the injected tokens). + +import { config } from './config.mjs'; +import { escapeHtml as e } from './html.mjs'; +import { adminThemeVars } from './theme.mjs'; + +function fontLinks() { + if (!config.fonts.googleCss) return ''; + return ` + +`; +} + +export function renderAdminPage() { + const name = config.name; + const v = e(config.assetVersion); + const brand = (tag = '') => `
${config.logo}${e(name)}${tag}
`; + return ` + + + + +${e(name)} · Editor + + + +${fontLinks()} + + + + +
+ + + + + + + +
+
+ + +`; +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/blocks.mjs b/clients/legacy-care-llc/netlify/functions/lib/blocks.mjs new file mode 100644 index 00000000..c4827120 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/blocks.mjs @@ -0,0 +1,180 @@ +// Building blocks for site/page.mjs. A renderer composes these so the parts +// that must be right (escaping, image CDN URLs, meta tags, JSON-LD, the CTA +// resolution, the lightbox data) are never re-implemented per client. +// +// Everything here returns strings of HTML. Every value that came from the +// owner is escaped here or by the caller with e(). + +import { config, siteName } from './config.mjs'; +import { e, instagramUrl, jsonForScript, paragraphs, smsHref, telHref } from './html.mjs'; + +export { e, paragraphs, telHref, smsHref, instagramUrl, jsonForScript }; +export { config }; + +// --- theme ----------------------------------------------------------------- + +import { siteThemeVars } from './theme.mjs'; +export { hexToRgb, mix, luminance } from './theme.mjs'; + +// :root custom properties from config.theme + config.fonts. Hex colors also +// get "-rgb: r g b" so CSS can write rgb(var(--accent-rgb) / .3). +export function themeVars() { + return siteThemeVars(); +} + +export function themeStyle() { + return ``; +} + +export function fontLinks() { + if (!config.fonts.googleCss) return ''; + return ` + +`; +} + +// --- head ------------------------------------------------------------------ + +// Everything inside except the renderer's own extras. `origin` is the +// request origin (canonical + og:url); falls back to config.productionUrl. +export function headTags({ content, featured, origin = '', title, description, extra = '' }) { + const base = origin || config.productionUrl; + const t = title || (content.seo && content.seo.title) || (content.brand && content.brand.name) || siteName(); + const d = description || (content.seo && content.seo.description) || ''; + const ogImage = featured ? new URL(featured.full, base).href : ''; + return ` + +${e(t)} + + + + + + +${ogImage ? `` : ''} + + + +${fontLinks()} +${themeStyle()} + +${extra}`; +} + +export function jsonLd(content, origin, featured, overrides = {}) { + const base = origin || config.productionUrl; + const c = content.contact || {}; + const data = { + '@context': 'https://schema.org', + '@type': 'LocalBusiness', + name: content.brand && content.brand.name, + description: content.seo && content.seo.description, + url: `${base}/`, + telephone: c.phone || undefined, + email: c.email || undefined, + image: featured ? new URL(featured.full, base).href : undefined, + sameAs: instagramUrl(c.instagram) || undefined, + ...overrides, + }; + return ``; +} + +// --- calls to action ------------------------------------------------------- + +// Resolves the primary action in priority order: booking link → phone → +// email → in-page anchor. Never null, so a site always has a next step. +export function primaryCta(content, { anchor = '#book', label } = {}) { + const c = content.contact || {}; + const fallback = label || (content.hero && content.hero.cta_primary) || c.cta_label || 'Book now'; + const url = String(c.booking_url || '').trim(); + if (/^https?:\/\//i.test(url)) return { kind: 'book', href: url, label: fallback, external: true }; + const tel = telHref(c.phone); + if (tel) return { kind: 'call', href: tel, label: fallback, external: false }; + if (c.email) return { kind: 'email', href: `mailto:${c.email}`, label: fallback, external: false }; + return { kind: 'anchor', href: anchor, label: fallback, external: false }; +} + +export const ICONS = { + phone: + '', + arrow: + '', + message: + '', + mail: + '', + calendar: + '', +}; + +// A primary button for the resolved CTA. `cls` adds classes; the icon follows the kind. +export function ctaButton(cta, cls = '', { magnetic = true } = {}) { + const icon = cta.kind === 'call' ? ICONS.phone : cta.kind === 'email' ? ICONS.mail : cta.kind === 'book' ? ICONS.calendar : ''; + const ext = cta.external ? ' target="_blank" rel="noopener"' : ''; + return `${icon}${e(cta.label)}`; +} + +// --- images ---------------------------------------------------------------- + +// for a media view (from lib/content.mjs toView). Uploads get srcset via +// the Image CDN; placeholders/site-relative files are served as-is. +export function img(view, { sizes = '100vw', cls = '', eager = false, alt } = {}) { + if (!view) return ''; + const srcset = view.srcset ? ` srcset="${e(view.srcset)}" sizes="${e(sizes)}"` : ''; + const load = eager ? ' fetchpriority="high"' : ' loading="lazy"'; + return ``; +} + +// The lightbox's data (kept out of the markup). site.js reads #site-media. +export function mediaJson(views) { + const data = views.map((m) => ({ src: m.full, alt: m.alt, caption: m.caption, category: m.category })); + return ``; +} + +export function lightboxHtml() { + return ``; +} + +// --- chrome ---------------------------------------------------------------- + +// Word-split headline for per-word reveal animations. +export function words(text, cls = 'w') { + return String(text) + .split(/\s+/) + .filter(Boolean) + .map((w, i) => `${e(w)}`) + .join(' '); +} + +export function logo() { + return config.logo; +} + +// Footer links every HAND-built site carries: the maker credit (unless +// white-label) and the owner sign-in. +export function footerLinks() { + const made = config.madeBy.label + ? `${e(config.madeBy.label)}` + : ''; + return ``; +} + +// Sticky mobile action bar (site.css shows it under 860px once past the hero). +export function callbarHtml(cta) { + return `
${ctaButton(cta, '', { magnetic: false })}
`; +} + +export function siteScript() { + return ``; +} + +export function year() { + return String(new Date().getFullYear()); +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/config.mjs b/clients/legacy-care-llc/netlify/functions/lib/config.mjs new file mode 100644 index 00000000..642bfb5e --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/config.mjs @@ -0,0 +1,76 @@ +// Normalized site config + everything derived from it (table names, bucket, +// cookie, env names). Import THIS in engine code, never site.config.mjs. + +import raw from '../../../site.config.mjs'; + +function must(cond, msg) { + if (!cond) throw new Error(`site.config.mjs: ${msg}`); +} + +export function normalizeConfig(c) { + must(c && typeof c === 'object', 'must export an object'); + must(/^[a-z0-9][a-z0-9-]{1,48}$/.test(c.slug || ''), 'slug must be lowercase [a-z0-9-], 2-49 chars'); + must(c.name && String(c.name).trim(), 'name is required'); + must(c.theme && c.theme.bg && c.theme.ink && c.theme.accent, 'theme needs bg, ink, accent'); + must(c.theme.admin === undefined || (c.theme.admin && typeof c.theme.admin === 'object'), 'theme.admin must be an object of feel tokens'); + const slug = c.slug; + const dbPrefix = slug.replace(/-/g, '_'); + const envPrefix = c.envPrefix || dbPrefix.toUpperCase(); + return { + ...c, + theme: { ...c.theme, admin: c.theme.admin || {} }, + slug, + dbPrefix, + envPrefix, + productionUrl: String(c.productionUrl || `https://${slug}.netlify.app`).replace(/\/$/, ''), + supabase: { projectRef: '', schema: 'command', ...(c.supabase || {}) }, + assetVersion: c.assetVersion || '1', + fonts: { googleCss: '', display: 'system-ui, sans-serif', body: 'system-ui, sans-serif', ...(c.fonts || {}) }, + logo: c.logo || '', + nav: Array.isArray(c.nav) ? c.nav : [], + labels: c.labels || {}, + media: { seed: [], placeholderPalette: [], ...(c.media || {}) }, + madeBy: { label: 'Made by HAND', href: 'https://handprotocol.org', ...(c.madeBy || {}) }, + tables: { + editors: `${dbPrefix}_editors`, + login_tokens: `${dbPrefix}_login_tokens`, + content: `${dbPrefix}_content`, + media: `${dbPrefix}_media`, + revisions: `${dbPrefix}_revisions`, + }, + bucket: slug, + cacheTag: slug, + cookie: `${dbPrefix}_session`, + }; +} + +export const config = normalizeConfig(raw); +export const TABLES = config.tables; +export const BUCKET = config.bucket; + +// Site-scoped env var: env('SESSION_SECRET') → process.env._SESSION_SECRET +export function siteEnv(key) { + return process.env[`${config.envPrefix}_${key}`] || ''; +} + +export function siteName() { + return siteEnv('SITE_NAME') || config.name; +} + +// Seed rows in the shape of a _media row (used with no DB, and by the +// migration generator). +export function seedMedia() { + return config.media.seed.map((m, i) => ({ + id: m.id || `00000000-0000-4000-8000-${String(i + 1).padStart(12, '0')}`, + sort: (i + 1) * 10, + path: m.path, + is_placeholder: Boolean(m.placeholder), + alt: m.alt || '', + caption: m.caption || '', + category: m.category || '', + featured: Boolean(m.featured), + width: m.width || null, + height: m.height || null, + mime: m.mime || (m.path.endsWith('.svg') ? 'image/svg+xml' : m.path.endsWith('.png') ? 'image/png' : m.path.endsWith('.webp') ? 'image/webp' : 'image/jpeg'), + })); +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/content.mjs b/clients/legacy-care-llc/netlify/functions/lib/content.mjs new file mode 100644 index 00000000..da76a633 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/content.mjs @@ -0,0 +1,72 @@ +// Loads the site document + media from Supabase, falling back to defaults so +// the page always renders (even with no database configured, e.g. local +// preview). + +import { config, seedMedia } from './config.mjs'; +import { CONTENT_KEY, DEFAULT_CONTENT, sanitize } from './site.mjs'; +import { dbConfigured, publicObjectUrl, sb } from './db.mjs'; + +export const IMAGE_WIDTHS = [480, 800, 1200, 1600, 2000]; + +export { seedMedia }; + +function imageCdn(url, w) { + return `/.netlify/images?url=${encodeURIComponent(url)}&w=${w}&q=78&fm=webp`; +} + +// Adds the URLs the page needs (src, srcset, full). +export function toView(row) { + const isLocal = row.is_placeholder || row.path.startsWith('/'); + const original = isLocal ? row.path : publicObjectUrl(row.path); + const width = Number(row.width) || 1200; + const height = Number(row.height) || 900; + // SVGs are served as-is. Raster files (uploads, or photos shipped with the + // site under public/img) go through the Image CDN, which also accepts + // site-relative paths. SITE_STATIC_PREVIEW=1 (render-static) has no CDN. + const resizable = !/\.svg$/i.test(row.path) && !process.env.SITE_STATIC_PREVIEW; + const view = { + id: row.id, + alt: row.alt || '', + caption: row.caption || '', + category: row.category || '', + featured: Boolean(row.featured), + is_placeholder: Boolean(row.is_placeholder), + width, + height, + original, + src: original, + srcset: '', + full: original, + }; + if (resizable) { + const widths = IMAGE_WIDTHS.filter((w) => w <= Math.max(width, 480)); + view.src = imageCdn(original, Math.min(1200, Math.max(width, 480))); + view.srcset = widths.map((w) => `${imageCdn(original, w)} ${w}w`).join(', '); + view.full = imageCdn(original, Math.min(2000, Math.max(width, 480))); + } + return view; +} + +export async function loadSite() { + if (!dbConfigured()) { + return { content: sanitize(DEFAULT_CONTENT), media: seedMedia(), source: 'defaults', updated_at: null, site: siteInfo() }; + } + const [rows, mediaRows] = await Promise.all([ + sb(`/{content}?key=eq.${CONTENT_KEY}&select=value,updated_at`), + sb('/{media}?select=*&order=sort.asc,created_at.asc'), + ]); + const content = rows && rows[0] ? sanitize(rows[0].value) : sanitize(DEFAULT_CONTENT); + const media = mediaRows && mediaRows.length ? mediaRows : seedMedia(); + return { + content, + media, + source: rows && rows[0] ? 'db' : 'defaults', + updated_at: rows && rows[0] ? rows[0].updated_at : null, + site: siteInfo(), + }; +} + +// What the admin needs to brand itself. Safe to expose (it is on the page). +export function siteInfo() { + return { slug: config.slug, name: config.name, logo: config.logo, theme: config.theme, assetVersion: config.assetVersion }; +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/db.mjs b/clients/legacy-care-llc/netlify/functions/lib/db.mjs new file mode 100644 index 00000000..3b731463 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/db.mjs @@ -0,0 +1,131 @@ +// Supabase REST + Storage helpers. Service role only; these never run in the +// browser. Table names come from site.config.mjs via ./config.mjs: write +// paths as '/{media}?select=*' and the placeholders resolve to +// '_media'. +// +// Env: SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY + +import { BUCKET, TABLES, config } from './config.mjs'; + +export { BUCKET }; +const SCHEMA = config.supabase.schema; + +function env(name) { + return process.env[name] || ''; +} + +export function supabaseUrl() { + return env('SUPABASE_URL').replace(/\/$/, ''); +} + +export function dbConfigured() { + return Boolean(env('SUPABASE_URL') && env('SUPABASE_SERVICE_ROLE_KEY')); +} + +function authHeaders(extra = {}) { + const key = env('SUPABASE_SERVICE_ROLE_KEY'); + return { apikey: key, Authorization: `Bearer ${key}`, ...extra }; +} + +// '/{media}?x' → '/_media?x'. Unknown names throw so a typo cannot +// silently query the wrong table. +export function resolveTables(path) { + return String(path).replace(/\{(\w+)\}/g, (_, name) => { + if (!TABLES[name]) throw new Error(`db: unknown table placeholder {${name}}`); + return TABLES[name]; + }); +} + +export async function sb(path, { method = 'GET', body, prefer } = {}) { + const headers = authHeaders({ + 'Content-Type': 'application/json', + 'Accept-Profile': SCHEMA, + 'Content-Profile': SCHEMA, + }); + if (prefer) headers.Prefer = prefer; + const res = await fetch(`${supabaseUrl()}/rest/v1${resolveTables(path)}`, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + const err = new Error(`supabase ${method} ${path} → ${res.status}: ${detail.slice(0, 300)}`); + err.status = res.status; + throw err; + } + if (res.status === 204) return null; + return res.json().catch(() => null); +} + +// --- storage ------------------------------------------------------------- + +export function publicObjectUrl(path) { + return `${supabaseUrl()}/storage/v1/object/public/${BUCKET}/${path.split('/').map(encodeURIComponent).join('/')}`; +} + +// Mints a signed upload URL the browser can PUT the file to directly, so big +// photos never pass through the function's 6 MB body limit. +export async function createSignedUpload(path) { + const res = await fetch(`${supabaseUrl()}/storage/v1/object/upload/sign/${BUCKET}/${path}`, { + method: 'POST', + headers: authHeaders({ 'Content-Type': 'application/json' }), + body: '{}', + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + throw new Error(`storage sign ${res.status}: ${detail.slice(0, 200)}`); + } + const data = await res.json(); + // data.url is relative to the storage API root, e.g. + // /object/upload/sign//uploads/x.jpg?token=… — concatenate, do not + // URL-resolve (a leading slash would discard the /storage/v1 prefix). + const url = `${supabaseUrl()}/storage/v1${data.url.startsWith('/') ? '' : '/'}${data.url}`; + const token = new URL(url).searchParams.get('token'); + return { uploadUrl: url, token }; +} + +// True when the object is actually in the bucket (used before registering a +// media row so a failed browser upload never leaves a broken gallery tile). +export async function objectExists(path) { + const res = await fetch(publicObjectUrl(path), { method: 'HEAD' }); + return res.ok; +} + +export async function deleteObjects(paths) { + if (!paths.length) return; + const res = await fetch(`${supabaseUrl()}/storage/v1/object/${BUCKET}`, { + method: 'DELETE', + headers: authHeaders({ 'Content-Type': 'application/json' }), + body: JSON.stringify({ prefixes: paths }), + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + console.warn(`storage delete ${res.status}: ${detail.slice(0, 200)}`); + } +} + +// --- cache purge ----------------------------------------------------------- + +// Netlify injects NETLIFY_PURGE_API_TOKEN + SITE_ID into the functions +// runtime. Best effort: the CDN entry also expires on its own (s-maxage). +export async function purgeSiteCache() { + const token = env('NETLIFY_PURGE_API_TOKEN'); + const siteId = env('SITE_ID'); + if (!token || !siteId) return { ok: false, reason: 'purge-unconfigured' }; + try { + const res = await fetch('https://api.netlify.com/api/v1/purge', { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ site_id: siteId, cache_tags: [config.cacheTag] }), + }); + if (!res.ok) { + console.warn(`purge failed ${res.status}: ${(await res.text().catch(() => '')).slice(0, 200)}`); + return { ok: false, reason: `purge-${res.status}` }; + } + return { ok: true }; + } catch (err) { + console.warn('purge threw:', err && err.message); + return { ok: false, reason: 'purge-network' }; + } +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/email.mjs b/clients/legacy-care-llc/netlify/functions/lib/email.mjs new file mode 100644 index 00000000..c9681d5f --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/email.mjs @@ -0,0 +1,52 @@ +// Magic-link email via Resend. Best effort: returns { ok:false } when the +// sender is not configured instead of throwing. Colors come from the theme. +// +// Env: RESEND_API_KEY, EMAIL_FROM (verified sender, e.g. "Studio ") + +import { config, siteName } from './config.mjs'; +import { escapeHtml } from './html.mjs'; + +export function emailConfigured() { + return Boolean(process.env.RESEND_API_KEY && process.env.EMAIL_FROM); +} + +export function loginEmailHtml({ link, name }) { + const t = config.theme; + const bg = t.bg, card = t['bg-2'] || t.bg, ink = t.ink, muted = t['ink-3'] || t['ink-2'] || t.ink, accent = t.accent, accent2 = t['accent-2'] || t.accent, onAccent = t['on-accent'] || '#ffffff'; + return ` +
+
+

${escapeHtml(name)}

+

Sign in to edit your site

+

Tap the button to open the editor. The link works once and expires in 20 minutes.

+

Open the editor

+

If the button doesn't work, paste this into your browser:
${escapeHtml(link)}

+

Didn't request this? You can ignore it.

+
+
`; +} + +export async function sendLoginEmail({ to, link, siteName: nameOverride }) { + if (!emailConfigured()) return { ok: false, reason: 'email-unconfigured' }; + const name = nameOverride || siteName(); + const subject = `Your ${name} sign-in link`; + const text = `Sign in to edit ${name}:\n\n${link}\n\nThis link works once and expires in 20 minutes. If you didn't request it, ignore this email.`; + const html = loginEmailHtml({ link, name }); + try { + const res = await fetch('https://api.resend.com/emails', { + method: 'POST', + headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ from: process.env.EMAIL_FROM, to, subject, html, text }), + }); + if (!res.ok) { + const body = await res.text().catch(() => ''); + console.warn(`[email] resend ${res.status}: ${body.slice(0, 200)}`); + return { ok: false, reason: `email-${res.status}` }; + } + const data = await res.json().catch(() => ({})); + return { ok: true, id: data.id }; + } catch (err) { + console.warn('[email] resend threw:', err && err.message); + return { ok: false, reason: 'email-network' }; + } +} diff --git a/clients/legacy-care-llc/netlify/functions/lib/html.mjs b/clients/legacy-care-llc/netlify/functions/lib/html.mjs new file mode 100644 index 00000000..f2735fd9 --- /dev/null +++ b/clients/legacy-care-llc/netlify/functions/lib/html.mjs @@ -0,0 +1,43 @@ +// Small HTML helpers shared by the renderer. + +export function escapeHtml(input) { + return String(input == null ? '' : input) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export const e = escapeHtml; + +// Multi-line text → paragraphs (blank line = new paragraph, single newline =
). +export function paragraphs(text, className) { + const cls = className ? ` class="${className}"` : ''; + return String(text || '') + .split(/\n{2,}/) + .map((p) => p.trim()) + .filter(Boolean) + .map((p) => `${escapeHtml(p).replace(/\n/g, '
')}

`) + .join(''); +} + +export function telHref(phone) { + const digits = String(phone || '').replace(/[^\d+]/g, ''); + return digits ? `tel:${digits}` : ''; +} + +export function smsHref(phone) { + const digits = String(phone || '').replace(/[^\d+]/g, ''); + return digits ? `sms:${digits}` : ''; +} + +export function instagramUrl(handle) { + const h = String(handle || '').trim().replace(/^@/, '').replace(/^https?:\/\/(www\.)?instagram\.com\//i, '').replace(/\/$/, ''); + return h ? `https://instagram.com/${encodeURIComponent(h)}` : ''; +} + +export function jsonForScript(value) { + // Safe to embed inside ' }).includes(''), false); +}); diff --git a/clients/legacy-care-llc/tests/migration.test.mjs b/clients/legacy-care-llc/tests/migration.test.mjs new file mode 100644 index 00000000..ef862435 --- /dev/null +++ b/clients/legacy-care-llc/tests/migration.test.mjs @@ -0,0 +1,25 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { migrationSql } from '../scripts/gen-migration.mjs'; +import { config, seedMedia } from '../netlify/functions/lib/config.mjs'; +import { netlifyToml } from '../scripts/gen-netlify-toml.mjs'; + +test('migration creates the five prefixed tables, RLS, bucket, seeds, first owner', () => { + const sql = migrationSql(); + for (const t of Object.values(config.tables)) { + assert.match(sql, new RegExp(`create table if not exists command\\.${t} \\(`)); + assert.match(sql, new RegExp(`alter table command\\.${t} enable row level security`)); + assert.match(sql, new RegExp(`revoke all on command\\.${t} from anon, authenticated`)); + } + assert.match(sql, new RegExp(`'${config.bucket}', '${config.bucket}', true`)); + assert.equal((sql.match(/00000000-0000-4000-8000-/g) || []).length, seedMedia().length); + assert.match(sql, /hand@handprotocol\.org/); + assert.equal(sql.includes('zeroblur'), false); +}); + +test('netlify.toml allow-lists exactly this bucket on the project host', () => { + const toml = netlifyToml(); + assert.match(toml, new RegExp(`storage/v1/object/public/${config.bucket}/`)); + assert.match(toml, /publish = "public"/); + assert.match(toml, /X-Robots-Tag = "noindex, nofollow"/); +}); diff --git a/clients/legacy-care-llc/tests/page.test.mjs b/clients/legacy-care-llc/tests/page.test.mjs new file mode 100644 index 00000000..b4c27324 --- /dev/null +++ b/clients/legacy-care-llc/tests/page.test.mjs @@ -0,0 +1,23 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { seedMedia } from '../netlify/functions/lib/config.mjs'; +import { DEFAULT_CONTENT } from '../site/schema.mjs'; +import { renderPage } from '../site/page.mjs'; + +test('renders Legacy Care with editable copy, bilingual attributes, media, and admin link', () => { + const html = renderPage({ content: DEFAULT_CONTENT, media: seedMedia(), origin: 'https://example.test' }); + assert.match(html, /Legacy Care/); + assert.match(html, /data-es=/); + assert.match(html, /id="main"/); + assert.match(html, /href="\/admin\/"/); + assert.match(html, /application\/ld\+json/); + assert.match(html, /hero\.webp/); +}); + +test('escapes owner copy before rendering it', () => { + const content = structuredClone(DEFAULT_CONTENT); + content.hero.copy_2 = ''; + const html = renderPage({ content, media: seedMedia() }); + assert.equal(html.includes(''), false); + assert.match(html, /<script>alert\(1\)<\/script>/); +}); diff --git a/clients/legacy-care-llc/tests/sanitize.test.mjs b/clients/legacy-care-llc/tests/sanitize.test.mjs new file mode 100644 index 00000000..2420b30e --- /dev/null +++ b/clients/legacy-care-llc/tests/sanitize.test.mjs @@ -0,0 +1,42 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { assertSections, sanitizeContent } from '../netlify/functions/lib/sanitize.mjs'; +import { DEFAULT_CONTENT, SECTIONS } from '../site/schema.mjs'; + +// A fixture schema so these tests do not depend on the site pack's fields. +const FIX = [ + { key: 'brand', label: 'Brand', fields: [{ key: 'name', type: 'text', label: 'Name', max: 10 }, { key: 'on', type: 'toggle', label: 'On' }] }, + { key: 'list', label: 'List', fields: [{ key: 'items', type: 'list', label: 'Items', max: 2, item: [{ key: 'a', type: 'text', label: 'A', max: 5 }, { key: 'b', type: 'textarea', label: 'B', max: 5 }] }] }, +]; +const BASE = { brand: { name: 'Base', on: false }, list: { items: [{ a: 'x', b: 'y' }] } }; + +test('the shipped schema validates and its defaults survive a sanitize round-trip', () => { + assert.doesNotThrow(() => assertSections(SECTIONS)); + const out = sanitizeContent(SECTIONS, DEFAULT_CONTENT, DEFAULT_CONTENT); + for (const s of SECTIONS) for (const f of s.fields) assert.ok(f.key in out[s.key], `${s.key}.${f.key}`); +}); + +test('rejects nested lists and text fields without max', () => { + assert.throws(() => assertSections([{ key: 'a', fields: [{ key: 'x', type: 'text' }] }]), /max/); + assert.throws(() => assertSections([{ key: 'a', fields: [{ key: 'l', type: 'list', max: 2, item: [{ key: 'n', type: 'list', max: 1, item: [] }] }] }]), /nest/); +}); + +test('clips text, drops unknown keys, caps lists, coerces toggles', () => { + const out = sanitizeContent(FIX, { + brand: { name: 'x'.repeat(100), evil: 'dropped', on: 'yes' }, + list: { items: [{ a: '1' }, { a: '2' }, { a: '3' }] }, + bogus: { a: 1 }, + }, BASE); + assert.equal(out.brand.name.length, 10); + assert.equal('evil' in out.brand, false); + assert.equal('bogus' in out, false); + assert.equal(out.brand.on, true); + assert.equal(out.list.items.length, 2); + assert.deepEqual(out.list.items[0], { a: '1', b: '' }); +}); + +test('missing keys fall back to base, empty list rows are dropped', () => { + const out = sanitizeContent(FIX, { list: { items: [{ a: '', b: '' }, { a: '9', b: 'z' }] } }, BASE); + assert.equal(out.brand.name, 'Base'); + assert.deepEqual(out.list.items, [{ a: '9', b: 'z' }]); +}); diff --git a/clients/legacy-care-llc/tests/session.test.mjs b/clients/legacy-care-llc/tests/session.test.mjs new file mode 100644 index 00000000..e5efb0a1 --- /dev/null +++ b/clients/legacy-care-llc/tests/session.test.mjs @@ -0,0 +1,28 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +process.env.SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || 'test-key'; +const { COOKIE, hashToken, newLoginToken, parseCookies, sessionCookie, signSession, verifySession } = await import('../netlify/functions/lib/session.mjs'); + +test('sign/verify round-trips and rejects tampering + expiry', () => { + const t = signSession('editor-1'); + assert.equal(verifySession(t), 'editor-1'); + assert.equal(verifySession(t.slice(0, -2) + 'zz'), null); + assert.equal(verifySession('garbage'), null); + const old = signSession('editor-1', Date.now() - 40 * 24 * 3600 * 1000); + assert.equal(verifySession(old), null); +}); + +test('login tokens are url-safe and hash deterministically', () => { + const tok = newLoginToken(); + assert.match(tok, /^[A-Za-z0-9_-]{40,50}$/); + assert.equal(hashToken(tok), hashToken(tok)); + assert.match(hashToken(tok), /^[0-9a-f]{64}$/); +}); + +test('cookie is HttpOnly, Secure, scoped by site, and clears', () => { + assert.match(COOKIE, /_session$/); + const set = sessionCookie('abc'); + assert.match(set, /HttpOnly; Secure; SameSite=Lax/); + assert.equal(parseCookies(set.split(';')[0])[COOKIE], 'abc'); + assert.match(sessionCookie('', { clear: true }), /Max-Age=0/); +}); From 528b3557681038a57d4f238ff8d82844a1c44ec9 Mon Sep 17 00:00:00 2001 From: koH Date: Fri, 11 Sep 2026 16:48:49 -0500 Subject: [PATCH 06/24] Add editable Legacy Care social and Google review links (cherry picked from commit 96f8ffa7b461165a2419f7e21ab8cd17fa4660f6) --- clients/legacy-care-llc/HANDOFF.md | 12 ++++ .../legacy-care-llc/public/assets/site.css | 15 +++++ clients/legacy-care-llc/site.config.mjs | 2 +- clients/legacy-care-llc/site/page.mjs | 29 +++++++++- clients/legacy-care-llc/site/schema.mjs | 58 +++++++++++++++++++ clients/legacy-care-llc/tests/page.test.mjs | 25 ++++++++ 6 files changed, 138 insertions(+), 3 deletions(-) diff --git a/clients/legacy-care-llc/HANDOFF.md b/clients/legacy-care-llc/HANDOFF.md index cfdb1c39..9a3bcec6 100644 --- a/clients/legacy-care-llc/HANDOFF.md +++ b/clients/legacy-care-llc/HANDOFF.md @@ -7,6 +7,18 @@ photos. Built from `clients/_template` with the `hand-client-site` skill on **Status:** LIVE at https://legacy-care-llc.netlify.app since 2026-09-11 (provisioned by provision.mjs). +## Social links (2026-09-11) + +Facebook, Instagram, and the Google review link appear after the direct contact +options and in the footer. The owner can edit or hide them under **Social & +reviews** in the admin. Missing fields in older stored content receive the +schema defaults; no database migration is needed. Facebook and Instagram also +populate LocalBusiness `sameAs` metadata. The Instagram URL uses the clean +profile address without QR tracking parameters. Asset version: `20260911c`. + +Validation: 32 tests pass; English and Spanish layouts checked at 360, 390, +768, and 1440px with no horizontal overflow and at least 44px link targets. + ## Start here (cold session) 1. Read this file, then `README.md` (architecture, deploy, env vars). diff --git a/clients/legacy-care-llc/public/assets/site.css b/clients/legacy-care-llc/public/assets/site.css index 03b9d64a..dff6bafa 100644 --- a/clients/legacy-care-llc/public/assets/site.css +++ b/clients/legacy-care-llc/public/assets/site.css @@ -356,3 +356,18 @@ .reveal{opacity:1;transform:none;transition:none} .btn,.nav__links a::after{transition:none} } + + /* Quiet secondary links, after the direct contact options. */ + .social{padding-top:1.25rem;border-top:1px solid var(--line)} + .social__heading{font:700 0.95rem/1.4 var(--font-body);letter-spacing:0;color:inherit} + .social__links{display:flex;flex-wrap:wrap;gap:0.25rem 1.25rem;list-style:none;margin-top:0.4rem} + .social__links li{min-width:0} + .social__links a{display:inline-flex;align-items:center;gap:0.35rem;min-height:44px;padding:0.5rem 0;font-size:0.95rem;font-weight:600;line-height:1.4;text-decoration:underline;text-underline-offset:0.2em;text-decoration-thickness:1px;overflow-wrap:anywhere} + .social__links svg{width:1rem;height:1rem;flex:none} + .contact__copy .social{border-color:var(--line-navy);color:var(--on-navy-2)} + .contact__copy .social a{color:var(--on-navy)} + .contact__copy .social a:hover{color:var(--gold)} + .foot__contact{min-width:0} + .foot__contact>a{overflow-wrap:anywhere} + .foot__contact .social{margin-top:0.9rem} + @media (max-width:760px){.foot__contact .social__links{justify-content:center}} diff --git a/clients/legacy-care-llc/site.config.mjs b/clients/legacy-care-llc/site.config.mjs index ddbaf442..b9ae5033 100644 --- a/clients/legacy-care-llc/site.config.mjs +++ b/clients/legacy-care-llc/site.config.mjs @@ -7,7 +7,7 @@ export default { "projectRef": "vconmgerblqbworcqkvr", "schema": "command" }, - "assetVersion": "20260911b", + "assetVersion": "20260911c", "fonts": { "googleCss": "https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600;700;800&family=Allura&display=swap", "display": "'Rubik', system-ui, sans-serif", diff --git a/clients/legacy-care-llc/site/page.mjs b/clients/legacy-care-llc/site/page.mjs index 9d925f1d..5bee3986 100644 --- a/clients/legacy-care-llc/site/page.mjs +++ b/clients/legacy-care-llc/site/page.mjs @@ -5,13 +5,36 @@ import { config } from '../netlify/functions/lib/config.mjs'; export function renderPage({ content, media, origin = '' }) { const c = content; const views = media.map(toView); + const social = c.social || {}; + const httpsUrl = (value) => { + try { + const url = new URL(value); + return url.protocol === 'https:' && !url.username && !url.password ? url.href : ''; + } catch { return ''; } + }; + const profiles = [ + { href: httpsUrl(social.facebook_url), label: 'Facebook' }, + { href: httpsUrl(social.instagram_url), label: 'Instagram' }, + ].filter((link) => link.href); + const reviewUrl = httpsUrl(social.google_review_url); + const socialLinks = (id) => { + if (!profiles.length && !reviewUrl) return ''; + const arrow = ''; + return ``; + }; const image = (name, options = {}) => { if (name === 'mark') return config.logo; const view = views.find((m) => (m.original || m.src || '').toLowerCase().endsWith('/' + name.toLowerCase() + '.webp')) || views.find((m) => (m.original || m.src || '').toLowerCase().includes('/' + name.toLowerCase() + '.')); return B.img(view, { sizes: '100vw', ...options }); }; return `${B.headTags({ content: c, featured: views.find((m) => m.featured), origin, extra: '' })} -${B.jsonLd(c, origin, views.find((m) => m.featured), { telephone: c.contact.phone, email: c.contact.email })} +${B.jsonLd(c, origin, views.find((m) => m.featured), { telephone: c.contact.phone, email: c.contact.email, sameAs: profiles.length ? profiles.map((link) => link.href) : undefined })} @@ -275,6 +298,7 @@ ${B.jsonLd(c, origin, views.find((m) => m.featured), { telephone: c.contact.phon ${B.e(c.contact.copy_6)}
+ ${socialLinks('contact-social-title')}
${image('hero', { eager: true })} @@ -294,11 +318,12 @@ ${B.jsonLd(c, origin, views.find((m) => m.featured), { telephone: c.contact.phon
- ${image('logo')} + ${image('logo', { cls: 'foot__logo', sizes: '150px' })}
${B.e(c.contact.phone)} ${B.e(c.contact.email)} + ${socialLinks('footer-social-title')}
diff --git a/clients/legacy-care-llc/site/schema.mjs b/clients/legacy-care-llc/site/schema.mjs index e555f631..01164ca6 100644 --- a/clients/legacy-care-llc/site/schema.mjs +++ b/clients/legacy-care-llc/site/schema.mjs @@ -1,5 +1,54 @@ export const CONTENT_KEY = 'site'; export const SECTIONS = [ + { + "key": "social", + "label": "Social & reviews", + "help": "Use full HTTPS links. Leave a URL blank to hide it. Links appear in the contact section and footer.", + "fields": [ + { + "key": "facebook_url", + "label": "Facebook page URL", + "type": "text", + "max": 500 + }, + { + "key": "instagram_url", + "label": "Instagram profile URL", + "type": "text", + "max": 500 + }, + { + "key": "google_review_url", + "label": "Google review URL", + "type": "text", + "max": 500 + }, + { + "key": "heading", + "label": "Social links heading (English)", + "type": "text", + "max": 100 + }, + { + "key": "heading_es", + "label": "Social links heading (Spanish)", + "type": "text", + "max": 100 + }, + { + "key": "review_label", + "label": "Google review link (English)", + "type": "text", + "max": 100 + }, + { + "key": "review_label_es", + "label": "Google review link (Spanish)", + "type": "text", + "max": 100 + } + ] + }, { "key": "brand", "label": "Brand & navigation", @@ -1090,6 +1139,15 @@ export const SECTIONS = [ } ]; export const DEFAULT_CONTENT = { + "social": { + "facebook_url": "https://www.facebook.com/share/1Er6RTdG3u/?mibextid=wwXIfr", + "instagram_url": "https://www.instagram.com/legacy_carellc/", + "google_review_url": "https://g.page/r/CcRDkF5piXrHEBI/review", + "heading": "Stay connected", + "heading_es": "Sigamos en contacto", + "review_label": "Leave a Google review", + "review_label_es": "Deje una reseña en Google" + }, "brand": { "name": "Legacy Care LLC", "copy_1": "Skip to content", diff --git a/clients/legacy-care-llc/tests/page.test.mjs b/clients/legacy-care-llc/tests/page.test.mjs index b4c27324..b793ac54 100644 --- a/clients/legacy-care-llc/tests/page.test.mjs +++ b/clients/legacy-care-llc/tests/page.test.mjs @@ -21,3 +21,28 @@ test('escapes owner copy before rendering it', () => { assert.equal(html.includes(''), false); assert.match(html, /<script>alert\(1\)<\/script>/); }); + +test('existing content gains social defaults, with profiles in metadata and reviews kept separate', async () => { + const { sanitize } = await import('../netlify/functions/lib/site.mjs'); + const stored = structuredClone(DEFAULT_CONTENT); + delete stored.social; + const content = sanitize(stored); + const html = renderPage({ content, media: seedMedia(), origin: 'https://example.test' }); + for (const url of Object.values(content.social).filter((value) => value.startsWith('https:'))) { + assert.equal(html.split(`href="${url}"`).length - 1, 2); + } + const metadata = JSON.parse(html.match(/ + diff --git a/yuhm/prototypes/the-mission/mission.css b/yuhm/prototypes/the-mission/mission.css new file mode 100644 index 00000000..db24ad09 --- /dev/null +++ b/yuhm/prototypes/the-mission/mission.css @@ -0,0 +1,440 @@ +/* THE MISSION — UX demo. yuhm's palette, pushed: a drenched garden-green stage, produce-colored + routes, and components shaped like real things (patches, tickets, punch cards, stickers). */ +:root { + --ground: #fbf6ea; --card: #fffdf6; --ink: #3b2922; --ink-soft: #6b564b; --line: #e4d8bd; --rule: #3b2922; + --field: #173f31; --field-hi: #21523f; --field-ink: #fbf3df; --field-soft: #b9d2be; --field-line: rgba(251, 243, 223, .2); + --action: #2d6b50; --action-deep: #1f4a37; --link: #2d6b50; + --tomato: #e2603f; --corn: #f0b429; --mint: #a9c98b; --cacao: #3b2922; + --tomato-tint: #fbe3d9; --corn-tint: #fbedc4; --green-tint: #e4efe1; + --band-dark: #2f211b; --band-dark-ink: #fbf3df; --band-dark-soft: #cdb9a6; + --code-bg: #f1e7d0; + --display: 'Baloo 2', 'Trebuchet MS', system-ui, sans-serif; + --body: 'DM Sans', system-ui, -apple-system, 'Segoe UI', sans-serif; + --label: 'Barlow Condensed', 'Arial Narrow', 'Helvetica Neue', sans-serif; + --hand: 'Caveat', 'Segoe Print', 'Bradley Hand', cursive; + --ease: cubic-bezier(0.16, 1, 0.3, 1); + --gutter: clamp(16px, 4vw, 48px); +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --ground: #1d1511; --card: #2a1e18; --ink: #f6ead6; --ink-soft: #c9b5a3; --line: #47352b; --rule: #f6ead6; + --field: #11281f; --field-hi: #1a3a2d; --link: #86cba7; + --tomato-tint: #4a2a20; --corn-tint: #43371a; --green-tint: #223a2e; --band-dark: #120c09; --code-bg: #33261f; + } +} +:root[data-theme="dark"] { + --ground: #1d1511; --card: #2a1e18; --ink: #f6ead6; --ink-soft: #c9b5a3; --line: #47352b; --rule: #f6ead6; + --field: #11281f; --field-hi: #1a3a2d; --link: #86cba7; + --tomato-tint: #4a2a20; --corn-tint: #43371a; --green-tint: #223a2e; --band-dark: #120c09; --code-bg: #33261f; +} + +*, *::before, *::after { box-sizing: border-box; } +body { background: var(--ground); color: var(--ink); font-family: var(--body); font-size: 16px; line-height: 1.55; } +a { color: var(--link); text-underline-offset: 3px; } +:focus-visible { outline: 3px solid var(--corn); outline-offset: 3px; border-radius: 6px; } +button { font: inherit; color: inherit; cursor: pointer; } +svg.i { flex: none; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +h1, h2, h3, h4 { font-family: var(--display); line-height: 1.04; margin: 0; text-wrap: balance; } +p { margin: 0; } +code { font-family: ui-monospace, 'SFMono-Regular', Menlo, monospace; font-size: .82em; background: var(--code-bg); padding: 1px 5px; border-radius: 5px; overflow-wrap: anywhere; } +.lab { font-family: var(--label); font-weight: 700; font-size: 12.5px; letter-spacing: .09em; text-transform: uppercase; } + +/* One gutter for every band: content sits in the middle column. */ +.field, .plan > section { display: grid; grid-template-columns: minmax(var(--gutter), 1fr) minmax(0, 1160px) minmax(var(--gutter), 1fr); } +.field > *, .plan > section > * { grid-column: 2; min-width: 0; } + +/* ---------- the green field: masthead + stage ---------- */ +.field { + background: radial-gradient(ellipse 60% 46% at 22% 74%, var(--field-hi), transparent 70%), + radial-gradient(circle at 1px 1px, rgba(251, 243, 223, .1) 1px, transparent 1.6px) 0 0 / 22px 22px, var(--field); + color: var(--field-ink); padding-block: 34px 72px; row-gap: 44px; +} +.field a { color: var(--field-ink); } +.field code { background: rgba(0, 0, 0, .28); color: #f6dc9a; } +.mast { display: flex; flex-direction: column; gap: 18px; } +.mast .lab { color: var(--field-soft); } +.title-row { display: flex; align-items: flex-end; gap: clamp(10px, 3vw, 36px); flex-wrap: wrap; } +h1 { font-size: clamp(3.7rem, 13.5vw, 10.5rem); font-weight: 800; line-height: .8; letter-spacing: -.02em; padding-top: .12em; } +h1 em { font-style: normal; color: var(--corn); display: block; } +.mast-patch { transform: rotate(11deg); margin-bottom: clamp(4px, 2vw, 26px); filter: drop-shadow(0 8px 10px rgba(0, 0, 0, .35)); } +.mast-patch svg { width: clamp(104px, 15vw, 176px); height: auto; display: block; } +.mast .lede { max-width: 58ch; font-size: clamp(1.05rem, .95rem + .5vw, 1.3rem); line-height: 1.45; color: var(--field-soft); } +.mast .lede strong { color: var(--field-ink); font-weight: 600; } +.toc { display: flex; flex-wrap: wrap; gap: 4px 20px; padding: 0; margin: 0; list-style: none; font-family: var(--label); font-weight: 600; font-size: 1rem; letter-spacing: .04em; text-transform: uppercase; } +.toc a { text-decoration: none; border-bottom: 2px solid var(--field-line); padding-bottom: 1px; transition: border-color 160ms; } +.toc a:hover { border-color: var(--corn); } + +.stage { display: grid; grid-template-columns: minmax(300px, 414px) minmax(0, 1fr); gap: clamp(28px, 5vw, 72px); align-items: start; } +@media (max-width: 900px) { .stage { grid-template-columns: minmax(0, 1fr); } } + +/* screen rail */ +.director { display: flex; flex-direction: column; gap: 30px; min-width: 0; } +.rail { display: flex; flex-direction: column; gap: 14px; } +.rail-row { display: grid; grid-template-columns: 112px minmax(0, 1fr); align-items: start; gap: 10px; } +.rail-row > .lab { color: var(--corn); padding-top: 8px; } +.rail-row ol { list-style: none; margin: 0; padding: 0; display: flex; } +.rail-row li { flex: 0 0 20%; min-width: 0; position: relative; } +.rail-row li::before { content: ''; position: absolute; top: 16px; left: 0; right: 0; height: 2px; background: var(--field-line); } +.rail-row li:first-child::before { left: 50%; } +.rail-row li:last-child::before { right: 50%; } +.rail-row button { position: relative; width: 100%; background: none; border: 0; padding: 0 2px; display: flex; flex-direction: column; align-items: center; gap: 6px; color: var(--field-soft); font-size: .78rem; line-height: 1.2; text-align: center; } +.rail-row button b { width: 34px; height: 34px; border-radius: 50%; display: grid; place-items: center; font-family: var(--display); font-size: 1rem; background: var(--field); border: 2px solid var(--field-line); color: var(--field-ink); transition: transform 220ms var(--ease), background 220ms, border-color 220ms; } +.rail-row button:hover b { border-color: var(--corn); } +.rail-row button[aria-current="step"] { color: var(--field-ink); font-weight: 600; } +.rail-row button[aria-current="step"] b { background: var(--corn); border-color: var(--corn); color: var(--cacao); transform: scale(1.18); } +.rail-row li.seen button:not([aria-current]) b { background: var(--field-hi); border-color: var(--field-soft); } +@media (max-width: 560px) { .rail-row { grid-template-columns: 1fr; gap: 6px; } .rail-row > .lab { padding-top: 0; } } + +.notes { display: flex; flex-direction: column; gap: 16px; } +.notes .lab { color: var(--field-soft); } +.notes h2 { font-size: clamp(1.9rem, 1.4rem + 2vw, 3rem); font-weight: 800; } +.notes > p { max-width: 60ch; font-size: 1.05rem; color: #e6efe0; } +.notes dl { margin: 6px 0 0; display: grid; grid-template-columns: 104px 1fr; gap: 0; } +.notes dt, .notes dd { border-top: 1px solid var(--field-line); padding-block: 12px; margin: 0; } +.notes dt { font-family: var(--label); font-weight: 700; font-size: 13px; letter-spacing: .09em; text-transform: uppercase; color: var(--corn); padding-top: 15px; } +.notes dd { font-size: .96rem; max-width: 58ch; color: #e6efe0; } +@media (max-width: 520px) { .notes dl { grid-template-columns: 1fr; } .notes dd { border-top: 0; padding-top: 0; } .notes dt { padding-bottom: 4px; } } +.nav-row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 4px; } +.nav-row button { border: 2px solid var(--field-line); background: transparent; color: var(--field-ink); border-radius: 14px; padding: 10px 18px; font-family: var(--display); font-weight: 700; font-size: 1.05rem; display: flex; align-items: center; gap: 8px; transition: transform 140ms var(--ease), box-shadow 140ms var(--ease); } +.nav-row button.primary { background: var(--corn); border-color: var(--corn); color: var(--cacao); box-shadow: 0 4px 0 #a97a0c; } +.nav-row button.primary:active { transform: translateY(3px); box-shadow: 0 1px 0 #a97a0c; } +.nav-row button[disabled] { opacity: .35; cursor: not-allowed; } + +/* ---------- device ---------- */ +.device { position: relative; width: 100%; max-width: 414px; margin-inline: auto; padding: 11px; border-radius: 56px; background: #17100c; box-shadow: inset 0 0 0 2px #46352b, 0 50px 70px -36px rgba(0, 0, 0, .7), 0 22px 30px -20px rgba(0, 0, 0, .55); } +.device::before { content: ''; position: absolute; top: 23px; left: 50%; translate: -50% 0; width: 92px; height: 26px; border-radius: 99px; background: #17100c; z-index: 6; } +.phone { + /* The phone depicts the product, which is a light surface: pin the tokens. */ + --ground: #fbf6ea; --card: #fffdf6; --ink: #3b2922; --ink-soft: #6b564b; --line: #e4d8bd; + --action: #2d6b50; --action-deep: #1f4a37; --link: #2d6b50; --green-tint: #e4efe1; + --tomato-tint: #fbe3d9; --corn-tint: #fbedc4; --code-bg: #f1e7d0; + --rc: #b79ac6; --rt: #efe6f4; + height: 772px; border-radius: 46px; overflow: hidden; position: relative; + display: flex; flex-direction: column; background: var(--ground); color: var(--ink); +} +.phone::after { content: ''; position: absolute; bottom: 7px; left: 50%; translate: -50% 0; width: 124px; height: 4px; border-radius: 99px; background: rgba(59, 41, 34, .32); z-index: 6; pointer-events: none; } +.sb { flex: none; height: 48px; padding: 8px 28px 0; display: flex; align-items: center; justify-content: space-between; font-weight: 700; font-size: 13.5px; background: var(--card); } +.sb.wa { background: #1f4a37; color: #fff; } +.sb-r { display: flex; align-items: center; gap: 6px; } +.p-top { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 20px 12px; background: var(--card); border-bottom: 1px solid var(--line); } +.lockup { font-family: var(--display); font-weight: 800; font-size: 1.4rem; line-height: 1; color: #4a332a; display: flex; align-items: baseline; gap: 5px; } +.lockup .heart { color: var(--tomato); font-size: .72em; } +.tag { font-family: var(--label); font-weight: 700; font-size: 11.5px; letter-spacing: .1em; text-transform: uppercase; padding: 2px 8px; border-radius: 4px; background: var(--corn); color: var(--cacao); white-space: nowrap; transform: rotate(-2deg); display: inline-block; } +.p-body { flex: 1; overflow-y: auto; padding: 20px 20px 10px; display: flex; flex-direction: column; gap: 16px; scrollbar-width: none; } +/* A tall screen scrolls. Without this, children with overflow: hidden (lists, tickets) get squashed instead. */ +.p-body > * { flex-shrink: 0; } +.phone[data-enter="1"] .p-body > * { animation: enter 420ms var(--ease) both; } +.phone[data-enter="1"] .p-body > *:nth-child(2) { animation-delay: 40ms; } +.phone[data-enter="1"] .p-body > *:nth-child(3) { animation-delay: 80ms; } +.phone[data-enter="1"] .p-body > *:nth-child(n+4) { animation-delay: 120ms; } +@keyframes enter { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } } +.p-body > h2 { font-size: 1.85rem; font-weight: 800; } +.p-body > h2.big { font-size: 2.5rem; line-height: .95; } +.p-body p.sub { color: var(--ink-soft); font-size: .96rem; } +.p-foot { flex: none; padding: 12px 20px 26px; display: flex; flex-direction: column; gap: 10px; } +.kick { font-family: var(--label); font-weight: 700; font-size: 12.5px; letter-spacing: .09em; text-transform: uppercase; color: var(--ink-soft); } + +.p-btn { display: flex; align-items: center; justify-content: center; gap: 9px; width: 100%; border: 0; border-radius: 18px; padding: 14px 18px; min-height: 54px; font-family: var(--display); font-weight: 700; font-size: 1.18rem; background: var(--action); color: #fff; box-shadow: 0 5px 0 var(--action-deep); transition: transform 140ms var(--ease), box-shadow 140ms var(--ease), filter 140ms; } +.p-btn:hover { filter: brightness(1.06); } +.p-btn:active { transform: translateY(4px); box-shadow: 0 1px 0 var(--action-deep); } +.p-btn.quiet { background: var(--card); color: var(--ink); box-shadow: 0 5px 0 #d5c7a6; border: 2px solid var(--ink); } +.p-btn.quiet:active { box-shadow: 0 1px 0 #d5c7a6; } +.p-btn[disabled] { opacity: .4; cursor: not-allowed; filter: none; } +.p-link { background: none; border: 0; padding: 6px; color: var(--link); text-decoration: underline; text-underline-offset: 3px; font-size: .93rem; align-self: center; } +.seeds { display: inline-flex; align-items: center; gap: 4px; font-family: var(--display); font-weight: 800; font-size: 1rem; line-height: 1; color: var(--cacao); background: var(--corn); border-radius: 99px; padding: 5px 10px 4px 8px; white-space: nowrap; } +.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; } + +/* landing hero inside the phone */ +.hero-art { position: relative; height: 118px; margin: -4px -20px 0; overflow: hidden; } +.hero-art svg { position: absolute; inset: 0; width: 100%; height: 100%; } + +/* join trail */ +.trail { list-style: none; margin: 0; padding: 0; display: flex; font-family: var(--label); font-weight: 700; font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-soft); } +.trail li { flex: 1; position: relative; padding-top: 18px; text-align: center; } +.trail li::before { content: ''; position: absolute; top: 5px; left: -50%; right: 50%; height: 4px; background: var(--line); border-radius: 9px; } +.trail li:first-child::before { display: none; } +.trail li::after { content: ''; position: absolute; top: 0; left: 50%; translate: -50% 0; width: 14px; height: 14px; border-radius: 50%; background: var(--card); border: 3px solid var(--line); } +.trail li.on { color: var(--ink); } +.trail li.on::before { background: var(--action); } +.trail li.on::after { background: var(--action); border-color: var(--action); } +.trail li.now::after { background: var(--corn); border-color: var(--ink); } + +/* route sticker tiles */ +.routes { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 12px; padding: 4px 2px; } +.route { position: relative; text-align: left; background: var(--c); color: var(--cacao); border: 4px solid #fffdf6; border-radius: 22px; padding: 12px 12px 13px; display: flex; flex-direction: column; gap: 3px; transform: rotate(var(--tilt)); box-shadow: 0 2px 0 rgba(59, 41, 34, .22), 0 12px 16px -12px rgba(59, 41, 34, .55); transition: transform 260ms var(--ease), box-shadow 260ms var(--ease); } +.route:hover { transform: rotate(0deg) translateY(-3px); } +.route strong { font-family: var(--display); font-weight: 800; font-size: 1.3rem; line-height: 1; margin-top: 2px; } +.route small { font-size: .8rem; line-height: 1.25; } +.route[aria-checked="true"] { transform: rotate(0deg) scale(1.04); box-shadow: 0 0 0 3px var(--cacao), 0 14px 18px -12px rgba(59, 41, 34, .6); z-index: 1; } +.route .tick { position: absolute; top: -10px; right: -8px; width: 30px; height: 30px; border-radius: 50%; background: var(--cacao); color: #fffdf6; display: grid; place-items: center; animation: thunk 360ms var(--ease) both; } + +.opts { display: flex; flex-wrap: wrap; gap: 9px; } +.opt { border: 2px solid var(--ink); background: var(--card); border-radius: 14px; padding: 10px 14px; font-weight: 500; font-size: .96rem; box-shadow: 0 3px 0 var(--ink); transition: transform 120ms var(--ease), box-shadow 120ms var(--ease), background 160ms; display: inline-flex; align-items: center; gap: 6px; } +.opt[aria-pressed="true"] { background: var(--rc); transform: translateY(3px); box-shadow: 0 0 0 var(--ink); font-weight: 700; } +.bite-q { background: var(--rt); border-radius: 22px; padding: 16px; display: flex; flex-direction: column; gap: 14px; } +.bite-q h2 { font-size: 1.55rem; font-weight: 800; } + +/* patches (stamps) */ +.patch { display: block; } +.patch-t { font-family: var(--label); font-weight: 700; font-size: 11px; letter-spacing: 1.6px; fill: #3b2922; text-transform: uppercase; } +.stamped { animation: thunk 520ms var(--ease) both; filter: drop-shadow(0 6px 0 rgba(59, 41, 34, .16)); } +@keyframes thunk { from { transform: scale(1.7) rotate(-14deg); opacity: 0; } 55% { opacity: 1; } to { transform: scale(1) rotate(-6deg); opacity: 1; } } +.route .tick { animation-name: tick; } +@keyframes tick { from { transform: scale(0); } to { transform: scale(1); } } +.cele { display: flex; flex-direction: column; gap: 12px; text-align: center; align-items: center; position: relative; padding-top: 4px; } +.cele h2 { font-size: 2.3rem; font-weight: 800; line-height: .95; } +.burst { position: absolute; top: 70px; left: 50%; width: 0; height: 0; pointer-events: none; } +.burst i { position: absolute; width: 10px; height: 10px; border-radius: 50% 0 50% 50%; background: var(--corn); animation: fly 1000ms var(--ease) both; } +.burst i:nth-child(odd) { background: var(--tomato); } +.burst i:nth-child(3n) { background: var(--mint); } +@keyframes fly { from { transform: translate(0, 0) scale(.3); opacity: 1; } to { transform: translate(var(--x), var(--y)) scale(1) rotate(220deg); opacity: 0; } } +.count { font-family: var(--display); font-weight: 800; font-size: 3.2rem; line-height: .9; font-variant-numeric: tabular-nums; display: flex; align-items: center; gap: 6px; } +.count small { font-family: var(--label); font-size: 14px; letter-spacing: .09em; text-transform: uppercase; color: var(--ink-soft); align-self: flex-end; padding-bottom: 5px; } + +/* save + fields */ +.keep { background: var(--rt); border-radius: 20px; padding: 12px 14px; display: flex; align-items: center; gap: 12px; } +.keep svg.patch { flex: none; transform: rotate(-8deg); } +.keep b { font-family: var(--display); font-size: 1.1rem; line-height: 1.1; display: block; } +.keep span { font-size: .86rem; color: var(--ink-soft); } +.field-in { display: flex; flex-direction: column; gap: 6px; font-weight: 600; font-size: .86rem; } +.field-in input { font: inherit; font-weight: 400; font-size: 16px; color: var(--ink); background: var(--card); border: 2px solid var(--ink); border-radius: 14px; padding: 13px 14px; } +.field-in input::placeholder { color: #a08f80; } + +/* opt-in */ +.cadence { display: grid; grid-template-columns: repeat(3, 1fr); gap: 9px; } +.cadence button { border: 2px solid var(--ink); background: var(--card); border-radius: 16px; padding: 12px 6px 10px; display: flex; flex-direction: column; align-items: center; gap: 5px; box-shadow: 0 4px 0 var(--ink); transition: transform 120ms var(--ease), box-shadow 120ms var(--ease), background 160ms; } +.cadence .pips { display: flex; gap: 4px; height: 14px; align-items: center; } +.cadence .pips i { width: 12px; height: 12px; border-radius: 50%; background: var(--ink); } +.cadence strong { font-family: var(--display); font-size: 1.05rem; line-height: 1; } +.cadence small { font-size: .74rem; color: var(--ink-soft); } +.cadence button[aria-pressed="true"] { background: var(--corn); transform: translateY(4px); box-shadow: 0 0 0 var(--ink); } +.group { background: var(--card); border: 2px solid var(--ink); border-radius: 18px; overflow: hidden; } +.group > * + * { border-top: 1px solid var(--line); } +.group h3 { font-size: 1.05rem; padding: 12px 14px 0; border: 0; } +.switch-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; font-weight: 600; font-size: .95rem; padding: 11px 14px; } +.switch-row small { display: block; font-weight: 400; color: var(--ink-soft); font-size: .8rem; } +.switch { flex: none; width: 50px; height: 30px; border-radius: 99px; border: 2px solid var(--ink); background: var(--card); position: relative; transition: background 200ms; } +.switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 20px; height: 20px; border-radius: 50%; background: var(--ink); transition: transform 240ms var(--ease); } +.switch[aria-checked="true"] { background: var(--action); } +.switch[aria-checked="true"]::after { transform: translateX(20px); background: #fff; } +.switch[disabled] { opacity: .55; cursor: default; } +.pledge { list-style: none; margin: 0; padding: 14px; display: flex; flex-direction: column; gap: 9px; font-size: .9rem; background: var(--green-tint); border-radius: 18px; } +.pledge li { display: flex; gap: 9px; align-items: flex-start; } +.pledge li svg { color: var(--action); margin-top: 2px; } +.mission-mark { font-family: var(--display); font-weight: 800; font-size: 3rem; line-height: .82; letter-spacing: -.01em; } +.mission-mark span { color: var(--tomato); display: block; } + +/* board */ +.passport { background: var(--card); border: 2px solid var(--ink); border-radius: 22px; padding: 14px; display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; align-items: center; position: relative; } +.passport::before { content: ''; position: absolute; inset: 5px; border: 1.5px dashed #cdbf9f; border-radius: 16px; pointer-events: none; } +.lvl { grid-row: span 2; display: flex; flex-direction: column; align-items: center; gap: 2px; } +.lvl b { font-family: var(--display); font-size: 1rem; line-height: 1; } +.lvl small { font-size: .68rem; color: var(--ink-soft); } +.pp-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; } +.pp-head h3 { font-size: 1.2rem; } +.punch { display: flex; gap: 5px; list-style: none; margin: 0; padding: 0; } +.punch li { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 3px; font-family: var(--label); font-weight: 700; font-size: 11px; color: var(--ink-soft); } +.punch i { width: 100%; max-width: 28px; aspect-ratio: 1; border-radius: 50%; border: 2px solid #cdbf9f; display: grid; place-items: center; color: #fff; font-style: normal; } +.punch li.on i { background: var(--action); border-color: var(--action); } +.punch li.now i { border: 2px dashed var(--ink); background: var(--corn-tint); } +.goal { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; border-top: 1.5px dashed #cdbf9f; padding-top: 9px; margin-top: 3px; font-size: .88rem; } +.goal .pips { display: flex; gap: 5px; } +.goal .pips i { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--ink); } +.goal .pips i.on { background: var(--ink); } +.free { width: 100%; text-align: left; display: flex; align-items: center; gap: 12px; border: 2px solid var(--ink); border-radius: 18px; padding: 12px 14px; background: var(--card); box-shadow: 0 4px 0 var(--ink); transition: transform 140ms var(--ease), box-shadow 140ms var(--ease), background 220ms, color 220ms; } +.free b { font-family: var(--display); font-size: 1.1rem; line-height: 1.1; display: block; } +.free small { display: block; font-size: .8rem; line-height: 1.3; color: var(--ink-soft); } +.free .knob { flex: none; width: 40px; height: 40px; border-radius: 50%; background: var(--ink); color: var(--card); display: grid; place-items: center; position: relative; } +.free[aria-checked="true"] { background: var(--action); color: #fff; transform: translateY(4px); box-shadow: 0 0 0 var(--ink); border-color: var(--action-deep); } +.free[aria-checked="true"] small { color: #d5ead9; } +.free[aria-checked="true"] .knob { background: #fff; color: var(--action); } +.free[aria-checked="true"] .knob::after { content: ''; position: absolute; inset: 0; border-radius: 50%; border: 2px solid #fff; animation: radar 1.6s ease-out infinite; } +@keyframes radar { from { transform: scale(1); opacity: .9; } to { transform: scale(2.1); opacity: 0; } } +.shelf { display: flex; flex-direction: column; gap: 9px; } +.shelf > .kick { display: flex; justify-content: space-between; } +.list { background: var(--card); border-radius: 18px; border: 1px solid var(--line); overflow: hidden; } +.list > * + * { border-top: 1px solid var(--line); } +.item { width: 100%; background: none; border: 0; text-align: left; display: flex; align-items: center; gap: 11px; padding: 11px 12px; font-size: .92rem; font-weight: 500; transition: background 160ms; } +button.item:hover { background: var(--corn-tint); } +.item > span:nth-child(2) { flex: 1; min-width: 0; } +.item small { display: block; font-weight: 400; color: var(--ink-soft); font-size: .78rem; } +.item .dot { flex: none; width: 34px; height: 34px; border-radius: 12px; background: var(--rt); display: grid; place-items: center; } +.item.done { color: var(--ink-soft); } +.item.done > span:nth-child(2) { text-decoration: line-through; } +.item.done .dot { background: var(--action); color: #fff; } +.cal { flex: none; width: 40px; border-radius: 10px; overflow: hidden; border: 1.5px solid var(--ink); text-align: center; background: var(--card); } +.cal em { display: block; font-style: normal; font-family: var(--label); font-weight: 700; font-size: 10.5px; letter-spacing: .08em; text-transform: uppercase; background: var(--tomato); color: #fff; line-height: 1.5; } +.cal b { display: block; font-family: var(--display); font-size: 1.1rem; line-height: 1.35; } +.circle { background: var(--field, #173f31); color: #fbf3df; border-radius: 20px; padding: 14px; display: flex; flex-direction: column; gap: 9px; } +.phone .circle { background: #173f31; } +.circle p { font-size: .86rem; color: #cfe2d2; } +.crates { height: 16px; border-radius: 99px; background: rgba(255, 255, 255, .16); overflow: hidden; } +.crates span { display: block; height: 100%; border-radius: 99px; background: repeating-linear-gradient(-45deg, #f0b429 0 8px, #f6c955 8px 16px); } +.searching { display: flex; align-items: center; gap: 10px; font-size: .92rem; padding: 16px; border-radius: 18px; border: 2px dashed #cdbf9f; color: var(--ink-soft); } +.quiet-note { padding: 14px 16px; border-radius: 18px; background: var(--green-tint); font-size: .92rem; } + +/* ticket */ +.ticket-wrap { filter: drop-shadow(0 3px 0 rgba(59, 41, 34, .2)) drop-shadow(0 14px 14px rgba(59, 41, 34, .16)); display: block; width: 100%; border: 0; padding: 0; background: none; text-align: left; transition: transform 240ms var(--ease); } +button.ticket-wrap:hover { transform: translateY(-3px) rotate(-.6deg); } +.ticket { --stub: 76px; background: var(--card); border-radius: 20px; overflow: hidden; + -webkit-mask: radial-gradient(circle 11px at 0 calc(100% - var(--stub)), #0000 97%, #000) left / 51% 100% no-repeat, radial-gradient(circle 11px at 100% calc(100% - var(--stub)), #0000 97%, #000) right / 51% 100% no-repeat; + mask: radial-gradient(circle 11px at 0 calc(100% - var(--stub)), #0000 97%, #000) left / 51% 100% no-repeat, radial-gradient(circle 11px at 100% calc(100% - var(--stub)), #0000 97%, #000) right / 51% 100% no-repeat; } +.tk-head { background: var(--rc); color: var(--cacao); padding: 14px 16px 13px; display: flex; flex-direction: column; gap: 4px; } +.tk-head h2, .tk-head h3 { font-size: 1.5rem; font-weight: 800; line-height: 1; } +.tk-head .row { align-items: center; } +.tk-facts { margin: 0; padding: 14px 16px; display: grid; grid-template-columns: 1fr 1fr; gap: 12px 14px; } +.tk-facts div { display: flex; flex-direction: column; gap: 1px; min-width: 0; } +.tk-facts dt { display: flex; align-items: center; gap: 5px; font-family: var(--label); font-weight: 700; font-size: 11.5px; letter-spacing: .09em; text-transform: uppercase; color: var(--ink-soft); } +.tk-facts dd { margin: 0; font-weight: 600; font-size: .93rem; line-height: 1.3; } +.tk-stub { height: var(--stub); border-top: 2px dashed #cdbf9f; margin-inline: 14px; padding-inline: 2px; display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.tk-stub div { display: flex; flex-direction: column; } +.tk-stub .lab { font-size: 11px; color: var(--ink-soft); } +.tk-stub b { font-family: var(--display); font-weight: 800; font-size: 1.7rem; line-height: 1; font-variant-numeric: tabular-nums; } +.ticket.compact { --stub: 50px; } +.ticket.compact .tk-head h3 { font-size: 1.25rem; } +.ticket.compact .tk-stub b { font-size: 1.05rem; } +.lockline { display: flex; gap: 9px; align-items: flex-start; font-size: .88rem; color: var(--ink-soft); } +.lockline svg { margin-top: 2px; color: var(--ink); } + +/* active mission */ +.steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } +.steps li { display: grid; grid-template-columns: 34px 1fr; gap: 12px; padding-bottom: 16px; position: relative; } +.steps li::before { content: ''; position: absolute; left: 14px; top: 30px; bottom: -2px; width: 6px; border-radius: 9px; background: var(--line); } +.steps li:last-child::before { display: none; } +.steps li.past::before { background: var(--action); } +.steps .node { width: 34px; height: 34px; border-radius: 50%; border: 3px solid var(--line); background: var(--card); display: grid; place-items: center; font-family: var(--display); font-weight: 800; font-size: .95rem; color: var(--ink-soft); z-index: 1; } +.steps li.past .node { background: var(--action); border-color: var(--action); color: #fff; } +.steps li.live .node { border-color: var(--ink); background: var(--rc); color: var(--cacao); box-shadow: 0 0 0 5px var(--rt); } +.steps h4 { margin: 5px 0 2px; font-size: 1.12rem; } +.steps li:not(.live):not(.past) h4 { color: var(--ink-soft); font-weight: 600; } +.steps p { font-size: .88rem; color: var(--ink-soft); } +.steps li.live .body { background: var(--card); border: 2px solid var(--ink); border-radius: 18px; padding: 8px 12px 12px; margin-top: -4px; } +.cks { display: flex; flex-direction: column; gap: 7px; margin-top: 10px; } +.ck { width: 100%; text-align: left; display: flex; align-items: center; gap: 10px; padding: 10px 11px; border-radius: 13px; border: 2px solid var(--line); background: var(--ground); font-weight: 500; font-size: .92rem; transition: background 160ms, border-color 160ms; } +.ck .box { flex: none; width: 24px; height: 24px; border-radius: 8px; border: 2px solid var(--ink); display: grid; place-items: center; color: transparent; background: var(--card); } +.ck[aria-pressed="true"] { background: var(--green-tint); border-color: var(--action); } +.ck[aria-pressed="true"] .box { background: var(--action); border-color: var(--action); color: #fff; } + +/* done */ +.ringrow { display: flex; align-items: center; gap: 14px; text-align: left; width: 100%; background: var(--card); border: 2px solid var(--ink); border-radius: 20px; padding: 12px 14px; } +.ringrow b { font-family: var(--display); font-size: 1.2rem; line-height: 1.1; display: block; } +.ringrow span { font-size: .85rem; color: var(--ink-soft); } +.thanks { position: relative; margin: 8px 6px 0; background: #fff8d9; color: #3b2922; padding: 20px 18px 14px; transform: rotate(-1.6deg); box-shadow: 0 10px 16px -10px rgba(59, 41, 34, .5); font-family: var(--hand); font-weight: 600; font-size: 1.5rem; line-height: 1.12; text-align: left; } +.thanks::before { content: ''; position: absolute; top: -11px; left: 50%; translate: -50% 0; width: 84px; height: 24px; background: rgba(169, 201, 139, .75); transform: rotate(2deg); } +.thanks cite { display: block; font-family: var(--body); font-style: normal; font-weight: 500; font-size: .76rem; color: #6b564b; margin-top: 8px; } +.loop { display: flex; align-items: center; gap: 12px; background: var(--green-tint); border-radius: 18px; padding: 12px 14px; text-align: left; } +.loop h3 { font-size: 1.05rem; } +.loop p { font-size: .84rem; color: var(--ink-soft); } + +/* email */ +.segs { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; background: #eadfc4; border-radius: 14px; padding: 4px; gap: 2px; } +.segs button { border: 0; background: none; border-radius: 11px; padding: 8px 4px; font-weight: 600; font-size: .8rem; color: var(--ink-soft); transition: background 180ms, color 180ms; } +.segs button[aria-selected="true"] { background: var(--card); color: var(--ink); box-shadow: 0 1px 3px rgba(59, 41, 34, .22); } +.mail { background: #fff; border-radius: 18px; overflow: hidden; font-size: .92rem; color: #33251f; box-shadow: 0 2px 0 rgba(59, 41, 34, .14), 0 14px 22px -16px rgba(59, 41, 34, .5); } +.mail header { padding: 14px; display: grid; grid-template-columns: 40px 1fr auto; gap: 2px 10px; align-items: center; border-bottom: 1px solid #efe6d2; } +.mail .av { grid-row: span 2; width: 40px; height: 40px; border-radius: 50%; background: #173f31; color: #fbf3df; display: grid; place-items: center; font-family: var(--display); font-weight: 800; font-size: 1.2rem; } +.mail header b { font-size: .92rem; } +.mail header time { font-size: .74rem; color: #8a786c; } +.mail header span { grid-column: 2 / -1; font-size: .78rem; color: #7d6a5f; } +.mail h3 { font-size: 1.3rem; padding: 14px 14px 0; } +.mail .m-body { padding: 10px 14px 16px; display: flex; flex-direction: column; gap: 10px; } +.mail .m-btns { display: flex; flex-wrap: wrap; gap: 8px; } +.mail .m-btns span { border-radius: 12px; padding: 10px 16px; font-family: var(--display); font-weight: 700; background: #2d6b50; color: #fff; box-shadow: 0 3px 0 #1f4a37; } +.mail .m-btns span.alt { background: #fbf6ea; color: #3b2922; box-shadow: 0 3px 0 #d5c7a6; } +.mail footer { padding: 11px 14px; font-size: .74rem; color: #8a786c; background: #faf5e8; } + +/* whatsapp */ +.wa-head { flex: none; display: flex; align-items: center; gap: 10px; padding: 4px 16px 12px; background: #1f4a37; color: #fff; } +.wa-head .av { width: 38px; height: 38px; border-radius: 50%; background: #fbf6ea; color: #4a332a; display: grid; place-items: center; font-family: var(--display); font-weight: 800; font-size: 1.2rem; } +.wa-head b { display: block; line-height: 1.2; } +.wa-head small { display: block; opacity: .8; font-size: .74rem; } +.wa-log { flex: 1; overflow-y: auto; padding: 14px 12px; display: flex; flex-direction: column; gap: 8px; scrollbar-width: none; background: radial-gradient(circle at 2px 2px, rgba(59, 41, 34, .06) 1.5px, transparent 2px) 0 0 / 20px 20px, #efe6d3; } +.msg { max-width: 84%; padding: 8px 11px; border-radius: 14px; font-size: .9rem; line-height: 1.4; background: #fff; color: #33251f; align-self: flex-start; border-top-left-radius: 4px; box-shadow: 0 1px 1px rgba(0, 0, 0, .1); animation: enter 300ms var(--ease) both; } +.msg.me { align-self: flex-end; background: #d6ecd0; border-radius: 14px; border-top-right-radius: 4px; } +.msg .qr { display: flex; flex-direction: column; margin-top: 8px; } +.msg .qr button { border: 0; border-top: 1px solid #ece3d2; background: none; padding: 8px 0 5px; color: #1f6f9c; font-weight: 600; font-size: .92rem; } +.msg.typing { display: flex; gap: 4px; padding: 12px; } +.msg.typing i { width: 7px; height: 7px; border-radius: 50%; background: #a39486; animation: blink 1.1s infinite both; } +.msg.typing i:nth-child(2) { animation-delay: .18s; } .msg.typing i:nth-child(3) { animation-delay: .36s; } +@keyframes blink { 0%, 80%, 100% { opacity: .3; } 40% { opacity: 1; } } +.wa-suggest { flex: none; display: flex; gap: 6px; overflow-x: auto; padding: 9px 12px 4px; background: #f6efe0; scrollbar-width: none; } +.wa-suggest button { flex: none; border: 1.5px solid #cdbf9f; background: #fffdf6; border-radius: 99px; padding: 7px 12px; font-size: .84rem; font-weight: 500; } +.wa-bar { flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 12px 24px; background: #f6efe0; } +.wa-bar span { flex: 1; background: #fff; border-radius: 99px; padding: 9px 14px; font-size: .88rem; color: #a39486; } +.wa-bar i { width: 38px; height: 38px; border-radius: 50%; background: #1f4a37; color: #fff; display: grid; place-items: center; } + +.banner { background: var(--tomato-tint); border-radius: 16px; padding: 11px 13px; font-size: .88rem; display: flex; gap: 9px; align-items: flex-start; } +.pause-tile { display: flex; flex-direction: column; gap: 10px; padding: 14px; } +.pause-tile p { font-size: .88rem; color: var(--ink-soft); } +.danger { color: #a63a1f; } + +/* ---------- plan ---------- */ +.plan { display: flex; flex-direction: column; gap: clamp(64px, 8vw, 110px); padding-block: clamp(56px, 7vw, 96px) 0; } +.plan > section { row-gap: 22px; scroll-margin-top: 24px; } +.plan > section > p, .plan > section > ul:not([class]), .plan > section > ol:not([class]) { max-width: 68ch; } +.plan ul:not([class]) { margin: 0; padding-left: 1.15em; display: flex; flex-direction: column; gap: 8px; } +.plan ul:not([class]) li::marker { color: var(--tomato); } +.plan .eyebrow { justify-self: start; font-family: var(--label); font-weight: 700; font-size: 14px; letter-spacing: .1em; text-transform: uppercase; background: var(--corn); color: var(--cacao); padding: 2px 11px; border-radius: 4px; transform: rotate(-1.6deg); margin-bottom: -4px; } +.plan h2 { font-size: clamp(2.1rem, 1.4rem + 3vw, 3.7rem); font-weight: 800; line-height: .95; letter-spacing: -.01em; max-width: 18ch; } +.plan h3 { font-size: 1.45rem; font-weight: 700; margin-top: 14px; } + +#rules { background: var(--band-dark); color: var(--band-dark-ink); padding-block: clamp(56px, 7vw, 92px); margin-top: calc(-1 * clamp(56px, 7vw, 96px)); } +#rules .eyebrow { background: var(--tomato); color: #fff; } +.rules { list-style: none; padding: 0; margin: 10px 0 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 34px clamp(28px, 5vw, 72px); } +.rules li { display: grid; grid-template-columns: 22px 1fr; gap: 6px 12px; align-content: start; } +.rules li::before { content: ''; width: 18px; height: 18px; border-radius: 50%; background: var(--dot, var(--corn)); margin-top: 7px; } +.rules li:nth-child(1) { --dot: #f08a6c; } .rules li:nth-child(2) { --dot: #8cc084; } .rules li:nth-child(3) { --dot: #f5c451; } +.rules li:nth-child(4) { --dot: #b79ac6; } .rules li:nth-child(5) { --dot: #f3a552; } +.rules b { font-family: var(--display); font-weight: 800; font-size: clamp(1.4rem, 1.2rem + .8vw, 1.85rem); line-height: 1.05; } +.rules span { grid-column: 2; font-size: .98rem; color: var(--band-dark-soft); max-width: 46ch; } + +.table-scroll { overflow-x: auto; } +table { border-collapse: collapse; width: 100%; font-size: .92rem; min-width: 660px; border-top: 3px solid var(--rule); } +th { font-family: var(--label); font-weight: 700; font-size: 13px; letter-spacing: .09em; text-transform: uppercase; text-align: left; padding: 10px 16px 9px 0; border-bottom: 1px solid var(--rule); white-space: nowrap; } +td { padding: 13px 16px 13px 0; border-bottom: 1px solid var(--line); vertical-align: top; } +td:first-child { font-family: var(--display); font-weight: 700; font-size: 1.05rem; line-height: 1.2; min-width: 8ch; } +td:first-child code { font-size: .8rem; font-weight: 400; } +tbody tr { transition: background 140ms; } +tbody tr:hover { background: color-mix(in srgb, var(--corn) 12%, transparent); } +td.no { color: var(--ink-soft); } +td.no:not(:empty)::before { content: '✕'; color: var(--tomato); font-weight: 700; margin-right: 7px; } +.two { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 30px clamp(28px, 4vw, 56px); } +.two > div { border-top: 3px solid var(--rule); padding-top: 4px; display: flex; flex-direction: column; gap: 10px; } +.two h3 { margin-top: 8px; } +.diagram { overflow-x: auto; border: 2px solid var(--rule); border-radius: 22px; background: var(--card); padding: 18px; } +.callout { background: var(--corn-tint); border-radius: 22px; padding: 20px 22px; max-width: 74ch; font-size: 1.02rem; position: relative; } +.callout b:first-child { display: block; font-family: var(--display); font-weight: 800; font-size: 1.4rem; line-height: 1.1; margin-bottom: 6px; } +.callout.warn { background: var(--tomato-tint); } +.phases { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; counter-reset: ph -1; } +.phases li { counter-increment: ph; display: grid; grid-template-columns: clamp(56px, 8vw, 96px) 1fr; gap: 0 18px; padding-bottom: 30px; position: relative; } +.phases li::before { content: counter(ph); width: clamp(48px, 6vw, 68px); aspect-ratio: 1; border-radius: 50%; display: grid; place-items: center; background: var(--ink); color: var(--ground); font-family: var(--display); font-weight: 800; font-size: clamp(1.4rem, 1rem + 1.4vw, 2.1rem); z-index: 1; } +.phases li:nth-child(2)::before { background: #8cc084; color: var(--cacao); } .phases li:nth-child(3)::before { background: #f5c451; color: var(--cacao); } +.phases li:nth-child(4)::before { background: #b79ac6; color: var(--cacao); } .phases li:nth-child(5)::before { background: #f3a552; color: var(--cacao); } +.phases li::after { content: ''; position: absolute; top: 8px; bottom: -8px; left: calc(clamp(48px, 6vw, 68px) / 2 - 2px); width: 4px; background: var(--line); } +.phases li:last-child::after { display: none; } +.phases li > div { display: flex; flex-direction: column; gap: 6px; max-width: 70ch; padding-top: 8px; } +.phases h3 { margin: 0; } +.phases small { color: var(--ink-soft); font-size: .95rem; } +.phases small b { color: var(--ink); } + +#decisions { background: var(--corn); color: var(--cacao); padding-block: clamp(56px, 7vw, 92px); } +#decisions .eyebrow { background: var(--cacao); color: var(--corn); } +#decisions code { background: rgba(59, 41, 34, .12); } +.decisions { list-style: none; padding: 0; margin: 6px 0 0; display: flex; flex-direction: column; counter-reset: dq; } +.decisions li { counter-increment: dq; padding: 18px 0; border-top: 2px solid rgba(59, 41, 34, .85); display: grid; grid-template-columns: 44px minmax(0, 1fr) minmax(0, 1.25fr); gap: 6px 22px; align-items: start; } +.decisions li::before { content: counter(dq); font-family: var(--display); font-weight: 800; font-size: 1.7rem; line-height: 1; } +.decisions b { font-family: var(--display); font-weight: 700; font-size: 1.3rem; line-height: 1.1; } +.decisions span { font-size: 1rem; } +.decisions span i { font-style: normal; font-family: var(--label); font-weight: 700; font-size: 12.5px; letter-spacing: .09em; text-transform: uppercase; background: var(--cacao); color: var(--corn); padding: 1px 8px; border-radius: 4px; display: inline-block; margin: 0 8px 4px 0; } +@media (max-width: 700px) { .decisions li { grid-template-columns: 30px 1fr; } .decisions span { grid-column: 2; } } +.foot { width: min(1160px, 100% - 2 * var(--gutter)); margin: -24px auto 0; padding-bottom: 56px; font-size: .88rem; color: var(--ink-soft); } + +@media (max-width: 480px) { + .device { padding: 8px; border-radius: 46px; } + .phone { border-radius: 38px; height: 730px; } + .device::before { top: 18px; } +} +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; } + .stamped { transform: rotate(-6deg); } +} diff --git a/yuhm/prototypes/the-mission/mission.js b/yuhm/prototypes/the-mission/mission.js new file mode 100644 index 00000000..1cf4d1ec --- /dev/null +++ b/yuhm/prototypes/the-mission/mission.js @@ -0,0 +1,413 @@ +/* THE MISSION — clickable UX demo. Everything here is sample content; nothing talks to Supabase. */ +(() => { + 'use strict' + + // Icon paths from lucide (ISC), the same set the app already ships. + const P = { + check: '', + clock: '', + pin: '', + truck: '', + users: '', + sprout: '', + bell: '', + utensils: '', + chef: '', + heart: '', + leaf: '', + arrow: '', + back: '', + lock: '', + box: '', + bag: '', + radar: '', + pause: '', + send: '', + languages: '', + } + const icon = (name, size = 18) => `` + + // Produce-colored routes: tomato, leaf, corn, aubergine, pea, carrot. [fill, tint, tilt] + const LOOK = { eat: ['#f08a6c', '#fde6dc', -2.2], grow: ['#8cc084', '#e3f1df', 1.6], make: ['#f5c451', '#fcefc9', -1.2], move: ['#b79ac6', '#efe6f4', 2], share: ['#b9d99b', '#edf6e2', -1.8], organize: ['#f3a552', '#fde9d0', 1.4] } + + const ROUTES = [ + { id: 'eat', label: 'Eat', icon: 'utensils', copy: 'Find food, help others find it', + bite: { q: 'Last time you stopped by a community fridge, how was it?', opts: ['Well stocked', 'A few things', 'Empty', "Haven't been yet"] }, + mission: { title: 'Fridge check: Chestnut fridge', when: 'Any time today', dist: '0.4 mi · 15 min', needs: 'Just your phone', moves: 'Keeps one listing honest for everyone after you', seeds: 20, stamp: 'First check', + steps: [['Walk to the fridge', 'The exact spot shows here now that you have accepted.', "I'm here"], ['Note what is inside', 'A quick look. No need to touch anything.', 'Noted', ['Fridge is running and clean', 'Shelves photographed', 'Hours on the door match the listing']], ['Send the update', 'Your note goes to the listing and to the fridge host.', 'Send it']], + thanks: ['Thanks for checking on us. We restocked an hour after your note.', 'Fridge host, Chestnut'] } }, + { id: 'grow', label: 'Grow', icon: 'sprout', copy: 'Share your garden’s extra', + bite: { q: 'What do you have more of than you can eat?', opts: ['Tomatoes and peppers', 'Herbs', 'Figs, citrus, pecans', 'Eggs', 'Nothing yet'] }, + mission: { title: 'Harvest share: Saturday pool table', when: 'Sat Sep 26, 9 to 10 am', dist: '0.8 mi · 45 min', needs: 'Bags or a crate', moves: 'About 12 lb of garden extras', seeds: 35, stamp: 'First harvest', + steps: [['Pick and bag', 'Whatever you can spare this week.', 'Bagged', ['Soil rinsed off', 'Bagged by type', 'Date written on the bag']], ['Bring it to the pool table', 'The exact spot shows here now that you have accepted.', "I'm here"], ['Hand off to the pool host', 'They weigh it in so the circle can count it.', 'Handed off']], + thanks: ['Your peppers were gone in ten minutes. Bring more any time.', 'Pool host, Eastside'] } }, + { id: 'make', label: 'Make', icon: 'chef', copy: 'Cook or bake for a gathering', + bite: { q: 'What can your kitchen do?', opts: ['Batch cooking', 'Baking', 'Canning and preserving', 'Prep and chopping', 'Washing up'] }, + mission: { title: 'Kitchen shift: soup night prep', when: 'Thu Sep 24, 5 to 7 pm', dist: '1.4 mi · 2 hours', needs: 'Closed shoes, hair tied back', moves: 'About 60 portions of soup', seeds: 45, stamp: 'First shift', + steps: [['Arrive and wash in', 'The kitchen address shows here now that you have accepted.', 'Washed in', ['Hands washed', 'Hair tied back', 'Closed shoes on']], ['Cook with the crew', 'The kitchen lead hands out stations.', 'Shift done'], ['Portion and label', 'Every container gets a date and an allergen note.', 'All labeled']], + thanks: ['Sixty bowls went out warm. The crew says you chop fast.', 'Kitchen lead'] } }, + { id: 'move', label: 'Move', icon: 'truck', copy: 'Carry food to where it is needed', + bite: { q: 'What wheels do you have?', opts: ['On foot', 'Bike', 'Cargo bike', 'Car', 'Truck or van'] }, + mission: { title: 'Rescue run: bakery to fridge', when: 'Today, 4:30 to 5:30 pm', dist: '2.1 mi · 40 min', needs: 'Car or cargo bike, can lift 25 lb', moves: 'About 60 lb of day-old bread', seeds: 40, stamp: 'First rescue', + steps: [['Pick up at the bakery', 'The address and the contact show here now that you have accepted.', 'Picked up', ['Crates counted (4)', 'Bags sealed', 'Pickup photo taken']], ['Drive to the fridge', 'The fridge host gets a heads-up that you are on the way.', "I'm here"], ['Stock and hand off', 'Bread on the top shelf, oldest in front.', 'Handed off']], + thanks: ['The bread shelf was empty this morning. It is full now. Thank you.', 'Fridge host, Eastside'] } }, + { id: 'share', label: 'Share', icon: 'heart', copy: 'Stock a fridge, pass it along', + bite: { q: 'What could you share this month?', opts: ['Pantry staples', 'Garden extras', 'Fridge or freezer space', 'A ride', 'My time'] }, + mission: { title: 'Stock the fridge: pantry staples', when: 'Any time before Friday', dist: '0.6 mi · 20 min', needs: 'Sealed, in-date items', moves: 'About 10 lb of staples', seeds: 25, stamp: 'First drop', + steps: [['Gather your items', 'Rice, beans, pasta, canned fish, peanut butter all go fast.', 'Packed', ['Everything sealed', 'Dates checked', 'Nothing home-canned']], ['Drop at the fridge', 'The exact spot shows here now that you have accepted.', "I'm here"], ['Shelve and snap a photo', 'The photo updates the listing for the next neighbor.', 'Stocked']], + thanks: ["Somebody's dinner tonight started on your shelf.", 'Fridge host'] } }, + { id: 'organize', label: 'Organize', icon: 'users', copy: 'Bring neighbors to the table', + bite: { q: 'Where would you gather people?', opts: ['My block', 'A park', 'A church or school', 'An apartment courtyard', 'Not sure yet'] }, + mission: { title: 'Welcome table: Saturday pool', when: 'Sat Sep 26, 9 to 11 am', dist: '0.8 mi · 2 hours', needs: 'A friendly face. Spanish is a plus', moves: 'Around 40 neighbors welcomed', seeds: 40, stamp: 'First welcome', + steps: [['Set up the table', 'The exact spot shows here now that you have accepted.', 'Set up', ['Sign is out', 'Sign-in sheet ready', 'Water and shade sorted']], ['Welcome neighbors', 'Say hello, point to the table, answer what you can.', 'Wrapped up'], ['Close out', 'Send the visitor count so the circle can plan next week.', 'Count sent']], + thanks: ['Three new families came back because someone said hello.', 'Circle organizer'] } }, + ] + const BOARD_BITES = [['Confirm hours at a fridge near you', '2 min', 10, 'clock'], ['Translate one listing into Spanish', '3 min', 10, 'languages'], ['Nominate a food source you know', '2 min', 15, 'pin']] + const LEVELS = [['Seed', 0], ['Sprout', 50], ['Vine', 150], ['Bloom', 400], ['Harvest', 900], ['Perennial', 2000]] + const CORE_SCREENS = [['arrive', 'Arrive'], ['route', 'Pick a route'], ['bite', 'First bite'], ['save', 'Save your spot'], ['optin', 'Opt in'], ['board', 'Mission board'], ['offer', 'The offer'], ['active', 'On a mission'], ['done', 'Done'], ['email', 'Email'], ['whatsapp', 'WhatsApp'], ['controls', 'Controls']] + const CORE_GROUPS = [['First visit', 0, 5], ['The loop', 5, 9], ['Staying in touch', 9, 12]] + + const state = { screen: 'arrive', route: 'move', picked: [], biteDone: false, seeds: 0, done: 0, optedIn: null, goal: 2, email: true, whatsapp: false, free: false, offerReady: false, passed: false, step: 0, checks: [], missionDone: false, miniDone: [], mailTab: 'offer', chat: null, paused: false, left: false, foodNote: false, seen: ['arrive'] } + // Pending replies are never cancelled: they settle state even if the viewer moved on, + // and only repaint when their screen is still showing. Only the hold countdown is per-render. + let holdTimer = null + let lastScreen = null + let countFrom = null + let uid = 0 + const later = (fn, ms) => { setTimeout(fn, ms) } + const reduced = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches + + const route = () => ROUTES.find((r) => r.id === state.route) + const level = () => { + const at = LEVELS.reduce((found, entry, i) => (state.seeds >= entry[1] ? i : found), 0) + const next = LEVELS[at + 1] + const span = next ? next[1] - LEVELS[at][1] : 1 + return { name: LEVELS[at][0], next: next ? next[0] : null, toNext: next ? next[1] - state.seeds : 0, pct: next ? Math.round(((state.seeds - LEVELS[at][1]) / span) * 100) : 100 } + } + + /* ---------- components ---------- */ + const seedsTag = (n) => `${icon('leaf', 14)}+${n}` + const statusBar = (cls = '') => `
9:41
` + const top = (right = 'Sample data') => `${statusBar()}
yuhm♥${right}
` + const shell = (body, foot = '', right) => `${top(right)}
${body}
${foot ? `
${foot}
` : ''}` + const trail = (n) => `
    ${['Route', 'First bite', 'Save'].map((l, i) => `
  1. ${l}
  2. `).join('')}
` + const switchRow = (label, sub, on, key) => `
${label}${sub}
` + const burst = () => Array.from({ length: 16 }, (_, i) => { const a = (i / 16) * Math.PI * 2; return `` }).join('') + + // An embroidered-patch stamp: scalloped edge, stitched ring, text on two arcs. + function patch(topText, bottomText, iconName, fill, size = 132, cls = '') { + const id = `pt${++uid}`; const n = 20; const R = 54; const c = 66 + const pts = Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2 - Math.PI / 2; return [(c + R * Math.cos(a)).toFixed(2), (c + R * Math.sin(a)).toFixed(2)] }) + const r = (R * Math.sin(Math.PI / n)).toFixed(2) + const d = `M${pts[0][0]} ${pts[0][1]}${pts.map((_, i) => { const p = pts[(i + 1) % n]; return `A${r} ${r} 0 0 1 ${p[0]} ${p[1]}` }).join('')}Z` + return ` + + + ${topText} + ${bottomText} + ${P[iconName]}` + } + const ring = (pct, inner) => { const r = 24; const c = 2 * Math.PI * r; return `` } + const factList = (m) => `
${icon('clock', 13)}When
${m.when}
${icon('pin', 13)}How far
${m.dist}
${icon('bag', 13)}You need
${m.needs}
${icon('box', 13)}It moves
${m.moves}
` + const cadence = () => `
${[[1, 'Easy'], [2, 'Steady'], [3, 'All in']].map(([n, l]) => ``).join('')}
` + const heroArt = `
` + + /* ---------- screens ---------- */ + const VIEWS = { + arrive: () => shell(` + ${heroArt} +

Food, shared full circle.

+

Find food near you, or take part in moving it. Nothing good goes to waste.

+ + ${state.foodNote ? '
Unchanged. Straight to the map. No account, no seeds, no prompts to join. A hungry neighbor never meets a game.
' : ''} + + `), + + route: () => shell(` + ${trail(1)} +

How do you want to take part?

+
${ROUTES.map((r) => ` + `).join('')}
+

Pick one to start. You can add more later.

`, + ``), + + bite: () => { + const b = route().bite + if (state.biteDone) return shell(` + ${trail(2)} +
${burst()}
+ ${patch('First bite', 'yuhm · Austin', 'leaf', LOOK[state.route][0], 150, 'stamped')} +

First mission done

${seedsTag(10)} +

That was a bite: two minutes, and yuhm already knows what to offer you. Runs and shifts are the bigger ones.

`, + ``) + return shell(` + ${trail(2)} +
First bite · ${route().label} · 2 min${seedsTag(10)} +

${b.q}

+
${b.opts.map((o, i) => ``).join('')}
+

Your answer shapes which missions you get offered. Change it any time.

`, + ``) + }, + + save: () => shell(` + ${trail(3)} +
${patch('First bite', 'yuhm · Austin', 'leaf', LOOK[state.route][0], 64)}
${state.seeds || 10} seeds and a stamp${route().label} route. An account keeps them.
+

Save your spot

+

One step. If this email already has a yuhm account, this signs you in.

+ + `, + ``), + + optin: () => shell(` + Optional · your account works either way +
Join theMISSION?
${patch('Opt in', 'Pause any time', route().icon, LOOK[state.route][0], 92)}
+

Missions matched to your ${route().label} route, near your neighborhood, at a rhythm you choose.

+
Your weekly rhythm${cadence()}
+
How may we reach you?
+ ${switchRow('In the app', 'Always on', true, null)} + ${switchRow('Email', 'Offers, reminders, a Sunday digest', state.email, 'email')} + ${switchRow('WhatsApp', 'Offers and a helper you can talk to', state.whatsapp, 'whatsapp')}
+
    +
  • ${icon('check', 17)}Passing on a mission never costs you anything.
  • +
  • ${icon('check', 17)}Pause or leave in one tap. Quiet from 9 pm to 8 am.
  • +
  • ${icon('check', 17)}Addresses stay hidden until you accept.
  • +
  • ${icon('check', 17)}Seeds are thanks, not money. No public ranking.
`, + ``), + + board: () => { + if (state.optedIn === false) return shell(` +

You're in. No missions.

+

Your account works like it does today: post, request, gather, coordinate. THE MISSION waits in your profile as one quiet card, and nothing will message you about it.

+
${icon('sprout')}THE MISSIONMissions near you, at your rhythm. See what it is.${icon('arrow', 16)}
`, + ``) + const lv = level(); const m = route().mission + const now = state.missionDone ? '
Nothing held for you right now. New missions show here the moment they match.
' + : state.passed ? '
Passed. No harm done. It went to the next neighbor.
' + : state.offerReady || !state.free ? `` + : `
${icon('radar', 20)}Looking for missions near Eastside…
` + return shell(` + ${state.paused ? `` : ''} +
+
${ring(lv.pct, 'leaf')}${lv.name}${lv.next ? `${lv.toNext} to ${lv.next}` : 'top level'}
+

Week 1 rhythm

${`${icon('leaf', 14)}${state.seeds}`}
+
    ${['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => `
  1. ${i === 5 && state.done ? icon('check', 13) : ''}${d}
  2. `).join('')}
+
${Math.min(state.done, state.goal)} of ${state.goal} this week${Array.from({ length: state.goal }, (_, i) => ``).join('')}
+
+ +
For you now${now}
+
Bitestwo minutes each
${BOARD_BITES.map((b, i) => ``).join('')}
+
Claim a slot this week
+
Sun20Compost return4 pm · 1 spot left${seedsTag(30)}
+
Sat26Eastside pool table9 am · 2 spots left${seedsTag(35)}
+
Eastside Circle this weekSample

310 of 500 lb moved together. No ranking, one shared goal.

`, + '', `Sample data`) + }, + + offer: () => { + const m = route().mission + return shell(` +
+
${route().label} · held for you${icon(route().icon, 22)}

${m.title}

+ ${factList(m)} +
Seeds+${m.seeds}
Hold ends in14:59
+
+

${icon('lock', 16)}Exact addresses and contacts appear after you accept. Until then it is neighborhood-level only.

+

Not a fit? Passing is free. It goes to the next neighbor and nothing is held against you.

`, + ``) + }, + + active: () => { + const m = route().mission + const live = Math.min(state.step, m.steps.length - 1) + const items = [`
  • ${icon('check', 16)}

    Accepted

    Details unlocked. Reminder set for 2 hours before.

  • `] + .concat(m.steps.map((s, i) => { + const cls = i < live ? 'past' : i === live ? 'live' : '' + const checks = i === live && s[3] ? `
    ${s[3].map((c, n) => ``).join('')}
    ` : '' + return `
  • ${i < live ? icon('check', 16) : i + 1}

    ${s[0]}

    ${i <= live ? `

    ${s[1]}

    ` : ''}${checks}
  • ` + })) + const s = m.steps[live] + const ready = !s[3] || s[3].every((_, n) => state.checks.includes(n)) + return shell(` +
    On a mission · ${route().label}${seedsTag(m.seeds)}
    +

    ${m.title}

    +
      ${items.join('')}
    `, + ``) + }, + + done: () => { + const m = route().mission; const lv = level() + return shell(` +
    ${burst()}
    + ${patch(m.stamp, 'yuhm · Austin', route().icon, LOOK[state.route][0], 156, 'stamped')} +

    Mission done

    +
    ${icon('leaf', 30)}${state.seeds}seeds
    +

    ${m.moves}. ${Math.min(state.done, state.goal)} of ${state.goal} this week, and your rhythm holds.

    +
    ${ring(lv.pct, 'sprout')}
    ${lv.name}${lv.next ? `${lv.toNext} seeds until you grow to ${lv.next}` : 'Top level'}
    +
    ${m.thanks[0]}${m.thanks[1]} · sample note
    +
    ${patch('Full circle', 'back to soil', 'sprout', '#b9d99b', 58)}

    Take the scraps to compost

    ${seedsTag(15)}

    What is left returns to the soil. Optional, ten minutes.

    `, + ``) + }, + + email: () => { + const m = route().mission + const MAILS = { + offer: ['A mission near Eastside', '3:58 pm', m.title, `

    ${m.when}
    ${m.dist}
    You need: ${m.needs}
    It moves: ${m.moves}

    Held for you until 4:15 pm. Passing is free.

    AcceptPass
    `, 'One tap, no login. The address arrives after you accept.'], + reminder: ['In 2 hours', '2:30 pm', m.title, `

    ${m.when}. Calendar file attached.

    Bring: ${m.needs}.

    See the stepsI can't make it
    `, 'Releasing early costs nothing. It goes straight back to the board.'], + digest: ['Your week with yuhm', 'Sun 5:00 pm', 'Week 1 of your rhythm', `

    You: ${Math.max(state.done, 1)} mission${Math.max(state.done, 1) === 1 ? '' : 's'} and ${Math.max(state.seeds, 10)} seeds.

    Eastside Circle: 310 lb moved, 4 fridges checked. (sample)

    Open next week: Compost return Sun 4 pm · Pool table Sat 9 am

    Claim a slot
    `, 'Sundays at 5 pm. One email a week, never more.'], + checkin: ['Still want missions?', 'Wed 10:00 am', 'Either answer is fine', `

    You have not picked one up in three weeks, which is completely okay. Life is full.

    Should we keep sending them?

    Keep them comingPause a monthStop missions
    `, 'If we do not hear back, we go quiet on our own. Your account and history stay.'], + } + const mail = MAILS[state.mailTab] + return shell(` +

    What lands in the inbox

    +
    ${[['offer', 'Offer'], ['reminder', 'Reminder'], ['digest', 'Digest'], ['checkin', 'Check-in']].map(([id, l]) => ``).join('')}
    +
    y${mail[0]}yuhm <missions@yuhm.handprotocol.org>

    ${mail[2]}

    ${mail[3]}
    ${mail[4]} · Pause · Stop mission email
    `) + }, + + whatsapp: () => `${statusBar('wa')} + + + + `, + + controls: () => shell(` +

    Your controls

    + ${state.left ? '' : ''} +
    Weekly rhythm${cadence()}
    +
    Reach me by
    ${switchRow('In the app', 'Always on', true, null)}${switchRow('Email', 'Offers, reminders, Sunday digest', state.email, 'email')}${switchRow('WhatsApp', 'Offers and the helper', state.whatsapp, 'whatsapp')} +
    Quiet hoursNothing is sent in between9 pm to 8 am
    +
    Take a break

    ${state.paused ? 'Paused until Oct 3. No offers, no nudges. Your rhythm is frozen, not broken.' : 'Pausing freezes your rhythm and stops every mission message.'}

    +
    `, + ``), + } + + const NOTES = { + arrive: ['Arrive: two doors, one new label', 'The landing keeps its two doors. Find food stays exactly as it is: no account, no game, straight to the map. For first-time visitors the second door changes from Sign in to Take part, and Sign in drops to a text link for returning members.', ['Borrowed', 'Nothing yet. The rule on this screen is restraint.'], ['Writes', 'Nothing. A first-visit flag in localStorage (yuhm:first-visit) decides which label the second door wears.'], ['Guardrail', 'Find food never shows seeds, streaks, or prompts to join. Tap it to see.']], + route: ['Pick a route: commitment before paperwork', 'Six routes, the same six the living world already uses (WorldRole: eat, grow, make, move, share, organize). Each gets a produce color that follows the person through every later screen: the first bite, the ticket, the stamps.', ['Borrowed', 'Duolingo asks what you want to learn before it asks who you are.'], ['Writes', 'Nothing yet. The choice rides in localStorage (yuhm:mission-draft) until the account exists.']], + bite: ['First bite: a mission before the account', 'A two-minute mission finished before sign-up. It is the profile form in disguise: the answer becomes the capabilities the dispatcher matches on (wheels, kitchen skills, what they grow). Finishing it earns the first 10 seeds and the first stamp.', ['Borrowed', 'Duolingo lets you finish a lesson, then offers to save your progress. People protect what they have already earned.'], ['Writes', 'Draft only. On account creation the draft is claimed: capabilities go to food_mission_enrollments, the seeds go to food_reputation_ledger as training_completed.']], + save: ['Save your spot: the same one-step form', 'This is the existing EmailContinueForm, untouched: email, password, Continue. It signs in or creates the account. The only change is a header showing what the person is about to keep. Email and password stays the mechanism.', ['Borrowed', 'The save-your-progress moment. Sign-up reads as keeping something, not as paperwork.'], ['Writes', 'Supabase auth user, command.profiles, then the existing ensure_food_participant(). The draft is claimed right after.'], ['Guardrail', 'No new fields. The September funnel pass cut sign-up to one step and this keeps it there.']], + optin: ['Opt in: a separate yes', 'An account does not enroll anyone. This screen says what the person gets, asks for a rhythm, asks how yuhm may reach them, and states four promises. Not now is a full-size button, and it leads to the normal app.', ['Borrowed', 'Duolingo’s goal picker (casual, regular, serious), changed from daily to weekly because food work runs on a weekly beat.'], ['Writes', 'food_mission_enrollments (status, routes, rhythm goal, zone, consent version). One food_notification_prefs row per category and channel. A WhatsApp number goes to food_contact_channels, encrypted, with consent time recorded.'], ['Notifies', 'A welcome email listing this week’s open slots. WhatsApp sends its own opt-in confirmation.']], + board: ['Mission board: home for members who opted in', 'A punch card on top: level ring, the week’s punches, the goal. Then one ticket held for you, bites that take two minutes, and slots to claim. The I’m free now bar is the volunteer version of going online. The circle goal is shared progress, not a ranking.', ['Borrowed', 'DoorDash: Dash Now, scheduled shifts, the offer card. Duolingo: streak counter, daily quests, goal ring.'], ['Writes', 'The bar sets available_until on the enrollment. Everything else is one read: list_food_missions().'], ['Guardrail', 'Only real missions appear. A quiet zone says it is quiet. Bites always exist because the public directory always has hours to confirm, so the board is never empty and never fake.']], + offer: ['The offer: a ticket you can accept or pass', 'One ticket, four facts: when, how far, what you need, what it moves. The hold on the stub is calm and long: 15 minutes for same-day rescues, hours for scheduled work. Pass is free and says so. The exact address stays hidden until acceptance.', ['Borrowed', 'DoorDash’s offer card and countdown, without the red urgency or the acceptance-rate penalty.'], ['Writes', 'food_mission_offers moves to accepted or passed. Accept locks the mission row, fills a slot, creates food_mission_assignments, and for rescues calls the existing claim_food_rescue().'], ['Notifies', 'Accept schedules the 24-hour and 2-hour reminders. Pass re-offers to the next neighbor.']], + active: ['On a mission: one live step', 'A route line with one stop live at a time. A stop can ask for light evidence: a checklist, a count, a photo. Releasing is always visible, and releasing early costs nothing.', ['Borrowed', 'DoorDash’s pickup and drop-off flow, with a confirmation at each stop.'], ['Writes', 'Each tap appends to food_mission_checkpoints with an idempotency key, so a double tap on bad signal never double-counts. Rescue missions also call the existing record_food_rescue_checkpoint().'], ['Notifies', 'The coordinator sees progress live. The receiving spot gets a heads-up at the on-the-way step.'], ['Guardrail', 'Food-safety checklists live on the mission template, so a cold-chain run always asks about the cooler.']], + done: ['Done: the payoff', 'A stamp thunks down, the seeds count up, the week gets its punch, and a real thank-you note shows when there is one. Then one optional next step, the compost return, which closes the loop back to soil.', ['Borrowed', 'Duolingo’s lesson-complete screen. DoorDash’s delivery summary, with impact where earnings would be.'], ['Writes', 'One transaction: assignment completed, a ledger row (delivery_completed, points), the food_mission_progress cache, a stamp if earned, and an outbox row for the receipt.'], ['Notifies', 'A receipt on the person’s chosen channel. No upsell.']], + email: ['Email: four messages, all one-tap', 'Email is the default channel because Resend is already wired. Every email works without a login: signed links accept, pass, pause, or stop. Scheduled missions attach a calendar file. The fourth tab matters most: after three quiet weeks yuhm asks once, and silence means it goes quiet.', ['Borrowed', 'Duolingo’s reminder cadence, turned around: fewer messages when someone drifts, never more.'], ['Writes', 'food_notification_log on every send and every suppression. One-tap links hit a Netlify function that verifies the signature and calls the same RPCs as the app.']], + whatsapp: ['WhatsApp: a one-to-one helper', 'Opt-in only. The helper sends offers and reminders as approved utility templates with quick-reply buttons, and answers questions in English or Spanish. It can do only what the person could do in the app, and it hands off to a coordinator on request or when something sounds like safety or urgent need. Tap the buttons and suggestions to try it.', ['Borrowed', 'DoorDash’s text-message offer loop, moved to the app many Austin neighbors already live in.'], ['Writes', 'Rows in food_messages under one food_conversations thread. Every action lands in food_agent_actions under a food_agent_mandates grant.'], ['Guardrail', 'Official Cloud API only. A bot inside a big neighborhood group is not possible there (groups cap at 8 people and need a verified business badge), so circle-wide news goes to a human-run announcement group.']], + controls: ['Controls: pause and leave are one tap', 'Rhythm, channels, quiet hours, pause, leave. Pausing freezes the rhythm instead of breaking it. Leaving keeps the account and the history, deletes the phone number, and stops every mission message.', ['Borrowed', 'Duolingo’s streak freeze, made automatic and generous.'], ['Writes', 'food_mission_enrollments.status and paused_until, food_notification_prefs, and on leave a hard delete of the WhatsApp row in food_contact_channels.']], + } + + // Extensions (gather.js) add a group of screens without touching the core flow. Each one is a + // function that takes the shared components and returns { group, screens, views, notes, state, actions }. + const EXT = (window.YUHM_DEMO_EXT ?? []).map((extend) => extend({ icon, shell, seedsTag, patch, state, render: () => render() })) + const SCREENS = EXT.reduce((all, ext) => [...all, ...ext.screens], CORE_SCREENS) + const GROUPS = EXT.reduce((all, ext) => [...all, [ext.group, all.at(-1)[2], all.at(-1)[2] + ext.screens.length]], CORE_GROUPS) + const merged = (key) => Object.assign({}, ...EXT.map((ext) => ext[key])) + const views = { ...VIEWS, ...merged('views') } + const notesFor = { ...NOTES, ...merged('notes') } + const extActions = merged('actions') + Object.assign(state, merged('state')) + + const phone = document.getElementById('phone') + const stepper = document.getElementById('stepper') + const notes = document.getElementById('notes') + const mastPatch = document.getElementById('mast-patch') + const index = () => SCREENS.findIndex((s) => s[0] === state.screen) + + function seedChat() { + const r = route(); const m = r.mission + state.chat = [{ who: 'bot', html: `A mission near Eastside fits your ${r.label} route:
    ${m.title}
    ${m.when} · ${m.dist}
    ${m.moves}.
    Want it?`, qr: [['Accept', 'accept'], ['Pass', 'pass'], ['Tell me more', 'bring']] }] + } + function reply(key) { + const m = route().mission; const lv = level() + return { + accept: ['Accept', `It's yours. ${m.title}, ${m.when}. The spot is on E 11th (sample), shown only now that you have accepted. I'll remind you 2 hours before. Reply DROP any time to release it, no hard feelings.`], + pass: ['Pass', 'No problem, passed. It goes to the next neighbor and costs you nothing. If it was the wrong kind of mission, tell me what did not fit and I will adjust.'], + bring: ['What do I need to bring?', `${m.needs}. ${m.moves}. Anything else you want to know before you decide?`], + pausa: ['Pausa por dos semanas', 'Listo. Pausé tus misiones por dos semanas, hasta el 3 de octubre. No te escribo hasta entonces y tu ritmo queda guardado. Responde VOLVER cuando quieras regresar.'], + rhythm: ["What's my rhythm?", `Week 1 of your rhythm, ${Math.min(state.done, state.goal)} of ${state.goal} missions this week. ${state.seeds} seeds${lv.next ? `, ${lv.toNext} more and you grow to ${lv.next}` : ''}.`], + person: ['Talk to a person', 'Of course. I flagged this chat for a coordinator, and a person will answer here, usually within a few hours. If anyone needs food right now, the map is open with no sign-in: yuhm.handprotocol.org'], + }[key] + } + + function countUp() { + const el = document.getElementById('seedcount') + if (!el || countFrom === null) return + const from = countFrom; const to = state.seeds; countFrom = null + if (reduced()) return + const t0 = performance.now() + const tick = (t) => { const k = Math.min(1, (t - t0) / 900); const e = 1 - Math.pow(1 - k, 4); el.textContent = String(Math.round(from + (to - from) * e)); if (k < 1) requestAnimationFrame(tick) } + el.textContent = String(from); requestAnimationFrame(tick) + } + + function render() { + if (holdTimer) { clearInterval(holdTimer); holdTimer = null } + const pastSave = index() >= SCREENS.findIndex((s) => s[0] === 'save') + if (pastSave && !state.biteDone) { state.biteDone = true; state.seeds += 10; state.done += 1 } + if (state.screen === 'whatsapp' && !state.chat) seedChat() + if (state.screen === 'done' && !state.missionDone) { countFrom = state.seeds; state.missionDone = true; state.seeds += route().mission.seeds; state.done += 1 } + if (!state.seen.includes(state.screen)) state.seen = [...state.seen, state.screen] + phone.dataset.enter = lastScreen === state.screen ? '0' : '1' + lastScreen = state.screen + phone.style.setProperty('--rc', LOOK[state.route][0]); phone.style.setProperty('--rt', LOOK[state.route][1]) + phone.innerHTML = views[state.screen]() + const at = index() + stepper.innerHTML = GROUPS.map(([label, a, b]) => `
    ${label}
      ${SCREENS.slice(a, b).map((s, i) => `
    1. `).join('')}
    `).join('') + const n = notesFor[state.screen] + notes.innerHTML = `Screen ${at + 1} of ${SCREENS.length}

    ${n[0]}

    ${n[1]}

    ${n.slice(2).map(([k, v]) => `
    ${k}
    ${v}
    `).join('')}
    + ` + if (state.screen === 'offer') { + let left = 899 + holdTimer = setInterval(() => { left = Math.max(0, left - 1); const el = document.getElementById('hold'); if (el) el.textContent = `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` }, 1000) + } + if (state.screen === 'done') countUp() + const log = document.getElementById('wa-log'); if (log) log.scrollTop = log.scrollHeight + } + + function act(name, arg) { + const A = { + food: () => { state.foodNote = !state.foodNote }, + route: () => { if (state.route !== arg) { state.route = arg; state.picked = []; state.chat = null; state.step = 0; state.checks = [] } }, + pick: () => { const i = Number(arg); state.picked = state.picked.includes(i) ? state.picked.filter((p) => p !== i) : [...state.picked, i] }, + 'bite-done': () => { if (!state.biteDone) { state.biteDone = true; state.seeds += 10; state.done += 1 }; lastScreen = null }, + goal: () => { state.goal = Number(arg) }, + sw: () => { + state[arg] = !state[arg] + if (arg === 'free' && state.free && !state.missionDone) { state.offerReady = false; state.passed = false; later(() => { state.offerReady = true; if (state.screen === 'board') render() }, 1900) } + }, + join: () => { state.optedIn = true; state.left = false; state.screen = 'board' }, + notnow: () => { state.optedIn = false; state.screen = 'board' }, + mini: () => { const i = Number(arg); if (!state.miniDone.includes(i)) { state.miniDone = [...state.miniDone, i]; state.seeds += BOARD_BITES[i][2]; state.done += 1 } }, + accept: () => { state.step = 0; state.checks = []; state.screen = 'active' }, + pass: () => { state.passed = true; state.screen = 'board' }, + ck: () => { const i = Number(arg); state.checks = state.checks.includes(i) ? state.checks.filter((c) => c !== i) : [...state.checks, i] }, + step: () => { state.checks = []; if (state.step >= route().mission.steps.length - 1) state.screen = 'done'; else state.step += 1 }, + release: () => { state.passed = true; state.step = 0; state.checks = []; state.screen = 'board' }, + mail: () => { state.mailTab = arg }, + pause: () => { state.paused = !state.paused }, + leave: () => { state.left = !state.left; if (state.left) state.whatsapp = false }, + say: () => { + const r = reply(arg) + state.chat = [...state.chat.map((c) => ({ ...c, qr: null })), { who: 'me', html: r[0] }, { who: 'bot', typing: true }] + later(() => { state.chat = [...state.chat.filter((c) => !c.typing), { who: 'bot', html: r[1] }]; if (state.screen === 'whatsapp') render() }, 1100) + }, + } + const run = A[name] ?? extActions[name] + if (run) { run(arg); render() } + } + + document.addEventListener('click', (event) => { + const el = event.target instanceof Element ? event.target.closest('[data-go],[data-act],[data-nav]') : null + if (!el || el.disabled) return + if (el.dataset.go) { if (state.optedIn === null && ['board', 'offer', 'active', 'done'].includes(el.dataset.go)) state.optedIn = true; state.screen = el.dataset.go; render(); return } + if (el.dataset.nav) { const next = SCREENS[index() + Number(el.dataset.nav)]; if (next) { if (state.optedIn === false && next[0] !== 'board') state.optedIn = true; state.screen = next[0]; render() } return } + const [name, arg] = el.dataset.act.split(':') + act(name, arg) + }) + + if (mastPatch) mastPatch.innerHTML = patch('Demo + plan', 'Not built yet', 'sprout', '#f08a6c', 176) + const start = (data) => { if (data && data.state) Object.assign(state, data.state); render() } + try { window.claude?.hot?.snapshot?.(() => ({ state })) } catch { /* preview without the runtime */ } + if (window.claude?.hot?.ready) window.claude.hot.ready(start) + else start(window.claude?.hot?.data ?? {}) +})() diff --git a/yuhm/prototypes/the-mission/preview.mjs b/yuhm/prototypes/the-mission/preview.mjs new file mode 100644 index 00000000..8de0778d --- /dev/null +++ b/yuhm/prototypes/the-mission/preview.mjs @@ -0,0 +1,86 @@ +// Local preview and screenshots for the THE MISSION demo. +// The published artifact wraps index.html in a doctype/head/body; this builds the same wrapper, +// clicks through the flow in headless Chromium, and reports console errors and phone-width overflow. +// +// Usage: node preview.mjs +// On this machine Chromium needs --no-sandbox, and the Claude Code Bash sandbox must be disabled for the call. +import { chromium } from '/home/koh/.claude/skills/gstack/node_modules/playwright/index.mjs' +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const out = resolve(process.argv[2] ?? join(here, '.preview')) +mkdirSync(out, { recursive: true }) +for (const file of ['mission.css', 'mission.js', 'gather.css', 'gather.js']) copyFileSync(join(here, file), join(out, file)) +const head = '' +writeFileSync(join(out, 'index.html'), `${head}${readFileSync(join(here, 'index.html'), 'utf8')}`) + +const browser = await chromium.launch({ chromiumSandbox: false, args: ['--no-sandbox'] }) +const errors = [] +const page = await browser.newPage({ viewport: { width: 1400, height: 920 } }) +page.on('console', (message) => { if (message.type() === 'error') errors.push(message.text()) }) +page.on('pageerror', (error) => errors.push(`PAGEERROR ${error.message}`)) +await page.goto(`file://${out}/index.html`) +await page.waitForTimeout(1500) +await page.screenshot({ path: join(out, 'desktop-top.png') }) + +const device = page.locator('.device') +const go = async (label) => { await page.click(`#stepper button:has-text("${label}")`); await page.waitForTimeout(700) } +const unticked = '#phone .ck[aria-pressed="false"]' + +await go('Pick a route'); await device.screenshot({ path: join(out, 'p02-route.png') }) +await go('First bite'); await page.click('#phone [data-act="pick:3"]'); await page.click('#phone [data-act="bite-done"]') +await page.waitForTimeout(1300); await device.screenshot({ path: join(out, 'p03-bite-done.png') }) +await go('Opt in'); await device.screenshot({ path: join(out, 'p05-optin.png') }) +await go('Mission board'); await device.screenshot({ path: join(out, 'p06-board.png') }) +await go('The offer'); await device.screenshot({ path: join(out, 'p07-offer.png') }) +await page.click('#phone [data-act="accept"]'); await page.waitForTimeout(600) +await device.screenshot({ path: join(out, 'p08-active.png') }) +for (let step = 0; step < 3; step += 1) { + // The checklist re-renders after every tap, so always re-query instead of holding a list. + while (await page.locator(unticked).count()) await page.locator(unticked).first().click() + await page.click('#phone [data-act="step"]'); await page.waitForTimeout(400) +} +await page.waitForTimeout(1500); await device.screenshot({ path: join(out, 'p09-done.png') }) +await go('Email'); await device.screenshot({ path: join(out, 'p10-email.png') }) +await go('WhatsApp'); await page.click('#phone [data-act="say:accept"]'); await page.waitForTimeout(1500) +await page.click('#phone [data-act="say:pausa"]'); await page.waitForTimeout(1500) +await device.screenshot({ path: join(out, 'p11-whatsapp.png') }) +await go('Controls'); await device.screenshot({ path: join(out, 'p12-controls.png') }) + +// Gatherings: order, lock, the money holder's checklist, the shop run, the bin, the settle tab. +const tap = async (act) => { await page.click(`#phone [data-act="${act}"]`); await page.waitForTimeout(150) } +const toBottom = () => page.evaluate(() => { const body = document.querySelector('#phone .p-body'); body.scrollTop = body.scrollHeight }) +const cents = (text) => Math.round(Number(text.replace(/[^0-9.]/g, '')) * 100) +await go('The gathering'); await device.screenshot({ path: join(out, 'p13-gather.png') }) +await tap('grole:sort'); await tap('gjoin') +await tap('gdish:beans|1'); await tap('gsrc:lime|network'); await device.screenshot({ path: join(out, 'p14-order.png') }) +await toBottom(); await device.screenshot({ path: join(out, 'p14b-order-share.png') }) +await tap('glock'); await page.waitForTimeout(800); await device.screenshot({ path: join(out, 'p14c-order-locked.png') }) +await go('Paid checklist'); await tap('gpaid:4'); await tap('gpayby'); await tap('gkeep:6'); await tap('gdrop:7') +await device.screenshot({ path: join(out, 'p15-paid.png') }) +await go('Shop run'); await tap('gswap'); await tap('gbuyall'); await device.screenshot({ path: join(out, 'p16-shop.png') }) +await tap('greceipt'); await tap('gshoptab:sort'); await device.screenshot({ path: join(out, 'p16b-sort.png') }) +await go('Pick up my bin'); await device.screenshot({ path: join(out, 'p17-pick.png') }) +await toBottom(); await device.screenshot({ path: join(out, 'p17b-balance.png') }) +await tap('gsettleview'); await tap('gsettle:4'); await device.screenshot({ path: join(out, 'p15b-settle.png') }) +const receipt = cents(await page.locator('#phone .tally b').first().innerText()) +const shares = (await page.locator('#phone .led > b').allInnerTexts()).reduce((sum, text) => sum + cents(text), 0) +const moneyCheck = receipt === shares ? `ok (${receipt} cents)` : `MISMATCH receipt ${receipt} vs shares ${shares}` + +for (const id of ['rules', 'game', 'gather', 'phases', 'decisions']) { + await page.evaluate((target) => document.getElementById(target).scrollIntoView(), id) + await page.waitForTimeout(300); await page.screenshot({ path: join(out, `plan-${id}.png`) }) +} + +const mobile = await browser.newPage({ viewport: { width: 400, height: 900 } }) +await mobile.goto(`file://${out}/index.html`); await mobile.waitForTimeout(1200) +await mobile.screenshot({ path: join(out, 'mobile-top.png') }) +const overflow = await mobile.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth) +await mobile.click('#stepper button:has-text("Build my order")'); await mobile.waitForTimeout(600) +const gatherOverflow = await mobile.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth) +await mobile.locator('.device').screenshot({ path: join(out, 'mobile-order.png') }) +await browser.close() + +process.stdout.write(`screenshots: ${out}\nmobile horizontal overflow px: ${overflow} (gathering screen: ${gatherOverflow})\nshares equal the receipt: ${moneyCheck}\nconsole errors: ${JSON.stringify(errors)}\n`) diff --git a/yuhm/src/App.tsx b/yuhm/src/App.tsx index 8c317293..ec6857d4 100644 --- a/yuhm/src/App.tsx +++ b/yuhm/src/App.tsx @@ -10,6 +10,7 @@ import { DashboardApp } from './DashboardApp' const MapLab = lazy(() => import('./map-lab/MapLab').then((module) => ({ default: module.MapLab }))) const WorldExperience = lazy(() => import('./world/WorldExperience').then((module) => ({ default: module.WorldExperience }))) +const RunsApp = lazy(() => import('./runs/RunsApp').then((module) => ({ default: module.RunsApp }))) // Re-exported so tests and callers keep a single import point. export { CommunityBoard } from './CommunityBoard' @@ -46,12 +47,15 @@ function AppRoutes() { const consumerIntent = intent === 'food' || intent === 'contribute' || intent === 'gather' || intent === 'request' ? intent : null const advancedMode = mode === 'advanced' || Boolean(workspace) const isMapLab = path.startsWith('/app') && mode === 'map-lab' + // The run sheet: a runner's own tool for one pickup shared out to several families. + const isRun = path.startsWith('/app') && mode === 'run' // The living world is the default app experience: bare /app/ and the anonymous // entry always open it, on every viewport. The dashboard is explicit only // (mode=advanced or workspace=); focused intents, auth, and map-lab keep // their existing routes. const isWorld = path.startsWith('/app') && !isMapLab + && !isRun && (mode === 'world' || (!authMode && !advancedMode && !consumerIntent)) const isMobileMap = path.startsWith('/app') && mobileViewport @@ -59,7 +63,9 @@ function AppRoutes() { && !advancedMode && !isWorld && consumerIntent === 'food' - const page = isWorld + const page = isRun + ? Opening your run sheet…}> + : isWorld ? Loading the living map…}> : isMapLab ? Loading map lab…}> @@ -68,7 +74,7 @@ function AppRoutes() { : path.startsWith('/app') ? authMode ? : advancedMode ? : : - return <>{page}{!isMapLab && } + return <>{page}{!isMapLab && } } function App() { diff --git a/yuhm/src/runs/AdvancedRules.tsx b/yuhm/src/runs/AdvancedRules.tsx new file mode 100644 index 00000000..7c639bca --- /dev/null +++ b/yuhm/src/runs/AdvancedRules.tsx @@ -0,0 +1,88 @@ +/** + * How seeds are counted. Everyone can read the rules. A coordinator can + * change them, and sees totals for the whole network with no names in them. + */ +import { useEffect, useState } from 'react' +import { useRuns } from './context' +import { shortDate } from './helpers' +import type { Rules } from './model' +import type { NetworkPayload } from './repository' +import { useRunText, type RunKey } from './runStrings' +import { Banner, Button, Stepper, Switch } from './ui' + +type NumberRule = Exclude + +const RULES: Array<{ key: NumberRule; max: number; step?: number }> = [ + { key: 'seeds_ask', max: 100 }, { key: 'seeds_intake', max: 100 }, { key: 'seeds_pickup', max: 100 }, { key: 'seeds_delivered', max: 100 }, + { key: 'seeds_full_circle', max: 100 }, { key: 'seeds_no_waste', max: 100 }, { key: 'seeds_tough_each', max: 100 }, { key: 'seeds_tough_cap', max: 200, step: 5 }, + { key: 'seeds_complete', max: 100 }, { key: 'seeds_stamp', max: 100 }, { key: 'intake_threshold', max: 10 }, { key: 'circle_goal', max: 100000, step: 5 }, +] + +export function AdvancedRules() { + const { t, lang } = useRunText() + const { snapshot, state, store, toast } = useRuns() + const [network, setNetwork] = useState(null) + const [draft, setDraft] = useState(state.rules) + const [seen, setSeen] = useState(state.rules) + const [busy, setBusy] = useState(false) + if (state.rules !== seen) { setSeen(state.rules); setDraft(state.rules) } + + // Only a coordinator's account can load the network totals; that answer is what unlocks editing. + useEffect(() => { + if (snapshot.mode !== 'account') { setNetwork(null); return } + let active = true + store.loadNetwork(8).then((loaded) => { if (active) setNetwork(loaded) }).catch(() => { if (active) setNetwork(null) }) + return () => { active = false } + }, [snapshot.mode, snapshot.userId, store]) + + const coordinator = network !== null + const changed = RULES.some((rule) => draft[rule.key] !== state.rules[rule.key]) || draft.stamps_enabled !== state.rules.stamps_enabled + const save = async () => { + setBusy(true) + const patch: Partial = { stamps_enabled: draft.stamps_enabled } + for (const rule of RULES) patch[rule.key] = draft[rule.key] + const result = await store.saveRules(patch) + setBusy(false) + toast(result.error ?? t('adv.rulesSaved')) + } + + return
    +

    {t('adv.rulesCopy')}

    + {coordinator && {t('adv.rulesCoordinator')}} +
      + {RULES.map((rule) =>
    • + {t(`rule.${rule.key}` as RunKey)} + {coordinator + ? setDraft({ ...draft, [rule.key]: value })} /> + : {state.rules[rule.key]}} +
    • )} +
    • + {coordinator + ? setDraft({ ...draft, stamps_enabled: value })} label={t('rule.stamps_enabled')} /> + : <>{t('rule.stamps_enabled')}{state.rules.stamps_enabled ? '✓' : '–'}} +
    • +
    + {coordinator && } + + {network &&
    +

    {t('adv.network')}

    +

    {t('adv.networkCopy')}

    +

    {t('net.enrolled', { count: network.enrolled })} · {t('net.open', { count: network.open_runs })}

    +
    + + + + + + + {[...network.weeks].reverse().map((week) => + + + )} + +
    {t('net.week')}{t('net.runs')}{t('net.tough')}{t('net.families')}{t('net.people')}{t('net.seeds')}
    {shortDate(lang, `${week.week_start}T12:00:00`)}{week.runs}{week.tough_runs}{week.families}{week.people}{week.seeds}
    +
    +
    } +
    +} diff --git a/yuhm/src/runs/AdvancedRun.tsx b/yuhm/src/runs/AdvancedRun.tsx new file mode 100644 index 00000000..9cd25c70 --- /dev/null +++ b/yuhm/src/runs/AdvancedRun.tsx @@ -0,0 +1,153 @@ +/** + * Advanced controls for one run: change it, reopen it, cancel or delete it, + * set any check-off by hand, edit every portion in a grid, and read what was + * done and when. + */ +import { useEffect, useState } from 'react' +import { Pencil, RotateCcw, Trash2 } from 'lucide-react' +import { useRoute } from '../router' +import { useRuns } from './context' +import { clock, dayLabel, runHref, windowLabel } from './helpers' +import { itemQty, type ContactState, type DeliveryState, type Run, type RunEvent } from './model' +import { partsOf } from './portioning' +import { RunDetailsSheet } from './RunDetails' +import { hasRunKey, runText, useRunText, type RunKey } from './runStrings' +import { Banner, Button } from './ui' + +const CONTACT_STATES: ContactState[] = ['to_ask', 'asked', 'confirmed', 'declined', 'no_answer'] +const DELIVERY_STATES: DeliveryState[] = ['pending', 'packed', 'on_the_way', 'delivered', 'missed'] + +function ActivityLog({ run }: { run: Run }) { + const { t, lang } = useRunText() + const { snapshot, store, now } = useRuns() + const [events, setEvents] = useState(null) + const account = snapshot.mode === 'account' + + useEffect(() => { + if (!account) return + let active = true + store.loadRunEvents(run.id).then((loaded) => { if (active) setEvents(loaded) }).catch(() => { if (active) setEvents(null) }) + return () => { active = false } + }, [account, store, run.id, snapshot.pending]) + + if (!account || events === null) return

    {t('adv.activityOnline')}

    + if (!events.length) return

    {t('adv.activityEmpty')}

    + const words = (event: RunEvent): string => { + const key = `log.${event.op}` + if (!hasRunKey(key)) return event.op + const summary = event.summary as Record + const state = typeof summary.state === 'string' && hasRunKey(`chip.${summary.state}`) ? runText(lang, `chip.${summary.state}` as RunKey) : '' + const to = typeof summary.to === 'string' && hasRunKey(`status.${summary.to}`) ? runText(lang, `status.${summary.to}` as RunKey) : '' + const check = typeof summary.check === 'string' && hasRunKey(`check.${summary.check}`) ? runText(lang, `check.${summary.check}` as RunKey) : '' + return t(key, { ...summary, state, to, check }) + } + return
      + {events.map((event, index) =>
    1. + + {words(event)} +
    2. )} +
    +} + +export function AdvancedRun({ run }: { run: Run }) { + const { t, lang } = useRunText() + const { state, dispatch, now, toast } = useRuns() + const { navigate } = useRoute() + const [editing, setEditing] = useState(false) + const [deleting, setDeleting] = useState(false) + const [reason, setReason] = useState('') + const parts = partsOf(state, run.id) + const open = run.status === 'planned' || run.status === 'pickup' || run.status === 'delivering' + + const remove = () => { + if (!dispatch({ op: 'run.delete', id: run.id }).error) { toast(t('toast.deleted')); navigate(runHref({ tab: 'advanced' }), { replace: true }) } + } + const quantity = (stopId: string, itemId: string): number => + parts.portions.find((portion) => portion.stop_id === stopId && portion.item_id === itemId)?.quantity ?? 0 + + return
    +

    {run.source_name} · {windowLabel(lang, run, now)} · {t(`status.${run.status}` as RunKey)}

    + +
    + {open && } + {run.status === 'completed' && } + {run.status === 'cancelled' && } + {open && + setReason(event.target.value)} /> + + } +
    + + {open && parts.stops.length > 0 &&
    +

    {t('adv.states')}

    +

    {t('adv.statesHint')}

    +
    + + + + {parts.stops.map((stop) => + + + + )} + +
    {t('tabs.families')}{t('adv.contactState')}{t('adv.deliveryState')}
    {stop.label}
    +
    +
    } + + {parts.items.length > 0 && parts.stops.length > 0 &&
    +

    {t('adv.grid')}

    +

    {t('adv.gridHint')}

    +
    + + + + {parts.stops.map((stop) => )} + + + + + {parts.items.map((item) => { + const given = parts.stops.reduce((sum, stop) => sum + (stop.contact_state === 'declined' ? 0 : quantity(stop.id, item.id)), 0) + const left = Math.round((itemQty(item) - given) * 10) / 10 + return + + {parts.stops.map((stop) => )} + + + + })} + +
    {t('adv.gridItem')}{stop.bag ?? ''} {stop.label}{t('adv.gridHave')}{t('adv.gridLeft')}
    {item.name} + { const next = Number(event.target.value); if (Number.isFinite(next) && next >= 0) dispatch({ op: 'portion.set', run_id: run.id, stop_id: stop.id, item_id: item.id, quantity: next, locked: true }) }} /> + {itemQty(item)}{left}
    +
    +
    } + +
    +

    {t('adv.activity')}

    + +
    + +
    + {deleting + ? + {t('adv.deleteAsk')} +

    {t('adv.deleteCopy')}

    +
    + + +
    +
    + : } +
    + + {editing && setEditing(false)} />} +
    +} diff --git a/yuhm/src/runs/AdvancedTab.tsx b/yuhm/src/runs/AdvancedTab.tsx new file mode 100644 index 00000000..91c537b4 --- /dev/null +++ b/yuhm/src/runs/AdvancedTab.tsx @@ -0,0 +1,188 @@ +/** + * Advanced: everything the run sheet decides on its own, in one place to + * change it. Timing and reminders, how food is shared out, the wording of + * every message, one run's controls, the data on this phone, and how seeds + * are counted. + */ +import { useState } from 'react' +import { CalendarPlus, Download, ShieldCheck, Trash2 } from 'lucide-react' +import type { Lang } from '../i18n' +import { AdvancedRules } from './AdvancedRules' +import { AdvancedRun } from './AdvancedRun' +import { useRuns } from './context' +import { download, windowLabel } from './helpers' +import { DEFAULT_TEMPLATES, TEMPLATE_KEYS, buildMessage } from './messages' +import { householdSize, type Prefs, type Run, type TemplateKey } from './model' +import { useCalendarDownload } from './NextUp' +import { currentRun } from './reminders' +import { useRunText, type RunKey } from './runStrings' +import { Banner, Button, Eyebrow, Field, Segmented, Stepper, Switch } from './ui' + +function CalendarButton({ run }: { run: Run }) { + const { t } = useRunText() + const save = useCalendarDownload(run) + return
    + +

    {t('adv.calendarHint')}

    +
    +} + +const csvCell = (value: string | number | null | undefined): string => `"${String(value ?? '').replace(/"/g, '""')}"` + +export function AdvancedTab({ runId }: { runId: string | null }) { + const { t, lang } = useRunText() + const { snapshot, state, prefs, dispatch, store, now, runnerName, toast } = useRuns() + const [messageLang, setMessageLang] = useState(lang) + const [erasing, setErasing] = useState(false) + const [alertsBlocked, setAlertsBlocked] = useState(false) + const runs = Object.values(state.runs).sort((a, b) => Date.parse(b.pickup_starts_at) - Date.parse(a.pickup_starts_at)) + const [picked, setPicked] = useState(runId) + const run = (picked && state.runs[picked]) || currentRun(state, now) || runs[0] || null + const save = (patch: Partial) => { dispatch({ op: 'settings.save', prefs: patch }) } + + const setAlerts = async (on: boolean) => { + if (!on) { save({ alerts: false }); return } + if (typeof Notification === 'undefined') { setAlertsBlocked(true); return } + const permission = Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission() + setAlertsBlocked(permission !== 'granted') + if (permission === 'granted') save({ alerts: true }) + } + + const setTemplate = (key: TemplateKey, text: string | null) => { + const templates = { ...prefs.templates, [key]: { ...prefs.templates[key] } } + if (text === null || !text.trim() || text.trim() === DEFAULT_TEMPLATES[key][messageLang]) delete templates[key]![messageLang] + else templates[key]![messageLang] = text.trim() + save({ templates }) + } + + const sampleRun = run ?? { source_name: 'Oak Hill Baptist', pickup_starts_at: new Date(now.getTime() + 86400000).toISOString(), pickup_ends_at: new Date(now.getTime() + 86400000 + 1800000).toISOString() } + const preview = (key: TemplateKey): string => buildMessage(key, { + name: 'Rosa', language: messageLang, run: sampleRun, lines: [], runnerName, templates: prefs.templates, now, + }).text + + const exportJson = () => { + const { households, runs: allRuns, items, stops, portions, settings } = state + download('yuhm-run-sheet.json', JSON.stringify({ exported_at: now.toISOString(), households: Object.values(households), runs: Object.values(allRuns), items: Object.values(items), stops: Object.values(stops), portions: Object.values(portions), settings }, null, 2), 'application/json') + } + const exportCsv = () => { + const header = ['name', 'people', 'language', 'reach', 'contact', 'place', 'neighborhood', 'allergies', 'does_not_eat', 'never_needs', 'especially_needs', 'kitchen', 'notes'] + const rows = Object.values(state.households).filter((household) => !household.is_practice).map((household) => [ + household.label, householdSize(household), household.language, household.contact_method, household.contact_value, household.place, household.neighborhood, + household.allergies.join('; '), household.avoids.join('; '), household.never_needs.join('; '), household.wants.join('; '), household.kitchen.join('; '), household.notes, + ].map(csvCell).join(',')) + download('yuhm-families.csv', [header.join(','), ...rows].join('\r\n'), 'text/csv') + } + + return
    +
    + {t('run.name')} +

    {t('adv.title')}

    +

    {t('adv.copy')}

    +
    + +
    + {t('adv.timing')} +
    + + save({ contactLeadHours: Number(value) })} + options={[6, 12, 24, 48].map((hours) => ({ value: String(hours), label: t('adv.hours', { count: hours }) }))} /> + + + save({ followUpMinutes: Number(value) })} + options={[60, 120, 240].map((minutes) => ({ value: String(minutes), label: minutes === 60 ? t('adv.hour') : t('adv.hours', { count: minutes / 60 }) }))} /> + +
    + {t('adv.travel')} + save({ travelMinutes: value })} /> +
    + + save({ coldMinutes: Number(value) })} + options={[60, 90, 120].map((minutes) => ({ value: String(minutes), label: t('adv.minutes', { count: minutes }) }))} /> + + + {alertsBlocked &&

    {t('adv.alertsBlocked')}

    } + save({ quietHours: value })} label={t('adv.quiet')} disabled={!prefs.alerts} /> + {run && (run.status === 'planned' || run.status === 'pickup') && } +
    +
    + +
    + {t('adv.sharing')} +
    + + save({ splitBy: value })} + options={[{ value: 'people', label: t('adv.splitPeople') }, { value: 'household', label: t('adv.splitHousehold') }]} /> + +
    + {t('adv.reserve')} + save({ reserveEach: value })} /> +
    + save({ onlyConfirmed: value })} label={t('adv.onlyConfirmed')} /> + save({ respectWants: value })} label={t('adv.respectWants')} /> +
    +
    + +
    + {t('adv.messages')} +
    + + { const value = event.target.value.trim(); if (value !== (prefs.myName ?? '')) save({ myName: value || null }) }} /> + + +

    {t('adv.placeholders')}

    + {TEMPLATE_KEYS.map((key) => { + const own = prefs.templates[key]?.[messageLang] + return
    + +