# Walleye library reference

`lib/walleye.js` is one plain script (ES2017, no modules, no libraries, no
`eval`). It defines `window.Walleye`. `lib/walleye.css` is the style every
Walleye page shares and the viewer needs. The scene format is in
[scene-format.md](scene-format.md); the rules behind both are in
[design.md](design.md).

## Embedding

```html
<link rel="stylesheet" href="/walleye/lib/walleye.css">
<script src="/walleye/lib/walleye.js" defer></script>

<!-- from a file -->
<div data-walleye data-src="/walleye/examples/scenes/torus.json"></div>

<!-- inline -->
<div data-walleye data-mode="parallel">
  <script type="application/json">{"version": 1, "surface": {"type": "param", "expr": "torus"}}</script>
</div>
```

Every `[data-walleye]` element is mounted when the document is ready (or at
once, if the script loads later). Attributes: `data-src`, `data-mode`,
`data-controls="false"`, `data-caption="false"`, `data-coach="false"`,
`data-height` (a CSS length). `Walleye.mountAll(root)` mounts any added
later.

**No layout shift.** The stage's box is reserved by CSS before the script
runs: `.wy-stage` has `aspect-ratio: 2 / 1` (the `--wy-aspect` token), and an
unmounted `[data-walleye]` (or `.wy-reserve`) element reserves the stage and
one toolbar row with pseudo-elements. For an exact reservation, put the stage
in the HTML yourself; `mount` uses an existing child `.wy-stage`:

```html
<div id="viewer" class="wy-reserve"><div class="wy-stage"></div></div>
```

## Walleye.mount(element, sceneOrUrl, options) -> viewer

`element` is an element or a selector. It becomes the viewer's root (class
`wy-viewer`); a stage, toolbar, coach line, status line, caption and a
live region are added inside it. If `element` is itself a `.wy-stage`, it is
wrapped in a new root. Mounting an element again destroys the old viewer.

`sceneOrUrl` is a scene object or a URL (resolved against the page). Scenes
load asynchronously; `viewer.ready` is a promise that resolves to `true` when
the scene is shown and `false` if it failed (it never rejects).

| option | default | meaning |
|---|---|---|
| `mode` | `Walleye.settings.mode` (`mono` on a first visit) | starting mode |
| `controls` | true | toolbar and key list |
| `caption` | true | scene caption and credit under the stage |
| `coach` | true | the prompt line under the stage |
| `height` | none | a fixed stage height (number of px or CSS length) instead of the 2:1 aspect |
| `keys` | `'stage'` | `'page'` also takes keys when nothing else has focus (arrows and Space only when the page cannot scroll) |
| `modes` | all five | which mode buttons to offer, in order |
| `views` | true | Front, Top and Side buttons |
| `setupHref` | `'/walleye/setup/'` | link in the coach line for parallel and cross-eyed; `null` for none |
| `settings` | `Walleye.settings` | a settings object to use instead (the setup page passes its unsaved draft; call `viewer.refresh()` after changing it) |
| `view` | none | overrides the scene's start view (`{yaw, pitch, zoom}`) |
| `onload`, `onchange`, `onerror` | none | callbacks with the same `detail` as the events below |

### Viewer methods

| method | does |
|---|---|
| `setMode(m)` | `'mono'`, `'parallel'`, `'cross'`, `'anaglyph'` or `'wiggle'` |
| `cycleMode(dir)` | next (`1`) or previous (`-1`) mode |
| `home()` | eases back to the start view (instant under reduced motion); stops spinning |
| `setView({yaw, pitch, zoom})` | sets the view at once; pitch clamped to +-85, zoom to 0.5..4 |
| `animateTo(view)` | eases to a view |
| `namedView('front' \| 'top' \| 'side')` | eases there, keeping the zoom |
| `zoomBy(f)`, `setZoom(z)` | zoom |
| `setSpin(on)`, `setGuides(on)` | |
| `load(sceneOrUrl)` | swaps the scene in place; the stage does not resize. Returns a promise of `true`/`false` |
| `getView()`, `getMode()` | current state |
| `refresh()` | re-reads theme colours and settings and redraws |
| `destroy()` | removes everything it added and every listener |

Properties worth reading: `root`, `stage`, `canvas`, `scene`, `start` (the
start view), `state` (`loading`, `ready`, `empty` for a seed, `error`),
`message`.

### Events

Dispatched on `viewer.root` (they bubble):

| event | `detail` |
|---|---|
| `walleye:load` | `{viewer, scene}` |
| `walleye:change` | `{viewer, mode, view, reason}`; `reason` is `mode`, `drag`, `key`, `zoom`, `wheel`, `pinch`, `home`, `view`, `spin` or `guides` |
| `walleye:error` | `{viewer, error}` |

