# HTML Actions Authoring Guide
Embed interactive HTML inside a Breeze Booth screen (a game, a form, a quiz, a custom overlay) and exchange data with the rest of the app — read tokens, write tokens, trigger Photobooth actions.
This is the guide for the *page author*. The native side (`updateHTMLActions` in `ViewController.swift`) builds the bridge automatically; you do not need to register anything.
---
## 1. The runtime API
When Breeze Booth mounts your HTML in its WKWebView, it injects a `window.bb` object **before any of your scripts run**. Three things hang off it:
| API | Direction | Purpose |
|---|---|---|
| `window.bb.tokens` | app → page | Read-only snapshot of the substitution map (see [TAGS.md](TAGS.md)). |
| `window.bb.setToken(key, value)` | page → app | Write a value back to the app. Surfaces as `{_}`. |
| `window.bb.runAction(name)` | page → app | Trigger a `PhotoboothAction` (e.g. `videoStart`). |
| `window.bb.actionId` | app → page | The `id` of this HTML action (the XML attribute). |
`window.bb` is **not present** when the file is opened in a regular browser (for design / preview work). Always feature-check before calling — see the helpers below.
### Recommended helpers
Paste these at the top of your script and use them everywhere:
```js
function bbGet(key, fallback) {
if (window.bb && window.bb.tokens && Object.prototype.hasOwnProperty.call(window.bb.tokens, key)) {
const v = window.bb.tokens[key];
return (v === '' || v == null) ? fallback : v;
}
return fallback;
}
function bbSet(key, value) {
if (window.bb && typeof window.bb.setToken === 'function') {
window.bb.setToken(key, String(value));
}
}
function bbRun(actionName) {
if (window.bb && typeof window.bb.runAction === 'function') {
window.bb.runAction(actionName);
}
}
```
The fallbacks make the page usable in a desktop browser for layout/styling work — `bbGet` returns the fallback you pass in, `bbSet` and `bbRun` no-op.
---
## 2. Reading tokens (`window.bb.tokens`)
`window.bb.tokens` is a plain object whose **keys include the curly braces**, exactly as they appear in the substitution map.
```js
const name = bbGet('{user_name}', 'Guest');
const event = bbGet('{eventName}', '');
const code = bbGet('{syncCode}', '');
```
Everything listed in [TAGS.md](TAGS.md) is available, including survey results (`{text_}`, `{checkbox_}`, …) and previously-set HTML values (`{_}`).
### Important: it's a snapshot
The token map is captured when the page first mounts. **It does not refresh when the photobooth state changes** (see §5 for why). If you need a value that changes during the user session, capture it once at start; if you need it later, ask the user to re-enter or push it through `setToken` from another layer.
---
## 3. Writing tokens (`window.bb.setToken`)
Values written from your page land in the app as `{_}`, where `` is the `id` attribute on the `` element in `settings.xml`.
```js
// In a page mounted as
bbSet('score', 7); // → {soccer_score} = "7"
bbSet('streak', 3); // → {soccer_streak} = "3"
bbSet('player', 'Alice'); // → {soccer_player} = "Alice"
```
The native side stores these in the same place as keyboard survey results (`theSurveyResults`), so they are usable **wherever any substitution tag works** — filename templates, email/SMS bodies, print layout text, overlay text, sharing URLs, etc.
### Overwrite semantics
Calling `setToken` with the same key replaces the previous value. There's no append — the page is the authoritative source for its own keys.
### Value coercion
Everything becomes a string on the way through. Pass numbers, booleans, anything — the helper wraps with `String(...)`. `null` and `undefined` become the string `""`.
### Lifetime
Values are cleared at the same boundaries as survey results — session resets, returning to standby, etc. For "use the value in the email being sent right now" this is exactly right; for "remember the high score across sessions" you'd need to also write it somewhere the app persists (out of scope for this doc).
---
## 4. Triggering Photobooth actions (`window.bb.runAction`)
Invoke any `PhotoboothAction` by its raw enum name. Common ones:
| Action | Effect |
|---|---|
| `stillsStart` | Begin a stills capture (countdown + photo). |
| `gifStart` | Begin a GIF capture. |
| `videoStart` | Begin a video recording. |
| `videoEnd` | Stop video recording. |
| `cancelCountdown` | Abort an in-progress countdown. |
| `stillsPhotoAccept` / `stillsPhotoRetake` | Accept or retake the just-captured photo. |
| `switchToStillsAndStart` / `switchToGifAndStart` / `switchToVideoAndStart` | Switch mode then immediately start. |
| `standBy` | Drop to standby. |
| `exit` / `exitFromReady` / `exitFromStandby` | Leave the active session. |
The full list is in `Breeze Booth/Domain/Entities/PhotoboothEventAction.swift`.
```js
document.getElementById('takePhoto').addEventListener('click', () => bbRun('stillsStart'));
```
### State gating
`runAction` calls are gated on the native side by the *same rules* the touchscreen buttons follow:
1. No popup is currently displayed.
2. The action is valid for the current photobooth state (per `TouchscreenDefinitions`).
If either check fails, the call is **silently dropped** and a line is written to the journal. There's no error callback to the page — design your UI to not rely on a response (the touchscreen path works the same way).
### Common pitfall: state transitions cause your page to be reloaded
When you call `runAction` and it triggers a photobooth state change, the new state may or may not include your HTML action in its `screens` list. See §5.
---
## 5. XML configuration
An HTML layer is declared in `settings.xml` under ``:
```xml
```
| Attribute | Required | Purpose |
|---|---|---|
| `id` | recommended | Namespaces token writes — values surface as `{_}`. Falls back to the file basename if omitted (so legacy configs keep working). |
| `file` | yes | HTML filename in the event assets folder. Sibling CSS/JS/images alongside the file load fine. |
| `x` / `y` / `w` / `h` | yes | Normalised 0–100 coordinates, same convention as touchscreen actions. |
| `screens` | yes | Comma-separated list of `PhotoboothState` raw names the layer appears on. |
### `screens` and the "diff" remount behaviour
When the photobooth state changes, the native side recomputes which HTML actions should be visible:
- Layers with **the same `(id, file)`** present in both the old and new state → **kept** (the WKWebView survives, in-page state and JS heap are preserved). The frame is updated in case the rect differs between states.
- Layers only in the old state → **torn down**.
- Layers only in the new state → **mounted fresh**.
**Implication.** If your page calls `runAction('videoStart')` and the photobooth transitions from `.videoReady` to `.videoCapture`, list **both** states in `screens` so the page survives the transition. Otherwise the page is destroyed and reloaded mid-call, throwing away your in-progress state (and the user has to tap again).
```xml
```
### Multiple layers on one screen
You can mount more than one HTML action on the same state. Give each a unique `id` so token writes don't collide.
---
## 6. Worked example — a scored mini-game during video
A 15-second game that:
1. Reads the player's name from a previous keyboard survey.
2. Starts a video recording when the user taps PLAY.
3. Pushes the running score back to the app on every goal.
4. Stops the video recording at game over and pushes final stats.
### `settings.xml`
```xml
```
### `soccer.html` (excerpt)
```html
```
### Using the values elsewhere in `settings.xml`
```xml
Hi {text_name},
You scored {soccer_score} out of {soccer_attempts} ({soccer_accuracy}%) — see attached!
```
The values are available everywhere the substitution system runs.
---
## 7. Debugging
- **Page does nothing when opened in a browser.** Expected — `window.bb` only exists inside the photobooth. The helpers in §1 return fallbacks so layout/styling can be worked on outside the app.
- **`setToken` value doesn't show up.** Check the `id` attribute matches the token you're reading (`` → `{soccer_…}`, not `{score_…}`).
- **`runAction` doesn't fire.** Check the journal — invalid action names and state-gated drops are logged with the reason (`unknown action`, `not valid for state X`, `popup displayed`).
- **Page reloads when I trigger a state change.** Your `screens="…"` doesn't include the destination state. See §5.
- **Tokens look stale after a state change.** They are — `window.bb.tokens` is a one-time snapshot. Pull fresh values by writing them from another layer with `setToken`, or design the page to be self-contained.
---
## 8. Touch input
WKWebView handles taps on your HTML content directly. Taps that fall outside the page's frame bubble up to the photobooth touchscreen handler as normal. You don't need to do anything special — `