# STEM Player V2 — Reusable Web Components

The twelve native Custom Elements are **now independent ECMAScript modules**, not class definitions embedded in `index.html`. They keep their original Shadow DOM, styles, accessibility labels, pointer/keyboard interactions, and composed CustomEvents. No frameworks or Node runtime are required in the browser.

## Use in another application

Import a single element and its local dependencies:

```js
import '../stem-player-v2/components/stem-mixer.js';
const mixer = document.createElement('stem-mixer');
mixer.track = {id:'song',title:'Song',artist:'Artist',stemCount:2,image:''};
mixer.mix = {
  trackId:'song',label:'Full Mix',activeCount:2,totalCount:2,
  stems:[
    {id:'vocals',name:'Vocals',color:'#e67693',on:true,solo:false,gain:0,audible:true},
    {id:'drums',name:'Drums',color:'#e98b57',on:true,solo:false,gain:0,audible:true}
  ]
};
mixer.addEventListener('mixer-action',({detail}) => {
  // Handle {action:'mute'|'solo'|'gain'|'reset',stemId,gain} in your host state.
});
mixer.style.height = '510px'; // Standalone: host must allocate grid height
document.body.append(mixer);
```

Or import `./components/index.js` to register all twelve. JavaScript `import` is enough; do not copy class definitions into your app. Mount components and pass **plain snapshots** to their setters. They emit composed events describing user intent; they do **not** require `StemAppController` or the ALAC engine. If you want V2's existing application state machine, import `./state/stem-app-controller.js`. To integrate actual ALAC playback, import `./services/core-playback-adapter.js` and use the unchanged Core library alongside it.

## Elements and contracts

| Module / custom tag | Public interface | Outbound events / behavior |
|---|---|---|
| `stem-artwork.js` / `stem-artwork` | `.artwork = {image,title,artMode,plate,caption}`; `size="thumb" | "large"` attribute | `artMode="embedded"` shows the original image; `"plate"` builds the STEM EDITION frame. The size attribute adjusts captions, not CSS width; host controls width (e.g. 82px or 260px). |
| `stem-track-item.js` / `stem-track-item` | `.track = track` | `track-select` `{id}` |
| `stem-library.js` / `stem-library` | `.tracks = tracks[]` | `track-select` bubbles from each row |
| `stem-now-playing.js` / `stem-now-playing` | `.track = track` | `player-action` `{action:'favorite'}` |
| `stem-toggle.js` / `stem-toggle` | `.mode`, `.playing`, `.stems` | `player-action` `{action:'toggle-mixer'}` |
| `stem-toolbar.js` / `stem-toolbar` | `.mode`, `.playing`, `.stems` | `player-action` (`toggle-mixer`, `output`, `queue`) |
| `stem-transport.js` / `stem-transport` | `.playback = {trackId,position,duration,playing,shuffle,repeat}` | `player-action` (`play`,`seek`,`skip`,`shuffle`,`repeat`) |
| `stem-player.js` / `stem-player` | `.track`, `.mode`, `.stems`, `.playback`; named `slot="mixer"` | `player-action` (`library`,`more`, other descendant intents) |
| `stem-tile.js` / `stem-tile` | `.stem = {id,name,color,on,solo,gain,audible}` | `stem-action` `{action:'mute'|'solo'|'gain',stemId,gain}`; pointer drag and keyboard |
| `stem-mixer.js` / `stem-mixer` | `.track`, `.mix = {trackId,label,activeCount,totalCount,stems}`; creates one real `<stem-tile>` and one color indicator per `stems[]` item, re-syncs on ID/order/count changes | `mixer-action` `{action:'mute'|'solo'|'gain'|'reset',stemId,gain}` |
| `stem-action-sheet.js` / `stem-action-sheet` | `.sheet = {type,tracks,mode}` | `sheet-dismiss`, `sheet-action` |
| `stem-app.js` / `stem-app` | `.artwork`, `.sheet`, `.showToast(message)`; default slot | Owns ambient layer, overlay, toast; forwards `sheet-*` events |

All emitted events have `bubbles:true` and `composed:true` and can be heard outside Shadow DOM. Passing updated snapshots re-renders the affected components. The individual UI elements own *local* interaction state such as a drag gesture, animation bars, and the open-sheet display. `StemAppController` owns the shared navigation, playback and mix state; `StemPlayerView` connects its snapshots to the UI. `CorePlaybackAdapter` is the only module in this player which opens `.stem.mp4` and talks to the Core playback engine.

