diff --git a/web/e2e/landing.spec.ts b/web/e2e/landing.spec.ts index 7e4e3c7..ec704ea 100644 --- a/web/e2e/landing.spec.ts +++ b/web/e2e/landing.spec.ts @@ -94,15 +94,21 @@ test.describe('the homepage (#145)', () => { }); test.describe('the homepage’s hero (#151)', () => { - /** The element around the heading that sways: its inline transform. */ + /** The badge's transform, as the lanyard sways it (#174). */ const swayOf = (page: import('@playwright/test').Page) => - page.evaluate(() => { - let element = document.querySelector('main h1'); - while (element && !element.classList.contains('origin-top')) { - element = element.parentElement; - } - return element?.style.transform ?? null; - }); + page.evaluate( + () => + document.querySelector('main [data-swing]')?.style + .transform ?? null + ); + + /** The lanyard's tab's shift, as it sways with the badge. */ + const tabOf = (page: import('@playwright/test').Page) => + page.evaluate( + () => + document.querySelector('main [data-tab]')?.getAttribute('transform') ?? + null + ); /** Sweeps the mouse right across the badge, in small steps. */ async function sweep(page: import('@playwright/test').Page) { @@ -151,21 +157,28 @@ test.describe('the homepage’s hero (#151)', () => { }); } - test('sways the badge with the mouse, then lets it settle', async ({ + test('swings in, settles, then sways with the mouse and settles (#174)', async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto('/'); await expect(page.getByRole('heading', { name: HEADING })).toBeVisible(); - expect(await swayOf(page)).toBe(''); + // It arrives swinging, then hangs straight within about six seconds. + expect(await swayOf(page)).toMatch(/rotate\(/); + await expect.poll(() => swayOf(page), { timeout: 9000 }).toBe(''); await sweep(page); await expect .poll(() => swayOf(page), { timeout: 2000 }) - .toMatch(/^rotate\(-?[\d.]+deg\)$/); + .toMatch(/^translateX\(-?[\d.]+px\) rotate\(-?[\d.]+deg\)$/); + // The lanyard sways with it, a little. + expect(await tabOf(page)).toMatch(/^translate\(-?[\d.]+ 0\)$/); // A few degrees at most, and still again after about six seconds. - const angle = Number(/-?[\d.]+/.exec((await swayOf(page)) ?? '')?.[0]); + const angle = Number( + /rotate\((-?[\d.]+)/.exec((await swayOf(page)) ?? '')?.[1] + ); expect(Math.abs(angle)).toBeLessThan(5); await expect.poll(() => swayOf(page), { timeout: 9000 }).toBe(''); + expect(await tabOf(page)).toBeNull(); }); test('keeps the badge still with reduced motion', async ({ page }) => { @@ -173,8 +186,122 @@ test.describe('the homepage’s hero (#151)', () => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto('/'); await expect(page.getByRole('heading', { name: HEADING })).toBeVisible(); + // No swing as it arrives, and none for the mouse. + expect(await swayOf(page)).toBe(''); await sweep(page); await page.waitForTimeout(300); expect(await swayOf(page)).toBe(''); }); }); + +test.describe('the homepage badge, turned over to sign in (#175)', () => { + /** The badge's two faces, front then back. */ + const faces = (page: import('@playwright/test').Page) => + page.locator('main [data-face] > [data-sleeve]'); + + test('turns over to the form, at the same size, and back again', async ({ + page, + }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto('/'); + const turning = page.locator('main [data-face]'); + await expect(turning).toHaveAttribute('data-face', 'front'); + // It turns, rather than jumping. + expect( + await turning.evaluate( + (element) => getComputedStyle(element).transitionDuration + ) + ).toBe('0.7s'); + + await page + .getByRole('banner') + .getByRole('link', { name: 'Sign in' }) + .click(); + await expect(page).toHaveURL('/sign-in'); + await expect(turning).toHaveAttribute('data-face', 'back'); + await expect(page.getByRole('heading', SIGN_IN)).toBeFocused(); + await page.waitForTimeout(800); + // Front and back are one size, so the turn is convincing. + const [front, back] = await Promise.all([ + faces(page).nth(0).boundingBox(), + faces(page).nth(1).boundingBox(), + ]); + expect(back?.width).toBeCloseTo(front?.width ?? 0, 0); + expect(back?.height).toBeCloseTo(front?.height ?? 0, 0); + await expect( + page.getByRole('combobox', { name: 'Your handle' }) + ).toBeVisible(); + await expect(page.getByRole('heading', { name: HEADING })).toHaveCount(0); + + await page.goBack(); + await expect(page).toHaveURL('/'); + await expect(turning).toHaveAttribute('data-face', 'front'); + await expect(page.getByRole('heading', { name: HEADING })).toBeFocused(); + await expect(page.getByRole('combobox')).toHaveCount(0); + }); + + test('turns over at once with reduced motion', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.goto('/sign-in'); + const turning = page.locator('main [data-face]'); + await expect(turning).toHaveAttribute('data-face', 'back'); + expect( + await turning.evaluate( + (element) => getComputedStyle(element).transitionDuration + ) + ).toBe('0s'); + }); + + test('shows every suggestion for a handle, past the badge’s edge (#176)', async ({ + page, + }) => { + await page.route( + 'https://public.api.bsky.app/xrpc/app.bsky.actor.searchActorsTypeahead**', + (route) => + route.fulfill({ + json: { + actors: Array.from({ length: 8 }, (_, index) => ({ + did: `did:plc:suggestion${index}aaaaaaaaaaaaaa`, + handle: `ren${index}.bsky.social`, + displayName: `Ren ${index}`, + })), + }, + }) + ); + // On a phone the form is at the badge's foot, so the list hangs out. + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto('/sign-in'); + await page.getByRole('combobox', { name: 'Your handle' }).fill('ren'); + const listbox = page.getByRole('listbox'); + await expect(listbox.getByRole('option')).toHaveCount(8); + await listbox.evaluate((element) => + element.scrollIntoView({ block: 'end' }) + ); + // Nothing it sits in clips it, however tall it grows. + const clippers = await listbox.evaluate((element) => { + const found: string[] = []; + for ( + let parent = element.parentElement; + parent && parent !== document.body; + parent = parent.parentElement + ) { + const { overflowY } = getComputedStyle(parent); + if (overflowY !== 'visible') + found.push(`${parent.tagName}: ${overflowY}`); + } + return found; + }); + expect(clippers).toEqual([]); + const box = await listbox.boundingBox(); + // Its foot is its own: nothing covers it. + const foot = await page.evaluate( + ({ x, y }) => + Boolean(document.elementFromPoint(x, y)?.closest('[role="listbox"]')), + { + x: (box?.x ?? 0) + (box?.width ?? 0) / 2, + y: (box?.y ?? 0) + (box?.height ?? 0) - 4, + } + ); + expect(foot).toBe(true); + }); +}); diff --git a/web/e2e/qr.spec.ts b/web/e2e/qr.spec.ts index b440f4a..e5c68de 100644 --- a/web/e2e/qr.spec.ts +++ b/web/e2e/qr.spec.ts @@ -219,6 +219,34 @@ test.describe('QR sheet', () => { await expect(sheet).toBeHidden(); }); + test('sways with the mouse, as the homepage’s does, then settles (#174)', async ({ + page, + }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto('/lanyard'); + await page.getByRole('link', { name: 'Share' }).click(); + const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); + const sleeve = sheet.locator('[data-sleeve]'); + // Straight as it opens: the code is there to be scanned. + expect(await sleeve.evaluate((element) => element.style.transform)).toBe( + '' + ); + const box = await sleeve.boundingBox(); + const y = (box?.y ?? 0) + (box?.height ?? 0) * 0.7; + await page.mouse.move((box?.x ?? 0) + 10, y); + await page.mouse.move((box?.x ?? 0) + (box?.width ?? 0) - 10, y, { + steps: 12, + }); + await expect + .poll(() => sleeve.evaluate((element) => element.style.transform)) + .toMatch(/rotate\(/); + await expect + .poll(() => sleeve.evaluate((element) => element.style.transform), { + timeout: 9000, + }) + .toBe(''); + }); + test('stays black on white in dark mode', async ({ page }) => { await page.emulateMedia({ colorScheme: 'dark' }); await page.goto('/lanyard'); diff --git a/web/e2e/settings.spec.ts b/web/e2e/settings.spec.ts index dc02a01..cf5be20 100644 --- a/web/e2e/settings.spec.ts +++ b/web/e2e/settings.spec.ts @@ -1,4 +1,5 @@ import { expect, test } from './fixtures'; +import { ADA, mockPerson, signIn } from './mocks'; test('sends signed-out visitors to sign in first', async ({ page }) => { await page.goto('/settings'); @@ -8,3 +9,18 @@ test('sends signed-out visitors to sign in first', async ({ page }) => { ).toBeVisible(); await expect(page.getByRole('button', { name: 'Sign in' })).toBeVisible(); }); + +test('signing out goes to the homepage (#172)', async ({ page }) => { + await mockPerson(page); + await signIn(page, { did: ADA.did, scope: 'atproto transition:generic' }); + await page.goto('/settings'); + await page.getByRole('button', { name: 'Sign out' }).click(); + await expect(page.getByText('Signed out')).toBeVisible(); + await expect(page).toHaveURL('/'); + await expect( + page.getByRole('heading', { level: 1, name: 'Welcome to Lanyards' }) + ).toBeVisible(); + await expect( + page.getByRole('banner').getByRole('link', { name: 'Sign in' }) + ).toBeVisible(); +}); diff --git a/web/src/app/customise.test.tsx b/web/src/app/customise.test.tsx index 90699cf..8dec102 100644 --- a/web/src/app/customise.test.tsx +++ b/web/src/app/customise.test.tsx @@ -189,9 +189,14 @@ describe('//edit', { timeout: 20_000 }, () => { expect(grounds()).toHaveLength(1); const [ground] = grounds(); expect(ground).toContainElement(region); - expect(ground).toContainElement( - screen.getByRole('heading', { level: 1, name: 'Customise your lanyard' }) - ); + const heading = screen.getByRole('heading', { + level: 1, + name: 'Customise your lanyard', + }); + expect(ground).toContainElement(heading); + // For screen readers only: the lanyard hangs from the canvas's top + // edge, and the header already says Customise (#173). + expect(heading).toHaveClass('sr-only'); }); it('shows only its own header, with the customiser’s actions', async () => { diff --git a/web/src/app/landing.test.tsx b/web/src/app/landing.test.tsx index d8b9a36..ab2a417 100644 --- a/web/src/app/landing.test.tsx +++ b/web/src/app/landing.test.tsx @@ -1,4 +1,5 @@ -import { screen, within } from '@testing-library/react'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -48,7 +49,11 @@ describe('landing page', () => { expect( await screen.findByRole('heading', { name: 'Welcome to Lanyards' }) ).toBeInTheDocument(); + // The form is on the badge's back, out of reach until it turns (#175). expect(screen.queryByRole('combobox')).toBeNull(); + expect( + screen.getByRole('combobox', { hidden: true }).closest('[inert]') + ).not.toBeNull(); expect(screen.queryByRole('button', { name: 'Sign in' })).toBeNull(); expect(document.title).toBe( 'Researcher profiles on the AT Protocol · Lanyards' @@ -88,6 +93,45 @@ describe('landing page', () => { expect(document.title).toBe('Sign in · Lanyards'); }); + it('turns the homepage badge over to sign in, and back (#175)', async () => { + vi.mocked(useSession).mockReturnValue({ + status: 'signedOut', + signOut: vi.fn(), + refresh: vi.fn(), + }); + const { router } = renderRoute('/'); + const welcome = await screen.findByRole('heading', { + name: 'Welcome to Lanyards', + }); + // One badge, two faces: the sign-in face is behind, out of reach. + const signIn = () => + screen.getByRole('heading', { level: 1, name: 'Sign in', hidden: true }); + expect(welcome.closest('[inert]')).toBeNull(); + expect(signIn().closest('[inert]')).not.toBeNull(); + + const banner = screen.getByRole('banner'); + await userEvent.click( + await within(banner).findByRole('link', { name: 'Sign in' }) + ); + await waitForRoute(router, '/sign-in'); + // The same badge, turned over: nothing was rebuilt. + await waitFor(() => expect(welcome.closest('[inert]')).not.toBeNull()); + expect(welcome).toBeInTheDocument(); + expect(signIn().closest('[inert]')).toBeNull(); + expect(signIn()).toHaveFocus(); + expect(document.title).toBe('Sign in · Lanyards'); + expect(within(banner).queryByRole('link', { name: 'Sign in' })).toBeNull(); + + router.history.back(); + await waitForRoute(router, '/'); + await waitFor(() => expect(welcome.closest('[inert]')).toBeNull()); + expect(signIn().closest('[inert]')).not.toBeNull(); + expect(welcome).toHaveFocus(); + expect(document.title).toBe( + 'Researcher profiles on the AT Protocol · Lanyards' + ); + }); + // Links from before the sign-in page had its own address (#157). it('sends /?returnTo= on to /sign-in, keeping where to return', async () => { vi.mocked(useSession).mockReturnValue({ diff --git a/web/src/features/account/components/AccountCard/AccountCard.test.tsx b/web/src/features/account/components/AccountCard/AccountCard.test.tsx index e97a1ed..6adb4b0 100644 --- a/web/src/features/account/components/AccountCard/AccountCard.test.tsx +++ b/web/src/features/account/components/AccountCard/AccountCard.test.tsx @@ -6,7 +6,7 @@ import { useSession } from '@/features/auth/session/useSession'; import { useProfile } from '@/lib/atproto/useProfile'; import { expectNoAxeViolations } from '@/test/axe'; import { ALICE } from '@/test/fixtures'; -import { renderWithProviders } from '@/test/render'; +import { renderInRouter, waitForRoute } from '@/test/router'; import { AccountCard } from './AccountCard'; @@ -31,31 +31,47 @@ const signedInAs = (profile: object | undefined, status = 'success') => { }; describe('AccountCard', () => { - it('shows who is signed in', () => { + it('shows who is signed in', async () => { signedInAs(ALICE); - renderWithProviders(); - expect(screen.getByText('Alice')).toBeInTheDocument(); + renderInRouter(, '/settings'); + expect(await screen.findByText('Alice')).toBeInTheDocument(); expect(screen.getByText('@alice.bsky.social')).toBeInTheDocument(); }); - it('falls back to the handle when there is no display name', () => { + it('falls back to the handle when there is no display name', async () => { signedInAs({ did: ALICE.did, handle: ALICE.handle }); - renderWithProviders(); - expect(screen.getByText('alice.bsky.social')).toBeInTheDocument(); + renderInRouter(, '/settings'); + expect(await screen.findByText('alice.bsky.social')).toBeInTheDocument(); + }); + + it('signs out to the homepage (#172)', async () => { + signedInAs(ALICE); + // The session ends, then calls back to say where to go. + signOut.mockImplementation(async (leave?: () => Promise) => { + await leave?.(); + }); + const { router } = renderInRouter(, '/settings'); + await userEvent.click( + await screen.findByRole('button', { name: 'Sign out' }) + ); + expect(signOut).toHaveBeenCalledWith(expect.any(Function)); + await waitForRoute(router, '/'); }); it('signs out', async () => { signedInAs(ALICE); - renderWithProviders(); - await userEvent.click(screen.getByRole('button', { name: 'Sign out' })); + renderInRouter(, '/settings'); + await userEvent.click( + await screen.findByRole('button', { name: 'Sign out' }) + ); expect(signOut).toHaveBeenCalled(); }); it('still offers sign-out when the profile cannot load', async () => { signedInAs(undefined, 'error'); - renderWithProviders(); + renderInRouter(, '/settings'); expect( - screen.getByText("We couldn't load your profile.") + await screen.findByText("We couldn't load your profile.") ).toBeInTheDocument(); await userEvent.click(screen.getByRole('button', { name: 'Sign out' })); expect(signOut).toHaveBeenCalled(); @@ -63,7 +79,8 @@ describe('AccountCard', () => { it('has no axe violations', async () => { signedInAs(ALICE); - const { container } = renderWithProviders(); + const { container } = renderInRouter(, '/settings'); + await screen.findByText('Alice'); await expectNoAxeViolations(container); }); }); diff --git a/web/src/features/account/components/AccountCard/AccountCard.tsx b/web/src/features/account/components/AccountCard/AccountCard.tsx index 4b778ce..6242e3e 100644 --- a/web/src/features/account/components/AccountCard/AccountCard.tsx +++ b/web/src/features/account/components/AccountCard/AccountCard.tsx @@ -1,4 +1,5 @@ import { useLingui } from '@lingui/react/macro'; +import { useRouter } from '@tanstack/react-router'; import { Button } from '@/components/Button/Button'; import { useSession } from '@/features/auth/session/useSession'; @@ -11,6 +12,7 @@ import type { AccountCardProps } from './AccountCard.types'; export function AccountCard({ className }: AccountCardProps) { const { t } = useLingui(); const session = useSession(); + const router = useRouter(); const did = session.status === 'signedIn' ? session.session.did : undefined; const profile = useProfile(did); @@ -39,7 +41,11 @@ export function AccountCard({ className }: AccountCardProps) { : t`Loading your profile…`}

)} - diff --git a/web/src/features/auth/components/LandingPage/LandingPage.tsx b/web/src/features/auth/components/LandingPage/LandingPage.tsx index de1b746..b07992b 100644 --- a/web/src/features/auth/components/LandingPage/LandingPage.tsx +++ b/web/src/features/auth/components/LandingPage/LandingPage.tsx @@ -1,29 +1,41 @@ import { useLingui } from '@lingui/react/macro'; -import { useRouter } from '@tanstack/react-router'; +import { useMatch, useRouter } from '@tanstack/react-router'; import { useEffect } from 'react'; import { useSession } from '@/features/auth/session/useSession'; import { HomePage } from '@/features/home/components/HomePage/HomePage'; import { useDocumentTitle } from '@/hooks/useDocumentTitle'; +import { safeReturnTo } from '@/lib/atproto/oauthConfig'; import { SIGNED_IN_HOME } from './LandingPage.constants'; import type { LandingPageProps } from './LandingPage.types'; /** - * `/`: the homepage for people who aren't signed in (#145), which points - * to the sign-in page (#157); signed in, it sends people to their lanyard. + * `/` and `/sign-in` (#157, #175): one page, so it stays put between them. + * At `/` its badge faces out, the homepage for people who aren't signed in + * (#145); at `/sign-in` it's turned over to the sign-in form on its back. + * Signed in, it sends people on: to where they were going, or their + * lanyard. */ export function LandingPage({ className }: LandingPageProps) { const { t } = useLingui(); const session = useSession(); const router = useRouter(); - useDocumentTitle(t`Researcher profiles on the AT Protocol`); + const signIn = useMatch({ from: '/_home/sign-in', shouldThrow: false }); + const face = signIn ? 'back' : 'front'; + useDocumentTitle( + face === 'back' ? t`Sign in` : t`Researcher profiles on the AT Protocol` + ); + const safe = safeReturnTo(signIn?.search.returnTo ?? '/'); + const destination = safe === '/' ? SIGNED_IN_HOME : safe; const signedIn = session.status === 'signedIn'; useEffect(() => { - if (signedIn) router.history.replace(SIGNED_IN_HOME); - }, [signedIn, router]); + // destination is a validated same-origin path, which may not be a + // typed route, so use the history directly. + if (signedIn) router.history.replace(destination); + }, [signedIn, destination, router]); if (signedIn) return null; - return ; + return ; } diff --git a/web/src/features/auth/session/SessionProvider.test.tsx b/web/src/features/auth/session/SessionProvider.test.tsx index d25d534..01fd316 100644 --- a/web/src/features/auth/session/SessionProvider.test.tsx +++ b/web/src/features/auth/session/SessionProvider.test.tsx @@ -26,7 +26,7 @@ vi.mock('@/components/Toaster/notify', () => ({ const session = { did: 'did:plc:ewvi7nxzyoun6zhxrhs64oiz' } as never; -function Probe() { +function Probe({ leave }: { leave?: () => Promise }) { const session = useSession(); return ( <> @@ -34,6 +34,9 @@ function Probe() { + @@ -41,10 +44,10 @@ function Probe() { ); } -const renderProvider = () => +const renderProvider = (leave?: () => Promise) => renderWithProviders( - + ); @@ -105,6 +108,51 @@ describe('SessionProvider', () => { expect(track).toHaveBeenCalledWith('signed_out'); }); + it('moves on before anyone is shown as signed out (#172)', async () => { + vi.mocked(restoreSession).mockResolvedValue({ + status: 'restored', + session, + }); + vi.mocked(signOut).mockResolvedValue(undefined); + const seen: string[] = []; + // Where to go next, once the session has ended. Meanwhile nobody is + // signed in or out, so a page that needs a session doesn't send + // people off to sign in again. + const leave = vi.fn(async () => { + await screen.findByText('status: loading'); + seen.push( + vi.mocked(signOut).mock.calls.length ? 'ended' : 'still signed in' + ); + }); + renderProvider(leave); + await screen.findByText('status: signedIn'); + await userEvent.click( + screen.getByRole('button', { name: 'Sign out and leave' }) + ); + expect(await screen.findByText('status: signedOut')).toBeInTheDocument(); + expect(leave).toHaveBeenCalledTimes(1); + expect(seen).toEqual(['ended']); + expect(notify.success).toHaveBeenCalledWith('Signed out'); + }); + + it('signs out even if moving on fails', async () => { + vi.mocked(restoreSession).mockResolvedValue({ + status: 'restored', + session, + }); + vi.mocked(signOut).mockResolvedValue(undefined); + const failure = new Error('navigation failed'); + renderProvider(() => Promise.reject(failure)); + await screen.findByText('status: signedIn'); + await userEvent.click( + screen.getByRole('button', { name: 'Sign out and leave' }) + ); + expect(await screen.findByText('status: signedOut')).toBeInTheDocument(); + expect(captureError).toHaveBeenCalledWith(failure, { + source: 'sign-out-leave', + }); + }); + it('refresh() picks up a session stored after sign-in', async () => { vi.mocked(restoreSession).mockResolvedValueOnce({ status: 'none' }); renderProvider(); diff --git a/web/src/features/auth/session/SessionProvider.tsx b/web/src/features/auth/session/SessionProvider.tsx index 136b6e1..de81130 100644 --- a/web/src/features/auth/session/SessionProvider.tsx +++ b/web/src/features/auth/session/SessionProvider.tsx @@ -71,14 +71,25 @@ export function SessionProvider({ children }: SessionProviderProps) { if (started === generation.current) apply(result); }, [apply]); - const signOut = useCallback(async () => { - if (state.status !== 'signedIn') return; - generation.current++; - await endSession(state.session); - setState({ status: 'signedOut' }); - track('signed_out'); - notify.success(t`Signed out`); - }, [state, t]); + const signOut = useCallback( + async (leave?: () => Promise) => { + if (state.status !== 'signedIn') return; + generation.current++; + // Neither signed in nor out until `leave` has moved on. + setState({ status: 'loading' }); + await endSession(state.session); + try { + await leave?.(); + } catch (error) { + // Wherever they are, they're signed out all the same. + captureError(error, { source: 'sign-out-leave' }); + } + setState({ status: 'signedOut' }); + track('signed_out'); + notify.success(t`Signed out`); + }, + [state, t] + ); const value = useMemo( () => ({ ...state, signOut, refresh }), diff --git a/web/src/features/auth/session/SessionProvider.types.ts b/web/src/features/auth/session/SessionProvider.types.ts index 5b14ad4..122323b 100644 --- a/web/src/features/auth/session/SessionProvider.types.ts +++ b/web/src/features/auth/session/SessionProvider.types.ts @@ -8,7 +8,13 @@ export type SessionState = | { status: 'signedIn'; session: SessionHandle }; export type SessionContextValue = SessionState & { - signOut(): Promise; + /** + * Ends the session. `leave`, if given, runs once it has ended and before + * anyone is shown as signed out: say where to go next there (#172), so + * a page that needs a session never sends people off to sign in again. + * Meanwhile the status is `loading`. + */ + signOut(leave?: () => Promise): Promise; /** Re-reads the stored session, e.g. right after the OAuth callback. */ refresh(): Promise; }; diff --git a/web/src/features/home/components/HomeBadge/HomeBadge.styles.ts b/web/src/features/home/components/HomeBadge/HomeBadge.styles.ts index c50bb58..f360236 100644 --- a/web/src/features/home/components/HomeBadge/HomeBadge.styles.ts +++ b/web/src/features/home/components/HomeBadge/HomeBadge.styles.ts @@ -3,31 +3,49 @@ // (#170), and built as a person's is (spec §7). The badge's tokens are the // same in light and dark. -/** Edge to edge: the ground the badge hangs on. Crops the straps' tops. */ +// Edge to edge: the ground the badge hangs on. It clips only sideways, so +// a badge swinging or turning never makes the page scroll, while the +// handle's suggestions on its back can hang below it (#176). export const stage = - 'flex w-full flex-col items-center overflow-hidden bg-qr-ground px-4 pb-14 md:px-8 md:pb-20'; + 'flex w-full flex-col items-center overflow-x-clip bg-qr-ground px-4 pb-14 md:px-8 md:pb-28'; export const hang = 'flex w-full max-w-[58rem] flex-col items-center'; // The clasp's hook ends in the sleeve's slot, a little below its top edge. +// Short enough that the badge sits in the middle of its blue (#174). export const ribbon = - 'relative z-10 h-32 w-auto shrink-0 translate-y-[1.125rem] md:h-52 md:translate-y-7'; + 'relative z-10 h-32 w-auto shrink-0 translate-y-[1.125rem] md:h-40 md:translate-y-7'; -// Tilted on its clasp from md up, after one swing as it arrives. A mouse -// sways it on the same clasp (#151), with a transform added to the tilt. -export const sleeve = - 'origin-top md:-rotate-[1.5deg] md:p-4 md:pt-12 md:motion-safe:animate-swing'; +// What sways (#174): straight at rest, turning on the clasp, in the +// middle of its slot. Over what follows, so the handle's suggestions on +// its back are too (#176). +export const swing = + 'relative z-10 w-full origin-[50%_1rem] [perspective:2400px] md:origin-[50%_1.5rem]'; + +// What turns over (#175): both faces in one grid cell, so they share a +// size. Its back is half a turn round. With reduced motion it turns at +// once. +export const turn = + 'grid w-full [transform-style:preserve-3d] data-[face=back]:[transform:rotateY(180deg)] motion-safe:transition-transform motion-safe:duration-700 motion-safe:ease-[cubic-bezier(0.45,0,0.2,1)]'; + +const face = + 'flex flex-col [backface-visibility:hidden] [grid-area:1/1] md:p-4 md:pt-12'; + +export const front = face; + +export const back = `${face} [transform:rotateY(180deg)]`; /** A bigger slot for the bigger sleeve. */ export const slot = 'md:top-4 md:h-4 md:w-24'; +/** It fills its face, however tall its back is. */ export const badge = - '@container flex w-full flex-col overflow-hidden rounded-sm bg-accent text-on-accent'; + '@container flex w-full flex-1 flex-col overflow-hidden rounded-sm bg-accent text-on-accent'; export const cover = 'relative h-30 @min-[40rem]:h-52'; export const field = - 'flex flex-col gap-4 px-5 pb-8 @min-[40rem]:px-12 @min-[40rem]:pb-12'; + 'flex flex-1 flex-col gap-4 px-5 pb-8 @min-[40rem]:px-12 @min-[40rem]:pb-12'; /** Half the logo's height: the other half overlaps the cover. */ export const logoBox = 'h-12 @min-[40rem]:h-17'; diff --git a/web/src/features/home/components/HomeBadge/HomeBadge.test.tsx b/web/src/features/home/components/HomeBadge/HomeBadge.test.tsx index a136362..1f13724 100644 --- a/web/src/features/home/components/HomeBadge/HomeBadge.test.tsx +++ b/web/src/features/home/components/HomeBadge/HomeBadge.test.tsx @@ -3,15 +3,19 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { renderWithProviders } from '@/test/render'; -import { SWAY_MEDIA } from '../../usePointerSway'; +import { ARRIVAL_MEDIA, SWAY_MEDIA } from '@/features/qr/useLanyardSway'; + import { HomeBadge } from './HomeBadge'; -/** A mouse and no request for less motion, or not. */ -function pointer(fine: boolean) { +/** A mouse and no request for less motion, or not; a wide screen, or not. */ +function pointer(fine: boolean, wide = false) { + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(930); + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(760); vi.spyOn(window, 'matchMedia').mockImplementation( (query: string) => ({ - matches: fine && query === SWAY_MEDIA, + matches: + (fine && query === SWAY_MEDIA) || (wide && query === ARRIVAL_MEDIA), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn(), @@ -26,10 +30,14 @@ function turned(heading: HTMLElement) { return element; } -/** A mouse sweeping right across the badge's heading. */ +/** A mouse sweeping right across the badge's heading, low on the badge. */ function sweep(heading: HTMLElement) { for (let x = 100; x <= 600; x += 50) { - fireEvent.pointerMove(heading, { pointerType: 'mouse', clientX: x }); + fireEvent.pointerMove(heading, { + pointerType: 'mouse', + clientX: x, + clientY: 400, + }); vi.advanceTimersByTime(16); } } @@ -66,15 +74,37 @@ describe('HomeBadge (#151)', () => { sweep(heading); const badge = turned(heading); expect(badge).not.toBeNull(); - // The badge turns in its sleeve, together, on the clasp (#170). - expect(badge).toHaveAttribute('data-sleeve'); - expect(badge?.style.transform).toMatch(/^rotate\(-[\d.]+deg\)$/); - // It turns about its clip, at the top, as the arrival swing does. - expect(badge?.className).toMatch(/(^|\s)origin-top(\s|$)/); + // The badge turns in its sleeve, together, on the clasp (#170, #174). + expect(badge?.querySelector('[data-sleeve]')).not.toBeNull(); + expect(badge?.style.transform).toMatch( + /^translateX\([\d.]+px\) rotate\(-[\d.]+deg\)$/ + ); vi.advanceTimersByTime(8000); expect(badge?.style.transform).toBe(''); }); + it('hangs straight at rest, as a real badge does (#174)', () => { + pointer(true); + renderWithProviders(); + const heading = screen.getByRole('heading', { level: 1 }); + const sleeve = heading.closest('[data-sleeve]'); + expect(sleeve?.style.transform).toBe(''); + expect(sleeve?.className).not.toMatch(/rotate-|animate-swing/); + }); + + it('swings in as it arrives on a wide screen, then settles (#174)', () => { + pointer(false, true); + vi.useFakeTimers({ + toFake: ['requestAnimationFrame', 'cancelAnimationFrame'], + }); + renderWithProviders(); + const heading = screen.getByRole('heading', { level: 1 }); + vi.advanceTimersByTime(100); + expect(turned(heading)?.querySelector('[data-sleeve]')).not.toBeNull(); + vi.advanceTimersByTime(8000); + expect(turned(heading)).toBeNull(); + }); + it('hangs still for touch, or with reduced motion', () => { pointer(false); vi.useFakeTimers({ @@ -85,4 +115,49 @@ describe('HomeBadge (#151)', () => { sweep(heading); expect(turned(heading)).toBeNull(); }); + + it('has a back, out of reach until it’s turned over (#175)', () => { + pointer(false); + const { rerender } = renderWithProviders( + Sign in here} /> + ); + const front = screen.getByRole('heading', { level: 1 }); + // Turned away, it's hidden from assistive technology too. + expect(screen.queryByRole('heading', { name: 'Sign in here' })).toBeNull(); + const back = screen.getByRole('heading', { + name: 'Sign in here', + hidden: true, + }); + const turning = front.closest('[data-face]'); + expect(turning).toHaveAttribute('data-face', 'front'); + expect(front.closest('[inert]')).toBeNull(); + expect(back.closest('[inert]')).not.toBeNull(); + // Both faces in one place, so they're always the same size. + expect(turning).toContainElement(back); + + rerender( + Sign in here} /> + ); + expect(turning).toHaveAttribute('data-face', 'back'); + expect(front.closest('[inert]')).not.toBeNull(); + expect(back.closest('[inert]')).toBeNull(); + expect( + screen.getByRole('heading', { name: 'Sign in here' }) + ).toBeInTheDocument(); + expect(screen.queryByRole('heading', { level: 1 })).toBeNull(); + }); + + it('stays straight and still while turned over (#175)', () => { + pointer(true, true); + vi.useFakeTimers({ + toFake: ['requestAnimationFrame', 'cancelAnimationFrame'], + }); + renderWithProviders( + Form

} /> + ); + const heading = screen.getByRole('heading', { level: 1, hidden: true }); + sweep(heading); + vi.advanceTimersByTime(100); + expect(turned(heading)).toBeNull(); + }); }); diff --git a/web/src/features/home/components/HomeBadge/HomeBadge.tsx b/web/src/features/home/components/HomeBadge/HomeBadge.tsx index 50e2dfd..62b1983 100644 --- a/web/src/features/home/components/HomeBadge/HomeBadge.tsx +++ b/web/src/features/home/components/HomeBadge/HomeBadge.tsx @@ -1,14 +1,14 @@ import { useLingui } from '@lingui/react/macro'; -import { useRef } from 'react'; +import { useState } from 'react'; import { CoverPattern } from '@/components/CoverPattern/CoverPattern'; import { Logo } from '@/components/Logo/Logo'; import { BadgeSleeve } from '@/features/qr/components/BadgeSleeve/BadgeSleeve'; import { LanyardRibbon } from '@/features/qr/components/LanyardRibbon/LanyardRibbon'; import { BRAND_PRINT } from '@/features/qr/components/LanyardRibbon/LanyardRibbon.constants'; +import { useLanyardSway } from '@/features/qr/useLanyardSway'; import { cn } from '@/lib/utils'; -import { usePointerSway } from '../../usePointerSway'; import { ACCENT, BOARD, COVER } from './HomeBadge.constants'; import * as styles from './HomeBadge.styles'; import type { HomeBadgeProps } from './HomeBadge.types'; @@ -17,48 +17,81 @@ import type { HomeBadgeProps } from './HomeBadge.types'; * Lanyards' own billboard badge, hanging at the top of the homepage * (#145): the old homepage's welcome, in the new design language. It * hangs in a clear sleeve from a lanyard printed with the site's address, - * as a person's does on the Share screen (#170). A mouse moving across the - * lanyard sways the sleeve on its clasp (#151). + * as a person's does on the Share screen (#170). It hangs straight, swings + * in as it arrives, and a mouse brushing past sways it and its lanyard, + * with real physics (#151, #174). Signing in turns it over, on its clasp, + * to the form on its back (#175): both faces share one place, so they're + * the same size, and the one turned away is out of reach (inert, so the + * app's focus after navigating lands on the face that's up). While it + * shows its back it hangs still, for the form. */ -export function HomeBadge({ headingId, className }: HomeBadgeProps) { +export function HomeBadge({ + headingId, + face = 'front', + back, + className, +}: HomeBadgeProps) { const { t, i18n } = useLingui(); - const lanyard = useRef(null); - const sleeve = useRef(null); - usePointerSway(lanyard, sleeve); + const [lanyard, setLanyard] = useState(null); + const [swing, setSwing] = useState(null); + const [ribbon, setRibbon] = useState(null); + useLanyardSway({ + area: lanyard, + sleeve: swing, + ribbon, + enabled: face === 'front', + arrive: true, + }); + return (
-
- - -
-
- -
-
-
- -
-

- {t`Welcome to Lanyards`} -

-

- {t`The curated link for academic researchers that collects your complete scholarly presence—publications, talks, affiliations, and social profiles.`} -

-
-
- {BOARD.map((cell) => ( -
-
{i18n._(cell.label)}
-
{i18n._(cell.value)}
+
+ +
+
+ +
+
+
- ))} -
+
+
+ +
+

+ {t`Welcome to Lanyards`} +

+

+ {t`The curated link for academic researchers that collects your complete scholarly presence—publications, talks, affiliations, and social profiles.`} +

+
+
+ {BOARD.map((cell) => ( +
+
{i18n._(cell.label)}
+
{i18n._(cell.value)}
+
+ ))} +
+
+
+ + {back} +
- +
); diff --git a/web/src/features/home/components/HomeBadge/HomeBadge.types.ts b/web/src/features/home/components/HomeBadge/HomeBadge.types.ts index cbf7105..e416f53 100644 --- a/web/src/features/home/components/HomeBadge/HomeBadge.types.ts +++ b/web/src/features/home/components/HomeBadge/HomeBadge.types.ts @@ -1,5 +1,11 @@ +import type { ReactNode } from 'react'; + export type HomeBadgeProps = { /** The page's one h1. */ headingId: string; + /** Which way it faces: the welcome, or its back (#175). */ + face?: 'front' | 'back'; + /** What's on its back: the sign-in form (#175). */ + back?: ReactNode; className?: string; }; diff --git a/web/src/features/home/components/HomePage/HomePage.tsx b/web/src/features/home/components/HomePage/HomePage.tsx index bcdbdba..f1163b3 100644 --- a/web/src/features/home/components/HomePage/HomePage.tsx +++ b/web/src/features/home/components/HomePage/HomePage.tsx @@ -13,6 +13,7 @@ import { HomeBadge } from '../HomeBadge/HomeBadge'; import { HomeBoard } from '../HomeBoard/HomeBoard'; import { HomeHeader } from '../HomeHeader/HomeHeader'; import { HomeSection } from '../HomeSection/HomeSection'; +import { SignInFace } from '../SignInFace/SignInFace'; import { BENEFITS, FEATURES, LINKS, PARADOX } from './HomePage.constants'; import * as styles from './HomePage.styles'; import type { HomePageProps } from './HomePage.types'; @@ -20,20 +21,29 @@ import type { HomePageProps } from './HomePage.types'; /** * The homepage for people who aren't signed in: the old site's homepage * (#145) in the new design language. It makes its case and points to the - * sign-in page (#157). It wears brand blue whatever lanyard was last open, + * sign-in page (#157), which is this page with its badge turned over to + * the form on its back (#175). It wears brand blue whatever lanyard was last open, * and draws its own header on that blue (#151). */ -export function HomePage({ className }: HomePageProps) { +export function HomePage({ + face = 'front', + returnTo = '/', + className, +}: HomePageProps) { const { t, i18n } = useLingui(); const headingId = useId(); const ctaId = useId(); return (
- +
- + } + />
diff --git a/web/src/features/home/components/HomePage/HomePage.types.ts b/web/src/features/home/components/HomePage/HomePage.types.ts index 7be7b21..45da3fa 100644 --- a/web/src/features/home/components/HomePage/HomePage.types.ts +++ b/web/src/features/home/components/HomePage/HomePage.types.ts @@ -1,3 +1,7 @@ export type HomePageProps = { + /** The badge's front, or its back with the sign-in form (#175). */ + face?: 'front' | 'back'; + /** Where signing in returns to, from the back. */ + returnTo?: string; className?: string; }; diff --git a/web/src/features/home/components/SignInFace/SignInFace.constants.ts b/web/src/features/home/components/SignInFace/SignInFace.constants.ts new file mode 100644 index 0000000..f1aae94 --- /dev/null +++ b/web/src/features/home/components/SignInFace/SignInFace.constants.ts @@ -0,0 +1,4 @@ +import type { CoverPattern } from '@/design/covers'; + +/** The front's cover, so the back is the same badge. */ +export const COVER: CoverPattern = 'arrows'; diff --git a/web/src/features/home/components/SignInFace/SignInFace.styles.ts b/web/src/features/home/components/SignInFace/SignInFace.styles.ts new file mode 100644 index 0000000..533e34a --- /dev/null +++ b/web/src/features/home/components/SignInFace/SignInFace.styles.ts @@ -0,0 +1,42 @@ +// The homepage badge's back (#175): the sign-in form, built as the front +// is, at the front's size. The badge's tokens are the same in light and +// dark; the form keeps the app's own palette, in a panel on the badge. +// Nothing here clips, so the handle's suggestions hang out of the badge +// (#176): only the cover rounds its own corners. + +export const badge = + '@container flex w-full flex-1 flex-col rounded-sm bg-accent text-on-accent'; + +export const cover = + 'relative h-30 overflow-hidden rounded-t-sm @min-[40rem]:h-52'; + +// Beside each other where there's room: the welcome back, then the form. +export const field = + 'grid flex-1 content-start gap-x-12 gap-y-4 px-5 pb-8 @min-[40rem]:grid-cols-[minmax(0,1fr)_minmax(0,24rem)] @min-[40rem]:px-12 @min-[40rem]:pb-12'; + +export const intro = 'flex flex-col gap-4'; + +/** Half the logo's height: the other half overlaps the cover. */ +export const logoBox = 'h-12 @min-[40rem]:h-17'; + +// The ring is the field's colour, so the logo seems cut into the cover. +export const logo = + 'size-24 -translate-y-1/2 shadow-[0_0_0_6px_var(--accent)] @min-[40rem]:size-34'; + +export const heading = + 'text-[clamp(2.5rem,8cqi,4.5rem)] font-extrabold leading-[0.9] tracking-[-0.04em]'; + +export const lede = + 'max-w-[34ch] text-lg font-medium leading-7 @min-[40rem]:text-xl @min-[40rem]:leading-8'; + +/** The form's column: clear of the cover where they sit side by side. */ +export const aside = 'flex flex-col @min-[40rem]:pt-10'; + +// The form keeps the app's own palette: a card on the badge, over the +// sleeve's glare so its text keeps its full contrast. +export const form = + 'relative z-20 max-w-none shadow-[0_1px_2px_rgb(6_1_30/0.15)]'; + +/** While the session loads: the same card, saying so. */ +export const loading = + 'relative z-20 rounded-sm border border-ui-border bg-ui-surface p-6 text-[15px] leading-[22px] text-ui-text-muted'; diff --git a/web/src/features/home/components/SignInPage/SignInPage.test.tsx b/web/src/features/home/components/SignInFace/SignInFace.test.tsx similarity index 50% rename from web/src/features/home/components/SignInPage/SignInPage.test.tsx rename to web/src/features/home/components/SignInFace/SignInFace.test.tsx index b727951..62deae8 100644 --- a/web/src/features/home/components/SignInPage/SignInPage.test.tsx +++ b/web/src/features/home/components/SignInFace/SignInFace.test.tsx @@ -1,15 +1,13 @@ -import { screen, waitFor, within } from '@testing-library/react'; +import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { useSession } from '@/features/auth/session/useSession'; import { startSignIn, startSignUp } from '@/lib/atproto/session'; import { expectNoAxeViolations } from '@/test/axe'; -import { ADA } from '@/test/people'; -import { signedInSession } from '@/test/person'; import { renderInRouter } from '@/test/router'; -import { SignInPage } from './SignInPage'; +import { SignInFace } from './SignInFace'; vi.mock('@/features/auth/session/useSession', () => ({ useSession: vi.fn() })); vi.mock('@/lib/atproto/session', async (importOriginal) => ({ @@ -25,19 +23,21 @@ const signedOut = () => refresh: vi.fn(), }); -const page = (returnTo = '/settings') => +const face = (returnTo = '/settings') => renderInRouter( - , - `/sign-in?returnTo=${encodeURIComponent(returnTo)}` +
+ +
, + '/sign-in' ); beforeEach(() => { signedOut(); }); -describe('SignInPage (#157)', () => { - it('puts the sign-in form on a badge, with the typeahead', async () => { - const { container } = page(); +describe('SignInFace, the homepage badge’s back (#157, #175)', () => { + it('puts the sign-in form on the badge, with the typeahead', async () => { + const { container } = face(); expect( await screen.findByRole('heading', { level: 1, name: 'Sign in' }) ).toBeInTheDocument(); @@ -48,41 +48,11 @@ describe('SignInPage (#157)', () => { expect( screen.getByRole('button', { name: 'Create an account' }) ).toBeInTheDocument(); - expect(document.title).toBe('Sign in · Lanyards'); await expectNoAxeViolations(container); }); - it('hangs in a clear sleeve from a lanyard printed lanyards.app (#170)', async () => { - const { container } = page(); - const heading = await screen.findByRole('heading', { - level: 1, - name: 'Sign in', - }); - const sleeve = heading.closest('[data-sleeve]'); - expect(sleeve).not.toBeNull(); - expect(sleeve).toContainElement( - screen.getByRole('combobox', { name: 'Your handle' }) - ); - const straps = container.querySelectorAll('textPath'); - expect(straps).toHaveLength(2); - for (const strap of straps) { - expect(strap.textContent).toContain('lanyards.app'); - } - expect(container.querySelectorAll('polygon')).toHaveLength(0); - }); - - it('has the homepage’s header, without a Sign in link to itself', async () => { - page(); - const banner = await screen.findByRole('banner'); - expect( - within(banner).getByRole('link', { name: 'Lanyards' }) - ).toHaveAttribute('href', '/'); - expect(within(banner).queryByRole('link', { name: 'Sign in' })).toBeNull(); - expect(screen.getByRole('main')).not.toContainElement(banner); - }); - it('signs in, coming back to where the person was', async () => { - page(); + face(); await userEvent.type( await screen.findByRole('combobox', { name: 'Your handle' }), 'alice.bsky.social' @@ -92,7 +62,7 @@ describe('SignInPage (#157)', () => { }); it('creates an account, coming back to where the person was', async () => { - page(); + face(); await userEvent.click( await screen.findByRole('button', { name: 'Create an account' }) ); @@ -105,24 +75,23 @@ describe('SignInPage (#157)', () => { signOut: vi.fn(), refresh: vi.fn(), }); - page(); + face(); expect(await screen.findByRole('status')).toHaveTextContent('Loading…'); expect(screen.queryByRole('combobox')).toBeNull(); }); - it('sends someone already signed in on to where they were going', async () => { - vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); - const { router } = page(); - await waitFor(() => - expect(router.state.location.pathname).toBe('/settings') - ); - }); - - it('sends someone already signed in to their lanyard by default', async () => { - vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); - const { router } = page('/'); - await waitFor(() => - expect(router.state.location.pathname).toBe('/lanyard') - ); + // The badge clips nothing on its back: the suggestions hang below it. + it('lets the handle’s suggestions hang out of the badge (#176)', async () => { + face(); + const combobox = await screen.findByRole('combobox', { + name: 'Your handle', + }); + for ( + let element: HTMLElement | null = combobox.parentElement; + element && !element.hasAttribute('data-accent'); + element = element.parentElement + ) { + expect(element.className).not.toMatch(/\boverflow-(hidden|clip)\b/); + } }); }); diff --git a/web/src/features/home/components/SignInFace/SignInFace.tsx b/web/src/features/home/components/SignInFace/SignInFace.tsx new file mode 100644 index 0000000..5c2d8b0 --- /dev/null +++ b/web/src/features/home/components/SignInFace/SignInFace.tsx @@ -0,0 +1,50 @@ +import { useLingui } from '@lingui/react/macro'; +import { useId } from 'react'; + +import { CoverPattern } from '@/components/CoverPattern/CoverPattern'; +import { Logo } from '@/components/Logo/Logo'; +import { SignInForm } from '@/features/auth/components/SignInForm/SignInForm'; +import { useSession } from '@/features/auth/session/useSession'; + +import { COVER } from './SignInFace.constants'; +import * as styles from './SignInFace.styles'; +import type { SignInFaceProps } from './SignInFace.types'; + +/** + * The back of the homepage badge (#175): the sign-in form, with its handle + * typeahead (#157), on the same badge as the welcome on its front. + */ +export function SignInFace({ returnTo }: SignInFaceProps) { + const { t } = useLingui(); + const session = useSession(); + const headingId = useId(); + return ( +
+
+ +
+
+
+
+ +
+

+ {t`Sign in`} +

+

+ {t`Use your handle from Bluesky or any other AT Protocol app. New here? Create an account, and it’s yours to take anywhere.`} +

+
+
+ {session.status === 'signedOut' ? ( + + ) : ( +

+ {t`Loading…`} +

+ )} +
+
+
+ ); +} diff --git a/web/src/features/home/components/SignInFace/SignInFace.types.ts b/web/src/features/home/components/SignInFace/SignInFace.types.ts new file mode 100644 index 0000000..8531a7f --- /dev/null +++ b/web/src/features/home/components/SignInFace/SignInFace.types.ts @@ -0,0 +1,4 @@ +export type SignInFaceProps = { + /** Where to go once signed in: a validated same-origin path. */ + returnTo: string; +}; diff --git a/web/src/features/home/components/SignInPage/SignInPage.constants.ts b/web/src/features/home/components/SignInPage/SignInPage.constants.ts deleted file mode 100644 index 346ccd2..0000000 --- a/web/src/features/home/components/SignInPage/SignInPage.constants.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Accent } from '@/design/accents'; -import type { CoverPattern } from '@/design/covers'; - -/** Lanyards' own badge, as on the homepage: lime on brand blue. */ -export const BADGE_ACCENT: Accent = 'lime'; - -export const COVER: CoverPattern = 'arrows'; diff --git a/web/src/features/home/components/SignInPage/SignInPage.styles.ts b/web/src/features/home/components/SignInPage/SignInPage.styles.ts deleted file mode 100644 index bc68537..0000000 --- a/web/src/features/home/components/SignInPage/SignInPage.styles.ts +++ /dev/null @@ -1,46 +0,0 @@ -// The sign-in page (#157): the form on a badge in a clear sleeve, hanging -// from a lanyard on the brand blue as the homepage's does (#170), but -// straight and still so the form is easy to use. The badge's tokens are -// the same in light and dark; the form keeps the app's own palette in a -// panel on the badge. - -/** The page's ground: brand blue (the blue palette's accent). */ -export const page = 'relative flex min-h-dvh flex-col bg-accent'; - -/** Crops the straps' tops, so they never run up behind the header. */ -export const main = - 'flex flex-1 flex-col items-center overflow-hidden px-4 pb-14 md:px-8 md:pb-20'; - -export const hang = 'flex w-full max-w-[34rem] flex-col items-center'; - -// The clasp's hook ends in the sleeve's slot, a little below its top edge. -export const ribbon = - 'relative z-10 h-28 w-auto shrink-0 translate-y-[1.125rem] md:h-36'; - -export const badge = - '@container flex w-full flex-col overflow-hidden rounded-sm bg-accent text-on-accent'; - -export const cover = 'relative h-24 @min-[30rem]:h-28'; - -export const field = - 'flex flex-col gap-4 px-5 pb-6 @min-[30rem]:px-8 @min-[30rem]:pb-8'; - -/** Half the logo's height: the other half overlaps the cover. */ -export const logoBox = 'h-10 @min-[30rem]:h-12'; - -export const logo = - 'size-20 -translate-y-1/2 shadow-[0_0_0_6px_var(--accent)] @min-[30rem]:size-24'; - -export const heading = - 'text-[clamp(2.5rem,12cqi,3.75rem)] font-extrabold leading-[0.9] tracking-[-0.04em]'; - -export const lede = 'max-w-[34ch] text-lg font-medium leading-7'; - -// The form keeps the app's own palette: a card on the badge, full width, -// over the sleeve's glare so its text keeps its full contrast. -export const form = - 'relative z-20 max-w-none shadow-[0_1px_2px_rgb(6_1_30/0.15)]'; - -/** While the session loads: the same card, saying so. */ -export const loading = - 'relative z-20 rounded-sm border border-ui-border bg-ui-surface p-6 text-[15px] leading-[22px] text-ui-text-muted'; diff --git a/web/src/features/home/components/SignInPage/SignInPage.tsx b/web/src/features/home/components/SignInPage/SignInPage.tsx deleted file mode 100644 index b811046..0000000 --- a/web/src/features/home/components/SignInPage/SignInPage.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import { useLingui } from '@lingui/react/macro'; -import { useRouter } from '@tanstack/react-router'; -import { useEffect, useId } from 'react'; - -import { CoverPattern } from '@/components/CoverPattern/CoverPattern'; -import { Logo } from '@/components/Logo/Logo'; -import { SIGNED_IN_HOME } from '@/features/auth/components/LandingPage/LandingPage.constants'; -import { SignInForm } from '@/features/auth/components/SignInForm/SignInForm'; -import { useSession } from '@/features/auth/session/useSession'; -import { BadgeSleeve } from '@/features/qr/components/BadgeSleeve/BadgeSleeve'; -import { LanyardRibbon } from '@/features/qr/components/LanyardRibbon/LanyardRibbon'; -import { BRAND_PRINT } from '@/features/qr/components/LanyardRibbon/LanyardRibbon.constants'; -import { useDocumentTitle } from '@/hooks/useDocumentTitle'; -import { safeReturnTo } from '@/lib/atproto/oauthConfig'; - -import { HomeHeader } from '../HomeHeader/HomeHeader'; -import { BADGE_ACCENT, COVER } from './SignInPage.constants'; -import * as styles from './SignInPage.styles'; -import type { SignInPageProps } from './SignInPage.types'; - -/** - * `/sign-in` (#157): the sign-in form, with its handle typeahead, on a - * badge in a clear sleeve, hanging from a lanyard on the brand blue as the - * homepage's does (#170). Signed in already, it sends people on to where - * they were going. - */ -export function SignInPage({ returnTo }: SignInPageProps) { - const { t } = useLingui(); - const session = useSession(); - const router = useRouter(); - const headingId = useId(); - useDocumentTitle(t`Sign in`); - const safe = safeReturnTo(returnTo); - const destination = safe === '/' ? SIGNED_IN_HOME : safe; - const signedIn = session.status === 'signedIn'; - - useEffect(() => { - // destination is a validated same-origin path, which may not be a typed - // route, so use the history directly. - if (signedIn) router.history.replace(destination); - }, [signedIn, destination, router]); - - return ( -
- -
-
- - -
-
- -
-
-
- -
-

- {t`Sign in`} -

-

- {t`Use your handle from Bluesky or any other AT Protocol app. New here? Create an account, and it’s yours to take anywhere.`} -

- {session.status === 'signedOut' ? ( - - ) : ( -

- {t`Loading…`} -

- )} -
-
-
-
-
-
- ); -} diff --git a/web/src/features/home/components/SignInPage/SignInPage.types.ts b/web/src/features/home/components/SignInPage/SignInPage.types.ts deleted file mode 100644 index 57f15e4..0000000 --- a/web/src/features/home/components/SignInPage/SignInPage.types.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type SignInPageProps = { - /** Where to land after signing in; already a safe, same-origin path. */ - returnTo: string; -}; diff --git a/web/src/features/home/sway.test.ts b/web/src/features/home/sway.test.ts deleted file mode 100644 index 230660e..0000000 --- a/web/src/features/home/sway.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - atRest, - MAX_ANGLE, - REST, - stepSway, - swayAngle, - type Sway, -} from './sway'; - -const FRAME = 1 / 60; - -/** Runs the sway for `seconds`, pushed at `speed` px/s for `pushFor`. */ -function run(speed: number, pushFor: number, seconds: number, from = REST) { - let sway: Sway = from; - const angles: number[] = []; - let restedAt: number | null = null; - for (let time = 0; time < seconds; time += FRAME) { - sway = stepSway(sway, time < pushFor ? speed : 0, FRAME); - angles.push(swayAngle(sway)); - if (restedAt === null && time >= pushFor && atRest(sway)) restedAt = time; - } - return { sway, angles, restedAt }; -} - -/** The angle at each turn of the swing, in order. */ -function turns(angles: number[]) { - return angles.filter((angle, index) => { - const before = angles[index - 1]; - const after = angles[index + 1]; - if (before === undefined || after === undefined) return false; - return (angle - before) * (after - angle) < 0; - }); -} - -describe('sway', () => { - it('stays still with nothing pushing it', () => { - const { sway } = run(0, 0, 2); - expect(sway).toEqual(REST); - expect(atRest(sway)).toBe(true); - }); - - // CSS turns clockwise for a positive angle: the bottom moves left. - it('swings the bottom of the badge the way the pointer moves', () => { - const right = run(1200, 0.5, 0.6).angles.at(-1) ?? 0; - const left = run(-1200, 0.5, 0.6).angles.at(-1) ?? 0; - expect(right).toBeLessThan(-0.3); - expect(left).toBeGreaterThan(0.3); - }); - - it('moves only a little for a slow pointer', () => { - const { angles } = run(150, 1, 3); - expect(Math.max(...angles.map(Math.abs))).toBeLessThan(0.75); - }); - - it('never leans past its cap, however hard it is pushed', () => { - for (const speed of [5_000, 100_000, -100_000, Number.MAX_VALUE]) { - const { angles } = run(speed, 10, 12); - expect(Math.max(...angles.map(Math.abs))).toBeLessThan(MAX_ANGLE); - } - }); - - it('swings well, then back and forth, each swing smaller, then rests', () => { - const { angles, restedAt, sway } = run(1200, 0.5, 10); - const [first, second, third, fourth] = turns(angles); - // A brisk sweep: a swing of well over 2 degrees (#163), then back. - expect(first).toBeLessThan(-2.5); - expect(second).toBeGreaterThan(0); - expect(third).toBeLessThan(0); - expect(fourth).toBeGreaterThan(0); - for (const [bigger, smaller] of [ - [first, second], - [second, third], - [third, fourth], - ]) { - expect(Math.abs(smaller ?? 0)).toBeLessThan(Math.abs(bigger ?? 0) * 0.7); - } - // Still again about six seconds after the pointer stops. - expect(restedAt).not.toBeNull(); - expect((restedAt ?? 0) - 0.5).toBeGreaterThan(4.5); - expect((restedAt ?? 0) - 0.5).toBeLessThan(6.5); - expect(sway).toEqual(REST); - }); - - it('comes to rest from its cap in about six seconds', () => { - const { restedAt } = run(100_000, 3, 14); - expect(restedAt).not.toBeNull(); - expect((restedAt ?? 0) - 3).toBeLessThan(6.5); - }); - - // A tab in the background, or a long frame, doesn't fling it. - it('treats a long gap between frames as one short frame', () => { - const swinging = run(1200, 0.5, 0.5).sway; - const after = stepSway(swinging, 0, 5); - const short = stepSway(swinging, 0, 1 / 30); - expect(after).toEqual(short); - expect(stepSway(swinging, 0, -1)).toEqual(swinging); - }); - - it('ignores a pointer speed that isn’t a number', () => { - expect(stepSway(REST, Number.NaN, FRAME)).toEqual(REST); - expect(stepSway(REST, Number.POSITIVE_INFINITY, FRAME).angle).toBeLessThan( - 0 - ); - }); -}); diff --git a/web/src/features/home/sway.ts b/web/src/features/home/sway.ts deleted file mode 100644 index 161dcb8..0000000 --- a/web/src/features/home/sway.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * How the homepage badge sways when a pointer brushes past it (#151): a - * damped spring, pushed by how fast the pointer moves sideways. A brisk - * sweep swings it nearly 3 degrees (#163), then back and forth, - * each swing about half the last, and it's still about six seconds after - * the pointer stops. The angle shown never reaches MAX_ANGLE, however - * hard it's pushed. - * - * Angles are in degrees, as CSS turns them: positive is clockwise, which - * moves the bottom of the badge left. - */ -export type Sway = { - /** Degrees from hanging straight. */ - angle: number; - /** Degrees a second. */ - velocity: number; -}; - -export const REST: Sway = { angle: 0, velocity: 0 }; - -/** The furthest the badge ever leans, either way. */ -export const MAX_ANGLE = 5; - -/** About 1.6 seconds a swing. */ -const STIFFNESS = 4; - -/** - * Light enough to sway on, heavy enough that each swing is about half the - * last, so it's still in about six seconds. - */ -const DAMPING = 0.2; - -/** Degrees a second, squared, for each pixel a second of pointer. */ -const GAIN = 0.032; - -/** The most the pointer pushes: a brisk sweep, not a fling. */ -const MAX_PUSH = 80; - -/** The fastest it turns, and how far it can wind up past what it shows. */ -const MAX_VELOCITY = 60; -const MAX_WIND = MAX_ANGLE * 2; - -/** A longer frame (a tab in the background) counts as this. */ -const MAX_STEP = 1 / 30; - -/** Below these, it's still: under half a pixel at the badge's foot. */ -const REST_ANGLE = 0.03; -const REST_VELOCITY = 0.1; - -const clamp = (value: number, limit: number) => - Math.max(-limit, Math.min(limit, value)); - -/** - * Advances the sway by `seconds`, pushed by the pointer moving sideways - * at `pointerSpeed` pixels a second (rightwards positive). - */ -export function stepSway( - sway: Sway, - pointerSpeed: number, - seconds: number -): Sway { - const step = Math.min(Math.max(seconds, 0), MAX_STEP); - if (step === 0) return sway; - const speed = Number.isNaN(pointerSpeed) ? 0 : pointerSpeed; - // Moving right pushes the bottom right: an anticlockwise turn. - const push = clamp(-speed * GAIN, MAX_PUSH); - const spring = -STIFFNESS * STIFFNESS * sway.angle; - const drag = -2 * DAMPING * STIFFNESS * sway.velocity; - // Semi-implicit Euler: velocity first, then the angle from it. - const velocity = clamp( - sway.velocity + (spring + drag + push) * step, - MAX_VELOCITY - ); - const angle = clamp(sway.angle + velocity * step, MAX_WIND); - const next = { angle, velocity }; - return atRest(next) && push === 0 ? REST : next; -} - -/** The angle to draw: eases into MAX_ANGLE rather than stopping at it. */ -export function swayAngle(sway: Sway): number { - return MAX_ANGLE * Math.tanh(sway.angle / MAX_ANGLE); -} - -/** Still enough to stop animating. */ -export function atRest(sway: Sway): boolean { - return ( - Math.abs(sway.angle) < REST_ANGLE && Math.abs(sway.velocity) < REST_VELOCITY - ); -} diff --git a/web/src/features/home/usePointerSway.test.tsx b/web/src/features/home/usePointerSway.test.tsx deleted file mode 100644 index a44becb..0000000 --- a/web/src/features/home/usePointerSway.test.tsx +++ /dev/null @@ -1,134 +0,0 @@ -import { fireEvent, render, screen } from '@testing-library/react'; -import { useRef } from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -import { MAX_ANGLE } from './sway'; -import { SWAY_MEDIA, usePointerSway } from './usePointerSway'; - -function Lanyard() { - const area = useRef(null); - const badge = useRef(null); - usePointerSway(area, badge); - return ( -
-
-
- ); -} - -let matches = true; -let onChange: (() => void) | undefined; - -beforeEach(() => { - matches = true; - onChange = undefined; - vi.spyOn(window, 'matchMedia').mockImplementation( - (query: string) => - ({ - get matches() { - return query === SWAY_MEDIA && matches; - }, - media: query, - addEventListener: (_type: string, listener: () => void) => { - onChange = listener; - }, - removeEventListener: (_type: string, listener: () => void) => { - if (onChange === listener) onChange = undefined; - }, - }) as unknown as MediaQueryList - ); - vi.useFakeTimers({ - toFake: ['requestAnimationFrame', 'cancelAnimationFrame', 'performance'], - }); -}); - -afterEach(() => { - vi.useRealTimers(); - vi.restoreAllMocks(); -}); - -/** Moves the pointer across the lanyard, a frame at a time. */ -function sweep(pointerType: string, from: number, to: number, frames = 10) { - const lanyard = screen.getByTestId('lanyard'); - for (let frame = 0; frame <= frames; frame += 1) { - const clientX = from + ((to - from) * frame) / frames; - fireEvent.pointerMove(lanyard, { pointerType, clientX, clientY: 100 }); - vi.advanceTimersByTime(16); - } -} - -/** The badge's drawn angle, in degrees; 0 when it has no transform. */ -function angle() { - const transform = screen.getByTestId('badge').style.transform; - if (!transform) return 0; - const match = /^rotate\((-?[\d.]+)deg\)$/.exec(transform); - expect(match).not.toBeNull(); - return Number(match?.[1]); -} - -describe('usePointerSway', () => { - it('sways the badge the way a mouse moves across it', () => { - render(); - sweep('mouse', 100, 500); - vi.advanceTimersByTime(150); - // Moving right swings the bottom right: an anticlockwise turn. - expect(angle()).toBeLessThan(-0.2); - expect(Math.abs(angle())).toBeLessThan(MAX_ANGLE); - }); - - it('comes to rest, straightens and stops animating', () => { - render(); - sweep('mouse', 500, 100); - expect(angle()).toBeGreaterThan(0); - vi.advanceTimersByTime(8000); - expect(screen.getByTestId('badge').style.transform).toBe(''); - expect(vi.getTimerCount()).toBe(0); - }); - - it('leaves the badge alone for touch and pen', () => { - render(); - sweep('touch', 100, 500); - sweep('pen', 100, 500); - expect(screen.getByTestId('badge').style.transform).toBe(''); - expect(vi.getTimerCount()).toBe(0); - }); - - it('leaves it alone with reduced motion, or with no fine pointer', () => { - matches = false; - render(); - sweep('mouse', 100, 500); - expect(screen.getByTestId('badge').style.transform).toBe(''); - expect(vi.getTimerCount()).toBe(0); - }); - - it('straightens at once when reduced motion is turned on mid-swing', () => { - render(); - sweep('mouse', 100, 500); - expect(angle()).not.toBe(0); - matches = false; - onChange?.(); - expect(screen.getByTestId('badge').style.transform).toBe(''); - expect(vi.getTimerCount()).toBe(0); - sweep('mouse', 500, 100); - expect(screen.getByTestId('badge').style.transform).toBe(''); - }); - - it('starts afresh after the pointer leaves and comes back', () => { - render(); - const lanyard = screen.getByTestId('lanyard'); - fireEvent.pointerMove(lanyard, { pointerType: 'mouse', clientX: 100 }); - fireEvent.pointerLeave(lanyard, { pointerType: 'mouse' }); - // Back in at the far side: not a sweep across the whole badge. - fireEvent.pointerMove(lanyard, { pointerType: 'mouse', clientX: 900 }); - vi.advanceTimersByTime(300); - expect(Math.abs(angle())).toBeLessThan(0.05); - }); - - it('lets go when it unmounts mid-swing', () => { - const { unmount } = render(); - sweep('mouse', 100, 500); - unmount(); - expect(vi.getTimerCount()).toBe(0); - expect(onChange).toBeUndefined(); - }); -}); diff --git a/web/src/features/home/usePointerSway.ts b/web/src/features/home/usePointerSway.ts deleted file mode 100644 index 5b01063..0000000 --- a/web/src/features/home/usePointerSway.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { type RefObject, useEffect } from 'react'; - -import { atRest, REST, stepSway, type Sway, swayAngle } from './sway'; - -/** - * Sway only for a mouse or trackpad, and only for people who haven't - * asked for less motion. Touch has no hover to brush past with. - */ -export const SWAY_MEDIA = - '(prefers-reduced-motion: no-preference) and (hover: hover) and (pointer: fine)'; - -/** - * Sways `target` as a mouse moves sideways over `area` (#151), then lets - * it settle (see ./sway). It animates only while it moves: at rest there - * is no frame loop and no transform. The turn is drawn as the target's - * transform, set frame by frame here, so it adds to any tilt the - * target's classes give it with `rotate`. - */ -export function usePointerSway( - area: RefObject, - target: RefObject -): void { - useEffect(() => { - const zone = area.current; - const badge = target.current; - if (!zone || !badge) return; - const media = window.matchMedia(SWAY_MEDIA); - - let sway: Sway = REST; - let frame = 0; - let lastFrame: number | null = null; - let lastX: number | null = null; - /** Pixels moved sideways since the last frame. */ - let moved = 0; - - function straighten() { - if (frame) cancelAnimationFrame(frame); - frame = 0; - lastFrame = null; - lastX = null; - moved = 0; - sway = REST; - badge?.style.removeProperty('transform'); - } - - function tick(now: number) { - const seconds = lastFrame === null ? 0 : (now - lastFrame) / 1000; - lastFrame = now; - // The first frame only starts the clock; the movement waits for it. - if (seconds <= 0) { - frame = requestAnimationFrame(tick); - return; - } - sway = stepSway(sway, moved / seconds, seconds); - moved = 0; - if (atRest(sway)) { - straighten(); - return; - } - badge?.style.setProperty( - 'transform', - `rotate(${swayAngle(sway).toFixed(3)}deg)` - ); - frame = requestAnimationFrame(tick); - } - - function onMove(event: PointerEvent) { - if (event.pointerType !== 'mouse' || !media.matches) return; - if (lastX !== null) moved += event.clientX - lastX; - lastX = event.clientX; - if (!frame) frame = requestAnimationFrame(tick); - } - - // Coming back in elsewhere isn't a sweep across the gap. - function onLeave() { - lastX = null; - } - - function onMediaChange() { - if (!media.matches) straighten(); - } - - zone.addEventListener('pointermove', onMove); - zone.addEventListener('pointerleave', onLeave); - media.addEventListener('change', onMediaChange); - return () => { - zone.removeEventListener('pointermove', onMove); - zone.removeEventListener('pointerleave', onLeave); - media.removeEventListener('change', onMediaChange); - straighten(); - }; - }, [area, target]); -} diff --git a/web/src/features/lanyard/components/BadgeHero/BadgeHero.styles.ts b/web/src/features/lanyard/components/BadgeHero/BadgeHero.styles.ts index 3002035..1faf16a 100644 --- a/web/src/features/lanyard/components/BadgeHero/BadgeHero.styles.ts +++ b/web/src/features/lanyard/components/BadgeHero/BadgeHero.styles.ts @@ -4,14 +4,10 @@ // only generates classes it finds in the source. export const badge = - '@container flex w-full flex-col overflow-hidden rounded-sm shadow-badge outline outline-1 -outline-offset-1 outline-border'; + '@container flex w-full flex-col overflow-hidden rounded-sm outline outline-1 -outline-offset-1 outline-border'; export const cover = 'relative h-30 @min-[40rem]:h-60'; -/** Where a real lanyard's clip would go through the badge. */ -export const slot = - 'absolute left-1/2 top-[1.125rem] h-3.5 w-24 -translate-x-1/2 rounded-sm bg-background shadow-[inset_0_2px_3px_rgb(6_1_30/0.35)]'; - export const field = 'flex flex-wrap items-end gap-x-10 gap-y-6 bg-accent px-5 pb-6 text-on-accent @min-[40rem]:px-12 @min-[40rem]:pb-10'; diff --git a/web/src/features/lanyard/components/BadgeHero/BadgeHero.test.tsx b/web/src/features/lanyard/components/BadgeHero/BadgeHero.test.tsx index 8bbba90..ab26d3c 100644 --- a/web/src/features/lanyard/components/BadgeHero/BadgeHero.test.tsx +++ b/web/src/features/lanyard/components/BadgeHero/BadgeHero.test.tsx @@ -1,5 +1,5 @@ import userEvent from '@testing-library/user-event'; -import { screen } from '@testing-library/react'; +import { fireEvent, screen } from '@testing-library/react'; import { describe, expect, it } from 'vitest'; import { ADA } from '@/test/people'; @@ -51,6 +51,28 @@ describe('BadgeHero', () => { ).toBeInTheDocument(); }); + it('hangs in a laminate sleeve from a lanyard printed with the handle (#173)', () => { + const { container } = renderWithProviders(); + const badge = screen.getByRole('region', { name: 'Dr Ada Example' }); + expect(badge.closest('[data-sleeve]')).not.toBeNull(); + const straps = container.querySelectorAll('textPath'); + expect(straps).toHaveLength(2); + for (const strap of straps) { + expect(strap.textContent).toContain('@alice.test'); + } + }); + + it('never sways: it holds buttons, which must stay put (#173)', () => { + const { container } = renderWithProviders(); + const badge = screen.getByRole('region', { name: 'Dr Ada Example' }); + for (let x = 100; x <= 600; x += 50) { + fireEvent.pointerMove(badge, { pointerType: 'mouse', clientX: x }); + } + for (const element of container.querySelectorAll('*')) { + expect(element.style.transform).toBe(''); + } + }); + it('wears a decorative cover and shows initials without an avatar (#129)', () => { const { container } = renderWithProviders(); const cover = container.querySelector('[data-cover] svg'); diff --git a/web/src/features/lanyard/components/BadgeHero/BadgeHero.tsx b/web/src/features/lanyard/components/BadgeHero/BadgeHero.tsx index 88e997a..7e6ee45 100644 --- a/web/src/features/lanyard/components/BadgeHero/BadgeHero.tsx +++ b/web/src/features/lanyard/components/BadgeHero/BadgeHero.tsx @@ -2,13 +2,16 @@ import { CoverPattern } from '@/components/CoverPattern/CoverPattern'; import { heroName } from '@/lib/person/hero'; import { cn } from '@/lib/utils'; +import { BadgeLanyard } from '../BadgeLanyard/BadgeLanyard'; import { DepartureBoard } from '../DepartureBoard/DepartureBoard'; import * as styles from './BadgeHero.styles'; import type { BadgeHeroProps } from './BadgeHero.types'; /** * The badge at the top of a lanyard (spec §7): the cover, the accent field - * with the name in billboard type, and the departure board. + * with the name in billboard type, and the departure board. It hangs in a + * laminate sleeve from a lanyard printed with the handle, as on the Share + * screen (#173), but never sways: it holds buttons, which must stay put. */ export function BadgeHero({ hero, @@ -22,51 +25,51 @@ export function BadgeHero({ const meta = [hero.pronouns, `@${hero.handle}`].filter(Boolean).join(' · '); return ( -
-
- -
-
-
-
- {hero.avatar ? ( - - ) : ( - + +
+
+ +
+
+
+
+ {hero.avatar ? ( + + ) : ( + + )} +
+
+ + {heroName(hero)} + +

{meta}

+
+ {hero.headline && ( +

{hero.headline}

)}
-
- - {heroName(hero)} - -

{meta}

-
- {hero.headline &&

{hero.headline}

} + {actions &&
{actions}
}
- {actions &&
{actions}
} -
- -
+ + + ); } diff --git a/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.styles.ts b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.styles.ts new file mode 100644 index 0000000..6244932 --- /dev/null +++ b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.styles.ts @@ -0,0 +1,15 @@ +// A person's badge on their lanyard page (#173): in a laminate sleeve, on +// a lanyard in their accent, on a page that may be light or dark. + +export const hang = 'flex w-full flex-col items-center'; + +// The clasp's hook ends in the sleeve's slot, a little below its top edge. +// The straps are cut cleanly where the box starts, before the shift down, +// so they run up to the header or the canvas's edge. +export const ribbon = + 'relative z-10 h-24 w-auto shrink-0 translate-y-[1.125rem] [clip-path:inset(-1.125rem_-100vw_-100vw)] sm:h-32 md:translate-y-7 md:[clip-path:inset(-1.75rem_-100vw_-100vw)]'; + +/** A bigger sleeve for the bigger badge. */ +export const sleeve = 'md:p-4 md:pt-12'; + +export const slot = 'md:top-4 md:h-4 md:w-24'; diff --git a/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.test.tsx b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.test.tsx new file mode 100644 index 0000000..b125cc1 --- /dev/null +++ b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.test.tsx @@ -0,0 +1,33 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { BadgeLanyard } from './BadgeLanyard'; + +describe('BadgeLanyard (#173)', () => { + it('hangs the badge in a sleeve, from straps printed with the handle', () => { + const { container } = render( + +

Dr Ada Example

+
+ ); + const name = screen.getByRole('heading', { name: 'Dr Ada Example' }); + expect(name.closest('[data-sleeve]')).not.toBeNull(); + const straps = container.querySelectorAll('textPath'); + expect(straps).toHaveLength(2); + for (const strap of straps) { + expect(strap.textContent).toContain('@alice.test'); + } + }); + + it('hangs plain straps while the handle is unknown', () => { + const { container } = render( + +

Loading

+
+ ); + expect(container.querySelector('[data-sleeve]')).not.toBeNull(); + for (const strap of container.querySelectorAll('textPath')) { + expect(strap.textContent).toBe(''); + } + }); +}); diff --git a/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.tsx b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.tsx new file mode 100644 index 0000000..51e019a --- /dev/null +++ b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.tsx @@ -0,0 +1,34 @@ +import { BadgeSleeve } from '@/features/qr/components/BadgeSleeve/BadgeSleeve'; +import { LanyardRibbon } from '@/features/qr/components/LanyardRibbon/LanyardRibbon'; +import { cn } from '@/lib/utils'; + +import * as styles from './BadgeLanyard.styles'; +import type { BadgeLanyardProps } from './BadgeLanyard.types'; + +/** + * The lanyard a person's badge hangs from on their page (#173): straps in + * their accent, printed with their handle, and a laminate sleeve, as on + * the Share screen. It never sways: the badge holds buttons. + */ +export function BadgeLanyard({ + children, + handle, + className, +}: BadgeLanyardProps) { + return ( +
+ + + {children} + +
+ ); +} diff --git a/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.types.ts b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.types.ts new file mode 100644 index 0000000..9717d48 --- /dev/null +++ b/web/src/features/lanyard/components/BadgeLanyard/BadgeLanyard.types.ts @@ -0,0 +1,9 @@ +import type { ReactNode } from 'react'; + +export type BadgeLanyardProps = { + /** The badge, or its loading shape. */ + children: ReactNode; + /** Printed on the straps; plain straps while it's unknown. */ + handle?: string; + className?: string; +}; diff --git a/web/src/features/lanyard/components/LanyardPage/LanyardPage.styles.ts b/web/src/features/lanyard/components/LanyardPage/LanyardPage.styles.ts index 8eaaa4b..48ffd6b 100644 --- a/web/src/features/lanyard/components/LanyardPage/LanyardPage.styles.ts +++ b/web/src/features/lanyard/components/LanyardPage/LanyardPage.styles.ts @@ -1,6 +1,7 @@ // The badge is up to 1,120 px wide; the blocks under it up to 760 px (#129). +// No padding on top: the badge's lanyard starts under the header (#173). export const page = - 'flex w-full max-w-[70rem] flex-col items-center gap-10 self-center px-4 py-8 sm:px-6 sm:py-10'; + 'flex w-full max-w-[70rem] flex-col items-center gap-10 self-center px-4 pb-8 sm:px-6 sm:pb-10'; export const column = 'flex w-full max-w-[47.5rem] flex-col gap-6'; diff --git a/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.styles.ts b/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.styles.ts index e20ed43..e7ce052 100644 --- a/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.styles.ts +++ b/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.styles.ts @@ -2,10 +2,10 @@ // the badge's sizes, so nothing jumps when it arrives. export const page = - 'flex w-full max-w-[70rem] flex-col items-center gap-10 self-center px-4 py-8 sm:px-6 sm:py-10'; + 'flex w-full max-w-[70rem] flex-col items-center gap-10 self-center px-4 pb-8 sm:px-6 sm:pb-10'; export const badge = - '@container flex w-full flex-col overflow-hidden rounded-sm shadow-badge outline outline-1 -outline-offset-1 outline-border'; + '@container flex w-full flex-col overflow-hidden rounded-sm outline outline-1 -outline-offset-1 outline-border'; const pulse = 'motion-safe:animate-pulse'; diff --git a/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx b/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx index 147726d..76ac8d8 100644 --- a/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx +++ b/web/src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx @@ -2,26 +2,32 @@ import { useLingui } from '@lingui/react/macro'; import { cn } from '@/lib/utils'; +import { BadgeLanyard } from '../BadgeLanyard/BadgeLanyard'; import * as styles from './LanyardSkeleton.styles'; import type { LanyardSkeletonProps } from './LanyardSkeleton.types'; -/** Holds the badge's place, in its shape, while the profile loads. */ +/** + * Holds the badge's place, in its shape, while the profile loads: on its + * lanyard and in its sleeve, with plain straps (#173). + */ export function LanyardSkeleton({ className }: LanyardSkeletonProps) { const { t } = useLingui(); return (
-
- {t`Loading lanyard…`} -
+
); } diff --git a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.styles.ts b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.styles.ts index 138cd94..0082fc6 100644 --- a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.styles.ts +++ b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.styles.ts @@ -13,17 +13,18 @@ export const workspace = 'flex flex-1 items-stretch md:min-h-0'; // From md up it scrolls, and is positioned, so absolutely placed content // inside it (such as screen-reader text) scrolls with it rather than // stretching the page. +// The lanyard hangs from its top edge (#173), unless a notice comes first. export const canvas = - 'min-w-0 items-center gap-6 px-4 py-6 md:relative md:overflow-y-auto md:px-8 md:py-8'; + 'min-w-0 items-center gap-6 px-4 pb-6 has-[>[data-notice]:not(:empty)]:pt-6 md:relative md:overflow-y-auto md:px-8 md:pb-8 md:has-[>[data-notice]:not(:empty)]:pt-8'; export const intro = 'flex w-full max-w-[640px] flex-col gap-3'; -export const heading = - 'text-[22px] font-semibold leading-7 tracking-tight text-ui-text'; +/** For screen readers: the header already says Customise (#173). */ +export const heading = 'sr-only'; /** Empty but present, so the status is announced when it appears. */ export const moving = - 'text-[15px] leading-[22px] text-ui-text-muted empty:sr-only'; + 'w-full max-w-[640px] text-[15px] leading-[22px] text-ui-text-muted empty:sr-only'; export const frame = 'w-full max-w-[640px]'; diff --git a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.tsx b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.tsx index d4d84ae..305d44a 100644 --- a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.tsx +++ b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.tsx @@ -156,34 +156,39 @@ function Customiser({ /> -
-

- {t`Customise your lanyard`} -

- {(!canEdit || !canKeep || draft.permissionLost) && ( - - )} -

- {move.moving ? t`Updating your podcasts and videos…` : ''} -

- {settings.invalid && ( -
-

- {t`We couldn't read your lanyard settings`} -

-

- {t`They may have been saved in a form Lanyards doesn't recognise. Resetting replaces them with the defaults.`} -

- -
- )} -
+

+ {t`Customise your lanyard`} +

+

+ {move.moving ? t`Updating your podcasts and videos…` : ''} +

+ {(!canEdit || + !canKeep || + draft.permissionLost || + settings.invalid) && ( +
+ {(!canEdit || !canKeep || draft.permissionLost) && ( + + )} + {settings.invalid && ( +
+

+ {t`We couldn't read your lanyard settings`} +

+

+ {t`They may have been saved in a form Lanyards doesn't recognise. Resetting replaces them with the defaults.`} +

+ +
+ )} +
+ )}
{ expect(slot?.className).toMatch(/(^|\s)top-4(\s|$)/); expect(glare?.className).toMatch(/(^|\s)hidden(\s|$)/); }); + + it('is white plastic on the brand ground, and themed on a page (#173)', () => { + const { container, rerender } = render( + +

Badge

+
+ ); + const sleeve = () => container.querySelector('[data-sleeve]'); + expect(sleeve()?.className).toContain('border-white/60'); + rerender( + +

Badge

+
+ ); + // The page may be light or dark: its own ink shows the edge. + expect(sleeve()?.className).not.toContain('border-white/60'); + expect(sleeve()?.className).toContain('border-foreground/20'); + expect(sleeve()?.querySelector('span')?.className).toContain( + 'bg-background' + ); + }); }); diff --git a/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.tsx b/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.tsx index 3c89cc8..d76a6f9 100644 --- a/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.tsx +++ b/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.tsx @@ -5,19 +5,32 @@ import type { BadgeSleeveProps } from './BadgeSleeve.types'; /** * The clear sleeve a badge hangs in (#169), on the Share screen, the - * homepage and the sign-in page (#170). Its lip's slot is where a - * LanyardRibbon's clasp goes through. + * homepage and the sign-in page (#170), and on a person's lanyard page + * (#173). Its lip's slot is where a LanyardRibbon's clasp goes through. */ export function BadgeSleeve({ children, ref, + ground = 'brand', + inert, className, slotClassName, glareClassName, }: BadgeSleeveProps) { return ( -
-
-
+
{hero && ( )} ({ speed, below }); + +/** + * Runs the lanyard for `seconds`, brushed by `push` for the first + * `pushFor` seconds, a frame at a time. + */ +function run( + push: Push, + pushFor: number, + seconds: number, + { badge = CARD, frame = FRAME, from = REST } = {} +) { + let hang: Hang = from; + const angles: number[] = []; + const shifts: number[] = []; + let restedAt: number | null = null; + for (let time = 0; time < seconds; time += frame) { + hang = stepHang(hang, badge, time < pushFor ? push : null, frame); + const shown = drawn(hang); + angles.push(shown.angle); + shifts.push(shown.shift); + if (restedAt === null && time >= pushFor && atRest(hang)) restedAt = time; + } + return { hang, angles, shifts, restedAt }; +} + +/** The angle at each turn of the swing, in order. */ +function turns(values: number[]) { + return values.filter((value, index) => { + const before = values[index - 1]; + const after = values[index + 1]; + if (before === undefined || after === undefined) return false; + return (value - before) * (after - value) < 0; + }); +} + +/** Seconds between the first two swings the same way: one period. */ +function period(values: number[], frame = FRAME) { + const peaks = values + .map((value, index) => ({ value, index })) + .filter(({ value, index }) => { + const before = values[index - 1]; + const after = values[index + 1]; + return ( + before !== undefined && + after !== undefined && + value > before && + value >= after && + value > 0 + ); + }); + const [first, second] = peaks; + return ((second?.index ?? 0) - (first?.index ?? 0)) * frame; +} + +const biggest = (values: number[]) => Math.max(...values.map(Math.abs)); + +describe('lanyard physics (#174)', () => { + it('hangs still with nothing touching it', () => { + const { hang } = run(brush(0), 0, 2); + expect(hang).toEqual(REST); + expect(atRest(hang)).toBe(true); + }); + + it('swings the badge, and the lanyard with it, the way the pointer moves', () => { + const right = run(brush(1500), 0.3, 0.45); + const left = run(brush(-1500), 0.3, 0.45); + // Positive is the badge's foot moving right; the tab follows a little. + expect(Math.max(...right.angles)).toBeGreaterThan(0.5); + expect(Math.max(...right.shifts)).toBeGreaterThan(0.3); + expect(Math.min(...left.angles)).toBeLessThan(-0.5); + expect(Math.min(...left.shifts)).toBeLessThan(-0.3); + }); + + it('swings well for a brisk sweep, about 3 degrees (#163)', () => { + const { angles } = run(brush(1500), 0.3, 1.5); + expect(biggest(angles)).toBeGreaterThan(2); + expect(biggest(angles)).toBeLessThan(4); + }); + + it('moves only a little for a slow pointer', () => { + const { angles } = run(brush(150), 1, 3); + expect(biggest(angles)).toBeLessThan(0.75); + }); + + it('turns the badge most when brushed low, and the lanyard when high', () => { + const low = run(brush(1500, 500), 0.3, 1); + const high = run(brush(1500, -60), 0.3, 1); + expect(biggest(low.angles)).toBeGreaterThan(biggest(high.angles) * 2); + expect(biggest(high.shifts)).toBeGreaterThan(0.3); + }); + + it('can never be pushed faster than the pointer moves', () => { + // Brushed for ever at a steady speed, the badge goes with the pointer, + // never past it: the lanyard pulls it back long before. + const { angles } = run(brush(600), 10, 10); + expect(biggest(angles)).toBeLessThan(MAX_ANGLE); + }); + + it('swings back and forth, each swing smaller, then rests within 6 s', () => { + const { angles, restedAt, hang } = run(brush(1500), 0.3, 10); + const swings = turns(angles); + expect(swings.length).toBeGreaterThanOrEqual(6); + for (let index = 1; index < 4; index += 1) { + expect(Math.abs(swings[index] ?? 0)).toBeLessThan( + Math.abs(swings[index - 1] ?? 0) + ); + } + expect(restedAt).not.toBeNull(); + expect((restedAt ?? 0) - 0.3).toBeGreaterThan(3.5); + expect((restedAt ?? 0) - 0.3).toBeLessThan(6.5); + expect(hang).toEqual(REST); + }); + + it('swings at a real badge’s pace: a bigger badge swings slower', () => { + const card = period(run(brush(1500), 0.2, 4).angles); + const billboard = period( + run(brush(1500), 0.2, 4, { badge: BILLBOARD }).angles + ); + // A 9 cm card swings in about 0.65 s; a billboard more slowly. + expect(card).toBeGreaterThan(0.5); + expect(card).toBeLessThan(0.9); + expect(billboard).toBeGreaterThan(card); + expect(billboard).toBeLessThan(1.2); + }); + + it('never leans past its caps, however hard it is pushed', () => { + for (const speed of [5_000, 100_000, -100_000, Number.MAX_VALUE]) { + for (const below of [-200, 0, 300, 2_000]) { + const { angles, shifts } = run(brush(speed, below), 5, 12); + expect(biggest(angles)).toBeLessThan(MAX_ANGLE); + expect(biggest(shifts)).toBeLessThan(MAX_SHIFT); + } + } + }); + + it('comes to rest from its caps within 6 s', () => { + const { restedAt } = run(brush(100_000), 3, 14); + expect(restedAt).not.toBeNull(); + expect((restedAt ?? 0) - 3).toBeLessThan(6.5); + }); + + it('moves the same at 60 and 144 frames a second', () => { + const slow = run(brush(1500), 0.3, 1.2); + const fast = run(brush(1500), 0.3, 1.2, { frame: 1 / 144 }); + expect(Math.abs(biggest(slow.angles) - biggest(fast.angles))).toBeLessThan( + 0.15 + ); + }); + + // A tab in the background, or a long frame, doesn't fling it. + it('treats a long gap between frames as one short frame', () => { + const swinging = run(brush(1500), 0.3, 0.3).hang; + expect(stepHang(swinging, CARD, null, 5)).toEqual( + stepHang(swinging, CARD, null, 1 / 30) + ); + expect(stepHang(swinging, CARD, null, -1)).toEqual(swinging); + }); + + it('ignores a push that isn’t a number', () => { + expect(stepHang(REST, CARD, brush(Number.NaN), FRAME)).toEqual(REST); + expect(stepHang(REST, CARD, brush(1500, Number.NaN), FRAME)).toEqual(REST); + }); + + it('swings in from a lean and settles, as it arrives', () => { + const { angles, restedAt } = run(brush(0), 0, 10, { + from: { ...REST, angle: 4 }, + }); + expect(angles[0]).toBeGreaterThan(3); + expect(Math.min(...angles)).toBeLessThan(-1); + expect(restedAt).not.toBeNull(); + expect(restedAt ?? 0).toBeLessThan(6.5); + }); +}); diff --git a/web/src/features/qr/lanyardPhysics.ts b/web/src/features/qr/lanyardPhysics.ts new file mode 100644 index 0000000..a4eb1d8 --- /dev/null +++ b/web/src/features/qr/lanyardPhysics.ts @@ -0,0 +1,222 @@ +/** + * How a badge hangs and swings on its lanyard (#174), as a real one does. + * + * Two bodies, coupled: + * - The lanyard's tab, at the bottom of the straps, swings sideways: a + * pendulum of the strap below where it lies on the wearer's chest. The + * straps rub on clothes, so it follows the badge smoothly rather than + * trading swings with it, and moves only a little. + * - The badge in its sleeve swings on the clasp below the tab: a physical + * pendulum, a flat card whose size sets its pace. A small card swings + * quickly; a billboard more slowly. + * + * Moving the tab swings the badge, and the badge's swing tugs the tab, so + * the straps sway too and the badge follows through. A mouse brushing past + * pushes at its own height: low on the badge it turns it; high, on the + * straps, it moves the lanyard. It can't push faster than it moves. Air + * drag and the clasp's friction bring it to a clean stop within about six + * seconds, as asked in #163. + * + * Lengths are CSS pixels, and gravity is real at a pixel's nominal size + * (0.26 mm), so a badge drawn life-size swings at a real badge's pace. + * Angles are degrees, positive when the badge's foot moves right; CSS turns + * the other way, so it draws them negated. + */ + +/** Where the lanyard is, and how it's moving. */ +export type Hang = { + /** The tab's shift sideways, in px: positive is right. */ + shift: number; + /** Px a second. */ + drift: number; + /** The badge's turn from hanging straight, in degrees. */ + angle: number; + /** Degrees a second. */ + spin: number; +}; + +/** The sleeve that swings, as drawn. */ +export type Badge = { + width: number; + height: number; + /** From the sleeve's top edge down to the clasp it turns on. */ + pivot: number; +}; + +/** A pointer brushing past. */ +export type Push = { + /** Px a second, sideways: positive is right. */ + speed: number; + /** Px below the clasp; negative is above it, on the straps. */ + below: number; +}; + +export const REST: Hang = { shift: 0, drift: 0, angle: 0, spin: 0 }; + +/** The furthest the badge is ever drawn turned, either way. */ +export const MAX_ANGLE = 5; + +/** The furthest the tab is ever drawn shifted, either way. */ +export const MAX_SHIFT = 16; + +/** Gravity in px a second squared: 9.81 m/s² at 0.26 mm a pixel. */ +const GRAVITY = 37_000; + +/** The strap hanging free above the tab: about 24 cm. */ +const STRAP = 900; + +/** + * The tab's weight beside the badge's 1: the straps, and the chest they + * lie on, which holds them back. So a push turns the badge more than it + * moves the lanyard. + */ +const STRAP_MASS = 3; + +/** + * How quickly a swing dies away in air, each second (an e-folding rate): + * each swing about three quarters of the last. + */ +const AIR = 0.5; + +/** + * The lanyard's own sway, rubbing on clothes: more than enough to stop it + * swinging on its own, so it never trades swings with the badge. + */ +const STRAP_AIR = 10; + +/** Drag that grows with speed: big swings lose more, as in air. */ +const DRAG = 0.004; + +/** The clasp's friction, as an angular deceleration, and where it eases. */ +const CLASP = 0.05; +const CLASP_EASE = 0.2; + +/** + * How firmly a brushing pointer pushes what it passes. Like the air a hand + * pushes, it grows with the square of the speed it passes at, so a slow + * pointer barely stirs it and a brisk one swings it. + */ +const BRUSH = 0.0006; + +/** The fastest a pointer pushes: a brisk sweep, not a fling. */ +const MAX_POINTER = 3_000; + +/** The most the state may wind up past what's drawn. */ +const MAX_WIND_ANGLE = MAX_ANGLE * 2; +const MAX_WIND_SHIFT = MAX_SHIFT * 2; + +/** Integrated in short steps; a longer frame (a background tab) is cut. */ +const SUBSTEP = 1 / 240; +const MAX_STEP = 1 / 30; + +/** Below these, it's still: under half a pixel anywhere on the badge. */ +const REST_ANGLE = 0.03; +const REST_SPIN = 0.1; +const REST_SHIFT = 0.3; +const REST_DRIFT = 1; + +const RADIANS = Math.PI / 180; + +const clamp = (value: number, limit: number) => + Math.max(-limit, Math.min(limit, value)); + +const finite = (value: number) => (Number.isFinite(value) ? value : 0); + +/** One short step of the coupled tab and badge. */ +function substep(hang: Hang, badge: Badge, push: Push | null, h: number) { + const height = Math.max(badge.height, 1); + const width = Math.max(badge.width, 1); + // The badge's centre below the clasp, and its inertia about the clasp: + // a flat rectangle of mass 1. + const reach = Math.max(height / 2 - badge.pivot, 1); + const inertia = (width * width + height * height) / 12 + reach * reach; + const mass = 1 + STRAP_MASS; + + const theta = hang.angle * RADIANS; + const omega = hang.spin * RADIANS; + const cos = Math.cos(theta); + const sin = Math.sin(theta); + + // The pointer drags what it passes towards its own speed. + let force = 0; + let torque = 0; + if (push) { + const speed = clamp(finite(push.speed), MAX_POINTER); + const below = finite(push.below); + const arm = Math.max(Math.min(below, height - badge.pivot), 0); + const passing = hang.drift + arm * omega * cos; + const relative = speed - passing; + const brush = BRUSH * relative * Math.abs(relative); + force = brush; + torque = brush * arm * cos; + } + + // The tab: gravity on the straps' pendulum, air, and the push. + const pull = (-mass * GRAVITY * hang.shift) / STRAP; + const strapAir = -2 * STRAP_AIR * mass * hang.drift; + const sideways = pull + strapAir + force + reach * sin * omega * omega; + + // The badge: gravity about the clasp, air, drag, friction, and the push. + const weight = -GRAVITY * reach * sin; + const air = -2 * AIR * inertia * omega; + const drag = -DRAG * inertia * omega * Math.abs(omega); + const clasp = -CLASP * inertia * Math.tanh(omega / CLASP_EASE); + const turning = weight + air + drag + clasp + torque; + + // The two are coupled: solve for both accelerations at once. + const coupling = reach * cos; + const determinant = mass * inertia - coupling * coupling; + const along = (inertia * sideways - coupling * turning) / determinant; + const around = (mass * turning - coupling * sideways) / determinant; + + // Semi-implicit Euler: velocities first, then positions from them. + const drift = hang.drift + along * h; + const spin = omega + around * h; + return { + shift: clamp(hang.shift + drift * h, MAX_WIND_SHIFT), + drift, + angle: clamp((theta + spin * h) / RADIANS, MAX_WIND_ANGLE), + spin: spin / RADIANS, + }; +} + +/** Advances the lanyard by `seconds`, brushed by `push` if it's moving. */ +export function stepHang( + hang: Hang, + badge: Badge, + push: Push | null, + seconds: number +): Hang { + const time = Math.min(Math.max(finite(seconds), 0), MAX_STEP); + if (time === 0) return hang; + const pushing = + push !== null && + Number.isFinite(push.speed) && + Number.isFinite(push.below) && + push.speed !== 0; + if (!pushing && hang === REST) return REST; + const steps = Math.ceil(time / SUBSTEP); + let next = hang; + for (let step = 0; step < steps; step += 1) { + next = substep(next, badge, pushing ? push : null, time / steps); + } + return !pushing && atRest(next) ? REST : next; +} + +/** What to draw: eases into each cap rather than stopping at it. */ +export function drawn(hang: Hang): { shift: number; angle: number } { + return { + shift: MAX_SHIFT * Math.tanh(hang.shift / MAX_SHIFT), + angle: MAX_ANGLE * Math.tanh(hang.angle / MAX_ANGLE), + }; +} + +/** Still enough to stop animating. */ +export function atRest(hang: Hang): boolean { + return ( + Math.abs(hang.angle) < REST_ANGLE && + Math.abs(hang.spin) < REST_SPIN && + Math.abs(hang.shift) < REST_SHIFT && + Math.abs(hang.drift) < REST_DRIFT + ); +} diff --git a/web/src/features/qr/useLanyardSway.test.tsx b/web/src/features/qr/useLanyardSway.test.tsx new file mode 100644 index 0000000..c6607ed --- /dev/null +++ b/web/src/features/qr/useLanyardSway.test.tsx @@ -0,0 +1,235 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { useState } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { LanyardRibbon } from './components/LanyardRibbon/LanyardRibbon'; +import { MAX_ANGLE, MAX_SHIFT } from './lanyardPhysics'; +import { ARRIVAL_MEDIA, SWAY_MEDIA, useLanyardSway } from './useLanyardSway'; + +function Lanyard({ + enabled = true, + arrive = false, + hidden = false, +}: { + enabled?: boolean; + arrive?: boolean; + /** Not drawn yet: as a dialog's content, a render after it opens. */ + hidden?: boolean; +}) { + const [area, setArea] = useState(null); + const [sleeve, setSleeve] = useState(null); + const [ribbon, setRibbon] = useState(null); + useLanyardSway({ area, sleeve, ribbon, enabled, arrive }); + if (hidden) return null; + return ( +
+ +
+
+ ); +} + +/** Which media queries match: a mouse, motion, a wide window. */ +let media: Record = {}; +const listeners = new Set<() => void>(); + +beforeEach(() => { + media = { [SWAY_MEDIA]: true, [ARRIVAL_MEDIA]: true }; + listeners.clear(); + vi.spyOn(window, 'matchMedia').mockImplementation( + (query: string) => + ({ + get matches() { + return media[query] ?? false; + }, + media: query, + addEventListener: (_type: string, listener: () => void) => { + listeners.add(listener); + }, + removeEventListener: (_type: string, listener: () => void) => { + listeners.delete(listener); + }, + }) as unknown as MediaQueryList + ); + // jsdom lays nothing out: give the sleeve the Share badge's size. + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(350); + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(560); + vi.useFakeTimers({ + toFake: ['requestAnimationFrame', 'cancelAnimationFrame', 'performance'], + }); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const changeMedia = (query: string, matches: boolean) => { + media[query] = matches; + for (const listener of [...listeners]) listener(); +}; + +/** Moves the pointer across the lanyard, a frame at a time. */ +function sweep( + pointerType: string, + from: number, + to: number, + { frames = 10, clientY = 300 } = {} +) { + const lanyard = screen.getByTestId('lanyard'); + for (let frame = 0; frame <= frames; frame += 1) { + const clientX = from + ((to - from) * frame) / frames; + fireEvent.pointerMove(lanyard, { pointerType, clientX, clientY }); + vi.advanceTimersByTime(16); + } +} + +const TRANSFORM = /^translateX\((-?[\d.]+)px\) rotate\((-?[\d.]+)deg\)$/; + +/** The badge as drawn: its shift in px and its CSS turn in degrees. */ +function badge() { + const transform = screen.getByTestId('badge').style.transform; + if (!transform) return { shift: 0, turn: 0 }; + const match = TRANSFORM.exec(transform); + expect(match).not.toBeNull(); + return { shift: Number(match?.[1]), turn: Number(match?.[2]) }; +} + +const tab = () => document.querySelector('[data-tab]'); + +describe('useLanyardSway (#174)', () => { + it('swings the badge, and its lanyard, the way a mouse moves', () => { + render(); + sweep('mouse', 100, 500); + vi.advanceTimersByTime(60); + // Moving right swings the foot right: an anticlockwise CSS turn. + const { shift, turn } = badge(); + expect(turn).toBeLessThan(-0.2); + expect(Math.abs(turn)).toBeLessThan(MAX_ANGLE); + // The tab, and the badge's clasp with it, follow a little, and the + // straps' feet with them. jsdom draws nothing: a px is a unit. + expect(shift).toBeGreaterThan(0); + expect(shift).toBeLessThan(MAX_SHIFT); + const moved = /^translate\(([\d.]+) 0\)$/.exec( + tab()?.getAttribute('transform') ?? '' + ); + expect(Number(moved?.[1])).toBeCloseTo(shift, 1); + const left = document.querySelector('path[data-strap="left"]'); + expect(left?.getAttribute('d')).toMatch(/^M-130 -410 L15\d/); + }); + + it('sways a lanyard drawn a render after it starts, as in a dialog', () => { + const { rerender } = render(