Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ The repository holds two apps during the rebuild (epic #94):
- **Protocol**: `@atcute/*` packages (client, lexicons, identity resolver)
- **Copy**: British English via Lingui (`web/src/i18n/`)
- **Tests**: Vitest + Testing Library + MSW + axe-core; Playwright for e2e
- **Hosting**: Vercel project with Root Directory `web`, serving `next.lanyards.app` until the swap
- **Hosting**: Vercel project `lanyards-next` with Root Directory `web`, serving `lanyards.app` (`PUBLIC_BASE_URL=https://lanyards.app` in Production). `www` and the retired `next.lanyards.app` redirect to it (#154)

**Repository root: the legacy Next.js app.** It is frozen and serves `lanyards.app` until Slice 1c (#103) swaps the domain and deletes it. Don't start new work on it.
**Repository root: the legacy Next.js app.** It is frozen and no longer served: `lanyards.app` moved to the new app (#154), and Slice 1c (#103) deletes it. Don't start new work on it.

---

Expand Down
6 changes: 3 additions & 3 deletions web/e2e/landing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,10 @@ test.describe('the homepage’s hero (#151)', () => {
await expect
.poll(() => swayOf(page), { timeout: 2000 })
.toMatch(/^rotate\(-?[\d.]+deg\)$/);
// Never more than a couple of degrees.
// A few degrees at most, and still again within about three seconds.
const angle = Number(/-?[\d.]+/.exec((await swayOf(page)) ?? '')?.[0]);
expect(Math.abs(angle)).toBeLessThan(2);
await expect.poll(() => swayOf(page), { timeout: 8000 }).toBe('');
expect(Math.abs(angle)).toBeLessThan(4);
await expect.poll(() => swayOf(page), { timeout: 4000 }).toBe('');
});

test('keeps the badge still with reduced motion', async ({ page }) => {
Expand Down
22 changes: 19 additions & 3 deletions web/scripts/vercelConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import { afterEach, describe, expect, it } from 'vitest';
type Config = {
ignoreCommand: string;
functions?: Record<string, { includeFiles?: string }>;
redirects?: { source: string; destination: string; permanent: boolean }[];
redirects?: {
source: string;
destination: string;
permanent: boolean;
has?: { type: string; key?: string; value?: string }[];
}[];
rewrites: { source: string; destination: string }[];
headers: { source: string; headers: { key: string; value: string }[] }[];
};
Expand All @@ -25,9 +30,20 @@ const config = JSON.parse(
) as Config;

describe('vercel.json', () => {
// The beta's /@handle links, link previews included (#150).
it('sends /@handle on to /handle for good', () => {
// The beta's /@handle links, link previews included (#150). The beta
// subdomain's pages move to lanyards.app (#154); only page visits, so
// an installed copy's service worker can still fetch its update there.
it('sends next.lanyards.app pages to lanyards.app, and /@handle to /handle', () => {
expect(config.redirects).toEqual([
{
source: '/:path*',
has: [
{ type: 'host', value: 'next.lanyards.app' },
{ type: 'header', key: 'sec-fetch-dest', value: 'document' },
],
destination: 'https://lanyards.app/:path*',
permanent: true,
},
{ source: '/@:handle', destination: '/:handle', permanent: true },
]);
});
Expand Down
18 changes: 10 additions & 8 deletions web/src/features/home/sway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ describe('sway', () => {
expect(left).toBeGreaterThan(0.3);
});

it('barely moves for a slow pointer', () => {
it('moves only a little for a slow pointer', () => {
const { angles } = run(150, 1, 3);
expect(Math.max(...angles.map(Math.abs))).toBeLessThan(0.25);
expect(Math.max(...angles.map(Math.abs))).toBeLessThan(0.6);
});

it('never leans past its cap, however hard it is pushed', () => {
Expand All @@ -61,23 +61,25 @@ describe('sway', () => {
}
});

it('swings back lightly, each swing smaller, then rests', () => {
it('swings visibly, back lightly, each swing smaller, then rests', () => {
const { angles, restedAt, sway } = run(1200, 0.5, 8);
const [first, second, third] = turns(angles);
// A swing, a smaller one back the other way, a smaller one again.
expect(first).toBeLessThan(0);
// A brisk sweep: a swing you see, a smaller one back, smaller again.
expect(first).toBeLessThan(-1.5);
expect(second).toBeGreaterThan(0);
expect(Math.abs(second ?? 0)).toBeLessThan(Math.abs(first ?? 0) / 2);
expect(Math.abs(third ?? 0)).toBeLessThan(Math.abs(second ?? 0) / 2);
// Still again two to three seconds after the pointer stops.
expect(restedAt).not.toBeNull();
expect(restedAt).toBeLessThan(5);
expect((restedAt ?? 0) - 0.5).toBeGreaterThan(1.5);
expect((restedAt ?? 0) - 0.5).toBeLessThan(3);
expect(sway).toEqual(REST);
});

it('comes to rest from its cap within a few seconds', () => {
it('comes to rest from its cap within three seconds', () => {
const { restedAt } = run(100_000, 3, 12);
expect(restedAt).not.toBeNull();
expect((restedAt ?? 0) - 3).toBeLessThan(5);
expect((restedAt ?? 0) - 3).toBeLessThan(3);
});

// A tab in the background, or a long frame, doesn't fling it.
Expand Down
28 changes: 15 additions & 13 deletions web/src/features/home/sway.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
/**
* How the homepage badge sways when a pointer brushes past it (#151): a
* heavily damped spring, pushed by how fast the pointer moves sideways.
* One swing, a smaller one back, a smaller one again, then still. The
* angle shown never reaches MAX_ANGLE, however hard it's pushed.
* A brisk sweep swings it about 2 degrees, then a quarter of that back,
* a little more, and it's still two to three 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.
Expand All @@ -17,30 +19,30 @@ export type Sway = {
export const REST: Sway = { angle: 0, velocity: 0 };

/** The furthest the badge ever leans, either way. */
export const MAX_ANGLE = 2;
export const MAX_ANGLE = 4;

/** About 1.6 seconds a swing. */
const STIFFNESS = 4;
/** About 1.4 seconds a swing. */
const STIFFNESS = 4.5;

/** Heavy enough that each swing is well under half the last. */
const DAMPING = 0.3;
/** Heavy enough that each swing is about a quarter of the last. */
const DAMPING = 0.4;

/** Degrees a second, squared, for each pixel a second of pointer. */
const GAIN = 0.012;
const GAIN = 0.035;

/** The most the pointer pushes: a brisk sweep, not a fling. */
const MAX_PUSH = 24;
const MAX_PUSH = 70;

/** The fastest it turns, and how far it can wind up past what it shows. */
const MAX_VELOCITY = 24;
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: less than a pixel at the badge's foot. */
const REST_ANGLE = 0.01;
const REST_VELOCITY = 0.02;
/** 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));
Expand Down
77 changes: 77 additions & 0 deletions web/src/lib/origin/movedOrigin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from 'vitest';

import { leaveFor, movedTo } from './movedOrigin';

const HOME = 'https://lanyards.app';

describe('movedTo (#154)', () => {
it('sends a visit to next.lanyards.app on to lanyards.app, path and all', () => {
expect(
movedTo('https://next.lanyards.app/alice.test/edit?x=1#top', HOME)
).toBe('https://lanyards.app/alice.test/edit?x=1#top');
expect(movedTo('https://next.lanyards.app/', HOME)).toBe(
'https://lanyards.app/'
);
});

it('stays put where the app lives', () => {
expect(movedTo('https://lanyards.app/alice.test', HOME)).toBeNull();
});

// Until the build's base URL moves, next.lanyards.app is still home.
it('stays put on next.lanyards.app while that is the base URL', () => {
expect(
movedTo(
'https://next.lanyards.app/alice.test',
'https://next.lanyards.app'
)
).toBeNull();
});

it('leaves every other origin alone: previews, local, Vercel URLs', () => {
for (const href of [
'https://lanyards-next-git-x-renderghost.vercel.app/',
'https://lanyards-next.vercel.app/',
'http://127.0.0.1:5173/',
]) {
expect(movedTo(href, HOME)).toBeNull();
}
});
});

describe('leaveFor (#154)', () => {
it('drops the old service worker and its caches, then goes', async () => {
const unregister = vi.fn(async () => true);
const remove = vi.fn(async (_key: string) => true);
const go = vi.fn();
await leaveFor('https://lanyards.app/', {
registrations: async () => [{ unregister }, { unregister }],
cacheKeys: async () => ['workbox-precache-v2', 'other'],
deleteCache: remove,
go,
});
expect(unregister).toHaveBeenCalledTimes(2);
expect(remove.mock.calls.map(([key]) => key)).toEqual([
'workbox-precache-v2',
'other',
]);
expect(go).toHaveBeenCalledWith('https://lanyards.app/');
});

it('goes anyway when clearing up fails or hangs', async () => {
vi.useFakeTimers();
const go = vi.fn();
const leaving = leaveFor('https://lanyards.app/', {
registrations: () => new Promise(() => undefined),
cacheKeys: async () => {
throw new Error('no caches');
},
deleteCache: async () => true,
go,
});
await vi.advanceTimersByTimeAsync(2000);
await leaving;
expect(go).toHaveBeenCalledWith('https://lanyards.app/');
vi.useRealTimers();
});
});
61 changes: 61 additions & 0 deletions web/src/lib/origin/movedOrigin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* Where the app used to live (#154). A visit there, including from a copy
* installed with its service worker, moves to the build's base URL once
* the base URL is somewhere else.
*/
export const RETIRED_ORIGINS: readonly string[] = ['https://next.lanyards.app'];

/** How long to spend clearing up before leaving regardless. */
const CLEAR_UP_MS = 1500;

/**
* The same page at `baseUrl`, if `href` is on a retired origin that is no
* longer the base URL; otherwise null.
*/
export function movedTo(href: string, baseUrl: string): string | null {
const here = new URL(href);
const home = new URL(baseUrl);
if (here.origin === home.origin) return null;
if (!RETIRED_ORIGINS.includes(here.origin)) return null;
return new URL(`${here.pathname}${here.search}${here.hash}`, home).href;
}

export type LeaveDeps = {
registrations(): Promise<readonly { unregister(): Promise<boolean> }[]>;
cacheKeys(): Promise<readonly string[]>;
deleteCache(key: string): Promise<boolean>;
go(url: string): void;
};

/** The browser's own service workers, caches and navigation. */
export const browserLeaveDeps = (): LeaveDeps => ({
registrations: async () =>
(await navigator.serviceWorker?.getRegistrations()) ?? [],
cacheKeys: async () => (await globalThis.caches?.keys()) ?? [],
deleteCache: (key) => caches.delete(key),
go: (url) => window.location.replace(url),
});

/**
* Leaves for `url`, first dropping this origin's service worker and
* caches so an installed copy doesn't keep serving the old app here.
* Leaves anyway if that fails or takes too long.
*/
export async function leaveFor(
url: string,
deps: LeaveDeps = browserLeaveDeps()
): Promise<void> {
const clearUp = Promise.allSettled([
deps
.registrations()
.then((all) => Promise.all(all.map((each) => each.unregister()))),
deps
.cacheKeys()
.then((keys) => Promise.all(keys.map((key) => deps.deleteCache(key)))),
]);
await Promise.race([
clearUp,
new Promise((resolve) => setTimeout(resolve, CLEAR_UP_MS)),
]);
deps.go(url);
}
44 changes: 28 additions & 16 deletions web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,35 @@ import {
track,
} from './lib/analytics/analytics';
import { configureAuth } from './lib/atproto/session';
import { leaveFor, movedTo } from './lib/origin/movedOrigin';

configureAuth();
void initAnalytics({
key: import.meta.env.VITE_POSTHOG_KEY,
host: import.meta.env.VITE_POSTHOG_HOST ?? DEFAULT_POSTHOG_HOST,
doNotTrack: browserDoNotTrack(),
framed: isFramed(),
});
track('app_opened');
function start() {
configureAuth();
void initAnalytics({
key: import.meta.env.VITE_POSTHOG_KEY,
host: import.meta.env.VITE_POSTHOG_HOST ?? DEFAULT_POSTHOG_HOST,
doNotTrack: browserDoNotTrack(),
framed: isFramed(),
});
track('app_opened');

const container = document.getElementById('root');
if (!container) throw new Error('Missing #root element');
const container = document.getElementById('root');
if (!container) throw new Error('Missing #root element');

createRoot(container).render(
<StrictMode>
<AppProviders>
<RouterProvider router={router} />
</AppProviders>
</StrictMode>
createRoot(container).render(
<StrictMode>
<AppProviders>
<RouterProvider router={router} />
</AppProviders>
</StrictMode>
);
}

// On a retired origin, such as an installed copy of the beta, go to where
// the app lives now instead of starting here (#154).
const moved = movedTo(
window.location.href,
import.meta.env.VITE_PUBLIC_BASE_URL
);
if (moved) void leaveFor(moved);
else start();
9 changes: 9 additions & 0 deletions web/vercel.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@
}
},
"redirects": [
{
"source": "/:path*",
"has": [
{ "type": "host", "value": "next.lanyards.app" },
{ "type": "header", "key": "sec-fetch-dest", "value": "document" }
],
"destination": "https://lanyards.app/:path*",
"permanent": true
},
{
"source": "/@:handle",
"destination": "/:handle",
Expand Down
Loading