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.initials}
-
+
+
+
+
+
+
+
+
+ {hero.avatar ? (
+

+ ) : (
+
+ {hero.initials}
+
+ )}
+
+
+
+ {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…`}
-
-
-
-
+
+
+ {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 (
-
-
+
+
{children}
diff --git a/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.types.ts b/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.types.ts
index 230185a..6b47909 100644
--- a/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.types.ts
+++ b/web/src/features/qr/components/BadgeSleeve/BadgeSleeve.types.ts
@@ -5,6 +5,10 @@ export type BadgeSleeveProps = {
children: ReactNode;
/** The sleeve: the element that turns, if it sways. */
ref?: Ref
;
+ /** What it hangs on: the brand ground (the default), or a page (#173). */
+ ground?: 'brand' | 'page';
+ /** Out of reach: the face of a badge that's turned away (#175). */
+ inert?: boolean;
className?: string;
/** The lip's slot, where the clasp goes through. */
slotClassName?: string;
diff --git a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.constants.ts b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.constants.ts
index 24d21a5..9997cde 100644
--- a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.constants.ts
+++ b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.constants.ts
@@ -7,10 +7,14 @@
export const VIEW = { width: 320, height: 210 };
export const STRAPS = {
- left: 'M-130 -410 L150 150',
- right: 'M450 -410 L170 150',
+ /** Each strap, from far above the box down to the tab, as [x, y]. */
+ left: { from: [-130, -410], to: [150, 150] },
+ right: { from: [450, -410], to: [170, 150] },
width: 44,
-};
+} as const;
+
+/** The hairline each side of an edged strap (#173). */
+export const EDGE = 1;
/** Enough repeats to print each strap from the top of any screen. */
export const REPEATS = 14;
@@ -22,3 +26,10 @@ export const METAL = ['#8d8ba3', '#f1f1f7', '#77758c'] as const;
/** What Lanyards' own lanyards print, where there's no person's handle. */
export const BRAND_PRINT = 'lanyards.app';
+
+/** A strap's path, its foot moved `shift` units sideways with the tab. */
+export function strapPath(side: 'left' | 'right', shift = 0): string {
+ const { from, to } = STRAPS[side];
+ const foot = Math.round((to[0] + shift) * 100) / 100;
+ return `M${from[0]} ${from[1]} L${foot} ${to[1]}`;
+}
diff --git a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.styles.ts b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.styles.ts
index 6a284fc..d37e361 100644
--- a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.styles.ts
+++ b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.styles.ts
@@ -1,16 +1,33 @@
-// The straps in the owner's strap colour, printed in the badge's label
-// colour, which reads on it (spec §8); the clasp is metal on any accent.
+// The straps, printed in a colour that reads on them; the clasp is metal
+// on any ground. Every class is written out in full: Tailwind only
+// generates those.
+
// Decoration: anything it hangs over still takes the click.
export const ribbon = 'pointer-events-none overflow-visible';
-export const strap = 'fill-none stroke-qr-strap';
-
-export const print =
- 'fill-board-label text-[16px] font-bold uppercase tracking-[0.16em]';
-
-export const tab = 'fill-qr-strap';
-
-export const stitch = 'stroke-board-label';
+export const print = 'text-[16px] font-bold uppercase tracking-[0.16em]';
-/** The clasp's hook, open where the ground shows through. */
-export const gap = 'fill-qr-ground';
+/**
+ * ink: the owner's strap colour, printed in the badge's label colour, on
+ * the brand blue or ink (spec §8, #169). accent: the badge's own accent,
+ * edged with a hairline, on a page that may be light or dark (#173).
+ */
+export const tones = {
+ ink: {
+ strap: 'fill-none stroke-qr-strap',
+ print: 'fill-board-label',
+ tab: 'fill-qr-strap',
+ stitch: 'stroke-board-label',
+ // The clasp's hook, open where the ground shows through.
+ gap: 'fill-qr-ground',
+ edge: undefined,
+ },
+ accent: {
+ strap: 'fill-none stroke-accent',
+ print: 'fill-on-accent',
+ tab: 'fill-accent stroke-border-strong',
+ stitch: 'stroke-on-accent',
+ gap: 'fill-background',
+ edge: 'fill-none stroke-border-strong',
+ },
+} as const;
diff --git a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.test.tsx b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.test.tsx
index da85e7e..4ae6490 100644
--- a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.test.tsx
+++ b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.test.tsx
@@ -1,4 +1,5 @@
import { render } from '@testing-library/react';
+import { createRef } from 'react';
import { describe, expect, it } from 'vitest';
import { LanyardRibbon } from './LanyardRibbon';
@@ -33,4 +34,40 @@ describe('LanyardRibbon (#169)', () => {
const ids = [...container.querySelectorAll('path[id]')].map((p) => p.id);
expect(new Set(ids).size).toBe(ids.length);
});
+
+ it('wears the ink strap by default, as on the brand blue (#169)', () => {
+ const { container } = render();
+ const straps = container.querySelectorAll('path[id]');
+ for (const strap of straps) {
+ expect(strap.getAttribute('class')).toContain('stroke-qr-strap');
+ }
+ expect(container.querySelector('[data-edge]')).toBeNull();
+ });
+
+ it('wears the accent, edged, on a page that may be light or dark (#173)', () => {
+ const { container } = render(
+
+ );
+ const straps = container.querySelectorAll('path[id]');
+ for (const strap of straps) {
+ expect(strap.getAttribute('class')).toContain('stroke-accent');
+ }
+ for (const print of container.querySelectorAll('text')) {
+ expect(print.getAttribute('class')).toContain('fill-on-accent');
+ }
+ // A hairline under each strap, so a pale accent reads on white.
+ expect(container.querySelectorAll('[data-edge]')).toHaveLength(2);
+ });
+
+ it('hands its drawing to what sways it, straps and tab marked (#174)', () => {
+ const drawing = createRef();
+ const { container } = render(
+
+ );
+ expect(drawing.current).toBe(container.querySelector('svg'));
+ // Each strap, and its edge, by side; the tab and clasp in one group.
+ expect(container.querySelectorAll('[data-strap="left"]')).toHaveLength(2);
+ expect(container.querySelectorAll('[data-strap="right"]')).toHaveLength(2);
+ expect(container.querySelector('[data-tab] circle')).not.toBeNull();
+ });
});
diff --git a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.tsx b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.tsx
index 48b3bfb..02f6c4e 100644
--- a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.tsx
+++ b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.tsx
@@ -3,39 +3,40 @@ import { useId } from 'react';
import { cn } from '@/lib/utils';
import {
+ EDGE,
METAL,
REPEATS,
SEPARATOR,
STRAPS,
+ strapPath,
VIEW,
} from './LanyardRibbon.constants';
import * as styles from './LanyardRibbon.styles';
import type { LanyardRibbonProps } from './LanyardRibbon.types';
+const SIDES = ['left', 'right'] as const;
+
/**
* A lanyard (#169): two straps printed with `text`, meeting at a sewn tab
* above a swivel ring and a clasp. The clasp's hook ends at the bottom
- * edge, to go through the slot of the badge below.
+ * edge, to go through the slot of the badge below. Its `ref` is the
+ * drawing, which useLanyardSway moves as the lanyard sways (#174).
*/
-export function LanyardRibbon({ text, className }: LanyardRibbonProps) {
+export function LanyardRibbon({
+ text,
+ tone = 'ink',
+ ref,
+ className,
+}: LanyardRibbonProps) {
const id = useId();
- const printed = Array.from({ length: REPEATS }, () => text).join(SEPARATOR);
- const strap = (side: 'left' | 'right') => (
- <>
-
-
- {printed}
-
- >
- );
+ const colours = styles.tones[tone];
+ const printed = text
+ ? Array.from({ length: REPEATS }, () => text).join(SEPARATOR)
+ : '';
return (
);
}
diff --git a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.types.ts b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.types.ts
index 3f71188..7af69c0 100644
--- a/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.types.ts
+++ b/web/src/features/qr/components/LanyardRibbon/LanyardRibbon.types.ts
@@ -1,8 +1,19 @@
+import type { Ref } from 'react';
+
+export type LanyardTone = 'ink' | 'accent';
+
export type LanyardRibbonProps = {
/**
* Printed along both straps, repeated: the person's handle (#169), or
* Lanyards' own address (#170).
*/
text: string;
+ /** ink on the brand ground (the default); accent on a page (#173). */
+ tone?: LanyardTone;
+ /**
+ * The drawing, for a lanyard that sways (#174): its straps are marked
+ * data-strap, by side, and its tab and clasp are one data-tab group.
+ */
+ ref?: Ref;
className?: string;
};
diff --git a/web/src/features/qr/components/QrSheet/QrSheet.styles.ts b/web/src/features/qr/components/QrSheet/QrSheet.styles.ts
index a4e3b68..ad31832 100644
--- a/web/src/features/qr/components/QrSheet/QrSheet.styles.ts
+++ b/web/src/features/qr/components/QrSheet/QrSheet.styles.ts
@@ -43,7 +43,8 @@ export const ribbon =
// The sleeve (BadgeSleeve), a little tighter on the narrowest phones;
// sideways the screen is the badge, so there's no sleeve.
-export const sleeve = 'max-[22.5rem]:p-1.5 max-[22.5rem]:pt-7 flat:contents';
+export const sleeve =
+ 'max-[22.5rem]:origin-[50%_0.875rem] max-[22.5rem]:p-1.5 max-[22.5rem]:pt-7 flat:contents';
export const slot = 'max-[22.5rem]:top-2 flat:hidden';
diff --git a/web/src/features/qr/components/QrSheet/QrSheet.test.tsx b/web/src/features/qr/components/QrSheet/QrSheet.test.tsx
index af47a40..66e673b 100644
--- a/web/src/features/qr/components/QrSheet/QrSheet.test.tsx
+++ b/web/src/features/qr/components/QrSheet/QrSheet.test.tsx
@@ -10,6 +10,7 @@ import { ADA } from '@/test/people';
import { servePerson } from '@/test/person';
import { renderWithClient } from '@/test/render';
+import { SWAY_MEDIA } from '../../useLanyardSway';
import { QrSheet } from './QrSheet';
vi.mock('@/lib/analytics/analytics', () => ({
@@ -232,3 +233,56 @@ describe('QrSheet, a lanyard in a clear sleeve (#169)', () => {
);
});
});
+
+describe('QrSheet, a lanyard that sways (#174)', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('sways on its clasp as a mouse moves across it, then settles', async () => {
+ vi.spyOn(window, 'matchMedia').mockImplementation(
+ (query: string) =>
+ ({
+ matches: query === SWAY_MEDIA,
+ media: query,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ }) as unknown as MediaQueryList
+ );
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(350);
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(560);
+ servePerson();
+ sheet();
+ const dialog = await screen.findByRole('dialog', {
+ name: 'Dr Ada Example',
+ });
+ await waitFor(() =>
+ expect(dialog.querySelector('textPath')?.textContent).toContain(
+ '@alice.test'
+ )
+ );
+ vi.useFakeTimers({
+ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'],
+ });
+ const sleeve = dialog.querySelector('[data-sleeve]');
+ expect(sleeve).not.toBeNull();
+ for (let x = 100; x <= 600; x += 50) {
+ fireEvent.pointerMove(sleeve as HTMLElement, {
+ pointerType: 'mouse',
+ clientX: x,
+ clientY: 300,
+ });
+ vi.advanceTimersByTime(16);
+ }
+ expect(sleeve?.style.transform).toMatch(
+ /^translateX\([\d.]+px\) rotate\(-[\d.]+deg\)$/
+ );
+ // The lanyard's tab sways with it.
+ expect(
+ dialog.querySelector('[data-tab]')?.getAttribute('transform')
+ ).toMatch(/^translate\(/);
+ vi.advanceTimersByTime(8000);
+ expect(sleeve?.style.transform).toBe('');
+ });
+});
diff --git a/web/src/features/qr/components/QrSheet/QrSheet.tsx b/web/src/features/qr/components/QrSheet/QrSheet.tsx
index bc07ec4..467dd1a 100644
--- a/web/src/features/qr/components/QrSheet/QrSheet.tsx
+++ b/web/src/features/qr/components/QrSheet/QrSheet.tsx
@@ -12,6 +12,7 @@ import { captureError } from '@/lib/analytics/analytics';
import { heroName } from '@/lib/person/hero';
import { qrUrl } from '../../qrUrl';
+import { useLanyardSway } from '../../useLanyardSway';
import { useOwnerBadge } from '../../useOwnerBadge';
import { BadgeSleeve } from '../BadgeSleeve/BadgeSleeve';
import { LanyardRibbon } from '../LanyardRibbon/LanyardRibbon';
@@ -54,6 +55,12 @@ export function QrSheet({
// An avatar that won't load gives way to the initials, not a blank disc.
const [brokenAvatar, setBrokenAvatar] = useState(null);
useWakeLock(open);
+ // A mouse brushing past sways it, as on the homepage (#174). It doesn't
+ // swing in as it opens: the code is there to be scanned at once.
+ const [hang, setHang] = useState(null);
+ const [sleeve, setSleeve] = useState(null);
+ const [ribbon, setRibbon] = useState(null);
+ useLanyardSway({ area: hang, sleeve, ribbon, enabled: open && !!hero });
async function copy() {
try {
@@ -114,14 +121,16 @@ export function QrSheet({
{t`Point a camera at the code to open my lanyard, or send the link.`}
-
+
{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();
+ rerender();
+ sweep('mouse', 100, 500);
+ vi.advanceTimersByTime(60);
+ expect(badge().turn).toBeLessThan(-0.2);
+ });
+
+ it('comes to rest, straightens and stops animating', () => {
+ render();
+ sweep('mouse', 500, 100);
+ expect(badge().turn).toBeGreaterThan(0);
+ vi.advanceTimersByTime(8000);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ expect(tab()?.hasAttribute('transform')).toBe(false);
+ expect(
+ document.querySelector('path[data-strap="left"]')?.getAttribute('d')
+ ).toBe('M-130 -410 L150 150');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('leaves it 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', () => {
+ media[SWAY_MEDIA] = 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(badge().turn).not.toBe(0);
+ changeMedia(SWAY_MEDIA, false);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ expect(tab()?.hasAttribute('transform')).toBe(false);
+ 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,
+ clientY: 300,
+ });
+ 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,
+ clientY: 300,
+ });
+ vi.advanceTimersByTime(300);
+ expect(Math.abs(badge().turn)).toBeLessThan(0.05);
+ });
+
+ it('stays straight and still while turned off, as for a form', () => {
+ const { rerender } = render();
+ sweep('mouse', 100, 500);
+ expect(badge().turn).not.toBe(0);
+ rerender();
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ expect(vi.getTimerCount()).toBe(0);
+ sweep('mouse', 500, 100);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ });
+
+ it('swings in as it arrives, then settles, on a wide screen', () => {
+ render();
+ vi.advanceTimersByTime(100);
+ expect(Math.abs(badge().turn)).toBeGreaterThan(1);
+ vi.advanceTimersByTime(8000);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('arrives still with reduced motion, or on a phone', () => {
+ media[ARRIVAL_MEDIA] = false;
+ render();
+ vi.advanceTimersByTime(100);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does nothing where the sleeve has no box of its own', () => {
+ // The Share screen, sideways: the screen itself is the badge.
+ render();
+ screen.getByTestId('badge').style.display = 'contents';
+ sweep('mouse', 100, 500);
+ vi.advanceTimersByTime(8000);
+ sweep('mouse', 500, 100);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(screen.getByTestId('badge').style.transform).toBe('');
+ });
+
+ it('lets go when it unmounts mid-swing', () => {
+ const { unmount } = render();
+ sweep('mouse', 100, 500);
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(listeners.size).toBe(0);
+ });
+});
diff --git a/web/src/features/qr/useLanyardSway.ts b/web/src/features/qr/useLanyardSway.ts
new file mode 100644
index 0000000..ea7547c
--- /dev/null
+++ b/web/src/features/qr/useLanyardSway.ts
@@ -0,0 +1,224 @@
+import { useEffect } from 'react';
+
+import {
+ strapPath,
+ VIEW,
+} from './components/LanyardRibbon/LanyardRibbon.constants';
+import {
+ atRest,
+ type Badge,
+ drawn,
+ type Hang,
+ type Push,
+ REST,
+ stepHang,
+} from './lanyardPhysics';
+
+/**
+ * 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, and on the
+ * Share screen a phone's code stays still to be scanned.
+ */
+export const SWAY_MEDIA =
+ '(prefers-reduced-motion: no-preference) and (hover: hover) and (pointer: fine)';
+
+/** Swing in on arrival only with motion, and only on a wide screen. */
+export const ARRIVAL_MEDIA =
+ '(prefers-reduced-motion: no-preference) and (min-width: 48rem)';
+
+/** The lean a badge arrives at, as if just let go, in degrees. */
+const ARRIVAL_ANGLE = 3.5;
+
+/** Where the clasp is below the sleeve's top, if the style doesn't say. */
+const DEFAULT_PIVOT = 16;
+
+/**
+ * The elements themselves, not refs: held in state by callback refs, so
+ * the sway starts when they appear, even a render later, as a dialog's
+ * content does in its portal.
+ */
+export type LanyardSwayOptions = {
+ /** Where a mouse brushing past pushes it: the lanyard and the badge. */
+ area: HTMLElement | null;
+ /** What swings: the sleeve, turning about its transform origin. */
+ sleeve: HTMLElement | null;
+ /** The lanyard's drawing (LanyardRibbon's ref): its tab sways too. */
+ ribbon?: SVGSVGElement | null;
+ /** Off: straight and still, as while it shows a form (#175). */
+ enabled?: boolean;
+ /** Swing in as it first appears, then settle (the homepage's). */
+ arrive?: boolean;
+};
+
+/**
+ * Moves the lanyard's tab, and the clasp under it, `units` of its drawing
+ * sideways: the straps' feet follow it. 0 hangs it straight.
+ */
+function shiftTab(drawing: SVGSVGElement, units: number) {
+ for (const side of ['left', 'right'] as const) {
+ for (const strap of drawing.querySelectorAll(`[data-strap="${side}"]`)) {
+ strap.setAttribute('d', strapPath(side, units));
+ }
+ }
+ const tab = drawing.querySelector('[data-tab]');
+ if (!tab) return;
+ if (units === 0) tab.removeAttribute('transform');
+ else
+ tab.setAttribute(
+ 'transform',
+ `translate(${Math.round(units * 100) / 100} 0)`
+ );
+}
+
+/** The clasp's height in the sleeve, from its CSS transform origin. */
+function pivotOf(element: HTMLElement): number {
+ const [, y] = getComputedStyle(element).transformOrigin.split(' ');
+ const pivot = Number.parseFloat(y ?? '');
+ return Number.isFinite(pivot) ? pivot : DEFAULT_PIVOT;
+}
+
+/**
+ * Hangs `sleeve` from its lanyard with real physics (#174): a mouse
+ * brushing across `area` pushes it, at the mouse's height, and it swings
+ * and settles (see ./lanyardPhysics). It animates only while it moves: at
+ * rest there is no frame loop and no transform. The sleeve's transform is
+ * set frame by frame here; its classes set the transform origin, where
+ * the clasp is.
+ */
+export function useLanyardSway({
+ area,
+ sleeve,
+ ribbon,
+ enabled = true,
+ arrive = false,
+}: LanyardSwayOptions): void {
+ useEffect(() => {
+ const zone = area;
+ const target = sleeve;
+ if (!zone || !target || !enabled) return;
+ const sway = window.matchMedia(SWAY_MEDIA);
+ const arrival = window.matchMedia(ARRIVAL_MEDIA);
+
+ let hang: Hang = REST;
+ let frame = 0;
+ let lastFrame: number | null = null;
+ let lastX: number | null = null;
+ let lastY = 0;
+ /** Pixels moved sideways since the last frame. */
+ let moved = 0;
+ /**
+ * The badge's size, its clasp on the page, and the lanyard's drawing
+ * units a pixel, as it set off.
+ */
+ let geometry: { badge: Badge; pivotY: number; units: number } | null = null;
+
+ function measure(element: HTMLElement) {
+ const pivot = pivotOf(element);
+ const top = element.getBoundingClientRect().top + window.scrollY;
+ const drawn = ribbon?.getBoundingClientRect().height ?? 0;
+ return {
+ units: drawn > 0 ? VIEW.height / drawn : 1,
+ badge: {
+ width: element.offsetWidth,
+ height: element.offsetHeight,
+ pivot,
+ },
+ pivotY: top + pivot,
+ };
+ }
+
+ function straighten() {
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ lastFrame = null;
+ lastX = null;
+ moved = 0;
+ hang = REST;
+ geometry = null;
+ target?.style.removeProperty('transform');
+ if (ribbon) shiftTab(ribbon, 0);
+ }
+
+ function draw() {
+ const { shift, angle } = drawn(hang);
+ target?.style.setProperty(
+ 'transform',
+ `translateX(${shift.toFixed(2)}px) rotate(${(-angle).toFixed(3)}deg)`
+ );
+ if (ribbon) shiftTab(ribbon, shift * (geometry?.units ?? 1));
+ }
+
+ 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 || !geometry) {
+ frame = requestAnimationFrame(tick);
+ return;
+ }
+ const push: Push | null =
+ moved === 0
+ ? null
+ : {
+ speed: moved / seconds,
+ below: lastY + window.scrollY - geometry.pivotY,
+ };
+ moved = 0;
+ hang = stepHang(hang, geometry.badge, push, seconds);
+ if (!push && atRest(hang)) {
+ straighten();
+ return;
+ }
+ draw();
+ frame = requestAnimationFrame(tick);
+ }
+
+ /** No box of its own (the Share screen sideways): nothing to turn. */
+ const boxless = () =>
+ !target || getComputedStyle(target).display === 'contents';
+
+ function start() {
+ if (boxless()) return;
+ if (target && !geometry) geometry = measure(target);
+ if (!frame) frame = requestAnimationFrame(tick);
+ }
+
+ function onMove(event: PointerEvent) {
+ if (event.pointerType !== 'mouse' || !sway.matches) return;
+ if (lastX !== null) moved += event.clientX - lastX;
+ lastX = event.clientX;
+ lastY = event.clientY;
+ start();
+ }
+
+ // Coming back in elsewhere isn't a sweep across the gap.
+ function onLeave() {
+ lastX = null;
+ }
+
+ // Asked for less motion mid-swing, or the mouse has gone: hang
+ // straight at once, unless it's still swinging in as it arrives.
+ function onMediaChange() {
+ if (!sway.matches && !(arrive && arrival.matches)) straighten();
+ }
+
+ if (arrive && arrival.matches && !boxless()) {
+ geometry = measure(target);
+ hang = { ...REST, angle: ARRIVAL_ANGLE };
+ draw();
+ start();
+ }
+
+ zone.addEventListener('pointermove', onMove);
+ zone.addEventListener('pointerleave', onLeave);
+ sway.addEventListener('change', onMediaChange);
+ arrival.addEventListener('change', onMediaChange);
+ return () => {
+ zone.removeEventListener('pointermove', onMove);
+ zone.removeEventListener('pointerleave', onLeave);
+ sway.removeEventListener('change', onMediaChange);
+ arrival.removeEventListener('change', onMediaChange);
+ straighten();
+ };
+ }, [area, sleeve, ribbon, enabled, arrive]);
+}
diff --git a/web/src/hooks/useFocusOnNavigation.test.tsx b/web/src/hooks/useFocusOnNavigation.test.tsx
new file mode 100644
index 0000000..5733ea0
--- /dev/null
+++ b/web/src/hooks/useFocusOnNavigation.test.tsx
@@ -0,0 +1,82 @@
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+ Outlet,
+ RouterProvider,
+} from '@tanstack/react-router';
+import { render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useFocusOnNavigation } from './useFocusOnNavigation';
+
+function Root() {
+ useFocusOnNavigation();
+ return ;
+}
+
+/** Two pages; on the second, a face turned away holds the first h1. */
+function app() {
+ const root = createRootRoute({ component: Root });
+ const home = createRoute({
+ getParentRoute: () => root,
+ path: '/',
+ component: () => (
+
+ Home
+
+ ),
+ });
+ const turned = createRoute({
+ getParentRoute: () => root,
+ path: '/turned',
+ component: () => (
+
+
+
Turned away
+
+
+
Turned up
+
+
+ ),
+ });
+ const router = createRouter({
+ routeTree: root.addChildren([home, turned]),
+ history: createMemoryHistory({ initialEntries: ['/'] }),
+ });
+ render();
+ return router;
+}
+
+describe('useFocusOnNavigation', () => {
+ it('leaves the first load alone', async () => {
+ app();
+ expect(
+ await screen.findByRole('heading', { name: 'Home' })
+ ).not.toHaveFocus();
+ });
+
+ it('lands on the new page’s heading after navigating', async () => {
+ const router = app();
+ await screen.findByRole('heading', { name: 'Home' });
+ router.history.push('/turned');
+ await waitFor(() =>
+ expect(screen.getByRole('heading', { name: 'Turned up' })).toHaveFocus()
+ );
+ });
+
+ // A badge turned over keeps its front in the page, out of reach (#175).
+ it('skips a heading that’s out of reach', async () => {
+ const router = app();
+ await screen.findByRole('heading', { name: 'Home' });
+ router.history.push('/turned');
+ await waitFor(() =>
+ expect(screen.getByRole('heading', { name: 'Turned up' })).toHaveFocus()
+ );
+ expect(
+ screen.getByRole('heading', { name: 'Turned away' })
+ ).not.toHaveFocus();
+ });
+});
diff --git a/web/src/hooks/useFocusOnNavigation.ts b/web/src/hooks/useFocusOnNavigation.ts
index 46cb177..67f40e4 100644
--- a/web/src/hooks/useFocusOnNavigation.ts
+++ b/web/src/hooks/useFocusOnNavigation.ts
@@ -3,8 +3,8 @@ import { useEffect } from 'react';
/**
* After client-side navigation, moves focus to the new page's main heading
- * so keyboard and screen-reader users land on, and hear, the new content.
- * The first load is left alone.
+ * so keyboard and screen-reader users land on, and hear, the new content:
+ * the first one within reach. The first load is left alone.
*/
export function useFocusOnNavigation(): void {
const router = useRouter();
@@ -14,7 +14,11 @@ export function useFocusOnNavigation(): void {
router.subscribe('onResolved', (event) => {
if (!event.fromLocation || !event.pathChanged) return;
requestAnimationFrame(() => {
- const heading = document.querySelector('main h1');
+ // The first within reach: a badge turned over keeps its other
+ // face in the page, inert (#175).
+ const heading = [
+ ...document.querySelectorAll('main h1'),
+ ].find((candidate) => !candidate.closest('[inert]'));
if (!heading) return;
heading.tabIndex = -1;
heading.focus();
diff --git a/web/src/i18n/locales/en-GB/messages.po b/web/src/i18n/locales/en-GB/messages.po
index c0c8fd2..5118414 100644
--- a/web/src/i18n/locales/en-GB/messages.po
+++ b/web/src/i18n/locales/en-GB/messages.po
@@ -42,7 +42,7 @@ msgstr "{name} is over position {position} of {total}."
msgid "{name} moved to position {position} of {total}"
msgstr "{name} moved to position {position} of {total}"
-#: src/features/qr/components/QrSheet/QrSheet.tsx:70
+#: src/features/qr/components/QrSheet/QrSheet.tsx:77
msgid "{name} on Lanyards"
msgstr "{name} on Lanyards"
@@ -159,7 +159,7 @@ msgid "Badge"
msgstr "Badge"
#: src/features/lanyard/components/DepartureBoard/DepartureBoard.tsx:84
-#: src/features/qr/components/QrSheet/QrSheet.tsx:160
+#: src/features/qr/components/QrSheet/QrSheet.tsx:169
msgid "Based"
msgstr "Based"
@@ -199,7 +199,7 @@ msgstr "Bluesky isn't answering right now. Check your connection and try again."
msgid "Board positions"
msgstr "Board positions"
-#: src/features/home/components/HomePage/HomePage.tsx:102
+#: src/features/home/components/HomePage/HomePage.tsx:112
msgid "Built for researchers"
msgstr "Built for researchers"
@@ -211,7 +211,7 @@ msgstr "Built on"
msgid "Built on AT Protocol—transparent, inspectable, and aligned with academic values of openness and reusability."
msgstr "Built on AT Protocol—transparent, inspectable, and aligned with academic values of openness and reusability."
-#: src/features/home/components/HomePage/HomePage.tsx:144
+#: src/features/home/components/HomePage/HomePage.tsx:154
msgid "Built on the AT Protocol"
msgstr "Built on the AT Protocol"
@@ -227,7 +227,7 @@ msgstr "Capture this screen"
msgid "Career continuity"
msgstr "Career continuity"
-#: src/features/home/components/HomePage/HomePage.tsx:70
+#: src/features/home/components/HomePage/HomePage.tsx:80
msgid "Career progression demands comprehensive online presence, but maintaining it is administratively overwhelming."
msgstr "Career progression demands comprehensive online presence, but maintaining it is administratively overwhelming."
@@ -266,7 +266,7 @@ msgstr "Clear"
#: src/components/Dialog/Dialog.tsx:75
#: src/components/Sheet/Sheet.tsx:59
-#: src/features/qr/components/QrSheet/QrSheet.tsx:191
+#: src/features/qr/components/QrSheet/QrSheet.tsx:200
msgid "Close"
msgstr "Close"
@@ -306,7 +306,7 @@ msgstr "Connect ORCID, and your publications appear automatically."
msgid "Constant maintenance"
msgstr "Constant maintenance"
-#: src/features/home/components/HomePage/HomePage.tsx:165
+#: src/features/home/components/HomePage/HomePage.tsx:175
msgid "Contact"
msgstr "Contact"
@@ -315,7 +315,7 @@ msgid "Contract roles"
msgstr "Contract roles"
#: src/features/lanyard/customise/OrcidHelper/OrcidHelper.tsx:149
-#: src/features/qr/components/QrSheet/QrSheet.tsx:189
+#: src/features/qr/components/QrSheet/QrSheet.tsx:198
msgid "Copy link"
msgstr "Copy link"
@@ -340,7 +340,7 @@ msgid "Couldn't copy it. Please try again."
msgstr "Couldn't copy it. Please try again."
#: src/features/lanyard/customise/OrcidHelper/OrcidHelper.tsx:94
-#: src/features/qr/components/QrSheet/QrSheet.tsx:64
+#: src/features/qr/components/QrSheet/QrSheet.tsx:71
msgid "Couldn't copy the link. Please try again."
msgstr "Couldn't copy the link. Please try again."
@@ -357,7 +357,7 @@ msgstr "Couldn't load your lanyard settings"
msgid "Couldn't open feedback. Please try again."
msgstr "Couldn't open feedback. Please try again."
-#: src/features/qr/components/QrSheet/QrSheet.tsx:75
+#: src/features/qr/components/QrSheet/QrSheet.tsx:82
msgid "Couldn't open sharing. Copy the link instead."
msgstr "Couldn't open sharing. Copy the link instead."
@@ -396,7 +396,7 @@ msgstr "Cover"
msgid "Create an account"
msgstr "Create an account"
-#: src/features/home/components/HomePage/HomePage.tsx:129
+#: src/features/home/components/HomePage/HomePage.tsx:139
msgid "Create your lanyard"
msgstr "Create your lanyard"
@@ -405,7 +405,7 @@ msgstr "Create your lanyard"
msgid "Customise"
msgstr "Customise"
-#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:161
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:160
msgid "Customise your lanyard"
msgstr "Customise your lanyard"
@@ -435,7 +435,7 @@ msgid "Discard your unsaved changes?"
msgstr "Discard your unsaved changes?"
#: src/features/feedback/components/SupportLinks/SupportLinks.tsx:54
-#: src/features/home/components/HomePage/HomePage.tsx:151
+#: src/features/home/components/HomePage/HomePage.tsx:161
msgid "Documentation"
msgstr "Documentation"
@@ -483,7 +483,7 @@ msgstr "Enter your handle"
msgid "Enter your handle, not your email — for example alice.bsky.social"
msgstr "Enter your handle, not your email — for example alice.bsky.social"
-#: src/features/home/components/HomePage/HomePage.tsx:43
+#: src/features/home/components/HomePage/HomePage.tsx:53
msgid "Everything you work on, in one link"
msgstr "Everything you work on, in one link"
@@ -516,7 +516,7 @@ msgstr "Follow"
msgid "Follow @{BLUESKY_HANDLE} on Bluesky"
msgstr "Follow @{BLUESKY_HANDLE} on Bluesky"
-#: src/features/home/components/HomePage/HomePage.tsx:136
+#: src/features/home/components/HomePage/HomePage.tsx:146
#: src/features/lanyard/components/HeroActions/HeroActions.tsx:60
msgid "Follow on Bluesky"
msgstr "Follow on Bluesky"
@@ -565,11 +565,11 @@ msgstr "For example alice.bsky.social"
msgid "Full-time roles"
msgstr "Full-time roles"
-#: src/features/home/components/HomePage/HomePage.tsx:42
+#: src/features/home/components/HomePage/HomePage.tsx:52
msgid "Get started"
msgstr "Get started"
-#: src/features/home/components/HomePage/HomePage.tsx:158
+#: src/features/home/components/HomePage/HomePage.tsx:168
msgid "GitHub"
msgstr "GitHub"
@@ -627,7 +627,7 @@ msgstr "Interview"
msgid "Items to show for {name}"
msgstr "Items to show for {name}"
-#: src/features/home/components/HomePage/HomePage.tsx:122
+#: src/features/home/components/HomePage/HomePage.tsx:132
msgid "Join researchers building their professional identity on open infrastructure."
msgstr "Join researchers building their professional identity on open infrastructure."
@@ -691,11 +691,11 @@ msgstr "Lanyards needs your permission"
msgid "Lanyards needs your permission to post feedback"
msgstr "Lanyards needs your permission to post feedback"
-#: src/features/home/components/HomePage/HomePage.tsx:83
+#: src/features/home/components/HomePage/HomePage.tsx:93
msgid "Lanyards pulls together your complete scholarly presence with zero maintenance overhead."
msgstr "Lanyards pulls together your complete scholarly presence with zero maintenance overhead."
-#: src/features/home/components/HomePage/HomePage.tsx:62
+#: src/features/home/components/HomePage/HomePage.tsx:72
msgid "Learn more"
msgstr "Learn more"
@@ -708,7 +708,7 @@ msgid "Lime"
msgstr "Lime"
#: src/features/lanyard/customise/OrcidHelper/OrcidHelper.tsx:91
-#: src/features/qr/components/QrSheet/QrSheet.tsx:61
+#: src/features/qr/components/QrSheet/QrSheet.tsx:68
msgid "Link copied"
msgstr "Link copied"
@@ -720,17 +720,17 @@ msgstr "Link to add"
msgid "Links"
msgstr "Links"
-#: src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx:14
+#: src/features/lanyard/components/LanyardSkeleton/LanyardSkeleton.tsx:19
msgid "Loading lanyard…"
msgstr "Loading lanyard…"
-#: src/features/account/components/AccountCard/AccountCard.tsx:39
+#: src/features/account/components/AccountCard/AccountCard.tsx:41
msgid "Loading your profile…"
msgstr "Loading your profile…"
#: src/features/account/components/SettingsPage/SettingsPage.tsx:28
#: src/features/feedback/components/FeedbackDialog/FeedbackDialog.tsx:246
-#: src/features/home/components/SignInPage/SignInPage.tsx:68
+#: src/features/home/components/SignInFace/SignInFace.tsx:43
#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:68
#: src/features/qr/components/SharePage/SharePage.tsx:41
msgid "Loading…"
@@ -800,11 +800,11 @@ msgstr "Nothing to show yet"
#: src/features/lanyard/components/blocks/RolesBlock/RolesBlock.tsx:59
#: src/features/lanyard/components/DepartureBoard/DepartureBoard.tsx:67
-#: src/features/qr/components/QrSheet/QrSheet.tsx:154
+#: src/features/qr/components/QrSheet/QrSheet.tsx:163
msgid "Now"
msgstr "Now"
-#: src/features/home/components/HomePage/HomePage.tsx:82
+#: src/features/home/components/HomePage/HomePage.tsx:92
msgid "One link, everything visible"
msgstr "One link, everything visible"
@@ -895,7 +895,7 @@ msgstr "Podcast episode"
msgid "Podcasts and videos"
msgstr "Podcasts and videos"
-#: src/features/qr/components/QrSheet/QrSheet.tsx:114
+#: src/features/qr/components/QrSheet/QrSheet.tsx:121
msgid "Point a camera at the code to open my lanyard, or send the link."
msgstr "Point a camera at the code to open my lanyard, or send the link."
@@ -903,7 +903,7 @@ msgstr "Point a camera at the code to open my lanyard, or send the link."
msgid "Post on Bluesky, {date}"
msgstr "Post on Bluesky, {date}"
-#: src/features/home/components/HomePage/HomePage.tsx:103
+#: src/features/home/components/HomePage/HomePage.tsx:113
msgid "Powerful tools designed for academic needs, not corporate networking."
msgstr "Powerful tools designed for academic needs, not corporate networking."
@@ -911,7 +911,7 @@ msgstr "Powerful tools designed for academic needs, not corporate networking."
msgid "Preparing screenshot…"
msgstr "Preparing screenshot…"
-#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:187
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:192
msgid "Preview"
msgstr "Preview"
@@ -935,7 +935,7 @@ msgstr "Put your work in the order you want, and hide what’s not relevant."
msgid "QR code for {value}"
msgstr "QR code for {value}"
-#: src/features/home/components/HomePage/HomePage.tsx:119
+#: src/features/home/components/HomePage/HomePage.tsx:129
msgid "Ready to simplify your research presence?"
msgstr "Ready to simplify your research presence?"
@@ -964,7 +964,7 @@ msgstr "Reordering cancelled. {name} stayed where it was."
msgid "Research outputs"
msgstr "Research outputs"
-#: src/features/auth/components/LandingPage/LandingPage.tsx:20
+#: src/features/auth/components/LandingPage/LandingPage.tsx:27
msgid "Researcher profiles on the AT Protocol"
msgstr "Researcher profiles on the AT Protocol"
@@ -972,7 +972,7 @@ msgstr "Researcher profiles on the AT Protocol"
msgid "Reset"
msgstr "Reset"
-#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:182
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:186
msgid "Reset to defaults"
msgstr "Reset to defaults"
@@ -1005,7 +1005,7 @@ msgstr "Save or reset your lanyard changes first: giving permission leaves this
msgid "Saving…"
msgstr "Saving…"
-#: src/features/qr/components/QrSheet/QrSheet.tsx:141
+#: src/features/qr/components/QrSheet/QrSheet.tsx:150
msgid "Scan to see my lanyard"
msgstr "Scan to see my lanyard"
@@ -1043,8 +1043,8 @@ msgid "Send more"
msgstr "Send more"
#: src/components/MobileNav/MobileNav.tsx:71
-#: src/features/qr/components/QrSheet/QrSheet.tsx:111
-#: src/features/qr/components/QrSheet/QrSheet.tsx:178
+#: src/features/qr/components/QrSheet/QrSheet.tsx:118
+#: src/features/qr/components/QrSheet/QrSheet.tsx:187
#: src/features/qr/components/ShareLink/ShareLink.tsx:26
msgid "Share"
msgstr "Share"
@@ -1084,15 +1084,15 @@ msgstr "Sifa"
#: src/components/AppHeader/AppHeader.tsx:48
#: src/features/auth/components/CallbackStatus/CallbackStatus.tsx:22
#: src/features/auth/components/CallbackStatus/CallbackStatus.tsx:32
+#: src/features/auth/components/LandingPage/LandingPage.tsx:27
#: src/features/auth/components/SignInForm/SignInForm.tsx:109
#: src/features/home/components/HomeHeader/HomeHeader.tsx:35
-#: src/features/home/components/SignInPage/SignInPage.tsx:32
-#: src/features/home/components/SignInPage/SignInPage.tsx:59
+#: src/features/home/components/SignInFace/SignInFace.tsx:32
#: src/features/lanyard/components/LanyardPage/LanyardPage.tsx:98
msgid "Sign in"
msgstr "Sign in"
-#: src/features/home/components/HomePage/HomePage.tsx:55
+#: src/features/home/components/HomePage/HomePage.tsx:65
msgid "Sign in to get started"
msgstr "Sign in to get started"
@@ -1101,11 +1101,11 @@ msgstr "Sign in to get started"
msgid "Sign in to see this lanyard"
msgstr "Sign in to see this lanyard"
-#: src/features/home/components/HomePage/HomePage.tsx:44
+#: src/features/home/components/HomePage/HomePage.tsx:54
msgid "Sign in with your Bluesky handle, or any AT Protocol account, and Lanyards gathers your publications, talks, affiliations and profiles into one lanyard to share anywhere: on a conference badge, in an email signature, on a slide."
msgstr "Sign in with your Bluesky handle, or any AT Protocol account, and Lanyards gathers your publications, talks, affiliations and profiles into one lanyard to share anywhere: on a conference badge, in an email signature, on a slide."
-#: src/features/account/components/AccountCard/AccountCard.tsx:43
+#: src/features/account/components/AccountCard/AccountCard.tsx:49
msgid "Sign out"
msgstr "Sign out"
@@ -1125,7 +1125,7 @@ msgstr "Signal username copied"
msgid "Signed in, you can send us feedback, with screenshots, right from Lanyards. Or reach us here:"
msgstr "Signed in, you can send us feedback, with screenshots, right from Lanyards. Or reach us here:"
-#: src/features/auth/session/SessionProvider.tsx:80
+#: src/features/auth/session/SessionProvider.tsx:89
msgid "Signed out"
msgstr "Signed out"
@@ -1208,15 +1208,15 @@ msgstr "Thank you"
msgid "That doesn't look like a handle — for example alice.bsky.social"
msgstr "That doesn't look like a handle — for example alice.bsky.social"
-#: src/features/home/components/HomeBadge/HomeBadge.tsx:49
+#: src/features/home/components/HomeBadge/HomeBadge.tsx:73
msgid "The curated link for academic researchers that collects your complete scholarly presence—publications, talks, affiliations, and social profiles."
msgstr "The curated link for academic researchers that collects your complete scholarly presence—publications, talks, affiliations, and social profiles."
-#: src/features/home/components/HomePage/HomePage.tsx:68
+#: src/features/home/components/HomePage/HomePage.tsx:78
msgid "The problem"
msgstr "The problem"
-#: src/features/home/components/HomePage/HomePage.tsx:69
+#: src/features/home/components/HomePage/HomePage.tsx:79
msgid "The visibility paradox"
msgstr "The visibility paradox"
@@ -1224,7 +1224,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:175
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:179
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."
@@ -1310,11 +1310,11 @@ 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:167
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:163
msgid "Updating your podcasts and videos…"
msgstr "Updating your podcasts and videos…"
-#: src/features/home/components/SignInPage/SignInPage.tsx:62
+#: src/features/home/components/SignInFace/SignInFace.tsx:35
msgid "Use your handle from Bluesky or any other AT Protocol app. New here? Create an account, and it’s yours to take anywhere."
msgstr "Use your handle from Bluesky or any other AT Protocol app. New here? Create an account, and it’s yours to take anywhere."
@@ -1381,11 +1381,11 @@ msgstr "We couldn't finish signing you in."
msgid "We couldn't load this lanyard"
msgstr "We couldn't load this lanyard"
-#: src/features/account/components/AccountCard/AccountCard.tsx:38
+#: src/features/account/components/AccountCard/AccountCard.tsx:40
msgid "We couldn't load your profile."
msgstr "We couldn't load your profile."
-#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:172
+#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:176
msgid "We couldn't read your lanyard settings"
msgstr "We couldn't read your lanyard settings"
@@ -1393,7 +1393,7 @@ msgstr "We couldn't read your lanyard settings"
msgid "Web address"
msgstr "Web address"
-#: src/features/home/components/HomeBadge/HomeBadge.tsx:46
+#: src/features/home/components/HomeBadge/HomeBadge.tsx:70
msgid "Welcome to Lanyards"
msgstr "Welcome to Lanyards"
@@ -1406,7 +1406,7 @@ msgstr "What happened, and what did you expect? Steps to repeat it help."
msgid "What is this about?"
msgstr "What is this about?"
-#: src/features/home/components/HomePage/HomePage.tsx:81
+#: src/features/home/components/HomePage/HomePage.tsx:91
msgid "What you get"
msgstr "What you get"
@@ -1414,7 +1414,7 @@ msgstr "What you get"
msgid "What you share"
msgstr "What you share"
-#: src/features/home/components/HomePage/HomePage.tsx:101
+#: src/features/home/components/HomePage/HomePage.tsx:111
msgid "Why Lanyards"
msgstr "Why Lanyards"
@@ -1474,7 +1474,7 @@ msgid "Your handle"
msgstr "Your handle"
#: src/features/lanyard/customise/CustomisePage/CustomisePage.tsx:51
-#: src/features/qr/components/QrSheet/QrSheet.tsx:51
+#: src/features/qr/components/QrSheet/QrSheet.tsx:52
msgid "Your lanyard"
msgstr "Your lanyard"
diff --git a/web/src/routes/_home.tsx b/web/src/routes/_home.tsx
new file mode 100644
index 0000000..af576b5
--- /dev/null
+++ b/web/src/routes/_home.tsx
@@ -0,0 +1,23 @@
+import { createFileRoute, Outlet } from '@tanstack/react-router';
+
+import { LandingPage } from '@/features/auth/components/LandingPage/LandingPage';
+
+/**
+ * The homepage and the sign-in page are one page, its badge turned over to
+ * sign in (#175): they share this layout, so the badge stays mounted and
+ * turns between them.
+ */
+export const Route = createFileRoute('/_home')({
+ // It draws its own header, on the brand blue (#151, #157).
+ staticData: { ownHeader: true },
+ component: Home,
+});
+
+function Home() {
+ return (
+ <>
+
+
+ >
+ );
+}
diff --git a/web/src/routes/index.tsx b/web/src/routes/_home/index.tsx
similarity index 72%
rename from web/src/routes/index.tsx
rename to web/src/routes/_home/index.tsx
index 610011c..745e400 100644
--- a/web/src/routes/index.tsx
+++ b/web/src/routes/_home/index.tsx
@@ -1,11 +1,11 @@
import { createFileRoute, redirect } from '@tanstack/react-router';
-import { LandingPage } from '@/features/auth/components/LandingPage/LandingPage';
import { safeReturnTo } from '@/lib/atproto/oauthConfig';
type LandingSearch = { returnTo?: string };
-export const Route = createFileRoute('/')({
+/** `/`: the homepage, drawn by the _home layout (#175). */
+export const Route = createFileRoute('/_home/')({
// Always return the key: search params merge with the parent route's raw
// params, so omitting it would let an unvalidated value through.
validateSearch: (search: Record): LandingSearch => {
@@ -22,11 +22,4 @@ export const Route = createFileRoute('/')({
});
}
},
- // The homepage draws its own header, on the brand blue (#151).
- staticData: { ownHeader: true },
- component: Landing,
});
-
-function Landing() {
- return ;
-}
diff --git a/web/src/routes/sign-in.tsx b/web/src/routes/_home/sign-in.tsx
similarity index 57%
rename from web/src/routes/sign-in.tsx
rename to web/src/routes/_home/sign-in.tsx
index 578a813..8094c6a 100644
--- a/web/src/routes/sign-in.tsx
+++ b/web/src/routes/_home/sign-in.tsx
@@ -1,23 +1,18 @@
import { createFileRoute } from '@tanstack/react-router';
-import { SignInPage } from '@/features/home/components/SignInPage/SignInPage';
import { safeReturnTo } from '@/lib/atproto/oauthConfig';
type SignInSearch = { returnTo?: string };
-export const Route = createFileRoute('/sign-in')({
+/**
+ * `/sign-in` (#157): the homepage with its badge turned over to the form,
+ * drawn by the _home layout (#175).
+ */
+export const Route = createFileRoute('/_home/sign-in')({
// Always return the key: search params merge with the parent route's raw
// params, so omitting it would let an unvalidated value through.
validateSearch: (search: Record): SignInSearch => {
const returnTo = safeReturnTo(search.returnTo);
return { returnTo: returnTo === '/' ? undefined : returnTo };
},
- // The page draws its own header, on the brand blue (#157).
- staticData: { ownHeader: true },
- component: SignIn,
});
-
-function SignIn() {
- const { returnTo } = Route.useSearch();
- return ;
-}
diff --git a/web/src/styles/index.css b/web/src/styles/index.css
index 16369f3..4c7e81d 100644
--- a/web/src/styles/index.css
+++ b/web/src/styles/index.css
@@ -11,20 +11,6 @@
@custom-variant wide (@media (min-width: 48rem) and (min-height: 36.0625rem));
@custom-variant flat (@media (orientation: landscape) and (max-height: 36rem));
-/* The homepage's badge swings once on its straps as it arrives (#145). */
-@theme {
- --animate-swing: swing 1.6s cubic-bezier(0.25, 1.5, 0.4, 1) both;
-
- @keyframes swing {
- from {
- rotate: -7deg;
- }
- to {
- rotate: -1.5deg;
- }
- }
-}
-
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
diff --git a/web/vite.config.ts b/web/vite.config.ts
index c58e33b..ac90875 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -56,7 +56,19 @@ export default defineConfig({
rolldownOptions: {
output: {
codeSplitting: {
- groups: [{ name: 'posthog', test: /node_modules[\\/]posthog-js/ }],
+ // A group holds only what it names, not everything that imports.
+ includeDependenciesRecursively: false,
+ groups: [
+ { name: 'posthog', test: /node_modules[\\/]posthog-js/ },
+ // A badge's drawing, wherever one hangs (#173): its cover, its
+ // lanyard and its sleeve, in one request, not three. A lanyard
+ // loads its route's code in a burst, and over HTTP/1.1 every
+ // extra file there can cost another round trip (spec §2).
+ {
+ name: 'badge',
+ test: /src[\\/](components[\\/]CoverPattern|features[\\/]qr[\\/]components[\\/](LanyardRibbon|BadgeSleeve))[\\/]/,
+ },
+ ],
},
},
},