From 84216e13ce6258e5cb9b2d2c480707ce4d198254 Mon Sep 17 00:00:00 2001 From: Barry Prendergast Date: Fri, 20 Nov 2026 21:58:16 +0000 Subject: [PATCH 1/4] feat: lanyards at /, customising at //edit (#150) The public lanyard moves to the old site's address, /. The beta's /@ links redirect there, permanently on the server too. A DID goes to /d/, and anything that can't be a handle is not found. Customise is now //edit, and only the owner may use it. Anyone else is sent to that person's lanyard; anyone signed out signs in and comes back. /lanyard forwards to your own customiser. Link previews follow the new address, and canonical URLs name it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PSPB1cH898qV61BH1NiFKL --- web/api/meta.ts | 2 +- web/e2e/customise.spec.ts | 2 +- web/e2e/feedback.spec.ts | 4 +- web/e2e/fixtures.ts | 2 +- web/e2e/lanyard.spec.ts | 45 ++++++----- web/e2e/perf.spec.ts | 2 +- web/e2e/qr.spec.ts | 2 +- web/scripts/bundleSize.ts | 2 +- web/scripts/vercelConfig.test.ts | 15 +++- web/server/metaHandler.test.ts | 14 +++- web/server/metaHandler.ts | 4 +- web/server/profileMeta.test.ts | 4 +- web/server/profileMeta.ts | 2 +- web/src/app/customise.test.tsx | 81 +++++++++++-------- web/src/app/landing.test.tsx | 14 ++-- web/src/app/lanyard.test.tsx | 56 +++++++------ .../components/HomePage/HomePage.test.tsx | 4 +- .../SampleLanyard/SampleLanyard.tsx | 2 +- .../LanyardNotFound/LanyardNotFound.test.tsx | 2 +- .../LanyardNotFound/LanyardNotFound.tsx | 2 +- .../CustomisePage/CustomisePage.constants.ts | 5 +- .../customise/CustomisePage/CustomisePage.tsx | 32 ++++++-- .../CustomisePage/CustomisePage.types.ts | 2 + web/src/hooks/useOwnPaths.ts | 11 +++ web/src/i18n/locales/en-GB/messages.po | 24 +++--- web/src/lib/person/ownPaths.test.ts | 25 ++++++ web/src/lib/person/ownPaths.ts | 25 ++++++ .../routes/{@{$handle}.tsx => $handle.tsx} | 24 +++--- web/src/routes/$handle_.edit.tsx | 46 +++++++++++ web/src/routes/__root.tsx | 2 +- web/src/routes/lanyard.tsx | 38 ++++++++- web/vercel.json | 9 ++- 32 files changed, 364 insertions(+), 140 deletions(-) create mode 100644 web/src/hooks/useOwnPaths.ts create mode 100644 web/src/lib/person/ownPaths.test.ts create mode 100644 web/src/lib/person/ownPaths.ts rename web/src/routes/{@{$handle}.tsx => $handle.tsx} (68%) create mode 100644 web/src/routes/$handle_.edit.tsx diff --git a/web/api/meta.ts b/web/api/meta.ts index 06679cb..95a57b1 100644 --- a/web/api/meta.ts +++ b/web/api/meta.ts @@ -13,7 +13,7 @@ function readIndex(): Promise { return index; } -/** /@:handle and /d/:did, with person-specific link-preview meta. */ +/** /:handle and /d/:did, with person-specific link-preview meta. */ export const GET = createMetaHandler({ readIndex, baseUrl: process.env.PUBLIC_BASE_URL, diff --git a/web/e2e/customise.spec.ts b/web/e2e/customise.spec.ts index 2b7372b..758818d 100644 --- a/web/e2e/customise.spec.ts +++ b/web/e2e/customise.spec.ts @@ -424,7 +424,7 @@ test.describe('lanyard customiser', () => { await page.getByRole('link', { name: 'Lanyards' }).click(); await page.goBack(); await expect.poll(() => dialogs).toEqual(['confirm', 'confirm']); - await expect(page).toHaveURL(/\/lanyard$/); + await expect(page).toHaveURL(/\/alice\.test\/edit$/); // Dismissing the prompt cancels the reload, so don't wait for a load. await page.evaluate(() => window.location.reload()); await expect.poll(() => dialogs).toContain('beforeunload'); diff --git a/web/e2e/feedback.spec.ts b/web/e2e/feedback.spec.ts index ded8881..eb33169 100644 --- a/web/e2e/feedback.spec.ts +++ b/web/e2e/feedback.spec.ts @@ -162,7 +162,7 @@ test.describe('feedback (#134)', () => { await expect(form.getByRole('img', { name: 'Screenshot 1' })).toBeVisible(); await form.getByLabel('Describe screenshot 1').fill('The QR sheet'); await form.getByLabel('Include technical details').check(); - await expect(form.locator('pre')).toContainText('Page: /lanyard'); + await expect(form.locator('pre')).toContainText('Page: /alice.test/edit'); // Nothing in the dialog spills sideways at 320 px. const overflow = await page.evaluate( @@ -200,7 +200,7 @@ test.describe('feedback (#134)', () => { expect(post?.record.body).toContain( 'On my phone the bottom of the code is hidden.' ); - expect(post?.record.body).toContain('Page: /lanyard'); + expect(post?.record.body).toContain('Page: /alice.test/edit'); }); test('captures the page without the dialog over it', async ({ page }) => { diff --git a/web/e2e/fixtures.ts b/web/e2e/fixtures.ts index 30ed44e..11829ba 100644 --- a/web/e2e/fixtures.ts +++ b/web/e2e/fixtures.ts @@ -3,7 +3,7 @@ import { test as base, expect } from '@playwright/test'; export const HEADING = 'Welcome to Lanyards'; /** The homepage's live sample lanyard (#145), framed at `md` and up. */ -export const SAMPLE_PATH = '/@renderg.host'; +export const SAMPLE_PATH = '/renderg.host'; const APP_ORIGIN = 'http://127.0.0.1:4173'; diff --git a/web/e2e/lanyard.spec.ts b/web/e2e/lanyard.spec.ts index 55944e8..e0bd258 100644 --- a/web/e2e/lanyard.spec.ts +++ b/web/e2e/lanyard.spec.ts @@ -13,7 +13,7 @@ const badge = (page: import('@playwright/test').Page) => test.describe('public lanyard, signed out', () => { test('shows the badge, links and Bluesky follow link', async ({ page }) => { await mockPerson(page); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(badge(page)).toBeVisible(); const links = page.getByRole('region', { name: 'Links' }); await expect( @@ -41,7 +41,7 @@ test.describe('public lanyard, signed out', () => { }, }); await page.emulateMedia({ colorScheme }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(page.getByRole('region', { name: 'Talks' })).toBeVisible(); await expect( page.getByRole('region', { name: 'Open to' }) @@ -57,7 +57,7 @@ test.describe('public lanyard, signed out', () => { }) => { await mockPerson(page); await page.setViewportSize({ width: 320, height: 640 }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(badge(page)).toBeVisible(); const width = await page.evaluate( () => document.documentElement.scrollWidth @@ -83,7 +83,7 @@ test.describe('public lanyard, signed out', () => { }, }); await page.setViewportSize({ width: 320, height: 640 }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(page.getByRole('region', { name: 'Skills' })).toBeVisible(); await expect(page.getByText(unbroken)).toBeVisible(); const width = await page.evaluate( @@ -98,7 +98,7 @@ test.describe('public lanyard, signed out', () => { const longName = `Ada${'x'.repeat(57)}`; await mockPerson(page, { sifa: { displayName: longName } }); await page.setViewportSize({ width: 320, height: 640 }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect( page.getByRole('heading', { level: 1, name: `Dr ${longName}` }) ).toBeVisible(); @@ -122,7 +122,7 @@ test.describe('public lanyard, signed out', () => { }) => { await mockPerson(page, { config: { accent } }); await page.emulateMedia({ colorScheme }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(badge(page)).toBeVisible(); await expect(page.locator('dl', { hasText: 'Now' })).toBeVisible(); const result = await new AxeBuilder({ page }) @@ -138,7 +138,7 @@ test.describe('public lanyard, signed out', () => { page, }) => { await mockPerson(page); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); const roles = page.getByRole('region', { name: 'Roles' }); const rows = roles.getByRole('listitem'); await expect(rows).toHaveCount(3); @@ -168,7 +168,7 @@ test.describe('public lanyard, signed out', () => { }, }); await page.setViewportSize({ width: 320, height: 640 }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); const roles = page.getByRole('region', { name: 'Roles' }); const title = roles.getByText('Senior Research Software Engineer'); await expect(title).toBeVisible(); @@ -186,7 +186,7 @@ test.describe('public lanyard, signed out', () => { hidden: [`at://${ADA.did}/id.sifa.profile.position/3mpos2`], }, }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); const roles = page.getByRole('region', { name: 'Roles' }); await expect(roles.getByRole('listitem')).toHaveCount(2); await expect(roles).not.toContainText('Visiting Fellow'); @@ -196,10 +196,19 @@ test.describe('public lanyard, signed out', () => { await expect(page.getByRole('link', { name: /more role/ })).toHaveCount(0); }); + test('sends the beta’s /@handle links to /handle (#150)', async ({ + page, + }) => { + await mockPerson(page); + await page.goto('/@alice.test'); + await expect(page).toHaveURL('/alice.test'); + await expect(badge(page)).toBeVisible(); + }); + test('redirects an encoded @ to the canonical URL', async ({ page }) => { await mockPerson(page); await page.goto('/%40alice.test'); - await expect(page).toHaveURL('/@alice.test'); + await expect(page).toHaveURL('/alice.test'); await expect(badge(page)).toBeVisible(); }); @@ -209,7 +218,7 @@ test.describe('public lanyard, signed out', () => { 'https://public.api.bsky.app/xrpc/app.bsky.actor.searchActorsTypeahead**', (route) => route.fulfill({ json: { actors: [] } }) ); - await page.goto('/@nobody.test'); + await page.goto('/nobody.test'); await expect( page.getByRole('heading', { name: "We couldn't find @nobody.test" }) ).toBeVisible(); @@ -220,7 +229,7 @@ test.describe('public lanyard, signed out', () => { test('respects an opt-out from logged-out viewing', async ({ page }) => { await mockPerson(page, { labels: ['!no-unauthenticated'] }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect( page.getByText( 'This person has chosen to show their lanyard only to people who are signed in.' @@ -233,7 +242,7 @@ test.describe('public lanyard, signed out', () => { page, }) => { await mockPerson(page, { sifaDown: true }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); // The title comes from Sifa: without it, the name stands alone. await expect( page.getByRole('heading', { level: 1, name: 'Ada Example' }) @@ -286,7 +295,7 @@ test.describe('public lanyard, signed in', () => { }); await signIn(page, { did: BEA.did, scope: GRANULAR }); await page.setViewportSize({ width: 320, height: 640 }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect( page.getByRole('list', { name: 'What you share' }) ).toContainText(unbroken); @@ -302,7 +311,7 @@ test.describe('public lanyard, signed in', () => { await mockPerson(page); const writes = await mockViewer(page); await signIn(page, { did: BEA.did, scope: 'atproto' }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await page.getByRole('button', { name: 'Follow' }).click(); await expect( page.getByRole('heading', { name: 'Lanyards needs your permission' }) @@ -345,7 +354,7 @@ test.describe('pills at 320 px', () => { ], }, }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect(page.getByRole('region', { name: 'Skills' })).toBeVisible(); expect( await page.evaluate(() => document.documentElement.scrollWidth) @@ -358,7 +367,7 @@ test.describe('cards', () => { page, }) => { await mockPerson(page); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); const talks = page.getByRole('region', { name: 'Talks' }); await expect(talks).toBeVisible(); // Every card holds at most one link. @@ -388,7 +397,7 @@ test.describe('cards', () => { page, }) => { await mockPerson(page); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); const talks = page.getByRole('region', { name: 'Talks' }); const card = talks.locator('[data-card]:has(a)').first(); await expect(card).toBeVisible(); diff --git a/web/e2e/perf.spec.ts b/web/e2e/perf.spec.ts index 26050a6..8e63634 100644 --- a/web/e2e/perf.spec.ts +++ b/web/e2e/perf.spec.ts @@ -24,7 +24,7 @@ async function coldLoad(browser: Browser, baseURL: string): Promise { uploadThroughput: (750 * 1024) / 8, }); - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect( page.getByRole('heading', { level: 1, name: 'Dr Ada Example' }) ).toBeVisible({ timeout: 15_000 }); diff --git a/web/e2e/qr.spec.ts b/web/e2e/qr.spec.ts index 1753f4c..9962fd3 100644 --- a/web/e2e/qr.spec.ts +++ b/web/e2e/qr.spec.ts @@ -287,7 +287,7 @@ test.describe('the Show QR badge, opened on someone else’s lanyard (#129)', () test('wears the owner’s accent, and leaves the page’s alone', async ({ page, }) => { - await page.goto('/@alice.test'); + await page.goto('/alice.test'); await expect( page.getByRole('heading', { level: 1, name: 'Dr Ada Example' }) ).toBeVisible(); diff --git a/web/scripts/bundleSize.ts b/web/scripts/bundleSize.ts index 0b20e67..250d532 100644 --- a/web/scripts/bundleSize.ts +++ b/web/scripts/bundleSize.ts @@ -8,7 +8,7 @@ export const INITIAL_JS_BUDGET_BYTES = 200 * 1024; * own (spec §2: initial JS for the public lanyard route ≤ 200 KB gzipped). */ export const PUBLIC_LANYARD_ROUTES = [ - 'routes/@{$handle}.tsx', + 'routes/$handle.tsx', 'routes/d.$did.tsx', ] as const; diff --git a/web/scripts/vercelConfig.test.ts b/web/scripts/vercelConfig.test.ts index 0409ece..9ea4d85 100644 --- a/web/scripts/vercelConfig.test.ts +++ b/web/scripts/vercelConfig.test.ts @@ -15,6 +15,7 @@ import { afterEach, describe, expect, it } from 'vitest'; type Config = { ignoreCommand: string; functions?: Record; + redirects?: { source: string; destination: string; permanent: boolean }[]; rewrites: { source: string; destination: string }[]; headers: { source: string; headers: { key: string; value: string }[] }[]; }; @@ -24,9 +25,21 @@ const config = JSON.parse( ) as Config; describe('vercel.json', () => { + // The beta's /@handle links, link previews included (#150). + it('sends /@handle on to /handle for good', () => { + expect(config.redirects).toEqual([ + { source: '/@:handle', destination: '/:handle', permanent: true }, + ]); + }); + + // A lanyard is one path segment with a dot in it: a handle. Files such + // as /sw.js are served before any rewrite. it('sends lanyard and image paths to the preview functions before the app', () => { expect(config.rewrites).toEqual([ - { source: '/@:handle', destination: '/api/meta?handle=:handle' }, + { + source: '/:handle([^/]+\\.[^/]+)', + destination: '/api/meta?handle=:handle', + }, { source: '/d/:did', destination: '/api/meta?did=:did' }, { source: '/og/p/:did.png', destination: '/api/og?did=:did' }, { source: '/og/default.png', destination: '/api/og' }, diff --git a/web/server/metaHandler.test.ts b/web/server/metaHandler.test.ts index 8616053..16d2473 100644 --- a/web/server/metaHandler.test.ts +++ b/web/server/metaHandler.test.ts @@ -28,7 +28,7 @@ const handler = (fetchImpl: typeof fetch = profileFetch) => describe('meta handler', () => { it('serves the app with person-specific meta, cached for ten minutes', async () => { const response = await handler()( - new Request('https://next.lanyards.app/@alice.test?handle=alice.test') + new Request('https://next.lanyards.app/alice.test?handle=alice.test') ); const html = await response.text(); expect(response.status).toBe(200); @@ -56,6 +56,16 @@ describe('meta handler', () => { ); }); + it('reads a bare handle from the path, the lanyard’s address (#150)', async () => { + const fetchImpl = vi.fn(profileFetch); + await handler(fetchImpl as unknown as typeof fetch)( + new Request('https://next.lanyards.app/alice.test') + ); + expect(String(vi.mocked(fetchImpl).mock.calls[0]?.[0])).toContain( + 'actor=alice.test' + ); + }); + it('serves default meta, briefly cached, when the person is unknown', async () => { const missing = (async () => Response.json( @@ -63,7 +73,7 @@ describe('meta handler', () => { { status: 400 } )) as typeof fetch; const response = await handler(missing)( - new Request('https://next.lanyards.app/@nobody.test?handle=nobody.test') + new Request('https://next.lanyards.app/nobody.test?handle=nobody.test') ); expect(response.status).toBe(200); expect(response.headers.get('cache-control')).toBe('public, s-maxage=60'); diff --git a/web/server/metaHandler.ts b/web/server/metaHandler.ts index 8bdc147..94bde96 100644 --- a/web/server/metaHandler.ts +++ b/web/server/metaHandler.ts @@ -16,7 +16,7 @@ type Options = { /** The handle or DID asked for, from the rewrite's query or the path. */ function subject(url: URL): { handle?: string; did?: string } { const handle = - url.searchParams.get('handle') ?? /^\/@([^/]+)$/.exec(url.pathname)?.[1]; + url.searchParams.get('handle') ?? /^\/@?([^/]+)$/.exec(url.pathname)?.[1]; const did = url.searchParams.get('did') ?? /^\/d\/([^/]+)$/.exec(url.pathname)?.[1]; const clean = (value?: string) => { @@ -36,7 +36,7 @@ function subject(url: URL): { handle?: string; did?: string } { } /** - * Serves the app's index.html for /@handle and /d/did with that person's + * Serves the app's index.html for /handle and /d/did with that person's * title, description and badge image, so link previews show who it is. * Anything unknown or failing gets the default meta, briefly cached. */ diff --git a/web/server/profileMeta.test.ts b/web/server/profileMeta.test.ts index c1446e4..74601d5 100644 --- a/web/server/profileMeta.test.ts +++ b/web/server/profileMeta.test.ts @@ -55,7 +55,7 @@ describe('fetchProfileMeta', () => { expect(meta).toEqual({ title: 'Ada Example (@alice.test) · Lanyards', description: 'Research Engineer', - canonical: 'https://lanyards.app/@alice.test', + canonical: 'https://lanyards.app/alice.test', image: `https://lanyards.app/og/p/${DID}.png`, imageAlt: "Ada Example's lanyard", type: 'profile', @@ -75,7 +75,7 @@ describe('fetchProfileMeta', () => { it('points the DID page at the handle URL', async () => { const meta = await fetchProfileMeta({ did: DID }, BASE, stubFetch({})); - expect(meta?.canonical).toBe('https://lanyards.app/@alice.test'); + expect(meta?.canonical).toBe('https://lanyards.app/alice.test'); }); it('gives nothing away for someone who opted out of logged-out viewing', async () => { diff --git a/web/server/profileMeta.ts b/web/server/profileMeta.ts index 18bd22a..8f5ebce 100644 --- a/web/server/profileMeta.ts +++ b/web/server/profileMeta.ts @@ -106,7 +106,7 @@ export async function fetchProfileMeta( title: `${person.displayName} (@${person.handle}) · Lanyards`, description: person.headline ?? `${person.displayName}'s conference lanyard`, - canonical: `${base}/@${person.handle}`, + canonical: `${base}/${person.handle}`, image: `${base}/og/p/${person.did}.png`, imageAlt: `${person.displayName}'s lanyard`, type: 'profile', diff --git a/web/src/app/customise.test.tsx b/web/src/app/customise.test.tsx index 9cc4211..f905744 100644 --- a/web/src/app/customise.test.tsx +++ b/web/src/app/customise.test.tsx @@ -8,7 +8,7 @@ import { useSession } from '@/features/auth/session/useSession'; import { expectNoAxeViolations } from '@/test/axe'; import { server } from '@/test/msw'; import { mockListRecords } from '@/test/handlers'; -import { ADA } from '@/test/people'; +import { ADA, BEA } from '@/test/people'; import { servePerson, signedInSession, @@ -118,6 +118,9 @@ async function jobCheckbox() { const saveChanges = () => userEvent.click(screen.getByRole('button', { name: 'Save' })); +/** The owner's customiser (#150). */ +const EDIT = `/${ADA.handle}/edit`; + beforeEach(() => { vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); document.documentElement.dataset.accent = 'blue'; @@ -125,17 +128,31 @@ beforeEach(() => { // Lazily loaded routes and Sifa's retry-then-fallback path take a few // seconds under a full parallel run. -describe('/lanyard', { timeout: 20_000 }, () => { - it('sends signed-out visitors to sign in first', async () => { +describe('//edit', { timeout: 20_000 }, () => { + it('sends signed-out visitors to sign in, then back here', async () => { vi.mocked(useSession).mockReturnValue(signedOutSession()); + const { router } = renderRoute(EDIT); + await waitForRoute(router, `/?returnTo=${encodeURIComponent(EDIT)}`, 5000); + }); + + it('forwards /lanyard to your own //edit (#150)', async () => { + servePerson(); const { router } = renderRoute('/lanyard'); - await waitForRoute(router, '/?returnTo=%2Flanyard', 5000); + await waitForRoute(router, EDIT, 5000); + expect(await preview()).toBeInTheDocument(); + }); + + it('sends anyone else to that person’s lanyard (#150)', async () => { + vi.mocked(useSession).mockReturnValue(signedInSession(BEA.did)); + servePerson(); + const { router } = renderRoute(EDIT); + await waitForRoute(router, `/${ADA.handle}`, 5000); }); it('previews the owner’s lanyard as the owner sees it', async () => { servePerson(); sifaDown(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); // The title comes from Sifa: without it, the name stands alone. expect( @@ -155,7 +172,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('the lanyard sits on its own ground, with no box round it', async () => { servePerson(); - const { container } = renderRoute('/lanyard'); + const { container } = renderRoute(EDIT); const region = await preview(); await within(region).findByRole( 'heading', @@ -184,7 +201,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('shows only its own header, with the customiser’s actions', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); await preview(); const banners = screen.getAllByRole('banner'); expect(banners).toHaveLength(1); @@ -197,7 +214,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('keeps support at the foot of the sidebar, even viewed as public (#134)', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); await preview(); expect(screen.queryByRole('contentinfo')).toBeNull(); const support = screen.getByRole('region', { name: 'Beta support' }); @@ -214,7 +231,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('keeps support at the foot of the Style sheet on phones (#134)', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); await preview(); const toolbar = screen.getByRole('toolbar', { name: 'Customiser' }); expect( @@ -241,7 +258,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('lays the lanyard out beside a pinned style sidebar', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); const sidebar = await screen.findByRole( 'complementary', { name: 'Style' }, @@ -260,7 +277,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('View as public hides the sidebar and edit controls, and Edit brings them back', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); await within(region).findByRole( 'button', @@ -289,7 +306,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('asks before leaving with unsaved changes', async () => { const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false); servePerson(); - const { router } = renderRoute('/lanyard'); + const { router } = renderRoute(EDIT); const mint = await accent('Mint'); await waitFor(() => expect(mint).toBeEnabled(), { timeout: 5000 }); await userEvent.click(mint); @@ -297,13 +314,13 @@ describe('/lanyard', { timeout: 20_000 }, () => { expect(confirm).toHaveBeenCalledWith( 'You have unsaved changes. Leave without saving?' ); - expect(router.state.location.pathname).toBe('/lanyard'); + expect(router.state.location.pathname).toBe(EDIT); confirm.mockRestore(); }); it('gives the page one level-one heading, its purpose', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); await within(region).findByRole( 'heading', @@ -318,7 +335,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('switches the preview to what visitors see', async () => { servePerson(); sifaDown(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); await within(region).findAllByText("Couldn't load Sifa", undefined, { timeout: 8000, @@ -333,7 +350,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('applies and saves a new accent, announcing progress', async () => { servePerson(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const mint = await accent('Mint'); await waitFor(() => expect(mint).toBeEnabled(), { timeout: 5000 }); await userEvent.click(mint); @@ -356,7 +373,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('resets unsaved changes to the last save, writing nothing', async () => { servePerson(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const mint = await accent('Mint'); await waitFor(() => expect(mint).toBeEnabled(), { timeout: 5000 }); const save = screen.getByRole('button', { name: 'Save' }); @@ -379,7 +396,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('saves the current-role switch', async () => { servePerson(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const job = await jobCheckbox(); await waitFor(() => expect(job).toBeEnabled(), { timeout: 5000 }); expect(job).toBeChecked(); @@ -395,7 +412,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('asks for permission instead of letting an identity-only session edit', async () => { vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did, 'atproto')); servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); expect( await screen.findByRole( 'heading', @@ -418,7 +435,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { : undefined ) ); - renderRoute('/lanyard'); + renderRoute(EDIT); await preview(); expect( await screen.findByText( @@ -433,7 +450,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('saves a new block order', async () => { servePerson(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const links = await screen.findByRole( 'listitem', { name: 'Links' }, @@ -455,7 +472,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('hides a record in place, then shows it again', async () => { servePerson(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); const hide = await within(region).findByRole( 'button', @@ -487,7 +504,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { }, }); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); await userEvent.click( await within(region).findByRole( @@ -508,7 +525,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('links can only be hidden', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); const links = await linksBlock(); expect( await within(links).findByRole( @@ -527,7 +544,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('has no Title control: the title comes from Sifa', async () => { servePerson(); - renderRoute('/lanyard'); + renderRoute(EDIT); await enabled('Hide GitHub'); expect(screen.queryByRole('combobox', { name: 'Title' })).toBeNull(); }); @@ -546,7 +563,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { ) ); servePerson({ config: { blocks: [{ type: 'media', visible: true }] } }); - renderRoute('/lanyard'); + renderRoute(EDIT); expect(await enabled('Add a podcast or video')).toBeEnabled(); expect( screen.queryByRole('heading', { name: 'Lanyards needs your permission' }) @@ -575,7 +592,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { () => new Promise(() => {}) ) ); - renderRoute('/lanyard'); + renderRoute(EDIT); expect( await screen.findByText('Updating your podcasts and videos…', undefined, { timeout: 8000, @@ -596,7 +613,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { ], }, }); - renderRoute('/lanyard'); + renderRoute(EDIT); const region = await preview(); const publications = await within(region).findByRole( 'listitem', @@ -615,7 +632,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('adds a podcast in a dialog; it’s saved only on Save', async () => { servePerson({ config: { blocks: [{ type: 'media', visible: true }] } }); const batches = captureWrites(); - renderRoute('/lanyard'); + renderRoute(EDIT); await userEvent.click(await enabled('Add a podcast or video')); const dialog = screen.getByRole('dialog', { name: 'Add a podcast or video', @@ -660,7 +677,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { servePerson({ config: { blocks: [{ type: 'media', visible: true }] } }); const batches = captureWrites(); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); await userEvent.click(await enabled('Add a podcast or video')); const dialog = screen.getByRole('dialog', { name: 'Add a podcast or video', @@ -700,7 +717,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { config: { blocks: [{ type: 'links', visible: true, limit: 0 }] }, }); const saves = captureSaves(); - renderRoute('/lanyard'); + renderRoute(EDIT); expect( await screen.findByText( "We couldn't read your lanyard settings", @@ -723,7 +740,7 @@ describe('/lanyard', { timeout: 20_000 }, () => { it('has no accessibility violations', async () => { servePerson(); - const { container } = renderRoute('/lanyard'); + const { container } = renderRoute(EDIT); const region = await preview(); await within(region).findByRole( 'heading', diff --git a/web/src/app/landing.test.tsx b/web/src/app/landing.test.tsx index 5678011..fd77dba 100644 --- a/web/src/app/landing.test.tsx +++ b/web/src/app/landing.test.tsx @@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { useSession } from '@/features/auth/session/useSession'; import { TYPEAHEAD_URL } from '@/test/fixtures'; +import { ADA } from '@/test/people'; +import { servePerson, signedInSession } from '@/test/person'; import { server } from '@/test/msw'; import { renderRoute, waitForRoute } from '@/test/router'; @@ -79,10 +81,11 @@ describe('landing page', () => { expect(document.title).toBe('Sign in · Lanyards'); }); - it('sends a signed-in visitor to their lanyard', async () => { - vi.mocked(useSession).mockReturnValue(signedIn); + it('sends a signed-in visitor to their own customiser (#150)', async () => { + vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); + servePerson(); const { router } = renderRoute('/'); - await waitForRoute(router, '/lanyard', LAZY_ROUTE_TIMEOUT); + await waitForRoute(router, `/${ADA.handle}/edit`, LAZY_ROUTE_TIMEOUT); }); it('honours a safe return path for signed-in visitors', async () => { @@ -92,8 +95,9 @@ describe('landing page', () => { }); it('ignores an unsafe return path', async () => { - vi.mocked(useSession).mockReturnValue(signedIn); + vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); + servePerson(); const { router } = renderRoute('/?returnTo=%2F%2Fevil.com'); - await waitForRoute(router, '/lanyard', LAZY_ROUTE_TIMEOUT); + await waitForRoute(router, `/${ADA.handle}/edit`, LAZY_ROUTE_TIMEOUT); }); }); diff --git a/web/src/app/lanyard.test.tsx b/web/src/app/lanyard.test.tsx index c4267d7..d86e8b2 100644 --- a/web/src/app/lanyard.test.tsx +++ b/web/src/app/lanyard.test.tsx @@ -37,7 +37,7 @@ beforeEach(() => { describe('public lanyard routes', () => { it('shows the badge for a handle', async () => { servePerson(); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect(await hero()).toBeInTheDocument(); expect(screen.getByText('she/her · @alice.test')).toBeInTheDocument(); expect( @@ -54,7 +54,7 @@ describe('public lanyard routes', () => { it("keeps the lanyard's own background on its public page", async () => { servePerson(); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); const name = await hero(); // The app chrome is neutral (#118); the lanyard keeps its brand ground. expect(name.closest('.bg-background')).not.toBeNull(); @@ -67,8 +67,12 @@ describe('public lanyard routes', () => { }); it.each([ - ['/@Alice.Test', '/@alice.test'], - ['/%40alice.test', '/@alice.test'], + ['/Alice.Test', '/alice.test'], + // The beta's links, and some apps' encoding of them (#150). + ['/@alice.test', '/alice.test'], + ['/@Alice.Test', '/alice.test'], + ['/%40alice.test', '/alice.test'], + [`/${ADA.did}`, `/d/${ADA.did}`], [`/@${ADA.did}`, `/d/${ADA.did}`], ])('redirects %s to %s', async (from, to) => { servePerson(); @@ -77,7 +81,7 @@ describe('public lanyard routes', () => { expect(await hero()).toBeInTheDocument(); }); - it.each(['/%40alice%', '/@alice%'])( + it.each(['/%40alice%', '/@alice%', '/alice%', '/not-a-handle'])( 'shows the not-found page, not an error, for a malformed escape in %s', async (path) => { renderRoute(path); @@ -100,7 +104,7 @@ describe('public lanyard routes', () => { describe('lanyard page states', () => { it('offers search when a handle does not exist', async () => { servePerson(); - const { container } = renderRoute('/@nobody.test'); + const { container } = renderRoute('/nobody.test'); expect( await screen.findByRole('heading', { name: "We couldn't find @nobody.test", @@ -122,7 +126,7 @@ describe('lanyard page states', () => { } ) ); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); const loading = await screen.findByText('Loading lanyard…', undefined, { timeout: 5000, }); @@ -137,7 +141,7 @@ describe('lanyard page states', () => { return HttpResponse.json({}); }) ); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByText('Loading lanyard…', undefined, { timeout: 5000 }) ).toBeInTheDocument(); @@ -154,7 +158,7 @@ describe('lanyard page states', () => { it("keeps the lanyard's own ground and palette for an unknown handle", async () => { servePerson(); - renderRoute('/@nobody.test'); + renderRoute('/nobody.test'); const heading = await screen.findByRole('heading', { name: "We couldn't find @nobody.test", }); @@ -168,7 +172,7 @@ describe('lanyard page states', () => { servePerson({ profileError: { error: 'AccountDeactivated', status: 400 }, }); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByRole('heading', { name: "This account isn't available", @@ -189,7 +193,7 @@ describe('lanyard page states', () => { ], }, }); - const { container } = renderRoute('/@alice.test'); + const { container } = renderRoute('/alice.test'); expect( await screen.findByText( 'This person has chosen to show their lanyard only to people who are signed in.' @@ -197,7 +201,7 @@ describe('lanyard page states', () => { ).toBeInTheDocument(); expect( within(screen.getByRole('main')).getByRole('link', { name: 'Sign in' }) - ).toHaveAttribute('href', '/?returnTo=%2F%40alice.test'); + ).toHaveAttribute('href', '/?returnTo=%2Falice.test'); expect(screen.queryByText('Dr Ada Example')).not.toBeInTheDocument(); // The name must not leak through the tab title either. await waitFor(() => @@ -222,7 +226,7 @@ describe('lanyard page states', () => { }); serveViewerReads(); vi.mocked(useSession).mockReturnValue(signedInSession(BEA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect(await hero()).toBeInTheDocument(); }); @@ -232,7 +236,7 @@ describe('lanyard page states', () => { relationship: { blockedBy: `at://${ADA.did}/app.bsky.graph.block/3m` }, }); vi.mocked(useSession).mockReturnValue(signedInSession(BEA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByText("This lanyard isn't available to you.") ).toBeInTheDocument(); @@ -241,7 +245,7 @@ describe('lanyard page states', () => { it('passes axe on a loaded lanyard', async () => { servePerson(); - const { container } = renderRoute('/@alice.test'); + const { container } = renderRoute('/alice.test'); await hero(); await expectNoAxeViolations(container); }); @@ -252,7 +256,7 @@ describe('shared context', () => { servePerson(); serveViewerReads(); vi.mocked(useSession).mockReturnValue(signedInSession(BEA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByText('You follow each other') ).toBeInTheDocument(); @@ -265,7 +269,7 @@ describe('shared context', () => { it('is absent for signed-out visitors and on your own lanyard', async () => { servePerson(); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); await hero(); expect(screen.queryByText('You follow each other')).not.toBeInTheDocument(); }); @@ -274,7 +278,7 @@ describe('shared context', () => { describe('accent', () => { it('applies the owner’s accent while their lanyard is open', async () => { servePerson({ config: { accent: 'mint' } }); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); await hero(); await waitFor(() => expect(document.documentElement.dataset.accent).toBe('mint') @@ -285,7 +289,7 @@ describe('accent', () => { describe('lanyard blocks', () => { it('shows the default blocks: links and talks', async () => { servePerson(); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); const links = await screen.findByRole('region', { name: 'Links' }); expect( within(links).getByRole('link', { name: 'GitHub (opens in a new tab)' }) @@ -307,7 +311,7 @@ describe('lanyard blocks', () => { ], }, }); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); await screen.findByRole('region', { name: 'Skills' }); const headings = screen .getAllByRole('heading', { level: 2 }) @@ -331,7 +335,7 @@ describe('lanyard blocks', () => { ) ); vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); const talks = await screen.findByRole( 'region', { name: 'Talks' }, @@ -351,7 +355,7 @@ describe('lanyard blocks', () => { describe('visitor actions on the page', () => { it('offers signed-out visitors Bluesky, with sign-in and sign-up in the header', async () => { servePerson(); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByRole('link', { name: 'Follow on Bluesky (opens in a new tab)', @@ -362,7 +366,7 @@ describe('visitor actions on the page', () => { within(header).getByRole('link', { name: 'Sign in' }) ).toHaveAttribute( 'href', - `/?returnTo=${encodeURIComponent('/@alice.test')}` + `/?returnTo=${encodeURIComponent('/alice.test')}` ); expect( within(header).getByRole('button', { name: 'Make your lanyard' }) @@ -395,7 +399,7 @@ describe('visitor actions on the page', () => { it('gives owners Edit lanyard and Show QR on the badge', async () => { servePerson(); vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); const badge = await screen.findByRole('region', { name: /Ada/ }); expect( within(badge).getByRole('link', { name: 'Edit lanyard' }) @@ -436,7 +440,7 @@ describe('blocks between viewer and owner', () => { ) ); vi.mocked(useSession).mockReturnValue(signedInSession(BEA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); await new Promise((resolve) => setTimeout(resolve, 400)); expect(screen.queryByText('Dr Ada Example')).not.toBeInTheDocument(); release(); @@ -460,7 +464,7 @@ describe('owner settings that cannot be read', () => { ) ); vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); - renderRoute('/@alice.test'); + renderRoute('/alice.test'); expect( await screen.findByText( "Couldn't load your lanyard settings", diff --git a/web/src/features/home/components/HomePage/HomePage.test.tsx b/web/src/features/home/components/HomePage/HomePage.test.tsx index b24fcce..9e7201a 100644 --- a/web/src/features/home/components/HomePage/HomePage.test.tsx +++ b/web/src/features/home/components/HomePage/HomePage.test.tsx @@ -104,11 +104,11 @@ describe('HomePage (#145)', () => { home(); const frame = screen.getByTitle('Sample lanyard'); expect(frame.tagName).toBe('IFRAME'); - expect(frame).toHaveAttribute('src', '/@renderg.host'); + expect(frame).toHaveAttribute('src', '/renderg.host'); expect(frame).toHaveAttribute('loading', 'lazy'); expect( screen.getByRole('link', { name: /View sample profile/ }) - ).toHaveAttribute('href', '/@renderg.host'); + ).toHaveAttribute('href', '/renderg.host'); }); it('takes “Create your lanyard” to the sign-in form', async () => { diff --git a/web/src/features/home/components/SampleLanyard/SampleLanyard.tsx b/web/src/features/home/components/SampleLanyard/SampleLanyard.tsx index 4a3c182..6b3ad0c 100644 --- a/web/src/features/home/components/SampleLanyard/SampleLanyard.tsx +++ b/web/src/features/home/components/SampleLanyard/SampleLanyard.tsx @@ -13,7 +13,7 @@ import type { SampleLanyardProps } from './SampleLanyard.types'; */ export function SampleLanyard({ handle, className }: SampleLanyardProps) { const { t } = useLingui(); - const href = `/@${handle}`; + const href = `/${handle}`; return (