See [`examples/standalone.html`](examples/standalone.html) for a self-contained mixer/transport consumer with no ALAC dependency.

## Dependency layout and hosting

The complete player remains at `stem-player-v2/index.html`; it loads `main.js`, which composes the same controller, UI, and frozen Core adapter as before. Serve the **entire suite** over HTTP(S) using a server with JavaScript module MIME types. Keep `stem-player-v2/` beside `stem-core/`, `vendor/` and `standalone-alac-wasm/`. The `mp4box` import map in the player HTML must remain before the module entrypoint.

To integrate components into another suite app, preserve the relative directory tree or adjust the explicit import URLs; a lone `stem-mixer.js` file is not a complete install because it imports `stem-tile.js` and shared helpers. The components do not import Core; the optional Core adapter does.

## Interactive component reference

Open **[`components.html`](components.html)** from the same HTTP(S) directory as the player. It imports `components/index.js`, renders the actual twelve components, documents their public setters, methods and emitted event details, and includes copyable integration examples. The player library screen links to this page through **Components & API**. The previews use mock data and do not load Core or require an audio file.


## Interactive property playground

Open `components.html` to exercise the **real** twelve Web Components. Every entry has controls for its supported visual states, with immediate component rendering, event logging and a copyable **Current configuration** code sample that updates as controls change. The demonstrations share one mock song and mix to show propagation of host-owned state.

For artwork, switch `artMode` (`embedded` / `plate`) and `size` (`thumb` / `large`) independently. Physical dimensions come from parent layout; the playground sets 82px/260px host widths for the size presets and also exposes a separate width control. Other examples cover mixer and player modes, transport flags, track mute/solo/gain, library size, action sheet types, and shell screen selection.

### Stem mixer layout and data ownership

`<stem-mixer>` does **not** hardcode four tile colors or four tiles. On each `.mix` snapshot, its tiles and status bars come directly from `mix.stems` (using each item's `id`, `name`, `color`, `on`, `solo`, `gain`, and `audible`). It rebuilds the grid when the ordered stem IDs change, even if `trackId` does not. The containing application owns mix updates and must pass the updated snapshot after `mixer-action`.

The tile grid fills the **height provided by its parent**. The full player supplies this through its mixer slot. If you use the mixer standalone, give it a bounded height (for example `mixer.style.height='510px'` or a height-constrained flex parent); otherwise the flexible grid can collapse and appear as empty space with only the header and status bars showing. The component catalog allocates this height and lets you switch between 2, 4, and 6 stems to inspect the real tiles.


### Composing `<stem-player>` (required layout and state)

`<stem-player>` fills a **bounded height**. An unconstrained HTML container can
show the toolbar/transport while collapsing the central artwork or mixer view.
Set a height on the player or use a parent flex layout that provides one.

```html
<stem-player id="preview" mode="player" style="height:560px">
  <stem-mixer slot="mixer"></stem-mixer>
</stem-player>
```

```js
import './components/stem-player.js';
import './components/stem-mixer.js';
const player = document.querySelector('#preview');
const mixer = player.querySelector('stem-mixer[slot="mixer"]');
player.track = track;              // artwork, artist, title, artMode
player.mode = 'player';           // or 'mixer'
player.stems = mix;               // toolbar STEMS count / activity colors
player.playback = playback;       // play/seek controls
mixer.track = track;              // mini cover, title and artist
mixer.mix = mix;                  // ACTUAL tiles, from mix.stems
player.addEventListener('player-action', ({detail}) => {
  if (detail.action === 'toggle-mixer') {
    player.mode = player.getAttribute('mode') === 'mixer' ? 'player' : 'mixer';
  }
});
mixer.addEventListener('mixer-action', ({detail}) => {
  const updatedMix = applyMixerActionToYourModel(detail);
  mixer.mix = updatedMix;
  player.stems = updatedMix;
});
```

`artMode` (`embedded` or `plate`) is a property of the **track artwork** and
is visible in Now Playing. The mixer header currently displays the unframed
cover thumbnail and does not implement art-mode switching. The mixer and tile
colors are data-driven from the current `mix.stems[].color`, including updates
to an existing stem ID; no per-stem colors are hard-coded in the mixer.
