Router unstable
The Router: the current URL as a route value, its changes, and the
navigation Commands.
Router is a host service. Its Layers are Router.memory (tests and
TestHost), Router.static (server rendering) and, in
effect/ui/html, BrowserRouter.layer and BrowserRouter.layerHash.
Each provides the Router service and the navigation Commands, Push,
Replace, PatchSearch, Back, Forward, Load and Retry. A component
that navigates has them in its requirements, so a missing Router is a
compile error at mount.
Where the route lives
The root's Model holds the route. Its props carry the initial one: mount it
with Router.props(AppRoute), which reads { route } from the Router, or
map Router.currentRoute(AppRoute) for a root with other props.
Later changes arrive as a message from
Router.subscription, so every route change is in the log. The Router is
shaped like a SubscriptionRef: changes starts with the current
location, so a change made before the Subscription starts isn't lost. The
Subscription suppresses the first delivery when the root already holds it.
Pages are chosen with the union's exhaustive match and keyed by their
path, AppRoute.printPath(route). A new path mounts a fresh page, and a
change to the search alone updates the page in place:
SearchPage(h, { key: AppRoute.printPath(route), props: { route } }).
A page that should start over when a param changes adds the param to its
key.
View state in search params
A value such as a search box's text or a page number can live in the
search alone, with no copy in any Model. A page that uses its search takes
its whole route as props, typed by a one-case subset such as
AppRoute.subset(["Search"]), and reads h.props.route.search. A page
with no search can take picked fields, such as { id: route.params.id }.
The page writes the search with Router.patchSearch, and a query that
reads it can wait for typing to stop with its debounce option.
Example A root that follows the route
import { Effect, Schema } from "effect"import { Command, Component, Route, Router, UiSchema } from "effect/ui"import { TestHost } from "effect/ui/testing"
const AppRoute = Route.union({ Home: Route.make("/"), About: Route.make("/about"), NotFound: Route.make("/*")})const AppNavigation = Router.navigable(AppRoute)
const Message = UiSchema.TaggedEnum({ ChangedRoute: { route: AppRoute }, ClickedHome: {}})
const App = Component.define({ name: "App", props: Schema.Struct({ route: AppRoute }), model: Schema.Struct({ route: AppRoute }), message: Message}).make({ init: ($) => ({ route: $.props.route }), update: ($, message) => Message.match(message, { ChangedRoute: ({ route }) => ({ route }), // The new route comes back through the subscription: the push itself sends nothing. ClickedHome: () => $.run(AppNavigation.Home.push().pipe(Command.asNoop)) }), subscriptions: ({ model }) => [Router.subscription(AppRoute, model.route, (route) => Message.ChangedRoute({ route }))], view: (h, model) => h.el("p", model.route._tag)})
// The initial route comes from the Router.const mount = TestHost.mount(App, Router.props(AppRoute)).pipe( Effect.provide(Router.memory({ routes: AppRoute, url: AppRoute.About.href() })))Accessors
currentRoute
unstableReads the Router's current route as a value of the given union.
When to use
Use to initialize a routed root's props from its Router rather than stating the initial URL again at the mount site.
Gotchas
Dies if the given union cannot parse the current location. Pass the union used by the Router Layer, or a subset that includes the current route.
Signature
declare function currentRoute<U extends Routes>(routes: U): Effect<U["Type"], never, Router>The props of a root whose only prop is the route: { route }, read from
the Router when the root mounts.
When to use
Use as a routed root's props in BrowserHost.mount, TestHost.mount or
HtmlServer.renderToHtml, which run it once before init. The mount
then requires the Router. A root with other props maps
Router.currentRoute to them instead.
init still receives a plain route, so a Story or a test can start the
root on any page by passing { route } with no Router.
Gotchas
Dies if the given union cannot parse the current location, as
currentRoute does.
Signature
declare function props<U extends Routes>(routes: U): Effect<{ readonly route: U["Type"];}, never, Router>Example Mounting a routed root
import { Effect, Schema } from "effect"import { Component, Route, Router } from "effect/ui"import { TestHost } from "effect/ui/testing"
const AppRoute = Route.union({ Home: Route.make("/"), NotFound: Route.make("/*")})
const App = Component.define({ name: "App", props: Schema.Struct({ route: AppRoute }), model: AppRoute, message: Schema.Never}).make({ init: ($) => $.props.route, update: ($) => $.model, view: (h, route) => h.el("p", route._tag)})
// Requires the Router: the initial route comes from its URL.const mount = TestHost.mount(App, Router.props(AppRoute)).pipe( Effect.provide(Router.memory({ routes: AppRoute, url: AppRoute.Home.href() })))Commands
Goes back one history entry.
Signature
declare class Back extends Shape<"effect/ui/Router/Back", (args: {}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Back, never, Router>;}Goes forward one history entry.
Signature
declare class Forward extends Shape<"effect/ui/Router/Forward", (args: {}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Forward, never, Router>;}Loads an href with a full page load, such as an external URL.
Signature
declare class Load extends Shape<"effect/ui/Router/Load", (args: { readonly href: string;}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Load, never, Router>;}patchSearch
unstableWrites some of the current route's search params, keeping the rest.
When to use
Use to keep view state such as a search box's text, a filter or a page number in the URL, with no copy in the Model.
Details
route is the route the page holds, and patch is typed by its search
fields: undefined removes a param, or resets it to its default. When the
Command runs, the patch applies to the Router's current search; the held
route only names the path, so two patches issued in one round trip both
land. If the Router's path no longer matches the held route, the Command
does nothing and returns "stale".
It replaces the history entry by default; { history: "push" } pushes
one. Params the route doesn't declare, such as utm_source, are kept,
printed after the declared ones in their original order, and so is the
#hash. A patch that changes nothing doesn't navigate.
The navigation is quiet: Settled.quiet is true, so the browser Router
announces nothing and leaves focus alone. It leaves scroll alone too,
unless { scroll: true } asks it to scroll to the top. A push still runs
the Router.prefetch declarations. Router.blocked doesn't block it.
The component requires PatchSearch.
Gotchas
Key the page by printPath, not print: a page keyed by its search
remounts on every patch and loses its Model. If a block held when the patch
ran is gone when it settles, PatchSearchLostBlock is reported.
See
- replace to navigate to a whole route value instead
Signature
declare function patchSearch<U extends Routes, R extends { readonly _tag: string;}>(_routes: U, route: R, patch: NoInfer<SearchPatch<R>>, options?: { readonly history?: "push" | "replace"; readonly scroll?: boolean;}): Issued<"stale" | "navigated" | "blocked", PatchSearch, "stale" | "navigated" | "blocked", "Effect">Example A search box bound to the URL
import { Command, Route, Router } from "effect/ui"import { Schema } from "effect"
const AppRoute = Route.union({ Search: Route.make("/search", { search: { q: Schema.optional(Schema.String) } }), NotFound: Route.make("/*")})const SearchRoute = AppRoute.subset(["Search"])
const typed = (route: typeof SearchRoute.Type, text: string) => Router.patchSearch(AppRoute, route, { q: text || undefined }).pipe(Command.asNoop)PatchSearch
unstableThe Command behind patchSearch. Use patchSearch, which types the patch;
the class is what a Layer fake or a story's resolve step names.
Signature
declare class PatchSearch extends Shape<"effect/ui/Router/PatchSearch", (args: { readonly history: "push" | "replace"; readonly patch: Readonly<Record<string, unknown>>; readonly route: { readonly _tag: string; }; readonly scroll: boolean;}) => Effect<"stale" | "navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<PatchSearch, never, Router>;}Pushes a history entry for a route value of the given union.
Details
The route must be a complete value of routes, such as one built with
routes.make; pass the union given to the Router Layer or one of its
subsets. A route equal to the current one does nothing: unlike a link to
it, it sends no message. It returns "blocked" without navigating while a
Router.blocked Subscription holds a block. Map the outcome to a message
with Command.map, or end it with no message with Command.asNoop, which
also hides a "blocked" outcome. The component requires Push. For a
route whose tag is known, navigable is shorter.
Signature
declare function push<U extends Routes>(_routes: U, route: U["Type"]): Issued<"navigated" | "blocked", Push, "navigated" | "blocked", "Effect">The Command behind push. Use push, which types the route value; the
class is what a Layer fake or a story's resolve step names.
Signature
declare class Push extends Shape<"effect/ui/Router/Push", (args: { readonly route: { readonly _tag: string; };}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Push, never, Router>;}Replaces the current history entry with a route value of the given union.
Details
Accepts the same route values as push. Replacing the current route
removes undeclared search parameters without emitting a route change.
A replace that changes the route but keeps the same tag and pathname
settles without announcements or changes to focus or scroll.
Use patchSearch to update search parameters as the user types while
preserving undeclared parameters. The component requires Replace.
For a route whose tag is known, navigable is shorter.
Signature
declare function replace<U extends Routes>(_routes: U, route: U["Type"]): Issued<"navigated" | "blocked", Replace, "navigated" | "blocked", "Effect">The Command behind replace. Use replace, which types the route value;
the class is what a Layer fake or a story's resolve step names.
Signature
declare class Replace extends Shape<"effect/ui/Router/Replace", (args: { readonly route: { readonly _tag: string; };}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Replace, never, Router>;}Runs a navigation a block stopped, as reported to Router.blocked.
Details
It's blocked like any navigation, so release the block in the same update: the Router's Commands run after the update's Subscriptions change. Another block still held stops it again and hears the attempt.
Signature
declare class Retry extends Shape<"effect/ui/Router/Retry", (args: { readonly attempt: { readonly _tag: "Navigate"; readonly href: string; readonly replace: boolean; } | { readonly _tag: "Load"; readonly href: string; } | { readonly _tag: "Go"; readonly index: number; };}) => Effect<"navigated" | "blocked", never, FrameworkService>, this> { constructor(_: never); static readonly layer: Layer<Retry, never, Router>;}Constructors
Builds a Router Layer on a History, for hosts that bring their own.
Details
The Router resolves every href through routes: redirects and a trailing
slash are replaced with the canonical URL, and an href the routes don't
parse is a full page load. The Layer dies if the start URL doesn't resolve;
a "/*" route covers URLs under the route base. The Router implements
blocking, history restore and the settle timing; a host adds scroll,
announcements and focus in onSettled.
History restore: unless restore is false, before leaving an entry,
the Router saves the encoded state of every mounted instance by path: its
Model and query results. It can't save only the page's
subtree, because which instances the navigation unmounts is only known
after it. On back and forward, an instance created for the entry adopts its
saved state, so only the re-keyed subtree is restored, and an instance that
stayed mounted keeps its own. As with hydration, init is replayed for
its Commands, but a restored instance skips those marked with
Command.skipOnRestore. A component's restore option in
Component.define keeps it out of the snapshot, or saves another Model in
place of its own. An owner of shared state whose shares has collects
also saves the message its readers' reports last sent, and a restored owner
compares their reports with it.
A restored query result seeds the cache when its entry is cold, as after a
reload: the entry is stored stale, so the first frame shows the data with
waiting: true and one refetch runs. If the refetch fails, the data stays
as the Failure's previous Success. A warm entry is used as it is. A result
taken under an optimistic patch is never a seed: it is dropped from the
restored state and starts from loading.
Saved state is decoded with the component's current Schemas, as one value.
State that doesn't decode, such as state an older build wrote before its
Model or state format changed, is dropped whole: the instance runs init
as if nothing was saved, its saved Model is lost too, and its queries
fetch afresh.
The snapshot is kept in memory per entry. When a push leaves an entry, it's
also written into that entry's state, so it survives a reload. When that
write throws, the entry is written with its index only and
SnapshotWriteFailed is reported. When back or forward leaves an entry,
the host has already moved to the other entry, so the snapshot stays in
memory only. After a reload, each root's first mount restores its part of
the snapshot written when a push last left the entry, or starts fresh. Once
that mount settles, the rest of its part is dropped, so a later remount
starts from init. An instance that hydrates server-rendered HTML starts
from the server's state instead.
The snapshot holds server-rendered state only of components the client has
built, since only a built component's restore option is known. One built
but still waiting for its Layer or for its state to decode has the server's
state saved through its restore option. One not built yet, such as a
component below a waiting one, has none of its server state saved, even
after hydration has settled: after Back or forward it starts from init.
A child bound with children is built with its parent, placed or not.
A state whose Schema encodes asynchronously, as Schema.File does, joins
the snapshot in memory once it is encoded, after the push has written the
entry. Back and forward restore it, and after a reload it starts fresh,
with a warning logged the first time. A state that doesn't encode is left
out, with a warning logged once per component. An instance whose state holds
a Schema.Redacted anywhere is left out of the snapshot too, with no
warning. A state whose Schema decodes asynchronously shows nothing until it
is decoded, then starts from it.
With throttle, a replace that stays on the page is written at once, and
then at most once per interval, with the latest URL. A pending one is
written before a push, a change to the hash, back, forward, a full page
load, the host's flushOn and the Layer's Scope closing. It is dropped
when the host moves to another entry by itself, as with the back button,
since that entry is no longer current. A replace the history throws on is
reported as HistoryWriteFailed, whether it was written at once or later.
Every navigation the Router makes closes the cache's fetch-free window after hydration, if adoption hasn't closed it yet.
Signature
declare function make(options: Options): Layer<Services>memoryHistory
unstableA history kept in memory, starting at url.
Details
go reports the entry it lands on synchronously, and does nothing past
either end. load records the href in loaded instead of leaving the page.
Signature
declare function memoryHistory(url: string): History & { readonly entries: () => readonly Array<string>; readonly index: () => number; readonly loaded: () => readonly Array<string>;}Layers
A Router on an in-memory history, for tests and TestHost.
Details
It needs no DOM. Pass your own memoryHistory as history to inspect the
entries, or to move through them as the back button would. A full page
load is recorded by the history instead of leaving the page.
Signature
declare function memory(options: { readonly history?: History; readonly restore?: boolean; readonly routes: AnyUnion; readonly url?: string;}): Layer<Services>Models
How a location was reached: the first load, a push, a replace, or a move
through history (pop), such as the back button.
Signature
type Action = "initial" | "push" | "replace" | "pop"A navigation a block stopped, which Router.Retry runs: an href to
navigate to (a push, replace, link or GET form), a full page load, or a
move through history to the entry at index.
Signature
type Attempt = typeof Attempt.TypeA history a Router runs on: Router.memory keeps one in memory, and the
browser Router wraps window.history.
Details
go moves through the entries and, synchronously or later, reports the
entry it landed on to the listener given to listen, as the browser's
popstate does. Pass true as the callback's third argument when the
host already animated the traversal to suppress a second view transition.
state is opaque to the history; the Router stores the entry's index and
its history-restore snapshot in it.
Signature
interface History { readonly current: () => { readonly state: unknown; readonly url: string; }; readonly go: (delta: number) => void; readonly listen: (popped: (url: string, state: unknown, animated?: boolean) => void) => () => void; readonly load: (href: string) => void; readonly push: (url: string, state: unknown) => void; readonly replace: (url: string, state: unknown) => void;}Where the Router is: the route, its printed URL (path and search, under the
base) and its #hash, and the navigation that got there.
Signature
interface Location { readonly action: Action; readonly hash: string; readonly index: number; readonly route: { readonly _tag: string; }; readonly seq: number; readonly url: string;}The options of make.
Signature
interface Options { readonly history: History; readonly onBlocked?: (blocked: boolean) => void; readonly onHash?: (hash: string, action: "pop" | "push", index: number) => void; readonly onLeave?: (index: number) => void; readonly onSettled?: (settled: Settled) => void; readonly restore?: boolean; readonly routes: AnyUnion; readonly throttle?: { readonly flushOn?: (flush: () => void) => () => void; readonly interval: Input; };}What a navigation Command returns: "blocked" when a block was held,
else "navigated".
Signature
type Outcome = typeof Outcome.TypeA page a Router.prefetch handler names: a component and its props.
R is the services of the component's own queries.
Signature
interface Page<out R = never> { readonly "~effect/ui/Router/Page": { readonly _R: Covariant<R>; }; readonly component: Any | Any; readonly props: unknown;}What patchSearch returns: "stale" when the Router's path no longer
matches the held route, "blocked" from Router.static only, else
"navigated".
Signature
type PatchOutcome = typeof PatchOutcome.TypeThe map Router.prefetch takes: a handler per route tag, given the route
value as match gives it, returning the route's pages.
Signature
type PrefetchMap<U extends Routes> = { [K in U["Type"]["_tag"]]: (route: Extract<U["Type"], { readonly _tag: K;}>) => ReadonlyArray<Page<any>> }The Router service.
Details
changes starts with the current location, then emits each route change.
A change to the #hash alone within the same route isn't a route change.
navigate takes an href: one the routes parse is pushed (or replaced), and
anything else is a full page load.
A target with the same tag and printed route doesn't start a navigation or
advance seq. A push preserves undeclared search parameters and writes a
new entry only when the hash changes. A replace updates the current entry
and location().url: replace(route) uses the printed route, removing
undeclared search parameters; navigate(href, { replace: true }) uses the
canonicalized href.
Following an href to the current route emits the current location again on
changes. Typed push and replace calls emit nothing unless a push
writes a new entry for a hash change. Back and forward to another entry of
the same route also emit the current location with that entry's index.
settled replays the latest Settled, if any, then emits new settles
after the host handles scroll, announcements and focus. See Settled
for initial-load and superseded-navigation behavior.
Signature
interface Router { readonly back: Effect<"navigated" | "blocked">; readonly block: (key: string, onAttempt?: (attempt: { readonly _tag: "Navigate"; readonly href: string; readonly replace: boolean; } | { readonly _tag: "Load"; readonly href: string; } | { readonly _tag: "Go"; readonly index: number; }) => void) => Effect<void, never, Scope>; readonly blocked: () => boolean; readonly changes: Stream<Location>; readonly forward: Effect<"navigated" | "blocked">; readonly intent: (href: string) => Effect<void>; readonly load: (href: string) => Effect<"navigated" | "blocked">; readonly location: () => Location; readonly navigate: (href: string, options?: { readonly replace?: boolean; }) => Effect<"navigated" | "blocked">; readonly patchSearch: (route: { readonly _tag: string; }, patch: Readonly<Record<string, unknown>>, options?: { readonly history?: "push" | "replace"; readonly scroll?: boolean; }) => Effect<"stale" | "navigated" | "blocked">; readonly push: (route: { readonly _tag: string; }) => Effect<"navigated" | "blocked">; readonly replace: (route: { readonly _tag: string; }) => Effect<"navigated" | "blocked">; readonly reporting: () => boolean; readonly retry: (attempt: { readonly _tag: "Navigate"; readonly href: string; readonly replace: boolean; } | { readonly _tag: "Load"; readonly href: string; } | { readonly _tag: "Go"; readonly index: number; }) => Effect<"navigated" | "blocked">; readonly routes: AnyUnion; readonly settled: Stream<Settled>;}A route union, with its route values' type.
Signature
type Routes = Route.AnyUnion & { readonly Type: { readonly _tag: string; };}Everything a Router Layer provides.
Signature
type Services = Router | Push | Replace | PatchSearch | Back | Forward | Load | RetryA page load or navigation whose DOM has committed, before browser paint. Queries may still be loading.
Details
A navigation settles when the first attached root flushes after receiving
it, with no provided Layer build begun since still pending, no child
waiting for hydrated or restored state to decode, and no Router.unsettled
held.
The initial location settles once that root flushes with no pending Layer
builds, state decoding or Router.unsettled. It has location.seq: 0,
from: "", quiet: true and scroll: false. Use it to end a page-load
span.
If a navigation starts first, the initial location never settles.
Superseded navigations never settle. To avoid leaving a span open, end
the span for sequence n at the first settle with location.seq >= n,
or at the next value from changes.
A quiet navigation stays on the page; the host neither announces it nor moves focus. These navigations are quiet:
- a
patchSearch, replace or push; - a replace to the same page: the same tag and pathname;
- back and forward between entries of the same page.
A push to the same page, such as a ?page=2 link or a GET form, is loud.
A quiet navigation that supersedes a loud one settles loud, under its
own location.seq.
Signature
interface Settled { readonly container: unknown; readonly from: string; readonly index: number; readonly location: Location; readonly quiet: boolean; readonly scroll: boolean; readonly title: string | undefined;}Example Logging settled page loads and navigations
import { Effect, Stream } from "effect"import { Router } from "effect/ui"
const logSettled = Effect.gen(function*() { const router = yield* Router.Router yield* Stream.runForEach(router.settled, (settled) => Effect.log( settled.location.seq === 0 ? "page load" : "navigation", settled.location.url ))})Other
Problems
HistoryWriteFailed
unstableReports that the history threw on a replace, as a browser does past its rate limit on history calls. The Router's location changed anyway, so the address bar shows an older URL until the next write.
Signature
declare class HistoryWriteFailed extends Readonly<{ readonly error: unknown; readonly message: string; readonly url: string;}> & { readonly _tag: "HistoryWriteFailed";} & Pipeable { constructor(args: { readonly error: unknown; readonly message: string; readonly url: string; });}PatchSearchLostBlock
unstableReports that a block held when patchSearch ran was gone when the
navigation settled, as when a page keyed by its search remounts on the
patch and loses its Model. It can also fire when the Model releases the
block in response to the new route.
Signature
declare class PatchSearchLostBlock extends Readonly<{ readonly keys: readonly Array<string>; readonly message: string;}> & { readonly _tag: "PatchSearchLostBlock";} & Pipeable { constructor(args: { readonly keys: readonly Array<string>; readonly message: string; });}PrefetchEntryNotWatched
unstableAfter a push settled, the page instances created since the push never
watched an entry the Router.prefetch declaration fetched for them.
Signature
declare class PrefetchEntryNotWatched extends Readonly<{ readonly logKey: string; readonly message: string; readonly page: string; readonly path: string; readonly query: string;}> & { readonly _tag: "PrefetchEntryNotWatched";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly page: string; readonly path: string; readonly query: string; });}PrefetchPageNotMounted
unstableAfter a push settled, a page its Router.prefetch declaration named has
no mounted instance.
Signature
declare class PrefetchPageNotMounted extends Readonly<{ readonly message: string; readonly page: string; readonly path: string;}> & { readonly _tag: "PrefetchPageNotMounted";} & Pipeable { constructor(args: { readonly message: string; readonly page: string; readonly path: string; });}PrefetchQueryNotProvided
unstableA query in a Router.prefetch walk is missing from the declarer's context,
with no Component.provide between the page and the component that needs
it. That read was skipped.
Signature
declare class PrefetchQueryNotProvided extends Readonly<{ readonly message: string; readonly page: string; readonly path: string; readonly query: string;}> & { readonly _tag: "PrefetchQueryNotProvided";} & Pipeable { constructor(args: { readonly message: string; readonly page: string; readonly path: string; readonly query: string; });}PrefetchThrew
unstableA component or view threw while a Router.prefetch declaration walked a
page. That page's walk stopped. The declarer is unaffected.
Signature
declare class PrefetchThrew extends Readonly<{ readonly error: unknown; readonly message: string; readonly page: string; readonly path: string;}> & { readonly _tag: "PrefetchThrew";} & Pipeable { constructor(args: { readonly error: unknown; readonly message: string; readonly page: string; readonly path: string; });}RouteMismatch
unstableReports that an initial held route differs from the Router location.
Signature
declare class RouteMismatch extends Readonly<{ readonly have: string; readonly message: string; readonly router: string;}> & { readonly _tag: "RouteMismatch";} & Pipeable { constructor(args: { readonly have: string; readonly message: string; readonly router: string; });}SnapshotWriteFailed
unstableWriting the instances' saved state (each Model, plus its query results) into
history.state threw, as a browser does when the state is too large. The
history entry was written with its index only, so the saved state survives
in memory and not across a reload.
Signature
declare class SnapshotWriteFailed extends Readonly<{ readonly error: unknown; readonly message: string;}> & { readonly _tag: "SnapshotWriteFailed";} & Pipeable { constructor(args: { readonly error: unknown; readonly message: string; });}Schemas
Schema for Attempt.
Signature
declare const Attempt: Union<readonly [TaggedStruct<"Navigate", { readonly href: String; readonly replace: Boolean;}>, TaggedStruct<"Load", { readonly href: String;}>, TaggedStruct<"Go", { readonly index: Int;}>]>Schema for Outcome.
Signature
declare const Outcome: Literals<readonly ["navigated", "blocked"]>PatchOutcome
unstableSchema for PatchOutcome.
Signature
declare const PatchOutcome: Literals<readonly ["navigated", "blocked", "stale"]>Services
Subscriptions
Blocks navigation under a key while the Subscription runs, such as while a form has unsaved changes.
Details
While any block is held, Push, Replace, Back, Forward and Load
return "blocked" and links aren't followed. Back and forward in the
browser can't be blocked, only reverted: the Router moves back to the
entry it was on, announces nothing and leaves focus alone.
Writes within the page aren't blocked: PatchSearch, and back and forward
between entries of the same page that differ in their search only. So a
search box on a page with unsaved changes still types, and the user can
go back after ?page=2. The block is
held while subscriptions returns it, so the Model says when, and it's
released when the instance unmounts.
With f, each navigation the block stops is sent as f(attempt), so the
app can ask the user and, if they confirm, release the block and run
Router.Retry in one update. Only the newest held block with f hears an
attempt. While one is held, BrowserRouter also stops http(s) links and
GET forms the routes don't parse, other sites' included. f is captured
when the block starts.
In the browser, BrowserRouter also asks the browser to warn before the
page unloads, unless its warnOnUnload option is false. This covers
reloads, closing the tab and links the routes don't parse. The warning
saves nothing. The browser chooses its text and requires prior user
interaction to show it. The warning may not appear, especially on mobile
when a tab is discarded in the background. Save drafts as the user types
or on visibilitychange rather than relying on the warning.
The Subscription is named effect/ui/Router/blocked and key is its
dep, so Router.blocked("form") has the Subscription key
effect/ui/Router/blocked:"form".
Signature
declare function blocked<Msg = never>(key: string, f?: (attempt: { readonly _tag: "Navigate"; readonly href: string; readonly replace: boolean;} | { readonly _tag: "Load"; readonly href: string;} | { readonly _tag: "Go"; readonly index: number;}) => Msg): Subscription<Msg, Router>Example Blocking navigation while a form is dirty
import { Router } from "effect/ui"
const subscriptions = ({ model }: { readonly model: { readonly dirty: boolean } }) => model.dirty ? [Router.blocked("form")] : []Example Asking before leaving
import { Schema } from "effect"import { Command, Component, Router, UiSchema } from "effect/ui"
const Message = UiSchema.TaggedEnum({ Leaving: { attempt: Router.Attempt }, Confirmed: {}})
const Editor = Component.define({ name: "Editor", model: Schema.Struct({ dirty: Schema.Boolean, leaving: Schema.optional(Router.Attempt) }), message: Message}).make({ init: () => ({ dirty: true }), update: ($, message) => Message.match(message, { Leaving: ({ attempt }) => ({ ...$.model, leaving: attempt }), // Releasing the block and retrying in one update navigates. Confirmed: () => $.model.leaving === undefined ? $.model : $.set({ dirty: false }).run( Router.Retry.make({ attempt: $.model.leaving }).pipe(Command.asNoop) ) }), subscriptions: ({ model }) => [ model.dirty && Router.blocked("editor", (attempt) => Message.Leaving({ attempt })) ], view: (h) => h.el("button").on("click", Message.Confirmed()).children("Leave")})Returns a page declaration for a Router.prefetch handler from an eager
or lazy component and its props.
Details
Omit props when the component takes none. The page's queries become
requirements of the declaring component: provide their Layers at that
component or above it, even if the page provides them itself. Otherwise,
mount fails to typecheck. This also applies to lazy pages. To keep query
Layers in the page's chunk, preload it with preload() and return []
from the prefetch handler.
Gotchas
Accepts a component built with Component.define, with or without
Component.provide, and a Component.lazy of one. Rejects features and
components whose types erase their queries, including Component.Mountable
values and lazy components that load them.
Signature
declare function page<C extends Any | Any>(component: C & PageInput<C>, ...props: {} extends PageProps<C> ? [props?: PageProps<C>] : [props: PageProps<C>]): Page<PageRequirements<C>>Declares the queries of each route's pages, so they are fetched before the pages mount: on link intent and on navigation.
Details
Return it from a component's subscriptions. The map is exhaustive over
the routes it is given: pass AppRoute.subset(...) to declare a section's
routes only, and return [] for a route with nothing to fetch. For each
page the runtime runs init with the page's props, discarding its
Commands, prefetches what its queries would watch first, and walks its
initial view into its component children. A query that waits on loaded
data is skipped, and so is a feature child.
The declaration runs in the declaring instance's context, so the queries must
be provided at the declarer or above it. A query below the page that the
declarer can't see is skipped, and reported as PrefetchQueryNotProvided
unless a Component.provide sits between the page and the component that
needs it. A throw from init, a query or view during the walk stops
that page's walk and is reported as PrefetchThrew.
For an unloaded lazy page or child, the runtime loads its module, then walks it with the declared props. It skips the walk if the declaration was released or the declarer closed or failed. Repeated requests for the same target and props share a pending walk. Deferred walks are excluded from the checks below because navigation can settle before the module loads.
It runs on intent(href), which BrowserRouter calls on hover, focus
and touch, at most once per route every 30 seconds per declarer. A push, a
link click and a replace that changes the pathname run it as well, before
the route changes, and never wait for it. Back, forward, a reload and the
first mount run nothing. Once a push settles, each declared page with no
mounted instance is reported as PrefetchPageNotMounted, and each entry
an instance created since the push never watched as
PrefetchEntryNotWatched.
With staleTime: 0, the page renders prefetched data immediately but
refetches on mount. With staleTime between 0 and 30 seconds, the intent
guard can suppress a second hover that would refresh stale data, leaving
the page to render stale data and refetch on mount.
One Router.prefetch per instance: a second one throws. Nothing runs on
the server.
Signature
declare function prefetch<U extends Routes, M extends PrefetchMap<U>>(routes: U, map: M): Subscription<never, Router | PrefetchRequirements<M>>Example Prefetching a detail page
import { Schema } from "effect"import { Query } from "effect/ui"import { Component, Route, Router } from "effect/ui"
const AppRoute = Route.union({ Home: Route.make("/"), Person: Route.make("/people/:id", { params: { id: Schema.Number } })})
class GetPerson extends Query.Service<GetPerson>()("GetPerson", { args: { id: Schema.Number }, success: Schema.String, error: Schema.Never, staleTime: "1 minute"}) {}
const Person = Component.define({ name: "Person", props: Schema.Struct({ id: Schema.Number }), model: Schema.Struct({}), message: Schema.Never, queries: { person: { query: GetPerson, args: ({ props }) => ({ id: props.id }) } }}).make({ init: () => ({}), update: ($) => $.model, view: (h) => h.el("p", "Person")})
const subscriptions = () => [ Router.prefetch(AppRoute, { Home: () => [], Person: ({ params }) => [Router.page(Person, { id: params.id })] })]subscription
unstableFeeds route changes into the update of a root or a component whose Model
follows the route.
Details
Pass the route held in the Model. The first location is suppressed when its
tag and printed URL match that route. Otherwise it is delivered, and a
RouteMismatch is reported if the Router has not navigated (sequence 0).
Hydrated hash roots skip that report, and so do roots hydrated from a
static: true render whose route differs from the Router's in its search
only, as a page prerendered at /search and opened at /search?q=x, or
where both are the catch-all "/*" route, as a 404 prerendered at /404
and served at /some/old-link.
Later locations are always delivered, and the held route is delivered
again when a link to it is followed.
f also gets the location, whose index is the history entry's, as a
screen stack needs.
The key stays stable as the held route changes. A subset only sees its own
routes. On the server the root is checked once without running its Streams,
regardless of the navigation sequence.
A navigation Command such as Router.push runs in the flush its update
caused, and this Subscription delivers the new route from inside it. The
root and its pages render the new route in that flush, so a field whose
value is read from the search keeps what the user typed and where the caret
is. A navigation issued from init while the root mounts runs after it has
mounted.
To reset a draft on navigation, a component below the root supplies the
route from its props as the held route. Nothing is delivered at mount while
those props hold the Router's route. When the root and that component are
the only subscribers, navigation reaches the component's update before
its first view of the new route.
Use this helper rather than Router.changes directly: the browser Router
times scroll, announcements and focus from the flush in which the root
received the change.
Gotchas
Build the message from the route f is given, not from $.props in
update. Subscribers hear a navigation in the order they started, so a
component that mounted with the root hears it before the root does, while
its props still hold the previous route.
Only the subscriber receiving a navigation waits for its update before
rendering. Delivery can render other subscribers through ancestors that
already heard the navigation. For example: two forms mounted by an earlier
navigation hear the next one after the root. The second form can run its
view with the new route and its old Model, even in a separate wrapper.
Its own update resets the draft before the flush commits.
Signature
declare function subscription<U extends Routes, Msg>(routes: U, held: U["Type"], f: (route: U["Type"], location: Location) => Msg): Subscription<Msg, Router>Example A draft that follows the URL
import { Route, Router, UiSchema } from "effect/ui"import { Html } from "effect/ui/html"import { Schema } from "effect"
const SearchRoute = Route.union({ Search: Route.make("/search", { search: { q: Schema.optional(Schema.String) } })})
const Message = UiSchema.TaggedEnum({ Navigated: { q: Schema.String }, Typed: { text: Schema.String }})
const SearchForm = Html.component({ name: "SearchForm", props: Schema.Struct({ route: SearchRoute }), model: Schema.Struct({ draft: Schema.String }), message: Message}).make({ init: ($) => ({ draft: $.props.route.search.q ?? "" }), update: (_, message) => Message.match(message, { Navigated: ({ q }) => ({ draft: q }), Typed: ({ text }) => ({ draft: text }) }), subscriptions: ({ props }) => [ Router.subscription(SearchRoute, props.route, (route) => Message.Navigated({ q: route.search.q ?? "" })) ], view: (h, model) => h.input.value(model.draft).on("input", ({ value }) => Message.Typed({ text: value }))})Defers navigation settlement while this subscription is active.
When to use
Use when a root loads the destination's data while keeping the current
page on screen. Return it from subscriptions while loading.
Details
While any component holds this subscription, the Router defers initial
load and navigation settlement, including scrolling, focus, announcements
and Router.settled. It retains Back/Forward restore state until settlement.
The URL, history and changes update as usual.
Releasing the last hold allows settlement after the destination renders,
once pending Layer builds and state decoding finish. Release it in the
update that commits the destination to settle in that flush if those
conditions are met, including inside viewTransition.
Only the latest navigation can settle; superseded navigations never do.
Gotchas
Release the hold on loading failure too, or navigation will never settle.
Signature
declare const unsettled: Subscription.Subscription<never, Router>Example Showing the destination once its data is loaded
import { Component, Route, Router, UiSchema } from "effect/ui"import { Schema } from "effect"
const AppRoute = Route.union({ Home: Route.make("/"), Person: Route.make("/people/:id", { params: { id: Schema.Number } })})
const Message = UiSchema.TaggedEnum({ Requested: { route: AppRoute }, // Sent by the Command that prefetches the requested page's queries. Loaded: { route: AppRoute }})
const App = Component.define({ name: "App", props: Schema.Struct({ route: AppRoute }), model: Schema.Struct({ route: AppRoute, next: Schema.NullOr(AppRoute) }), message: Message}).make({ init: ($) => ({ route: $.props.route, next: null }), update: ($, message) => Message.match(message, { Requested: ({ route }) => $.evolve({ next: () => route }), // Ignore completions for a different requested route. Loaded: ({ route }) => $.model.next === null || AppRoute.print($.model.next) !== AppRoute.print(route) ? $.model : $.set({ route, next: null }).viewTransition() }), subscriptions: ({ model }) => [ Router.subscription(AppRoute, model.next ?? model.route, (route) => Message.Requested({ route })), model.next !== null && Router.unsettled ], view: (h, model) => h.el("p", model.route._tag)})Utility Types
The reads a component's own queries name: what Router.page adds to the
declarer's requirements.
Signature
type PageRequirements<C> = C extends unknown ? Component.QueryServices<Component.Queries<C>> : neverThe queries every page of a Router.prefetch map names.
Signature
type PrefetchRequirements<M> = { [K in keyof M]: M[K] extends (route: any) => ReadonlyArray<infer P> ? PageRequirement<P> : never }[keyof M]The patch patchSearch takes for a route value: any of its search fields,
where undefined removes the param, or resets it to its default.
Signature
type SearchPatch<R> = [R] extends [{ readonly search: infer Q;}] ? { [K in keyof Q]: Q[K] } : never