diff --git a/packages/mosaic/AGENTS.md b/packages/mosaic/AGENTS.md index a26473d521c..a723c4a0946 100644 --- a/packages/mosaic/AGENTS.md +++ b/packages/mosaic/AGENTS.md @@ -31,6 +31,7 @@ Read every line that matches your task. Paths below are relative to this package - Write or change a controller, or how a feature handles pending state, errors, dialogs or removal focus → [Controllers](docs/controllers.md) - Write or debug a state machine → [Controllers → Machines](docs/controllers.md#machines), then [Machine runtime](src/machine/README.md) - Build a flow with several steps on one surface → [Controllers → Multi-step flows](docs/controllers.md#multi-step-flows), then [Views → Moving between screens](docs/views.md#moving-between-screens-on-one-surface) +- Route a component's pages or steps, put them in the URL or behind the host router, or open a modal at a page → [Routing](docs/routing.md) - Write or change a view, a dialog or step it renders, or a feature's copy → [Views](docs/views.md) - Add a styled component, or change a token, a `.cl-` class or `data-` attribute, `MosaicProvider`, or the CSS build → [Theming](docs/theming.md) - Write or change a `*.styles.ts` or `*.stylex.ts` file → [StyleX](docs/stylex.md) @@ -60,6 +61,7 @@ Before you change a file that matches a pattern below, read its guide, even for - `src/**/*.view.tsx` → [Views](docs/views.md) - `src/**/*.doc.ts`, `src/docs-schema.ts` → [Agent docs](docs/agent-docs.md) - `src/**/__tests__/**`, `src/**/*.test.ts(x)`, `src/**/*.test-d.ts` → [Testing](docs/testing.md) +- `src/routing/**`, `src/modals/modal-host.tsx` → [Routing decisions](docs/edrs/README.md) ## Layers in one paragraph diff --git a/packages/mosaic/docs/edrs/0001-embedded-segment-router.md b/packages/mosaic/docs/edrs/0001-embedded-segment-router.md new file mode 100644 index 00000000000..f5f89761ef0 --- /dev/null +++ b/packages/mosaic/docs/edrs/0001-embedded-segment-router.md @@ -0,0 +1,45 @@ +--- +id: 1 +title: 'Embed a segment router that derives its route from the location' +summary: "A Mosaic component owns one segment of the page's location and derives its route from it on every change. Navigations inside the segment are steps through the router; everything else is an exit handed to clerk-js as a full URL." +status: accepted +implementation: shipped +implementation_note: 'src/routing; exits still go through clerk-js as before.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [architecture] +supersedes: null +superseded_by: null +--- + +## TL;DR + +A component owns a segment under a base, `security` under `/user`, and never the page. It reads its segment, derives a route from it, and navigates by writing a new segment. It keeps no routing state and awaits nothing after a write. A navigation whose destination is outside the segment is not a routing concern: build a full URL and hand it to `clerk-js`, which keeps its origin and protocol checks, URL decoration and the transitive-state handling. + +## Context + +Mosaic renders inside the host app and on the server, before `clerk-js` has loaded, so it cannot wait for `clerk-js` to route. Legacy's router loads with `clerk-js`, uses one `navigate` for both steps and exits, and awaits navigations, which most frameworks cannot honour and which Clerk hacks around. Legacy's `` tree also mixes matching, rendering, guards and relative paths. + +Rejected: routing through `clerk.navigate` for steps, as PR #9843 did. It awaited the write and committed with `flushSync`, ignoring outside changes while in flight, which reintroduced the awaitable-navigate dependency and a stuck state when a host promise never resolves. + +## Decision + +Mosaic has its own routing layer that owns one segment per component and derives the route from the location on every change. `go(name, params)` is the only navigation it offers. Exits are not part of the router and cannot be expressed through it. Guards belong to the component or its machine, not to routes. + +## Consequences + +- Nothing is synchronised after a navigation, so nothing needs to be awaited. +- The server and the client render the same thing from the same input. +- Open-redirect protection stays in one place, `clerk-js`. +- "Which step next" decisions after an OAuth or email-link return still live in `clerk-js` and should move to `shared` as pure functions; that is separate work. + +## References + +- `src/routing/use-router.ts`, `src/routing/router.ts` +- [Routing in Mosaic](../internals/routing.md), mental model and constraints +- [MEDR-0002](./0002-names-in-parts-out.md), [MEDR-0004](./0004-owner-and-nested-routers.md) + +## Changelog + +- **2026-11-06**: Accepted. diff --git a/packages/mosaic/docs/edrs/0002-names-in-parts-out.md b/packages/mosaic/docs/edrs/0002-names-in-parts-out.md new file mode 100644 index 00000000000..8143a4a3698 --- /dev/null +++ b/packages/mosaic/docs/edrs/0002-names-in-parts-out.md @@ -0,0 +1,44 @@ +--- +id: 2 +title: 'Route by name, encode in the location, keep the codec representation-free' +summary: 'Code refers to routes by name and go() takes a name, never a URL. The location splits and decodes once per part and encodes once on write. The codec matches decoded literals against decoded parts and never sees a URL string.' +status: accepted +implementation: shipped +implementation_note: 'src/routing/routes.ts, src/routing/location.ts; virtual mode has no encoded form, so the encoding half is exercised only by the codec tests until a URL mode lands.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [architecture, security] +supersedes: null +superseded_by: null +--- + +## TL;DR + +A route table maps names to patterns; views, controllers and machines use names; `go(name, params)` takes a name and the param types the pattern implies. Only `routes.ts` sees patterns. A pattern literal is written decoded, `api keys` not `api%20keys`; a percent-encoded literal throws when the pattern compiles. Nothing above a location calls `encodeURIComponent` or `decodeURIComponent` on anything from a URL, and nothing navigates to a value taken from a URL. + +## Context + +Double decoding has caused real vulnerabilities at Clerk. Legacy builds and parses URLs ad hoc across components. Names are also what lets the step/exit split from [MEDR-0001](./0001-embedded-segment-router.md) be enforced by a type rather than a convention. + +Rejected: a codec that works on path strings and encodes or decodes itself. It would be one half of a double decode by construction. Rejected: a literal check that refuses anything `encodeURIComponent` would change; it rejected spaces and non-ASCII that match fine as decoded literals. The hazard is only a literal written in encoded form. + +## Decision + +The location owns encoding: split the raw segment, decode once per part, encode once per part on write, and read a malformed escape as no parts. The codec is representation-free: it matches decoded literals against decoded parts and captures params verbatim. `go` takes names; param types flow from the pattern to the name. + +## Consequences + +- Encoding cannot change which route matches, and a param is either fully decoded once or absent. +- A pattern's shape can change for legacy compatibility without touching callers. +- A framework adapter that only offers a decoded path collapses the encoded-slash distinction; that ambiguity is the host's, and Clerk never generates a value with a slash. +- Every location must carry a round-trip test for slashes, percent signs and non-ASCII. + +## References + +- `src/routing/routes.ts`, `src/routing/__tests__/routes.test.ts` +- The Security section of [Routing in Mosaic](../internals/routing.md) + +## Changelog + +- **2026-11-06**: Accepted. diff --git a/packages/mosaic/docs/edrs/0003-page-state-acts-like-a-url.md b/packages/mosaic/docs/edrs/0003-page-state-acts-like-a-url.md new file mode 100644 index 00000000000..be9203a7db1 --- /dev/null +++ b/packages/mosaic/docs/edrs/0003-page-state-acts-like-a-url.md @@ -0,0 +1,54 @@ +--- +id: 3 +title: 'Hold routing state above the components and make it behave like a URL' +summary: "The page's routing state is a map from base to parts in MosaicProvider. A segment lives while its base has a mounted owner. A modal is open exactly while its segment exists. Components hold no routing state in any mode." +status: accepted +implementation: shipped +implementation_note: 'src/routing/virtual-store.tsx, src/modals/modal-host.tsx. The URL modes keep the same contract without the map; see MEDR-0008.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [architecture, virtual, modals] +supersedes: null +superseded_by: null +--- + +## TL;DR + +In virtual mode `MosaicProvider` holds a map keyed by normalised base, one segment per owner. A location is one segment: it reads its own, writes its own, clears its own. A mounted `useRouterScope` counts itself in as an owner of its base; when a base's last owner leaves, the store drops the segment after the commit. A modal host keeps no open flag: `open(options)` writes `initialParts(options)` to the modal's base, `close()` clears it, and the content renders while the segment exists. Nothing a component does on mount or unmount writes to the location. + +## Context + +Legacy virtual state lived inside each component, so it could not be written before mount and did not behave like a URL. Lifting it gave modals a way to open at a page and made two profiles with different bases independent, but it also made the state outlive the component, which no URL does: a host that navigated away and back found the profile where it left it. + +Rejected, in order: clearing on modal close only (left inline profiles stale); the component clearing on its own unmount (wipes a pre-mount write under StrictMode and puts mode knowledge in the component); a writer-keyed release that clears only what the leaving scope wrote (right for user navigations, wrong for a host's seed, which a URL would also drop); an ownership registry with takeover (correct, but a queue, two contexts and a provider). Owner counting with a post-commit sweep is what survived the contract suite, including an owner replaced in the same commit. On its own it treated a parked component as having left, which under `Activity` would reset a profile on Back and on every hide; parking in component state is what keeps that case. A `WeakMap` in the store keyed by the location was passed over because the component's own state already has the right lifetime. Parking from the same effect that owns the base, with the segment as a dependency, was tried and failed the outside-clear case: the cleanup also ran when the segment was cleared and the next run restored it. + +## Decision + +Routing state is a map above the components. A segment lives while its base has an owner, counted in store state and swept after the commit; only a base that has had an owner is swept, so a write ahead of a later mount survives. A component owns its segment only while its effects are live; when they stop it parks the segment in its own state, and when they run again it writes the segment back unless the base was written meanwhile. The park happens only on hide, unmount or a change of location, never on a navigation; the scope renders from the parked segment while hidden, so the page's subtree keeps its state and resume has no flash; a park is tied to the location it came from, so a scope moved to another base starts on that base's root; and the parked value is consumed in render once a segment is present, so a segment cleared from outside shows the root. A truly unmounted component has no state to park in and starts fresh. A modal's open state is the presence of its segment, and its content loads whenever the segment is present, so a segment written from outside opens the modal fully. The sweep deletes only the segment committed with the zero count, never one written after it. In URL modes `own` is a no-op and nothing is parked, because the URL holds the segment; owners are keyed by base alone. + +## Consequences + +- Leave and return starts fresh; a parked owner resumes where it was; an owner replaced mid-exit keeps its page; StrictMode changes nothing. +- A parked modal does not resume, since its content is inside a closed dialog; legacy closes modals on navigation too. +- The parked case is a todo in the contract suite until a React 19 test project exists, since React 18 cannot produce the cycle. The outside-clear case is in the suite, because it is the one a park that also ran on navigation got wrong. +- Back closes a modal and a URL with the segment opens one in the URL modes. A link in the query string writes a segment the same way in every mode, and a redirect returns through one, [MEDR-0010](./0010-links.md). +- A modal clears its own segment when the host's pathname changes, in every mode: the modal host records the page it opened on, on every `open()`, and compares in a passive effect. In the URL modes a host navigation that drops the param closes the modal before the check runs, and one that carries the param to another page, a host that preserves its query string, meets the same close, with a replace that removes the param, so the mode does not change what a page change does; the rule was virtual-only first and widened for that case. Legacy closed modals on every Clerk navigation, hash steps included; here a change of the query string or the hash alone leaves a modal open, since in those modes its own steps live there. A deep link opens on the page it names and stays. The virtual store itself is not scoped to a page, so an inline owner that stays mounted across pathnames keeps its segment. One race is accepted: a page that opens the same modal from its own mount effect, in the commit that changed the pathname, loses to the close, since the child's effect runs before the host's; an `open()` after that commit is kept, because it records the new page. Making the close a layout effect would win by phase ordering alone, which is the kind of timing rule this design avoids. +- Ownership arrives one commit after mount, so an owner's first redirect runs on its second commit. +- `useSegmentParts` returns `undefined` for a base with no segment; a scope reads that as the root, a modal as closed. +- A URL location was expected to project the map so two writes in one tick could not clobber each other. [MEDR-0008](./0008-url-carriers.md) decided otherwise: a URL location reads and writes the URL directly, and the clobber is accepted. + +## References + +- `src/routing/virtual-store.tsx`, `src/routing/location.ts`, `src/modals/modal-host.tsx` +- `src/routing/__tests__/location-contract.test.tsx` +- [MEDR-0007](./0007-location-contract-suite.md) + +## Changelog + +- **2026-11-06**: Accepted. +- **2026-11-06**: Amended after review: render from the parked entry while hidden, park tied to its location, compare-and-delete in the sweep, content loaded on any entry. +- **2026-11-11**: Amended when the URL modes shipped: the projection consequence points at MEDR-0008. +- **2026-11-17**: Amended: links and the return after a redirect are MEDR-0010. +- **2026-11-24**: Amended: a virtual modal closes when the host's pathname changes. +- **2026-11-25**: Amended: `open()` records the page every time; the mount-effect race is accepted and named; entry is now called segment; the close on a pathname change applies in every mode. diff --git a/packages/mosaic/docs/edrs/0004-owner-and-nested-routers.md b/packages/mosaic/docs/edrs/0004-owner-and-nested-routers.md new file mode 100644 index 00000000000..94f1f200781 --- /dev/null +++ b/packages/mosaic/docs/edrs/0004-owner-and-nested-routers.md @@ -0,0 +1,51 @@ +--- +id: 4 +title: "Let the segment's owner name its root and decide the rest; nested routers never write" +summary: 'useRouterScope is for the one component that owns a segment: it names the root that lives at the base, an unknown segment shows the root and is replaced with the base, and an unsettled table reports no route. useRouter is for anything inside: it never writes.' +status: accepted +implementation: shipped +implementation_note: 'src/routing/use-router.ts; MosaicRoutingScope is rendered only in tests until a nested consumer exists.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [api] +supersedes: null +superseded_by: null +--- + +## TL;DR + +The component that owns a segment calls `useRouterScope(routes, { routing, path, root })` once and renders the `scope` it returns around its children. `root` is the route that lives at the base: it is matched by the empty segment and `go` writes the empty segment for it, whatever pattern the table gives it, and that pattern is accepted too and canonicalised to the base. Any other segment nothing matches shows the root at once and is replaced with the base, so the dead segment leaves history. `route` is never undefined, unless the owner passes `ready: false` because its table depends on data that has not arrived; then it is undefined and nothing is written, so an entry the table cannot match yet survives. Children call `useRouter(routes)` with their own table, read mode and base from the scope, and get `route: undefined` for a segment a sibling owns. They never redirect. + +## Context + +If every router could redirect, two tables under one base would fight. Not-found needs a single decision, and the replace is what keeps legacy's back-button traps out. Page-shaped surfaces all put their first entry at the base, and the profiles also let that entry be named from outside through the modal `page` option, so the root needs both an empty segment and its own name. + +Earlier shape: a `notFound` route, which the owner redirected unknown segments to. Two owners on one base with different fallbacks then looped, and three guards were tried: remembering the last redirected-from segment (blocked legitimately recurring segments), detecting an overwritten redirect (only worked at mount), and an ownership registry (correct, but a queue, two contexts and a provider). A redirect fuse replaced them. Naming the root made all of it unnecessary: every owner's fallback is its own base, so two owners of one base write the same thing and cannot loop, and the fuse was removed as untestable. A separate `aliases` map for the root's own segment was folded into `root` for the same reason. + +`notFound` came back as an option of the owner, for the combined profile, which sends an unknown page in the organization group to that group's first page. It names another route for a segment nothing matches, so it reopens the loop for two owners of one base whose `notFound` disagree, and a route it names that needs params would be written without them, match nothing and redirect forever. The second is checked: a name whose built parts do not match back to it shows the root, with a warning. The first is left as the configuration error below rather than guarded with a fuse again. + +Not-ready: the combined profile routed while the organization model loaded, and a deep link to an organization page was replaced with the base before the pages existed. Withholding the table at the call site was `main`'s answer; `ready` is the same answer as a routing-layer concept. + +## Decision + +Two hooks with an opaque scope between them. The owner names its `root`, redirects unknown segments to the base with replace, and reports no route while not ready; nested routers never write. + +## Consequences + +- `route` can be switched on without a guard. Passing `ready` at all makes it optional in the type, so an owner with an unsettled table has to decide what the loading window shows. +- Owners of one base that fall back to their root cannot loop each other, but the second keeps snapping the first back to its root on every navigation; a configuration error shows as that, with no warning. Two such owners whose `notFound` send one segment to different routes redirect each other forever, also with no warning. Owners of one base in different modes, a virtual and a query owner of `/user`, share the query param of [MEDR-0010](./0010-links.md): the query owner reads it as its entry and the virtual owner takes it as a link and removes it. +- An empty table, as when a profile has no pages yet, routes to a placeholder root and writes nothing. +- Nesting lands on the scope later: a sub-surface's base is the parent's base plus its segment. + +## References + +- `src/routing/use-router.ts`, `src/routing/routing-scope.tsx` +- `src/routing/__tests__/use-router.test.tsx` + +## Changelog + +- **2026-11-06**: Accepted. +- **2026-11-06**: Amended after review: `notFound` and the redirect fuse replaced by `root`; `ready` added. +- **2026-11-12**: Amended: `notFound` as an owner option recorded; a route it names that needs params shows the root with a warning; two owners of one base whose `notFound` disagree can loop. +- **2026-11-17**: Amended: owners of one base in different modes share a link's param. diff --git a/packages/mosaic/docs/edrs/0005-profile-url-shape.md b/packages/mosaic/docs/edrs/0005-profile-url-shape.md new file mode 100644 index 00000000000..a95be72cbf8 --- /dev/null +++ b/packages/mosaic/docs/edrs/0005-profile-url-shape.md @@ -0,0 +1,43 @@ +--- +id: 5 +title: "Give the profiles legacy's URL shape and no opening-page prop" +summary: "The first page in navigation order is the root with no segment; every other page has legacy's segment, api-keys for apiKeys. Ids stay the API; the mapping lives in the profile layer. There is no defaultPage: a modal opens on the page passed to open." +status: accepted +implementation: shipped +implementation_note: "src/features/profile-pages; the profiles' modal surfaces write pageParts(options.page) on open." +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [profiles, compatibility] +supersedes: null +superseded_by: null +--- + +## TL;DR + +`useProfilePagesController` maps every page id through `pageSegment`, which is the one place `apiKeys` becomes `api-keys` and `organization/apiKeys` becomes `organization/api-keys`, and names the first page as the scope's `root`, so it lives at the base and its own segment is canonicalised there. Custom pages use their `path`. While the page ids are unknown, because a model is loading, the controller passes nothing and the profile shows its loading fallback. An inline profile opens on its first page; a modal opens on the page passed to `open`, which the host writes before the content mounts through `initialParts`; in a URL mode the URL says. Reorder with `pageOrder` if another page should come first. + +## Context + +Existing URL shapes must keep working, and page ids are host-facing props that cannot change. `defaultPage` predated routing: it was the `useState` initial value. Every meaning tried for it with a location either moved the root with availability, which broke the sticky fallback when a page disappears, or needed an "absent entry shows this page" rule that served only the prop. Legacy never had it for inline profiles, and legacy virtual profiles always opened on their first page. + +## Decision + +First page as root, legacy segments for the rest, mapping in the profile layer, `defaultPage` removed. + +## Consequences + +- The root page has no named segment, as in legacy, so `/user/account` is not a route when Account is first. +- Opening a modal at the first page writes its segment, which the owner canonicalises to the base. The modal `page` option works for every page, including the first; `open()` with no page lands on the first page directly. +- A host that wants an inline virtual profile to open on another page has no way to say so; the honest shape, if needed, is a write to the location from outside, not a prop. +- The breaking changeset for the prop removal ships with this branch. + +## References + +- `src/features/profile-pages/profile-pages.controller.ts`, `profile-pages.layout.ts` +- Legacy: `packages/ui/src/components/UserProfile/UserProfileRoutes.tsx` + +## Changelog + +- **2026-11-06**: Accepted. +- **2026-11-06**: Amended after review: the first page is the scope's `root`; unknown page ids show the fallback instead of routing. diff --git a/packages/mosaic/docs/edrs/0006-validate-host-paths-at-the-edge.md b/packages/mosaic/docs/edrs/0006-validate-host-paths-at-the-edge.md new file mode 100644 index 00000000000..721893e6913 --- /dev/null +++ b/packages/mosaic/docs/edrs/0006-validate-host-paths-at-the-edge.md @@ -0,0 +1,43 @@ +--- +id: 6 +title: 'Validate host-supplied paths where they enter, not in the codec' +summary: "A custom page's path must be exactly its segment: no stray slashes, no leading colon, no percent-encoding, not a built-in page's segment. One that is not is left out with a warning saying what to write. The codec still throws on a bad pattern, because that is Mosaic's own bug." +status: accepted +implementation: shipped +implementation_note: 'withRoutablePaths in src/features/profile-pages/profile-pages.layout.ts.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [profiles, security] +supersedes: null +superseded_by: null +--- + +## TL;DR + +Custom page paths are configuration, but they become pattern literals and are compared raw as page ids. `withRoutablePaths` drops a path that is not written as its own segment (a leading, trailing or doubled slash, or an empty path), one that starts with a colon, one that is percent-encoded, and one that equals the segment of one of the profile's built-in pages where that segment differs from the id, such as `api-keys`. Each warning names the path and, where there is one, the spelling to use. Spaces and non-ASCII are fine. The codec's own assertion stays, for patterns Mosaic writes. + +## Context + +Before this, a host passing `customPages={[{ path: 'my page' }]}` threw inside render with no boundary, where `main` rendered it. A path starting with a colon silently became a param. A path equal to `api-keys` compiled to the same pattern as the built-in and was unreachable. Review then found that `security/` and `/security` passed the raw-string duplicate check while compiling to the same parts as the built-in, and that a built-in table shared between the profiles made the organization profile reject `organization/api-keys`, a page only the combined user profile has. Legacy warns and continues for duplicate paths. + +Rejected: throwing in production for a host typo, which takes down the whole profile over one unreachable tab. Correcting instead of rejecting was considered for the slash and built-in-segment cases, where the fix is unambiguous; it needs the same canonicalisation applied to `pageOrder` and the modal `page` option, and was left as a warning for now. Open: throwing in development only, which the package does elsewhere. + +## Decision + +Reject at the edge with a warning that says what to write, checked per profile against its own built-in pages; keep the codec strict for Mosaic's own patterns. + +## Consequences + +- A bad custom page is hidden rather than shown unroutable, which is a visible change for hosts using such paths. +- The literal rule in [MEDR-0002](./0002-names-in-parts-out.md) is the one the edge enforces. + +## References + +- `src/features/profile-pages/profile-pages.layout.ts` +- `src/features/user-profile/__tests__/user-profile.layout.test.ts` + +## Changelog + +- **2026-11-06**: Accepted. +- **2026-11-06**: Amended after review: paths checked as segments against the profile's own built-ins; messages reworded. diff --git a/packages/mosaic/docs/edrs/0007-location-contract-suite.md b/packages/mosaic/docs/edrs/0007-location-contract-suite.md new file mode 100644 index 00000000000..02bb760df40 --- /dev/null +++ b/packages/mosaic/docs/edrs/0007-location-contract-suite.md @@ -0,0 +1,46 @@ +--- +id: 7 +title: 'Prove mode parity with one contract suite' +summary: 'One test file states what every location mode guarantees to the components above it, parameterised over modes and run in StrictMode. A new mode starts by passing it; inherent differences are declared by name.' +status: accepted +implementation: shipped +implementation_note: 'src/routing/__tests__/location-contract.test.tsx, run for virtual, path, hash and query.' +date: 2026-11-06 +authors: + - 'Fredrik Höglund ' +tags: [testing] +supersedes: null +superseded_by: null +--- + +## TL;DR + +Add a behaviour to the contract suite when it should hold in every mode. Add a mode to the suite before building anything else on it. Declare an inherent difference, such as the pathname holding one entry, in the mode's `excludes` so it is stated rather than discovered. + +## Context + +The virtual-mode gaps were found one at a time by reviewers tracing lifecycles, and each fix found the hole the previous one missed. Parity between modes cannot be guaranteed by reasoning case by case. + +## Decision + +The component-visible contract is a parameterised test suite, and it is the definition of parity. + +## Consequences + +- A divergence between modes is a failing test, not a review finding. +- The suite's "leave" step is what the host navigating away means in each mode: virtual unmounts the owner, a URL mode navigates to another URL and unmounts it. The URL modes declare `parks` and `dropsOnMove`, since the URL keeps a segment until the host navigates; `path` declares `severalBases`; `query` declares `linkIsEntry`, since a link in the query string is its own entry. What the suite does not cover is a write through an adapter, which the location tests cover on their own. +- The suite found two of the bugs it exists for: a park that also ran on navigation restored a segment cleared from outside, and a park not tied to its location carried a page to a new base. Both cases are in it now. +- The parked-and-resumed case needs React 19.2's `Activity` and is a todo until a React 19 test project exists. +- The profile feature tests stay where they are: they test the profiles, not the location. + +## References + +- `src/routing/__tests__/location-contract.test.tsx` +- [MEDR-0003](./0003-page-state-acts-like-a-url.md) + +## Changelog + +- **2026-11-06**: Accepted. +- **2026-11-06**: Amended after review: outside-clear, base-change and two-owner cases added. +- **2026-11-11**: Amended when the URL modes joined the suite: leave per mode, declared differences. +- **2026-11-24**: Amended: `slashInPart` is gone, a part may contain a slash in every mode; `query` declares `linkIsEntry`. diff --git a/packages/mosaic/docs/edrs/0008-url-carriers.md b/packages/mosaic/docs/edrs/0008-url-carriers.md new file mode 100644 index 00000000000..07f4a478770 --- /dev/null +++ b/packages/mosaic/docs/edrs/0008-url-carriers.md @@ -0,0 +1,70 @@ +--- +id: 8 +title: 'Carry a segment in the pathname, the hash or the query string' +summary: "A URL mode reads its segment from the host URL every render and writes the whole URL back at once. The pathname holds one segment in legacy's shape; the hash and the query string hold one param per base, named by a prefix and the base." +status: accepted +implementation: shipped +implementation_note: 'src/routing/url-location.ts, src/routing/url-params.ts, src/routing/window-location.ts and src/routing/use-mosaic-location.ts.' +date: 2026-11-11 +authors: + - 'Fredrik Höglund ' +tags: [architecture, path, hash, query, modals] +supersedes: null +superseded_by: null +--- + +## TL;DR + +`routing: 'path' | 'hash' | 'query'` puts a component's segment in the page's URL. The location is derived: every render reads the host URL, finds its segment and decodes it, and a write builds the full URL with only that segment changed and hands it to the host at once. Nothing is stored or counted; a write asked for before the page has settled is parked until it has. The pathname holds exactly one segment, `/user/security`, as legacy did. The hash and the query string hold one param per base: the key is a prefix and the base with dots for slashes, `.user`, and the value is the parts encoded one by one and joined with `/`. The query string and the hash are read and written as `URLSearchParams`, and a param's value is the encoded segment encoded once more, so a slash inside a part survives there as it does in the pathname. A component's mode is fixed when it mounts. + +## Context + +[MEDR-0003](./0003-page-state-acts-like-a-url.md) made the virtual store behave like a URL and ended with the note that a URL location would have to project the map, or two writes in one tick would clobber each other. Building it the other way round is simpler: a URL already is the shared state the store imitates, so a location that reads the URL and writes it has nothing of its own to keep in step. Projecting the map, or queueing writes into a microtask, was rejected: it adds a second copy of the state, a flush that the host's transitions cannot see, and a window in which a read is stale. Two writes in one handler clobbering each other is accepted; no Mosaic code does it, and a host that does gets the last write, as it would from the URL anywhere else. + +Where a segment lives: + +- The pathname keeps legacy's shape, and `path` is where the component is mounted. There is room for one owner; a second would need the pathname too. A component mounted somewhere other than its `path` shows its root, and its first navigation writes under `path`, away from the page. Legacy threw here; a development warning was tried and dropped. +- Legacy kept hash and query state in one `__clerk_` param it parsed itself. Hosts should not meet Clerk's name in their URLs, and two components on one page need two params, so there is one param per base. The key is the base with its slashes as dots, leading slash included, `.user` and `.modal.user`: the leading dot keeps Clerk's params apart from the host's without naming Clerk, and it survives a host re-serialising the query string, which `~`, `@`, `$` and `:` do not, since `URLSearchParams` percent-encodes everything but letters, digits and `-._*`. A prefix the host sets goes in front, `clerk.user`; there is none by default. +- In the pathname, parts are encoded one at a time and the segment is split before it is decoded, as [MEDR-0002](./0002-names-in-parts-out.md) requires, so a slash inside a part survives. The same was tried for the query string, reading pairs on their raw form, and failed in the swingset under Next: something in the host's stack re-serialised the query after hydration, `organization/general` came back as `organization%2Fgeneral`, and the segment read as one unknown part. A host may re-serialise its query at any time, so the raw form of the query is the host's, not Mosaic's. The query string and the hash are therefore read and written as `URLSearchParams`, the platform's parser, and a param's value is the encoded segment encoded once more: a slash between parts is `%2F`, a slash inside a part `%252F`, and reading reverses both, so a part may contain a slash in every mode. A write spells every pair in `URLSearchParams` form. A raw pair writer that kept the host's bytes, with a decoder of its own to find Mosaic's pair, was built and dropped: the bytes are not Mosaic's to promise once any host re-serialises, the two parsers disagreed at their edges, and a readable slash that turned into `%2F` on the next host write was harder to explain than `%2F` from the start. + +Rejected: `location.hash =` for hash writes, since Next strips a hash it did not write, so every mode writes with `pushState`; one reserved param for every base, since two components would collide and a modal's entry could not be dropped on its own; escaping dots in the key, since `/a.b` and `/a/b` sharing `.a.b` costs less than an unreadable key; closing a modal with `history.back()`, since after a navigation inside the modal that would show the previous page of the modal rather than close it. + +## Decision + +A URL location is derived from the host URL and writes to it directly. + +- The object that spells a segment in one field of the URL is a `SegmentCodec`, built once per owner from the mode and the base by `createPathCodec` or `createParamCodec`: it finds the base's parts in the field's text, writes or removes them, and converts between the parts text and the parts. It holds nothing. +- A mode renders from the one field it owns, read through the adapter's hook where it has one, [MEDR-0009](./0009-router-adapter.md), and from a `window` store otherwise. Reading all three fields through the adapter was how it started, and it made hash and path mode call Next's `useSearchParams`, with its Suspense requirement, for a field they never use. The server renders no segment, so a URL-mode component renders its root and corrects once after hydration. +- A write composes from where it lands, plus the change: from the address bar when it goes to `history`, and through the adapter's `push` or `replace` from the address bar as well, or from the adapter's `readUrl` when it has one. It never starts from the adapter's hooks as the component last rendered them. The address bar is updated by every browser router before or in the same commit as the tree, so it is never behind the host and may be ahead, on Back or during a pending navigation, and ahead is the right thing to compose on; starting from the committed hooks would put the old page back in the address bar in that window. The one host whose location is not the address bar is a memory router, which `readUrl` covers. Starting from the committed hooks, carried to the write through an insertion effect, was built first and replaced. The location object changes only when its segment does, so a host that re-renders does not hand the components above a new location. +- `own` is a no-op and nothing is parked: the URL outlives the component by itself. `clear` replaces; in the pathname it writes the base, in a param it removes the pair. +- A modal opens with a push and closes with a replace. +- The pathname refuses parts of `.` and `..`, which a URL resolves away; compares its base part by part on the decoded form, since browsers and routers leave different characters raw; and reads one trailing slash as the same pathname. +- A `window` write carries no history state, so a host router's bookkeeping never lands on a history entry it did not make. Next's App Router copies its own marker onto a foreign write by itself; a router that needs its state on every entry, for blockers or scroll restoration, is given `push` and `replace` instead. Copying the host's state onto Mosaic's pushes was tried and dropped: React Router and TanStack then saw their index twice and turned a blocked Back into a reload. +- Change notifications are synchronous. A `window` write asked for before the page has settled, in the first commit's effects, is parked and lands in a microtask after that commit, in order; `RoutingConfigProvider` marks the page settled from its first effect. The Next.js App Router installs its `history` patch in its own first effect, which runs after every descendant's, so an unparked correction there would be invisible to it. +- The mode is fixed on the first render, since each mode calls its own hooks. A component changes mode by remounting, which the profiles do by keying on `routing`; a changed prop warns and is ignored. +- Where there is no `window`, the `window` store subscribes to nothing, reads nothing and writes nothing, so virtual mode works in a native app as it is. A URL mode there needs an adapter that is the location, and a write that has nothing to compose from is dropped. + +## Consequences + +- Back works in every URL mode, a deep link opens the page it names, and the page survives a reload. After a modal is opened and closed the page has two history entries, so the first Back appears to do nothing; cheap to change if it turns out to matter. +- Two writes in one tick clobber each other; the last one wins. +- A host that adds trailing slashes serves one redirect when a Mosaic-written URL is loaded; a write makes no request. Under a base path, hash and query work with reads alone; path mode needs the base path in the adapter's pathname and in the component's `path`, since Next leaves it out of both. +- A correction made in the first commit, an unknown segment replaced or a link consumed, lands after the page has settled and is seen by a host router that patches `history` in its own first effect. A guard a feature writes from an effect gets the same treatment without knowing about it. +- A slash inside a part is `%252F` in a param. A write spells the host's own pairs in `URLSearchParams` form, `x%20y` as `x+y` and a bare `flag` as `flag=`; in hash mode a bare anchor `#top` becomes `top=`, since the fragment is Mosaic's there. `/a.b` and `/a/b` share a key. Hash routing with the empty prefix needs a `path` other than `/`, and warns otherwise. +- Every mode runs the contract suite. The URL modes declare `parks` and `dropsOnMove` as differences, `path` declares `severalBases`, and `query` declares `linkIsEntry`. +- The provider's `routing.modals` puts Mosaic's own modals in the hash or the query string, all at once; it answers whether modals are part of the URL in this app, which is one answer per app. A per-surface mode was built and removed unused. Whether a surface should be addressable at all is the surface's to say, and a flag on `defineModalSurface` is where it would go when the first non-addressable surface exists. A URL in these modes can carry segments for several modals, so the host keeps open modals in opening order and lets only the top one take a dismissal. Path mode is not offered for modals: a pathname holds one segment, the page's, and a modal whose base is one configured page misbehaves when opened from any other, so a version that composed the modal's base under a page and closed back to it was built and removed. They stay virtual by default until a product decision says otherwise. +- Legacy's `__clerk_` hash and query shapes are not read. A host moving from the legacy components to Mosaic changes its URLs. + +## References + +- `src/routing/url-location.ts`, `src/routing/url-params.ts`, `src/routing/window-location.ts`, `src/routing/use-mosaic-location.ts` +- `src/routing/__tests__/url-location.test.tsx`, `src/routing/__tests__/url-params.test.ts`, `src/routing/__tests__/location-contract.test.tsx` +- [MEDR-0003](./0003-page-state-acts-like-a-url.md), [MEDR-0009](./0009-router-adapter.md) + +## Changelog + +- **2026-11-11**: Accepted. +- **2026-11-12**: Amended after review: the re-serialised query is attributed to the swingset's stack rather than to Next's hydration. +- **2026-11-17**: Amended: the microtask example is consuming a link. +- **2026-11-24**: Amended: params go through `URLSearchParams` with the segment encoded twice, so a slash in a part works in every mode; `window` writes carry no history state and wait for the page to settle; path mode for modals removed. +- **2026-11-25**: Amended: a write composes from the address bar, or `readUrl`, never from the committed hooks; each mode reads only its own field; the codec is named; the store is inert without a `window`; per-surface modal routing removed; modals keep opening order. diff --git a/packages/mosaic/docs/edrs/0009-router-adapter.md b/packages/mosaic/docs/edrs/0009-router-adapter.md new file mode 100644 index 00000000000..018fef00cca --- /dev/null +++ b/packages/mosaic/docs/edrs/0009-router-adapter.md @@ -0,0 +1,58 @@ +--- +id: 9 +title: 'Reach the host router through a plain adapter object' +summary: 'A host hands MosaicProvider a RouterAdapter of optional hooks, readUrl and navigation functions; each missing member falls back to window. The adapter is taken from the first render. Next supplies its own two hooks as they are.' +status: accepted +implementation: shipped +implementation_note: 'src/routing/router-adapter.tsx; the Next.js App Router adapter is packages/swingset/src/lib/mosaic-next-router-adapter.ts.' +date: 2026-11-11 +authors: + - 'Fredrik Höglund ' +tags: [architecture, adapters, ssr] +supersedes: null +superseded_by: null +--- + +## TL;DR + +`` connects the URL modes to the host router. The adapter is a plain object with `usePathname`, `useSearchParams`, `useHash`, `push`, `replace` and `readUrl`, every one of them optional; a read the adapter does not have comes from `window`, a write without `push` or `replace` goes to `window.history`, and a write composes from the address bar unless `readUrl` says where the router is. `usePathname` returns the pathname as the address bar has it; `useSearchParams` returns a string or a `URLSearchParams`. Mosaic has no framework entry points: the Next.js adapter is `{ usePathname, useSearchParams }` from `next/navigation`, in a file a host copies. + +## Context + +Reading the host's own hooks is what makes a component's segment and the page change in the same commit, inside the host's transitions. Frameworks expose different things: Next has `usePathname` and a `ReadonlyURLSearchParams`, no hash hook, and a `router.push` that fetches from the server; React Router has `useLocation`; TanStack applies navigations asynchronously. One adapter per mode was considered and rejected, since the pathname never needs one and the hash rarely does. Making the reads mandatory whenever `push` is given was considered and rejected in favour of stating what a partial adapter can and cannot see. + +The first adapter read the query string raw, from `window.location.search` under a subscription to Next's hook, because `useSearchParams().toString()` re-encodes the `/` between a value's parts. That workaround was a sign the model was wrong, and the swingset proved it: under Next the query came back re-serialised on load, adapter or not, from something in that app's stack rather than from Next's own hydration. [MEDR-0008](./0008-url-carriers.md) now reads a param's value decoded, so Next's hook serves as it is and the adapter is two imports. Next needs no `push` or `replace`: a `window` write with no history state moves its hooks without the server round trip `router.push` makes, since Next copies its marker onto a foreign entry by itself. + +## Decision + +The adapter is a plain object on `MosaicProvider`, with per-method fallback to `window`. + +- The whole adapter is taken from the first render under the provider: the hooks because the components below call them in their own hook order, `push`, `replace` and `readUrl` so that nothing under the provider has to track a changing adapter. An adapter that later has other hooks warns and is ignored; anything else that changes is silently kept. Taking the functions fresh, through a ref written in an insertion effect, was built first and removed as machinery for a case nobody has. +- A component calls only the adapter hook for the field its mode owns: `usePathname` in path mode, `useSearchParams` in query mode, nothing in hash mode. A missing hook is filled with a no-op hook by the provider, so the call is unconditional and `window` fills in for what comes back empty. +- `usePathname` and `useHash` return the URL percent-encoded, with or without the leading `#`. `useSearchParams` returns the query string with or without its `?`, or a `URLSearchParams`, or `undefined` where it cannot read, and that read falls back to `window`. The hash from `useHash` is ignored until the page has hydrated: a server has no hash, and a client that read one through the adapter hydrated onto a different page than the server rendered. +- A write composes from the address bar, whoever performs it, so the adapter's reads never reach a write and a `URLSearchParams` read cannot respell the host's params. `readUrl`, a plain synchronous function returning `{ pathname, search, hash }`, is for a router whose location is not the address bar, a memory router: with it, a write through `push` or `replace` composes from the router's own location. It is paired with `push` and `replace`, since a write that lands in `history` composes from `history`; that pairing is documented, not enforced. A write through `push` or `replace` is seen through the adapter's hooks, and through `window.location` for a field the adapter does not read, read right after the call returns. +- `keyPrefix` sets what goes in front of the hash and query param names, which start with a dot on their own, so the query prefix names the links of [MEDR-0010](./0010-links.md) too; empty by default. + +## Consequences + +- Build the adapter once, outside render. The provider keeps the first one, hooks and functions alike. +- A host router moves its hooks inside a React transition, so a page change that comes from the host arrives in a transition render. Anything that suspends on purpose to hold the DOM, `Freeze` under a leaving tab panel or dialog, would make that transition wait forever; `Freeze` therefore asks for its hold from the render that first sees it, commits the hold in a sync update before the transition can commit, and lets the transition retry against the already held boundary, which React does not wait for. The profile's pages did not switch in path mode under Next until it did. +- Under Next, only an owner in query mode calls the adapter's `useSearchParams`, so only a statically rendered route that hosts one needs a `Suspense` boundary above it or `next build` fails. That is Next's rule for its own hook; the guide says so. The link consumer of [MEDR-0010](./0010-links.md) reads it for every owner today, and moving that read to the `window` store is open there. +- A memory router works in the URL modes with `readUrl`, `push`, `replace` and the hooks. Without any `window`, as in a native app, virtual mode works with no adapter and the URL modes need that full adapter. +- A router that applies a navigation asynchronously must read the fields it moves, or a write through its `push` is never observed. Under a base path, hash and query work with reads alone, since the write then starts from `window`; path mode needs the base path in the adapter's pathname and in the component's `path`, so that the pathname is read and written in the same world. The earlier advice to supply `push` and `replace` that prepend it was dropped: it made every step a server navigation and still left `useReturnUrl` without the prefix. +- The server renders the pathname and the query string through the adapter, so `path` and `query` render their page on the server, and so does a link. `hash` renders the root, since a server has no hash. +- When `ClerkProvider` starts rendering `MosaicProvider`, the framework SDKs supply the same adapter and hosts stop copying it. + +## References + +- `src/routing/router-adapter.tsx`, `src/routing/use-mosaic-location.ts` +- `packages/swingset/src/lib/mosaic-next-router-adapter.ts`, `packages/swingset/src/app/(clerk)/live/user-profile/user-profile/[[...page]]/page.tsx` +- `src/routing/__tests__/url-location.test.tsx` +- [MEDR-0008](./0008-url-carriers.md) + +## Changelog + +- **2026-11-11**: Accepted. +- **2026-11-17**: Amended: the query prefix names links too. +- **2026-11-24**: Amended: the adapter's hash waits for hydration; the base path recipe prefixes the pathname instead of supplying `push` and `replace`; `query` renders on the server too. +- **2026-11-25**: Amended: the whole adapter is taken from the first render; one hook per mode; writes compose from the address bar or `readUrl`; `readUrl` added. diff --git a/packages/mosaic/docs/edrs/0010-links.md b/packages/mosaic/docs/edrs/0010-links.md new file mode 100644 index 00000000000..e956a87f33f --- /dev/null +++ b/packages/mosaic/docs/edrs/0010-links.md @@ -0,0 +1,71 @@ +--- +id: 10 +title: "Link to a component's page with the query mode's own param" +summary: '?.user=security lands the owner of /user on security in every mode. Owners outside query mode take the param into their own location and remove it; a segment they mount with wins. Redirects return through useReturnUrl.' +status: accepted +implementation: shipped +implementation_note: 'src/routing/consume-link.ts, called from useRouterScope in src/routing/use-router.ts and from src/modals/modal-host.tsx; useReturnUrl in src/routing/use-router.ts.' +date: 2026-11-17 +authors: + - 'Fredrik Höglund ' +tags: [architecture, virtual, modals, redirects] +supersedes: null +superseded_by: null +--- + +## TL;DR + +A link to a component's page is the query mode's own param: the query prefix and the base with dots for slashes, valued as the query codec values it. `?.user=security` lands the owner of `/user` on `security` and `?.modal.user=account` opens the profile modal on `account`, whatever mode they route in. In query mode the param is the segment and nothing happens. In `virtual`, `path` and `hash` mode the owner reads the param for its own base, writes the parts to its own carrier with a replace, and removes the param. The modal host does the same for each surface, since a modal's content does not mount until its segment exists. A link present at mount gives way to an segment the owner already has; one that arrives later is applied. A redirect hands Clerk `useReturnUrl(routes)(name, params)`, which is the page's URL with that link in it. + +## Context + +The first return was profile-specific: three section models appended `__clerk_mosaic_modal=user-profile/account` to the redirect URL in modal mode, and a component in the provider matched that one value and opened the profile modal. Every new redirecting feature would have needed its own value and reader. [MEDR-0003](./0003-page-state-acts-like-a-url.md) made a modal open exactly while its segment exists, so a return can be an segment written from outside, as a deep link is in the URL modes. + +The next shape was a return seed: in virtual mode `useReturnUrl` added a param under a separate return prefix, `r.user=security`, and the provider wrote every such param into the virtual store when it mounted and removed them. It was rejected: + +- Two params meant one thing. `?.user=security` already said "the owner of `/user` on `security`" in query mode; `r.user` said it again, for virtual mode only. A host linking to a page had to know which mode the component was in. +- Nothing outside needs a format of its own. The backend never writes a component's step; it appends `__clerk_*` params to a URL the frontend built. The only writers of the format are `useReturnUrl` and a host's own links, and both can use the query mode's. +- The provider read the URL once, at mount. A link clicked while the page stayed mounted, a Next ``, did nothing until a reload. +- The provider wrote segments for bases it knew nothing about, before anything owned them. + +Also rejected: + +- A reserved param holding every link, rejected for the URL modes in [MEDR-0008](./0008-url-carriers.md) for the same reasons: two links would share one value, and one could not be removed on its own. +- Writing or stripping from render or from the hydration commit. Under Next.js a replace in the hydration commit is lost, because Next patches `history` after it. The link is read during render, from the `window` store's committed snapshot, so the linked page is in the first client render; the write and the strip run in an effect and then a microtask. +- Reading links from the hash. The hash belongs to hash mode's live state and to the host's anchors; a link is a query param only. +- Carrying a modal's open options in the URL. Options are code, such as custom page content; a link falls back to the provider's, as any open without options does. +- Letting models build the URL from the mode, as the first return did. It puts routing knowledge in features. +- Guarding two owners of one base in different modes. They are already a configuration error ([MEDR-0004](./0004-owner-and-nested-routers.md)); a link adds one more way it shows. + +## Decision + +The owner consumes the link for its own base; the provider has no part in it. + +- `useConsumeLink(location, segment, { routing, path })` is called by `useRouterScope` and by the modal host for each surface. Nested routers never write, so they do not consume. The key is `paramKey(queryPrefix, path)`, the query carrier's key for that base; the modal host passes the surface's path. +- In query mode it does nothing. Otherwise it subscribes to the `window` store, and while the owner holds no segment of its own it renders from the link's parts, so a deep link shows its page in the first render. An effect keyed on the query string writes the parts into the owner's carrier or the store and strips the link, so a link that arrives while the owner is mounted is seen too; mount is its first run. The effect reads the live `window.location.search` in a microtask, skipping a run that was cleaned up before the microtask, so StrictMode reads once. +- At the first run a segment the owner has wins: the link is removed and not applied. "Has" means the store or the URL holds parts for the base; in path mode the base itself counts as nothing, since a pathname always says something. A link seen on a later run is applied whatever the segment, because it is a navigation. +- Applying is the location's own write with a replace, to the store, the pathname or the hash. The link is then removed by rewriting the live `window` URL with `writeWindowUrl(url, true)`, never through the adapter's `replace`, so two owners removing their links in one tick compose. Only that one pair is removed; the rest of the query string is rewritten in `URLSearchParams` form, and the write carries no history state. +- `useReturnUrl(routes)` reads the inherited scope and returns a builder typed like `go` without the write options. It reads `window.location` when called and returns an absolute URL with the route's parts written by the scope's carrier, and by the query carrier under the query prefix in virtual mode. Outside a scope it returns the page's URL as it is. + +## Consequences + +- One URL means one thing in every mode. A host links to a component's page without knowing its mode, and a redirect returns to the modal or inline component it left from. +- Only the route comes back. A modal opened by a link has the provider's options; machine state and unsaved input are gone; sections read their resources again, which is what shows the result of the redirect. +- The link is read through the adapter's `useSearchParams` where there is one, so a server render shows the linked page too. Without an adapter the `window` store has no server snapshot, so a server render shows the root and the client takes the link in the re-render that follows hydration. A modal is open from its first render as well, since the host derives the same way. +- A link to a base nothing owns stays in the URL until an owner mounts. A link for an owner mounted later, such as a profile waiting for Clerk, is applied when it mounts. +- Unknown parts in a link go through the owner's table like any segment and show the root. Nothing in a link is ever used as a URL or a destination. +- A virtual and a query owner of one base on one page share one param: the query owner reads it as its segment and the virtual owner removes it. It is the configuration error of [MEDR-0004](./0004-owner-and-nested-routers.md), unguarded. +- Every owner outside query mode re-renders on a change of the page's URL, to see a link arrive. +- Under an adapter whose `replace` applies asynchronously, the location's write may land after the link is removed and bring it back for one more pass. +- `/a.b` and `/a/b` share a link, as they share a param key. A redirect started before an upgrade returns with `__clerk_mosaic_modal` or `r.`, neither of which is read. + +## References + +- `src/routing/consume-link.ts`, `src/routing/use-router.ts`, `src/modals/modal-host.tsx` +- `src/routing/__tests__/location-contract.test.tsx`, `src/routing/__tests__/consume-link.test.tsx`, `src/routing/__tests__/use-return-url.test.tsx`, `src/features/user-profile/__tests__/user-profile.return.feature.test.tsx` +- [MEDR-0003](./0003-page-state-acts-like-a-url.md), [MEDR-0004](./0004-owner-and-nested-routers.md), [MEDR-0008](./0008-url-carriers.md) + +## Changelog + +- **2026-11-17**: Accepted. +- **2026-11-24**: Amended: path mode for modals is gone; a removed link leaves the query string in `URLSearchParams` form and no history state. diff --git a/packages/mosaic/docs/edrs/README.md b/packages/mosaic/docs/edrs/README.md new file mode 100644 index 00000000000..ba4a0303807 --- /dev/null +++ b/packages/mosaic/docs/edrs/README.md @@ -0,0 +1,54 @@ +# Mosaic routing EDRs + +Engineering Decision Records for routing in `@clerk/mosaic`: one file per decision, with the context that led to it and the consequences accepted. [Routing](../routing.md) is the synthesis of these records for someone using routing; the records are the source of truth for someone changing it. + +This follows [clerk/edr](https://github.com/clerk/edr) and the Protect variant, trimmed to what a package needs: no site, no review window. Merging the PR that carries a record is its acceptance, because the record and the code ship together. + +## Create a record + +1. Pick the next free number: `ls`. Numbers are never reused. +2. Copy `template.md` to `NNNN-short-kebab-slug.md`. +3. Fill in the frontmatter. `summary` is at most 240 characters and is read far more often than the body; write it last. `implementation` says what exists on `main` today, not what the decision asks for. +4. Write TL;DR, Context, Decision, Consequences. Keep it to about a screen. Rejected alternatives go in Context, so they are not retried. +5. Cite other records as `[MEDR-NNNN](./NNNN-slug.md)`, and from code as `MEDR-NNNN` in a comment so references are greppable. + +## Status and implementation + +`status` is about the decision, `implementation` about the code. + +| Status | Meaning | +| ------------ | ----------------------------------------------------- | +| `accepted` | Merged and authoritative. | +| `deprecated` | No longer recommended, nothing has replaced it. | +| `superseded` | Replaced by a newer record; `superseded_by` names it. | + +| Implementation | Meaning | +| -------------- | ----------------------------------------------------------------------------- | +| `shipped` | Built and on `main`. The whole decision, not the easy half. | +| `partial` | Some of it runs. The note says which half is missing. | +| `in-flight` | Implemented somewhere that is not `main`. The note names the branch or stash. | +| `none` | Nothing implements it yet. | + +## Amending vs superseding + +- Typo, clarification, the code catching up: amend in place and add a dated Changelog line. +- The decision changes: write a new record with `supersedes: N`, mark the old one `superseded` with `superseded_by: M`, and never edit its decision text. + +## Not a record + +Bug fixes, implementation detail inside a decided design, and open questions. Open questions live in [the design notes](../internals/routing.md). + +## Index + +| Record | Summary | +| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| [MEDR-0001](./0001-embedded-segment-router.md) | A component owns one segment and derives its route from it; everything outside the segment is an exit via clerk-js. | +| [MEDR-0002](./0002-names-in-parts-out.md) | Routes are named; the codec works on decoded parts and never sees a URL; the location encodes once each way. | +| [MEDR-0003](./0003-page-state-acts-like-a-url.md) | Routing state is a map above the components; a segment lives while its base has an owner; a modal is its segment. | +| [MEDR-0004](./0004-owner-and-nested-routers.md) | The owner names the root that lives at the base and redirects unknown segments there; nested routers never write. | +| [MEDR-0005](./0005-profile-url-shape.md) | Profiles use legacy's segments with the first page as root, and have no opening-page prop. | +| [MEDR-0006](./0006-validate-host-paths-at-the-edge.md) | A custom page path must be exactly its segment, checked where it enters; the codec throws only on Mosaic's own bugs. | +| [MEDR-0007](./0007-location-contract-suite.md) | Every location mode passes one contract suite; differences are declared, not discovered. | +| [MEDR-0008](./0008-url-carriers.md) | A URL mode derives its segment from the host URL and writes the URL back at once; one param per base in hash and query. | +| [MEDR-0009](./0009-router-adapter.md) | The host router is reached through a plain adapter of optional hooks and functions on `MosaicProvider`; missing ones fall back to window. | +| [MEDR-0010](./0010-links.md) | A link is the query mode's own param in every mode; other owners take it into their own location and remove it. | diff --git a/packages/mosaic/docs/edrs/template.md b/packages/mosaic/docs/edrs/template.md new file mode 100644 index 00000000000..208d31e797c --- /dev/null +++ b/packages/mosaic/docs/edrs/template.md @@ -0,0 +1,38 @@ +--- +id: NNNN +title: 'Short imperative title' +summary: 'One or two sentences saying what the decision is. At most 240 characters.' +status: accepted +implementation: none # shipped | partial | in-flight | none +# implementation_note: "One sentence naming the package, file or branch. Required for partial and in-flight." +date: YYYY-MM-DD +authors: + - 'Your Name ' +tags: [] +supersedes: null +superseded_by: null +--- + +## TL;DR + +The decision in plain language and the obligations it places on someone writing code. A reader should be able to act on this section alone. + +## Context + +What forced a decision: the constraints, and the alternatives that were tried or considered and why they were rejected. + +## Decision + +The decision in one or two sentences, present tense, then enough detail that a new engineer can apply it without asking. + +## Consequences + +What becomes easier, what becomes harder, what obligations this creates. + +## References + +- Files, tests, PRs, related records. + +## Changelog + +- **YYYY-MM-DD**: Accepted. diff --git a/packages/mosaic/docs/internals/routing.md b/packages/mosaic/docs/internals/routing.md new file mode 100644 index 00000000000..d2dba807cd5 --- /dev/null +++ b/packages/mosaic/docs/internals/routing.md @@ -0,0 +1,188 @@ +# Routing in Mosaic + +> [!NOTE] +> This document is written for humans as well as agents, it should stay primarily written by humans or else very heavily reviewed. +> +> We need to fully own the mental model, constraints and high level design here and not let it drift or deteriorate due to agents editing it poorly. + +## Mental model - Current state + +Routing in Clerk is not like traditional routing. Our router is usually a router embedded inside a host router and it doesn't own the full page (when no framework-adapter is provided, you can think of the host as `window`). You can think of it as having three conceptual parts: + +- Segment routing + - Our components live under some specific part of the hosts url and owns what happens there + - This might be `/sign-in/*` (path routing), `/sign-in#/x` (hash routing) or a modal on an arbitrary url like `/dashboard` (virtual routing, internal only). +- Navigations away from or outside of that segment - "Exits" + - Can be soft or hard (cross-origin, Safari ITP) + - Types of exits: + - After an auth change. `setActive` with a redirect, sign-out, task redirects. + - Leaving for Clerk's own pages. Sign-in to sign-up when they are different pages, Account Portal, the public user-verify route. Built from environment URLs. + - Leaving for a third party. OAuth, SAML, email-link, Web3 wallets. Always a hard navigation, with a return URL we choose. + - Leaving for the host's pages. `afterSignInUrl`, a custom profile link, "back to app" from a task. Plain URLs the host configured. +- Building and parsing urls + - This part is pretty ad-hoc rather than well defined currently + +In `clerk-js`/`ui`, routing is quite entangled. The router doesn't load until `clerk-js` is fully loaded, including `environment` etc, which is fine since `ui` never renders until that point anyway. The host routing adapter goes into `clerk-js` via options and gets passed on to `ui` in the form of `navigate`, which is used for both segment routing and exits. + +Three details about the current implementation worth knowing about: + +- Every `clerk.navigate` call also fires listeners that close modals +- Modal state is memory only. Return after a redirect exists for the profile's OAuth and enterprise connect, carried in a query param. +- The "which step next" decisions after an OAuth or email-link return live inside `clerk-js` and navigate using legacy URL shapes and component-relative paths. + +### The transitive state + +This is a confusing but very central aspect to how Clerk works, so it deserves its own section. + +After an auth change that also navigates, we need Page A to only see Session A, and Page B to only see Session B. There are many reasons for this, but the simplest one to understand is; imagine Session A does not have access to Page B. If we navigate before the auth change, we would hit a 403 or redirect. If Session B does not have access to Page A, then if we do the auth change first, the same thing happens so there is no safe order. + +What we do instead is, we emit `session: undefined` (loading), navigate, wait until navigation is complete, and then emit Session B. This is what the pages see: + +- Page A - Session A +- Page A - Session `undefined` - Loading state Page A +- Page B - Session `undefined` - Loading state Page B +- Page B - Session B + +This is built around the navigation being awaitable and is something we might want to change in the future. + +Since this is an exit `clerk-js` will keep handling, it only affects Mosaic in one case: + +- For any Mosaic component that stays mounted across the transitive gap, we need to handle loading going back to true, either by showing an actual loading state, or by snapshotting the previous state and keep showing that + +## Mosaic routing constraints + +- Mosaic renders inside the host app + - It cannot wait for `clerk-js` for segment routing + - Exits are asynchronous by nature, it can still rely on `clerk-js` for those +- Mosaic can render on the server + - We don't necessarily build full SSR support initially, but nothing may block it +- We should not rely on navigations being awaitable + - Most frameworks don't support this and we currently hack around that + - Mosaic should not make it harder to move away from these hacks +- No breaking changes to `clerk-js` + - We can do this later, but we need to build Mosaic without any +- Legacy ui and Mosaic can share a page during migration + - This is necessary for incremental adoption during the experimentation/beta phase +- Need to accept the existing URL shapes + - Fine to add more +- The host router adapter must be compatible with all frameworks and have a `window` fallback + - We don't need to build all framework adapters now, but whatever shape we pick needs to support all +- Need to preserve `path`, `hash` and the internal `virtual` router modes + - Public API should stay identical if possible to avoid churn + - Still needs to be configurable per component +- Building and parsing URLs has security implications and should be first class citizen +- Return to the right place after a redirect, including back into a modal + - This does not always happen in legacy, we should have higher ambitions for Mosaic +- We rely heavily on state machines in Mosaic, routing needs to play nicely with these +- Because `environment`, `client` etc is not available on page load, routing must not rely on those + +Another big change is that Mosaic also supports subcomponents. This creates a situation where the host app might now own the routing for a surface we previously had full control over. This creates additional challenges, for example when that subcomponent has its own internal routing, or when it does something like an OAuth redirect and needs to come back to the same place, a route the host now owns. This creates more points of interaction between the host router and our components. + +## Implications + +This is mostly based on the above constraints, but also some research. + +- The route is derived, never stored + - On every location change the router reads and parses the segment, and the result is the route + - Our own navigation is just one more source of change + - Because the router keeps no state of its own, there is nothing to sync after a navigation. That is why navigations no longer need to be awaited +- The only stateful piece is where the segment lives + - For `path`, `hash` and `query` that is the framework adapter's/browser's URL + - For `virtual` this is a value in memory +- Render from framework adapter state over `window` if it exists + - So our segment and the host page change in the same commit + - Each mode reads only the field it owns through the adapter, so a mode never calls a host hook for a field it does not use +- Writes go through the adapter if there is one, otherwise `history.pushState` + - A write composes from where it lands plus our change: the address bar, or the adapter's `readUrl` for a router whose location is not the address bar. Never from what the host last rendered; the address bar is updated before or in the same commit as the tree, so it is never behind the host + - Hash steps are written with `pushState` too, never `location.hash =`, since Next strips a hash it did not write + - `window` writes carry no history state and wait for the page to settle, so a host router keeps its bookkeeping off entries it did not make and sees a correction made in the first commit +- Automatic navigations replace; only a user action pushes + - Otherwise every bounce and redirect leaves a history entry, which is the source of legacy's back-button traps +- Change notifications + - Delivered synchronously after the write. Mosaic writes only from handlers and effects, never from a lifecycle where a state change is unsafe; an adapter's own hooks notify whenever the host does + - Carry no payload. Readers re-read the live location. - Payload can be stale by the time it's read if multiple writes are coalesced +- Exits are not part of the router. They are a single call into `clerk-js` with a full URL, and the router cannot express one +- Guards belongs to machines/components, not routes +- We should move "which step next" decisions from `clerk-js` to `shared` + - Pure functions returning a step or an exit URL, consumed by `clerk-js`, legacy ui and Mosaic alike. No behaviour change, so we can do this first. +- Mosaic-internal navigations do not need to trigger the navigation events in `clerk-js` + - These are only used to close legacy modals, which is not necessary on Mosaic-navigation + - Mosaic also do not need to listen to these as it has its own way to close modals + +## Design notes + +The decisions are recorded in [the routing EDRs](../edrs/README.md) and the usage in [docs/routing.md](../routing.md); this section keeps the context those two do not carry while the work is in progress. + +- The router is three parts: a location, one implementation per mode and per framework adapter; a route table per component, typed, that parses and builds a segment; and the router that derives a route from the two and hands the component `route`, `params` and `go` +- Names are the API, patterns are the codec. `go()` takes a name and params, never a URL, which is what enforces the step/exit split +- The seam is `useSegmentParts()`, `write()`, `clear()` and `own()`. Each location implements how React learns about its changes: with a framework adapter that is `usePathname`/`useLocation`, so the host's transitions apply; `virtual` is plain React state; only the `window` fallback needs `useSyncExternalStore`, since its source is outside React +- Two hooks: `useRouterScope` for the segment's owner, `useRouter` for everything inside it. The owner renders the `scope` it gets back around its children; nested routers read mode and base from it. The owner names its `root`, the route that lives at the base: an unknown segment shows the root and is replaced with the base, so owners of one base always agree and cannot loop. An owner whose table depends on data that has not arrived passes `ready` and reports no route, writing nothing, until it has. The scope is where nesting lands later: a sub-surface's base is the parent's base plus its current segment +- The page's routing state is a map from base to parts, held above the components. A segment lives while its base has an owner, and a parked component keeps its segment in its own state so it resumes where it was; a modal is open while its segment exists. Virtual holds the map as state in `MosaicProvider`. A URL mode holds nothing of its own: it reads its segment from the URL and writes the URL back at once ([MEDR-0008](../edrs/0008-url-carriers.md)); several segments fit in the hash or the query string, exactly one in the pathname. A second pathname owner on a page is a configuration error +- The profiles use legacy's segments with the first page as the root, and there is no `defaultPage`. The modal `page` option is the host writing the segment before the content mounts +- No `` component. Legacy's `` tree did matching, rendering, `canActivate` guards and nesting with relative paths. The table does the matching, the view switches on `route`, guards live in the component or machine, and a nested surface is a nested scope with its own table +- Framework adapters + - For now, they are passed into ``, as copy-paste objects rather than entry points. No adapter means the `window` fallback, which stays a supported mode + - The adapter is taken from the first render under the provider, hooks and functions alike; a changed hook set warns, anything else is silently kept + - Without a `window` the fallback is inert: virtual mode works on its own, a URL mode needs an adapter that is the location + - Later when `` starts rendering `` it comes in that way via the framework SDKs instead. Same adapter, different supplier + - These are also what would provide the server URL +- SSR status: `virtual` renders the same on server and client. `path` and `query` with an adapter read the request URL through the host's hooks; `hash` and the `window` fallback render the root on the server and correct once after hydration +- `query` mode is one param per base, `.user=security`, not one reserved param: two components keep apart and a modal's param can be dropped on its own. It is sent to the server, so it is the candidate for modal state that survives a refresh or a redirect + +## Security + +The URL is attacker-controlled input: anyone can send a user a link. That covers the path, the hash, the query string, and anything that seeds the virtual store from them. The routing layer treats all of it as untrusted and keeps the handling of it inside a few boundaries, so the rest of Mosaic never has to reason about encoding, canonical forms or redirects. + +### Boundaries + +- The location is the encoding boundary. It splits on the encoded form, decodes once per part, and encodes once per part on write. A malformed escape reads as no parts. Nothing else in Mosaic calls `decodeURIComponent` or `encodeURIComponent` on anything that came from a URL +- The codec is representation-free. It matches decoded literals against decoded parts and captures params verbatim. It never sees a URL string, so it cannot take part in a double decode, and it never throws on input, only on a bad pattern, which is ours +- The router takes names, never URLs. `go(name, params)` can only produce parts inside the component's own route table, so a step cannot leave the segment, carry an unchecked string, or skip the codec +- Exits are clerk-js's. Anything that navigates outside the segment is a full URL handed to clerk-js, which rewrites disallowed protocols, applies the cross-origin rules and decorates the URL. Mosaic never reimplements those checks +- The base isolates instances. A location reads only its own segment; one component cannot see or be moved by another's + +### Guarantees + +- Encoding cannot change which route matches. The split happens on the encoded form, so an encoded slash stays one part. On a framework adapter that only offers a decoded path the host has already collapsed that distinction; the ambiguity is the host's and Clerk never generates a value with a slash +- A param is either fully decoded, exactly once, or absent. There is no state in which a value is half decoded or still encoded +- Build and parse round-trip for any string, including slashes, percent signs and non-ASCII. Each location carries that test +- Input never throws. Malformed escapes give no parts and unknown segments give no route; both render the component's fallback page +- Pattern literals are written decoded. `compilePattern` throws on a percent-encoded literal, so a pattern cannot be written in a way that matches differently from how it reads + +### Rules for code outside the routing layer + +- A param is opaque, untrusted text. Use it as an id to look something up, or render it as text. Do not decode it, encode it, split it, or build a URL from it +- Never navigate to a value from the URL. A step is `go(name)`. Anything else is an exit, built as a full URL and passed to clerk-js, which is where open-redirect protection lives. A param, a query value or a hash is never a destination +- Do not read `window.location`, `location.hash` or the query string in a feature. Go through the router, or a location. A state-carrying query param, such as the return after an OAuth redirect, is read in one place, matched against an allowlist of known values, and stripped. Its value is never interpreted as a path or a URL +- Custom page paths are configuration, not URL input, but they become pattern literals, so they are validated where they enter: decoded, no leading colon, not a built-in page's segment +- An unknown route is a fallback page, not an error to repair. Do not try to recover by decoding differently or guessing a route +- The same rules apply to every mode. Values from the hash or a query param are URL input in exactly the way path parts are + +## Open questions + +- How routing and machines work together. The URL proposes a step and the machine decides, but the contract is undefined: how a proposal enters the machine, how the decision is written back, and whether the runtime can move to an earlier state on request. A deep link, a back press and a redirect return are the three cases. +- Whether sub-routes nest, for subcomponents with their own steps inside a host-owned container +- Whether the exit seam returns `clerk-js`'s navigation promise. Four models await it today for busy states, all of them exits. Returning it keeps a dependency on the awaitable navigate; dropping it means busy states end on unmount or a timeout instead. This is desirable to move away from awaitable navigation, but there's some details to figure out. +- Typed page ids for the profiles. A `const` type parameter on `UserProfile` can infer custom page paths from an inline `customPages` literal, so `pageOrder`, the modal `page` option and the pages controller's `route`/`go` become a union of built-in ids and the consumer's paths instead of `string`. It only narrows for inline or `as const` pages and must drop the `(string & {})` escape hatch, so it is one change across the props, the modal options and the controller + +## Vocabulary + +- **Embedded router**: Mosaic's router. It owns one segment of the location and never the page; the host, or the window when there is no host router, owns the rest. +- **Location**: where a segment lives and how it is read and written. One implementation per mode. Its seam is `useSegmentParts()`, `write()`, `clear()` and `own()`. +- **Mode**: which location a component uses. `path` (the pathname under a base), `hash` and `query` (one param per base), `virtual` (the page's in-memory map). Chosen per component through the `routing` prop, and fixed for the component's lifetime; `virtual` is also what modals use by default. +- **Base** (base path): the part of the location a component sits under, `/user` for the profile. Set with the `path` prop, defaulted per component. One owner per base per page. +- **Segment**: a component's piece of the location: its base and the parts under it. `/user/security` and `?.user=security` are the same segment spelled in two modes. A component has a segment or has none, and a segment with no parts is still one, which is what keeps a modal open at its root. Written by a navigation or from outside; in virtual mode dropped when the base's last owner leaves. +- **Parts**: the segment's value as decoded parts, `['billing', 'statement', 'st_1']`, as `useSegmentParts()` returns it. `undefined` when there is no segment. +- **Owner**: a mounted `useRouterScope` under a base. The only router that redirects, and what keeps the base's segment alive. +- **Route table**: a component's typed map from route names to patterns. The only place patterns are declared. +- **Route name**: how code refers to a route: `factorOne`, `statement`. What `go()` takes, what views switch on, what machine states map to. Never a URL. +- **Pattern**: the shape of a segment, `billing/statement/:statementId`. Only the codec sees it. Param types are derived from it. +- **Route**: the result of parsing a segment against a table: a name plus params, or nothing when no pattern matches. +- **Route codec**: parsing parts into a route and building parts from a name and params. Representation-free. +- **Segment codec**: how one mode spells a segment in one field of the URL, `SegmentCodec` from `createPathCodec` or `createParamCodec`. Translates between the field's text and the parts, holds nothing. +- **Step**: a navigation whose destination is inside the component's segment. Made with `go(name, params)`. +- **Exit**: a navigation whose destination is outside the segment. A full URL handed to `clerk-js`, which decides soft or hard, decoration and the transitive state. +- **Scope**: the mode and base a surface was mounted with, shared with everything nested inside it through `MosaicRoutingScope`. Configuration, not state. Returned by `useRouterScope` as an opaque value. +- **Framework adapter**: the host-router integration a URL-mode location reads and writes through, `usePathname` and `useSearchParams` in Next. A plain object of optional members, hooks for rendering and `readUrl`, `push` and `replace` for writing, supplied at the top, by `MosaicProvider` now and `ClerkProvider` later, and taken from the first render ([MEDR-0009](../edrs/0009-router-adapter.md)). +- **Window fallback**: what a URL-mode location reads and writes for each adapter member that is missing. Reads `window.location`, listens to `popstate`, `hashchange` and the Navigation API's `currententrychange` where the browser has it, writes with no history state once the page has settled, is inert where there is no `window`, and is the one place `useSyncExternalStore` is still needed. +- **Page** vs **step**: a profile's navigation entries are pages; a flow's states are steps. Both are routes; the words only say which kind of surface owns them. diff --git a/packages/mosaic/docs/routing.md b/packages/mosaic/docs/routing.md new file mode 100644 index 00000000000..34ab6126c77 --- /dev/null +++ b/packages/mosaic/docs/routing.md @@ -0,0 +1,129 @@ +# Routing + +How a Mosaic component keeps its place in the page's location, and how a host or a modal puts it there. The reasoning is in the [decision records](edrs/README.md); this guide is about using what they decided. + +## The model + +A component owns one segment of the location: a base, `/user` for the user profile by default, and the parts under it, `security` for its Security page. `/user/security` and `?.user=security` are the same segment spelled in two modes. Which page is open is the location's to say: the component reads its segment, derives a route from it, and navigates by writing new parts. It holds no routing state of its own, so Back, reload and deep links work by construction rather than by handling. + +Where the segment lives is the component's `routing`: + +- `virtual` keeps it in memory, in `MosaicProvider`, and the browser URL does not change. The default. +- `path` keeps it in the pathname under `path`, `/user/security`, as the legacy components do. +- `hash` and `query` keep it in one param per component, `#.user=security` or `?.user=security`. + +The same component code runs in every mode. The host, not the component, decides where its segment lives. + +## URL modes + +- In `path` mode `path` is where the component is mounted, so a host with a catch-all route at `/account/[[...page]]` passes `path='/account'`. One component per page can use the pathname; a second one takes another mode. +- In `hash` and `query` mode the param's name is the component's base with dots for slashes and a leading dot, `.user`, `.modal.user`, so it never collides with the host's own params. `routing={{ keyPrefix: { query: 'clerk' } }}` puts a prefix in front, `clerk.user`; there is none by default. The value is the segment, so `?.user=billing%2Fstatement%2Fst_1` is the statement page. The host's other params are kept; a Mosaic write spells the query string the way `URLSearchParams` does, so `x%20y` becomes `x+y` and a bare `flag` becomes `flag=`. +- In `hash` mode the fragment is Mosaic's. A host anchor such as `#top` stops scrolling once a param sits beside it, and clicking one resets the component. +- A navigation pushes a history entry; a correction to the first page and a modal closing replace. Back moves through a component's pages. Reloading or sharing the URL opens the page it names. +- `routing` is fixed when the component mounts; a changed prop warns and is ignored. The profiles remount themselves on their first page when their prop changes. +- Without an adapter the URL modes read and write `window.location`. The server renders the first page and the client corrects it after hydration. A host router that is not given `push` and `replace` does not see Mosaic's history entries in its blockers or scroll restoration. +- Where there is no `window` at all, as in a native app, virtual mode works as it is and the URL modes need an adapter that is the location: the hooks, `readUrl`, `push` and `replace`. + +### The host router + +Hand `MosaicProvider` an adapter so a Mosaic navigation and the host's page change in the same commit, and so the host's own navigations reach the component: + +```tsx + +``` + +A `RouterAdapter` is a plain object of optional members: `usePathname` and `useHash` are hooks returning that part of the URL as `window.location` has it, `useSearchParams` returns the query string or a `URLSearchParams`, `push` and `replace` navigate the host router to a full URL, and `readUrl` returns the router's current location for a write to start from. Each one the adapter does not have falls back to `window`. The whole adapter is taken from the first render under the provider, so build it once, outside render. + +A component in `path` mode calls `usePathname`, in `query` mode `useSearchParams`, and in `hash` mode nothing from the adapter, since each reads only the field it owns. A write composes from the address bar plus the component's change, whoever performs it. A router whose location is not the address bar, a memory router, provides `readUrl` with `push` and `replace`, and a write composes from that instead. + +Under Next.js App Router, copy `packages/swingset/src/lib/mosaic-next-router-adapter.ts`: `usePathname` and `useSearchParams` from `next/navigation`, nothing else. Leave out `push` and `replace`; Mosaic writes `window.history` and Next picks the change up without the server round trip `router.push` would make. Three things to know: + +- A component in `query` mode calls `useSearchParams`, so a statically rendered route that hosts one needs a `Suspense` boundary above it or `next build` fails, as it does for any component that calls that hook. The other modes do not call it. +- Under a `basePath`, hash and query need nothing. Path mode needs the base path in both places Next leaves it out: `usePathname: () => basePath + usePathname()` in the adapter and `path={basePath + '/account'}` on the component. +- With `trailingSlash` on, a URL Mosaic wrote gets one redirect when it is loaded. A write itself makes no request. + +Routers that keep their own copy of the location, React Router and TanStack among them, need `push` and `replace` as well as the reads, or they may not see a step Mosaic wrote to `window.history`. + +## Own a segment + +The component that owns a segment calls `useRouterScope` with a route table and the location options. Names are what the component uses; patterns are what the segment looks like. + +```tsx +const routes = { + account: '', + security: 'security', + statement: 'billing/statement/:statementId', +} as const; + +const { route, params, go, scope } = useRouterScope(routes, { routing: 'virtual', path, root: 'account' }); +``` + +- `root` is the route that lives at the base. `go(root)` writes the segment with no parts, and parts nothing matches show the root and are corrected to the base. +- `notFound(parts)` may name the route unknown parts go to instead of the root, as the combined profile does for an unknown organization page. +- `route` is a name from the table and never undefined. If the table depends on data that has not arrived, pass `ready: false` until it has; `route` is then `undefined` and nothing is written, so parts the table cannot match yet are kept. +- `go('statement', { statementId })` writes the parts for a name. Param types come from the pattern. There is no way to navigate to a URL from here; anything outside the segment is an exit through `clerk-js`. +- A pattern literal is written decoded, `api keys` not `api%20keys`; `:name` captures a part, `:name?` may be absent. The pattern `''` is the base itself. A part may contain any character, including a slash. +- Render `` around children that route inside the segment. They call `useRouter(routes)` with their own table, read the same segment, and never write. + +One owner per base on a page. Two owners of one base keep correcting each other; give one of them another `path`. + +## Profiles + +`UserProfile`, `OrganizationProfile` and `Profile` route their pages through one table built from the page ids: the first page in navigation order is the root with no parts, every other page has the parts legacy used, `api-keys` for `apiKeys`, a custom page's `path` for a custom page, and `organization/...` for the organization pages in combined mode. + +- A profile opens on its first page. Reorder with `pageOrder` if another page should come first; there is no prop for the opening page. +- `routing` picks the mode and `path` the base, `/user` and `/organization` by default. Both can be set once for every profile through the provider's `profile.userProfileProps` and `profile.organizationProfileProps`. Two profiles on one page need different bases. In path mode `path` is where the profile is mounted. +- A profile that unmounts and mounts again starts on its first page. One that is parked and shown again, by `Activity` or anything else that keeps its state, comes back on the page it was on. +- A custom page's `path` is its part of the segment, exactly: no leading, trailing or doubled slash, no leading colon, no percent-encoding, and not a built-in page's. A path that breaks a rule is left out with a warning saying what to write instead. +- A profile shows its loading fallback until every model its pages depend on is ready. A page written before then, by a modal opening at it, is shown once the pages are known. + +## Modals + +A modal surface declares a base with `path`, `/modal/` by default; the modal is open exactly while there is a segment for that base. `open(options)` writes `initialParts(options)` and the content mounts reading it; `close()` removes the segment. Content receives the base as `path` and routes under it like any owner. + +```ts +export const userProfileModal = defineModalSurface({ + id: 'userProfile', + variant: 'profile', + load: () => import('./user-profile.modal-content'), + path: '/modal/user', + initialParts: options => pageParts(options?.page), +}); +``` + +`useModal(userProfileModal).open({ page: 'security' })` opens a profile on a page. A segment written from outside, by a link or a URL, opens the modal too, and its content loads whenever it is open. + +Mosaic's own modals are virtual by default; `routing={{ modals: 'query' }}` on the provider puts them in the query string, `'hash'` in the hash, for every modal at once. In those modes opening pushes a history entry and closing replaces it, so Back closes the modal and a URL with the param opens it. Modals never use the pathname. In every mode a modal closes when the host moves to another pathname, even when the navigation carries its param along; a change of the query string or the hash alone leaves it open. A URL in hash or query mode can carry segments for more than one modal, so two can be open at once; the host keeps them in opening order and an outside press or Escape closes the one on top only. + +## Links + +A link to a component's page is the query mode's param, in every mode. `?.user=security` lands the owner of `/user` on Security, and `?.modal.user=account` opens the profile modal on Account, whether they route in memory, the pathname, the hash or the query string. A host links to a page with it, and a redirect returns through it. + +- In query mode the param is the component's segment and stays in the URL. In the other modes the owner moves the page to its own place and removes the param. +- Links are read from the query string only, and whenever the URL changes, so a `` on a page that stays mounted works. +- When the owner mounts with a page already in its own place, that page wins and the link is removed unused: a reload of a URL that already names the page. A link that arrives after mount is followed whatever page is open. +- A link for a base nothing owns stays in the URL until an owner mounts. + +### Returning after a redirect + +A flow that leaves the page and comes back, such as an OAuth or enterprise connection, hands Clerk the URL to return to. Build it with `useReturnUrl`, anywhere `useRouter` can be called: + +```ts +const returnUrl = useReturnUrl(routes); + +await user.createExternalAccount({ strategy, redirectUrl: returnUrl('account') }); +``` + +`returnUrl(name, params)` is typed like `go` and returns the page's URL as it is when called, with the route for the scope's owner written into it. It never navigates. Outside a scope it returns the page's URL unchanged. + +What comes back is the route and nothing else. A modal reopened by a link gets the provider's `profile` options, a flow's machine starts in its first state, and a section reads its resources again, which is what shows the result of the redirect. The profile sections that redirect return to the account page of the profile they left, modal or inline. + +## Seeing it run + +The swingset has a Routing section at `/routing`, `packages/swingset/src/app/(explorer)/routing`, that shows every mode on components with nothing in them but routing: a page with host links into its steps, two components side by side, a modal and a modal on a modal, tabs in the pathname, multiple tabs on one page, and a page with modals opened from inside it. None of it needs a session. The live user profile and switcher pages keep a mode switch for the real components. + +## Tests + +- The contract every mode keeps is in `src/routing/__tests__/location-contract.test.tsx`, run for all four modes. Add a behaviour there when it should hold in every mode, and add a mode there before anything else. +- To test routing in a hook, wrap it in `RoutingConfigProvider` and `VirtualStoreProvider` with an `initial` map of base to parts, and read the store with `useVirtualEntries` or `useVirtualSegment`. Both providers are needed: writes to `window.history` wait for the provider to settle. +- Feature tests render inside `MosaicProvider` and read segments the same way. `useVirtualSegment` returns `undefined` for a base with no segment, which is how a test tells "cleared" from "empty".