`walleye:settings` is dispatched on `window` when settings change.

The library never writes the URL and never scrolls the page. The viewer
page keeps the mode in the query string itself, with
`history.replaceState` on `walleye:change`.

## Walleye.settings

Read from `localStorage['walleye-settings']` when the script loads (every
access is guarded; a private window just gets the defaults).

| key | default | meaning |
|---|---|---|
| `mode` | `'mono'` | preferred mode |
| `pxPerMm` | 96 / 25.4 = 3.78 | CSS pixels per millimetre on this screen (from the setup page's card) |
| `eyeMm` | 63 | distance between the pupils |
| `separationMm` | 60 | the furthest apart the two pane centres may be in parallel mode |
| `crossMaxMm` | 0 | the widest a pane may be in cross-eyed mode (0: no limit) |
| `baseline` | 1 | multiplies every scene's stereo baseline (0..3) |

`Walleye.saveSettings(patch)` merges, validates, stores and redraws every
viewer; it returns `false` if the browser would not store it.
`Walleye.resetSettings()` goes back to `Walleye.defaults`. Settings changed
in another tab are picked up.

## Walleye.theme

`get()` gives `'light'` or `'dark'` (the `data-theme` attribute, else the
system). `set('light' | 'dark' | 'auto')` sets `data-theme` on `<html>` and
stores it under `walleye-theme`. Any element with `data-walleye-theme-toggle`
toggles the theme when clicked and carries `aria-pressed="true"` when dark.
A stored theme is applied when the script runs; to avoid a flash, pages also
apply it with a one-line inline script in `<head>`.

## Walleye.generators

Named parametric surfaces and curves; see the table in
[scene-format.md](scene-format.md#generators). Add your own:

```js
Walleye.generators.paraboloid = { kind: 'surface', u: [0, 1, 16], v: [0, 6.2832, 48], params: { a: 1 },
  f: function (r, t, p) { return [r * Math.cos(t), p.a * r * r, r * Math.sin(t)]; } };
```

Also exported: `Walleye.version`, `Walleye.modes`, `Walleye.viewers` (live
viewers), `Walleye.describeView(view)`.

## Modes and layout

The stage is always two panes wide (2:1). Switching modes redraws inside the
same box.

- **mono**: one view, centred, at the scale of a cross-eyed pane (the
  bounding sphere fills 80% of the smaller of half the width and the
  height).
- **parallel**: left eye's view on the left. Each pane is
  `min(stage width / 2, separationMm * pxPerMm)` wide and the two touch at
  the centre, so **pane centres are never further apart than the reader's
  separation** (60 mm at 96 px per inch by default). On a wide screen the
  panes are narrower than half the stage, and the picture is smaller than
  in mono: that is the price of a pair the eyes can fuse. A faint frame and
  a fusion dot mark each pane.
- **cross**: left eye's view on the right; panes are half the stage, or
  `crossMaxMm` if set.
- **anaglyph**: each eye is drawn in grey, multiplied by red (left) and cyan
  (right) and added. Works on light and dark themes.
- **wiggle**: one view alternating between the eyes about six frames a
  second. Under `prefers-reduced-motion` it does not move: an eye button on
  the stage, the `W` key or a tap switches eyes.

## Camera and stereo

- Turntable: yaw about world y, pitch clamped to +-85 degrees, so up stays
  up. The camera looks at the bounding sphere's centre from `distance`
  radii; perspective focal length is set so the sphere fills about 80% of a
  pane at zoom 1. Zoom is magnification (it does not move the camera).
- **Off-axis, not toe-in.** The two eye cameras are parallel, offset by
  +-b/2 along the camera's x, and each image is shifted sideways by
  f b / (2D) so the scene centre has zero disparity (it sits at the screen).
  Toed-in cameras would add vertical parallax at the corners, which is
  uncomfortable; parallel cameras have none.
- Baseline b = 0.06 D x `settings.baseline` x `scene.stereo.baseline`
  (about 3.4 degrees at the default). Two caps keep it comfortable: crossed
  (near) disparity at most 8% of a pane's width, and, in parallel mode,
  uncrossed (far) disparity at most `(eyeMm - separationMm) * pxPerMm`
  (2 px at least) so that the far side of the object never needs the eyes
  to turn outward. Zooming in therefore flattens depth a little instead of
  making the pair impossible to fuse.
- Depth cueing: lines get thinner and lighter with depth (8 bands), faces
  fade a little toward the background, points shrink. Edges and points on a
  face are drawn after it.
- Drawing: canvas 2D at `devicePixelRatio`, painter's algorithm over
  segments, faces and points together, flat shading with one light,
  quantised colours cached per theme. 5,000 segments and 3,000 faces with
  both eyes take about 35 ms in headless Chromium without a GPU (the smoke
  test measures it); a laptop browser is faster.

## Input

| input | does |
|---|---|
| drag (mouse, pen, one finger) | turn (pan for picture pairs) |
| pinch | zoom |
| wheel | zoom, but only when the stage has focus or Ctrl is held (trackpad pinch); otherwise the page scrolls and the coach line says how |
| arrows | turn 5 degrees (Shift: 15) |
| `+` `-` | zoom |
| `0` (and Home on the stage) | start view |
| `1` `2` `3` | front, top, side; `4` to `9` the scene's own `views` |
| `M` / Shift+`M` | next / previous mode |
| `S` | swap parallel and cross-eyed |
| Space | spin (not when a button has focus) |
| `G` | guides |
| `W` | other eye, in still wiggle |
| `?` | key list; `Esc` closes it and returns focus to where it was |

The stage is focusable (`role="group"`, described by the status line); the
canvas is `role="img"` with the scene's `alt`. A polite live region names the
view at most once a second ("Front-right (30 degrees right), tilted 20
degrees down"), and not while spinning. Spin and wiggle pause when the stage
is off screen or the tab is hidden.

## Page shell and CSS classes

All Walleye pages use this shell:

```html
<body class="wy-page">
<a class="wy-skip" href="#main">Skip to the content</a>
<header class="wy-header">
  <a class="wy-brand" href="/walleye/">Walleye</a>
  <nav class="wy-nav" aria-label="Walleye">
    <a href="/walleye/">Home</a> <a href="/walleye/viewer/">Viewer</a> <a href="/walleye/examples/">Examples</a>
    <a href="/walleye/setup/">Set up</a> <a href="/walleye/how-to/">How to</a>
    <a href="/atlas/">Atlas</a> <a href="/palace/">Wending House</a>
  </nav>
</header>
<main id="main" class="wy-main"> ... </main>
<footer class="wy-footer"> ... </footer>
```

Mark the current page's link with `aria-current="page"`. A plain `nav`
inside `.wy-header` is styled the same as `.wy-nav`.

| class | for |
|---|---|
| `.wy-page` | the body: background, serif text, rem sizes |
| `.wy-header`, `.wy-brand`, `.wy-nav` | site header |
| `.wy-main`, `.wy-footer`, `.wy-lede`, `.wy-crumb` | page parts; `.wy-lede` is the opening paragraph |
| `.wy-skip` | skip link, visible on focus |
| `.wy-grid`, `.wy-card` | gallery grid and cards; a card shows a focus ring when focused (give it `tabindex="-1"` to focus it from script) and an accent outline when it is the `:target` or has `.is-returned` |
| `.wy-badge` and `--seed`, `--historical`, `--new`, `--educational`, `--mathematics`, `--science`, `--intro`, `--intermediate`, `--advanced` | small labels |
| `.wy-btn`, `.wy-btn--primary` | buttons and button-like links; `[aria-pressed="true"]` is filled |
| `.wy-stage`, `.wy-reserve`, `.wy-viewer`, `.wy-toolbar`, `.wy-group`, `.wy-coach`, `.wy-status`, `.wy-caption`, `.wy-credit`, `.wy-keys` | the viewer |
| `.wy-note` | an aside |
| `.wy-steps` | numbered steps (an `ol`) |
| `.wy-figure` | a figure with a caption |
| `.wy-field`, `.wy-check`, `.wy-choices`, `.wy-choice`, `.wy-output` | form rows (the setup page) |
| `.wy-sr` | visually hidden text |
| `.wy-theme-toggle` | a theme button in the header |

Every element with an `id` has `scroll-margin-block: 5rem` (cards 30vh), so
deep links do not land under the top edge; for true centring call
`el.scrollIntoView({block: 'center'})` as the gallery does. Text contrast is
at least 4.5:1 in both themes; `prefers-reduced-motion`,
`prefers-contrast: more` and forced colours are honoured; the layout works at
360 px wide with no sideways scroll.

## Tests

`node walleye/tests/smoke.js` serves the site with `python3 -m http.server`
on a free port and checks the viewer and setup pages in Chromium at 1280 and
375 px: no console errors, a stage that keeps its box through every mode,
Home and `0`, clamped pitch, the key list's focus return, reduced-motion
wiggle, a picture pair, every gallery scene, saved settings reaching the
viewer, and drawing speed. Screenshots go to `walleye/tests/screenshots/`.
