Shipping less
Rearrange the room: its program loads when you ask
The room's pieces stay put until you press Rearrange. Only then does the page fetch the room's own program, with a Handle of its own, and the card says how long it took to arrive.
Reduced motion: Nothing changes: once drag has arrived, a piece follows your pointer, and nothing moves by itself.
Why
Most visitors look at a room plan and never move a thing, so the code that drags is weight they'd pay for nothing. This page gets domAnimation (hover, press, focus and in-view) from the shop's Wardic instance, createWardic(domAnimation), and nothing else. This room's pieces sit in a LazyWardic whose features is a function, () => import("~/lib/drag-feature.ts").then((m) => m.drag), and a lazy Feature loads as its section renders. The section renders when you press Rearrange, so that's when the page fetches drag. Until then the pieces are plain markup.
The cost is the wait. Switch on "Slow connection" and the import is held back 1.5 s: drag a piece meanwhile and nothing happens, and once drag arrives, the drag you tried isn't replayed. Props whose Feature hasn't arrived do nothing; values still animate at once. Replay the demo and drag arrives at once: the browser keeps a module it has loaded, as it would after a page that drags, such as Arrange a room.
A press is one trigger of several. Load on view, rendering the section as it scrolls in, for something below the fold that most visitors reach. Load after the first paint, rendering it once the page has mounted, for something nearly everyone uses that needn't hold up the first frame. Load on intent, as here, for something few use. And a page that uses a Feature from the start brings it with its route: every page in this shop that drags or lays out imports a Wardic instance of its own, createWardic([domAnimation, drag]), so the Feature is in the route's own chunk, there when the page is. This room uses a section instead: its load runs again at each press, so the card can time it and hold it back.
Gains
- A smaller first load: the room's program and its Handle, under 1 KB gzipped here, are fetched on the press.
- The cost only on intent: a visitor who never rearranges never fetches them.
- The server's render is unchanged: the room is there, in place, before any script runs.
Costs
- Until the program arrives, the pieces aren't handles, and nothing is replayed: a drag begun mid-load is lost.
- One more request, made just as the visitor wants to drag.
- A second Handle on the page, with Features and services of its own; and
drag's code is the shop's already, so the bytes saved are the program's alone.
The code
On Foldkit the room is a Foldkit program of its own (Runtime.makeElement), with its own Handle naming drag alone, in a module the page imports when you press Rearrange: a Mount on the plan embeds it (Runtime.embed) and disposes it when the plan goes. The shop's one Handle has drag already, since its other rooms drag on it, so what the press fetches is the room's program, and the card times that; "Slow connection" holds the import back.
import * as Effect from "effect/Effect"
import * as Schema from "effect/Schema"
import type { Html, HtmlBuilder } from "foldkit/html"
import { defineMessageUnion } from "foldkit/message"
import * as Mount from "foldkit/mount"
import { defineView } from "foldkit/submodel"
import { wardic } from "~/lib/wardic.ts"
import { definePage, type PageEnv } from "~/page.ts"
import { PIECES, placeOf } from "./pieces.ts"
/** How long "Slow connection" holds the import back: long enough to try a drag before the room arrives. */
const HOLD_MS = 1500
const Data = Schema.Struct({})
/** Whether Rearrange was pressed, whether the import is held back, and how long the room took to arrive from the press. */
const Model = Schema.Struct({ wanted: Schema.Boolean, slow: Schema.Boolean, arrivedIn: Schema.NullOr(Schema.Number) })
type Model = typeof Model.Type
const Message = defineMessageUnion({ Rearrange: {}, SetSlow: { on: Schema.Boolean }, Arrived: { ms: Schema.Number } })
type Message = typeof Message.Type
/**
* The host's Mount, on the press: it imports the room's program (`room.ts`), held back on a slow
* connection, embeds it in the host (`Runtime.embed`) and says how long that took. The program is
* disposed when the host goes: a Replay, or another page.
*/
const Room = Mount.define("RearrangeRoom", {
args: { slow: Schema.Boolean },
messages: [Message.Arrived],
execute: ({ element, slow }) =>
Effect.gen(function* () {
const pressedAt = performance.now()
// A Mount's element is an Element; the host is a div, which a Foldkit program's container must
// be, so anything else is a defect of the page's own.
if (!(element instanceof HTMLElement)) return yield* Effect.die(new Error("rearrange: the room's host isn't an HTMLElement"))
if (slow) yield* Effect.sleep(HOLD_MS)
const { mount } = yield* Effect.promise(() => import("./room.ts"))
yield* Effect.acquireRelease(
Effect.sync(() => mount(element)),
(handle) => Effect.promise(() => handle.disposeAsync()),
)
return Message.Arrived({ ms: Math.round(performance.now() - pressedAt) })
}),
})
type State = "still" | "loading" | "arrived"
/** The plan's state, which the stylesheet reads: the pieces aren't handles until the room has arrived. */
const stateOf = (model: Model): State => {
if (!model.wanted) return "still"
if (model.arrivedIn === null) return "loading"
return "arrived"
}
const status = (h: HtmlBuilder<Message>, state: State, arrivedIn: number | null): ReadonlyArray<Html | string> => {
if (state === "still") return ["The room's program isn't loaded: the pieces stay put."]
if (state === "loading") return ["Loading the room… a drag now does nothing."]
return [`The room arrived in ${String(arrivedIn)} ms, `, h.code([], ["drag"]), " on a Handle of its own."]
}
const view = defineView<Model, Message, PageEnv>((model, _env, h) => {
const w = wardic.html(h)
const state = stateOf(model)
return h.div([h.Class("room-demo")], [
h.div([h.Class("lazy-bar")], [
w.button([h.Class("button accent rearrange"), h.Disabled(model.wanted), w.WhileHover({ y: -1 }), w.WhileTap({ scale: 0.97 }), h.OnClick(Message.Rearrange())], ["Rearrange"]),
h.label([h.Class("switch")], [h.input([h.Type("checkbox"), h.Checked(model.slow), h.Disabled(model.wanted), h.OnClick(Message.SetSlow({ on: !model.slow }))]), h.span([], ["Slow connection"])]),
h.output([h.Class("lazy-status"), h.AriaLive("polite")], status(h, state, model.arrivedIn)),
]),
h.div([h.Class("room-frame")], [
h.div([h.Class("room-plan"), h.DataAttribute("drag", state)], [
// The page's own pieces, until the room's program draws its own in their places.
...(state === "arrived" ? [] : PIECES.map((piece) => h.div([h.Class("room-piece"), h.DataAttribute("id", piece.id), h.Style(placeOf(piece))], [piece.name]))),
// The host the program is embedded in, mounted by the press, with the switch as it was then. A
// Foldkit container has an id, for the Model preservation of its development reloads.
...(model.wanted ? [h.div([h.Id("room-host"), h.Class("room-host"), h.OnMount(Room({ slow: model.slow }))])] : []),
]),
]),
])
})
export default definePage({
id: "rearrange",
Data,
Model,
Message,
load: Effect.succeed({}),
init: (): Model => ({ wanted: false, slow: false, arrivedIn: null }),
update: (model, message) =>
Message.match(message, {
Rearrange: () => ({ model: { ...model, wanted: true } }),
SetSlow: ({ on }) => ({ model: { ...model, slow: on } }),
Arrived: ({ ms }) => ({ model: { ...model, arrivedIn: ms } }),
}),
view,
})
/** The room's pieces, where they start: what the page draws before the room's program arrives, and what the program draws then. */
export const PIECES = [
{ id: "sofa", name: "Sofa", x: 24, y: 24, width: 120, height: 52 },
{ id: "table", name: "Table", x: 64, y: 112, width: 72, height: 44 },
{ id: "lamp", name: "Lamp", x: 236, y: 32, width: 44, height: 44 },
] as const
export type Piece = (typeof PIECES)[number]
/** A piece's place in the plan, as its `style`. */
export const placeOf = (piece: Piece): Record<string, string> => ({ left: `${piece.x}px`, top: `${piece.y}px`, width: `${piece.width}px`, height: `${piece.height}px` })
/**
* The room as a Foldkit program of its own, with a Handle of its own that names `drag` alone. This
* module is imported when you press Rearrange, so the program and its Handle arrive as one chunk
* then, and `mount` embeds it in the plan. The shop's Handle has `drag` already (its other rooms
* drag on it), so the bytes the press fetches are this program's.
*/
import { DomLive } from "@wardic/dom"
import * as Schema from "effect/Schema"
import type { Html, HtmlBuilder } from "foldkit/html"
import * as Runtime from "foldkit/runtime"
import { Features, Wardic } from "@wardic/foldkit"
import { PIECES, placeOf } from "./pieces.ts"
const room = Wardic.make({ env: DomLive, features: [Features.drag] })
const Model = Schema.Struct({})
type Model = typeof Model.Type
// The pieces are Wardic's to move, inside their parent: the program has no Messages of its own.
const view = (_model: Model, h: HtmlBuilder<never>): Html => {
const w = room.html(h)
return w.div(
[h.Class("room-pieces")],
PIECES.map((piece) =>
w.keyed("div")(piece.id, [h.Class("room-piece"), h.DataAttribute("id", piece.id), w.Drag(), w.DragConstraints("parent"), w.DragElastic(0.1), w.DragMomentum(false), w.WhileDrag({ scale: 1.05 }), h.Style(placeOf(piece))], [piece.name]),
),
)
}
/** The room, running in `container` until its handle is disposed. */
export const mount = (container: HTMLElement): Runtime.EmbedHandle =>
Runtime.embed(Runtime.makeElement({ Model, init: () => ({ model: {} }), update: (model: Model, _message: never) => ({ model }), view, container, resources: room.resources }))