{move.moving ? t`Updating your podcasts and videos…` : ''} diff --git a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.types.ts b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.types.ts index 17ddb8f..d0e1a77 100644 --- a/web/src/features/lanyard/customise/CustomisePage/CustomisePage.types.ts +++ b/web/src/features/lanyard/customise/CustomisePage/CustomisePage.types.ts @@ -1,3 +1,5 @@ export type CustomisePageProps = { + /** Still checking this is the owner's own page (#150): wait. */ + pending?: boolean; className?: string; }; diff --git a/web/src/hooks/useOwnPaths.ts b/web/src/hooks/useOwnPaths.ts new file mode 100644 index 0000000..76e7ea3 --- /dev/null +++ b/web/src/hooks/useOwnPaths.ts @@ -0,0 +1,11 @@ +import { useSession } from '@/features/auth/session/useSession'; +import { useProfile } from '@/lib/atproto/useProfile'; +import { type OwnPaths, ownPaths } from '@/lib/person/ownPaths'; + +/** The signed-in person's own pages (#150); null when signed out. */ +export function useOwnPaths(): OwnPaths | null { + const session = useSession(); + const did = session.status === 'signedIn' ? session.session.did : undefined; + const profile = useProfile(did); + return did ? ownPaths(did, profile.data?.handle) : null; +} diff --git a/web/src/i18n/locales/en-GB/messages.po b/web/src/i18n/locales/en-GB/messages.po index 3a7092e..90d5dad 100644 --- a/web/src/i18n/locales/en-GB/messages.po +++ b/web/src/i18n/locales/en-GB/messages.po @@ -395,7 +395,7 @@ msgstr "Create an account" msgid "Create your lanyard" msgstr "Create your lanyard" -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:153 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:169 msgid "Customise your lanyard" msgstr "Customise your lanyard" @@ -726,7 +726,7 @@ msgstr "Loading your profile…" #: src/features/account/components/SettingsPage/SettingsPage.tsx:28 #: src/features/auth/components/LandingPage/LandingPage.tsx:45 #: src/features/feedback/components/FeedbackDialog/FeedbackDialog.tsx:246 -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:56 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:71 msgid "Loading…" msgstr "Loading…" @@ -908,7 +908,7 @@ msgstr "Powerful tools designed for academic needs, not corporate networking." msgid "Preparing screenshot…" msgstr "Preparing screenshot…" -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:184 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:200 msgid "Preview" msgstr "Preview" @@ -978,7 +978,7 @@ msgstr "Researcher profiles on the AT Protocol" msgid "Reset" msgstr "Reset" -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:174 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:190 msgid "Reset to defaults" msgstr "Reset to defaults" @@ -1222,7 +1222,7 @@ msgstr "The visibility paradox" msgid "There’s no single place that represents your complete, current scholarly identity when opportunities arise." msgstr "There’s no single place that represents your complete, current scholarly identity when opportunities arise." -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:167 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:183 msgid "They may have been saved in a form Lanyards doesn't recognise. Resetting replaces them with the defaults." msgstr "They may have been saved in a form Lanyards doesn't recognise. Resetting replaces them with the defaults." @@ -1308,7 +1308,7 @@ msgstr "Update" msgid "Update once, share everywhere. No more Sunday afternoons updating ten different websites or managing multiple link collections." msgstr "Update once, share everywhere. No more Sunday afternoons updating ten different websites or managing multiple link collections." -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:159 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:175 msgid "Updating your podcasts and videos…" msgstr "Updating your podcasts and videos…" @@ -1376,7 +1376,7 @@ msgstr "We couldn't load this lanyard" msgid "We couldn't load your profile." msgstr "We couldn't load your profile." -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:164 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:180 msgid "We couldn't read your lanyard settings" msgstr "We couldn't read your lanyard settings" @@ -1421,7 +1421,7 @@ msgstr "You can hide up to 500 items. Show some again first." msgid "You follow each other" msgstr "You follow each other" -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:118 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:134 msgid "You have unsaved changes. Leave without saving?" msgstr "You have unsaved changes. Leave without saving?" @@ -1433,7 +1433,7 @@ msgstr "You're offline. Connect to sign in." msgid "You're offline. Some things won't work until you reconnect." msgstr "You're offline. Some things won't work until you reconnect." -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:180 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:196 msgid "You’re seeing your lanyard as the public sees it." msgstr "You’re seeing your lanyard as the public sees it." @@ -1467,9 +1467,9 @@ msgstr "Your feedback is posted from your own account to our board on UserInput. msgid "Your handle" msgstr "Your handle" -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:44 -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:53 -#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:124 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:54 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:68 +#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:140 #: src/features/qr/components/QrSheet/QrSheet.tsx:41 msgid "Your lanyard" msgstr "Your lanyard" diff --git a/web/src/lib/person/ownPaths.test.ts b/web/src/lib/person/ownPaths.test.ts new file mode 100644 index 0000000..3da8158 --- /dev/null +++ b/web/src/lib/person/ownPaths.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; + +import { ownPaths } from './ownPaths'; + +const DID = 'did:plc:fixturealiceaaaaaaaaaaaa'; + +describe('ownPaths (#150)', () => { + it('names your pages by handle', () => { + expect(ownPaths(DID, 'alice.test')).toEqual({ + edit: '/alice.test/edit', + view: '/alice.test', + share: '/alice.test/share', + }); + }); + + it('falls back to your DID without a handle that verifies', () => { + for (const handle of [undefined, 'handle.invalid']) { + expect(ownPaths(DID, handle)).toEqual({ + edit: `/${DID}/edit`, + view: `/d/${DID}`, + share: `/${DID}/share`, + }); + } + }); +}); diff --git a/web/src/lib/person/ownPaths.ts b/web/src/lib/person/ownPaths.ts new file mode 100644 index 0000000..219ddf5 --- /dev/null +++ b/web/src/lib/person/ownPaths.ts @@ -0,0 +1,25 @@ +/** Bluesky's stand-in for a handle that no longer verifies. */ +const INVALID_HANDLE = 'handle.invalid'; + +export type OwnPaths = { + /** Customise: `//edit`. */ + edit: string; + /** View: the public lanyard, `/`. */ + view: string; + /** Show QR: `//share`. */ + share: string; +}; + +/** + * Someone's own pages (#150), by handle; by DID while the handle is + * unknown or doesn't verify, which every one of them also accepts. + */ +export function ownPaths(did: string, handle?: string): OwnPaths { + const valid = Boolean(handle) && handle !== INVALID_HANDLE; + const id = valid ? (handle as string) : did; + return { + edit: `/${id}/edit`, + view: valid ? `/${id}` : `/d/${did}`, + share: `/${id}/share`, + }; +} diff --git a/web/src/routes/@{$handle}.tsx b/web/src/routes/$handle.tsx similarity index 68% rename from web/src/routes/@{$handle}.tsx rename to web/src/routes/$handle.tsx index c3a8363..353c3b8 100644 --- a/web/src/routes/@{$handle}.tsx +++ b/web/src/routes/$handle.tsx @@ -1,4 +1,5 @@ -import { createFileRoute, redirect } from '@tanstack/react-router'; +import { isHandle } from '@atcute/lexicons/syntax'; +import { createFileRoute, notFound, redirect } from '@tanstack/react-router'; import { LanyardPage } from '@/features/lanyard/components/LanyardPage/LanyardPage'; import { LanyardProblem } from '@/features/lanyard/components/LanyardProblem/LanyardProblem'; @@ -7,16 +8,21 @@ import { LanyardSurface } from '@/features/lanyard/components/LanyardSurface/Lan import { useResolveHandle } from '@/features/lanyard/hooks/useResolveHandle'; import { prefetchHandleLanyard } from '@/lib/person/personQueries'; -export const Route = createFileRoute('/@{$handle}')({ - beforeLoad: ({ params }) => { - // A DID after @ belongs on the stable DID route. - if (params.handle.startsWith('did:')) { - throw redirect({ href: `/d/${params.handle}` }); +/** + * A public lanyard at `/` (#150), the old site's address. The + * beta's `/@` links come here; a DID goes to its stable route. + */ +export const Route = createFileRoute('/$handle')({ + beforeLoad: ({ params, location }) => { + const bare = params.handle.replace(/^@/, ''); + if (bare.startsWith('did:')) { + throw redirect({ href: `/d/${bare}${location.searchStr}` }); } // Handles are case-insensitive; keep one canonical URL. - const lower = params.handle.toLowerCase(); - if (lower !== params.handle) { - throw redirect({ to: '/@{$handle}', params: { handle: lower } }); + const handle = bare.toLowerCase(); + if (!isHandle(handle)) throw notFound(); + if (handle !== params.handle) { + throw redirect({ href: `/${handle}${location.searchStr}` }); } }, // Starts the badge's reads while the page's code loads, so its short diff --git a/web/src/routes/$handle_.edit.tsx b/web/src/routes/$handle_.edit.tsx new file mode 100644 index 0000000..d2992dd --- /dev/null +++ b/web/src/routes/$handle_.edit.tsx @@ -0,0 +1,46 @@ +import { createFileRoute, redirect, useRouter } from '@tanstack/react-router'; +import { useEffect } from 'react'; + +import { useSession } from '@/features/auth/session/useSession'; +import { useResolveHandle } from '@/features/lanyard/hooks/useResolveHandle'; +import { CustomisePage } from '@/features/lanyard/customise/CustomisePage/CustomisePage'; + +/** + * Customise, at `//edit` (#150): the owner's alone. Anyone else + * goes to that person's lanyard; anyone signed out signs in first. A DID + * stands in for a handle that doesn't verify. + */ +export const Route = createFileRoute('/$handle_/edit')({ + beforeLoad: ({ params }) => { + const lower = params.handle.toLowerCase(); + if (!params.handle.startsWith('did:') && lower !== params.handle) { + throw redirect({ href: `/${lower}/edit` }); + } + }, + // The customiser's header carries Save and Reset. + staticData: { ownHeader: true }, + component: EditLanyard, +}); + +function EditLanyard() { + const { handle } = Route.useParams(); + const session = useSession(); + // Loading, or signed out: the customiser waits, or sends them to sign in. + if (session.status !== 'signedIn') return ; + return ; +} + +function OwnerOnly({ handle, did }: { handle: string; did: string }) { + const router = useRouter(); + const { state } = useResolveHandle(handle); + const owner = state.status === 'ready' && state.value === did; + // Someone else's, or nobody's: their lanyard page says which. + const elsewhere = + (state.status === 'ready' && !owner) || state.status === 'error'; + + useEffect(() => { + if (elsewhere) router.history.replace(`/${handle}`); + }, [elsewhere, handle, router]); + + return ; +} diff --git a/web/src/routes/__root.tsx b/web/src/routes/__root.tsx index 6781150..c8b4709 100644 --- a/web/src/routes/__root.tsx +++ b/web/src/routes/__root.tsx @@ -30,7 +30,7 @@ export const Route = createRootRouteWithContext()({ // A malformed escape (a stray %) names nobody. throw notFound(); } - throw redirect({ href: `/@${handle}${location.searchStr}` }); + throw redirect({ href: `/${handle}${location.searchStr}` }); } }, component: RootLayout, diff --git a/web/src/routes/lanyard.tsx b/web/src/routes/lanyard.tsx index 3ef93d4..c154226 100644 --- a/web/src/routes/lanyard.tsx +++ b/web/src/routes/lanyard.tsx @@ -1,9 +1,41 @@ -import { createFileRoute } from '@tanstack/react-router'; +import { createFileRoute, useRouter } from '@tanstack/react-router'; +import { useEffect } from 'react'; +import { useSession } from '@/features/auth/session/useSession'; import { CustomisePage } from '@/features/lanyard/customise/CustomisePage/CustomisePage'; +import { useOwnPaths } from '@/hooks/useOwnPaths'; +import { useProfile } from '@/lib/atproto/useProfile'; +import { ownPaths } from '@/lib/person/ownPaths'; +/** + * `/lanyard` forwards to your own customiser, `//edit` (#150): old + * bookmarks, and where sign-in lands. Signed out, you sign in first. + */ export const Route = createFileRoute('/lanyard')({ - // The customiser's header carries Save, Reset and View as public. staticData: { ownHeader: true }, - component: CustomisePage, + component: ForwardToCustomise, }); + +function ForwardToCustomise() { + const session = useSession(); + if (session.status !== 'signedIn') return ; + return ; +} + +function Forward({ did }: { did: string }) { + const router = useRouter(); + const profile = useProfile(did); + const own = useOwnPaths(); + // Once the handle is known, or can't be: then by DID. + const target = profile.isSuccess + ? own?.edit + : profile.isError + ? ownPaths(did).edit + : undefined; + + useEffect(() => { + if (target) router.history.replace(target); + }, [target, router]); + + return ; +} diff --git a/web/vercel.json b/web/vercel.json index d1deb6d..b034e75 100644 --- a/web/vercel.json +++ b/web/vercel.json @@ -12,9 +12,16 @@ "includeFiles": "node_modules/{@resvg/resvg-wasm/index_bg.wasm,@fontsource/rethink-sans/files/rethink-sans-latin-{400,700}-normal.woff2}" } }, - "rewrites": [ + "redirects": [ { "source": "/@:handle", + "destination": "/:handle", + "permanent": true + } + ], + "rewrites": [ + { + "source": "/:handle([^/]+\\.[^/]+)", "destination": "/api/meta?handle=:handle" }, { From 49984f0ed542e71c5b94da3b20a497460b3e52c8 Mon Sep 17 00:00:00 2001 From: Barry Prendergast Date: Fri, 20 Nov 2026 22:11:46 +0000 Subject: [PATCH 2/4] feat: Show QR as its own page, //share (#150) The QR badge now opens full screen at //share, for anyone's lanyard, with no app header. Close and Escape go back to where you were, or to the lanyard if the page was opened directly. Show QR, in the header and on the badge, is now a link to your own share page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PSPB1cH898qV61BH1NiFKL --- web/e2e/qr.spec.ts | 31 ++-- web/scripts/styleRules.test.ts | 2 + web/src/app/lanyard.test.tsx | 2 +- web/src/app/share.test.tsx | 113 ++++++++++++ web/src/app/staticData.ts | 5 + .../components/AppHeader/AppHeader.test.tsx | 4 +- .../HeroActions/HeroActions.test.tsx | 2 +- .../CustomiserActions.test.tsx | 2 +- .../components/SharePage/SharePage.styles.ts | 3 + .../qr/components/SharePage/SharePage.tsx | 56 ++++++ .../components/SharePage/SharePage.types.ts | 4 + .../ShowQrButton/ShowQrButton.test.tsx | 164 ++---------------- .../components/ShowQrButton/ShowQrButton.tsx | 69 ++------ web/src/i18n/locales/en-GB/messages.po | 7 +- web/src/lib/person/ownPaths.test.ts | 2 + web/src/lib/person/ownPaths.ts | 3 + web/src/routes/$handle_.share.tsx | 20 +++ web/src/routes/__root.tsx | 6 +- web/src/test/router.tsx | 13 +- 19 files changed, 284 insertions(+), 224 deletions(-) create mode 100644 web/src/app/share.test.tsx create mode 100644 web/src/features/qr/components/SharePage/SharePage.styles.ts create mode 100644 web/src/features/qr/components/SharePage/SharePage.tsx create mode 100644 web/src/features/qr/components/SharePage/SharePage.types.ts create mode 100644 web/src/routes/$handle_.share.tsx diff --git a/web/e2e/qr.spec.ts b/web/e2e/qr.spec.ts index 9962fd3..821fb99 100644 --- a/web/e2e/qr.spec.ts +++ b/web/e2e/qr.spec.ts @@ -28,7 +28,7 @@ test.describe('QR sheet', () => { await expect( page.getByRole('heading', { name: 'Customise your lanyard' }) ).toBeVisible(); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); await expect( page.getByRole('dialog', { name: 'Dr Ada Example' }) ).toBeVisible(); @@ -41,13 +41,15 @@ test.describe('QR sheet', () => { }) => { await context.grantPermissions(['clipboard-read', 'clipboard-write']); await page.goto('/lanyard'); - const show = page.getByRole('button', { name: 'Show QR' }); + const show = page.getByRole('link', { name: 'Show QR' }); await expect(show).toBeVisible(); expect( await page.evaluate(() => document.documentElement.scrollWidth) ).toBeLessThanOrEqual(320); await show.click(); + // Its own page now, //share (#150). + await expect(page).toHaveURL('/alice.test/share'); const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); await expect(sheet).toBeVisible(); await expect(sheet.getByText('Scan to see my lanyard')).toBeVisible(); @@ -68,16 +70,17 @@ test.describe('QR sheet', () => { const copied = await page.evaluate(() => navigator.clipboard.readText()); expect(copied).toMatch(new RegExp(`/d/${ADA.did}$`)); + // Back where it was opened. await page.keyboard.press('Escape'); await expect(sheet).toBeHidden(); - await expect(show).toBeFocused(); + await expect(page).toHaveURL('/alice.test/edit'); }); test('keeps the whole code at least 240 px wide on a 320×640 screen (#129)', async ({ page, }) => { await page.goto('/lanyard'); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); const qr = sheet.getByRole('img', { name: /^QR code for / }); await expect(qr).toBeVisible(); @@ -103,7 +106,7 @@ test.describe('QR sheet', () => { const viewport = { width: 844, height: 390 }; await page.setViewportSize(viewport); await page.goto('/lanyard'); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); const qr = sheet.getByRole('img', { name: /^QR code for / }); await expect(qr).toBeVisible(); @@ -128,7 +131,7 @@ test.describe('QR sheet', () => { await mockPerson(page, { config: { accent: 'lime' } }); await page.setViewportSize({ width: 844, height: 390 }); await page.goto('/lanyard'); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); await expect(sheet).toHaveAttribute('data-accent', 'lime'); for (const name of ['Copy link', 'Close']) { @@ -171,7 +174,7 @@ test.describe('QR sheet', () => { const viewport = { width: 430, height: 390 }; await page.setViewportSize(viewport); await page.goto('/lanyard'); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); const sheet = page.getByRole('dialog', { name: 'Dr Ada Example' }); await expect(sheet).toBeVisible(); // Nothing spills or scrolls, in either direction. @@ -206,7 +209,7 @@ test.describe('QR sheet', () => { test('stays black on white in dark mode', async ({ page }) => { await page.emulateMedia({ colorScheme: 'dark' }); await page.goto('/lanyard'); - await page.getByRole('button', { name: 'Show QR' }).click(); + await page.getByRole('link', { name: 'Show QR' }).click(); const qr = page.getByRole('img', { name: /^QR code for / }); await expect(qr.locator('rect')).toHaveAttribute('fill', '#ffffff'); await expect(qr.locator('path')).toHaveAttribute('fill', '#000000'); @@ -223,7 +226,10 @@ test.describe('the Show QR badge, opened on someone else’s lanyard (#129)', () await page.route( 'https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile**', (route) => - new URL(route.request().url()).searchParams.get('actor') === BEA.did + // By DID or by handle, as the AppView answers. + [BEA.did, 'bea.test'].includes( + new URL(route.request().url()).searchParams.get('actor') ?? '' + ) ? route.fulfill({ json: { did: BEA.did, @@ -295,7 +301,7 @@ test.describe('the Show QR badge, opened on someone else’s lanyard (#129)', () page.evaluate(() => document.documentElement.dataset.accent); expect(await pageAccent()).toBe('mint'); - const show = page.getByRole('banner').getByRole('button', { + const show = page.getByRole('banner').getByRole('link', { name: 'Show QR', }); await show.click(); @@ -304,12 +310,13 @@ test.describe('the Show QR badge, opened on someone else’s lanyard (#129)', () await expect(sheet).toHaveAttribute('data-accent', 'pink'); const card = sheet.locator('.bg-accent').first(); await expect(card).toHaveCSS('background-color', 'rgb(247, 135, 154)'); - expect(await pageAccent()).toBe('mint'); const result = await new AxeBuilder({ page }).withTags(WCAG).analyze(); expect(result.violations).toEqual([]); + // Back on Ada's lanyard, in Ada's accent. await sheet.getByRole('button', { name: 'Close' }).click(); await expect(sheet).toBeHidden(); - expect(await pageAccent()).toBe('mint'); + await expect(page).toHaveURL('/alice.test'); + await expect.poll(pageAccent).toBe('mint'); }); }); diff --git a/web/scripts/styleRules.test.ts b/web/scripts/styleRules.test.ts index d3ed046..68a560c 100644 --- a/web/scripts/styleRules.test.ts +++ b/web/scripts/styleRules.test.ts @@ -122,6 +122,8 @@ const CHROME = [ const LANYARD_ONLY = [ 'src/components/RichText/', 'src/features/qr/components/QrSheet/', + // Show QR as a page (#150): the badge's ground while it loads. + 'src/features/qr/components/SharePage/', 'src/features/qr/components/LanyardStraps/', ]; diff --git a/web/src/app/lanyard.test.tsx b/web/src/app/lanyard.test.tsx index d86e8b2..f7b89d7 100644 --- a/web/src/app/lanyard.test.tsx +++ b/web/src/app/lanyard.test.tsx @@ -405,7 +405,7 @@ describe('visitor actions on the page', () => { within(badge).getByRole('link', { name: 'Edit lanyard' }) ).toHaveAttribute('href', '/lanyard'); expect( - within(badge).getByRole('button', { name: 'Show QR' }) + within(badge).getByRole('link', { name: 'Show QR' }) ).toBeInTheDocument(); }); }); diff --git a/web/src/app/share.test.tsx b/web/src/app/share.test.tsx new file mode 100644 index 0000000..c309bb1 --- /dev/null +++ b/web/src/app/share.test.tsx @@ -0,0 +1,113 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { notify } from '@/components/Toaster/notify'; +import { useSession } from '@/features/auth/session/useSession'; +import { qrUrl } from '@/features/qr/qrUrl'; +import { captureError, track } from '@/lib/analytics/analytics'; +import { expectNoAxeViolations } from '@/test/axe'; +import { ADA } from '@/test/people'; +import { servePerson, signedInSession, signedOutSession } from '@/test/person'; +import { renderRoute, waitForRoute } from '@/test/router'; + +vi.mock('@/features/auth/session/useSession', () => ({ useSession: vi.fn() })); +vi.mock('@/lib/analytics/analytics', () => ({ + captureError: vi.fn(), + track: vi.fn(), +})); +vi.mock('@/components/Toaster/notify', () => ({ + notify: { success: vi.fn(), error: vi.fn(), info: vi.fn() }, +})); + +const SHARE = `/${ADA.handle}/share`; + +const release = vi.fn(async () => undefined); +const request = vi.fn(async () => ({ + release, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), +})); + +beforeEach(() => { + vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); + servePerson(); + Object.defineProperty(navigator, 'wakeLock', { + value: { request }, + configurable: true, + }); +}); + +afterEach(() => { + Reflect.deleteProperty(navigator, 'wakeLock'); +}); + +const badge = () => + screen.findByRole('dialog', { name: 'Dr Ada Example' }, { timeout: 5000 }); + +describe('//share (#150)', { timeout: 20_000 }, () => { + it('shows the QR badge full screen, with no app header', async () => { + renderRoute(SHARE); + expect(await badge()).toHaveTextContent('Scan to see my lanyard'); + expect( + screen.getByRole('img', { name: `QR code for ${qrUrl(ADA.did)}` }) + ).toBeInTheDocument(); + expect(screen.queryByRole('banner')).toBeNull(); + expect(track).toHaveBeenCalledWith('qr_opened'); + }); + + it('works for anyone’s lanyard, signed in or not', async () => { + vi.mocked(useSession).mockReturnValue(signedOutSession()); + renderRoute(SHARE); + expect(await badge()).toBeInTheDocument(); + }); + + it('copies the link, saying so when it can’t', async () => { + const user = userEvent.setup(); + const writeText = vi.spyOn(navigator.clipboard, 'writeText'); + renderRoute(SHARE); + await badge(); + await user.click(screen.getByRole('button', { name: 'Copy link' })); + expect(writeText).toHaveBeenCalledWith(qrUrl(ADA.did)); + await waitFor(() => + expect(notify.success).toHaveBeenCalledWith('Link copied') + ); + + writeText.mockRejectedValueOnce(new Error('Denied')); + await user.click(screen.getByRole('button', { name: 'Copy link' })); + await waitFor(() => + expect(notify.error).toHaveBeenCalledWith( + "Couldn't copy the link. Please try again." + ) + ); + expect(captureError).toHaveBeenCalledWith(new Error('Denied'), { + source: 'copy-link', + }); + }); + + it('goes back to where you were on Close', async () => { + const { router } = renderRoute([`/${ADA.handle}/edit`, SHARE]); + await badge(); + await userEvent.click(screen.getByRole('button', { name: 'Close' })); + await waitForRoute(router, `/${ADA.handle}/edit`, 5000); + }); + + it('goes to the lanyard on Escape when opened directly', async () => { + const { router } = renderRoute(SHARE); + await badge(); + await userEvent.keyboard('{Escape}'); + await waitForRoute(router, `/${ADA.handle}`, 5000); + }); + + it('keeps the screen awake while it’s open', async () => { + renderRoute(SHARE); + await badge(); + await waitFor(() => expect(request).toHaveBeenCalledWith('screen')); + }); + + it('has no axe violations', async () => { + const { baseElement } = renderRoute(SHARE); + await badge(); + await expectNoAxeViolations(baseElement as HTMLElement); + }); +}); diff --git a/web/src/app/staticData.ts b/web/src/app/staticData.ts index a67f8ce..ace4905 100644 --- a/web/src/app/staticData.ts +++ b/web/src/app/staticData.ts @@ -11,6 +11,11 @@ declare module '@tanstack/react-router' { * lanyard (lanyard pages, #129). */ signedOutActions?: boolean; + /** + * The route fills the screen itself (Show QR, #150): the root layout + * renders no header, no

