# The UI layer

> Build the miniapp's WebView UI with React, talking to the background over the injected glassly global.

Source: https://docs.glassly.ai/app-devs/core-concepts/webviews/react-webviews/

The UI layer is the on-demand half of a [two-layer miniapp](https://docs.glassly.ai/app-devs/core-concepts/two-layer-architecture.md). It is a normal React app that mounts when the user opens your tile and is destroyed when they leave. It has zero direct hardware access. To reach the glasses it sends messages to its own [background layer](https://docs.glassly.ai/app-devs/core-concepts/session.md), which holds the `session` and translates those messages into `session.*` calls. The bridge is a single injected global named `glassly`.

The entry point is small: create a React root, wrap it in `<MiniappProvider>`, and call `glassly.ready()`.

```tsx src/ui/main.tsx
import { createRoot } from "react-dom/client";
import { MiniappProvider } from "@glassly/miniapp/ui";
import "../shared/channels";
import { App } from "./App";

createRoot(document.getElementById("root")!).render(
  <MiniappProvider>
    <App />
  </MiniappProvider>,
);

glassly.ready(); // flush any messages background buffered while the WebView mounted
```

UI imports come from two sub-paths. `@glassly/miniapp/ui` re-exports everything (the `glassly` global types, the React hooks, `<MiniappProvider>`, `<MiniappHeader>`), and `@glassly/miniapp/react` exports the hooks and components directly. There is no `@glassly/sdk` here and no hosted server: the UI never authenticates, never opens a port, and never owns a session.

The UI layer must not construct a `MiniappSession`. That class is the background (JSContext) API. Inside a WebView its `CONNECT` never gets acked by the host's UI router, so `session.connect()` times out with `CONNECT_ACK timeout`. UI code reaches the glasses only through `glassly`, and reads host state through the hooks below.

## The `glassly` global

The host injects `glassly` into every UI WebView before your content loads. It carries the typed bus to background plus the two lifecycle signals.

```tsx
glassly.send("ping", { at: Date.now() });             // fire-and-forget, UI → background
const off = glassly.on("pong", ({ roundtripMs }) => { /* … */ }); // subscribe, returns an unsubscribe fn
const res = await glassly.request("getNotes", {});    // request/response (RPC)
glassly.ready();                                       // call once on bootstrap
```

| Method | What it does |
|---|---|
| `glassly.send(channel, payload)` | Broadcast a message to background. Buffered until `ready()` is acked, then flushes; after that it fires immediately. Compile-error on an RPC channel. |
| `glassly.on(channel, cb)` | Subscribe to broadcasts from background. Returns an unsubscribe function. Compile-error on an RPC channel. |
| `glassly.request(channel, payload, options?)` | Call a background `session.ui.handle(channel, …)` handler and await its return. No default timeout; pass `options.timeout` and `options.signal` to bound it. |
| `glassly.onOpen(cb)` | Fires when the bridge is open and `send` is flushable. Fires immediately if you subscribe after `ready()`. Returns an unsubscribe function. |
| `glassly.onClose(cb)` | Fires when the host is about to destroy the WebView. Snapshot state into background via `send` here if you want it to survive. |
| `glassly.ready()` | Call once on bootstrap. Tells the host the WebView is mounted; background's `session.ui.onOpen` handlers fire after this lands. Idempotent. |

The two sides are asymmetric on purpose. `glassly.send` from the UI buffers until `ready()`, while `session.ui.send` from the background drops silently when no WebView is open. See [Talking between layers](https://docs.glassly.ai/app-devs/core-concepts/two-layer-architecture.md#talking-between-layers) for the background side (`session.ui.handle`, `on`, `send`).

`glassly.request` rejects with an `Error` whose `name` is `RpcError` (the handler threw), `RpcTimeoutError` (the `timeout` elapsed), or `AbortError` (the `signal` aborted). Branch on `err.name`, not `instanceof`: these errors come from the WebView's bare runtime scope, so `instanceof` checks are unreliable across the bridge.

## Typed channels

Declare every channel once in `src/shared/channels.ts`. Both halves import this file, so channel names and payload shapes are checked at compile time on both sides of the bridge. `TypedUiGlobal<Channels>` types the global; importing the file for its `declare global` side effect is what wires the types in.

```typescript src/shared/channels.ts
import type { TypedUiGlobal } from "@glassly/miniapp/ui";

export interface Channels {
  ping: { at: number };                       // UI → background
  pong: { at: number; roundtripMs: number };  // background → UI
}

declare global {
  // eslint-disable-next-line no-var
  var glassly: TypedUiGlobal<Channels>;
}
```

For request/response channels, mark the entry as an RPC shape so `glassly.request` (and `useRpc`) infer the request and response types. `send`/`on` then reject that channel at compile time, and `request` rejects the broadcast channels.

## React hooks

Each hook reads host-injected state or the `glassly` bridge. `useSafeArea` reads the injected insets at mount. `useColorScheme` reads the initial theme before content loads and follows host theme changes while the WebView remains mounted; no reload is needed.

| Hook | Signature | Returns |
|---|---|---|
| `useConnected` | `useConnected(): boolean` | `true` while the `glassly` bridge is open (after `ready()`, before close). Tracks `onOpen`/`onClose`. |
| `useColorScheme` | `useColorScheme(): MiniappColorScheme` | The host's color scheme, `"light"` or `"dark"`, updated live when the host theme changes. |
| `useSafeArea` | `useSafeArea(): UseSafeAreaResult` | `{ insets, capsuleMenu }`: pixel insets to pad your root with, plus the capsule menu rect (`null` when the host renders none or draws it in the iPhone Duo's status rail). Re-renders when they change. |
| `useCapsuleHeaderStyle` | `useCapsuleHeaderStyle(options?): CSSProperties` | Ready-to-spread CSS that vertically aligns a header row with the floating capsule menu. |
| `useCapabilities` | `useCapabilities(): GlassesCapabilities \| null` | Always `null` in the UI. The glasses profile is background-only; relay it over a channel instead (read `session.capabilities`, `session.ui.send` it, then `glassly.on` it). |
| `useRpc` | `useRpc<Channels, C>(channel): RpcCallable` | A stable callable around `glassly.request(channel, …)` for one RPC channel, plus `.abort()`. |

`useRpc` recreates its `AbortController` per call: calling it again aborts the previous in-flight request (good for per-keystroke autocomplete), and unmount aborts everything pending. A caller-provided `options.signal` is merged with the internal one.

```tsx
import { useRpc } from "@glassly/miniapp/react";

const autocomplete = useRpc<Channels, "places:autocomplete">("places:autocomplete");
const results = await autocomplete({ query: "blue bot" });
autocomplete.abort(); // cancel the latest in-flight call
```

`useCapabilities` returns `null` by design. It does not construct a `MiniappSession` (which would time out in a WebView). When a UI page needs the glasses profile, read `session.capabilities` in a background `session.ui.onOpen` handler, `session.ui.send` it on a channel, and pick it up in the UI with `glassly.on`.

## Components

### `<MiniappProvider>`

The optional root provider. Today it keeps `<html class="dark">` in sync with the host's color scheme so shared theme CSS switches automatically. The toggle runs synchronously during render, so children paint with the right class on first mount and there is no theme flash. Pass `syncColorScheme={false}` if your app owns the `dark` class itself (for example when integrating a theming library).

```tsx
<MiniappProvider syncColorScheme>
  <App />
</MiniappProvider>
```

### `<MiniappHeader>`

A drop-in header that aligns with the host's capsule menu, leaving the top-right clear. It has three slots: `left`, `title`, and `right`. A string `title` renders as a semantic `<h1>`; pass a node for custom markup. Set `onBack` to render a back chevron in the left slot (ignored if `left` is set). The component layers `useCapsuleHeaderStyle` underneath, so its `UseCapsuleHeaderStyleOptions` (`leftPadding`, `rightGap`, `fallbackHeight`, `fallbackMarginTop`) are accepted as props.

```tsx
import { MiniappHeader } from "@glassly/miniapp/react";

<MiniappHeader
  title="My Miniapp"
  onBack={() => history.back()}
  right={<Badge>Connected</Badge>}
/>
```

Use `useCapsuleHeaderStyle` directly when you want full control over header markup but want the alignment math done for you. For the capsule-menu rect, the safe-area insets, and where you may not place clickable content, see [Safe Areas & Layout](https://docs.glassly.ai/app-devs/core-concepts/webviews/safe-areas.md).

## Next steps

- [Two-layer architecture](https://docs.glassly.ai/app-devs/core-concepts/two-layer-architecture.md)
The bus model and how background and UI talk.
- [Safe areas & layout](https://docs.glassly.ai/app-devs/core-concepts/webviews/safe-areas.md)
Keep content clear of the capsule menu.
- [The session](https://docs.glassly.ai/app-devs/core-concepts/session.md)
The background-side `session` your UI sends to.
- [Interop & Actions](https://docs.glassly.ai/app-devs/core-concepts/miniapp-interop.md)
Let other miniapps call yours.
