@codefusion-cc/scene
v0.1.0
Published
One canvas scene loop per page, lively then calm, idle out of view, with reduced-motion and measured slow-device still pictures, React bindings and a deterministic test clock
Readme
@codefusion-cc/scene
Canvas scenes that move while someone looks, then settle. One animation-frame chain serves every scene in a
document. Offscreen scenes and hidden tabs paint nothing; the last destroy() stops the loop and removes all
observers and listeners. The package supplies the mechanism. Apps supply the pictures, colours and content.
DOM
Give the canvas a CSS width and height, independent of its backing-store attributes. For grid or flex layouts,
allow it to shrink with min-width: 0. Draw in CSS pixels; the context is cleared and scaled before each paint.
import { mountScene } from '@codefusion-cc/scene'
const scene = mountScene(canvas, {
colors: ['--sky-core'],
draw({ ctx, width, height, t, mode, colors }) {
ctx.fillStyle = colors['--sky-core'] || (mode === 'dark' ? '#fff' : '#111')
ctx.beginPath()
ctx.arc(width / 2 + Math.sin(t) * 8, height / 2, 5, 0, Math.PI * 2)
ctx.fill()
},
})
// After a person interacts, or the app changes its picture's data:
scene.touch()
scene.repaint()
// When the canvas is no longer used:
scene.destroy()The draw callback receives ctx, width, height, dpr, t, dt, mode, lively, offsetY and colors.
t is this scene's clock in seconds, starting at zero. dt is its clock time since the previous paint,
including skipped calm frames and excluding time hidden or offscreen. A frame crossing the lively deadline
advances at each speed for the corresponding part of the interval. Neither clock jumps on reappearance.
| Option | Default | Meaning |
| --- | --- | --- |
| lively | 5000 | Milliseconds of full-speed painting after appearing or touch() |
| calmSpeed | 0.1 | Clock speed when calm |
| calmEvery | 5 | Paint every fifth calm frame |
| maxDpr | 2 | Device-pixel-ratio cap |
| stillAt | 3.2 | Still picture's clock position, in seconds |
| pin | unset | 'viewport' makes the canvas sticky and viewport-height |
| element | canvas parent | Element whose visible offset the picture reads |
| storageKey | 'codefusion-scene-slow' | Session marker shared by scenes with this key |
| colors | [] | Custom property names cached on repaint, resize and look changes |
| environment | browser | Controllable boundaries from ./testing |
mode comes from the canvas's computed color-scheme: a single light or dark wins; a scheme allowing
both follows the system. Set color-scheme in the app's theme CSS. Changing <html>'s class, data-theme,
data-look or style, or the system colour scheme, repaints even a still picture. readColors(element, names)
is also available for custom repaint-time caching; calling it in every draw would repeat the style read.
Changes made only to a canvas or an ancestor below <html> require scene.repaint().
Long lists
Put the canvas and list in the same grid area to overlay them. The parent supplies the sticky scroll area;
avoid ancestor clipping that prevents sticky positioning. The canvas stays viewport-height, independently of
the list's length. Its width still comes from CSS. offsetY includes the containing element's scroll position
and its displacement relative to the canvas, so a scene can measure just the rows in view. On mobile the height
follows the visual viewport. Pinning uses box-sizing: border-box so padding and borders stay within that height.
It temporarily owns position, top, height, min-width and box-sizing, restoring their previous inline
values on destroy.
.scene-list { display: grid; }
.scene-list > canvas { grid-area: 1 / 1; align-self: start; width: 100%; pointer-events: none; }
.scene-list > ol { grid-area: 1 / 1; }Mount with { pin: 'viewport', element: listHost, draw }. Paints when moving can read the current scroll offset;
still pictures intentionally do not repaint on scroll. Call repaint() if a data change needs a new picture.
Still pictures
scene.still is 'reduced-motion', 'slow' or null. Reduced motion immediately draws at stillAt, with
dt: 0 and lively: false. Turning the preference off resumes the scene's own clock, unless it was slow.
A still picture paints once, then only on resize, look change or explicit repaint(); appearing again alone
does not paint it again. A hidden mount waits until visible before its first paint.
Each scene measures its first lively frames. After both 36 samples and 1.2 seconds of active sampling, a
median interval above 28 ms or median draw-call time above 9 ms holds a still picture. Equality does not trigger
it; isolated slow frames do not dominate a median. A short custom lively period may not provide enough samples
until subsequent touches or appearances. Sampling memory is capped at the latest 256 intervals and paint times.
The decision freezes all scenes sharing its storage key for the visit. sessionStorage carries it through page
reloads; when storage is blocked or full, the governor remembers it in this page only. Reduced motion takes
precedence in the reported reason without erasing a slow decision.
The package assumes modern browsers with ResizeObserver, IntersectionObserver, MutationObserver and matchMedia.
An unavailable 2D context returns an inert handle. Invalid options, mounting twice on the same canvas and errors
in drawing are programming errors and throw. A throwing draw destroys its scene; sibling scenes keep running.
Call destroy() before manually removing a canvas. React does this on unmount.
React
React is an optional peer; the DOM and testing entries do not import it.
import { SceneCanvas, useScene } from '@codefusion-cc/scene/react'
<SceneCanvas draw={drawSky} options={{ colors: ['--sky-core'] }} className="sky" />SceneCanvas accepts normal canvas attributes and fallback children. It is decorative (aria-hidden) by
default; provide aria-label or aria-labelledby and meaningful fallback content for an informative picture.
It does not intercept pointer or keyboard events. Use the imperative hook when the app needs to wake a scene:
const canvas = useRef<HTMLCanvasElement>(null)
const scene = useScene(canvas, drawSky, { pin: 'viewport' })
return <canvas ref={canvas} onPointerDown={() => scene.current?.touch()} aria-hidden="true" />Changing a draw callback repaints with the new function without restarting time, including in still mode.
Keep the callback stable when its picture has not changed. Inline equivalent options also preserve the clock.
Changing a mechanism option remounts; an environment or element must keep its
identity to preserve the scene. The returned ref exposes still imperatively, without triggering React renders.
Server rendering adds no observers or loop; mounting in the browser starts the scene.
Deterministic scene tests
import { mountScene } from '@codefusion-cc/scene'
import { createSceneClock } from '@codefusion-cc/scene/testing'
const clock = createSceneClock()
const scene = mountScene(canvas, {
environment: clock.environment,
draw(frame) { drawSky(frame); clock.paint() },
})
clock.durations(33, 0) // frame interval and draw duration in ms
clock.frames(37) // enough frames and elapsed time to judge a slow device
expect(scene.still).toBe('slow')
scene.destroy()
expect(clock.resources()).toEqual({ pendingFrames: 0, observers: 0, listeners: 0 })Share one clock's environment across scenes to test the shared loop. step(ms), frames(n) and paint(ms)
control timing. visibility(bool), reducedMotion(bool), appear(canvas, bool), resize(canvas, w, h), look()
and viewport(height, dpr) control browser events. blockStorage(true) models denied storage;
createSceneClock({ session }) accepts a shared Map<string, string> to model remounts across page clocks.
The clock measures only simulated paint() time; actual CPU time does not make tests nondeterministic.
Size and verification
The minified DOM entry is about 3 kB gzip, with no dependencies. Its test caps it at 5 kB and rejects accidental
React or testing imports. Bundle measurements use esbuild, ESM, browser target, with React external for ./react.
npx tsc -p packages/scene/tsconfig.build.json
npx oxlint packages/scene
npx vitest run packages/scene/test --maxWorkers=2 --reporter=dot
npx vitest run -c packages/scene/vitest.browser.config.ts --project 'scene-browser (chromium)' --reporter=dot
npx vitest run -c packages/scene/vitest.browser.config.ts --project 'scene-browser (firefox)' --reporter=dotBrowser projects run separately to keep one browser active at a time. The real engines check media queries, computed colours, observer cleanup, sticky sizing, DPR and React lifecycle. Node tests check exact clock and fallback bounds, storage persistence, cleanup and arbitrary lifecycle sequences. Mutation evidence is in test/MUTATIONS.md.
