Primitives / Media
Start with one: a media query
import { Schema } from 'effect'
import type { HtmlBuilder } from 'foldkit/html'
import { Bundle } from 'foldkit-bundle'
import { MediaQuery } from 'foldkit-primitives/media'
const Page = Bundle.compose({ theme: Schema.String }).pipe(
Bundle.withChild('dark', MediaQuery, { args: { query: '(prefers-color-scheme: dark)' } }),
)
type Model = typeof Page.Model.Type
type Message = typeof Page.Message.Type
const { placements } = Page
const config = placements.complete({
init: () => placements.initial({ theme: 'light' }),
update: placements.update(model => ({ model })),
view: (model: Model, h: HtmlBuilder<Message>) =>
h.div([], [model.dark.matches ? 'Dark mode' : 'Light mode']),
subscriptions: placements.subscriptions(),
})dark starts as the window answers the query when init runs
(matchMedia(query).matches), so the first frame is drawn for the screen it is
on; where there is no window or no matchMedia (a server, a minimal DOM) it
starts at { matches: false }. args.initial says the first value instead: for
a server that knows the device from a request hint, or a test. When the runtime
subscribes, after the first frame, the stream emits the current answer and then
every change, which corrects a seed that was wrong. A page resumed by
foldkit-ssr runs no init: it keeps the value the server drew, so its first
frame matches the markup, and the stream's first report corrects it. A preset places with no args:
import { PrefersDark } from 'foldkit-primitives/media'
const Themed = Bundle.compose({ theme: Schema.String }).pipe(Bundle.withChild('dark', PrefersDark))Two placements of one query open two matchMedia listeners. Share the field
instead.