diff --git a/apps/documentation/src/content/docs/decisions/0011-panel-plain-react-spa.md b/apps/documentation/src/content/docs/decisions/0011-panel-plain-react-spa.md index 7d02721a..930b67ec 100644 --- a/apps/documentation/src/content/docs/decisions/0011-panel-plain-react-spa.md +++ b/apps/documentation/src/content/docs/decisions/0011-panel-plain-react-spa.md @@ -64,9 +64,14 @@ content is content — `apps/documentation` and `apps/site`. (server functions, loaders) the panel cannot use. It is used where it fits — `examples/todo-app`, which is precisely the kind of app it serves. -**If the panel ever needs URL routing** (deep-linking an endpoint, say), -TanStack Router exists standalone — client-side, no Start, no server. The -routing is available without reopening this decision. +**If the panel ever needs URL routing**, TanStack Router exists standalone — +client-side, no Start, no server. The routing is available without reopening +this decision. + +Deep-linking an endpoint (`/__laqi?endpoint=POST%20/auth/login`) did not +need it: one query param read and written through the History API +(`packages/editor/src/location.ts`). The router becomes the right tool when +the panel grows a second screen or nested state, not before. ## Consequences diff --git a/apps/documentation/src/content/docs/product/roadmap.md b/apps/documentation/src/content/docs/product/roadmap.md index bea093a0..544f6506 100644 --- a/apps/documentation/src/content/docs/product/roadmap.md +++ b/apps/documentation/src/content/docs/product/roadmap.md @@ -99,8 +99,10 @@ flow. `--share`: stable URLs, no binary dependency. Phase 2 of [ADR-0007](/decisions/0007-public-url/), postponed until usage justifies it. -- **Panel deep-linking** — URL routing to an endpoint, via standalone - TanStack Router if ever needed ([ADR-0011](/decisions/0011-panel-plain-react-spa/)). +- ~~**Panel deep-linking**~~ — shipped as one query param + (`/__laqi?endpoint=…`) over the History API; no router, per + [ADR-0011](/decisions/0011-panel-plain-react-spa/). Routing proper stays + deferred until the panel grows a second screen. ## Backlog — known defects, Medium/Low diff --git a/packages/editor/src/App.test.tsx b/packages/editor/src/App.test.tsx index 7dd3edf2..dff8d3a7 100644 --- a/packages/editor/src/App.test.tsx +++ b/packages/editor/src/App.test.tsx @@ -57,6 +57,9 @@ function endpoint(partial: Partial & Pick { vi.clearAllMocks() + // The detail pane's endpoint lives in the URL, and jsdom keeps one window + // for the whole file: a detail a test opened would still be open in the next. + window.history.replaceState(null, '', '/__laqi') endpoints = [ endpoint({ id: 'GET /users', method: 'GET', path: '/users', description: 'the people' }), endpoint({ id: 'POST /orders', method: 'POST', path: '/orders' }), @@ -534,6 +537,76 @@ describe('endpoint detail', () => { }) }) +/** jsdom traverses history asynchronously; the popstate lands a tick later. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) + +describe('deep link', () => { + it('puts the open endpoint in the URL, with its path readable', async () => { + await renderApp() + fireEvent.click(screen.getByRole('button', { name: '/users' })) + await screen.findByLabelText('response body') + + expect(window.location.pathname + window.location.search).toBe('/__laqi?endpoint=GET%20/users') + }) + + it('lands on the endpoint the URL names, as a reload or a shared link would', async () => { + window.history.replaceState(null, '', '/__laqi?endpoint=POST%20/orders') + render() + + expect(await screen.findByLabelText('response body')).toBeTruthy() + expect(screen.getByText('/orders')).toBeTruthy() + expect(screen.queryByLabelText('filter')).toBeNull() + }) + + it('falls back to the list when the URL names an endpoint the project does not have', async () => { + window.history.replaceState(null, '', '/__laqi?endpoint=GET%20/nowhere') + await renderApp() + + expect(screen.getByLabelText('filter')).toBeTruthy() + expect(screen.queryByLabelText('response body')).toBeNull() + }) + + it("returns to the list on the browser's Back", async () => { + await renderApp() + fireEvent.click(screen.getByRole('button', { name: '/users' })) + await screen.findByLabelText('response body') + + window.history.back() + await settle() + + await waitFor(() => expect(screen.queryByLabelText('response body')).toBeNull()) + expect(window.location.search).toBe('') + + window.history.forward() + await settle() + expect(await screen.findByLabelText('response body')).toBeTruthy() + }) + + it('drops the endpoint from the URL when the panel goes back by itself', async () => { + await renderApp() + fireEvent.click(screen.getByRole('button', { name: '/users' })) + fireEvent.click(await screen.findByRole('button', { name: /Endpoints \(esc\)/ })) + + await waitFor(() => expect(screen.queryByLabelText('response body')).toBeNull()) + expect(window.location.pathname + window.location.search).toBe('/__laqi') + }) + + it('adds no history entry when jumping to the endpoint already open', async () => { + await renderApp() + fireEvent.click(screen.getByRole('button', { name: '/users' })) + await screen.findByLabelText('response body') + const length = window.history.length + + fireEvent.keyDown(window, { key: 'k', ctrlKey: true }) + fireEvent.change(await screen.findByLabelText('command'), { target: { value: 'users' } }) + fireEvent.keyDown(screen.getByLabelText('command'), { key: 'Enter', ctrlKey: true }) + + await waitFor(() => expect(screen.queryByLabelText('command')).toBeNull()) + expect(putState).not.toHaveBeenCalled() + expect(window.history.length).toBe(length) + }) +}) + describe('load failures', () => { it('shows the parse error inline and says the rest is still served', async () => { status = { diff --git a/packages/editor/src/App.tsx b/packages/editor/src/App.tsx index b377fdd7..18c8c89b 100644 --- a/packages/editor/src/App.tsx +++ b/packages/editor/src/App.tsx @@ -12,6 +12,7 @@ import { RequestLog } from './components/RequestLog' import { ScenarioStrip } from './components/ScenarioStrip' import { ShareBand } from './components/ShareBand' import { WarningBand } from './components/WarningBand' +import { useEndpointLocation } from './hooks/useEndpointLocation' import { useEvents } from './hooks/useEvents' import { appendLog, toLogEntry } from './log' import { isDirty, overriddenCount, overridesAfterChipClick } from './resolve' @@ -32,7 +33,8 @@ export function App() { const seq = useRef(0) const [filter, setFilter] = useState('') - const [detailId, setDetailId] = useState(null) + // Lives in the URL, not in memory: see useEndpointLocation. + const [detailId, setDetailId] = useEndpointLocation() const [paletteOpen, setPaletteOpen] = useState(false) const [creating, setCreating] = useState(false) diff --git a/packages/editor/src/hooks/useEndpointLocation.ts b/packages/editor/src/hooks/useEndpointLocation.ts new file mode 100644 index 00000000..94bfd2a7 --- /dev/null +++ b/packages/editor/src/hooks/useEndpointLocation.ts @@ -0,0 +1,39 @@ +import { useCallback, useEffect, useState } from 'react' +import { endpointFromSearch, searchForEndpoint } from '../location' + +/** + * The detail pane's endpoint id, kept in the URL (see `location.ts`) so a + * reload stays on it, back/forward move between it and the list, and the + * address bar is a link worth sharing. + * + * Every in-panel change is a `pushState`, opening and closing alike: the + * browser's Back always undoes the last thing the panel did, which is what + * a router would do too. Nothing is ever replaced, so an id the project does + * not have stays in the URL: the list shows meanwhile, and the detail comes + * back by itself when the endpoint does — a file being fixed, a link to an + * endpoint about to be created. + * + * Returns the same tuple `useState` would: callers set the id and the URL + * follows. Setting the id the URL already has is a no-op, so a jump from the + * log to the endpoint already open adds no entry. + */ +export function useEndpointLocation(): [string | null, (id: string | null) => void] { + const [detailId, setLocalId] = useState(() => + endpointFromSearch(window.location.search), + ) + + useEffect(() => { + const onPopState = () => setLocalId(endpointFromSearch(window.location.search)) + window.addEventListener('popstate', onPopState) + return () => window.removeEventListener('popstate', onPopState) + }, []) + + const setDetailId = useCallback((id: string | null) => { + setLocalId(id) + const { pathname, search, hash } = window.location + if (endpointFromSearch(search) === id) return + window.history.pushState(null, '', `${pathname}${searchForEndpoint(search, id)}${hash}`) + }, []) + + return [detailId, setDetailId] +} diff --git a/packages/editor/src/location.test.ts b/packages/editor/src/location.test.ts new file mode 100644 index 00000000..ab27a150 --- /dev/null +++ b/packages/editor/src/location.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { endpointFromSearch, searchForEndpoint } from './location' + +describe('endpointFromSearch', () => { + it('reads the endpoint id out of the query string', () => { + expect(endpointFromSearch('?endpoint=POST%20/auth/login')).toBe('POST /auth/login') + }) + + it('accepts the plus and fully-encoded forms a hand-typed link may use', () => { + expect(endpointFromSearch('?endpoint=POST+%2Fauth%2Flogin')).toBe('POST /auth/login') + }) + + it('is the list when the param is absent or empty', () => { + expect(endpointFromSearch('')).toBeNull() + expect(endpointFromSearch('?other=1')).toBeNull() + expect(endpointFromSearch('?endpoint=')).toBeNull() + }) +}) + +describe('searchForEndpoint', () => { + it('keeps the slashes of the path readable', () => { + expect(searchForEndpoint('', 'POST /auth/login')).toBe('?endpoint=POST%20/auth/login') + }) + + it('round-trips a path with params and odd characters', () => { + const id = 'GET /users/:id?x=1&y=2' + expect(endpointFromSearch(searchForEndpoint('', id))).toBe(id) + }) + + it('drops the param for the list, and the whole query when nothing else is in it', () => { + expect(searchForEndpoint('?endpoint=GET%20/users', null)).toBe('') + }) + + it('leaves unrelated params alone either way', () => { + expect(searchForEndpoint('?debug=1', 'GET /users')).toBe('?debug=1&endpoint=GET%20/users') + expect(searchForEndpoint('?debug=1&endpoint=GET%20/users', null)).toBe('?debug=1') + }) +}) diff --git a/packages/editor/src/location.ts b/packages/editor/src/location.ts new file mode 100644 index 00000000..4d1a8837 --- /dev/null +++ b/packages/editor/src/location.ts @@ -0,0 +1,34 @@ +/** + * The one piece of panel state that lives in the URL: which endpoint the + * detail pane shows. `/__laqi?endpoint=POST%20/auth/login` opens that + * endpoint; no param is the list. + * + * A query param rather than a hash because the server serves `/__laqi` for + * any query string and a shared `--share` link reads as one URL, not an + * anchor. Only the endpoint id goes in: the response that is live is server + * state (overrides, scenario), and a link that flipped it on open would be a + * GET with side effects. + */ + +export const ENDPOINT_PARAM = 'endpoint' + +/** The endpoint id a `location.search` names, or null for the list. */ +export function endpointFromSearch(search: string): string | null { + const id = new URLSearchParams(search).get(ENDPOINT_PARAM) + return id === null || id === '' ? null : id +} + +/** + * The `location.search` that shows `id` (or the list, with null), keeping + * any other params as they were. The id is encoded by hand instead of via + * URLSearchParams so the slashes in the path stay readable in the address + * bar: `POST%20/auth/login`, not `POST+%2Fauth%2Flogin`. + */ +export function searchForEndpoint(search: string, id: string | null): string { + const params = new URLSearchParams(search) + params.delete(ENDPOINT_PARAM) + const rest = params.toString() + if (id === null) return rest === '' ? '' : `?${rest}` + const own = `${ENDPOINT_PARAM}=${encodeURIComponent(id).replace(/%2F/g, '/')}` + return rest === '' ? `?${own}` : `?${rest}&${own}` +}