and no navigation around it. + */ + fullScreen?: boolean; } } diff --git a/web/src/components/AppHeader/AppHeader.test.tsx b/web/src/components/AppHeader/AppHeader.test.tsx index 3934b7c..e8ccabf 100644 --- a/web/src/components/AppHeader/AppHeader.test.tsx +++ b/web/src/components/AppHeader/AppHeader.test.tsx @@ -37,7 +37,7 @@ describe('AppHeader', () => { screen.queryByRole('link', { name: 'My lanyard' }) ).not.toBeInTheDocument(); expect( - screen.queryByRole('button', { name: 'Show QR' }) + screen.queryByRole('link', { name: 'Show QR' }) ).not.toBeInTheDocument(); }); @@ -57,7 +57,7 @@ describe('AppHeader', () => { 'href', '/lanyard' ); - expect(screen.getByRole('button', { name: 'Show QR' })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Show QR' })).toBeInTheDocument(); }); it('renders a title and actions when given, in place of its own links', async () => { diff --git a/web/src/features/lanyard/components/HeroActions/HeroActions.test.tsx b/web/src/features/lanyard/components/HeroActions/HeroActions.test.tsx index 066ac1a..e07aedb 100644 --- a/web/src/features/lanyard/components/HeroActions/HeroActions.test.tsx +++ b/web/src/features/lanyard/components/HeroActions/HeroActions.test.tsx @@ -125,7 +125,7 @@ describe('HeroActions when signed in', () => { expect( await screen.findByRole('link', { name: 'Edit lanyard' }) ).toHaveAttribute('href', '/lanyard'); - expect(screen.getByRole('button', { name: 'Show QR' })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Show QR' })).toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Follow' }) ).not.toBeInTheDocument(); diff --git a/web/src/features/lanyard/customise/CustomiserActions/CustomiserActions.test.tsx b/web/src/features/lanyard/customise/CustomiserActions/CustomiserActions.test.tsx index edecdf2..85133f0 100644 --- a/web/src/features/lanyard/customise/CustomiserActions/CustomiserActions.test.tsx +++ b/web/src/features/lanyard/customise/CustomiserActions/CustomiserActions.test.tsx @@ -118,7 +118,7 @@ describe('CustomiserActions', () => { expect( await screen.findByRole('link', { name: 'Your account' }) ).toHaveAttribute('href', '/settings'); - expect(button('Show QR')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Show QR' })).toBeInTheDocument(); }); it('has no axe violations', async () => { diff --git a/web/src/features/qr/components/SharePage/SharePage.styles.ts b/web/src/features/qr/components/SharePage/SharePage.styles.ts new file mode 100644 index 0000000..5fdc5cc --- /dev/null +++ b/web/src/features/qr/components/SharePage/SharePage.styles.ts @@ -0,0 +1,3 @@ +// The badge's own ground while its owner is looked up. +export const waiting = + 'fixed inset-0 flex items-center justify-center bg-qr-ground text-base leading-6 text-on-badge-ink'; diff --git a/web/src/features/qr/components/SharePage/SharePage.tsx b/web/src/features/qr/components/SharePage/SharePage.tsx new file mode 100644 index 0000000..cc1d62f --- /dev/null +++ b/web/src/features/qr/components/SharePage/SharePage.tsx @@ -0,0 +1,56 @@ +import { useLingui } from '@lingui/react/macro'; +import { useCanGoBack, useRouter } from '@tanstack/react-router'; +import { useEffect } from 'react'; + +import { useResolveHandle } from '@/features/lanyard/hooks/useResolveHandle'; +import { track } from '@/lib/analytics/analytics'; + +import { QrSheet } from '../QrSheet/QrSheet'; +import * as styles from './SharePage.styles'; +import type { SharePageProps } from './SharePage.types'; + +/** + * Show QR as a page, `//share` (#150): the badge full screen, for + * anyone's public lanyard. Close goes back where you were, or to the + * lanyard when the page was opened on its own. + */ +export function SharePage({ handle }: SharePageProps) { + const { t } = useLingui(); + const router = useRouter(); + const canGoBack = useCanGoBack(); + const { state } = useResolveHandle(handle); + const unknown = state.status === 'error'; + + useEffect(() => { + track('qr_opened'); + }, []); + + // Nobody by that name: their lanyard page says so. + useEffect(() => { + if (unknown) router.history.replace(`/${handle}`); + }, [unknown, handle, router]); + + function close() { + if (canGoBack) router.history.back(); + else router.history.replace(`/${handle}`); + } + + if (state.status !== 'ready') { + return ( +

+ {t`Loading…`} +

+ ); + } + return ( + { + if (!open) close(); + }} + // Focus belongs to the page Close goes to. + returnFocus={() => {}} + /> + ); +} diff --git a/web/src/features/qr/components/SharePage/SharePage.types.ts b/web/src/features/qr/components/SharePage/SharePage.types.ts new file mode 100644 index 0000000..89373a4 --- /dev/null +++ b/web/src/features/qr/components/SharePage/SharePage.types.ts @@ -0,0 +1,4 @@ +export type SharePageProps = { + /** Whose badge: a handle, or a DID. */ + handle: string; +}; diff --git a/web/src/features/qr/components/ShowQrButton/ShowQrButton.test.tsx b/web/src/features/qr/components/ShowQrButton/ShowQrButton.test.tsx index 71f61d8..1359b77 100644 --- a/web/src/features/qr/components/ShowQrButton/ShowQrButton.test.tsx +++ b/web/src/features/qr/components/ShowQrButton/ShowQrButton.test.tsx @@ -1,167 +1,41 @@ -import { screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { notify } from '@/components/Toaster/notify'; import { useSession } from '@/features/auth/session/useSession'; -import { captureError, track } from '@/lib/analytics/analytics'; import { expectNoAxeViolations } from '@/test/axe'; import { ADA } from '@/test/people'; -import { servePerson, signedInSession } from '@/test/person'; -import { renderWithClient } from '@/test/render'; +import { servePerson, signedInSession, signedOutSession } from '@/test/person'; +import { renderInRouter } from '@/test/router'; -import { qrUrl } from '../../qrUrl'; import { ShowQrButton } from './ShowQrButton'; vi.mock('@/features/auth/session/useSession', () => ({ useSession: vi.fn() })); -vi.mock('@/lib/analytics/analytics', () => ({ - captureError: vi.fn(), - track: vi.fn(), -})); -vi.mock('@/components/Toaster/notify', () => ({ - notify: { success: vi.fn(), error: vi.fn(), info: vi.fn() }, -})); -// Reading the export throws while `sheetFails` is set, as a chunk that -// failed to load would. -const sheetFails = vi.hoisted(() => ({ value: false })); -vi.mock('../QrSheet/QrSheet', async (importOriginal) => { - const actual = await importOriginal(); - return { - get QrSheet() { - if (sheetFails.value) { - throw new TypeError('Failed to fetch dynamically imported module'); - } - return actual.QrSheet; - }, - }; -}); - -const release = vi.fn(async () => undefined); -const request = vi.fn(async () => ({ - release, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), -})); beforeEach(() => { vi.mocked(useSession).mockReturnValue(signedInSession(ADA.did)); servePerson(); - Object.defineProperty(navigator, 'wakeLock', { - value: { request }, - configurable: true, - }); }); -afterEach(() => { - Reflect.deleteProperty(navigator, 'wakeLock'); - sheetFails.value = false; -}); - -const open = async () => { - await userEvent.click(screen.getByRole('button', { name: 'Show QR' })); - return screen.findByRole( - 'dialog', - { name: 'Dr Ada Example' }, - { timeout: 5000 } - ); -}; - -describe('ShowQrButton', () => { - it('opens a sheet with the owner’s name and QR code', async () => { - renderWithClient(); - const sheet = await open(); - expect(sheet).toHaveTextContent('Scan to see my lanyard'); - expect( - screen.getByRole('img', { name: `QR code for ${qrUrl(ADA.did)}` }) - ).toBeInTheDocument(); - expect(track).toHaveBeenCalledWith('qr_opened'); - }); - - it('copies the link as a text alternative', async () => { - const user = userEvent.setup(); - const writeText = vi.spyOn(navigator.clipboard, 'writeText'); - renderWithClient(); - await user.click(screen.getByRole('button', { name: 'Show QR' })); - await screen.findByRole( - 'dialog', - { name: 'Dr Ada Example' }, - { timeout: 5000 } - ); - await user.click(screen.getByRole('button', { name: 'Copy link' })); - expect(writeText).toHaveBeenCalledWith(qrUrl(ADA.did)); - await waitFor(() => - expect(notify.success).toHaveBeenCalledWith('Link copied') +describe('ShowQrButton (#150)', () => { + it('goes to your own Show QR page', async () => { + const { container } = renderInRouter(); + const link = await screen.findByRole('link', { name: 'Show QR' }); + await vi.waitFor(() => + expect(link).toHaveAttribute('href', `/${ADA.handle}/share`) ); + await expectNoAxeViolations(container); }); - it('says so and reports it when copying fails', async () => { - const user = userEvent.setup(); - vi.spyOn(navigator.clipboard, 'writeText').mockRejectedValueOnce( - new Error('Denied') - ); - renderWithClient(); - await user.click(screen.getByRole('button', { name: 'Show QR' })); - await screen.findByRole( - 'dialog', - { name: 'Dr Ada Example' }, - { timeout: 5000 } - ); - await user.click(screen.getByRole('button', { name: 'Copy link' })); - await waitFor(() => - expect(notify.error).toHaveBeenCalledWith( - "Couldn't copy the link. Please try again." - ) - ); - expect(captureError).toHaveBeenCalledWith(new Error('Denied'), { - source: 'copy-link', - }); - }); - - it('says so, and opens on a later try, when the sheet fails to load', async () => { - sheetFails.value = true; - renderWithClient(); - const show = screen.getByRole('button', { name: 'Show QR' }); - await userEvent.click(show); - await waitFor(() => - expect(notify.error).toHaveBeenCalledWith( - "Couldn't open your QR code. Please try again." - ) - ); - expect(captureError).toHaveBeenCalledWith(expect.any(TypeError), { - source: 'qr-sheet', - }); - expect(screen.queryByRole('dialog')).toBeNull(); - - sheetFails.value = false; - await userEvent.click(show); + it('is a link on the badge too', async () => { + renderInRouter(); expect( - await screen.findByRole( - 'dialog', - { name: 'Dr Ada Example' }, - { timeout: 5000 } - ) - ).toBeVisible(); - }); - - it('closes on Escape and returns focus to the button', async () => { - renderWithClient(); - await open(); - await userEvent.keyboard('{Escape}'); - await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); - expect(screen.getByRole('button', { name: 'Show QR' })).toHaveFocus(); - }); - - it('keeps the screen awake while open', async () => { - renderWithClient(); - await open(); - await waitFor(() => expect(request).toHaveBeenCalledWith('screen')); - await userEvent.click(screen.getByRole('button', { name: 'Close' })); - await waitFor(() => expect(release).toHaveBeenCalled()); + await screen.findByRole('link', { name: 'Show QR' }) + ).toBeInTheDocument(); }); - it('has no axe violations when open', async () => { - const { baseElement } = renderWithClient(); - await open(); - await expectNoAxeViolations(baseElement as HTMLElement); + it('shows nothing when signed out', () => { + vi.mocked(useSession).mockReturnValue(signedOutSession()); + renderInRouter(); + expect(screen.queryByRole('link', { name: 'Show QR' })).toBeNull(); }); }); diff --git a/web/src/features/qr/components/ShowQrButton/ShowQrButton.tsx b/web/src/features/qr/components/ShowQrButton/ShowQrButton.tsx index 099e429..b8bdb8c 100644 --- a/web/src/features/qr/components/ShowQrButton/ShowQrButton.tsx +++ b/web/src/features/qr/components/ShowQrButton/ShowQrButton.tsx @@ -1,66 +1,29 @@ import { useLingui } from '@lingui/react/macro'; +import { Link } from '@tanstack/react-router'; import { QrCode } from 'lucide-react'; -import { useRef, useState } from 'react'; -import { notify } from '@/components/Toaster/notify'; -import { useSession } from '@/features/auth/session/useSession'; -import { captureError, track } from '@/lib/analytics/analytics'; +import { useOwnPaths } from '@/hooks/useOwnPaths'; import { cn } from '@/lib/utils'; -import type { QrSheet } from '../QrSheet/QrSheet'; import * as styles from './ShowQrButton.styles'; import type { ShowQrButtonProps } from './ShowQrButton.types'; -type Sheet = typeof QrSheet; - -// The sheet (QR encoder and dialog) loads on first use, outside every -// route's initial JS; the service worker precaches it for offline use. -const loadSheet = (): Promise => - import('../QrSheet/QrSheet').then((module) => module.QrSheet); - -/** "Show QR" in the header or on the badge: opens the owner's QR sheet. */ +/** + * "Show QR" in the header or on the badge: goes to your own Show QR page, + * `//share` (#150). Nothing when signed out. + */ export function ShowQrButton({ tone = 'ui', className }: ShowQrButtonProps) { const { t } = useLingui(); - const session = useSession(); - const [open, setOpen] = useState(false); - /** The sheet, once its code has loaded. */ - const [Sheet, setSheet] = useState(null); - const button = useRef(null); - if (session.status !== 'signedIn') return null; - - async function show() { - track('qr_opened'); - try { - const loaded = Sheet ?? (await loadSheet()); - setSheet(() => loaded); - setOpen(true); - } catch (cause) { - // Offline before the sheet was cached, or a deploy replaced it: the - // app keeps working and the next press tries again. - captureError(cause, { source: 'qr-sheet' }); - notify.error(t`Couldn't open your QR code. Please try again.`); - } - } - + const own = useOwnPaths(); + if (!own) return null; return ( - <> - - {Sheet && ( - button.current?.focus()} - /> - )} - + +