# Widgets

Source: https://docs.lightair.app/developers/extend/widgets

> Build a Lightair widget as a folder of HTML, CSS and JavaScript, with settings in fields.json and the lightair bridge for events, totals, storage and more.

In short:
- A widget is a folder with `manifest.json`, `fields.json`, `index.html`, `style.css` and `main.js`; put it in a package as a `widget` content entry.
- Lightair puts the files together into one page and adds the `lightair` bridge.
- `lightair.on('event', fn)` gets every chat message and alert; `lightair.session` has the totals; `lightair.store` keeps values between runs.
- Try it with the Inspector's **Send a test** and **Placeholder**.

A widget is a web page Lightair serves on this computer and shows on the canvas. Lightair feeds it
chat, alerts and totals from every platform the show reads, and gives it settings people change in
the Inspector.

## Make a widget

1. Make a folder with these files at its top:

   | File | What it holds |
   |---|---|
   | `manifest.json` | The widget's name and page size, and the built-in it's a skin of, if any |
   | `fields.json` | Its settings |
   | `index.html` | The page's body: HTML only, no `<html>`, `<head>` or `<body>` |
   | `style.css` | Its style |
   | `main.js` | Its script |

2. Put any fonts, pictures, sounds and video it uses in folders under it.
3. List the folder in a package's `lightair-package.json` as
   `{ "kind": "widget", "path": "widgets/<folder>" }`. See [Packages](/developers/extend/packages).
4. Install the package. The widget is listed in **Add Object › Widgets** and on the package's page
   in the Packages panel.

A widget that counts follows:

```json title="manifest.json"
{ "name": "Follow counter", "size": [600, 120] }
```

```json title="fields.json"
{
  "title": { "type": "text", "label": "Title", "value": "Follows today" },
  "colour": { "type": "colorpicker", "label": "Colour", "value": "#3AA6F5" },
  "reset": { "type": "button", "label": "Start again" }
}
```

```html title="index.html"
<div class="box"><span id="title"></span> <b id="count">0</b></div>
```

```css title="style.css"
.box { font: 600 40px system-ui, sans-serif; }
```

```js title="main.js"
function draw() {
  document.querySelector(".box").style.color = lightair.fields.colour;
  document.getElementById("title").textContent = lightair.fields.title;
  document.getElementById("count").textContent = lightair.storage.count || 0;
}
lightair.on("load", draw);
lightair.on("fields", draw);
lightair.on("event", function (e) {
  if (lightair.kindOf(e) !== "follow" || e.test) return;
  lightair.store("count", (lightair.storage.count || 0) + 1);
  draw();
});
lightair.on("button", function (name) {
  if (name === "reset") { lightair.store("count", 0); draw(); }
});
```

## The page

Lightair builds one page from the folder: `style.css` in the head, then the bridge
(`/lightair.js`), then the body from `index.html`, then `main.js`. The page's background is
transparent and it doesn't scroll.

`{{name}}` anywhere in the HTML, CSS or JavaScript is replaced by that setting's value when the
page loads. A changed setting reaches a running page through `lightair.on('fields')` without a
reload, so read `lightair.fields` in your script for anything that should change live.

A widget that isn't a skin also gets jQuery 3.7.1 and compatibility with StreamElements and
Streamlabs custom widgets: StreamElements' `onWidgetLoad`, `onEventReceived` and
`onSessionUpdate`, or Streamlabs' `onLoad` and `onEventReceived`, fire as those sites fire them,
so an existing custom widget works as it is.

### Its own files

Files in the widget's folder are served beside its page, by relative path:
`url(fonts/display.woff2)` in CSS, `<img src="media/coin.png">` in HTML. Only fonts (`woff2`,
`woff`, `ttf`, `otf`), pictures (`png`, `jpg`, `jpeg`, `gif`, `webp`, `svg`, `apng`), sounds
(`mp3`, `wav`, `ogg`, `oga`, `m4a`) and video (`mp4`, `m4v`, `webm`, `mov`) are served, only
from inside the folder, and read-only. Scripts and styles must be in `main.js` and `style.css`.

A package widget that loads its own files needs the package API 1.1: write `"lightair": ">=1.1 <2"`
in the package's manifest.

### Reaching the internet

