diff --git a/CHANGELOG.md b/CHANGELOG.md index 40508e4..b55eb9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Documentation +- Establish the **Split Screen peer floor of 1.10.6** (issue #40). Piano is standalone-compatible, but focused multi-panel MIDI routing depends on Split Screen's six-method `window.slopsmithSplitscreen` focus API, and the repo carried two unresolved numbers for it: the earliest auditable provider snapshot (1.10.6, commit `54db8d2`) and a later version a maintainer had hand-verified (1.14.5). The six methods are byte-identical at those two snapshots, and all 26 version runs in between (1.10.6 → 1.14.21) carry them, so 1.10.6 is published as the floor — superseding the 1.14.5 "checked floor" note below. Only 1.14.20 carries a git tag, so the manifest `version` is the identity, the same rule core follows. README.md's "Requirements" gains a fourth entry declaring Split Screen as an *optional peer*: not needed for the board, MIDI input, or scoring, but required for focused multi-panel MIDI routing, with the six helper methods tabled and the degraded behavior on a partial or older surface stated as behavior rather than as "fail-soft" — focus stops being authoritative (routed notes and their scoring follow panel mount order, not the panel the user is looking at) and chrome falls back to the shared player mount and control rail. `tests/host-compat.test.js` pins every state — absent, partial in each of its two shapes, the 1.10.6 floor, and the current 1.14.21 surface. The current-surface test drives each panel through its whole lifecycle (mount, draw, resize, the first settings open, a host canvas replacement, then `destroy()`) before reading the helper's call log, so a dependency on a method the floor does not publish fails the test from whichever code path introduced it. The two partial fixtures pin that the three wrappers (`panelChromeFor` / `settingsAnchorFor` / `isCanvasFocused`) are all-or-nothing on the full-surface check while the subscribe/unsubscribe pair is gated only on its own two halves existing — they degrade identically and are consumed differently. The floor is not recorded in `plugin.json`: feedBack's manifest schema has no feature-scoped optional-dependency field and closes `capabilities.*` to unknown keys (audited at `af29496`), so the tests are the executable record until a host learns to read one. - Detect core drifting from the declared minimum-host surface (issue #43): `tools/verify-host-surface.js` clones core, diffs its `VERSION` against the two audited refs (`803bd0c` = `0.3.0-alpha.1`, `3a4dd7a` = `0.3.0-alpha.2`), and probes current upstream `main` as well as both audited refs for every API the README host table declares. `tests/host-compat.test.js` pins the plugin's behavior against hand-written fixtures, so it structurally cannot notice core renaming `logicalSourceKey` or dropping `ui.playerControlSlot()`; this script closes that gap from the other side. It needs the network, so `.github/workflows/host-surface-drift.yml` runs it on a schedule and on `workflow_dispatch`, mirroring `sri-drift.yml`. The network-free half runs per-PR: four new tests fail if a probe has no README row, a README row has no probe, a ref or `VERSION` in the checker is not cited in the README, or `screen.js` subscribes to a host event nothing probes. They read `SURFACE` and `AUDITED_REFS` out of the tool and compare both directions on the same normalized token, so a probe for a name the README no longer claims fails as loudly as a README row nothing probes. `tests/host-surface-checker.test.js` covers the CLI's non-zero exit against a reachable local ref, first-party file filtering, and a probe that hits, one that misses on a present file, and one whose path core no longer has. A `VERSION` that is missing or renamed at a ref is reported in the tool's own format — `could not read VERSION at ` — and the refs after it are still audited, instead of the run dying on a raw `git show` trace. - Declare and document the tested minimum host, **feedBack core v0.3.0-alpha.1** (issue #39) — the first core commit whose `VERSION` reads `0.3.0-alpha.1` (`803bd0c`), and the earliest snapshot whose source carries every API this plugin consumes. Core publishes no git tags, so `VERSION` is the identity to compare against. README.md's "Requirements" section now splits the three independent prerequisites: the core version (with a per-API surface table, marking `window.highway.resize()` as optional), Web MIDI browser/permission support, and the WebAudioFont network/audio prerequisites for the built-in synth. Documents the visualization-only fallback (no `midi-input` domain, or a non-v1 one, still renders) as a supported state rather than an error. This is a source-level compatibility floor, not a runtime certification of every older snapshot. - Add `tests/host-compat.test.js`: the executable half of the minimum-host declaration. Its fixtures reproduce the alpha.1 host surface (event bus, chart bundle, `midi-input` v1 domain, optional splitscreen helper) and pin mount/draw/resize/destroy, MIDI discovery and routing, session release, pause/seek/song change, the visualization-only and no-event-bus fallbacks, and split-panel focus routing. The 13 tests run only against those fixtures, never a live core; the matching `0.3.0-alpha.2` (`3a4dd7a`) evidence is a source audit of the same APIs, whose surface is a superset of alpha.1's. diff --git a/CLAUDE.md b/CLAUDE.md index f2b528e..a6fc007 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,12 +79,24 @@ Under splitscreen, multiple panels can run a Piano instance simultaneously, but only one keyboard input source (MIDI, or the on-screen keyboard) should ever be "live" at a time — the one the user is currently looking at/using. `window.slopsmithSplitscreen` exposes a small helper surface for this; -Piano is the only plugin observed consuming it end-to-end. The full -six-method surface (`isActive`/`isCanvasFocused`/`panelChromeFor`/ -`settingsAnchorFor`/`onFocusChange`/`offFocusChange`) is verified present -as of `feedback-plugin-splitscreen` **v1.14.5**; not a hard requirement -per the full-surface-validation design described next — but this is the -minimum version this integration has actually been checked against. +Piano is the only plugin observed consuming it end-to-end. + +Split Screen is an **optional peer** — standalone Piano consumes none of it, +and nothing in this integration is a precondition for the board to render. +The peer floor is **`feedBack-plugin-splitscreen` 1.10.6** — the repository's +earliest auditable snapshot (commit `54db8d2`) — where the full six-method +surface (`isActive` / `isCanvasFocused` / `panelChromeFor` / +`settingsAnchorFor` / `onFocusChange` / `offFocusChange`) is already +published. It was audited at that snapshot and at `main` (1.14.21, +`aefac76`): the six methods are byte-identical, and so is every version run +in between (26 of them, 1.10.6 → 1.14.21). The plugin calls nothing beyond +the six — current splitscreen publishes eight more, and the surface map in +`tests/host-compat.test.js` fails if a post-floor method is ever required. +Splitscreen tags only 1.14.20, so the manifest `version` is the identity to +compare against, the same rule core follows. **The floor is a two-snapshot +source audit plus four contract fixtures, not a runtime certification of the +builds in between** — a partial surface is a supported state, not a +violation of the floor. `_ssActive()` (see "Splitscreen helper wrappers" in `screen.js`) validates the **entire** surface this plugin needs before treating splitscreen as @@ -96,6 +108,29 @@ active," which falls the plugin back to the main-player single-instance fast path rather than reaching a half-broken state where focus never lands on any instance and MIDI routing silently dies. +The fallback is fail-soft, but calling it merely *safe* undersells it. What +actually changes under a real split-panel host: + +- **Focus stops being authoritative.** `_ssIsCanvasFocused()` returns `true` + unconditionally, so every instance claims focus and the module-level + `_activeInstance` routing slot lands on whichever panel initialised last. + Played notes and their scoring go to that panel, not the one the user is + looking at. Nothing is dropped and nothing throws. +- **Chrome falls back to the shared player.** `_ssPanelChrome()` and + `_ssSettingsAnchor()` return `null`, so the overlay canvas and settings + panel mount against `#player` (`_createOverlayCanvas`, + `_createSettingsPanel`) and the gear docks in `ui.playerControlSlot()` / + `#player-controls` (`_injectSettingsGear`) — N panels stack N overlays and + N gears in the same place. +- **Chrome and focus are all-or-nothing.** `_ssActive()` gates the three + wrappers, so a partial surface is never asked for chrome, anchoring or + focus — only `isActive()` is called for those. The subscribe/unsubscribe + pair is *not* gated on `_ssActive()`: `init()`/`destroy()` check only that + both halves exist, so a surface missing something *other* than + `offFocusChange` still subscribes (and still releases, symmetrically). What + that pair has to guarantee is symmetry, not authority — a listener firing + while every panel reports itself focused changes nothing. Pinned by both + partial-surface fixtures in `tests/host-compat.test.js`, one per shape. - **Subscribe** — `init()` calls `ss.onFocusChange(_onFocusChange)` only when *both* `onFocusChange` and `offFocusChange` exist on the helper. A subscribe without a matching unsubscribe path would leak the listener @@ -129,7 +164,13 @@ splitscreen panel is live" behavior, copy this pattern (full surface validation, subscribe/unsubscribe symmetry, the destroyed-instance guard) rather than reaching for `window.slopsmithSplitscreen` directly — the partial-surface fallback is what keeps this safe across splitscreen -version skew. +version skew. **The floor is recorded in prose only.** feedBack's manifest +schema (`docs/plugin-manifest.schema.json`) has no feature-scoped +optional-dependency field, and a `capabilities.*` block is closed to unknown +keys, so `plugin.json` cannot carry the peer version; the executable record +is the absent / partial / floor / current fixture set in +`tests/host-compat.test.js`, whose surface map is the authority on which +methods the floor covers. ## Versioning @@ -145,9 +186,12 @@ The declared minimum host is **feedBack core v0.3.0-alpha.1** (issue #39) — the first core commit whose `VERSION` reads `0.3.0-alpha.1` (`803bd0c`), the earliest snapshot carrying every host API this plugin consumes. Core publishes no git tags, so `VERSION` is the identity to compare against. -README.md's "Requirements" section carries the full surface table plus the +README.md's "Requirements" section carries the full surface table, the three independently-checked requirements (core version, Web MIDI -browser/permission support, WebAudioFont network/audio prerequisites). +browser/permission support, WebAudioFont network/audio prerequisites), and +the optional Split Screen peer floor (README "Requirements" item 4, +"*Peer plugin (optional): Split Screen, for focused multi-panel MIDI*"), +which the integration below implements. `tests/host-compat.test.js` is the executable half of that declaration: its fixtures reproduce the alpha.1 host surface (event bus, chart bundle, @@ -203,11 +247,12 @@ node --test tests/*.test.js # node:test — no package.json/build step in ``` Two suites: `tests/screen.test.js` (helper and rendering coverage) and -`tests/host-compat.test.js` (the minimum-host contract). Both share the -DOM/`window` stub in `tests/harness.js` — `installBrowserHarness({ feedBack, -slopsmith, slopsmithSplitscreen, storage })` — so host-contract fixtures -(the `midi-input` domain, the event bus, the splitscreen helper) live in -the suites rather than in the harness itself. +`tests/host-compat.test.js` (the minimum-host and peer-floor contracts). +Both share the DOM/`window` stub in `tests/harness.js` — +`installBrowserHarness({ feedBack, slopsmith, slopsmithSplitscreen, +storage })` — so host-contract fixtures (the `midi-input` domain, the event +bus, the splitscreen helper) live in the suites rather than in the harness +itself. `screen.js` exports a Node-only test hook (`module.exports`, guarded by `typeof module !== 'undefined'`) alongside the browser `window.*Viz_piano` diff --git a/README.md b/README.md index bc93c03..7671a36 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ A plugin for [Slopsmith](https://github.com/got-feedback/feedback) that replaces ## Requirements -These are three independent requirements — satisfying one does not imply the others. Core compatibility, browser support for MIDI, and network access for the built-in synth are checked separately below. +These are four independent prerequisites — satisfying one does not imply the others. The first three are requirements: core compatibility, browser support for MIDI, and network access for the built-in synth. The fourth is an optional peer plugin that decides what Piano can do when several panels are open at once. Each is checked separately below. ### 1. Host: feedBack core v0.3.0-alpha.1 or newer @@ -45,11 +45,11 @@ Rows are grouped by what the plugin can *do* when the host provides them, not by | `feedBack.uiVersion` + `feedBack.ui.playerControlSlot()` | Settings gear placement in the v3 player | | `window.highway.resize()` *(optional)* | Nudges the host's measure pass after the plugin changes player-control layout | -`tests/host-compat.test.js` pins this floor as an executable contract: each fake host in that file reproduces the rows above, and the renderer must mount, draw, route MIDI, survive pause/seek/song changes, and tear down against it. The 13 tests run only against those fixtures, never against a live core; the evidence for `0.3.0-alpha.2` (`3a4dd7a`) is a source audit of the same APIs, whose surface is a superset of alpha.1's — the two `setRenderer` / `matchesArrangement` sites moved from `static/app.js` to `static/js/viz.js`, with no change to the published contract. `tools/verify-host-surface.js` re-checks both audited refs and current upstream `main` on a schedule, so core drifting from this table fails loudly. +`tests/host-compat.test.js` pins this floor as an executable contract: each fake host in that file reproduces the rows above, and the renderer must mount, draw, route MIDI, survive pause/seek/song changes, and tear down against it. Every test in that file runs only against those fixtures, never against a live core; the evidence for `0.3.0-alpha.2` (`3a4dd7a`) is a source audit of the same APIs, whose surface is a superset of alpha.1's — the two `setRenderer` / `matchesArrangement` sites moved from `static/app.js` to `static/js/viz.js`, with no change to the published contract. `tools/verify-host-surface.js` re-checks both audited refs and current upstream `main` on a schedule, so core drifting from this table fails loudly. This is a source-level compatibility floor, not a runtime certification of every historical snapshot: no test here claims that all builds older than alpha.1 fail, only that alpha.1 is the earliest one examined that provides everything the plugin needs. -**Visualization-only fallback.** The renderer and MIDI input have different requirements. The scrolling piano view works on a visualization-only host — a core with no `midi-input` domain, or one whose domain is not v1, still renders the board; what is lost is everything reachable only from a played note — the MIDI device list, note-on/note-off, the synth voice it triggers, and hit detection — and the settings panel shows an empty device list. The synth is a monitor for what you play, not a backing track: nothing in the plugin sounds a note on its own. Likewise, a host with no event bus falls back to plain `window` events, and a host without the `window.slopsmithSplitscreen` helper runs the single-panel focus path. +**Visualization-only fallback.** The renderer and MIDI input have different requirements. The scrolling piano view works on a visualization-only host — a core with no `midi-input` domain, or one whose domain is not v1, still renders the board; what is lost is everything reachable only from a played note — the MIDI device list, note-on/note-off, the synth voice it triggers, and hit detection — and the settings panel shows an empty device list. The synth is a monitor for what you play, not a backing track: nothing in the plugin sounds a note on its own. Likewise, a host with no event bus falls back to plain `window` events, and a host without the full `window.slopsmithSplitscreen` helper runs the single-panel focus path (see requirement 4). ### 2. Browser: Web MIDI support for MIDI keyboard input @@ -63,6 +63,31 @@ MIDI features are optional — the piano view works without a MIDI keyboard. The instrument playback is **WebAudioFont**-based. On first use the plugin loads `WebAudioFontPlayer.js` and the soundfont data from `surikov.github.io`, so built-in sound needs network access (or a reachable cache) and an `AudioContext` the browser will allow to start — most browsers block audio until a user gesture, so the first note may need a click on the player. If either the script or the soundfont fails to load, the plugin logs a warning and everything except audio keeps working; note visuals, MIDI input and scoring are unaffected. +### 4. Peer plugin (optional): Split Screen, for focused multi-panel MIDI + +Piano needs no peer plugin. There is nothing extra to install for the board, MIDI input, or scoring. [Split Screen](https://github.com/get-flashbacks/feedBack-plugin-splitscreen) is needed for one thing: **focused multi-panel MIDI routing**. + +Under Split Screen several panels can each run a Piano instance, but a MIDI keyboard is a single browser-wide input. Only the panel the user is looking at may react to it, and only that panel may drive the shared synth. That decision comes from Split Screen's `window.slopsmithSplitscreen` helper, whose six methods this plugin consumes: + +| Peer API | Used for | +|---|---| +| `isActive()` | Whether split panels are live at all — `false` in the main player | +| `isCanvasFocused(canvas)` | Whether *this* panel is the focused one, which decides MIDI routing | +| `panelChromeFor(canvas)` | The panel element the overlay canvas and settings panel mount into | +| `settingsAnchorFor(canvas)` | That panel's control bar, where the settings gear docks | +| `onFocusChange(fn)` / `offFocusChange(fn)` | Subscribe / unsubscribe, so held notes release when focus moves away | + +**Peer floor: Split Screen 1.10.6.** That is the earliest auditable snapshot of that helper (commit `54db8d2`), and all six methods are already there, byte-identical to how they read on `main` (1.14.21, `aefac76`) — every version in between carries them too. Splitscreen tags only 1.14.20, so compare the manifest `version` — the same identity rule core follows for itself. Like the core floor above, this is a source-level audit of two snapshots plus executable fixtures, not a runtime certification of every build in between. + +**Degraded behavior on a partial or older surface.** The plugin treats anything less than the full six as "Split Screen is not present": panel chrome, settings anchoring and the focus probe are all-or-nothing, so none of them are asked of a partial surface and every panel falls back to resolving itself as focused. (The focus *subscription* is the one exception — it is taken whenever both `onFocusChange` and `offFocusChange` exist, and released on teardown, because a listener that can always be removed is harmless even while focus is not authoritative.) That is fail-soft, but under split panels it changes behavior rather than only avoiding errors: + +- **Focus stops being authoritative.** Every panel resolves as focused, so a played note lands on whichever panel initialised last, not the one you are looking at. Note rendering is unaffected; the key-press feedback and its scoring go to the wrong panel. +- **Chrome falls back to the shared player.** The overlay canvas and settings panel mount against the whole `#player` instead of a panel, and the settings gear docks in the shared control rail — with N panels open you get N overlays and N gears stacked in the same place. + +`tests/host-compat.test.js` pins every state — no helper at all, a partial surface in each of its two shapes, the 1.10.6 floor, and the current 1.14.21 surface — so the fallback is a tested contract rather than a hope. The current-surface test drives each panel through its whole lifecycle (mount, draw, resize, the first settings open, a host canvas replacement, then `destroy()`) before reading the helper's call log, so a dependency on a method the floor does not publish fails the test from whichever code path introduced it. + +**Where the floor is recorded.** Here, in `CLAUDE.md`, and in those tests — feedBack's plugin manifest has no feature-scoped optional-dependency field to declare it in. Audited against core's `docs/plugin-manifest.schema.json` at `af29496` (its last change as of `main` `ed0db38`): the top level carries no `requires` / `peerDependencies` key, and a `capabilities.*` block is closed to unknown fields (`additionalProperties: false`). So the floor cannot live in `plugin.json` until the host learns to read one; if a future core adds such a field, this is the value it should carry. + ## Installation ```bash diff --git a/screen.js b/screen.js index 93cf28b..68e9536 100644 --- a/screen.js +++ b/screen.js @@ -8,9 +8,11 @@ // display range, settings UI, held-notes state, and listeners are // now all per-instance (closured inside createFactory). Main-player // usage keeps its single-instance fast path via the -// window.slopsmithSplitscreen helper surface — its absence OR -// isActive()===false means "we're the only instance, always -// focused." +// window.slopsmithSplitscreen helper surface — its absence, +// isActive()===false, or an incomplete surface all mean +// "we're the only instance, always focused." See the Splitscreen +// helper wrappers section for what that costs when a host really +// does have several panels up. // // Under splitscreen (N panels, N simultaneous piano instances): // - each panel hosts its own overlay canvas, scoring, display @@ -1308,6 +1310,14 @@ function _approachAlpha(midi, notes, chords, t, handFilter = _cfg.handFilter) { // anchors?" queries so instance code can read the runtime environment // cheaply. Absence of window.slopsmithSplitscreen OR isActive()===false // means "main-player, always focused" from the plugin's POV. +// +// Split Screen is an OPTIONAL peer — standalone Piano needs none of this. +// What it buys is per-panel chrome and, above all, authoritative focus for +// MIDI routing: with several panels up, only the focused one may react. +// The peer floor is 1.10.6, the earliest auditable snapshot of the +// six-method surface (README "Requirements" carries the declaration, +// tests/host-compat.test.js pins it with absent / partial / floor / +// current fixtures). function _ssActive() { const ss = window.slopsmithSplitscreen; @@ -1318,7 +1328,25 @@ function _ssActive() { // newer methods), report "not active" so the wrappers fall // back to the main-player single-instance fast path rather // than reaching a half-broken splitscreen state where focus - // never lands on any instance and MIDI routing dies. + // never lands on any instance and MIDI routing silently dies. + // + // Fail-soft is not free, and the cost is documented rather than + // glossed: every panel then resolves as focused, so the + // module-level MIDI routing slot ends up on whichever panel + // initialised last instead of the one the user is looking at, and + // panel chrome / the settings gear fall back to the whole-player + // mount and the shared control rail — N panels stack N overlays + // and N gears in the same place. + // + // The three wrappers below are gated on this, so they are + // all-or-nothing: half a focus API cannot route MIDI, and a partial + // surface is never asked for chrome, anchoring or focus. The + // subscribe/unsubscribe pair is NOT gated here — init() and + // destroy() check only that both halves exist, because what they + // have to guarantee is symmetry (never subscribe without a way to + // release), and a listener that fires while every panel reports + // itself focused changes nothing. Both partial shapes are pinned by + // their own fixtures in tests/host-compat.test.js. return typeof ss.isCanvasFocused === 'function' && typeof ss.panelChromeFor === 'function' && typeof ss.settingsAnchorFor === 'function' diff --git a/tests/host-compat.test.js b/tests/host-compat.test.js index d1509ee..ae8f273 100644 --- a/tests/host-compat.test.js +++ b/tests/host-compat.test.js @@ -81,21 +81,38 @@ function createMidiDomain(devices = [{ sourceId: 'd1', label: 'Test Keys', logic // A split-panel host helper exposing the six-method surface the plugin // validates. `focused` is mutable so a test can move focus between panels. +// `extras` publishes the methods a later splitscreen snapshot added on top of +// the six, `omit` removes one, and every call is recorded in `calls` so a test +// can assert which methods the plugin actually reached for. `registerPanel` +// gives a panel its own chrome/bar, mirroring the real canvas -> panel index +// -> panel.div / panel.bar resolution. function createSplitscreenHelper(options = {}) { const focusListeners = new Set(); + const panels = new Map(); + const calls = []; + const chromeOf = (canvas, key) => (panels.get(canvas) || {})[key] || helper.chrome; const helper = { active: options.active !== false, focusedCanvas: options.focusedCanvas || null, chrome: options.chrome || null, - isActive() { return helper.active; }, - isCanvasFocused(canvas) { return helper.focusedCanvas === canvas; }, - panelChromeFor() { return helper.chrome; }, - settingsAnchorFor() { return helper.chrome; }, - onFocusChange(fn) { focusListeners.add(fn); }, - offFocusChange(fn) { focusListeners.delete(fn); }, + calls, + isActive() { calls.push(['isActive']); return helper.active; }, + isCanvasFocused(canvas) { + calls.push(['isCanvasFocused', canvas]); + return helper.focusedCanvas === canvas; + }, + panelChromeFor(canvas) { calls.push(['panelChromeFor', canvas]); return chromeOf(canvas, 'panelDiv'); }, + settingsAnchorFor(canvas) { calls.push(['settingsAnchorFor', canvas]); return chromeOf(canvas, 'bar'); }, + onFocusChange(fn) { calls.push(['onFocusChange', fn]); focusListeners.add(fn); }, + offFocusChange(fn) { calls.push(['offFocusChange', fn]); focusListeners.delete(fn); }, focusListenerCount() { return focusListeners.size; }, setFocused(canvas) { helper.focusedCanvas = canvas; for (const fn of focusListeners) fn(); }, + registerPanel(canvas, chrome) { panels.set(canvas, chrome); return helper; }, }; + for (const name of options.extras || []) { + helper[name] = (...args) => { calls.push([name, ...args]); }; + } + for (const name of options.omit || []) delete helper[name]; return helper; } @@ -110,6 +127,78 @@ const BUNDLE = { toneChanges: [{ t: 0, name: 'Keys' }], }; +// Mounts `count` panels laid out the way Split Screen lays them out: a panel +// div per panel (its chrome / overlay host) holding that panel's control bar +// and its own highway canvas, all under #player. Panels are registered with +// `split` before `init()` because that is the order the real host uses — the +// renderer resolves its panel chrome during init(). `split` may be null for +// the no-peer case, where nothing resolves per panel. +function mountSplitPanels(plugin, harness, split, count) { + const player = harness.doc.elementsById.player; + return Array.from({ length: count }, () => { + const panelDiv = harness.doc.createElement('div'); + const bar = harness.doc.createElement('div'); + const canvas = harness.doc.createElement('canvas'); + canvas.clientWidth = 640; + canvas.clientHeight = 360; + panelDiv.appendChild(bar); + panelDiv.appendChild(canvas); + player.appendChild(panelDiv); + if (split) split.registerPanel(canvas, { panelDiv, bar }); + const renderer = plugin._createFactory(); + renderer.init(canvas); + return { panelDiv, bar, canvas, renderer }; + }); +} + +// Counts note-ons per panel (by the `keys` label) so a MIDI-routing claim can +// be asserted on *which* instance received the stream. +function countNoteOns(panels, keys) { + const seen = Object.fromEntries(keys.map(key => [key, 0])); + panels.forEach((panel, i) => { + const original = panel.renderer._handleNoteOn; + panel.renderer._handleNoteOn = (midi, velocity) => { + seen[keys[i]] += 1; + return original(midi, velocity); + }; + }); + return seen; +} + +// Drives one panel through every lifecycle entry point that reaches the +// splitscreen helper, so a containment assertion over the call log is a fact +// about the whole lifecycle and not just about mount: `draw()` +// (`_renderLatestBundle`), `resize()` (`_applyCanvasDims` -> `_ssPanelChrome`), +// the first settings open (`_createSettingsPanel` -> `_ssPanelChrome`) and a +// host canvas replacement (`_rebuildOverlayForCanvas`, which re-resolves +// chrome, re-injects the gear and restores the settings panel). `mount()`'s +// init() only covers the first of those, so a helper call introduced in any +// other path — a `ss.getPanels()` while laying out the overlay, say — would +// never reach the log and the guard would pass silently. `destroy()` is the +// one entry point left out here, because it tears the panel down rather than +// exercising it; the caller destroys before reading the log so teardown is +// covered too. +function exercisePanelLifecycle(panel, host, split) { + panel.renderer.draw(BUNDLE); + panel.renderer.resize(800, 400); + + const gear = [...panel.bar.children, ...panel.panelDiv.children] + .find(el => String(el.className).startsWith('btn-piano-settings')); + gear.onclick(); + + // The host swapping the highway canvas re-mounts the overlay, which is the + // other path that re-resolves per-panel chrome. The replacement has to be + // registered with the helper first, the way the real host resolves + // canvas -> panel index -> panel.div. + const replacement = panel.canvas.ownerDocument.createElement('canvas'); + replacement.clientWidth = 800; + replacement.clientHeight = 400; + panel.panelDiv.appendChild(replacement); + split.registerPanel(replacement, { panelDiv: panel.panelDiv, bar: panel.bar }); + host.emit('highway:canvas-replaced', { canvas: replacement }); + return replacement; +} + function mount(options = {}) { const host = createCoreHost(options); const result = initRendererWithHarness({ @@ -362,12 +451,12 @@ test('renders on a host with no event bus at all (window-event fallback)', () => // ── Optional split-panel host ───────────────────────────────────────────── -test('subscribes to focus changes only when the helper exposes the full surface', () => { +test('subscribes on init and unsubscribes on destroy whenever the helper has a focus API', () => { const partial = { isActive: () => true, isCanvasFocused: () => true }; const withPartial = mount({ splitscreen: partial }); withPartial.renderer.destroy(); - // A partial helper is reported as "not active", so the plugin must not - // have subscribed to a focus API it cannot later unsubscribe from. + // No focus API to call, so nothing to subscribe to — the wrapper check + // never even gets that far. assert.equal(typeof partial.onFocusChange, 'undefined', 'fixture has no focus API to call'); const full = createSplitscreenHelper(); @@ -386,26 +475,13 @@ test('only the focused panel receives routed MIDI in split-panel mode', async () const split = createSplitscreenHelper(); window.slopsmithSplitscreen = split; - const mountPanel = () => { - const canvas = harness.doc.createElement('canvas'); - canvas.clientWidth = 640; - canvas.clientHeight = 360; - harness.doc.elementsById.player.appendChild(canvas); - const renderer = plugin._createFactory(); - renderer.init(canvas); - return { renderer, canvas }; - }; - const left = mountPanel(); - const right = mountPanel(); + const panels = mountSplitPanels(plugin, harness, split, 2); + const [left, right] = panels; split.setFocused(left.canvas); await new Promise(resolve => setImmediate(resolve)); await new Promise(resolve => setImmediate(resolve)); - const seen = { left: 0, right: 0 }; - const leftOriginal = left.renderer._handleNoteOn; - const rightOriginal = right.renderer._handleNoteOn; - left.renderer._handleNoteOn = (m, v) => { seen.left += 1; return leftOriginal(m, v); }; - right.renderer._handleNoteOn = (m, v) => { seen.right += 1; return rightOriginal(m, v); }; + const seen = countNoteOns(panels, ['left', 'right']); midiInput.handle.emit([0x90, 60, 100]); assert.deepEqual(seen, { left: 1, right: 0 }, 'focused panel is the routing target'); @@ -414,8 +490,235 @@ test('only the focused panel receives routed MIDI in split-panel mode', async () midiInput.handle.emit([0x90, 62, 100]); assert.deepEqual(seen, { left: 1, right: 1 }, 'routing follows focus'); - left.renderer.destroy(); - right.renderer.destroy(); + for (const panel of panels) panel.renderer.destroy(); +}); + +// ── Peer floor: the Split Screen focus API (issue #40) ───────────────────── +// +// Piano is standalone-compatible — with no split-panel host at all it mounts, +// draws and routes MIDI. What it cannot do without the peer is route that +// MIDI by *focus*: with several panels up, only the one the user is looking +// at may react, and only that one may own the shared synth. That needs Split +// Screen's focus API, so the peer carries a floor of its own. +// +// The floor is feedBack-plugin-splitscreen **1.10.6** — the repository's +// earliest auditable snapshot (commit `54db8d2`) — where the six focus +// methods already exist, byte-identical to how they read on `main` today +// (1.14.21, `aefac76`). Every version run in between (1.10.6 → 1.14.21, 26 +// of them) was also checked to carry the six. Only 1.14.20 carries a git +// tag, so the manifest `version` is the identity to compare against, the same +// rule core follows. The two surfaces below are hand-built from the +// `window.slopsmithSplitscreen = {` literal in each snapshot, extras +// included. +// +// `extras` is the whole post-floor surface a snapshot published beyond the +// six. The guard is a positive one — the set of methods the plugin actually +// calls must be a subset of the six — so the property is a fact about +// observed calls rather than about a hand-typed exclusion list, and it can +// only ever get stronger as a snapshot adds methods. +const SPLITSCREEN_PEER_FLOOR = '1.10.6'; +const SPLITSCREEN_CURRENT = '1.14.21'; +const SPLITSCREEN_FOCUS_API = [ + 'isActive', 'isCanvasFocused', 'panelChromeFor', + 'settingsAnchorFor', 'onFocusChange', 'offFocusChange', +]; +const SPLITSCREEN_SURFACES = { + '1.10.6': { extras: ['panelIndexFor'] }, + '1.14.21': { + extras: [ + 'panelIndexFor', 'getPanels', 'panelName', 'setPanelName', 'setPlayerContext', + 'beginOfflineRender', 'renderFrameAt', 'endOfflineRender', + ], + }, +}; + +test('peer floor: the 1.10.6 surface alone drives per-panel chrome, gear anchoring and focus-routed MIDI', async () => { + const midiInput = createMidiDomain(); + const host = createCoreHost({ midiInput }); + const harness = installBrowserHarness({ feedBack: host, slopsmith: host }); + const plugin = loadScreen(); + + const floor = SPLITSCREEN_SURFACES[SPLITSCREEN_PEER_FLOOR]; + const split = createSplitscreenHelper({ extras: floor.extras }); + window.slopsmithSplitscreen = split; + const panels = mountSplitPanels(plugin, harness, split, 2); + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + // Chrome is resolved per panel rather than against the whole player: each + // overlay lands in its own panel div, each gear in its own panel bar. + for (const panel of panels) { + assert.ok(panel.panelDiv.children.some(el => el.className === 'piano-highway-canvas'), + 'overlay mounted into the panel chrome panelChromeFor() returned'); + assert.equal(panel.bar.children.filter(el => el.className.startsWith('btn-piano-settings')).length, 1, + 'settings gear docked in the panel bar settingsAnchorFor() returned'); + } + assert.equal(harness.doc.elementsById.player.children.filter(el => el.className === 'piano-highway-canvas').length, 0, + 'no overlay fell back to the whole-player mount point'); + assert.deepEqual( + [...new Set(split.calls.filter(([name]) => name === 'panelChromeFor').map(([, canvas]) => canvas))], + panels.map(panel => panel.canvas), + 'each panel asked the helper about its own canvas'); + + // Each live instance holds a focus subscription, and releases it on teardown. + assert.equal(split.focusListenerCount(), panels.length, 'one focus subscription per panel'); + + const seen = countNoteOns(panels, ['left', 'right']); + split.setFocused(panels[0].canvas); + midiInput.handle.emit([0x90, 60, 100]); + assert.deepEqual(seen, { left: 1, right: 0 }, 'only the focused panel takes the note'); + + for (const panel of panels) panel.renderer.destroy(); + assert.equal(split.focusListenerCount(), 0, 'every subscription released on teardown'); +}); + +test('the current 1.14.21 surface is consumed no further than the floor', async () => { + const midiInput = createMidiDomain(); + const host = createCoreHost({ midiInput }); + const harness = installBrowserHarness({ feedBack: host, slopsmith: host }); + const plugin = loadScreen(); + + const current = SPLITSCREEN_SURFACES[SPLITSCREEN_CURRENT]; + const split = createSplitscreenHelper({ extras: current.extras }); + window.slopsmithSplitscreen = split; + const panels = mountSplitPanels(plugin, harness, split, 2); + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const seen = countNoteOns(panels, ['left', 'right']); + split.setFocused(panels[1].canvas); + midiInput.handle.emit([0x90, 62, 100]); + assert.deepEqual(seen, { left: 0, right: 1 }, 'routing follows focus on the current surface too'); + + // Every lifecycle entry point that can reach the helper, teardown included, + // before the call log is read — otherwise a post-floor call hiding in the + // draw, resize, settings, overlay-rebuild or destroy path would never be + // recorded here. + for (const panel of panels) exercisePanelLifecycle(panel, host, split); + for (const panel of panels) panel.renderer.destroy(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(split.focusListenerCount(), 0, + 'teardown reached the helper, so the reads below cover its calls too'); + + // What makes 1.10.6 the floor: the plugin reaches for nothing at all + // outside the six methods the floor already ships, so the current + // snapshot's extra eight methods are inert to it. Stated as positive + // containment of the observed calls rather than as an exclusion list, so + // the guarantee is a fact about what the plugin did — a post-floor + // dependency fails here instead of being excused by the current + // snapshot, and the 1.10.6 test above already shows the same routing with + // only the floor's surface present. + const called = [...new Set(split.calls.map(([name]) => name))]; + assert.ok(called.length > 0, 'the plugin did consult the helper at all'); + for (const name of called) { + assert.ok(SPLITSCREEN_FOCUS_API.includes(name), + `the plugin called \`${name}\`, which the ${SPLITSCREEN_PEER_FLOOR} floor does not publish`); + } +}); + +// A partial focus surface is not one behaviour but two, and which one you get +// depends on *which* method is missing. The three wrappers +// (`_ssPanelChrome` / `_ssSettingsAnchor` / `_ssIsCanvasFocused`) are +// all-or-nothing: they short-circuit on `_ssActive()`, so a surface missing +// any of them never has chrome, anchoring or focus asked of it. The +// subscribe/unsubscribe pair is not gated on `_ssActive()` at all — `init()` +// and `destroy()` check only that both halves exist — so a surface missing +// something else still gets `onFocusChange`, and still releases it on +// teardown, which is the property that actually matters. Each shape has its +// own fixture below: they degrade identically and are consumed differently. +function assertChromeFellBackToSharedRail(harness, host, panels) { + const gearsIn = (el) => el.children.filter(child => child.className.startsWith('btn-piano-settings')).length; + assert.equal(harness.doc.elementsById.player.children.filter(el => el.className === 'piano-highway-canvas').length, + panels.length, 'each overlay fell back to the whole-player mount point'); + assert.equal(gearsIn(host.ui.playerControlSlot()), panels.length, 'gears stacked in the shared control rail'); + for (const panel of panels) { + assert.equal(gearsIn(panel.panelDiv) + gearsIn(panel.bar), 0, 'nothing docked inside the panel'); + } +} + +test('a partial surface missing the unsubscribe half is probed with isActive() and then left entirely alone', async () => { + const midiInput = createMidiDomain(); + const host = createCoreHost({ midiInput }); + const harness = installBrowserHarness({ feedBack: host, slopsmith: host }); + const plugin = loadScreen(); + + // Five of the six: `offFocusChange` is missing, so a subscribe could not + // be undone. This is the version skew the full-surface check exists for. + const split = createSplitscreenHelper({ omit: ['offFocusChange'] }); + assert.equal(typeof split.offFocusChange, 'undefined', 'fixture really is missing the unsubscribe half'); + window.slopsmithSplitscreen = split; + const panels = mountSplitPanels(plugin, harness, split, 2); + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + // The subscribe is gated on the pair, so losing one half costs the whole + // pair: isActive() is all this surface is asked for. + assert.deepEqual([...new Set(split.calls.map(([name]) => name))], ['isActive'], + 'a surface that cannot be unsubscribed from is never subscribed to'); + assert.equal(split.focusListenerCount(), 0, 'no focus subscription without a matching unsubscribe'); + + // Degradation, stated as behavior rather than as "safe": the overlays fall + // back to the whole-player mount and the gears to the shared control rail + // instead of each panel's own chrome and bar. + assertChromeFellBackToSharedRail(harness, host, panels); + + for (const panel of panels) panel.renderer.destroy(); +}); + +test('a partial surface missing a chrome lookup still subscribes, and still unsubscribes', async () => { + const midiInput = createMidiDomain(); + const host = createCoreHost({ midiInput }); + const harness = installBrowserHarness({ feedBack: host, slopsmith: host }); + const plugin = loadScreen(); + + // The other shape: `panelChromeFor` is gone but the focus pair is intact. + // `init()` does not consult `_ssActive()` before subscribing, so this + // surface is used for the subscription and only for that. + const split = createSplitscreenHelper({ omit: ['panelChromeFor'] }); + assert.equal(typeof split.onFocusChange, 'function', 'fixture really does have the subscribe pair'); + window.slopsmithSplitscreen = split; + const panels = mountSplitPanels(plugin, harness, split, 2); + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + // The wrappers are all-or-nothing: no chrome lookup, no settings anchor, + // no focus probe — only the subscription, whose halves are symmetric. + assert.deepEqual([...new Set(split.calls.map(([name]) => name))], ['isActive', 'onFocusChange'], + 'chrome and focus stay untouched on a partial surface; only the symmetric subscription is taken'); + assert.equal(split.focusListenerCount(), panels.length, 'one focus subscription per panel'); + + assertChromeFellBackToSharedRail(harness, host, panels); + + for (const panel of panels) panel.renderer.destroy(); + assert.deepEqual([...new Set(split.calls.map(([name]) => name))], ['isActive', 'onFocusChange', 'offFocusChange'], + 'every subscription released on teardown'); + assert.equal(split.focusListenerCount(), 0, 'no listener outlives its instance'); +}); + +test('with no split-panel host at all the board still renders, but MIDI follows mount order', async () => { + const midiInput = createMidiDomain(); + const host = createCoreHost({ midiInput }); + const harness = installBrowserHarness({ feedBack: host, slopsmith: host }); + const plugin = loadScreen(); + + // No helper on window at all — the standalone case, which must keep working. + const panels = mountSplitPanels(plugin, harness, null, 2); + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(window.slopsmithSplitscreen, undefined, 'no peer on window'); + + for (const panel of panels) assert.doesNotThrow(() => panel.renderer.draw(BUNDLE)); + + // Every instance resolves itself as focused (the main-player fast path), + // so the routing slot lands on whichever panel initialised last. With one + // panel that is the only panel and the answer is right; with several it is + // why the peer is required for focused multi-panel MIDI rather than merely + // nice to have. + const seen = countNoteOns(panels, ['left', 'right']); + midiInput.handle.emit([0x90, 60, 100]); + assert.deepEqual(seen, { left: 0, right: 1 }, 'the last-mounted panel takes the stream'); + + for (const panel of panels) panel.renderer.destroy(); }); // ── Host-surface declaration drift (issue #43) ─────────────────────────────