# Provide a dashboard widget

> Put a card from your miniapp on the glasses dashboard.

Source: https://docs.dev.glassly.ai/app-devs/core-concepts/widgets/

A miniapp can put a widget on the glasses dashboard: a small card that shows
its state and answers the wearer's swipes and taps. The first provider is the
Spotify miniapp, whose now playing card shows the track and a live playhead and
drives play, pause, next and previous.

You declare the widget in `miniapp.json` and serve it from your background layer
with `session.widgets.provide`. The dashboard decides where the card goes and
how big it is. You draw into that box and push a new frame when your state
changes.

## Declare a widget

```json miniapp.json
{
  "widgets": [
    {
      "id": "now_playing",
      "name": "Now Playing",
      "sizes": ["SM", "MD", "LG", "EX"],
      "defaultSize": "MD"
    }
  ]
}
```

| Field | Type | Notes |
|---|---|---|
| `id` | string | Unique within the miniapp, `^[a-z][a-z0-9_]*$`, at most 64 characters. |
| `name` | string | Shown on the dashboard's Widgets page. |
| `sizes` | array | No repeats, from `XS`, `XSM`, `SM`, `MD`, `LG` and `EX`. The card sizes your widget can draw at, at least one; `XSM` sits between `XS` and `SM`. Add `EX` and a tap can expand it to the full screen. See [Expand to the full screen](#expand-to-the-full-screen). |
| `defaultSize` | string | One of its card sizes. Defaults to the first. |

Declaring a widget needs no permission. The Store listing shows it.

## Serve it

```typescript src/background/index.ts
import {registerMiniapp} from "@glassly/miniapp/background";

registerMiniapp((session) => {
  let track = "Nothing playing";

  const widget = session.widgets.provide("now_playing", {
    onBox: (box) => {
      if (box) draw();
    },
    onEvent: async (event) => {
      if (event.type === "beforeShow") {
        track = await fetchTrack();
        draw();
      }
      if (event.type === "tap") await togglePlayback();
    },
  });

  function draw() {
    const box = widget.box;
    if (!box) return;
    widget.update([
      {type: "text", id: "title", box: {x: 8, y: 8, w: box.width - 16, h: 24}, text: track},
    ]);
  }
});
```

`provide` takes the widget id and a set of optional hooks, and returns a handle.
It throws if you provide the same id twice. Call it as soon as your session
starts: a call that arrives before `provide` waits up to five seconds for it.

| Handle | Notes |
|---|---|
| `box` | The box the host assigned, or `null` while the widget is not placed. |
| `expanded` | `{width, height}` while the host has the widget expanded, else `null`. |
| `update(elements, opts?)` | Push the frame for the current box, or with `{view: "expanded"}` for the expanded view. |
| `release()` | Stop serving the widget. |

### The box

The host assigns the box. When the widget is placed, and again whenever the
wearer resizes it, `onBox` receives `{size, width, height}`: the size name and
the pixel extent of the card's inner area. `null` means the widget was taken
off. Draw in box-local coordinates, where `{x: 0, y: 0}` is the top left of
your area. Do not assume a width or height beyond what `onBox` gave you; the
height varies with how the dashboard shares a column.

### Push frames with `update`

`update(elements)` takes the same scene elements as `session.display.render`.
Call it whenever your state changes. The host keeps the latest frame per widget
and draws it, so you do not answer a render request and a closed dashboard costs
you nothing.

- At most one redraw per second reaches the glasses for each widget while the
  dashboard is open. Frames pushed faster are coalesced, and the latest wins.
- While the dashboard is closed, a frame only replaces the cached one.
- Keep a frame to 64 elements (128 for an expanded frame) and 256 KB at most.
- Elements outside the box are dropped.

### Events and answers

The host sends your `onEvent` hook these events. The hook may be async. The
host waits a few seconds for an answer and then moves on.

| Event | When | Answer |
|---|---|---|
| `{type: "beforeShow"}` | The dashboard is about to open. | Refresh over the network, then `update`. The host does not wait long, so show the cached state and correct it. |
| `{type: "activate"}` | The wearer tapped your widget while it was selected and it does not expand. | Show your first control highlighted. |
| `{type: "expand", width, height}` | The wearer tapped your widget while it was selected, and it lists `EX` with expansion on. | Draw the expanded view with `update(elements, {view: "expanded"})`. |
| `{type: "swipe", direction, input2d?}` | A swipe while your widget is active or expanded: `left`, `right`, `up` or `down`. `input2d` is `true` when it came from a 2D controller such as a Neural Band. | Move your highlight. Nothing means handled. |
| `{type: "tap"}` | A tap while your widget is active or expanded. | Press the highlighted control. |
| `{type: "hold"}` | The wearer pressed and held while your widget is active or expanded. | Start a press-and-hold action, such as listening for speech. |
| `{type: "release"}` | The held press ended. A Neural Band's long press sends `hold` with no `release`. | Finish it. |
| `{type: "deactivate"}` | The wearer double-tapped out, or the dashboard closed. | Clear your highlight. |
| `{type: "collapse"}` | The wearer double-tapped back to the card, or the dashboard closed. | Go back to the card and clear your highlight. |

Your widget is one stop in the dashboard's selection order, like the built-in
cards. Swipes move the selection over it without telling you. A tap on it
activates it: from then on every swipe, tap and hold comes to you, until the wearer
double-taps, which deactivates it and leaves the dashboard open on your card.
A second double tap closes the dashboard. Wrap your highlight around at the
ends; there is no way to hand a swipe back.

### Expand to the full screen

A widget does not have to expand. One without `EX` in its sizes keeps tap to
activate on its card, as above. List `EX` and a tap on the selected widget
expands it instead: the host gives it the full screen and sends
`{type: "expand", width, height}`. `handle.expanded` holds that box from then
on. Draw the expanded view in its local coordinates with
`update(elements, {view: "expanded"})`. Like an active card, an expanded widget
gets every swipe, tap and hold. A double tap sends `{type: "collapse"}` and
returns to the card, and so does closing the dashboard.

Expansion is optional for the wearer: the miniapp's page in the Glassly App has
an "Open full screen" switch for each widget that lists `EX`, on by default.
With it off, a tap activates the card. Your miniapp can read and change the same
setting, for example from its own phone page:

```typescript
const on = await widget.getExpandable()
await widget.setExpandable(false) // resolves with the setting now in force
```

Both reject for a widget that does not list `EX`. The dashboard reads the
setting each time it opens.

The host keeps the latest card frame and the latest expanded frame apart. An
expanded frame holds at most 128 elements. Expanded frames from a widget that
does not list `EX` are dropped.

## Widget mode

A provider runs while at least one of its widgets is placed, and stops when none
is. If you are placed, your miniapp runs headless in **widget mode**:

- It is running, but has no card in the app switcher.
- `session.display.render` resolves `{status: "blocked", reason: "widget mode"}`.
  The glasses show the dashboard's card, not your frame.
- It receives no touch events, and its gesture claims are set aside.
- The Glassly App's app switcher lists it under a Widgets pill. Tapping it opens
  the app.
- `session.miniapps.list` reports it with `running: false`.

Opening your miniapp from the home screen or the glasses' Apps menu
(`session.miniapps.start`) promotes it to a normal run: display and touch work
as usual. Closing a placed miniapp from the tray, the Apps menu or a double tap
demotes it back to widget mode instead of stopping it. It stops when the wearer
removes its widgets or the dashboard stops.

Your widget code must not depend on having the display, so keep it separate
from the code that draws your own screens.

## Limits

- The scene canvas is 576 by 288 pixels, and a widget draws into a part of it.
  The box is smaller than that, and a small card holds about two lines of text.
- The display is 4-bit grayscale: 16 gray levels.
- The builtin font is a fixed 20 px.
- The link to the glasses moves about 1 KB per second. Text is cheap, and
  images are not. Send art only when it changes, and do not animate anything
  you can redraw as text once a second.
- A tap travels from the glasses to the dashboard, to your miniapp, to your
  backend, and back as a frame. Draw the expected state at once and correct it
  when the answer arrives.

## Host widgets

A dashboard places other miniapps' widgets. This needs the `HOST_WIDGETS`
manifest permission, which has no OS prompt and is shown in the Store listing.
Its canonical key in `session.permissions` is `hostWidgets`. Without it, every
host call rejects with `PERMISSION_NOT_DECLARED`.

| Method | Notes |
|---|---|
| `list()` | Every widget the installed miniapps declare, yours excluded: `packageName`, `appName`, `id`, `name`, card `sizes`, `defaultSize`, `expandable` (a tap expands it: it lists `EX` with expansion on), `running` and `compatible`. |
| `place(packageName, widgetId, box)` | Place a widget in a box and start its provider in widget mode. Resolves with the provider's last card frame, or `null`. A cached expanded frame goes to your `onFrame` listeners first. Place again with a new box to resize. |
| `unplace(packageName, widgetId)` | Take it off. A provider with nothing placed stops. |
| `send(packageName, widgetId, event, opts?)` | Forward an event and wait for the provider's answer. `opts.timeoutMs` sets the wait. |
| `onFrame(listener)` | Frames pushed by the providers of the widgets you placed, each with `view` set to `"card"` or `"expanded"`. Returns an unsubscribe function. |

The host routes every call. A provider never learns which miniapp hosts it, and
a host never starts a provider by name. When a host stops or disconnects, the
engine drops its placements. See [Build a dashboard](https://docs.dev.glassly.ai/app-devs/core-concepts/dashboards.md)
for the role itself.
