Mirror / Mirrored state
How a mirror works without creating a second store
Diagram source
flowchart LR
subgraph app["application"]
direction TB
model["Model — the only truth"]
slice["slice: a writable projection<br/>encoded with defaults elided"]
model --> slice
end
subgraph stores["stores"]
direction TB
url["URL<br/>?filter=active&page=2"]
kv["KeyValueStore<br/>one JSON document per key"]
end
slice -- "entry writes what changed" --> url
slice -- "entry writes what changed" --> kv
url -. "urlChanged(model, url) on navigation, reduce(model, url) on load" .-> model
kv -. "reduce(model, MirrorRestored) from restore" .-> modelStart by declaring one mirror for query parameters and one for browser storage over your application's Model (assuming your app defines Model, Message, initial, update, and userId):
const Filters = Mirror.url(App, {
fields: [App.model.filter, App.model.page, App.model.q],
keys: { q: { history: 'replace' } },
})
const Prefs = Mirror.kv(App, {
key: 'todo/prefs',
scope: userId,
fields: [App.model.sidebar, App.model.draft],
})When your app updates filter to 'active' and q to 'milk' while page stays at its initial 1, the address bar becomes ?filter=active&q=milk (omitting page because it matches the default, and replacing the history entry as you type q). Typing a draft writes {"sidebar":"open","draft":"Buy oat milk"} to KeyValueStore under the scoped key todo/prefs:<userId>.
To wire both mirrors into your update and subscriptions, fold Mirror.reduces(message) for storage restoration and UrlChanged for navigation, then spread both subscription records:
function handleMirror(
model: Model,
message: Message,
): Update.Return<Model, Message, KeyValueStore.KeyValueStore> {
if (Mirror.reduces(message)) return { model: Prefs.reduce(model, message) }
return Match.value(message).pipe(
Match.tag('UrlChanged', ({ url }) => ({ model: Filters.urlChanged(model, url) })),
Match.orElse(() => ({ model })),
)
}
const subscriptions = Subscription.make<
Model,
Message,
KeyValueStore.KeyValueStore
>()(() => ({
...Filters.subscriptions,
...Prefs.subscriptions,
}))Under Sync.mount, pass init: (model, url) => Filters.reduce(model, url) and onUrlChange in the url option, and include both entries in subscriptions and your store layer in resources. Or let Page.assemble derive update, subscriptions, and url from Filters.wiring('UrlChanged') and Prefs.wiring().