Files
functional-programming-snake/fsharp/web/BrowserPlatform.fs
T
Lucas WintherandClaude Fable 5.2 edd57f0148 feat(course): audit fixes and twelve extensions (Modules 7b, 12, 13)
Audit pass:
- Frame rule counts frames since the last move, so every step lasts
  exactly movesEvery(score) frames, also right after a speed-up
- clampTime + MAX_GAP_MS: a hidden tab no longer replays the whole gap
- Pong Restart keeps held keys
- Fact corrections (mulberry32 output coverage, Haskell IO, uniform)
- New fixture cases from a mutation analysis

Extensions (all three tracks, shared fixtures, course text):
- Turn queue (Exercise 10.6), persisted high score (10.7),
  replay viewer (10.8), play() end-to-end helper (9.5)
- Optional State (4.7) and optional Module 7b, stack-safe IO
- Module 12, property-based testing with generators, shrinking,
  invariants and a model-based oracle
- Module 13, Conway's Life with a Click event
- JS type checking via jsconfig, JSDoc and types.d.ts
- Maintainer tools: scripts/mutate.mjs, scripts/typecheck-js.sh,
  Playwright end-to-end suite (e2e/, scripts/e2e.sh)

Docs: docs/contract.md is the canonical contract; specs and build log
under docs/superpowers.

Verified: JS 728, Scala 689, F# 691 unit tests; stubs and progression
M01-M13 and M07b; 176 end-to-end tests on Chromium and WebKit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 12:05:29 +01:00

109 lines
4.3 KiB
FSharp

/// Browser glue: turns a canvas into a Platform. Impure by nature; not part of the exercises' logic.
/// `?` (Fable.Core.JsInterop dynamic access) calls browser APIs by name, without type bindings or extra packages.
module Snake.Web.BrowserPlatform
open Fable.Core
open Fable.Core.JsInterop
open Snake.Runtime
[<Global>]
let private window: obj = jsNative
[<Global>]
let private crypto: obj = jsNative
// Keys that scroll the page should only steer the game.
let private prevent = [ "ArrowUp"; "ArrowDown"; "ArrowLeft"; "ArrowRight"; " " ]
let private listen (kind: string) (cb: string -> unit) : unit =
window?addEventListener (kind,
fun (e: obj) ->
let key: string = e?key
if List.contains key prevent then
e?preventDefault ()
cb key)
// t is the number of milliseconds since the first animation frame.
let private startClock (onTime: int64 -> unit) : unit =
let rec frame (start: float option) : float -> unit =
fun now ->
let t0 = defaultArg start now
onTime (int64 (now - t0))
window?requestAnimationFrame (frame (Some t0))
window?requestAnimationFrame (frame None)
// Fable compiles a uint32 array to a Uint32Array, which is what crypto.getRandomValues fills.
let private randomSeed () : uint32 =
let buf: uint32[] = Array.zeroCreate 1
crypto?getRandomValues (buf)
buf[0]
// m10: where the best score survives a reload.
let private bestKey = "pure-snake-best"
// Storage can be missing, blocked (privacy settings; some browsers throw as soon as localStorage is touched) or hold
// anything: all of that reads as 0, and nothing throws. Only a non-negative whole number counts.
let private loadBest () : int =
try
let raw: string = window?localStorage?getItem (bestKey)
if isNull raw then
0
else
// Only what saveBest writes counts: decimal digits, at most 2147483647 (so all three tracks read alike).
let digits = raw.Length >= 1 && raw.Length <= 10 && Seq.forall (fun c -> c >= '0' && c <= '9') raw
if digits && float raw <= 2147483647.0 then int (float raw) else 0
with _ ->
0
// A record that cannot be stored is lost; the game goes on.
let private saveBest (score: int) : unit =
try
window?localStorage?setItem (bestKey, string score)
with _ ->
()
// m13: a click on the canvas, in canvas pixels. The page may show the canvas larger or smaller than its width and
// height (CSS, zoom) and draws a border round it, so the window coordinates of the mouse are made relative to the
// drawing area (inside the border) and then scaled. The listener is added when the runtime asks, not before.
let private onClick (canvas: obj) (cb: int -> int -> unit) : unit =
canvas?addEventListener ("click",
fun (e: obj) ->
let r = canvas?getBoundingClientRect ()
let scale (client: float) (start: float) (border: float) (size: float) (shown: float) =
int (System.Math.Floor((client - start - border) * size / shown))
cb
(scale e?clientX r?left canvas?clientLeft canvas?width canvas?clientWidth)
(scale e?clientY r?top canvas?clientTop canvas?height canvas?clientHeight))
/// A Platform drawing on `canvas` (an HTML canvas element) and listening to the window's keys and frames, and from
/// m13 to clicks on the canvas.
let create (canvas: obj) : Platform =
let ctx = canvas?getContext ("2d")
{ FillRect =
fun x y w h color ->
ctx?fillStyle <- color
ctx?fillRect (x, y, w, h)
FillText =
fun x y text color size align ->
ctx?fillStyle <- color
ctx?font <- $"{size}px monospace"
ctx?textAlign <- align
ctx?fillText (text, x, y)
RandomSeed = randomSeed
LoadBest = loadBest
SaveBest = saveBest
StartClock = startClock
OnKeyDown = listen "keydown"
OnKeyUp = listen "keyup"
OnClick = onClick canvas }
/// The page's `<canvas id="game">`.
let gameCanvas () : obj = window?document?getElementById ("game")