Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

Showcase

A game and a flock, run by Roc

Ordinary components, rendered by the server and hydrated in your browser, that also run on time. Each animation frame calls a Roc handler that moves things. Only the holes that read what moved run again, patching the few attributes that changed.

Snake#

Click the board, then steer with the arrows or WASD. Space pauses, M mutes, Tab leaves. Easy, Medium and Hard keep one speed; on Impossible, every fruit speeds the snake up.

Score0 Best0 Length4 Speed6.7cells/s
Level

Snake, in Roc

Eat, grow, and don't bite yourself.

↑←↓→ or WASD

Click to play

Space pauses · M mutes

Roc is idle until you start: no frames run while the game waits.

A flock of Roc birds#

Type a number of birds, or use −5, −1, +1 and +5: new ones fly in, or the newest leave. Each bounces off the walls and the others, and squeaks when it bumps into one (once you've clicked the page: browsers keep pages quiet until then).

birds · 0 bounces

Measuring…

The line under each demo is measured live: a frame's time covers the handler that moves and collides the birds, the holes that read the flock, and their patches.

How they work#

Time is a handler

on:frame.ms={|ms| send!(Frame(ms))} runs its handler every animation frame, given the milliseconds since the last, while its element is on the page. The snake's sits inside an if that holds only while you play, so a paused game, like an empty sky, runs no frames.

Keys that do one thing

on:keydown.ArrowUp={|| send!(Turn(Up))} runs for that key only and stops it scrolling the page. Other keys, Tab among them, work as usual.

Rows that stay, so little changes

The birds are .map rows keyed by id, so each keeps its element; a move sets two custom properties the stylesheet turns into a translation. The snake's segments are rows by position (.map_with_index(|part, i| … key={i})): each step, a segment takes the cell ahead, and a one-step CSS transition slides it there.

Pure, so it replays

The rules are a plain function, update: last game and your move in, next game out, kept in a signal. Roc has no hidden randomness: the food's next place and a new bird's heading come from a seed in the game (Demos/Random.roc). The same moves give the same game, and every rule is an expect away from a test.

What isn't shown isn't read

The snake moves a cell per step's worth of frames. The time since its last move is a signal nothing reads, so a frame that only adds to it runs no hole and patches nothing.

The snake: site/Demos/Snake.rocx
site/Demos/Snake.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
import audio.Audio
import Random

## Snake. Arrow keys or WASD steer, Space pauses, M mutes. Four levels: Easy, Medium and Hard each
## keep one speed; on Impossible, every fruit makes the snake faster. Roc runs the game: the game is a signal,
## and `update` (pure, tested by `roc test`) makes the next one from what the player did. Every
## frame adds the time that passed to another signal, which nothing on the page reads, so a frame
## patches nothing until a step's worth has passed, and the snake moves one cell. A step's sound is
## part of the next game too (`update` can't play it); the handler plays it, with `Audio.play!`.
Snake := [].{
	Cell : { x : I64, y : I64 }
	Part : { x : I64, y : I64, id : U64 }
	Direction : [Up, Down, Left, Right]
	Phase : [Ready, Playing, Paused, Over]
	Level : [Easy, Medium, Hard, Impossible]

	## The best score on each level, kept from game to game.
	Bests : { easy : U64, medium : U64, hard : U64, impossible : U64 }
	Model : {
		body : List(Part),
		heading : Direction,
		turns : List(Direction),
		food : Cell,
		phase : Phase,
		score : U64,
		bests : Bests,
		level : Level,
		step : F64,
		seed : U64,
		next : U64,

		## The sound the last step made: the name of its file in site/static/sounds, or "" for none.
		sound : Str,
		muted : Bool,
	}
	Msg : [Turn(Direction), Toggle, Click, Mute, Pick(Level)]

	## The game, ready to start; `seed` says where the food goes.
	view! : { seed : U64 } => Html
	view! = |{ seed }| {
		(game!, set_game!) = create_signal!(Snake.init(seed))
		(waited!, set_waited!) = create_signal!(0.0)
		# The game goes on to `next`, and plays the sound that step made, unless it is muted.
		go! = |next| {
			set_game!(next)
			if (!next.muted and !next.sound.is_empty()) Audio.play!("/sounds/${next.sound}.wav") else {}
		}
		send! = |msg| go!(Snake.update(game!(), msg))
		frame! = |ms| {
			next = advance(game!(), waited!(), ms)
			set_waited!(next.waited)
			if (next.moved) go!(next.model) else {}
		}
		<div
			class="snake"
			on:keydown.ArrowUp={|| send!(Turn(Up))}
			on:keydown.ArrowDown={|| send!(Turn(Down))}
			on:keydown.ArrowLeft={|| send!(Turn(Left))}
			on:keydown.ArrowRight={|| send!(Turn(Right))}
			on:keydown.w={|| send!(Turn(Up))}
			on:keydown.s={|| send!(Turn(Down))}
			on:keydown.a={|| send!(Turn(Left))}
			on:keydown.d={|| send!(Turn(Right))}
			on:keydown.Space={|| send!(Toggle)}
			on:keydown.p={|| send!(Toggle)}
			on:keydown.m={|| send!(Mute)}
		>
			<div class="snake-bar">
				<span class="snake-stat"><small>Score</small><b>{game!().score.to_str()}</b></span>
				<span class="snake-stat"><small>Best</small><b>{best(game!()).to_str()}</b></span>
				<span class="snake-stat"><small>Length</small><b>{game!().body.len().to_str()}</b></span>
				<span class="snake-stat"><small>Speed</small><b>{speed(game!().step)}</b><span class="snake-unit">cells/s</span></span>
				<button type="button" class="snake-mute" on:click={|| send!(Mute)} aria-pressed={if (game!().muted) "true" else "false"}>{if (game!().muted) "Sound off" else "Sound on"}</button>
			</div>
			<div class="snake-levels" role="group" aria-label="Level">
				<small>Level</small>
				{...levels.map_with_index(|level, i|
					<button key={i}
						type="button"
						aria-pressed={if (game!().level == level) "true" else "false"}
						on:click={|| send!(Pick(level))}
					>
						{level_name(level)}
					</button>
				)}
			</div>
			<div
				class="board"
				class:playing={game!().phase == Playing}
				class:paused={game!().phase == Paused}
				class:over={game!().phase == Over}
				style:--step={step_ms(game!().step)}
				tabindex="0"
				aria-label="The board: arrow keys or WASD steer, Space pauses"
				on:click={|| send!(Click)}
			>
				{# A row per place along the snake: when it moves, each slides into the cell of the one ahead
				   of it (a CSS transition as long as a step), and eating adds a row at the tail. }
				<div class="board-snake" style:--n={game!().body.len().to_str()}>
					{...game!().body.map_with_index(|part, index|
						<i key={index}
							class={part_class(index == 0, game!().heading)}
							style:--x={part.x.to_str()}
							style:--y={part.y.to_str()}
							style:--i={index.to_str()}
						></i>
					)}
				</div>
				{# The food, keyed by where it is: a new place is a new element, which pops in. }
				{...[game!().food].map(|cell|
					<i key={"${cell.x.to_str()},${cell.y.to_str()}"} class="food" style:--x={cell.x.to_str()} style:--y={cell.y.to_str()}></i>
				)}
				{if (game!().phase != Playing) <>{message(game!())}</>}
			</div>
			<div class="pad" aria-label="Steer">
				<button type="button" class="pad-up" on:click={|| send!(Turn(Up))} aria-label="Up">▲</button>
				<button type="button" class="pad-left" on:click={|| send!(Turn(Left))} aria-label="Left">◀</button>
				<button type="button" class="pad-toggle" on:click={|| send!(Toggle)}>{if (game!().phase == Playing) "Pause" else "Play"}</button>
				<button type="button" class="pad-right" on:click={|| send!(Turn(Right))} aria-label="Right">▶</button>
				<button type="button" class="pad-down" on:click={|| send!(Turn(Down))} aria-label="Down">▼</button>
			</div>
			<div class="effects" hidden>
				{# While the game runs, this element takes the frames; paused or over, there is none, and
				   so no frames: time stands still. }
				{if game!().phase == Playing {
					<i on:frame.ms={frame!}></i>
				}}
			</div>
		</div>
	}

	init : U64 -> Model
	init = |seed| fresh(seed, no_bests, Medium, Bool.False)

	update : Model, Msg -> Model
	update = |last, msg| {
		# A step makes its own sound, if any: the last one's doesn't carry over.
		model = { ..last, sound: "" }
		match msg {
			Turn(direction) =>
				match model.phase {
					Playing => turn(model, direction)
					Over => model
					_ => start(turn(model, direction))
				}
			Toggle =>
				match model.phase {
					Playing => { ..model, phase: Paused }
					Over => start(again(model, model.level))
					_ => start(model)
				}
			Click =>
				match model.phase {
					Playing => model
					Over => start(again(model, model.level))
					_ => start(model)
				}
			Mute => { ..model, muted: !model.muted }
			# Another level starts over, ready, at its speed (the one it is already ready at stays).
			Pick(level) => if (level == model.level and model.phase == Ready) model else again(model, level)
		}
	}

	<style>
		/* The game's own colours: a violet snake on a dark floor, and a golden fruit. */
		.snake {
			--game-bg: #110e22;
			--game-bg-glow: #241c46;
			--game-check: rgb(255 255 255 / 0.028);
			--game-text: #f1ecff;
			--game-danger: #ff6b81;
			--snake: #8c52ff;
			--snake-head: #c9b0ff;
			--snake-tail: #3d2680;
			--food: #f5b942;
			--food-light: #fff1c9;
			--leaf: #5fd38d;
			display: grid;
			gap: var(--space-3);
		}

		.snake-bar {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: var(--space-2) var(--space-5);
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		.snake-stat {
			display: inline-flex;
			align-items: baseline;
			gap: var(--space-2);
			padding: var(--space-1) var(--space-3);
			border-radius: var(--pill);
			background: var(--bg-sunken);
		}

		.snake-stat > small,
		.snake-levels > small {
			color: var(--text-faint);
			font-size: var(--size-2xs);
			font-weight: 600;
			letter-spacing: 0.06em;
			text-transform: uppercase;
		}

		.snake-stat b {
			color: var(--text);
			font-variant-numeric: tabular-nums;
		}

		.snake-unit {
			margin-left: -0.2rem;
			color: var(--text-muted);
			font-size: var(--size-xs);
		}

		.snake-mute {
			margin-left: auto;
			padding: var(--space-1) var(--space-3);
			font-size: var(--size-sm);
		}

		.snake-mute[aria-pressed="true"] {
			color: var(--text-faint);
		}

		/* The levels: a row of pills, the one played lit in the snake's colour. */
		.snake-levels {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: var(--space-2);
		}

		.snake-levels > small {
			margin-right: var(--space-1);
		}

		.snake-levels button {
			padding: var(--space-1) var(--space-3);
			border-radius: var(--pill);
			color: var(--text-muted);
			font-size: var(--size-sm);
			font-weight: 500;
		}

		.snake-levels button[aria-pressed="true"] {
			background: color-mix(in srgb, var(--snake) 32%, transparent);
			box-shadow: 0 0 14px -4px var(--snake);
			color: var(--text);
			font-weight: 600;
		}

		/* The board is 24 by 15 cells; a cell is a 24th of its width, in container units. A checkered
		   floor, lit from the middle; a ring of light while a game runs, and a shake when it ends. */
		.board {
			--cell: calc(100cqw / 24);
			position: relative;
			aspect-ratio: 24 / 15;
			container-type: inline-size;
			overflow: hidden;
			border-radius: var(--radius-lg);
			background:
				repeating-conic-gradient(var(--game-check) 0 25%, transparent 0 50%) 0 0 / calc(200% / 24) calc(200% / 15),
				radial-gradient(ellipse 80% 70% at 50% 45%, var(--game-bg-glow), var(--game-bg));
			box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.06), inset 0 0 60px rgb(0 0 0 / 0.45);
			cursor: pointer;
			transition: box-shadow 0.4s;
		}

		.board.playing {
			box-shadow:
				inset 0 0 0 1px color-mix(in srgb, var(--snake) 45%, transparent),
				inset 0 0 60px rgb(0 0 0 / 0.45),
				0 0 36px -10px var(--snake);
		}

		.board.over {
			animation: board-shake 0.45s;
		}

		@keyframes board-shake {
			20% {
				translate: -7px 0;
			}

			40% {
				translate: 6px 0;
			}

			60% {
				translate: -4px 0;
			}

			80% {
				translate: 2px 0;
			}
		}

		.board:focus-visible {
			outline: 3px solid var(--accent);
			outline-offset: 3px;
		}

		/* A place is a cell of the board: `--x` 24ths of its width across, `--y` 15ths of its height down.
		   In percentages, not the board's container units, which Firefox works out only once the board
		   is laid out (the snake would slide in from the corner on every load). And with left and top,
		   not translate: a translate slides on the compositor, and when a step starts the next slide
		   before the last has ended, the browser may start it from where the page last thought the
		   part was, behind where it was drawn, so the snake jerks back. */
		.part,
		.food {
			position: absolute;
			top: calc(var(--y) * 100% / 15);
			left: calc(var(--x) * 100% / 24);
			width: var(--cell);
			height: var(--cell);
		}

		/* A segment per place along the snake (--i from the head, --n of them): it slides into the next
		   cell over a step, and fades from the head's colour to the tail's. */
		.part {
			border-radius: 30%;
			background: color-mix(in oklab, var(--snake) calc(100% - var(--i) * 70% / var(--n)), var(--snake-tail));
			box-shadow: 0 0 calc(var(--cell) * 0.3) color-mix(in srgb, var(--snake) 35%, transparent);
			scale: calc(0.94 - var(--i) * 0.2 / var(--n));
			transition:
				left var(--step, 150ms) linear,
				top var(--step, 150ms) linear;
		}

		.part.head {
			z-index: 1;
			border-radius: 38%;
			background: radial-gradient(circle at 35% 30%, #fff 0, var(--snake-head) 35%, var(--snake) 100%);
			box-shadow: 0 0 calc(var(--cell) * 0.7) color-mix(in srgb, var(--snake-head) 65%, transparent);
			scale: 1.06;
		}

		/* Eyes, white with a pupil, looking where the snake goes. */
		.part.head::before,
		.part.head::after {
			content: "";
			position: absolute;
			width: 26%;
			height: 26%;
			border-radius: 50%;
			background: radial-gradient(circle, var(--game-bg) 0 42%, #fff 46%);
		}

		.part.head.right::before {
			top: 16%;
			right: 14%;
		}

		.part.head.right::after {
			right: 14%;
			bottom: 16%;
		}

		.part.head.left::before {
			top: 16%;
			left: 14%;
		}

		.part.head.left::after {
			bottom: 16%;
			left: 14%;
		}

		.part.head.up::before {
			top: 14%;
			left: 16%;
		}

		.part.head.up::after {
			top: 14%;
			right: 16%;
		}

		.part.head.down::before {
			bottom: 14%;
			left: 16%;
		}

		.part.head.down::after {
			right: 16%;
			bottom: 14%;
		}

		.board.over .part {
			background: color-mix(in oklab, var(--game-danger) calc(70% - var(--i) * 50% / var(--n)), var(--game-bg-glow));
			box-shadow: none;
		}

		.board.over .part.head {
			background: var(--game-danger);
		}

		/* The food: a glowing fruit with a leaf, which pops in where it lands. */
		.food {
			animation: food-in 0.4s cubic-bezier(0.3, 1.7, 0.5, 1);
		}

		.food::before {
			content: "";
			position: absolute;
			inset: 18%;
			border-radius: 50%;
			background: radial-gradient(circle at 35% 30%, var(--food-light), var(--food) 45%, #c4790f);
			box-shadow: 0 0 calc(var(--cell) * 0.7) var(--food);
			animation: glow 0.9s ease-in-out infinite alternate;
		}

		.food::after {
			content: "";
			position: absolute;
			top: 6%;
			left: 52%;
			width: 26%;
			height: 16%;
			border-radius: 100% 0;
			background: var(--leaf);
			rotate: -25deg;
		}

		@keyframes food-in {
			from {
				scale: 0;
			}
		}

		@keyframes glow {
			to {
				scale: 0.85;
				opacity: 0.85;
			}
		}

		/* What the board says when the game isn't running, above the snake, on a dimmed, blurred board:
		   `message` makes it, outside the block, so it is global here, under the board. */
		.board :global(.board-message) {
			position: absolute;
			inset: 0;
			z-index: 2;
			display: grid;
			place-content: center;
			justify-items: center;
			gap: var(--space-2);
			padding: var(--space-4);
			background: radial-gradient(ellipse at center, rgb(10 8 22 / 0.55), rgb(10 8 22 / 0.82));
			backdrop-filter: blur(3px);
			color: var(--game-text);
			text-align: center;
		}

		.board :global(.board-message p) {
			margin: 0;
		}

		.board :global(.board-title) {
			background: linear-gradient(100deg, var(--snake-head), var(--food));
			-webkit-background-clip: text;
			background-clip: text;
			color: transparent;
			font: 800 clamp(1.5rem, 6.5cqw, 3rem) / 1.1 var(--font);
			letter-spacing: -0.03em;
		}

		.over :global(.board-title) {
			background-image: linear-gradient(100deg, var(--game-danger), var(--food));
		}

		.board :global(.board-lede) {
			color: rgb(241 236 255 / 0.8);
		}

		.board :global(.board-score) {
			font-size: var(--size-lg);
		}

		.board :global(.board-score b) {
			font-size: var(--size-xl);
			font-variant-numeric: tabular-nums;
		}

		.board :global(.board-best) {
			padding: 0.15rem var(--space-2);
			border-radius: var(--pill);
			background: color-mix(in srgb, var(--food) 22%, transparent);
			color: var(--food);
			font-size: var(--size-xs);
			font-weight: 700;
		}

		.board :global(.board-keys) {
			display: flex;
			align-items: center;
			gap: var(--space-1);
			color: rgb(241 236 255 / 0.65);
			font-size: var(--size-sm);
		}

		.board :global(.board-keys span) {
			margin: 0 var(--space-1);
		}

		.board :global(.board-message kbd) {
			display: inline-grid;
			place-items: center;
			min-width: 1.7em;
			height: 1.7em;
			padding: 0 0.35em;
			border: 1px solid rgb(255 255 255 / 0.22);
			border-bottom-width: 2px;
			border-radius: var(--radius-sm);
			background: rgb(255 255 255 / 0.07);
			color: var(--game-text);
			font: 600 var(--size-xs) / 1 var(--mono);
		}

		.board :global(.board-cta) {
			margin-top: var(--space-1);
			padding: var(--space-2) var(--space-5);
			border-radius: var(--pill);
			background: var(--snake);
			box-shadow: 0 6px 20px -6px var(--snake);
			color: #fff;
			font-weight: 700;
			animation: cta 1.6s ease-in-out infinite;
		}

		@keyframes cta {
			50% {
				scale: 1.05;
				box-shadow: 0 8px 28px -6px var(--snake);
			}
		}

		.board :global(.board-hint) {
			color: rgb(241 236 255 / 0.6);
			font-size: var(--size-xs);
		}

		.pad {
			display: grid;
			grid-template-columns: repeat(3, 3rem);
			grid-template-areas: ". up ." "left toggle right" ". down .";
			justify-content: center;
			gap: var(--space-1);
		}

		.pad button {
			height: 2.5rem;
			padding: 0;
			font-size: var(--size-sm);
		}

		.pad-up {
			grid-area: up;
		}

		.pad-left {
			grid-area: left;
		}

		.pad-toggle {
			grid-area: toggle;
		}

		.pad-right {
			grid-area: right;
		}

		.pad-down {
			grid-area: down;
		}

		@media (prefers-reduced-motion: reduce) {
			.part {
				transition: none;
			}

			.board.over,
			.food,
			.food::before,
			.board :global(.board-cta) {
				animation: none;
			}
		}
	</style>
}

columns : I64
columns = 24

rows : I64
rows = 15

## How many cells the board has: `columns` times `rows`.
cells : U64
cells = 360

## A new game on `level`: a snake of four in the middle, heading right, and food somewhere. The best
## scores, the sound setting and the random numbers go on from the last game.
fresh : U64, Snake.Bests, Snake.Level, Bool -> Snake.Model
fresh = |seed, bests, level, muted| {
	body = [{ x: 9, y: 7, id: 3 }, { x: 8, y: 7, id: 2 }, { x: 7, y: 7, id: 1 }, { x: 6, y: 7, id: 0 }]
	placed = place(seed, body)
	{
		body,
		heading: Right,
		turns: [],
		food: placed.cell,
		phase: Ready,
		score: 0,
		bests,
		level,
		step: first_step(level),
		seed: placed.seed,
		next: 4,
		sound: "",
		muted,
	}
}

## Another game after `model`, on `level`, ready to start.
again : Snake.Model, Snake.Level -> Snake.Model
again = |model, level| fresh(model.seed, model.bests, level, model.muted)

start : Snake.Model -> Snake.Model
start = |model| { ..model, phase: Playing, sound: "start" }

## A turn waits its turn: up to two are kept, so a quick double turn isn't lost, and none may go
## straight back into the snake.
turn : Snake.Model, Snake.Direction -> Snake.Model
turn = |model, direction| {
	last = model.turns.last() ?? model.heading
	if (direction == last or direction == opposite(last) or model.turns.len() >= 2) model else { ..model, turns: model.turns.append(direction) }
}

opposite : Snake.Direction -> Snake.Direction
opposite = |direction|
	match direction {
		Up => Down
		Down => Up
		Left => Right
		Right => Left
	}

## A frame: `ms` more since the snake last moved, after `waited`. Once a step's worth has passed,
## it moves one cell.
advance : Snake.Model, F64, F64 -> { model : Snake.Model, waited : F64, moved : Bool }
advance = |model, waited, ms|
	if model.phase != Playing {
		{ model, waited, moved: Bool.False }
	} else if waited + ms < model.step {
		{ model, waited: waited + ms, moved: Bool.False }
	} else {
		{ model: move(model), waited: F64.min(waited + ms - model.step, model.step), moved: Bool.True }
	}

move : Snake.Model -> Snake.Model
move = |model| {
	heading = model.turns.first() ?? model.heading
	turns = model.turns.drop_first(1)
	head = model.body.first() ?? { x: 0, y: 0, id: 0 }
	ahead = step_from(head, heading)
	eats = ahead.x == model.food.x and ahead.y == model.food.y
	# Unless it eats, the tail moves on as the head does, so the head may take its cell.
	rest = if (eats) model.body else model.body.drop_last(1)
	crashed = ahead.x < 0 or ahead.x >= columns or ahead.y < 0 or ahead.y >= rows or rest.any(|part| part.x == ahead.x and part.y == ahead.y)
	if crashed {
		{ ..model, heading, turns, phase: Over, sound: "die" }
	} else {
		body = [{ x: ahead.x, y: ahead.y, id: model.next }].concat(rest)
		moved = { ..model, body, heading, turns, next: model.next + 1, sound: "" }
		if eats {
			score = model.score + 1
			placed = place(model.seed, body)
			tone = if (score % 5 == 0) "level" else "eat"
			# The best moves with the score, as it is beaten, not once the game is over.
			{ ..moved, score, bests: with_best(model.bests, model.level, score), food: placed.cell, seed: placed.seed, step: next_step(model.level, model.step), sound: tone }
		} else {
			moved
		}
	}
}

step_from : Snake.Part, Snake.Direction -> Snake.Cell
step_from = |part, direction|
	match direction {
		Up => { x: part.x, y: part.y - 1 }
		Down => { x: part.x, y: part.y + 1 }
		Left => { x: part.x - 1, y: part.y }
		Right => { x: part.x + 1, y: part.y }
	}

## Food on a free cell: a few random tries, then the first free one.
place : U64, List(Snake.Part) -> { cell : Snake.Cell, seed : U64 }
place = |seed, body| {
	free = |cell| !body.any(|part| part.x == cell.x and part.y == cell.y)
	var $seed = seed
	var $cell = { x: 0.I64, y: 0.I64 }
	var $found = Bool.False
	var $tries = 0.U64
	while $tries < 40 and !$found {
		picked = Random.below($seed, cells)
		$seed = picked.seed
		index = picked.value.to_i64_wrap()
		$cell = { x: index % columns, y: index // columns }
		$found = free($cell)
		$tries = $tries + 1
	}
	var $index = 0.I64
	while !$found and $index < columns * rows {
		$cell = { x: $index % columns, y: $index // columns }
		$found = free($cell)
		$index = $index + 1
	}
	{ cell: $cell, seed: $seed }
}

levels : List(Snake.Level)
levels = [Easy, Medium, Hard, Impossible]

level_name : Snake.Level -> Str
level_name = |level|
	match level {
		Easy => "Easy"
		Medium => "Medium"
		Hard => "Hard"
		Impossible => "Impossible"
	}

## How long a step takes when a game starts: 5 cells a second on Easy, 6.7 on Medium, 10 on Hard and,
## at first, on Impossible.
first_step : Snake.Level -> F64
first_step = |level|
	match level {
		Easy => 200.0
		Medium => 150.0
		Hard => 100.0
		Impossible => 100.0
	}

## The step after a fruit is eaten: the same, but on Impossible, 5 ms shorter, down to 50 ms (20 cells
## a second).
next_step : Snake.Level, F64 -> F64
next_step = |level, step|
	match level {
		Impossible => F64.max(50.0, step - 5.0)
		_ => step
	}

no_bests : Snake.Bests
no_bests = { easy: 0, medium: 0, hard: 0, impossible: 0 }

## The best score on the game's level.
best : Snake.Model -> U64
best = |model|
	match model.level {
		Easy => model.bests.easy
		Medium => model.bests.medium
		Hard => model.bests.hard
		Impossible => model.bests.impossible
	}

## The bests, with `score` the best on `level` if it beats it.
with_best : Snake.Bests, Snake.Level, U64 -> Snake.Bests
with_best = |bests, level, score|
	match level {
		Easy => { ..bests, easy: U64.max(bests.easy, score) }
		Medium => { ..bests, medium: U64.max(bests.medium, score) }
		Hard => { ..bests, hard: U64.max(bests.hard, score) }
		Impossible => { ..bests, impossible: U64.max(bests.impossible, score) }
	}

## A part of the snake's classes: the head's say where it looks.
part_class : Bool, Snake.Direction -> Str
part_class = |head, heading| if (head) "part head ${direction_name(heading)}" else "part"

direction_name : Snake.Direction -> Str
direction_name = |direction|
	match direction {
		Up => "up"
		Down => "down"
		Left => "left"
		Right => "right"
	}

## How long a step takes, for the transition that slides the snake along: `150ms`.
step_ms : F64 -> Str
step_ms = |step| "${(step.round_to_i64_try() ?? 150).to_str()}ms"

message : Snake.Model -> Html
message = |model|
	match model.phase {
		Playing => <></>
		Ready =>
			<div class="board-message">
				<p class="board-title">Snake, in Roc</p>
				<p class="board-lede">Eat, grow, and don't bite yourself.</p>
				<p class="board-keys">
					<kbd>↑</kbd><kbd>←</kbd><kbd>↓</kbd><kbd>→</kbd>
					<span>or</span>
					<kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd>
				</p>
				<p class="board-cta">Click to play</p>
				<p class="board-hint"><kbd>Space</kbd> pauses · <kbd>M</kbd> mutes</p>
			</div>
		Paused =>
			<div class="board-message">
				<p class="board-title">Paused</p>
				<p class="board-cta">Click to go on</p>
				<p class="board-hint"><kbd>Space</kbd> works too</p>
			</div>
		Over =>
			<div class="board-message">
				<p class="board-title">Game over</p>
				<p class="board-score"><b>{model.score.to_str()}</b> {if (model.score == 1) "point" else "points"}</p>
				{if (model.score > 0 and model.score >= best(model)) <p class="board-best">Your best yet</p>}
				<p class="board-cta">Click to play again</p>
				<p class="board-hint"><kbd>Space</kbd> works too</p>
			</div>
	}

speed : F64 -> Str
speed = |step| {
	tenths = (10000.0 / step).round_to_i64_try() ?? 0
	"${(tenths // 10).to_str()}.${(tenths % 10).to_str()}"
}

expect Snake.init(7).phase == Ready
expect Snake.update(Snake.init(7), Toggle).phase == Playing
expect {
	moving = Snake.update(Snake.init(7), Toggle)
	first = advance(moving, 0.0, 100.0)
	second = advance(first.model, first.waited, 60.0)
	!first.moved and second.moved and (second.model.body.first() ?? { x: 0, y: 0, id: 0 }).x == 10 and second.model.body.len() == 4
}
# Straight back into itself isn't a turn.
expect Snake.update(Snake.update(Snake.init(7), Toggle), Turn(Left)).turns == []
expect speed(150.0) == "6.7"
# A fruit right ahead: eaten on the first step, the best goes up with the score, and only on
# Impossible does the snake get faster.
expect {
	ahead = |level| {
		ready = { ..fresh(7, no_bests, level, Bool.False), food: { x: 10, y: 7 } }
		advance(Snake.update(ready, Toggle), 0.0, first_step(level)).model
	}
	medium = ahead(Medium)
	impossible = ahead(Impossible)
	medium.score == 1 and best(medium) == 1 and step_ms(medium.step) == "150ms" and best(impossible) == 1 and step_ms(impossible.step) == "95ms" and medium.sound == "eat"
}
# A step's sound is its own: starting makes one, and the steps after it make none unless they eat.
expect {
	playing = Snake.update(Snake.init(7), Toggle)
	moved = advance(playing, 0.0, 150.0)
	playing.sound == "start" and Snake.update(playing, Turn(Up)).sound == "" and moved.moved and moved.model.sound == ""
}
expect step_ms(next_step(Impossible, 50.0)) == "50ms" and step_ms(next_step(Easy, 200.0)) == "200ms"
# Another level starts over, ready, keeping each level's best; the same one, ready, changes nothing.
expect {
	playing = Snake.update(Snake.init(7), Toggle)
	picked = Snake.update({ ..playing, bests: { ..no_bests, medium: 3 } }, Pick(Easy))
	again_picked = Snake.update(picked, Pick(Easy))
	picked.phase == Ready and picked.level == Easy and step_ms(picked.step) == "200ms" and best(picked) == 0 and picked.bests.medium == 3 and again_picked.food == picked.food and again_picked.seed == picked.seed
}
expect step_ms(70.0) == "70ms"
The flock: site/Demos/Birds.rocx
site/Demos/Birds.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
import audio.Audio
import Random

## A flock of Roc birds: say how many (type it, or ±1, ±5), and the newest come or go. Every
## frame, Roc moves them, bounces them off the walls and off each other, and the flock's signal
## changes: each bird's row (kept by its id) patches its place, and the count of bounces its text.
## How many there should be is a signal of its own, which frames don't touch, so the field isn't
## written over while you type in it. A step's sound (a pop, a bump) is part of the next flock, and
## the handler plays it, with `Audio.play_with!`: the same file, faster for a higher note.
Birds := [].{
	Bird : { id : U64, x : F64, y : F64, vx : F64, vy : F64 }

	## The sound the last step made: its file in site/static/sounds ("" for none), and how fast it plays:
	## 2.0 is twice as fast, and an octave up.
	Sound : { tone : Str, rate : F64 }
	Model : { birds : List(Bird), next : U64, seed : U64, bounces : U64, sound : Sound, quiet : F64, muted : Bool }
	Msg : [Resize(U64), Frame(F64), Shake, Mute]

	## The flock, with `count` birds in it.
	view! : { count : U64 } => Html
	view! = |{ count }| {
		(flock!, set_flock!) = create_signal!(Birds.init(count))
		(wanted!, set_wanted!) = create_signal!(U64.min(count, most))
		# The flock goes on to the next, and plays the sound that step made, unless muted.
		send! = |msg| {
			next = Birds.update(flock!(), msg)
			set_flock!(next)
			if (!next.muted and !next.sound.tone.is_empty()) Audio.play_with!("/sounds/${next.sound.tone}.wav", { volume: 1.0, rate: next.sound.rate }) else {}
		}
		resize! = |n| {
			size = U64.min(n, most)
			set_wanted!(size)
			send!(Resize(size))
		}
		<div class="flock">
			<div class="flock-bar">
				<div class="flock-size" role="group" aria-label="How many birds">
					<button type="button" class="round" on:click={|| resize!(less(wanted!(), 5))} disabled?={wanted!() == 0} aria-label="Five birds fewer">−5</button>
					<button type="button" class="round" on:click={|| resize!(less(wanted!(), 1))} disabled?={wanted!() == 0} aria-label="One bird fewer">−1</button>
					<input
						class="flock-count"
						type="number"
						inputmode="numeric"
						min="0"
						max={most.to_str()}
						aria-label="Birds"
						value={wanted!().to_str()}
						on:input.value={|text|
							match U64.from_str(text.trim()) {
								Ok(n) => resize!(n)
								Err(_) => {}
							}}
						on:change={|| set_wanted!(wanted!())}
					/>
					<button type="button" class="round" on:click={|| resize!(wanted!() + 1)} disabled?={wanted!() >= most} aria-label="One more bird">+1</button>
					<button type="button" class="round" on:click={|| resize!(wanted!() + 5)} disabled?={wanted!() >= most} aria-label="Five more birds">+5</button>
				</div>
				<span class="flock-label">{if (wanted!() == 1) "bird" else "birds"} · {flock!().bounces.to_str()} bounces</span>
				<span class="flock-actions">
					<button type="button" on:click={|| send!(Shake)} disabled?={wanted!() == 0}>Shake</button>
					<button type="button" on:click={|| send!(Mute)} aria-pressed={if (flock!().muted) "true" else "false"}>{if (flock!().muted) "Sound off" else "Sound on"}</button>
				</span>
			</div>
			{# Time flows only while there are birds: an empty arena has no frame handler, so no frames. }
			{if wanted!() > 0 {
				<div class="arena" on:frame.ms={|ms| send!(Frame(ms))}>
					{...flock!().birds.map(|bird|
						<span key={bird.id.to_str()} class="bird" class:left={bird.vx < 0.0} style:--x={css(bird.x)} style:--y={css(bird.y)}></span>
					)}
				</div>
			} else {
				<div class="arena"><p class="arena-empty">Empty sky. Press +1 to let a bird in.</p></div>
			}}
		</div>
	}

	init : U64 -> Model
	init = |count| {
		var $model = { birds: [], next: 0, seed: 2026, bounces: 0, sound: silent, quiet: 0.0, muted: Bool.False }
		var $left = count
		while $left > 0 {
			$model = arrive($model)
			$left = $left - 1
		}
		# No sound for the birds that were there when the page came.
		{ ..$model, sound: silent }
	}

	update : Model, Msg -> Model
	update = |last, msg| {
		# A step makes its own sound, if any: the last one's doesn't carry over.
		model = { ..last, sound: silent }
		match msg {
			Resize(count) => resize(model, count)
			Frame(ms) => fly(model, ms)
			Shake => shake(model)
			Mute => { ..model, muted: !model.muted }
		}
	}

	<style>
		.flock {
			display: grid;
			gap: var(--space-3);
		}

		.flock-bar {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: var(--space-2) var(--space-5);
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		/* How many birds: a number to type, between −5 −1 and +1 +5. */
		.flock-size {
			display: flex;
			align-items: center;
			gap: var(--space-2);
		}

		.round {
			width: 2.5rem;
			height: 2.5rem;
			padding: 0;
			border-radius: 50%;
			font-size: var(--size-sm);
			font-weight: 700;
			line-height: 1;
		}

		.round:hover:not(:disabled) {
			background: var(--accent-soft);
			color: var(--accent);
		}

		input.flock-count {
			width: 3.2em;
			height: 2.5rem;
			padding: 0 var(--space-1);
			border-radius: var(--radius);
			font: 700 var(--size-lg) / 1 var(--font);
			font-variant-numeric: tabular-nums;
			text-align: center;
			appearance: textfield;
			-moz-appearance: textfield;
		}

		.flock-count::-webkit-inner-spin-button,
		.flock-count::-webkit-outer-spin-button {
			margin: 0;
			-webkit-appearance: none;
		}

		.flock-actions {
			display: flex;
			gap: var(--space-2);
			margin-left: auto;
		}

		.flock-actions button {
			padding: var(--space-1) var(--space-3);
			font-size: var(--size-sm);
		}

		.flock-actions [aria-pressed="true"] {
			color: var(--text-faint);
		}

		/* The arena is 100 units wide (and 56.25 high): a unit is 1cqw, so Roc's numbers are the places. */
		.arena {
			position: relative;
			aspect-ratio: 16 / 9;
			container-type: inline-size;
			overflow: hidden;
			border-radius: var(--radius-lg);
			background: linear-gradient(#221a3d, #120f1d);
			box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.05);
		}

		.arena-empty {
			position: absolute;
			inset: 0;
			display: grid;
			place-items: center;
			margin: 0;
			color: var(--text-faint);
		}

		.bird {
			position: absolute;
			top: 0;
			left: 0;
			width: 3.5cqw;
			height: 3.5cqw;
			translate: calc(var(--x) * 1cqw - 1.75cqw) calc(var(--y) * 1cqw - 1.75cqw);
			animation: arrive 0.4s cubic-bezier(0.3, 1.6, 0.5, 1);
		}

		.bird::before {
			content: "";
			position: absolute;
			inset: 0;
			/* Roc's bird (static/roc-bird.svg), in the CSS: this stylesheet is in the page, so a relative URL
			   would be the page's, and a page may be under a base (/rocx/). */
			background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-1.25 0 53 53'%3E%3Cpolygon points='0,0 23.8834,3.21052 37.2438,19.0101 45.9665,16.6324 50.5,22 45,22 44.0315,26.3689 26.4673,39.3424 27.4527,45.2132 17.655,53 23.6751,22.7086' fill='%237c38f5'/%3E%3C/svg%3E") center / contain no-repeat;
			animation: flap 0.45s ease-in-out infinite alternate;
		}

		.bird.left::before {
			scale: -1 1;
		}

		@keyframes arrive {
			from {
				opacity: 0;
				scale: 0;
			}
		}

		@keyframes flap {
			to {
				rotate: -9deg;
			}
		}

		@media (prefers-reduced-motion: reduce) {
			.bird,
			.bird::before {
				animation: none;
			}
		}
	</style>
}

## `count` birds, at most `most`: the newest go, or new ones come.
resize : Birds.Model, U64 -> Birds.Model
resize = |model, count| {
	wanted = U64.min(count, most)
	if wanted < model.birds.len() {
		{ ..model, birds: model.birds.drop_last(model.birds.len() - wanted), sound: pop(330) }
	} else {
		var $model = model
		while $model.birds.len() < wanted {
			$model = arrive($model)
		}
		$model
	}
}

## `n` fewer, but not below none.
less : U64, U64 -> U64
less = |count, n| if (count > n) count - n else 0

## The arena is 100 units wide and 56.25 high (16:9, as its box); a bird is 3.5 across, and as
## many as 200 fly in it.
width : F64
width = 100.0

height : F64
height = 56.25

radius : F64
radius = 1.75

most : U64
most = 200

silent : Birds.Sound
silent = { tone: "", rate: 1.0 }

## A pop at `pitch` hertz: pop.wav is at 440.
pop : U64 -> Birds.Sound
pop = |pitch| { tone: "pop", rate: pitch.to_f64() / 440.0 }

## A bump at `pitch` hertz: bonk.wav is at 220.
bonk : U64 -> Birds.Sound
bonk = |pitch| { tone: "bonk", rate: pitch.to_f64() / 220.0 }

## Hundredths are plenty for a place on the screen, and keep patches short. Written with whole
## numbers: `F64.to_str` would put Roc's float printer, some 12 KB compressed, in the wasm.
css : F64 -> Str
css = |value| {
	hundredths = (value * 100.0).round_to_i64_try() ?? 0
	whole = I64.abs(hundredths)
	cents = whole % 100
	"${if (hundredths < 0) "-" else ""}${(whole // 100).to_str()}.${if (cents < 10) "0" else ""}${cents.to_str()}"
}

## A bird somewhere in the arena, flying in some direction at some speed.
arrive : Birds.Model -> Birds.Model
arrive = |model|
	if model.birds.len() >= most {
		model
	} else {
		x = Random.float(model.seed)
		y = Random.float(x.seed)
		course = direction(y.seed)
		speed = Random.float(course.seed)
		velocity = 16.0 + speed.value * 16.0
		newcomer = {
			id: model.next,
			x: radius + x.value * (width - 2.0 * radius),
			y: radius + y.value * (height - 2.0 * radius),
			vx: velocity * course.x,
			vy: velocity * course.y,
		}
		{ ..model, birds: model.birds.append(newcomer), next: model.next + 1, seed: speed.seed, sound: pop(440 + model.birds.len() * 20) }
	}

## A direction, as a vector one unit long: a random point in the square, scaled to the circle.
## (Without sine and cosine, which would add some 5 KB to the wasm; a square root is one wasm
## instruction.)
direction : U64 -> { x : F64, y : F64, seed : U64 }
direction = |seed| {
	across = Random.float(seed)
	down = Random.float(across.seed)
	x = across.value * 2.0 - 1.0
	y = down.value * 2.0 - 1.0
	length = F64.sqrt(x * x + y * y)
	if (length < 0.05) { x: 1.0, y: 0.0, seed: down.seed } else { x: x / length, y: y / length, seed: down.seed }
}

## Every bird a kick in a new direction.
shake : Birds.Model -> Birds.Model
shake = |model| {
	kicked = model.birds.fold(
		{ birds: [], seed: model.seed },
		|state, b| {
			course = direction(state.seed)
			{ birds: state.birds.append({ ..b, vx: 30.0 * course.x, vy: 30.0 * course.y }), seed: course.seed }
		},
	)
	{ ..model, birds: kicked.birds, seed: kicked.seed, sound: pop(660) }
}

## `ms` of flight: everyone moves, the walls send them back, and birds that meet bounce apart.
fly : Birds.Model, F64 -> Birds.Model
fly = |model, ms| {
	seconds = ms / 1000.0
	walled = model.birds.map(|b| wall({ ..b, x: b.x + b.vx * seconds, y: b.y + b.vy * seconds }))
	met = meet(walled.map(|w| w.bird))
	hits = walled.count_if(|w| w.hit) + met.hits
	quiet = model.quiet + ms
	# A bump makes a sound, at most one every 90 ms, so a crowd doesn't become a buzz.
	if met.hits > 0 and quiet >= 90.0 {
		{ ..model, birds: met.birds, bounces: model.bounces + hits, quiet: 0.0, sound: bonk(180 + met.hits * 40) }
	} else {
		{ ..model, birds: met.birds, bounces: model.bounces + hits, quiet }
	}
}

wall : Birds.Bird -> { bird : Birds.Bird, hit : Bool }
wall = |b| {
	left = b.x < radius
	right = b.x > width - radius
	top = b.y < radius
	bottom = b.y > height - radius
	vx = if (left) F64.abs(b.vx) else if (right) F64.negate(F64.abs(b.vx)) else b.vx
	vy = if (top) F64.abs(b.vy) else if (bottom) F64.negate(F64.abs(b.vy)) else b.vy
	x = F64.max(radius, F64.min(width - radius, b.x))
	y = F64.max(radius, F64.min(height - radius, b.y))
	{ bird: { ..b, x, y, vx, vy }, hit: left or right or top or bottom }
}

## Every pair that overlaps is pushed apart, and if they were closing in, they swap their speeds
## along the line between them: an elastic collision of equal masses.
meet : List(Birds.Bird) -> { birds : List(Birds.Bird), hits : U64 }
meet = |start| {
	count = start.len()
	var $birds = start
	var $hits = 0.U64
	var $i = 0.U64
	while $i < count {
		var $j = $i + 1
		while $j < count {
			met = bounce($birds, $i, $j)
			$birds = met.birds
			$hits = $hits + met.hits
			$j = $j + 1
		}
		$i = $i + 1
	}
	{ birds: $birds, hits: $hits }
}

bounce : List(Birds.Bird), U64, U64 -> { birds : List(Birds.Bird), hits : U64 }
bounce = |birds, i, j|
	match (birds.get(i), birds.get(j)) {
		(Ok(a), Ok(b)) => {
			dx = b.x - a.x
			dy = b.y - a.y
			apart = dx * dx + dy * dy
			reach = 2.0 * radius
			if apart >= reach * reach or apart == 0.0 {
				{ birds, hits: 0 }
			} else {
				distance = F64.sqrt(apart)
				nx = dx / distance
				ny = dy / distance
				push = (reach - distance) / 2.0
				closing = F64.min(0.0, (b.vx - a.vx) * nx + (b.vy - a.vy) * ny)
				moved_a = { ..a, x: a.x - nx * push, y: a.y - ny * push, vx: a.vx + closing * nx, vy: a.vy + closing * ny }
				moved_b = { ..b, x: b.x + nx * push, y: b.y + ny * push, vx: b.vx - closing * nx, vy: b.vy - closing * ny }
				with_a = birds.set(i, moved_a) ?? birds
				{ birds: with_a.set(j, moved_b) ?? with_a, hits: if (closing < 0.0) 1 else 0 }
			}
		}
		_ => { birds, hits: 0 }
	}

expect Birds.init(5).birds.len() == 5
expect Birds.init(5).sound.tone == ""
# A step's sound is its own: a bird more pops, and the next step (muting, here) makes none.
expect {
	more = Birds.update(Birds.init(2), Resize(3))
	more.sound.tone == "pop" and Birds.update(more, Mute).sound == silent
}
expect Birds.update(Birds.init(2), Resize(3)).birds.len() == 3
expect Birds.update(Birds.init(2), Resize(999)).birds.len() == 200
expect (Birds.update(Birds.init(5), Resize(2)).birds.map(|b| b.id)) == [0, 1]
expect Birds.update(Birds.init(1), Resize(0)).birds.len() == 0
expect less(3, 5) == 0
expect wall({ id: 0, x: -1.0, y: 10.0, vx: -5.0, vy: 0.0 }).bird == { id: 0, x: 1.75, y: 10.0, vx: 5.0, vy: 0.0 }
# Head on, at the same speed: they swap, and fly apart.
expect {
	met = meet([{ id: 0, x: 10.0, y: 10.0, vx: 5.0, vy: 0.0 }, { id: 1, x: 13.0, y: 10.0, vx: -5.0, vy: 0.0 }])
	met.hits == 1 and (met.birds.get(0) ?? { id: 9, x: 0.0, y: 0.0, vx: 0.0, vy: 0.0 }).vx == -5.0
}
expect css(12.3456) == "12.35"
expect css(-0.5) == "-0.50"
expect css(3.0) == "3.00"
expect {
	course = direction(99)
	F64.abs(course.x * course.x + course.y * course.y - 1.0) < 0.000001
}

Sound, from a handler#

update is pure, so it can't make a sound. The next game names its step's sound instead ("eat", "die", or nothing), which a test can check, and the handler that sets the game plays it with Audio.play!, from the audio plugin package (its script in the page plays it):

site/Demos/Snake.rocx
go! = |next| {
	set_game!(next)
	if (!next.muted and !next.sound.is_empty()) Audio.play!("/sounds/${next.sound}.wav") else {}
}

It plays any file the browser can (WAV, MP3, Ogg, from anywhere), with nothing prepared: the browser fetches each file once and keeps it. These are chiptune notes of a few KB, made by site/sounds.mjs. The flock plays one pop at every pitch with Audio.play_with!(url, { volume, rate }): each new bird plays it a little faster, a higher note.

A sound plays once the handler is done and the page is patched. Only handlers play sounds; in a hole or on the server, it fails. For browser features with no platform module (the clipboard, say), a handler calls the page's JavaScript with Browser.call!(name, arg), like Elm's ports. Nothing comes back; for answers, ask the server (talking to the server).

Timers#

For “every tenth of a second” or “once the typing stops”, use the browser's timers, from pf.Solid: set_interval!(ms, tick!) and set_timeout!(ms, done!) run a handler later, as a click would, and return a clear! function that stops it.

set_interval!, stopped by its clear!

0.0 s

set_timeout!, cleared at each key

Type, and the search runs once you pause.

0 keys, 0 searches

  • albatross
  • blackbird
  • cormorant
  • crane
  • dove
  • eagle
  • falcon
  • finch
  • flamingo
  • gull
  • heron
  • hummingbird
  • kestrel
  • kingfisher
  • magpie
  • nightingale
  • osprey
  • owl
  • parrot
  • pelican
  • puffin
  • raven
  • robin
  • sparrow
  • starling
  • swallow
  • swan
  • swift
  • tern
  • wren

Gone with its part

0 s on the page

0 ticks heard

The stopwatch keeps its interval's clear! in a signal, and Stop calls it:

site/Demos/Timers.rocx
(watch!, set_watch!) = create_signal!(stopped)
toggle! = ||
	match watch!() {
		Running(clear!) => {
			clear!()
			set_watch!(Stopped)
		}
		Stopped => set_watch!(Running(set_interval!(100, || set_tenths!(tenths!() + 1))))
	}

On each key, the search clears the last timeout and starts its own, so it searches once, 400 ms after the last key. The clock clears nothing: a timer belongs to what started it (a component, or the part of the page a handler's element is in) and stops when that goes. Hide the clock and its ticks stop. Solid needs onCleanup(() => clearInterval(id)) for this; here it is built in.

The timers, and the clock: site/Demos/Timers.rocx, site/Demos/Clock.rocx
site/Demos/Timers.rocx
import pf.Html
import pf.Solid exposing [create_signal!, create_signal_with!, set_interval!, set_timeout!]
import Clock

## The browser's timers, from Roc. `set_interval!` and `set_timeout!` run a handler later, and
## answer its `clear!`. The stopwatch keeps its interval's `clear!` in a signal, and Stop calls it.
## The search waits for a pause in the typing: each key clears the last key's timeout, and starts
## its own. And the clock in the if clears nothing: its interval stops when the clock goes.
Timers := [].{
	Watch : [Stopped, Running(() => {})]
	Search : [Idle, Waiting(() => {})]

	view! : {} => Html
	view! = |{}| {
		# The stopwatch: tenths of a second, and, while it runs, its interval's clear!.
		(tenths!, set_tenths!) = create_signal!(0.U64)
		(watch!, set_watch!) = create_signal_with!(stopped, { equals: |_, _| Bool.False })
		toggle! = ||
			match watch!() {
				Running(clear!) => {
					clear!()
					set_watch!(Stopped)
				}
				Stopped => set_watch!(Running(set_interval!(100, || set_tenths!(tenths!() + 1))))
			}

		# The search: what is typed, what was searched for once the typing paused, and the
		# timeout waiting for that pause.
		(draft!, set_draft!) = create_signal!("")
		(query!, set_query!) = create_signal!("")
		(search!, set_search!) = create_signal_with!(idle, { equals: |_, _| Bool.False })
		(keys!, set_keys!) = create_signal!(0.U64)
		(searches!, set_searches!) = create_signal!(0.U64)
		typed! = |text| {
			match search!() {
				Waiting(cancel!) => cancel!()
				Idle => {}
			}
			set_draft!(text)
			set_keys!(keys!() + 1)
			wait = set_timeout!(
				400,
				|| {
					set_query!(text)
					set_searches!(searches!() + 1)
					set_search!(Idle)
				},
			)
			set_search!(Waiting(wait))
		}

		# The clock: whether it shows, and the ticks heard from it.
		(clock!, set_clock!) = create_signal!(Bool.True)
		(ticks!, set_ticks!) = create_signal!(0.U64)

		<div class="timers">
			<section class="timer">
				<h3><code>set_interval!</code>, stopped by its <code>clear!</code></h3>
				<p class="timer-face"><b>{watch_time(tenths!())}</b> s</p>
				<div class="timer-actions">
					<button type="button" class:running={running(watch!())} on:click={toggle!}>{if (running(watch!())) "Stop" else "Start"}</button>
					<button type="button" on:click={|| set_tenths!(0)} disabled?={tenths!() == 0}>Reset</button>
				</div>
			</section>
			<section class="timer">
				<h3><code>set_timeout!</code>, cleared at each key</h3>
				<input type="search" placeholder="Search the birds" aria-label="Search the birds" value={draft!()} on:input.value={typed!} />
				<p class="timer-note">{waiting_note(search!(), query!())}</p>
				<p class="timer-note">{counted(keys!(), "key")}, {counted(searches!(), "search")}</p>
				<ul class="timer-birds">
					{...matches(query!()).map(|bird|
						<li key={bird}>{bird}</li>
					)}
				</ul>
			</section>
			<section class="timer">
				<h3>Gone with its part</h3>
				<label class="timer-check">
					<input type="checkbox" checked?={clock!()} on:change.checked={set_clock!} />
					Show the clock
				</label>
				{if clock!() {
					<Clock tick!={|| set_ticks!(ticks!() + 1)} />
				} else {
					<p class="timer-note">No clock, so no interval: the ticks stop.</p>
				}}
				<p class="timer-note">{counted(ticks!(), "tick")} heard</p>
			</section>
		</div>
	}

	<style>
		.timers {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(min(100%, max(14rem, calc((100% - var(--space-4)) / 2))), 1fr));
			gap: var(--space-4);
		}

		.timer {
			display: grid;
			align-content: start;
			gap: var(--space-2);
			padding: var(--space-4);
			border-radius: var(--radius);
			background: var(--bg-sunken);
		}

		.timer h3 {
			margin: 0;
			font-size: var(--size-md);
		}

		.timer-face {
			margin: 0;
			color: var(--text-muted);
		}

		.timer-face b {
			color: var(--text);
			font: 700 2rem/1.2 var(--font);
			font-variant-numeric: tabular-nums;
		}

		.timer-actions {
			display: flex;
			gap: var(--space-2);
		}

		.timer button {
			padding: var(--space-1) var(--space-4);
			font-size: var(--size-sm);
		}

		.timer button.running {
			background: var(--accent-soft);
			color: var(--accent);
		}

		.timer-note {
			margin: 0;
			color: var(--text-faint);
			font-size: var(--size-sm);
		}

		.timer-check {
			display: flex;
			align-items: center;
			gap: var(--space-2);
		}

		.timer-birds {
			display: flex;
			flex-wrap: wrap;
			gap: var(--space-1);
			margin: 0;
			padding: 0;
			list-style: none;
		}

		.timer-birds li {
			padding: 0.1rem var(--space-2);
			border-radius: var(--pill);
			background: var(--accent-soft);
			color: var(--accent);
			font-size: var(--size-sm);
		}
	</style>
}

stopped : Timers.Watch
stopped = Stopped

idle : Timers.Search
idle = Idle

running : Timers.Watch -> Bool
running = |watch|
	match watch {
		Running(_) => Bool.True
		Stopped => Bool.False
	}

## Tenths of a second, as the stopwatch shows them: `12.3`.
watch_time : U64 -> Str
watch_time = |tenths| "${(tenths // 10).to_str()}.${(tenths % 10).to_str()}"

waiting_note : Timers.Search, Str -> Str
waiting_note = |search, query|
	match search {
		Waiting(_) => "Waiting for a pause in the typing…"
		Idle => if (query.is_empty()) "Type, and the search runs once you pause." else "Searched for “${query}”."
	}

## A number of things: `1 key`, `2 searches`.
counted : U64, Str -> Str
counted = |n, thing| {
	plural = if (thing.ends_with("ch")) "${thing}es" else "${thing}s"
	"${n.to_str()} ${if (n == 1) thing else plural}"
}

birds : List(Str)
birds = ["albatross", "blackbird", "cormorant", "crane", "dove", "eagle", "falcon", "finch", "flamingo", "gull", "heron", "hummingbird", "kestrel", "kingfisher", "magpie", "nightingale", "osprey", "owl", "parrot", "pelican", "puffin", "raven", "robin", "sparrow", "starling", "swallow", "swan", "swift", "tern", "wren"]

## The birds whose names have the query in them; all of them for none.
matches : Str -> List(Str)
matches = |query| {
	wanted = query.trim().with_ascii_lowercased()
	birds.keep_if(|bird| bird.contains(wanted))
}

expect watch_time(123) == "12.3"
expect watch_time(0) == "0.0"
expect matches("sw") == ["swallow", "swan", "swift"]
expect matches("").len() == birds.len()
expect counted(1, "search") == "1 search" and counted(2, "search") == "2 searches" and counted(0, "tick") == "0 ticks"
site/Demos/Clock.rocx
import pf.Html
import pf.Solid exposing [create_signal!, set_interval!]

## A clock that counts the seconds it has been on the page. It starts an interval and never clears
## it: the interval is the clock's, so when the clock goes (the if around it hides it), the
## interval stops with it. Each tick it tells whoever shows it too (`tick!`).
Clock := [].{
	view! : { tick! : () => {} } => Html
	view! = |{ tick! }| {
		(seconds!, set_seconds!) = create_signal!(0.U64)
		_ = set_interval!(
			1000,
			|| {
				set_seconds!(seconds!() + 1)
				tick!()
			},
		)
		<p class="clock"><b>{seconds!().to_str()}</b> s on the page</p>
	}

	<style>
		.clock {
			margin: 0;
			color: var(--text-muted);
		}

		.clock b {
			color: var(--text);
			font: 700 2rem/1.2 var(--font);
			font-variant-numeric: tabular-nums;
		}
	</style>
}