Type a word, a function name or an error code.
Opening the index…
The search index did not load. Type again to retry.
Nothing in the docs matches “”.
↑↓ to moveenter to goesc to close
Async values
6 min·Assumes: statestate, computedcomputed, conditionalsconditionals
Some data takes time to load. You choose what the page shows while it waits.
import { computed, state } from '@markless/core';
import { fetchStick } from './dog.ts';
export default function Parkfunction Park(): Element() @{@{ · Statement containerHolds instructions: setup lines, then the element to show.
let throwslet throws: number = statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.(1);
const stickconst stick: any = computedcomputed · Derived valueDeclares a value worked out from other values by a recipe, worked out again whenever one of them changes. Give it an async recipe and read it inside @try.(async () => fetchStickimport fetchStick(throws));
<section<section> · HTML elementA section of a page, usually with its own heading.>
@try@try · Async blockShows its block once the slow value is ready. {
<p<p> · HTML elementA paragraph.>Rex brought back {stick}</p<p> · HTML elementA paragraph.>
} @pending@pending · Waiting contentShows while the answer is still loading. {
<p<p> · HTML elementA paragraph.>Rex is still running</p<p> · HTML elementA paragraph.>
}
<button<button> · HTML elementA button a person can press. onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => throwslet throws: number++}>
Throw it again
</button<button> · HTML elementA button a person can press.>
</section<section> · HTML elementA section of a page, usually with its own heading.>
}fetchStick is slow. Put it in computed(async …), and @pending@pending · Waiting contentShows while the answer is still loading. shows while it loads. When the answer is ready, @try@try · Async blockShows its block once the slow value is ready. shows it.
Show something while you wait
Slow data never holds up the rest of the page. Put what to show while it loads in @pending@pending · Waiting contentShows while the answer is still loading., and everything around it works as normal.
import { computed, state } from '@markless/core';import * as rooms from './rooms.ts';import * as walk from './walk.ts';export default function Corridor() @{ let door = state<rooms.Door>('red'); let inside = state(false); const room = computed(async () => rooms.open(door), ); function goThrough(next: rooms.Door) { if (!inside) door = next; inside = !inside; } <section class="corridor" tabindex="0" aria-label="Corridor: arrow keys walk" onClick={(event) => walk.click(event, goThrough)} onKeyDown={(event) => walk.key(event, goThrough)} onPointerDown={(event) => walk.press(event, goThrough)} onKeyUp={walk.release} onPointerUp={walk.lift} onPointerOut={walk.lift} onPointerCancel={walk.lift} onFocusOut={walk.leave} > @if (inside) { <div class="screen"> @try { <p class="room" data-room={room.kind}> {room.name} </p> } @pending { <p class="loading"> {rooms.tip(door)} </p> } </div> } <i class="knight" /> <p class="said"> {rooms.where(door, inside)} </p> <p class="pad"> @for (const pad of walk.pads; key pad.way) { <button class={pad.name} aria-label={pad.label} data-way={pad.way} /> } </p> </section>}
export type Door = 'red' | 'blue';export type Room = { kind: 'dragon' | 'toilet'; name: string;};const behind: Record<Door, Room> = { red: { kind: 'dragon', name: "The Dragon's Hoard", }, blue: { kind: 'toilet', name: 'The Royal Privy', },};const loads: Record<Door, number> = { red: 2000, blue: 1500,};const tips: Record<Door, string> = { red: 'Tip: the red door is red.', blue: 'Tip: doors open.',};// The room arrives once the game has loaded it.export function open(door: Door) { return new Promise<Room>((resolve) => { const ready = () => resolve(behind[door]); setTimeout(ready, loads[door]); });}export const tip = (door: Door) => tips[door];export function where( door: Door, inside: boolean,) { if (!inside) return 'In the corridor'; return `Behind the ${door} door`;}
import type { Door } from './rooms.ts';type Through = (door: Door) => void;export const pads = [ { way: -1, name: 'left', label: 'Walk left' }, { way: 1, name: 'right', label: 'Walk right' },];// His feet, in units of the 240-unit hall; the// room he is in; the way he walks; the spot a// click sent him to.let x = 120;let room: Door | undefined;let way = 0;let target: number | undefined;let last = 0;let hall: HTMLElement | undefined;let go: Through = () => {};const SPEED = 120;// Where each door puts him: in the room behind// it, or back in the corridor beside it.const sides: Record< Door, { inRoom: number; outside: number }> = { red: { inRoom: 176, outside: 64 }, blue: { inRoom: 64, outside: 176 },};// Red door at the left end, blue at the right.function edgeAt(at: number): Door | undefined { if (at <= 40) return 'red'; if (at >= 200) return 'blue'; return undefined;}function halt() { way = 0; target = undefined; if (!hall) return; delete hall.dataset.walking; delete hall.dataset.held;}// A door he reaches takes him through it; in a// room, the far wall is no way out.function through() { const edge = edgeAt(x); if (!edge || edge === room) return; const door = room ?? edge; const side = sides[door]; x = room ? side.outside : side.inRoom; room = room ? undefined : edge; if (target !== undefined) halt(); go(door);}function step(now: number) { if (!way || !hall) return; x += (way * SPEED * (now - last)) / 1000; x = Math.min(228, Math.max(12, x)); last = now; const aim = target; if (aim !== undefined && (aim - x) * way <= 0) { x = aim; halt(); } through(); hall.style.setProperty('--x', `${x}`); requestAnimationFrame(step);}function start( event: Event, to: number, then: Through,) { const scene = event.currentTarget; if (!(scene instanceof HTMLElement)) return; hall = scene; go = then; hall.dataset.walking = ''; hall.style.setProperty('--facing', `${to}`); const still = way === 0; way = to; last = performance.now(); if (still) requestAnimationFrame(step);}// Holding an arrow key or a pad key walks him// evenly; key repeats change nothing.function hold( event: Event, to: number, then: Through,) { target = undefined; start(event, to, then); if (hall) hall.dataset.held = `${to}`;}export function key( event: KeyboardEvent, then: Through,) { if ( event.key !== 'ArrowLeft' && event.key !== 'ArrowRight' ) return; event.preventDefault(); if (event.repeat) return; const to = event.key === 'ArrowLeft' ? -1 : 1; hold(event, to, then);}export function press( event: PointerEvent, then: Through,) { const pad = event.target; if (!(pad instanceof HTMLElement)) return; const to = Number(pad.dataset.way); if (to) hold(event, to, then);}function stop() { if (target === undefined) halt();}// A finger or mouse leaving a pad key lets go.export function lift(event: PointerEvent) { const pad = event.target; if (!(pad instanceof HTMLElement)) return; if (pad.dataset.way) stop();}export function release(event: KeyboardEvent) { const left = event.key === 'ArrowLeft'; const right = event.key === 'ArrowRight'; if (left && way < 0) stop(); if (right && way > 0) stop();}// Focus moving to a pad key stays in the scene.export function leave(event: FocusEvent) { const to = event.relatedTarget; const scene = event.currentTarget; if (!(scene instanceof HTMLElement)) return; if (to instanceof Node && scene.contains(to)) return; halt();}// A click on the floor or a room sends him there;// on a door, through it. The loading screen, the// pad and the line under the scene do nothing.export function click( event: MouseEvent, then: Through,) { const spot = event.target; const scene = event.currentTarget; if (!(scene instanceof HTMLElement)) return; const onRoom = spot instanceof HTMLElement && spot.dataset.room; if (spot !== scene && !onRoom) return; const box = scene.getBoundingClientRect(); const unit = box.width / 240; const top = event.clientY - box.top; if (top > 240 * unit) return; const at = (event.clientX - box.left) / unit; target = spotAt(at); if (Math.abs(target - x) < 1) return halt(); start(event, Math.sign(target - x), then);}// A click on a door aims past its edge.function spotAt(at: number) { if (at < 60) return 24; if (at > 180) return 216; return at;}
/* The hall is 240 x 240 units of --u; the line and the pad sit under it. */.corridor { --u: calc(100cqw / 240); container-type: inline-size; position: relative; width: 100%; max-width: 28rem; margin: 0 auto; background: 0 0 / 100% no-repeat url(/examples/ink/as-corridor-hall.svg); font-family: 'Shantell Sans', sans-serif; text-align: center; user-select: none; outline-offset: 3px; cursor: pointer;}.corridor:focus-visible { outline: 2px dashed;}.corridor .screen,.corridor .screen p { position: absolute; inset: 0 0 auto; height: calc(240 * var(--u)); margin: 0;}/* Behind the room, so it fades in from the dark of the loading screen, never over the hall. */.corridor .screen { z-index: 1; background: #2d2a24;}/* Each room is a frame of one sheet. */.corridor .room { --frame: 0; box-sizing: border-box; padding-top: calc(16 * var(--u)); background: url(/examples/ink/as-corridor-rooms.svg) 0 0 / 200% 100%; background-position: calc(var(--frame) * 100%) 0; font-size: clamp( 0.9rem, calc(15 * var(--u)), 1.3rem ); font-weight: 700;}.corridor [data-room='toilet'] { --frame: 1;}/* The loading screen: dark in either theme. */.corridor .loading { box-sizing: border-box; display: flex; flex-direction: column; justify-content: flex-end; padding: 0 calc(12 * var(--u)) calc(24 * var(--u)); background: #2d2a24; color: #ebe2cc; font-size: clamp( 0.75rem, calc(13 * var(--u)), 1.1rem );}.corridor .loading::before { content: ''; position: absolute; left: calc(96 * var(--u)); top: calc(64 * var(--u)); width: calc(48 * var(--u)); height: calc(64 * var(--u)); background: 0 0 / 100% no-repeat url(/examples/ink/as-corridor-hourglass.svg);}/* The knight: a frame of his sheet, standing at --x and facing --facing, set on the hall. */.corridor .knight { position: absolute; z-index: 2; left: 0; top: calc(143 * var(--u)); width: calc(48 * var(--u)); height: calc(64 * var(--u)); background: url(/examples/ink/as-corridor-knight.svg) 0 0 / 300% 100% no-repeat; translate: calc((var(--x, 120) - 24) * var(--u)) 0; scale: var(--facing, 1) 1;}.corridor:has(.loading) .knight { opacity: 0;}.corridor .said { margin: calc(244 * var(--u)) 0 0; font-weight: 700;}/* The gamepad: a held arrow presses its key. */.corridor .pad { display: flex; justify-content: space-between; box-sizing: border-box; height: calc(76 * var(--u)); margin: 0.3em 0 0; padding: calc(10 * var(--u)) calc(32 * var(--u)); background: 0 0 / 100% no-repeat url(/examples/ink/as-corridor-pad.svg);}.corridor .pad button { --k: 0; --down: 0; width: max(44px, calc(60 * var(--u))); height: max(44px, calc(52 * var(--u))); padding: 0; border: 0; background: url(/examples/ink/as-corridor-keys.svg) 0 0 / 200% 200% no-repeat; background-position: calc(var(--k) * 100%) calc(var(--down) * 100%); cursor: pointer; touch-action: none; -webkit-touch-callout: none;}.corridor .pad .right { --k: 1;}.corridor[data-held='-1'] .left,.corridor[data-held='1'] .right { --down: 1;}.corridor .pad button:focus-visible { outline: 2px dashed; outline-offset: 2px;}@media (prefers-reduced-motion: no-preference) { .corridor .loading::before { animation: corridor-turn 1s ease-in-out infinite; } .corridor .room { animation: corridor-in 0.2s ease-out; } .corridor[data-walking] .knight { animation: corridor-walk 0.3s infinite steps(2, jump-none); }}@keyframes corridor-walk { from { background-position-x: 50%; } to { background-position-x: 100%; }}@keyframes corridor-turn { 60%, to { rotate: 180deg; }}@keyframes corridor-in { from { opacity: 0; }}
In the corridor
- To do: Walk the knight into the red door with the arrow keys, or hold the arrows under the scene.
- To do: Walk him back out and into the red door again: no loading this time. Then try the blue door.
- To do: In rooms.ts, change the blue door's tip to
Tip: knock first.
The first answer comes with the page
Loading starts before the page is shown, with nothing for you to write. An answer that is ready in time is already in the page when it opens. A slower one shows its @pending@pending · Waiting contentShows while the answer is still loading. and fills in when it arrives.
The old answer stays until the new one is ready
Ask again, and the last answer stays on screen until the new one arrives.
Call base twice. While you wait, the old reply has aria-busy="true", and the CSS uses that to fade it.
import { computed, state } from '@markless/core';import { answer, say } from './base.ts';export default function Walkie() @{ let sent = state(0); const reply = computed(async () => answer(sent), ); const message = computed(() => say(sent)); <section class="walkie"> <p class="you-say">{message}</p> @try { <p class="base-says" style={'--face: ' + reply.face} > {reply.words} </p> } @pending { <p class="base-says">Kssh…</p> } <button class="talk" aria-label="Hold to talk" onClick={() => sent++} > Talk </button> </section>}
export type Reply = { words: string; face: number;};type Line = Reply & { you: string };// Faces: 0 glad, 1 tired, 2 cross, 3 asleep.const talk: Line[] = [ { you: 'Fort to base. Come in. Over.', words: 'Base here. Over.', face: 0, }, { you: 'The fort needs snacks. Over.', words: 'Copy. Ask nicely. Over.', face: 0, }, { you: 'Please can we have snacks? Over.', words: 'Copy. One biscuit. Over.', face: 1, }, { you: 'Fort to base, copy? Over.', words: 'Copy. Over.', face: 1, }, { you: 'Copy that copy. Over.', words: 'Please stop saying over.', face: 2, }, { you: 'Base, are you awake? Over.', words: 'No. Over and out.', face: 3, },];const silence: Line = { you: '', words: '', face: 0,};const line = (sent: number) => talk[sent % talk.length] ?? silence;export const say = (sent: number) => line(sent).you;// Base is slower to answer every time you call.export function answer(sent: number) { const { words, face } = line(sent); const wait = Math.min(300 + sent * 500, 2500); return new Promise<Reply>((resolve) => { setTimeout( () => resolve({ words, face }), wait, ); });}
/* The fort is 200 x 280 units. */.walkie { container-type: inline-size; position: relative; aspect-ratio: 200 / 280; max-width: 20rem; margin: 0 auto; background: 0 0 / 100% no-repeat url( /examples/ink/as-walkie-fort.svg ); font-family: 'Shantell Sans', sans-serif; user-select: none;}/* The two speech bubbles: yours points at the grille, base's crackles out of the antenna. */.walkie p { position: absolute; box-sizing: border-box; width: 46%; margin: 0; border: 0.8rem solid; padding-bottom: 0.2rem; font-size: 0.85rem; line-height: 1.25;}.walkie .you-say { bottom: 50%; left: 3%; border-image: url( /examples/ink/as-walkie-you.svg ) 20 fill / 0.8rem round;}.walkie .base-says { bottom: 59%; right: 3%; border-image: url( /examples/ink/as-walkie-base.svg ) 20 fill / 0.8rem round stretch; font-weight: 700;}/* Base's face, in a badge on the bubble. */.walkie .base-says::before { content: ''; position: absolute; top: -2.5rem; right: -1rem; width: 3rem; aspect-ratio: 1; background: url( /examples/ink/as-walkie-sister.svg ) 0 0 / 400% 100%; background-position: calc(var(--face) * 100% / 3) 0;}/* Still the last answer: faded, with static over it. */.walkie .base-says[aria-busy='true'] { color: color-mix( in oklch, currentColor 40%, #0000 );}.walkie .base-says[aria-busy='true']::after { content: ''; position: absolute; inset: 0; clip-path: inset(0 round 0.4rem); background: url( /examples/ink/as-walkie-crackle.svg ) 0 0 / 3.5rem auto;}/* The light: red while you talk, green while base is coming through. */.walkie::before { position: absolute; top: 53.9%; left: 37.3%; width: 7.5%; aspect-ratio: 1; background: url( /examples/ink/as-walkie-light.svg ) 0 0 / 200% 100%;}.walkie:has([aria-busy='true'])::before { content: ''; background-position-x: 100%;}.walkie:has(.talk:active)::before { content: ''; background-position-x: 0;}.walkie .talk { position: absolute; top: 67.5%; left: 37.5%; width: 25%; aspect-ratio: 1; padding: 0; border: 0; border-radius: 50%; background: url( /examples/ink/as-walkie-talk.svg ) 0 0 / 200% 100%; color: #2d2a24; font: inherit; font-weight: 700; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none;}.walkie .talk:active { background-position-x: 100%; padding-top: 4%;}/* Your voice going into the grille. */.walkie .talk:active::after { content: ''; position: absolute; bottom: 108%; left: 0; width: 100%; aspect-ratio: 2; background: url( /examples/ink/as-walkie-voice.svg ) 0 0 / 100%;}.walkie .talk:focus-visible { outline: 2px dashed currentColor; outline-offset: 3px;}@media (prefers-reduced-motion: no-preference) { .walkie .base-says[aria-busy='true']::after { animation: walkie-static 0.3s steps(3) infinite; } .walkie:has([aria-busy='true'])::before { animation: walkie-blink 0.6s steps(2) infinite; }}@keyframes walkie-static { to { background-position: 3.5rem 1rem; }}@keyframes walkie-blink { 50% { opacity: 0; }}
Fort to base. Come in. Over.
Base here. Over.
- To do: Hold to talk, then let go. Your message shows at once, and base’s last answer stays, crackling, until the new one comes through.
- To do: In
base.ts, change500to100. Base answers sooner, so the crackle is shorter.
Only the newest answer is shown
The page always shows the answer to your latest request, even if an older one finishes later.
Press the planes to throw both. Plane 1 is thrown first and arrives last, so the window turns it away.
To stop the older request as well, pass signal to fetch. It is the browser's AbortSignal, and Markless cancels it when a newer request starts:
const forecastconst forecast: any = computedcomputed · Derived valueDeclares a value worked out from other values by a recipe, worked out again whenever one of them changes. Give it an async recipe and read it inside @try.(async ({ signal(parameter) signal: AbortSignalAborts when a newer run starts or this run's answer will no longer be used. Pass it to fetch. Event handlers get no signal: to cancel a save that a newer one replaces, keep an AbortController in a plain .ts module. }) => {
const responseconst response: Response = await fetchfunction fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>MDN Reference(
`/api/forecast?city=${cityimport city}`,
{ signal },
);
return response.json(method) Body.json(): Promise<any>MDN Reference();
});When loading fails, say so and try again
When loading fails, the reader sees what you put in @catch@catch · Failure contentShows when loading fails. @catch (error) gives you the error. and keeps the last answer. Call reset to try again.
import { computed, state } from '@markless/core';import * as machine from './machine.ts';import * as steer from './steer.ts';export default function Claw() @{ let aim = state(2); let turn = state(machine.start); const prize = computed(async () => machine.grab(turn), ); <section class="claw" style={machine.hold(turn)} > @try { <p class={prize.kind} style={prize.look}> {prize.screen} @for (const toy of prize.pile; key toy) { <i class="toy" style={toy} /> } </p> } @catch (error, reset) { <p class="slipped"> <span>{error.message}</span> <button onClick={reset}> Insert coin </button> </p> } <div class="glass" role="slider" tabindex="0" aria-label="Claw" aria-valuemin="0" aria-valuemax="4" aria-valuenow={aim} aria-valuetext={machine.toys[aim]?.name} style={'--aim:' + aim} onPointerDown={(event) => (aim = steer.drag(event, aim))} onPointerMove={(event) => (aim = steer.drag(event, aim))} onKeyDown={(event) => (aim = steer.key(event, aim))} > <i class="hook" /> </div> <button class="drop" onClick={() => (turn = machine.drop(aim))} > Drop </button> </section>}
// Each toy's half-width where the arms close on// it, and how far below the hub it then hangs.export const toys = [ { name: 'Whale', grip: 18, hang: 19.4 }, { name: 'Octopus', grip: 14, hang: 25.4 }, { name: 'Toast', grip: 18, hang: 31.4 }, { name: 'Cactus', grip: 17, hang: 25 }, { name: 'Cloud', grip: 19, hang: 20.8 },];const duck = toys.length;// The claw holds on every third go.let goes = 0;// Every prize so far, the newest in the chute.const won = [duck];// The go in play: no new coin while it runs.let current = { toy: -1 };let running: Promise<Chute> | undefined;export const start = current;export function drop(aim: number) { if (!running) current = { toy: aim }; return current;}export function hold(turn: { toy: number }) { const { grip = 18, hang = 21 } = toys[turn.toy] ?? {}; const size = `--grip:${grip};--hang:${hang}`; return `--toy:${turn.toy};${size}`;}// Out of the machine once won; the newest is// still on its way to the chute.function spot(k: number, fresh: boolean) { if (!won.includes(k)) return `--k:${k}`; const out = `--k:${k};--out:1`; const flying = fresh && k === won.at(-1); return flying ? `${out};--won:1` : out;}function chute(fresh: boolean, screen?: string) { const last = won.at(-1) ?? duck; const was = won.at(-2) ?? last; return { screen: screen ?? toys[last]?.name ?? 'Duck', kind: fresh ? 'prize fresh' : 'prize', look: `--k:${last};--was:${was}`, pile: toys.map((_, k) => spot(k, fresh)), };}type Chute = ReturnType<typeof chute>;export function grab(turn: { toy: number }) { if (turn.toy < 0) return Promise.resolve(chute(false)); if (won.includes(turn.toy)) return Promise.resolve( chute(false, 'Nothing there!'), ); if (running) return running; goes++; const holds = goes % 3 === 0; running = new Promise<Chute>( (resolve, reject) => setTimeout(() => { running = undefined; if (!holds) return reject(new Error('It slipped!')); won.push(turn.toy); resolve(chute(true)); }, 1400), ); return running;}
const columns = 5;const clamp = (column: number) => Math.max(0, Math.min(columns - 1, column));// Pressed on the glass: the claw goes over the// toy under the finger, and follows it.export function drag( event: PointerEvent, aim: number,) { const glass = event.currentTarget; if (!(glass instanceof HTMLElement)) return aim; if (!event.buttons) return aim; if (event.type === 'pointerdown') glass.setPointerCapture(event.pointerId); const box = glass.getBoundingClientRect(); const x = event.clientX - box.left; const share = x / box.width; return clamp(Math.floor(share * columns));}export function key( event: KeyboardEvent, aim: number,) { if ( event.key !== 'ArrowLeft' && event.key !== 'ArrowRight' ) return aim; event.preventDefault(); const step = event.key === 'ArrowLeft' ? -1 : 1; return clamp(aim + step);}
/* The machine is 240 x 352 units of --u. The last Drop was over column --toy; that toy is held --grip wide and hangs --hang below. */.claw { --u: calc(100cqw / 240); --open: 60deg; --shut: asin(calc((var(--grip) - 3) / 29.5)); --lift: calc((var(--hang) - 128) * var(--u)); container-type: inline-size; position: relative; width: 100%; max-width: 28rem; aspect-ratio: 240 / 352; margin: 0 auto; background: 0 0 / 100% no-repeat url(/examples/ink/as-claw-machine.svg); color: #2d2a24; font-family: 'Shantell Sans', sans-serif; font-weight: 700; user-select: none;}.claw > *,.claw button { position: absolute; box-sizing: border-box; margin: 0;}.claw button { padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer;}.claw :focus-visible { outline: 2px dashed; outline-offset: 2px; border-radius: 6px;}/* The screen. */.claw .prize,.claw .slipped { top: calc(220 * var(--u)); left: calc(22 * var(--u)); width: calc(102 * var(--u)); height: calc(32 * var(--u)); display: grid; place-items: center; font-size: 0.8rem; line-height: 1; text-align: center;}.claw .prize[aria-busy='true'] { color: #2d2a2480;}.claw .slipped { border-radius: 4px; background: #8fc07a;}.claw .slipped[aria-busy='true'] span { opacity: 0.5;}/* Drop: a dome you push, its name beside it. */.claw .drop { top: calc(214 * var(--u)); left: calc(126 * var(--u)); width: calc(94 * var(--u)); height: calc(44 * var(--u)); display: flex; align-items: center; justify-content: space-between; font-size: 0.7rem;}.claw .drop::after { content: ''; width: calc(60 * var(--u)); aspect-ratio: 60 / 44; background: url(/examples/ink/as-claw-drop.svg) 0 0 / 200% 100% no-repeat;}.claw .drop:active::after { background-position-x: 100%;}/* The coin slot lights up when a go slipped; it is the button for another coin. */.claw .slipped button { top: calc(42 * var(--u)); left: calc(113 * var(--u)); width: calc(80 * var(--u)); height: calc(48 * var(--u)); display: grid; align-items: end; justify-items: center; padding-bottom: calc(1 * var(--u)); background: 0 0 / 100% url(/examples/ink/as-claw-slot.svg); font-size: 0.65rem; line-height: 1.2; white-space: nowrap;}.claw .slipped button::after { content: ''; position: absolute; top: calc(-6 * var(--u)); left: calc(34 * var(--u)); width: calc(12 * var(--u)); aspect-ratio: 1; background: 0 0 / 100% url(/examples/ink/as-claw-coin.svg); opacity: 0;}/* The tray: the prize, and the one before it (--was) until the new one lands. */.claw .prize::before,.claw .prize::after { content: ''; position: absolute; top: calc(50 * var(--u)); left: calc(22 * var(--u)); width: calc(44 * var(--u)); height: calc(60 * var(--u)); background: url(/examples/ink/as-claw-toys.svg) no-repeat; background-size: calc(264 * var(--u)) calc(44 * var(--u)); background-position: calc(var(--k) * -44 * var(--u)) calc(14 * var(--u));}.claw .prize::after { --k: var(--was); opacity: 0;}.claw .prize[aria-busy='true']::before { opacity: 0.5;}/* The toys, one per column; one won is out. */.claw .toy { --d: max( var(--k) - var(--toy), var(--toy) - var(--k) ); --hit: max(0, 1 - var(--d)); --near: max( 0, 1 - max(var(--d) - 1, 1 - var(--d)) ); --out: 0; --won: 0; --seen: calc(1 - var(--out) + var(--won)); --fly: calc( (-34.6 - var(--k) * 33.2) * var(--u) ); position: absolute; top: calc(-48 * var(--u)); left: calc((28.6 + var(--k) * 33.2) * var(--u)); width: calc(44 * var(--u)); aspect-ratio: 1; background: url(/examples/ink/as-claw-toys.svg) 0 0 / 600% 100% no-repeat; background-position: calc(var(--k) * 20%) 0; opacity: calc(1 - var(--out));}/* Behind the glass: the claw over column --aim, its arms open, and the prize bin's front. */.claw .glass { top: calc(46 * var(--u)); left: calc(56 * var(--u)); width: calc(166 * var(--u)); height: calc(166 * var(--u)); overflow: visible clip; cursor: grab; touch-action: none;}.claw .glass::before { content: ''; position: absolute; top: calc(110 * var(--u)); left: calc(-36 * var(--u)); width: calc(36 * var(--u)); height: calc(56 * var(--u)); background: 0 0 / 100% url(/examples/ink/as-claw-bin.svg);}.claw .hook { position: absolute; top: calc(-107 * var(--u)); left: calc( (var(--aim) * 33.2 + 6.6) * var(--u) ); width: calc(20 * var(--u)); height: calc(130 * var(--u)); background: 0 0 / 100% url(/examples/ink/as-claw-hook.svg); transform-origin: 50% 0;}.claw .hook::before,.claw .hook::after { --side: 1; content: ''; position: absolute; top: calc(124.5 * var(--u)); left: calc(1.5 * var(--u)); width: calc(12 * var(--u)); height: calc(36 * var(--u)); background: url(/examples/ink/as-claw-arm.svg) 0 0 / 200% 100% no-repeat; transform-origin: calc(3.5 * var(--u)) calc(2.5 * var(--u)); rotate: calc(var(--side) * var(--open));}.claw .hook::after { --side: -1; left: calc(6.5 * var(--u)); background-position-x: 100%; transform-origin: calc(8.5 * var(--u)) calc(2.5 * var(--u));}/* Busy: the claw over --toy, shut on it. */.claw:has([aria-busy='true']) .glass { pointer-events: none;}.claw:has([aria-busy='true']) .hook { left: calc( (var(--toy) * 33.2 + 6.6) * var(--u) );}.claw:has([aria-busy='true']) .hook::before,.claw:has([aria-busy='true']) .hook::after { rotate: calc(var(--side) * var(--shut));}.claw:has([aria-busy='true']) .toy { translate: 0 calc(var(--hit) * var(--lift)); transform-origin: 50% calc( (-105 - var(--hang)) * var(--u) );}@media (prefers-reduced-motion: no-preference) { .claw .hook { transition: left 0.15s ease-out; } .claw .slipped:not([aria-busy='true']) button { animation: claw-blink 0.9s ease-in-out infinite alternate; } .claw .slipped[aria-busy='true'] button::after { animation: claw-coin 0.25s ease-in; } .claw:has([aria-busy='true']) .hook { animation: claw-grab 0.7s ease-in-out, claw-sway 0.5s 0.7s ease-in-out infinite alternate; } .claw:has([aria-busy='true']) .hook::before, .claw:has([aria-busy='true']) .hook::after { animation: claw-close 0.7s; } .claw:has([aria-busy='true']) .toy { animation: claw-lift 0.7s, claw-sway 0.5s 0.7s ease-in-out infinite alternate; } .claw:has(.slipped:not([aria-busy='true'])) .hook::before, .claw:has(.slipped:not([aria-busy='true'])) .hook::after { animation: claw-let-go 0.08s ease-out; } .claw:has(.slipped:not([aria-busy='true'])) .toy { animation: claw-fall 0.4s 0.08s backwards; } .claw:has(.fresh):not( :has(.slipped, [aria-busy='true']) ) .hook { animation: claw-carry 0.65s ease-in-out; } .claw:has(.fresh):not( :has(.slipped, [aria-busy='true']) ) .hook::before, .claw:has(.fresh):not( :has(.slipped, [aria-busy='true']) ) .hook::after { animation: claw-drop-it 0.65s; } .claw:has(.fresh):not( :has(.slipped, [aria-busy='true']) ) .toy { animation: claw-away 0.55s; } .claw:not(:has(.slipped, [aria-busy='true'])) .fresh::before { animation: claw-tray 0.4s 0.55s backwards; } .claw:not(:has(.slipped, [aria-busy='true'])) .fresh::after { animation: claw-was 0.83s; }}@keyframes claw-blink { from { opacity: 0.6; }}@keyframes claw-coin { from { opacity: 1; translate: 0 calc(-14 * var(--u)); } 80% { opacity: 1; translate: 0 calc(10 * var(--u)); } to { translate: 0 calc(10 * var(--u)); }}/* Down, shut on the toy, and up with it. */@keyframes claw-grab { 43%, 57% { translate: 0 calc( (128 - var(--hang)) * var(--u) ); }}@keyframes claw-close { 0%, 43% { rotate: calc(var(--side) * var(--open)); animation-timing-function: ease-in-out; } 57% { rotate: calc(var(--side) * var(--shut)); }}@keyframes claw-lift { 0%, 57% { translate: 0 0; animation-timing-function: ease-in-out; }}@keyframes claw-sway { from { rotate: calc(var(--hit, 1) * -3deg); } to { rotate: calc(var(--hit, 1) * 3deg); }}/* It slips: the arms open, the toy drops into its own gap, squashes, bounces; its neighbours jostle. */@keyframes claw-let-go { from { rotate: calc(var(--side) * var(--shut)); }}@keyframes claw-fall { 0% { translate: 0 calc(var(--hit) * var(--lift)); animation-timing-function: cubic-bezier(0.5, 0, 1, 0.6); } 70% { translate: 0 0; rotate: calc(var(--hit) * 12deg); scale: calc(1 + var(--hit) * 0.14) calc(1 - var(--hit) * 0.18); animation-timing-function: ease-out; } 84% { translate: 0 calc( (var(--hit) * -6 + var(--near) * -3) * var(--u) ); rotate: calc(var(--near) * 4deg); animation-timing-function: ease-in; }}/* It holds: over to the bin, open, and back. */@keyframes claw-carry { 0% { left: calc( (var(--toy) * 33.2 + 6.6) * var(--u) ); } 38%, 62% { left: calc(-28 * var(--u)); }}@keyframes claw-drop-it { 0%, 35% { rotate: calc(var(--side) * var(--shut)); animation-timing-function: ease-out; } 42% { rotate: calc(var(--side) * var(--open)); }}@keyframes claw-away { 0% { translate: 0 calc(var(--won) * var(--lift)); opacity: var(--seen); animation-timing-function: ease-in-out; } 45% { translate: calc(var(--won) * var(--fly)) calc(var(--won) * var(--lift)); opacity: var(--seen); animation-timing-function: cubic-bezier(0.5, 0, 1, 0.6); } 99.9% { translate: calc(var(--won) * var(--fly)) calc(var(--won) * -6 * var(--u)); opacity: var(--seen); }}/* Down the chute into the tray, and settle. */@keyframes claw-tray { 0% { background-position-y: calc(-46 * var(--u)); animation-timing-function: cubic-bezier(0.5, 0, 1, 0.6); } 70% { background-position-y: calc(14 * var(--u)); animation-timing-function: ease-out; } 85% { background-position-y: calc(8 * var(--u)); animation-timing-function: ease-in; }}@keyframes claw-was { 0%, 99.9% { opacity: 1; }}
Duck
- To do: Steer the claw over the toast and press Drop.
- To do: Press Insert coin until the toast is yours. The duck stays in the chute until then.
- To do: In machine.ts, change
goes % 3togoes % 2: the claw holds on every other go.
@catch also shows when your own async function throws an error, not only when a request fails.
Do two slow values wait for each other?
No. Say the weather loads in one second and the news in three. Give each its own @try@try · Async blockShows its block once the slow value is ready.:
@try@try · Async blockShows its block once the slow value is ready. {
<p<p> · HTML elementA paragraph.>{weather}</p<p> · HTML elementA paragraph.>
} @pending@pending · Waiting contentShows while the answer is still loading. {
<p<p> · HTML elementA paragraph.>Loading the weather</p<p> · HTML elementA paragraph.>
}
@try@try · Async blockShows its block once the slow value is ready. {
<p<p> · HTML elementA paragraph.>{news}</p<p> · HTML elementA paragraph.>
} @pending@pending · Waiting contentShows while the answer is still loading. {
<p<p> · HTML elementA paragraph.>Loading the news</p<p> · HTML elementA paragraph.>
}The weather shows after one second. The news shows two seconds later.
Coming from React?
In React:
const [stick, setStick] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
setStick(null);
fetchStick(throws)
.then(setStick)
.catch(setError);
}, [throws]);
if (error) return <p>Rex got lost</p>;
if (!stick) return <p>Rex is running</p>;
return <p>Rex brought back {stick}</p>;Here:
const stickconst stick: any = computedcomputed · Derived valueDeclares a value worked out from other values by a recipe, worked out again whenever one of them changes. Give it an async recipe and read it inside @try.(async () =>
fetchStickimport fetchStick(throws));
@try@try · Async blockShows its block once the slow value is ready. {
<p<p> · HTML elementA paragraph.>Rex brought back {stick}</p<p> · HTML elementA paragraph.>
} @pending@pending · Waiting contentShows while the answer is still loading. {
<p<p> · HTML elementA paragraph.>Rex is running</p<p> · HTML elementA paragraph.>
} @catch@catch · Failure contentShows when loading fails. @catch (error) gives you the error. (error, reset) {
<p<p> · HTML elementA paragraph.>Rex got lost</p<p> · HTML elementA paragraph.>
}- No loading or error state to keep.
@pending@pending · Waiting contentShows while the answer is still loading. and@catchare the two cases. - No effect to start the request. Reading
stickstarts it.
Next, give a file its own CSS.
Button sounds are from Josh Comeau's Button Sounds library.