# Events and state

The viewer's events, state, capabilities and error codes.

## Subscribe to events

Subscribe with `on(event, handler)`: it returns the function that unsubscribes.

```ts
const unsubscribe = viewer.on('cosmeticschange', () => {
    console.log(viewer.state.stickers);
});

unsubscribe();
```

> When a handler runs, `viewer.state` and `viewer.capabilities` already hold what changed: read them rather than the event's payload. `progress` and the placement events are the exceptions: their payload is what they tell.

## Events

- `ready`: The item is on screen.
- `error`: The 3D view could not start, or the viewer reloaded and could not reconnect. The payload is the error, with its `code`.
- `reconnect`: The viewer reloaded and lost what your commands set: it is back to its `createViewer` options. Apply your state again.
- `progress`: The viewer is loading: while it starts, while it switches to another view, or while the scene changes. It shows no loading state of its own, so show yours from this event. The payload has `loading` (false once the wait is over), `ratio` (the share done, from 0 to 1) and `view` (the view being switched to, or `null`).
- `unavailable`: The item cannot be rendered.
- `change`: The state changed.
- `viewchange`: The view changed.
- `subjectchange`: The item the free view presents changed.
- `cosmeticschange`: Stickers, charm or patches changed.
- `animationchange`: An animation started or stopped.
- `playbackchange`: The inspect animation started or paused, for instance paused by a visitor's gesture.
- `capabilitieschange`: What the viewer can do right now changed.
- `placementstart`: A visitor started moving a sticker or the charm.
- `placementmove`: A visitor is moving a sticker or the charm.
- `placementend`: A visitor let go of a sticker or the charm.
- `refused`: Sent when the viewer is refused after a reload. At start, `createViewer` rejects with the `refused` error instead.

## Save a placement

A placement does not change `viewer.state`: its events carry the position. The payload has `target` (what moves), `center` for a sticker or `offsets` for the charm (where it is now), and `delta` (the movement since the gesture started). On `placementend`, add `delta` to the cosmetic's offsets and save them, then pass them back with `setStickers` or `setCharm` next time.

```js
viewer.on('placementend', ({ target, delta }) => {
    if (target.kind !== 'sticker') return;
    const stickers = viewer.state.stickers.map((sticker) =>
        sticker.slot === target.slot
            ? {
                  ...sticker,
                  offsetX: (sticker.offsetX ?? 0) + delta[0],
                  offsetY: (sticker.offsetY ?? 0) + delta[1],
              }
            : sticker,
    );
    saveStickers(stickers); // your own storage
});
```

## State

`viewer.state` is the viewer's last known state, readable at any time without waiting.

- `weapon`: The weapon shown, or `null`.
- `gloves`: The gloves shown, or `null`.
- `agent`: The agent shown, or `null`.
- `subject`: Which item the free view presents when a weapon and gloves are both shown.
- `view`: The current view, and `active`: whether it is on screen yet, false while it loads.
- `environment`: The current environment id.
- `background`: The current background.
- `watermark`: The current watermark.
- `stickers`: The placed stickers, each with a `uid` that `focus` takes.
- `charm`: The charm, or `null`.
- `charmAnchor`: Where the charm actually hangs, in the weapon's model space.
- `patches`: The agent's patches.
- `patchSlots`: How many patch slots the agent has, `null` until known.
- `playing`: Whether the inspect animation is playing.
- `animation`: The weapon animation running, or `null`.
- `animations`: The weapon animations the viewer can play, each marked looping or not.
- `agentAnimation`: The agent animation running, or `null`.
- `agentAnimations`: The agent animations the viewer can play.
- `sound`: Whether the sound is muted.
- `firstPerson`: The viewmodel settings.
- `facing`: Which side of the item faces the camera.
- `placement`: What free placement is armed on, or `null`.

## Capabilities

`viewer.capabilities` says, for each view and feature, whether your plan includes it (`entitled`) and whether the current scene can serve it (`available`). Offer a control only when both are true.

```ts
const { entitled, available } = viewer.capabilities.features.placeStickers;

if (entitled && available) {
    await viewer.armPlacement({ target: { kind: 'sticker', slot: 1 } });
}
```

Views, under `capabilities.views`:

- `free`: Free rotation around the item.
- `firstPerson`: The item in hand, as in game.
- `thirdPerson`: The agent holding the item.

Features, under `capabilities.features`:

- `selectWeapon`: Show or change the weapon (`setWeapon`, `catalog.weapons`).
- `selectGloves`: Show or change the gloves (`setGloves`).
- `selectAgent`: Show or change the agent (`setAgent`, `catalog.agents`, `catalog.weaponModels`).
- `selectEnvironment`: Change the environment (`setEnvironment`, `catalog.environments`).
- `editSeed`: Change the pattern seed.
- `editFloat`: Change the wear.
- `editStattrak`: Change the StatTrak™ counter.
- `editNametag`: Change the name tag.
- `selectSticker`: Add stickers from the catalog.
- `selectCharm`: Add a charm from the catalog.
- `selectPatch`: Add patches from the catalog.
- `editStickers`: Tune placed stickers: wear and rotation.
- `editCharms`: Tune the charm's pattern.
- `placeStickers`: Move stickers freely on the weapon (`armPlacement`).
- `placeCharm`: Move the charm freely (`armPlacement`).
- `screenshot`: Capture the viewer (`capture`).
- `inspectLink`: Offer the item's in-game inspect link.
- `subjectControls`: Facing, viewmodel settings and sound (`setFacing`, `setFirstPersonSettings`, `setSound`).
- `weaponAnimations`: Weapon animations, fire and silent reload.
- `agentAnimations`: Agent animations.
- `customBackground`: Show one of your backdrops (`setBackground` with `custom`).
- `customWatermark`: Show one of your watermarks (`setWatermark` with `custom`).

## Error codes

A command that fails rejects with an error that has a `code` and a `message`. Branch on the code: the message is for your logs and may change.

- `invalid_key`: The viewer did not answer within 15 seconds and its iframe was removed: the render service could not be reached, or the frame was blocked before it started, often by a Content Security Policy.
- `origin_not_allowed`: The command came from a page your key does not allow: outside your declared domains, or outside your own machine for your test key.
- `not_entitled`: Your plan does not include what the command asks for.
- `unsupported_view`: The current item cannot be shown in this view.
- `unavailable_item`: What the command names is not in the viewer: an item that cannot be rendered, a sticker that is not placed, an animation the viewer cannot play.
- `invalid_argument`: A command argument is missing or malformed, or names a backdrop or watermark that is not one of yours.
- `not_ready`: The viewer cannot do this now: it is still loading, it was destroyed or reloaded, or the command needs a weapon or agent that is not shown.
- `internal`: Something failed on our side, or the visitor's browser could not run the 3D view.
- `refused`: The service refused to open the viewer. The error's `family` says who can fix it, and `refusalCode` gives the reason, as a code.

[Read more in Errors](https://render.vskin.gg/docs/errors)