A package widget's page reaches only its own page, its own files, and the hosts the package
declares with `network:` permissions. See
[Network hosts for widgets](/developers/extend/permissions#network-hosts-for-widgets).

## manifest.json

| Field | What it is |
|---|---|
| `name` | The name shown in Add Object and the Packages panel. Without one, the folder's name, made readable (`neon-goal` as "Neon goal"). |
| `size` | The page's size in CSS pixels, `[width, height]`. Without one, 800 × 600. |
| `skin` | The kind of a built-in widget this one replaces the look of (see [Skins](#skins)). |

## fields.json

Settings use StreamElements' `fields.json` format: an object of setting name → description, in
the order the Inspector shows them.

```json
{
  "accent": { "type": "colorpicker", "label": "Accent", "value": "#3AA6F5", "group": "Look" },
  "size": { "type": "slider", "label": "Text size", "value": 100, "min": 80, "max": 140, "step": 5, "group": "Look" },
  "side": { "type": "dropdown", "label": "Side", "value": "left", "options": { "left": "Left", "right": "Right" } }
}
```

Each setting has:

- `type`: how the Inspector shows it (below). Without one, `text`.
- `label`: its name in the Inspector. Without one, the setting's name.
- `value`: its default.
- `group`: a heading the Inspector puts it under.
- `options` (dropdowns): an object of value → label, or a list of values or of
  `{ "value", "label" }` objects.
- `min`, `max`, `step` (sliders and numbers).

| Type | The Inspector shows |
|---|---|
| `text`, `textfield` | A line of text |
| `textarea` | Several lines of text |
| `number` | A number field |
| `slider` | A slider |
| `checkbox` | A switch |
| `colorpicker` | A colour picker |
| `dropdown` | A menu of `options` |
| `fontpicker` | A menu of fonts |
| `image-input`, `sound-input`, `video-input` | A file or address, with **Choose…** |
| `button` | A button that sends its setting's name to the page (`lightair.on('button')`) |
| `hidden` | Nothing: a value the page reads but people don't change |

Other types show as a line of text.

A button can also be pressed from outside Lightair's Inspector with
[widgets.button](/developers/remote-api/widgets.button), so automations, hotkeys and Stream Deck
keys can press it.

## The lightair bridge

The bridge is the global `lightair`. It connects to Lightair when the page opens and again if the
connection drops.

### Values

| Property | What it holds |
|---|---|
| `lightair.loaded` | `true` once the first `load` has arrived |
| `lightair.id` | This widget's id |
| `lightair.kind` | `custom`, or the built-in it's a skin of |
| `lightair.fields` | Every setting's value: its default, or what was set |
| `lightair.session` | This session's totals (see [Session totals](#session-totals)) |
| `lightair.recents` | The last 100 events, oldest first, from the platforms it listens to |
| `lightair.storage` | What it stored with `lightair.store` |
| `lightair.data` | Live data Lightair sends, by key (see [Live data](#live-data)) |
| `lightair.placeholder` | `true` while its placeholder is on |
| `lightair.samples` | The sample events its placeholder shows |

### Events

Listen with `lightair.on(name, fn)`. It returns `lightair`, so calls chain.

| Name | When | `fn` gets |
|---|---|---|
| `load` | Settings, totals, recent events and storage are ready. If it already happened, `fn` runs at once. | `lightair` |
| `reload` | The connection came back and everything was sent again | `lightair` |
| `event` | Any event: a chat message, an alert, a deletion | The [event](#event-data) |
| `alert` | An alert box's turn to show an alert (skins of `alert-box` only) | The event |
| `skip` | The current alert was skipped (alert box) | Nothing |
| `sound` | Lightair plays a sound through the alert box | `{ file, volume }` |
| `session` | The totals changed | `lightair.session` |
| `fields` | A setting changed | `lightair.fields` |
| `storage` | Storage changed in Lightair (a built-in's button) | `lightair.storage` |
| `button` | A `button` setting was pressed | The setting's name |
| `data` | Live data changed | `{ key, value }` |
| `placeholder` | The placeholder was turned on or off | `true` or `false` |
| `message` | A message from the script plugin whose overlay this page is | The message |

### Functions

| Function | What it does |
|---|---|
| `lightair.kindOf(e)` | Names an event: `follow`, `sub`, `raid`, `cheer` (Twitch bits), `paid` (donations, Super Chats, gifts), `message`, or the event's own type (`notice`, `deletion`) |
| `lightair.render(e, size)` | A message's fragments as safe HTML: text escaped, emotes as `<img class="emote">` pictures `size` high (default `1.6em`), mentions in bold, links as text in `<span class="link">`. Never the sender's own HTML. |
| `lightair.escape(text)` | `text` with `& < > " '` escaped for HTML |
| `lightair.format(template, e)` | Fills `{name}`, `{amount}`, `{viewers}`, `{message}`, `{headline}` and `{platform}` in `template` from an event |
| `lightair.icon(platform)` | The address of a platform's logo (SVG), for an `<img>` |
| `lightair.file(value)` | A setting that names a file on this computer, as an address the page can load. Addresses (`https:`, `data:`, `blob:`) come back as they are. |
| `lightair.store(key, value)` | Keeps `value` (any JSON) under `key` between runs, and in `lightair.storage` at once. `null` removes it. |
| `lightair.fetch(url, cb)` | Reads `url` through Lightair, for addresses a page can't read itself. `url` must be an `http` or `https` address that is the value of one of the widget's settings. See below. |
| `lightair.points(platform, id, name, delta, cb)` | Gives a viewer points (`delta` above 0) or takes them. `cb(ok, balance)`: `ok` is `false` when they haven't enough to take. |
| `lightair.speak(text)` | Says a viewer's text aloud with Lightair's voice, on its Voice track. Lightair filters it and caps its length. |
| `lightair.done()` | Tells the alert box the current alert has gone, so the next can start |
| `lightair.send(message)` | Sends a message to the script plugin whose overlay this page is |
| `lightair.emit(name, data)` | Runs this page's own handlers as if Lightair had sent `name`, to try a widget out |

`lightair.fetch` makes a GET request with a 10-second limit and reads at most 1 MB of the answer
as text. `cb` gets `{ ok, status, body }`, where `ok` is true for a 2xx status, or
`{ ok: false, error }`. An address that isn't one of the widget's settings gets
`error: "not one of its settings"`.

```js
// fields.json has "feed": { "type": "text", "label": "Feed address", "value": "https://example.com/score.json" }
lightair.on("load", function () {
  lightair.fetch(lightair.fields.feed, function (r) {
    if (r.ok) show(JSON.parse(r.body));
  });
});
```

While the placeholder is on, nothing a widget does with `store`, `points` or `speak` goes out, and
sounds don't play.

## Event data

Every event, live or in `lightair.recents`, is one JSON object:

| Field | What it is |
|---|---|
| `id` | Lightair's number for it, in arrival order |
| `ts_ms` | When it happened, in milliseconds since 1970 |
| `platform` | `twitch`, `youtube`, `kick` and so on |
| `channel` | The channel it came from, as it was set up |
| `native_id` | The platform's own id for it, when it has one |
| `kind` | What happened: `{ "type": … }`, below |
| `user` | Who it's from: `id`, `login`, `display_name`, `color` (`"#1E90FF"`), `roles`, `badges` |
| `fragments` | The message, in pieces (below) |
| `text` | The message as plain text, emotes as their codes |
| `reply_to` | The message it answers: `native_id`, `author`, `excerpt` |
| `paid` | Money or the like on it: `display` (`"$5.00"`, `"500 bits"`), `amount` (`5`, `500`), `currency` (an ISO code, `BITS`, `CHANNEL_POINTS`, …; `""` when unknown) |
| `headline` | A membership's or notice's own line: "Gifted 5 subs" |
| `deleted` | `true` once a moderator removed it |
| `test` | `true` for a test event |

Optional fields are left out when they're empty.

`kind.type` is one of:

- `message`: a chat message.
- `paid`: a message with money on it (a donation, a Super Chat, bits).
- `membership`: a new, renewed or gifted subscription or membership.
- `raid`: another channel sent its viewers here; `kind.viewers` is how many.
- `follow`: someone followed.
- `deletion`: a message (`kind.native_id`) or everything a user said (`kind.user_id`) was removed.
- `notice`: a platform's own notice. A channel-points redeem is a notice whose `paid.currency` is
  `CHANNEL_POINTS`.

`user.roles` holds any of `broadcaster`, `moderator`, `vip`, `subscriber`, `member` and
`verified`. Each badge has `set` (`"subscriber"`), `version` and `image`.

Each fragment has a `type`:

- `text`: `text`.
- `emote`: `provider`, `id`, `code` and `image` (the picture's address).
- `mention`: `name`.
- `link`: `url`.

```json
{
  "id": 412,
  "ts_ms": 1764835200000,
  "platform": "twitch",
  "channel": "examplechannel",
  "kind": { "type": "paid" },
  "user": { "id": "1234", "login": "nightowl", "display_name": "NightOwl", "roles": ["subscriber"] },
  "fragments": [{ "type": "text", "text": "Great stream " }, { "type": "emote", "provider": "twitch", "id": "25", "code": "Kappa", "image": "https://…" }],
  "text": "Great stream Kappa",
  "paid": { "display": "500 bits", "amount": 500, "currency": "BITS" },
  "deleted": false
}
```

## Session totals

`lightair.session` counts since Lightair started, leaving test events out:

- `counts`: how many of each kind (`follow`, `sub`, `paid`, `cheer`, `raid`, `redeem`, `message`).
- `totals`: money and the like per currency (`USD`, `BITS`, …).
- `latest`: the latest of each alert kind, each `{ name, platform, amount, display, currency, text, ts }`.
- `top`: the biggest single paid event, in the same shape.

A widget set to some platforms only (the Inspector's **Gets events from**) gets those platforms'
events, recent events and totals.

## Live data

`lightair.data` and the `data` event carry what Lightair sends besides events:

| Key | What it is |
|---|---|
| `featured` | The chat message the streamer features from the Chat panel |
| `heart_rate` | Beats per minute, when a heart-rate monitor is connected |
| `now_playing` | `{ app, title, artist, album, artwork }`, while a `now-playing` widget is in the show |
| `captions` | `{ lines, partial, error, at }`, while a `captions` widget is in the show |
| `spectrum` | `{ bands }`, while a `visualiser` widget is in the show |
| `input` | Keys, mouse buttons and game controllers, while an `input-overlay` widget is in the show |
| `leaderboard` | Viewers with the most points (`name`, `points`, `platform`), while a `leaderboard` widget is in the show |
| `giveaway` | The giveaway's entries, while a `wheel` widget is in the show |

To get a feed that runs only with its built-in, make the widget a skin of that built-in.

## Skins

A widget whose `manifest.json` names a built-in in `skin` is that built-in with your code:

```json
{ "name": "Neon alerts", "size": [1000, 600], "skin": "alert-box" }
```

Lightair then gives it what the built-in gets: the alert queue for `alert-box`, the feeds above,
and the state Lightair keeps for counters, subathon timers, scoreboards and lower thirds, with
their buttons. Use the built-in's setting names for what Lightair reads: an alert box's
`duration`, a counter's `step`, a subathon's `startMinutes`.

The built-ins are `alert-box`, `chat-box`, `event-list`, `goal`, `label`, `counter`, `subathon`,
`now-playing`, `emote-wall`, `credits`, `social`, `poll`, `wheel`, `leaderboard`, `featured`,
`emote-combo`, `prediction`, `heart-rate`, `scoreboard`, `lower-third`, `web-data`,
`input-overlay`, `captions` and `visualiser`. A `skin` that names none of them makes an ordinary
widget. Skins need the package API 1.1 (`"lightair": ">=1.1 <2"`).

The quickest start is a built-in's own code: select one on the canvas, choose **Customize code…**
in the Inspector, then keep its files in a folder (see [Edit while it runs](#edit-while-it-runs))
and copy them out.

### The alert queue

A skin of `alert-box` gets alerts one at a time through `lightair.on('alert')`. Show the alert,
then call `lightair.done()` when it has gone. If the page never calls it, the next alert comes
after the `duration` setting (8 seconds by default) plus 3 seconds. Up to 30 alerts wait; an
alert that waited 2 minutes is dropped.

```js
lightair.on("alert", function (e) {
  show(lightair.format("{name} gave {amount}", e));
  setTimeout(function () { hide(); lightair.done(); }, 5000);
});
```

## Test a widget

Select the widget on the canvas. Its Inspector offers:

- **Send a test**: a menu of test events (a chat message, a message with emotes, a follow, a
  subscription, a donation, a cheer, a raid). The test reaches this widget alone; no other widget,
  automation or panel sees it. Test events carry `test: true` and don't count in the totals.
- **Placeholder**: holds samples of what the widget shows on screen while you set it up. It shows
  on stream too until you turn it off; going live or recording turns it off.

For a widget that isn't a skin, **Send a test** appears when its page listens to `event` or
`alert`, and **Placeholder** when it listens to `event`, `alert`, `data` or `placeholder`. A skin
gets what its built-in offers.

### Show your own placeholder

When the placeholder turns on, `lightair.placeholder` is `true`, `lightair.samples` holds the
sample events, and `lightair.on('placeholder')` fires. Keep the samples on screen until it turns
off:

```js
lightair.on("placeholder", function (on) {
  if (on) lightair.samples.forEach(addRow);
  else clearRows();
});
```

A page that doesn't listen for `placeholder` is given one: the samples arrive as events, a skin of
the alert box gets a sample alert again and again, sample live data fills in where there's none,
and the page reloads when the placeholder goes off.

### Edit while it runs

Click the folder button beside the code tabs in the Inspector to keep the widget's files in a
folder. Edit them in any editor: each save shows on the canvas at once. The package button
exports the widget as a `.lwidget`. When it's done, copy the files back into your package's widget
folder and raise the package's version.

[widgets.test](/developers/remote-api/widgets.test) sends a test event to every widget and
automation, as if it came from a platform.

## Related

- [Widget packs](/developers/extend/widget-packs)
- [Permissions](/developers/extend/permissions)
- [Custom widgets](/desktop/chat-and-widgets/custom-widgets)
