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
Elements
3 min·Assumes: statestate, eventsevents
Focus an input, play a video or open a modal from your code.
import { element } from '@markless/core';
export default function Lessonfunction Lesson(): Element() @{@{ · Statement containerHolds instructions: setup lines, then the element to show.
const clipconst clip: HTMLVideoElement = elementelement · Element handleCreates a handle that el={…} points at an element. In handlers and attach the handle is that element, or undefined while it is not on the page.<HTMLVideoElementinterface HTMLVideoElementImplemented by the video element, the HTMLVideoElement interface provides special properties and methods for manipulating video objects.>();
<section<section> · HTML elementA section of a page, usually with its own heading.>
<h1<h1> · HTML elementThe top-level heading.>How to fold a fitted sheet</h1<h1> · HTML elementThe top-level heading.>
<video<video> · HTML elementA video player. elel · Element bindingPoints an element() handle at this element, so handlers and attach can reach it.={clip} src(property) src?: string | undefined="/fold.mp4" />
<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.={() => clip.play(method) HTMLMediaElement.play(): Promise<void>The HTMLMediaElement play() method attempts to begin playback of the media.()}>
Play part 1 of 14
</button<button> · HTML elementA button a person can press.>
</section<section> · HTML elementA section of a page, usually with its own heading.>
}The button starts the video by calling the play() function on the <video> element. element() makes the variable clip, and el={clip} points it at the <video>.
Call any function the browser gives an element
Any function the browser gives an element works this way: focus() on an input, play() on an <audio>, animate() on anything.
Tap the girl to swing. Each swing calls animate() on the stick and on the piñata.
import { element, state } from '@markless/core';import { cheer, strike, sway } from './swing.ts';export default function Party() @{ const pinata = element<HTMLElement | undefined>(); const stick = element<HTMLElement>(); let hits = state(0); function whack() { stick.animate(strike(), 220); pinata?.animate(sway(), 360); hits += 1; } <section class="party"> @if (hits < 5) { <i el={pinata} class="pinata" style={'--hits:' + hits} /> } @else { <i class="sweets" /> } <button class="girl" aria-label="Swing" onClick={whack} > <i el={stick} class="stick" /> </button> <p class="said">{cheer(hits)}</p> </section>}
const calm = () => matchMedia('(prefers-reduced-motion: reduce)') .matches;// No movement for readers who asked for less.const moving = (frames: Keyframe[]) => calm() ? [] : frames;// Down onto the piñata, then back up.export const strike = () => moving([ { rotate: '0deg' }, { rotate: '-80deg', offset: 0.35 }, { rotate: '0deg' }, ]);// It holds still until the stick lands.export const sway = () => moving([ { rotate: '0deg' }, { rotate: '0deg', offset: 0.18 }, { rotate: '18deg', offset: 0.4 }, { rotate: '-9deg', offset: 0.7 }, { rotate: '0deg' }, ]);const counts = [ 'One!', 'Two!', 'Three!', 'Four!',];export function cheer(hits: number) { if (hits === 0) return 'Five hits to break it.'; return counts[hits - 1] ?? 'Sweets!';}
/* The garden is 240 x 220 units of --u. */.party { --u: calc(100cqw / 240); container-type: inline-size; position: relative; width: 100%; max-width: 28rem; margin: 0 auto; background: 0 0 / 100% auto no-repeat url(/examples/ink/el-pinata-garden.svg); font-family: 'Shantell Sans', sans-serif; text-align: center; user-select: none;}/* It hangs from the knot on the branch, and cracks a little more with every hit. */.party .pinata { position: absolute; top: calc(28 * var(--u)); left: calc(58 * var(--u)); width: calc(92 * var(--u)); height: calc(118 * var(--u)); background: url(/examples/ink/el-pinata-donkey.svg) 0 0 / 500% 100% no-repeat; background-position: calc(var(--hits) * 25%) 0; transform-origin: 43.5% 1.7%;}.party .sweets { position: absolute; top: calc(161 * var(--u)); left: calc(40 * var(--u)); width: calc(120 * var(--u)); height: calc(40 * var(--u)); background: 0 0 / 100% no-repeat url(/examples/ink/el-pinata-sweets.svg);}.party .girl { position: absolute; top: calc(40 * var(--u)); left: calc(150 * var(--u)); width: calc(80 * var(--u)); height: calc(160 * var(--u)); padding: 0; border: 0; border-radius: 8px; background: 0 0 / 100% no-repeat url(/examples/ink/el-pinata-girl.svg); cursor: pointer;}.party .girl:focus-visible { outline: 2px dashed; outline-offset: 2px;}/* Her arms and the stick turn about her shoulders. */.party .stick { position: absolute; top: 0; left: 0; width: 100%; height: calc(110 * var(--u)); background: 0 0 / 100% no-repeat url(/examples/ink/el-pinata-arms.svg); transform-origin: 45% 87.3%;}.party .said { margin: calc(222 * var(--u)) 0 0; font-weight: 700;}@media (prefers-reduced-motion: no-preference) { .party .sweets { animation: party-burst 0.22s ease-in 0.06s backwards; }}@keyframes party-burst { from { translate: 0 calc(-70 * var(--u)); scale: 0.5; }}
Five hits to break it.
- To do: Swing five times. The piñata bursts, then swing again at the empty rope.
- To do: Make it swing harder: in swing.ts, change
18degto40deg.
An element inside an @if can be missing
An element inside an @if@if · ConditionalShows its block while the test is true. isn't always on the page. Add | undefined to its type and write ?. before the function, and a call while the element is gone does nothing. Leave out | undefined and the build tells you.
const noteconst note: any = elementelement · Element handleCreates a handle that el={…} points at an element. In handlers and attach the handle is that element, or undefined while it is not on the page.<HTMLTextAreaElementinterface HTMLTextAreaElementThe HTMLTextAreaElement interface provides properties and methods for manipulating the layout and presentation of textarea elements. | undefined>();
@if@if · ConditionalShows its block while the test is true. (writing) {
<textarea<textarea> · HTML elementA text field with several lines. elel · Element bindingPoints an element() handle at this element, so handlers and attach can reach it.={note} />
}
<buttonimport button onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={() => note?.focusany()}>
Back to my letter
</buttonimport button>An element that is always on the page needs neither: clip.play().
Drag down on the stick to bend it until it snaps, then try to bend it again.
Find out where an element is
The variable is the real DOM element, so anything the browser lets you do with an element works. Here getBoundingClientRect() tells each press where the ball and the flipper are.
import { element, state } from '@markless/core';import * as table from './table.ts';export default function Table() @{ const ball = element<SVGImageElement>(); const leftFlipper = element<HTMLElement>(); const rightFlipper = element<HTMLElement>(); const glow = element<HTMLElement>(); let game = state(table.newGame()); function flip( side: table.Side, flipper: HTMLElement, ) { const hit = table.overlap( ball.getBoundingClientRect(), flipper.getBoundingClientRect(), ); if (hit) scored(500); table.hold(side, true); run(); } function pressLeft() { flip('left', leftFlipper); } function pressRight() { flip('right', rightFlipper); } function key(event: KeyboardEvent) { const side = table.sideOf(event); if (side === 'left') pressLeft(); if (side === 'right') pressRight(); } function release(event: table.Press) { const side = table.sideOf(event); if (side) table.hold(side, false); } function pull(event: table.Press) { if (!table.pull(event)) return; if (game.over) game = table.newGame(); run(); } function scored(points: number) { game = table.award(game, points); } function drained() { game = table.next(game); } function run() { table.run( ball, leftFlipper, rightFlipper, glow, scored, drained, ); } <section class="table" data-over={game.over} onKeyDown={key} onKeyUp={release} > <output class="award">{game.award}</output> <output class="score">{game.score}</output> <span class="ball-in-play"> Ball {game.ball} </span> <svg viewBox="0 0 240 340"> <image el={ball} class="ball" x="-6" y="-6" width="12" height="12" href="/examples/ink/el-table-ball.svg" /> </svg> <i el={glow} class="glow" /> <i el={leftFlipper} class="flipper left" /> <i el={rightFlipper} class="flipper right" /> <button class="flip left" data-side="left" aria-label="Left flipper" onPointerDown={pressLeft} onPointerUp={release} onPointerLeave={release} /> <button class="flip right" data-side="right" aria-label="Right flipper" onPointerDown={pressRight} onPointerUp={release} onPointerLeave={release} /> <button class="plunger" onPointerDown={pull} onKeyDown={pull} onPointerUp={table.launch} onKeyUp={table.launch} > Pull </button> </section>}
import * as physics from './physics.ts';import type { Hit, Side } from './physics.ts';export type { Side };export type Press = PointerEvent | KeyboardEvent;export type Game = { score: number; ball: number; over: boolean; award: string;};export const newGame = (): Game => ({ score: 0, ball: 1, over: false, award: '',});export const award = ( game: Game, points: number,) => ({ ...game, score: game.score + points, award: `+${points}`,});export const next = (game: Game): Game => game.ball === 3 ? { ...game, over: true } : { ...game, ball: game.ball + 1 };// Do two boxes on the page overlap?export function overlap(a: DOMRect, b: DOMRect) { return ( a.right > b.left && a.left < b.right && a.bottom > b.top && a.top < b.bottom );}const keyed = (event: KeyboardEvent) => !event.repeat && (event.key === ' ' || event.key === 'Enter');// A Shift key, or a flipper button pressed.export function sideOf( event: Press,): Side | undefined { if (event instanceof KeyboardEvent) { if (event.repeat) return undefined; if (event.key === 'Shift') { return event.location === 2 ? 'right' : 'left'; } if (!keyed(event)) return undefined; } // The target, not currentTarget: a first press // can be handled after its dispatch is over. const button = event.target; if (!(button instanceof HTMLElement)) return undefined; const side = button.dataset.side; if (side === 'left' || side === 'right') return side; return undefined;}const table = physics.start();let frame = 0;let last = 0;let spare = 0;let knob: HTMLElement | undefined;type Parts = { ball: SVGElement; left: HTMLElement; right: HTMLElement; glow: HTMLElement; scored: (points: number) => void; drained: () => void;};let parts: Parts | undefined;export function hold(side: Side, held: boolean) { table[side] = { ...table[side], held };}// Starts pulling back; false if there is no ball// on the plunger to shoot.export function pull(event: Press) { if ( event instanceof KeyboardEvent && !keyed(event) ) { return false; } if (!table.resting) return false; if (event.target instanceof HTMLElement) { knob = event.target; } table.pulling = true; return true;}export function launch(event: Press) { const key = event instanceof KeyboardEvent; if ( key && event.key !== ' ' && event.key !== 'Enter' ) { return; } if (table.pulling) physics.launch(table);}// Runs the table a frame at a time until still.export function run( ball: SVGElement, left: HTMLElement, right: HTMLElement, glow: HTMLElement, scored: (points: number) => void, drained: () => void,) { parts = { ball, left, right, glow, scored, drained, }; if (frame) return; last = performance.now(); frame = requestAnimationFrame(tick);}const calm = '(prefers-reduced-motion: reduce)';function flash(at: number) { const bumper = physics.bumpers[at]; const glow = parts?.glow; if (!bumper || !glow) return; const left = ((bumper.x - 18) / 240) * 100; const top = ((bumper.y - 18) / 340) * 100; glow.style.left = `${left}%`; glow.style.top = `${top}%`; if (matchMedia(calm).matches) return; glow.animate({ opacity: [1, 0] }, 220);}function tell(hits: Hit[]) { for (const hit of hits) { if (hit.kind === 'bumper') { flash(hit.at); parts?.scored(100); } if (hit.kind === 'sling') parts?.scored(10); if (hit.kind === 'drain') parts?.drained(); }}function show() { const { x, y } = table.ball; const set = ( el: Element | undefined, k: string, v: string, ) => el instanceof HTMLElement || el instanceof SVGElement ? el.style.setProperty(k, v) : undefined; set(parts?.ball, 'translate', `${x}px ${y}px`); set( parts?.left, 'rotate', `${table.left.angle}rad`, ); set( parts?.right, 'rotate', `${table.right.angle}rad`, ); set(knob, '--pull', `${table.pull}`);}const still = () => table.resting && !table.pulling && table.left.angle === physics.flippers.left.rest && table.right.angle === physics.flippers.right.rest;function tick(now: number) { // A slow frame or a hidden tab never jumps the // ball: a thirtieth of a second at most. spare += Math.min(now - last, 1000 / 30) / 1000; last = now; const hits: Hit[] = []; while (spare >= physics.STEP) { if (table.pulling) { table.pull = Math.min( 1, table.pull + physics.STEP / 0.8, ); } physics.step(table, physics.STEP, hits); spare -= physics.STEP; } show(); tell(hits); frame = still() ? 0 : requestAnimationFrame(tick);}
// The table in the drawing's units, 240 x 340.// The art is drawn from these same numbers.export type Point = readonly [number, number];export type Bumper = { x: number; y: number; r: number;};export type Flipper = { x: number; y: number; length: number; rest: number; up: number;};export const BALL = 5;export const DRAIN = 306;// The shooter lane; the plunger's tip rests at// `floor`.export const lane = { left: 198, right: 222, floor: 282,};// The middle of the playfield, left of the lane.export const MIDDLE = 108;const MID = MIDDLE;const across = ([x, y]: Point): Point => [ MID * 2 - x, y,];const mirror = (line: Point[]): Point[] => line.map(across);// The top of the cabinet: half an ellipse.const arch = Array.from( { length: 25 }, (_, i): Point => { const turn = Math.PI * (1 + i / 24); return [ 120 + Math.cos(turn) * 102, 132 + Math.sin(turn) * 82, ]; },);const slingTop: Point = [48, 198];const slingFoot: Point = [48, 226];const slingTip: Point = [66, 240];const sling = [slingTop, slingFoot, slingTip];const inlane: Point[] = [ [32, 238], [64, 254],];// The side wall turns in, down into the inlane: a// ball rolling down the wall can't stop or drain.const side: Point[] = [ [18, 166], [32, 196], [32, 238],];const apron: Point[] = [ [58, 268], [96, 292], [96, 300],];// A guide between the lanes at the top.const post = (x: number): Point[] => [ [x, 64], [x, 84],];const laneWall: Point[] = [ [198, 300], [198, 128],];export const walls: Point[][] = [ [[18, 300], ...arch, [222, 300]], laneWall, post(86), post(114), post(142), sling, mirror(sling), inlane, mirror(inlane), side, mirror(side), apron, mirror(apron),];// The rubber faces of the slingshots, which kick.export const slings: [Point, Point][] = [ [slingTop, slingTip], [across(slingTop), across(slingTip)],];// One way: a ball leaves the lane, never back in.export const gate: [Point, Point] = [ [198, 128], [222, 118],];export const bumpers: Bumper[] = [ { x: 72, y: 120, r: 15 }, { x: 140, y: 108, r: 15 }, { x: 108, y: 160, r: 15 },];const tilt = 0.49;const lift = 0.38;const left: Flipper = { x: 58, y: 262, length: 46, rest: tilt, up: -lift,};const right: Flipper = { ...left, x: MID * 2 - left.x, rest: Math.PI - tilt, up: Math.PI + lift,};export const flippers = { left, right };// The bat: 7 round at the pivot, 3.5 at the tip.export const pivotRadius = 7;export const tipRadius = 3.5;export type Side = 'left' | 'right';export type Ball = { x: number; y: number; vx: number; vy: number;};type Flip = { angle: number; spin: number; held: boolean;};export type Table = { ball: Ball; left: Flip; right: Flip; pull: number; pulling: boolean; resting: boolean; cooling: number[]; still: { x: number; y: number; time: number };};export type Hit = | { kind: 'bumper'; at: number } | { kind: 'sling' } | { kind: 'drain' };type Contact = { x: number; y: number; nx: number; ny: number; gap: number; t: number;};// Drawing units and seconds.const GRAVITY = 560;const DRAG = 0.08;const WALL_BOUNCE = 0.45;const RUBBER_BOUNCE = 0.3;const BUMPER_KICK = 300;const SLING_KICK = 240;const LAUNCH = 1050;const TOP_SPEED = 1300;const FLIP_UP = 26;const FLIP_DOWN = 12;const PLUNGER_TRAVEL = 12;const SEARCH_AFTER = 2;const SEARCH_PUSH = 120;export const STEP = 1 / 800;const onPlunger = (pull = 0): Ball => ({ x: 210, y: lane.floor + pull * PLUNGER_TRAVEL - BALL, vx: 0, vy: 0,});const flipAt = (side: Side): Flip => ({ angle: flippers[side].rest, spin: 0, held: false,});export const start = (): Table => ({ ball: onPlunger(), left: flipAt('left'), right: flipAt('right'), pull: 0, pulling: false, resting: true, cooling: bumpers.map(() => 0), still: { x: 210, y: 0, time: 0 },});// A real table never kicks the same way twice.const give = (size: number) => (Math.random() * 2 - 1) * size;const clamp = ( value: number, low: number, high: number,) => Math.max(low, Math.min(high, value));// The nearest point of a segment within `reach`.export function touch( ball: Ball, [ax, ay]: Point, [bx, by]: Point, reach: number,): Contact | undefined { const dx = bx - ax; const dy = by - ay; const along = (ball.x - ax) * dx + (ball.y - ay) * dy; const t = clamp( along / (dx * dx + dy * dy || 1), 0, 1, ); const x = ax + dx * t; const y = ay + dy * t; const distance = Math.hypot( ball.x - x, ball.y - y, ); if (distance >= reach || distance === 0) return undefined; const nx = (ball.x - x) / distance; const ny = (ball.y - y) / distance; return { x, y, nx, ny, gap: reach - distance, t, };}function touchRound( ball: Ball, x: number, y: number, reach: number,): Contact | undefined { const distance = Math.hypot( ball.x - x, ball.y - y, ); if (distance >= reach || distance === 0) return undefined; const nx = (ball.x - x) / distance; const ny = (ball.y - y) / distance; return { x, y, nx, ny, gap: reach - distance, t: 0, };}// Out of the surface, then reflected off it; the// surface may be moving at (sx, sy).export function bounce( ball: Ball, hit: Contact, bounciness: number, sx = 0, sy = 0,): Ball { const x = ball.x + hit.nx * hit.gap; const y = ball.y + hit.ny * hit.gap; const rx = ball.vx - sx; const ry = ball.vy - sy; const into = rx * hit.nx + ry * hit.ny; if (into >= 0) return { ...ball, x, y }; const push = (1 + bounciness) * into; return { x, y, vx: rx - push * hit.nx + sx, vy: ry - push * hit.ny + sy, };}// A bounce, then a shove out along a slightly// turned normal.export function kick( ball: Ball, hit: Contact, strength: number,): Ball { const off = bounce(ball, hit, WALL_BOUNCE); const turn = give(0.25); const cos = Math.cos(turn); const sin = Math.sin(turn); const power = strength * (1 + give(0.15)); return { ...off, vx: off.vx + (hit.nx * cos - hit.ny * sin) * power, vy: off.vy + (hit.nx * sin + hit.ny * cos) * power, };}export function tipOf( side: Side, angle: number,): Point { const { x, y, length } = flippers[side]; return [ x + Math.cos(angle) * length, y + Math.sin(angle) * length, ];}// Swings up while held, back down when not.export function turn( flip: Flip, side: Side, h: number,) { const { rest, up } = flippers[side]; const goal = flip.held ? up : rest; const speed = flip.held ? FLIP_UP : FLIP_DOWN; const way = Math.sign(goal - flip.angle); const next = flip.angle + way * speed * h; const past = way > 0 ? next >= goal : next <= goal; return { ...flip, angle: past ? goal : next, spin: past ? 0 : way * speed, };}// The bat tapers, and where it meets the ball it// is moving at spin x distance from the pivot.export function offFlipper( ball: Ball, flip: Flip, side: Side,): Ball { const { x, y } = flippers[side]; const tip = tipOf(side, flip.angle); const near = touch( ball, [x, y], tip, BALL + pivotRadius, ); if (!near) return ball; const thick = pivotRadius + (tipRadius - pivotRadius) * near.t; const hit = touch( ball, [x, y], tip, BALL + thick, ); if (!hit) return ball; const sx = -flip.spin * (hit.y - y); const sy = flip.spin * (hit.x - x); return bounce(ball, hit, RUBBER_BOUNCE, sx, sy);}export function limit(ball: Ball): Ball { const speed = Math.hypot(ball.vx, ball.vy); if (speed <= TOP_SPEED) return ball; const slow = TOP_SPEED / speed; return { ...ball, vx: ball.vx * slow, vy: ball.vy * slow, };}export function fall( ball: Ball, h: number,): Ball { const keep = 1 - DRAG * h; const vx = ball.vx * keep; const vy = (ball.vy + GRAVITY * h) * keep; return { x: ball.x + vx * h, y: ball.y + vy * h, vx, vy, };}function offWalls(ball: Ball): Ball { let next = ball; for (const line of walls) line.slice(1).forEach((b, i) => { const a = line[i]; const hit = a && touch(next, a, b, BALL); if (hit) next = bounce(next, hit, WALL_BOUNCE); }); return next;}function cradled(table: Table) { return (['left', 'right'] as const).some( (side) => { const { x, y } = flippers[side]; const tip = tipOf(side, table[side].angle); const reach = BALL + pivotRadius + 2; const on = touch( table.ball, [x, y], tip, reach, ); return table[side].held && on; }, );}// A ball still for two seconds, and not held on// a flipper, gets a small push toward the middle,// as a real table's ball search does.export function search( table: Table, h: number,): Ball { const { ball, still } = table; const moved = Math.hypot( ball.x - still.x, ball.y - still.y, ); if (moved > BALL || cradled(table)) { table.still = { x: ball.x, y: ball.y, time: 0, }; return ball; } table.still = { ...still, time: still.time + h, }; if (table.still.time < SEARCH_AFTER) return ball; table.still = { x: ball.x, y: ball.y, time: 0 }; const way = Math.sign(MIDDLE - ball.x) || 1; return { ...ball, vx: ball.vx + way * SEARCH_PUSH, vy: ball.vy + SEARCH_PUSH / 2, };}// One small step of the whole table.export function step( table: Table, h: number, hits: Hit[],) { table.left = turn(table.left, 'left', h); table.right = turn(table.right, 'right', h); if (table.resting) { table.ball = onPlunger(table.pull); return; } let ball = offWalls(fall(table.ball, h)); const [gateA, gateB] = gate; const atGate = ball.vy > 0 && touch(ball, gateA, gateB, BALL); if (atGate) ball = bounce(ball, atGate, WALL_BOUNCE); const floor = lane.floor + table.pull * PLUNGER_TRAVEL; const { left, right } = lane; const tip = touch( ball, [left, floor], [right, floor], BALL, ); if (tip) ball = bounce(ball, tip, 0.2); for (const [a, b] of slings) { const hit = touch(ball, a, b, BALL); if (!hit) continue; ball = kick(ball, hit, SLING_KICK); hits.push({ kind: 'sling' }); } bumpers.forEach(({ x, y, r }, at) => { const cool = Math.max( 0, (table.cooling[at] ?? 0) - h, ); table.cooling[at] = cool; const hit = touchRound( ball, x, y, r + BALL, ); if (!hit) return; if (cool) { ball = bounce(ball, hit, WALL_BOUNCE); return; } table.cooling[at] = 0.08; ball = kick(ball, hit, BUMPER_KICK); hits.push({ kind: 'bumper', at }); }); ball = offFlipper(ball, table.left, 'left'); ball = offFlipper(ball, table.right, 'right'); table.ball = limit(ball); if (ball.x < left) table.ball = search(table, h); if (ball.y > DRAIN) { hits.push({ kind: 'drain' }); table.ball = onPlunger(); table.resting = true; } const inLane = ball.x > left && ball.y > floor - 20; const slow = Math.hypot(ball.vx, ball.vy) < 8; if (inLane && slow) table.resting = true;}// A longer pull shoots harder, never the same.export function launch(table: Table) { const power = table.pull; table.pulling = false; table.pull = 0; if (!table.resting) return; table.resting = false; table.ball = { ...onPlunger(), vy: -LAUNCH * power * (1 + give(0.03)), };}
/* The drawing is 240 x 340: the backglass, then the playfield down to the front at y 296. */.table { position: relative; container-type: inline-size; max-width: 22rem; aspect-ratio: 240 / 340; margin: 0 auto; background: 0 0 / 100% no-repeat url(/examples/ink/el-table-field.svg); font-family: 'Shantell Sans', sans-serif; font-weight: 700; user-select: none;}/* The three windows in the backglass. */.table output,.table .ball-in-play,.table[data-over='true']::before { position: absolute; top: 3.75cqw; height: 10.8cqw; display: grid; place-items: center; font-size: 3.6cqw;}.table .award,.table[data-over='true']::before { left: 4.2cqw; width: 25cqw;}.table[data-over='true']::before { content: 'GAME OVER'; background: #ffd84d; color: #2d2a24; border-radius: 3px;}/* The last award would show through the sign. */.table[data-over='true'] .award { visibility: hidden;}/* One digit to each of the six reels. */.table .score { right: 32.5cqw; margin-right: -0.43cqw; font-size: 9cqw; font-variant-numeric: tabular-nums; letter-spacing: 0.43cqw;}.table .ball-in-play { left: 70.8cqw; width: 25cqw;}.table svg { position: absolute; inset: 0; width: 100%; height: 100%;}/* On the plunger until the game moves it. */.table .ball { translate: 210px 277px;}.table .glow { position: absolute; width: 15%; aspect-ratio: 1; background: center / contain no-repeat url(/examples/ink/el-table-glow.svg); opacity: 0; pointer-events: none;}/* Each turns on its pivot: 58, 262 on the left, 158, 262 on the right. */.table .flipper { position: absolute; top: 75%; left: 21.25%; width: 23.54%; aspect-ratio: 56.5 / 14; background: center / contain no-repeat url(/examples/ink/el-table-flipper.svg); transform-origin: 12.39% 50%; rotate: 0.49rad;}.table .flipper.right { left: 62.92%; rotate: 2.6516rad;}.table button { position: absolute; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; touch-action: none;}.table :focus-visible { outline: 2px dashed currentColor; outline-offset: 2px;}/* The red buttons on the cabinet's sides. */.table .flip { top: 77%; width: max(2.75rem, 16%); aspect-ratio: 1; translate: 0 -50%;}.table .flip.left { left: 0;}.table .flip.right { right: 0;}/* Each button also reaches over its flipper, so pressing the flipper itself works it too. */.table .flip::before { content: ''; position: absolute; top: calc(50% - 10.8cqw); width: 25cqw; height: 23.4cqw;}.table .flip.left::before { left: 20cqw;}.table .flip.right::before { right: 30cqw;}/* Tip, spring, rod and knob, pulled back together. */.table .plunger { top: 82.35%; left: 55%; right: 0; bottom: 0; display: flex; align-items: flex-end; justify-content: space-between; padding-bottom: 4cqw;}.table .plunger::after { content: ''; position: absolute; top: 0; right: 0; width: 55.6%; aspect-ratio: 1; background: center / contain no-repeat url(/examples/ink/el-table-plunger.svg); translate: 0 calc(var(--pull, 0) * 5cqw);}
- To do: Pull the plunger back and let go: the longer you hold it, the harder it shoots. Then hit the ball with a flipper as it comes down. A hit scores +500.
- To do: Make a flipper hit worth more: in pinball.tsrx, change
scored(500)toscored(5000), then hit the ball again.
Connect a label to its input
A label has to know which input it belongs to. Put the same variable on both:
<label<label> · HTML elementThe name of a form field. for(property) for?: SingleIdrefValue={rain}>Rain</label<label> · HTML elementThe name of a form field.>
<input<input> · HTML elementA field a person types in or picks a value with. elel · Element bindingPoints an element() handle at this element, so handlers and attach can reach it.={rain} type(property) type?: string | undefined="range" />That connects them. You never write an id.
Press a word on the mixer, then move its slider with the arrow keys.
import { element, state } from '@markless/core';import { quiet, read, say } from './mixer.ts';export default function StudyStream() @{ const rain = element<HTMLInputElement>(); const cat = element<HTMLInputElement>(); const vinyl = element<HTMLInputElement>(); let mix = state(quiet); <section class="stream" onInput={() => (mix = read(rain, cat, vinyl))} > <i class="rain" data-level={mix.rain} /> <i class="cat" data-level={mix.cat} /> <i class="record" data-level={mix.vinyl} /> <label for={rain}>Rain</label> <input el={rain} type="range" value="0" /> <label for={cat}>Cat</label> <input el={cat} type="range" value="0" /> <label for={vinyl}>Vinyl</label> <input el={vinyl} type="range" value="0" /> <p class="playing">{say(mix)}</p> </section>}
type Fader = HTMLInputElement;export interface Mix { readonly rain: number; readonly cat: number; readonly vinyl: number;}export const quiet: Mix = { rain: 0, cat: 0, vinyl: 0,};// A fader's 0 to 100 as 0 (off) to 3 (loud).function levelOf(fader: Fader) { const value = fader.valueAsNumber; return Math.ceil(value / 34);}export function read( rain: Fader, cat: Fader, vinyl: Fader,): Mix { return { rain: levelOf(rain), cat: levelOf(cat), vinyl: levelOf(vinyl), };}const sounds = [ ['rain', 'rain on the window'], ['cat', 'a purring cat'], ['vinyl', 'vinyl crackle'],] as const;export function say(mix: Mix) { const on = sounds .filter(([name]) => mix[name] > 0) .map(([, words]) => words); const last = on.pop(); if (!last) return 'Quiet.'; if (!on.length) return `Playing: ${last}.`; return `Playing: ${on.join(', ')} and ${last}.`;}
/* The drawing is 240 x 236 units of --u: the room is 156 tall, then the mixer's three strips, each 80 wide. */.stream { --u: calc(100cqw / 240); container-type: inline-size; position: relative; display: grid; grid-template-columns: repeat(3, 1fr); background: 0 0 / 100% auto no-repeat url(/examples/ink/elements-label2-room1.svg); font-family: 'Shantell Sans', sans-serif; user-select: none;}/* The room and the faders' row. Safari leaves a row out of the height when all it holds is upright sliders, so this spans both. */.stream::before { content: ''; grid-area: 1 / 1 / 3 / -1; height: calc(206 * var(--u));}.stream::after,.stream .rain,.stream .cat,.stream .record,.stream .record::before { position: absolute; background: 0 0 / 100% no-repeat;}/* The record player's arm, over the record. */.stream::after { content: ''; top: calc(16 * var(--u)); left: calc(188 * var(--u)); width: calc(26 * var(--u)); height: calc(18 * var(--u)); background-image: url(/examples/ink/elements-label2-arm1.svg);}/* Rain on the glass, a tile repeated down it. */.stream .rain { top: calc(10 * var(--u)); left: calc(14 * var(--u)); width: calc(102 * var(--u)); height: calc(91 * var(--u)); background-size: 100% calc(88 * var(--u)); background-repeat: repeat-y;}.stream .rain[data-level='1'] { background-image: url(/examples/ink/elements-label2-rain1.svg);}.stream .rain[data-level='2'] { background-image: url(/examples/ink/elements-label2-rain2.svg);}.stream .rain[data-level='3'] { background-image: url(/examples/ink/elements-label2-rain3.svg);}/* Placed on the drawing, also when it is a label. */.stream .cat { grid-row: auto; margin: 0; top: calc(78 * var(--u)); left: calc(18 * var(--u)); width: calc(58 * var(--u)); height: calc(30 * var(--u)); background-image: url(/examples/ink/elements-label2-cat1.svg); transform-origin: 59% 87%;}/* Seen from the side: a disc squashed flat. */.stream .record { top: calc(10 * var(--u)); left: calc(166 * var(--u)); width: calc(36 * var(--u)); height: calc(36 * var(--u)); scale: 1 0.28;}.stream .record::before { content: ''; inset: 0; background-image: url(/examples/ink/elements-label2-disc1.svg);}/* Each name on its tape, its fader above. */.stream label { grid-row: 3; margin: 0 calc(10 * var(--u)); font-size: max(13px, calc(11 * var(--u))); font-weight: 700; line-height: calc(24 * var(--u)); text-align: center; cursor: pointer;}.stream label:has(+ input:focus) { text-decoration: underline wavy;}/* A column each: the room above spans every column, so nothing places itself. */.stream :is(label, input):nth-of-type(1) { grid-column: 1;}.stream :is(label, input):nth-of-type(2) { grid-column: 2;}.stream :is(label, input):nth-of-type(3) { grid-column: 3;}/* Upright faders, loud at the top. */.stream input { grid-row: 2; place-self: end center; width: calc(24 * var(--u)); height: calc(50 * var(--u)); margin: 0; appearance: none; writing-mode: vertical-lr; direction: rtl; background: none; cursor: grab;}.stream input:focus-visible { outline: 2px dashed; outline-offset: 0;}.stream input::-webkit-slider-thumb { width: calc(22 * var(--u)); height: calc(12 * var(--u)); appearance: none; border: 0; background: 0 0 / 100% no-repeat url(/examples/ink/elements-label2-fader.svg);}.stream input::-moz-range-thumb { width: calc(22 * var(--u)); height: calc(12 * var(--u)); border: 0; border-radius: 0; background: 0 0 / 100% no-repeat url(/examples/ink/elements-label2-fader.svg);}.stream .playing { grid-row: 4; grid-column: 1 / -1; margin: calc(8 * var(--u)) 0 0; font-weight: 700; text-align: center;}@media (prefers-reduced-motion: no-preference) { .stream .rain:not([data-level='0']) { animation: stream-rain 1.1s linear infinite; } .stream .rain[data-level='3'] { animation-duration: 0.6s; } .stream .cat:not([data-level='0']) { animation: stream-purr 2.6s infinite; } .stream .cat[data-level='2'] { animation-duration: 1.9s; } .stream .cat[data-level='3'] { animation-duration: 1.3s; } /* 33 turns a minute: one turn in 1.8 s. */ .stream .record:not([data-level='0'])::before { animation: stream-spin 1.8s linear infinite; }}@keyframes stream-rain { to { background-position-y: calc(88 * var(--u)); }}@keyframes stream-purr { 50% { scale: 1.03 1.09; }}@keyframes stream-spin { to { rotate: 1turn; }}
Quiet.
- To do: Press the word Cat, then hold the up arrow. Her cat starts to purr.
- To do: Make the cat a label too: in study-stream.tsrx, change
<i class="cat"to<label class="cat" for={cat}, then press the cat.
Get every element in a list
An @for@for · ListShows its block once per item. It needs a key. makes many elements. To get all of them, add [] to the type:
const fansconst fans: any = elementelement · Element handleCreates a handle that el={…} points at an element. In handlers and attach the handle is that element, or undefined while it is not on the page.<HTMLButtonElementinterface HTMLButtonElementThe HTMLButtonElement interface provides properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating button elements.[]>();
@for@for · ListShows its block once per item. It needs a key. (const fanconst fan: any of crowd; key fan.seat) {
<button<button> · HTML elementA button a person can press. elel · Element bindingPoints an element() handle at this element, so handlers and attach can reach it.={fans} />
}Now fans is an array of every button, in the order they are on the page.
Tap any fan to start a wave.
import { element, state } from '@markless/core';import { crowd } from './crowd.ts';import { wave } from './wave.ts';export default function Stand() @{ const fans = element<HTMLButtonElement[]>(); let starter = state('Nobody'); function cheer(seat: number, name: string) { wave(fans, seat); starter = name; } <section class="stand"> <div class="seats"> @for (const fan of crowd; key fan.seat) { <button el={fans} class="fan" style={fan.look} aria-label={fan.name} onClick={() => cheer(fan.seat, fan.name)} /> } </div> <p class="said"> {starter} started the wave. </p> </section>}
// Sit, rise, arms up, hold it, rise, sit.const poses = [ '0%', '50%', '100%', '100%', '50%', '0%',];const stand = poses.map((pose) => ({ backgroundPositionX: pose,}));const still = '(prefers-reduced-motion: reduce)';export function wave( fans: HTMLElement[], from: number,) { if (matchMedia(still).matches) return; fans.forEach((fan, i) => fan.animate(stand, { duration: 480, delay: Math.abs(i - from) * 70, easing: 'steps(6, jump-none)', }), );}
// In seat order: each column of the stand,// back row first, from left to right.const names = [ 'Amara', 'Kenji', 'Sofía', 'Tomasz', 'Priya', 'Mehmet', 'Fatima', 'Lars', 'Nkechi', 'Mateus', 'Mei', 'Diego',];export const crowd = names.map((name, seat) => ({ seat, name, look: `--fan: ${seat}`,}));
.stand { max-width: 26rem; margin: 0 auto; font-family: 'Shantell Sans', sans-serif;}.stand::before { content: ''; display: block; aspect-ratio: 360 / 46; background: url(/examples/ink/el-wave-roof.svg) 0 0 / 100% 100%;}.stand .seats { position: relative; display: grid; grid-template-columns: repeat(6, 1fr); grid-template-rows: repeat(2, auto); grid-auto-flow: column; padding-bottom: calc(100% * 50 / 360); background: url(/examples/ink/el-wave-steps.svg) 0 0 / 100% auto no-repeat, url(/examples/ink/el-wave-pitch.svg) 0 100% / 100% auto no-repeat;}/* The tier walls sit in front of every fan. */.stand .seats::after { content: ''; position: absolute; inset: 0 0 calc(100% * 50 / 360); background: url(/examples/ink/el-wave-walls.svg) 0 0 / 100% 100%; pointer-events: none;}.stand .fan { aspect-ratio: 60 / 110; padding: 0; border: 0; background: url(/examples/ink/el-wave-fans.svg) 0 0 / 300% 1200%; background-position: 0 calc(var(--fan) * 100% / 11); cursor: pointer; touch-action: manipulation;}.stand .fan:focus-visible { outline: 2px dashed currentColor; outline-offset: -3px;}.stand .said { margin: 0.5rem 0 0; text-align: center;}
Nobody started the wave.
- To do: Tap Diego, the last fan in the front row. The wave rolls all the way to the other end.
- To do: Make the wave slower: in wave.ts, change
70to200, then tap a fan in the middle.
What if code needs the element as soon as it appears?
Give the element attach and a function. Markless calls it with the element the first time the element is used: an event on it or inside it, onVisible, or onIdle. An element an @if@if · ConditionalShows its block while the test is true. shows later gets it straight away. Return a function, and Markless calls that one when the element leaves the page.
<canvas<canvas> · HTML elementA surface your code draws pixels on. attachattach · Element setupRuns your function with this element, for setup like an observer. A function it returns runs when the element leaves the page. On an element that was already rendered in the page, it waits until a handler on the element runs, or onVisible or onIdle fires.={(canvas(parameter) canvas: HTMLCanvasElement) => drawChartimport drawChart(canvas)} onVisibleonVisible · Visibility handlerRuns once, the first time this element scrolls into view.={() => {}} />Coming from React?
element()isuseRefwithout.current:fieldis the element itself.- No
?.unless the element can be missing: an element that is always on the page is nevernull. - Write
el={field}where React writesref={field}. - There is no
forwardRef. Pass the variable as an ordinary prop. - There is no
useId. Put the variable infororaria-describedbyand Markless writes the id.
Next, split a page into components.
Button sounds are from Josh Comeau's Button Sounds library.