| 6 | callbacks. The HTML you pass is the whole widget (inline CSS and JS); nothing |
| 7 | in it can reach the network. |
| 8 |
| 9 | The same `Options` exist everywhere with the same defaults (`memoryLimitBytes` |
| 10 | 8 MB, `cpuLimitMs` 500, `cpuQuotaMs` 300 per `cpuQuotaWindowMs` 1000 (the |
| 11 | widget's JS time and, on the native hosts, the validator's CPU time for it: |
| 12 | `stats.validatorMs`), `mainThreadQuotaMs` 100 (the host's main-thread work for |
| 13 | the widget: its layout queries and the modelled cost of its ops), `maxTimers` |
| 14 | 64, `visible`, `policy` `strict`), see `packages/core/src/shared/protocol.ts` and `docs/decisions.md`, |
| 15 | "Strict limits from the start". Keep the defaults in a product build; `policy` |
| 16 | `compat` and wider quotas are for tests and the stress kit's measuring runs. |
| 17 | Call `setVisible(false)` when the bubble leaves the screen (frames stop, timers |
| 18 | drop to 1 Hz), `setTheme` when the chat theme changes, `destroy()` when the |
| 19 | bubble is recycled. A widget that exceeds its limits is killed; the renderer |
| 20 | keeps the last frame with a "Widget stopped" badge (`stoppedLabel`) and `onDead` |
| 21 | fires — destroy or re-create, your choice. |
| 22 |
| 23 | The rest of this page is in the order a client team meets it: pinning a |
| 24 | release, the policy and features, the widget payload, bubble sizing, heavy boxes, |
| 25 | input, forwarding, then the per-platform API and the conformance set. |
| 26 |
| 27 | ## Pinning a release |
| 28 |
| 29 | Releases are annotated tags on this repository (`v0.1.0` is the first). Pin |
| 30 | the tag, never a branch: `main` moves, and the JS bundles, the native |
| 31 | bytecode and the QuickJS submodule change together, so a mixed checkout does |
| 32 | not boot. |
| 33 |
| 34 | - **SwiftPM (iOS, macOS)**: `.package(url: "https://github.com/TelegramMessenger/widget-sandbox.git", exact: "0.6.0")` |
| 35 | (SwiftPM reads the `v` prefix of the tag). The manifest is the repo-root |
| 36 | `Package.swift`; SwiftPM clones the QuickJS submodule itself. A registry or |
| 37 | zip copy without the submodule does not build. |
| 38 | - **Git submodule (Bazel, CMake, tdesktop)**: add the repository as a submodule |
| 39 | at the tag and `git submodule update --init --recursive` (the sandbox has its |
| 40 | own submodule, `packages/ios/Sources/CQuickJS/quickjs`). The C++ core is |
| 41 | `add_subdirectory(<submodule>/packages/desktop)`. |
| 42 | - **Gradle (Android)**: a checkout at the tag and `includeBuild("<checkout>/packages/android")` |
| 43 | in `settings.gradle.kts`, then depend on `org.telegram.widgetsandbox:widget-sandbox` |
| 44 | as `apps/android` does. The AAR carries the native library (arm64-v8a, x86_64) |
| 45 | and the bundles as assets; a Maven publication comes later. |
| 46 | - **npm (web)**: `@telegram/widget-sandbox` lives in `packages/core`. With pnpm: |
| 47 | `"@telegram/widget-sandbox": "github:TelegramMessenger/widget-sandbox#v0.6.0&path:packages/core"`; |
| 48 | with another package manager, a checkout at the tag and a `file:` / workspace |
| 49 | dependency on `packages/core`. The package is not on the npm registry yet. |
| 50 |
| 51 | What you get at a tag is one state of the framework: the three JS bundles, the |
| 52 | `.qbc` bytecode next to them, the QuickJS submodule they were compiled with, |
| 53 | `packages/quickjs-wasm/dist` for the web, and `packages/conformance` (below). |
| 54 | Never mix files from two tags. |
| 55 |
| 56 | **`VERSION.json`** at the repository root names that state (since v0.6.0): |
| 57 |
| 58 | ```json |
| 59 | { "version": "0.6.0", "protocol": 1, "profile": 1, "sdk": 1 } |
| 60 | ``` |
| 61 |
| 62 | | field | what it is | |
| 63 | |---|---| |
| 64 | | `version` | the release, semver; the tag is `v` + it (`package.json`, `packages/core/package.json` and the Android library's `version` repeat it) | |
| 65 | | `protocol` | the wire between the glue and the bundles (`docs/protocol.md`: the config, the host calls, the messages, the validator's API); it changes when a bundle needs glue it cannot run without | |
| 66 | | `profile` | the widget profile, `TelegramWidget.profile` (`docs/profile-v1.md`; `packages/core/profile.json` repeats it) | |
| 67 | | `sdk` | the widget SDK (`docs/sdk-v1.md`); an addition to SDK v1 does not change it | |
| 68 |
| 69 | `pnpm build:ios|android|desktop` stamps all four on the first line of every |
| 70 | bundle (`/* widget-sandbox version=0.6.0 protocol=1 profile=1 sdk=1 */`) and |
| 71 | writes them into the glue as constants: `WidgetSandboxVersion` (Swift and |
| 72 | Kotlin) and `twidget::version` (C++, `twidget/version.h`), which also give the |
| 73 | glue its `profile`. **The native glue refuses a bundle without a stamp or with |
| 74 | another `protocol`, `profile` or `sdk`**, the way it refuses a stale `.qbc`, |
| 75 | except that there is nothing to fall back to: the engine stops at boot, before |
| 76 | any widget code, with the diagnostic `bundle-mismatch` (its detail names the |
| 77 | bundle, both versions and the fix) and dies with `sandbox bundle failed to |
| 78 | load`; the validator loads nothing and answers every batch empty. The release |
| 79 | itself is not compared: bundles of another release with the same three numbers |
| 80 | run. A `bundle-mismatch` means your copy mixes two releases (a resources folder |
| 81 | not updated with the code, a bundle copied over by hand): take the bundles and |
| 82 | the glue from the same tag. The web host builds its bundles from the same |
| 83 | `packages/core` sources as the rest of the page, so it has nothing to compare. |
| 84 | A client that loads the bundles from a resource layout of its own gets the same |
| 85 | check (Swift `SandboxResources(sandboxBundle:rendererBundle:validatorBundle:sandboxBytecode:validatorBytecode:)`, |
| 86 | the fields of the C++ `SandboxResources`); `SandboxResources.refusal` (Swift, |
| 87 | Kotlin) and `BundleStamp::refusal(resources)` (C++) give the reason before any |
| 88 | widget starts, for a startup check of your own. |
| 89 |
| 90 | ## Policy and features |
| 91 |
| 92 | **`strict` is the default on every host.** Privileged bridge calls need a real |
| 93 | user gesture, text is budgeted, `data-*`/`aria-*` and CSS strings included, and |
| 94 | the limits of `docs/changes.md` apply. `compat` exists for tests and tooling; |
| 95 | a product client never sets it (Kotlin and C++ take a string: anything but |
| 96 | exactly `"compat"` is strict). |
| 97 |
| 98 | **Features** are opt-in wire forms the host advertises to the runtime; the |
| 99 | runtime uses none it did not list. The option has the same name everywhere: |
| 100 |
| 101 | | | option | type | |
| 102 | |---|---|---| |
| 103 | | Swift | `WidgetHost.Options.features` | `Set<String>` | |
| 104 | | Kotlin | `WidgetHost.Options.features` | `Set<String>` | |
| 105 | | C++ | `WidgetHostOptions.features` | `std::vector<std::string>` | |
| 106 | | TypeScript | `WidgetHost` option `features` | `string[]` | |
| 107 |
| 108 | The profile sets them, not the client: today that is `["webAnimations"]` on |
| 109 | every platform (Web Animations records instead of per-frame style writes). |
| 110 | `canvasWords`, `binaryOps` and `morphUpdates` are Swift-only optimisations of |
| 111 | the same validated output (`docs/changes.md`, "Swift-only"); list them only on |
| 112 | iOS/macOS and only after measuring. A feature the renderer behind your |
| 113 | `Renderer` seam cannot draw must not be listed. |
| 114 |
| 115 | ## The widget payload |
| 116 |
| 117 | A **widget is mini-HTML**: one self-contained HTML document of at most 4 KB |
| 118 | compressed and 32 KB uncompressed. Since API layer 233 it is message media of |
| 119 | its own: `messageMediaWidget width:int height:int payload:bytes` |
| 120 | (`docs/tgw-format.md` has the TL, the server's checks and the errors). The |
| 121 | server compresses the bot's plain HTML with zlib (level 9) and enforces both |
| 122 | limits. The client takes `payload`, a **zlib stream (RFC 1950), not gzip**, |
| 123 | inflates it and passes the text to `WidgetHost`; what inflates it on each |
| 124 | platform, and the decoders that look right but are not (Apple's `COMPRESSION_ZLIB` |
| 125 | is raw deflate, `qUncompress` wants a length prefix): `docs/tgw-format.md`, |
| 126 | "Inflating the payload". Do not add size |
| 127 | checks of your own: the server enforces them and they can move without a |
| 128 | client update; the sandbox is the security boundary. |
| 129 |
| 130 | There is **no file download and no loading state for a file**: the bytes are |
| 131 | already in the message. The only thing to show before the first frame is the |
| 132 | bubble at the size the bot asked for (below) while the sandbox boots, which |
| 133 | takes tens of milliseconds warm and a few hundred cold. A widget is fixed code |
| 134 | plus changeable state: the HTML never changes after sending, and the bot edits |
| 135 | only the widget's state (and the caption), which goes to the live host with |
| 136 | `setData`, never through a new host ("The widget's state and requests", below). |
| 137 | A forwarded message carries a copy of the bytes. |
| 138 |
| 139 | **Enabling.** The server has no flag for widgets. Each client turns rendering |
| 140 | on with its own platform/version flag (a debug or rollout flag, not app |
| 141 | config); with it off, and on clients below layer 233 which receive |
| 142 | `messageMediaUnsupported`, the message shows as unsupported media with its |
| 143 | caption. Keep that fallback. |
| 144 |
| 145 | **Caption and preview.** The media caption is the preview text for the chat |
| 146 | list, notifications and search; without one show the localized "Widget" stub, |
| 147 | as for other media without a caption. |
| 148 |
| 149 | **Testing.** Everything in the shared test channel is a real layer-233 |
| 150 | message: a test bot sends each widget to a tester's private chat (a bot may |
| 151 | also send widgets to the basic groups and supergroups it is a member of, and |
| 152 | via its inline mode; a channel gets them only as forwards) and the messages are |
| 153 | forwarded into the channel; the |
| 154 | copy works like the original. That includes every conformance widget |
| 155 | (`packages/conformance`: each one fits a mini-widget), with its reference |
| 156 | picture posted as a photo next to it in the order of |
| 157 | `packages/conformance/channel.json`, the corpus widgets that fit, forward-copy |
| 158 | storage, the bot's edits of the state and the size anchors from the bot |
| 159 | (`docs/tgw-format.md`). |
| 160 |
| 161 | ## Bubble sizing |
| 162 |
| 163 | `messageMediaWidget` carries two size anchors, `width` and `height`, in logical |
| 164 | pixels (CSS px, pt, dp); `0` means auto and each axis is independent. Every |
| 165 | axis of the bubble is bounded, auto included. The shared constants of v0.1.0, |
| 166 | the same on every client and tunable in a later release: minimum width 200, |
| 167 | height within **[50, 600]**. |
| 168 |
| 169 | | `width` | `height` | before the widget loads | after the first render | |
| 170 | |---|---|---|---| |
| 171 | | 0 | 0 | the default placeholder at the bubble's width | the content height the host reports, clamped to [50, 600], cached per message | |
| 172 | | 0 | H | a bubble of height clamp(H, 50, 600) at the bubble's width | unchanged: the fixed height stays; the reported content height is ignored | |
| 173 | | W | 0 | a widget W px wide, W clamped to [200, the bubble's maximum width]; the default placeholder height | the content height, clamped to [50, 600], cached per message | |
| 174 | | W | H | a fixed widget: width clamp(W, 200, max), height clamp(H, 50, 600) | unchanged | |
| 175 |
| 176 | Width: `0` means the widget takes the bubble's width, the widest the chat |
| 177 | gives a bubble; `W > 0` is a fixed-width widget, and the host is created with |
| 178 | that width (`WidgetHost(width:)`, `widthDp`, the web host's container). Height: |
| 179 | in auto mode use the height the host reports (`onChange` / `onResize`), |
| 180 | clamped to [50, 600], and **cache it per message**, so the bubble opens at |
| 181 | the right height next time the message scrolls in and the list does not jump; |
| 182 | a fixed height is applied from the start and the reported height does not |
| 183 | change it. |
| 184 |
| 185 | The hosts clamp the reported height to these bounds by default since v0.1.0 |
| 186 | (web `MIN_HEIGHT` / `MAX_HEIGHT`, Swift `minHeight` 50 and `Options.maximumHeight` |
| 187 | 600, Kotlin `minHeightDp` 50 / `maxHeightDp` 600, C++ [50, 600]), so a client on |
| 188 | defaults gets the rule; a client that needs other bounds passes its own cap. |
| 189 | Content taller than the bubble's height (600 in auto mode, or the fixed height) |
| 190 | is **hard-clipped**: it does not scroll inside the bubble, and there is no |
| 191 | fullscreen or "open" button in v0.1.0. The width is never changed by the |
| 192 | widget. |
| 193 |
| 194 | **Which edge stays put** (v0.1.3, `docs/sdk-v1.md` §2.12, §5.6). The widget |
| 195 | chooses it with `TelegramWidget.setResizeAnchor('top' | 'bottom')`, and the |
| 196 | host reports it with every height: Swift `WidgetDiagnostics.resizeAnchor` |
| 197 | (`WidgetResizeAnchor`), Kotlin and C++ `WidgetDiagnostics.resizeAnchor` |
| 198 | (`"top"` / `"bottom"`), web `onResize(height, anchor)` and |
| 199 | `WidgetHost.resizeAnchor`; `top` until the widget sets one. When an auto height |
| 200 | changes on screen, compensate the list's scroll so that edge does not move: |
| 201 |
| 202 | | anchor | the bubble | what moves | in a list laid out from the top | |
| 203 | |---|---|---|---| |
| 204 | | `top` (default) | grows and shrinks downward | the content below it | nothing to do | |
| 205 | | `bottom` | grows and shrinks upward, its bottom stays | the content above it | add the height difference to the scroll offset | |
| 206 |
| 207 | In a chat list that is laid out from the bottom (inverted), `bottom` is what the |
| 208 | list does anyway and `top` needs the compensation instead. Apply it to every |
| 209 | height change of the bubble: a size report, the cached height giving way to the |
| 210 | first report, a re-created bubble (the new run reports its own anchor with its |
| 211 | height). A bubble off screen keeps what is on screen in place, as any list item |
| 212 | does. Keep the anchor next to the cached height per message. If your list |
| 213 | animates height changes, pin the widget view (or the snapshot you show during |
| 214 | the animation) to the anchored edge of the bubble, so the old pixels stay |
| 215 | aligned with the edge that stays put. The web dev app and the feed demo do all |
| 216 | of this (`apps/web/src/main.ts`, `feed.ts`); `corpus/resize` has one widget per |
| 217 | anchor to try it. |
| 218 |
| 219 | ## The time over a widget with no caption below it |
| 220 |
| 221 | Without a caption, and with a caption shown above the widget (`invert_media`, as on |
| 222 | a photo whose caption is moved up), draw the message time and its status (ticks, |
| 223 | "edited", views) over the widget's bottom corner, on a backing, as over a photo: |
| 224 | the right corner in a left-to-right interface, the left one in a right-to-left one. |
| 225 | With a caption below the widget the time goes into the caption's line and nothing is |
| 226 | drawn over the widget: pass 0 (`docs/sdk-v1.md` §2.17, §5.12). |
| 227 |
| 228 | Pass what the time takes as the host's `contentSafeArea` (points, dp, CSS px): |
| 229 | `bottom`, the height of its band at the widget's bottom edge, and `cornerRight` (or |
| 230 | `cornerLeft` in a right-to-left interface), the width of the corner it takes in that |
| 231 | band, backing and margins included; the rest 0. Pass it **at creation**, so the first |
| 232 | height the host reports already has the band, and change it with |
| 233 | `setContentSafeArea` only when the bubble's layout changes (a caption added or |
| 234 | removed by an edit, or moved above or below the widget, "edited" appears, the views |
| 235 | counter grows). Never per frame, and |
| 236 | not for the floating date pill, which has no contract. The time is your view over |
| 237 | the widget: its taps are yours; nothing in the gesture policy changes. |
| 238 |
| 239 | The widget sees it as `env(safe-area-inset-bottom)` (the validator rewrites it to a |
| 240 | root variable the renderer sets), `--tg-content-safe-area-inset-*` / |
| 241 | `--tg-content-safe-area-corner-left|right` and `TelegramWidget.contentSafeAreaInset`; |
| 242 | the renderer's UA layer pads an unstyled body by the band. A client that passes |
| 243 | nothing keeps v0.3.0's behaviour (all 0). The dev app's **time** control and |
| 244 | `?time=corner|corner-rtl` show it; `visual/17-time-corner` and `auto/36-safe-area` |
| 245 | are its conformance cases (sent without a caption, and once more with the caption |
| 246 | above), and `corpus/safe-area` has examples (its `07` is posted three times: no |
| 247 | caption, a caption below, a caption above). |
| 248 |
| 249 | ## Heavy boxes |
| 250 |
| 251 | Since v0.6.0 a widget has at most 16 heavy boxes at once, of them at most 2 with `backdrop-filter`; past either it |
| 252 | stops like at any limit (`onDead` / `WidgetDiagnostics.dead`: `Paint limit exceeded: 17 boxes with shadows, filters or |
| 253 | transparency (max 16)` or `Paint limit exceeded: 3 boxes with backdrop-filter (max 2)`, the diagnostic `paint-limit` / |
| 254 | `backdrop-limit`). A box is heavy when its computed style has a blurred `box-shadow` layer, a `filter`, a |
| 255 | `backdrop-filter` or `opacity` below 1, or while an animation of one of them runs on it (`docs/decisions.md`, "Heavy |
| 256 | boxes"). The opacity of a `<button>` that is disabled or held down (`:active`) is its own dimming and does not count, |
| 257 | so the client-styled button's disabled and pressed looks never stop a widget. Only the renderer knows the cascade, so |
| 258 | **the renderer counts**: |
| 259 |
| 260 | - **The framework's WebView renderer** (`RendererWebView` on iOS, macOS and Android, the iframe and Shadow DOM |
| 261 | renderers on the web) counts by itself, before each frame it draws, and reports to the host. Nothing to do; keep |
| 262 | `policy` `strict` (under `compat` nothing is counted). |
| 263 | - **A renderer of your own** behind the `Renderer` seam counts the same rule and calls the seam once, before it draws |
| 264 | the frame that would pass the limit: `renderer.limitExceeded(.paint, count: 17)` (Swift), |
| 265 | `limitExceeded(WidgetPaintLimit.PAINT, 17)` (Kotlin), `limitExceeded(WidgetPaintLimit::Paint, 17)` (C++); the |
| 266 | WebView renderer's message on the web is `{ type: 'limit', code, count }` (`docs/protocol.md`). The host does the |
| 267 | rest. The renderer then draws the stopped widget without those effects (no blurred shadow, filter, backdrop-filter |
| 268 | or transparency; animations stopped): the frozen frame costs nothing while the chat scrolls. |
| 269 | - **Count against the fixture.** The rule is `packages/core/src/shared/paint-policy.ts` (`boxPaint`, |
| 270 | `animationPaint`, `PaintCounter`) and `packages/core/tests/fixtures/paint-policy.json` is its contract: computed |
| 271 | values to heavy or not (blur 0, inset without blur, opacity 0.999 and 1, `brightness(1)`, a `::before` with `content: |
| 272 | none`, `visibility: hidden`, a disabled or pressed `<button>` dimmed, one with a blurred shadow), keyframes to an animation that counts or not, and sequences of batches and animation |
| 273 | events to the counts and the moment of the stop. Count after a whole batch (never op by op), when an animation of |
| 274 | the rule starts or ends (CSS animation and transition events, a Web Animation that runs), and when the cascade changes |
| 275 | without an op (the theme, the safe area, the bubble's width, `:hover`, `:active`). You may recount only the boxes a |
| 276 | change reaches (the changed elements and their subtrees, the parent's subtree with a sibling combinator or a structural |
| 277 | pseudo-class in the widget's sheets, all of them for a stylesheet change). The conformance set has the cases |
| 278 | (`auto/37`–`43`). |
| 279 |
| 280 | ## Input |
| 281 |
| 282 | - **Text selection is the widget's choice** (since v0.1.1, `docs/sdk-v1.md` |
| 283 | §2.4, §5.10). Text is not selectable by default; text the widget marks |
| 284 | `user-select: text` is. A long press over text is the bubble's (below), so |
| 285 | on touch a selection inside a widget starts the way your client |
| 286 | selects text in an ordinary message (its menu's Select, or its selection mode); with a mouse, |
| 287 | a drag over selectable text selects it. Copy is your normal copy command. |
| 288 | The bubble never lets the user start a drag of the widget's content. A |
| 289 | native renderer that cannot select yet keeps the text unselectable. |
| 290 | - **No keyboard input, no focus.** Widgets get no key events and never take |
| 291 | keyboard focus (`docs/decisions.md`, "Profile v1"). The chat's input field |
| 292 | keeps the focus while a widget is on screen; a widget's `focus()` must not |
| 293 | move it (one of the known issues of v0.1.0 on the web, see below) and the |
| 294 | conformance set checks `chatFocused` for exactly this. |
| 295 | - **User activation is a pointer press only.** A link call (`openLink`, |
| 296 | `openTelegramLink`, a tapped `<a href>`) goes through only from the handler of a real |
| 297 | tap or click the renderer saw (`trusted`), one call per press; no key press |
| 298 | counts, and a finger's press counts from its release (it may still become the |
| 299 | chat's scroll). A renderer behind your own `Renderer` implementation must mark its |
| 300 | real input `trusted: true` or the widget never gets a gesture, but not a finger's |
| 301 | or a pen's `pointerdown`. |
| 302 | - **Who gets a press: `touch-action` is the claim, and vertical drags are |
| 303 | always the chat's** (v0.1.2 and v0.1.3, `docs/sdk-v1.md` §5.5). On every |
| 304 | primary pointer press the host reports the widget's claim (`onGestureClaim` |
| 305 | in Swift and on the web, `onGesture` in Kotlin and C++): horizontal drags |
| 306 | (`x`: from `pan-y` or `none`) and `hold` (only from `touch-action: none`); |
| 307 | `y` is always false since v0.1.3. Taps and double taps over the widget are |
| 308 | always the widget's: your double-tap reaction must not act over the widget |
| 309 | (it stays on the bubble outside it), and the renderer gives the widget its |
| 310 | own `dblclick`. Drive your bubble's recognizers from the shared |
| 311 | `GestureArbiter` (every package ships it with its thresholds: 10 px slop, |
| 312 | 500 ms hold, 300 ms / 40 px double tap, 20 px leading edge strip): a |
| 313 | vertical drag always scrolls the list, over every element; over an element |
| 314 | that does not claim the press, a hold opens the message menu and a |
| 315 | horizontal swipe is reply or back; in each case you cancel the widget's |
| 316 | touch the platform's way (it gets `pointercancel`, no `click`). Over one |
| 317 | that claims it, you stand back for that gesture and the renderer gives the |
| 318 | widget its own `contextmenu`. Never stop your list from scrolling because of |
| 319 | a claim. The bubble outside the widget stays yours. With a mouse, a right |
| 320 | click follows the same claim; clicks, double clicks, holds and drags are the |
| 321 | widget's. On Android `RendererWebView` keeps its parent from intercepting |
| 322 | only while a hold claim may still win. On the web pass `bubbleGestures` and |
| 323 | the renderer plays the bubble itself (`onBubbleGesture` says what it took); |
| 324 | the browser's vertical pan stays allowed over every widget. The conformance |
| 325 | widgets `auto/23-gestures-a` / `-b` and `visual/sdk/12-drag-gestures` check your |
| 326 | client. |
| 327 | - **What the widget asks for** arrives as `onAction`, checked: `openLink(url)` |
| 328 | (show a confirmation with the full URL, then the browser), |
| 329 | `openTelegramLink(url)` (your own t.me handling, as a tapped `t.me` link in a |
| 330 | message: no confirmation of its own), `haptic(…)` (play it or |
| 331 | ignore it on desktop and web), `ready`. `docs/sdk-v1.md` §5 is the client's |
| 332 | side of each. The widget's state and requests add two callbacks of their own: |
| 333 | `onRequest` and `onCopyText` (below). |
| 334 |
| 335 | ## The widget's state and requests |
| 336 |
| 337 | A widget is fixed code plus changeable state. The HTML is set when the bot |
| 338 | sends the widget and never changes; the state changes, and only the bot writes |
| 339 | it: the **chat state**, `chat_data` (tied to this message, seen only in its |
| 340 | chat, never forwarded), and the **shared state**, `public_data` (seen wherever |
| 341 | the widget is shown: a forward gets a copy as of the forward, or, in a shared |
| 342 | widget, the one shared state of all its messages and forwards). The widget reads |
| 343 | its state and cannot change it itself; it can send the bot a request, a callback |
| 344 | button inside the widget (`docs/sdk-v1.md` §2.13–§2.15 and §5.11; the server's |
| 345 | side, `docs/tgw-format.md` "The widget's state and requests"). The host |
| 346 | interface is the same on every platform (`docs/sdk-v1.md` §4 has the exact |
| 347 | types): |
| 348 |
| 349 | | the client passes or implements | what it is | |
| 350 | |---|---| |
| 351 | | `data` (at creation) | `{ chatData, publicData }`: the message's chat state and shared state as the client has them now; none = null | |
| 352 | | `context` (at creation, fixed) | the server's flags from `messageMediaWidget`, read, not derived: `isCopy` (`is_copy`), `canQuery` (`can_query`: requests on a tap; never set for a widget the bot sent without `allow_queries`), `backgroundQuery` (`background_query`: requests without a tap too, one when the widget appears on screen, then one per 5 s while it is visible; one the widget makes off screen, at boot included, waits in the framework and reaches `onRequest` once `setVisible(true)` reports the bubble on screen); `chatType` (the kind of chat: `private`, `group`, `supergroup`), `viewer` (the account's own: its user id, first and last name, username and Premium flag, as the bot gets them in `from`). Pass them for every message: the framework gives no copy the chat type, and no message without `canQuery` the viewer (the widget knows who views it only where it may send requests). No flags: no requests | |
| 353 | | `setData(data)` | the state changed: the full new state (the chat state and the shared state); the widget gets `chatDataChanged` / `publicDataChanged`, nothing restarts. Call it on `updateMessageWidgetData` (apply the chat state and the shared state it carries) and when polling brings a new shared state (below) | |
| 354 | | `onRequest(request, complete)` | `{ data }`: call `messages.getBotWidgetQueryAnswer` (the peer, the message id, `data` as UTF-8 bytes) and complete with its `{ result }`, or a failure: `timeout` for `WIDGET_RESPONSE_TIMEOUT`, `rateLimited` for `FLOOD_WAIT`, `failed` for anything else; complete every request exactly once. The answer carries no state and no toast, alert or link: show nothing for it, and do not re-fetch the state after it | |
| 355 | | `onCopyText(text)` | copy it and show the client's toast with the copied text | |
| 356 | | `onWatchPublicData(on)` / `watchesPublicData` | the widget asks to follow its shared state live (`watchPublicData()`) or stops: poll its `public_data` only while it watches, is on screen and has a `widget_id` (below); called on a change, the field has the latest (web `WidgetHost.watchesPublicData`, native `WidgetDiagnostics.watchesPublicData`) | |
| 357 | | `context.preview` | a widget in a list of inline results, before it is sent (`botInlineMessageWidget` with its state, `public_data` and `chat_data`, and a `widget_id` for a result by reference, which takes the shared state from its object; a result has no flags): no input (a tap on it selects the result: route no touches to the view), no requests or actions, no viewer, no storage, no network marker. Create a new host for the message once it is sent | |
| 358 |
| 359 | **The network marker** (a UI contract of the server's spec). When the message |
| 360 | has `can_query` (`context.canQuery`), mark the widget as network-capable: "a |
| 361 | tap may send data to the bot's server", a small sign in the bubble that |
| 362 | explains itself on a tap or hover. Without `can_query` show no marker: the bot |
| 363 | sent the widget without `allow_queries`, or this copy may not ask, and the |
| 364 | server refuses every request from it, so the marker is exactly as honest as the |
| 365 | flag. A preview has no flags and no marker; a client that sets no `onRequest` |
| 366 | delivers no request and shows no marker either. The dev app draws one in its |
| 367 | bubble's header (`?message=private`: shown; `no-queries`, `copy`, `preview`: |
| 368 | none). |
| 369 |
| 370 | **Applying the bot's edits of the state.** `updateMessageWidgetData` carries |
| 371 | the new chat state (`chat_data`) and/or shared state (`public_data`) of one |
| 372 | message (a field not in it is unchanged, an empty string clears it). In private |
| 373 | chats and basic groups it comes in the account's pts sequence, as |
| 374 | `updateEditMessage` does; in a supergroup the post is updated through the usual |
| 375 | edit of channel posts, with the channel's pts (`updateEditChannelMessage` and |
| 376 | the like). Apply it by the rules of that sequence, store the state with the |
| 377 | message and pass the full new state to the live host with `setData`. |
| 378 |
| 379 | **Polling a shared widget's shared state.** When the media has a `widget_id`, |
| 380 | the widget is a shared object: its payload, size anchors and shared state |
| 381 | (`public_data`) are the same in the original, every forward and every other |
| 382 | message the bot sent by that id, and the bot changes the shared state for all |
| 383 | of them at once. Only **widgets that watch** are polled: a widget asks to follow |
| 384 | its shared state live with `TelegramWidget.watchPublicData()` and stops with |
| 385 | `unwatchPublicData()`, and the host reports the latest (web `onWatchPublicData(on)` and |
| 386 | `WidgetHost.watchesPublicData`; Swift, Kotlin and C++ `onWatchPublicData` and |
| 387 | `WidgetDiagnostics.watchesPublicData`). Every other widget gets its shared |
| 388 | state with the message only; a widget that watches without a `widget_id` changes |
| 389 | nothing (there is no object to poll), and a preview never watches. While |
| 390 | widgets with an id are on screen and watch, the messenger (never the sandbox) |
| 391 | polls **one visible carrier per `widget_id`** with |
| 392 | `messages.getWidgetPublicData`, |
| 393 | one message per call, with the hash of the shared state it has (`0` at first): |
| 394 | `widgetPublicDataNotModified` changes nothing, `widgetPublicData` brings the new |
| 395 | shared state, which the client applies with `setData` to **every** widget on |
| 396 | screen with that id (and stores with each message). Every answer carries the object's |
| 397 | `period`, the recommended cadence: poll that object again after it (the |
| 398 | server's period: 5–3600 s, 30 s by default, which also applies before the |
| 399 | first answer). An edit is visible at once to any read, so a message loaded |
| 400 | later is current anyway. A widget without a `widget_id` keeps the shared state |
| 401 | its message has (a forward's copy never changes); the chat state (`chat_data`) |
| 402 | is never polled: the server pushes it. |
| 403 |
| 404 | Optional: widgets with the same `widget_id` are one widget, so a client may |
| 405 | cache the checked payload (the inflated HTML) and the current shared state per |
| 406 | `widget_id` and share them between the messages that show it; the host still |
| 407 | gets the HTML and the state per message, as above. |
| 408 |
| 409 | The framework checks everything coming out of the sandbox (the limits of a |
| 410 | request's `data`, the flags, one tap per request or the background rules, one |
| 411 | request in flight, the `copyText` tap) and everything going in (the chat state, |
| 412 | the shared state and `result`, each a text of up to 1024 bytes (UTF-8) without a |
| 413 | NUL; a copy without chat state): |
| 414 | the client only delivers. A client that sets no `onRequest` gets every request |
| 415 | refused in the widget (`NOT_ALLOWED`). Requests are never sent over the |
| 416 | widget's own channels: the sandbox has no network (invariant 5); the client's |
| 417 | MTProto connection carries them. |
| 418 |
| 419 | ## The wallet |
| 420 |
| 421 | A widget can pay and sign through Gram Wallet (`docs/sdk-v1.md` §2.18, §5.13). Nothing changes until the client |
| 422 | passes `context.wallet = true`: the client supports the wallet and the wallet is available to this user (their |
| 423 | country). Then: |
| 424 |
| 425 | | Host input / callback | What the client does | |
| 426 | |---|---| |
| 427 | | `WidgetRequest.wallet` | the widget asked, on a tap, for the user's wallet: call `getBotWidgetQueryAnswer` with `widgetQueryTypeData` and `with_wallet`; the server attaches the profile's wallet card (the cloud wallet) to the bot's update and creates the wallet if there is none | |
| 428 | | `onWallet(call, complete)` | `sendTransaction` (a `WalletTransaction`: TON Connect's `sendTransaction` request, `json` / `toJson()` in its field names) or `signData` (a `SignDataPayload`, TON Connect's payload), with `data`: show the existing TON Connect window over the chat with the bot of the message in its header, ignore taps on it for its first 0.5–1 s, top up an empty wallet over the chat; on confirmation send the transaction the wallet's way (or sign for the domain `bot<bot_id>`), send the outcome to the bot as a widget query with `data` (`widgetQueryTypeSentTransaction` with the normalised message hash, or `widgetQueryTypeSignData` with `signData`'s result, each with the device's wallet as `userWallet`: the address (raw or user-friendly, mainnet), the balance in nanotons, the 32-byte public key and the wallet's StateInit as a bag of cells (one flag: both or neither, both with a signature); it can differ from the profile's card when the wallet's backup is off; the formats: `docs/sdk-v1.md` §5.13), and complete with the bot's answer. Decline: `rejected`; the wallet's refusal: `badRequest`; the query's failures as a request's | |
| 429 |
| 430 | The framework has checked the transaction or the payload (TON Connect's fields only, 1–255 messages, user-friendly destinations), the tap or the |
| 431 | grant (the answer to a call made by a tap, within 10 s), and one call in flight with the requests. The server's API |
| 432 | is agreed and not shipped yet (`docs/decisions.md`, "The wallet"); until it is, leave `context.wallet` unset. |
| 433 |
| 434 | ## Forwarding and state |
| 435 |
| 436 | A widget message may be forwarded to any chat, groups and channels included. |
| 437 | The copy runs the same HTML (isolated, no network) with the copy's own flags |
| 438 | (`is_copy`; `can_query` only when the bot sent the widget with |
| 439 | `fwd_allow_queries`, and then on a tap only) and a shared state: its own, frozen as of the forward, or the |
| 440 | shared widget's one shared state, which changes and is polled as above. It never has |
| 441 | a chat state, and it is told nothing about the chat it is in (no chat type: the |
| 442 | bot must not learn where its widget was forwarded, and the server sends the bot |
| 443 | neither the chat nor its type with a request from a copy); the viewer only with |
| 444 | `can_query`. It is a different message, so **each copy has its own storage**: keep Web Storage per (account, chat, message id), pass it as the |
| 445 | host's `storage` at creation and keep what `onStorageCommit(area, values)` |
| 446 | hands you — `local` on disk (with a short delay, and at once when the widget |
| 447 | is hidden or destroyed and when the app goes to the background), `session` in |
| 448 | memory — and delete both with the message, the chat, the account and on "Clear |
| 449 | cache" (`docs/sdk-v1.md` §5.4). The framework enforces the 4 KB quota. |
| 450 |
| 451 | **Theme and language.** Pass the chat's theme as a `WidgetTheme` (colour |
| 452 | scheme, the Mini Apps palette keys as `#rrggbb`, your button's tokens, your |
| 453 | message text's tokens) and call `setTheme` on every change; pass the UI |
| 454 | language as `locale` (`docs/sdk-v1.md` §2.3, §2.4, §2.9). |
| 455 |
| 456 | - The palette is the colours of **this bubble**. Keep the widget view |
| 457 | transparent over your bubble as before: the bubble you draw in `bg_color` is |
| 458 | the widget's canvas, its text is drawn in `text_color`, and a background the |
| 459 | widget sets on its root or body covers the whole bubble. **The widget view |
| 460 | fills the bubble: no padding of the bubble's own around it** (the widget's |
| 461 | body margin, the `padding` text token, is the inset), and the bubble clips |
| 462 | the view at its corner radius, so a widget background reaches the rounded |
| 463 | edges (`visual/15-body-background`). A widget the user |
| 464 | sent or forwarded sits in an outgoing bubble: pass the outgoing colours |
| 465 | (fill, text, hint, link, separator). |
| 466 | - The text tokens (since v0.1.1) are your message text: `fontSize` in points / |
| 467 | dp = CSS px, following the chat's text-size setting (call `setTheme` when the |
| 468 | user changes it), `lineHeight` (unitless) and `padding` (the inset of text in |
| 469 | your bubble, CSS lengths; the body's margin, so `body { margin: 0 }` in a |
| 470 | widget still goes edge to edge). Without them the renderer uses the reference set |
| 471 | 15 / 1.35 / `8px 12px`. A widget without CSS is then drawn in your text style |
| 472 | on your bubble's colour; any widget CSS wins (`docs/sdk-v1.md` §2.4). |
| 473 |
| 474 | ## iOS and macOS (Swift package) |
| 475 |
| 476 | Add the repo as a package dependency (the manifest is the repo-root |
| 477 | `Package.swift`; a local checkout works with a path dependency), product |
| 478 | `WidgetSandbox`. iOS 16 / macOS 10.13 (the demo apps need macOS 13). |
| 479 |
| 480 | ```swift |
| 481 | import WidgetSandbox |
| 482 |
| 483 | var options = WidgetHost.Options() // policy .strict, features [] by default |
| 484 | options.features = ["webAnimations"] |
| 485 | options.locale = "ru" |
| 486 | options.storage = WidgetStorage(local: savedLocal, session: savedSession) // this message's Web Storage |
| 487 | options.contentSafeArea = media.caption == nil || message.invertMedia ? WidgetContentSafeArea(bottom: timeBand, cornerRight: timeWidth) : WidgetContentSafeArea() // no caption below: the time over the corner |
| 488 | options.data = WidgetData(chatData: media.chatData, publicData: media.publicData) // the chat state and the shared state |
| 489 | options.context = WidgetContext(isCopy: media.isCopy, canQuery: media.canQuery, backgroundQuery: media.backgroundQuery, |
| 490 | chatType: .private, viewer: WidgetViewer(id: me.id, firstName: me.firstName, lastName: me.lastName, |
| 491 | username: me.username, isPremium: me.isPremium)) // the server's flags; the account |
| 492 | let theme = WidgetTheme(colorScheme: .light, params: ["bg_color": "#ffffff", "text_color": "#000000" /* … every key, this bubble's */], |
| 493 | button: WidgetButtonTokens(radius: "10px", font: "500 15px system-ui"), |
| 494 | text: WidgetTextTokens(fontSize: 17, lineHeight: 1.3, padding: "6px 10px")) |
| 495 | let host = try WidgetHost(html: html, theme: theme, width: 360, options: options) |
| 496 | host.onChange = { d in /* d.height, d.loaded, d.dead, d.lastError, d.stats */ } |
| 497 | host.onAction = { action in /* .openLink(url): confirm, open; .openTelegramLink; .haptic; .ready */ } |
| 498 | host.onStorageCommit = { area, values in /* keep values as the new content of that area */ } |
| 499 | host.onGestureClaim = { claim in /* x, y, hold: feed your bubble's GestureArbiter (docs/sdk-v1.md §5.5) */ } |
| 500 | host.onRequest = { request, complete in /* getBotWidgetQueryAnswer(request.data); complete(.success(WidgetRequestAnswer(result: answer.result))) or .failure(.timeout) */ } |
| 501 | host.onCopyText = { text in /* copy it, show "Copied: \(text)" */ } |
| 502 | // updateMessageWidgetData, or a polled shared state: host.setData(WidgetData(chatData: …, publicData: …)) |
| 503 | bubble.addSubview(host.view) // UIView on iOS, NSView on macOS; its height follows the widget |
| 504 | // later: |
| 505 | host.setVisible(false) // off screen |
| 506 | host.setTheme(darkTheme) |
| 507 | host.destroy() |
| 508 | ``` |
| 509 |
| 510 | SwiftUI: `WidgetView(host:)` wraps the view, `WidgetModel` is an |
| 511 | `ObservableObject` that owns a host and publishes its diagnostics. |
| 512 |
| 513 | For a list of many bubbles, `WidgetHost.Options` has `sharedWebKit`, `pools`, |
| 514 | `parallelBoot`, `asyncValidation`, `sharedValidatorThread`; `docs/chat-feed-ios.md` |
| 515 | explains what each buys and `apps/ios/DemoApp/Sources/ChatFeed` is a working |
| 516 | list. |
| 517 |
| 518 | ## Android (Gradle library) |
| 519 |
| 520 | Coordinates `org.telegram.widgetsandbox:widget-sandbox`. Inside this repo |
| 521 | `apps/android` takes them from `packages/android` through |
| 522 | `includeBuild("../../packages/android")`; a client outside the repo does the |
| 523 | same with a checkout at the tag, or takes the AAR from a Maven repository once |
| 524 | one is published. minSdk 26; the AAR carries the QuickJS native library for |
| 525 | arm64-v8a and x86_64 and the JS bundles as assets. |
| 526 |
| 527 | ```kotlin |
| 528 | import org.telegram.widgetsandbox.WidgetHost |
| 529 |
| 530 | val options = WidgetHost.Options(features = setOf("webAnimations"), // policy "strict" by default |
| 531 | locale = "ru", storage = WidgetStorage(local = savedLocal, session = savedSession), |
| 532 | contentSafeArea = if (caption == null || message.invertMedia) WidgetContentSafeArea(bottom = timeBand, cornerRight = timeWidth) else WidgetContentSafeArea(), // no caption below: the time over the corner |
| 533 | data = WidgetData(media.chatData, media.publicData), |
| 534 | context = WidgetContext(isCopy = media.isCopy, canQuery = media.canQuery, backgroundQuery = media.backgroundQuery, |
| 535 | chatType = "private", viewer = WidgetViewer(me.id, me.firstName, me.lastName, me.username, me.isPremium))) // the server's flags; the account |
| 536 | val theme = WidgetTheme("light", params = mapOf("bg_color" to "#ffffff" /* … every key, this bubble's */), button = WidgetButtonTokens(radius = "10px"), |
| 537 | text = WidgetTextTokens(fontSize = 16.0, padding = "6px 10px")) |
| 538 | val host = WidgetHost(context, html, theme, widthDp = 360.0, options = options) |
| 539 | host.onChange = { d -> /* d.height, d.loaded, d.dead, d.lastError */ } |
| 540 | host.onAction = { action -> /* WidgetAction.OpenLink(url): confirm, open; OpenTelegramLink; Haptic; Ready */ } |
| 541 | host.onStorageCommit = { area, values -> /* "local" | "session": keep values */ } |
| 542 | host.onGesture = { claim -> /* x, y, hold: feed your bubble's GestureArbiter (docs/sdk-v1.md §5.5) */ } |
| 543 | host.onRequest = { request, complete -> /* getBotWidgetQueryAnswer(request.data); complete(Result.success(WidgetRequestAnswer(answer.result))) or Result.failure(WidgetRequestException(WidgetRequestFailure.TIMEOUT)) */ } |
| 544 | host.onCopyText = { text -> /* copy it, show the text */ } |
| 545 | // updateMessageWidgetData, or a polled shared state: host.setData(WidgetData(…, …)) |
| 546 | bubble.addView(host.view) // a View whose height follows the widget (minHeightDp / maxHeightDp in Options) |
| 547 | host.setVisible(false); host.setTheme(darkTheme); host.destroy() |
| 548 | ``` |
| 549 |
| 550 | `SandboxResources.get(context)` loads the bundles from the library's assets |
| 551 | once per process. `Options.pools` / `sharedValidatorThread` are the list |
| 552 | optimisations ported so far (`docs/android-renderer-bench.md`). |
| 553 |
| 554 | ## Web (npm package) |
| 555 |
| 556 | `@telegram/widget-sandbox` (a pnpm workspace package here; pin it as above). |
| 557 | The host runs the widget in a Worker with QuickJS compiled to wasm and renders |
| 558 | through the Shadow DOM renderer (the product renderer, `docs/shadow-dom-renderer.md`) |
| 559 | or into a sandboxed `srcdoc` iframe (the dev app's default and the reference). |
| 560 | Two requirements on the embedding page: |
| 561 |
| 562 | - the page must be **cross-origin isolated** (`Cross-Origin-Opener-Policy: |
| 563 | same-origin`, `Cross-Origin-Embedder-Policy: require-corp`) — the sync |
| 564 | query bridge is a `SharedArrayBuffer`; the Vite plugin sets the headers in |
| 565 | dev, your server must send them in production — and, for the Shadow DOM |
| 566 | renderer, the page's own CSP must close the network as `docs/decisions.md` |
| 567 | ("The web renders through Shadow DOM") lists; |
| 568 | - the two in-page bundles are built from the package's sources by its Vite |
| 569 | plugin (`virtual:sandbox-bundle`, `virtual:renderer-bundle`), so the host |
| 570 | must be bundled with Vite + `widgetSandbox()` from `@telegram/widget-sandbox/vite`. |
| 571 |
| 572 | ```ts |
| 573 | // vite.config.ts |
| 574 | import { widgetSandbox } from '@telegram/widget-sandbox/vite'; |
| 575 | export default { plugins: [widgetSandbox()] }; |
| 576 |
| 577 | // in the app |
| 578 | import { WidgetHost } from '@telegram/widget-sandbox/host/widget-host'; |
| 579 | import { ShadowDomRenderer } from '@telegram/widget-sandbox/host/shadow-renderer'; |
| 580 | const host = new WidgetHost(bubbleElement, html, { |
| 581 | theme: { colorScheme: 'light', params: { bg_color: '#ffffff' /* … every key, this bubble's */ }, button: { radius: '10px' }, text: { fontSize: 16, padding: '6px 10px' } }, |
| 582 | locale: 'ru', |
| 583 | storage: { local: savedLocal, session: savedSession }, // this message's Web Storage |
| 584 | contentSafeArea: caption && !message.invertMedia ? {} : { bottom: timeBand, cornerRight: timeWidth }, // no caption below: the time over the corner |
| 585 | data: { chatData, publicData }, // the chat state and the shared state |
| 586 | context: { isCopy, canQuery, backgroundQuery, chatType: 'private', viewer: { id: me.id, firstName: me.firstName, lastName: me.lastName, username: me.username, isPremium: me.isPremium } }, // the server's flags; the account |
| 587 | onRequest: async ({ data }) => ({ result }), // getBotWidgetQueryAnswer; or throw 'TIMEOUT' | 'RATE_LIMITED' | 'FAILED' |
| 588 | onCopyText: (text) => {}, // copy it, show the text |
| 589 | features: ['webAnimations'], // policy 'strict' by default |
| 590 | rendererFactory: ShadowDomRenderer.factory, |
| 591 | onResize: (h) => {}, // CSS px |
| 592 | onAction: (action) => {}, // { kind: 'openLink', url } | 'openTelegramLink' | 'haptic' | 'ready' |
| 593 | onStorageCommit: (area, values) => {}, |
| 594 | onGestureClaim: ({ x, y, hold }) => {}, |
| 595 | bubbleGestures: true, // no recognizers of your own over the widget: the renderer plays the bubble |
| 596 | onBubbleGesture: ({ action }) => {}, // 'menu' | 'swipe' | 'scroll' | 'back' |
| 597 | onDead: (reason) => {}, |
| 598 | }); |
| 599 | host.setVisible(false); host.setTheme(darkTheme); host.destroy(); |
| 600 | host.setData({ chatData, publicData }); // updateMessageWidgetData, or a polled shared state |
| 601 | ``` |
| 602 |
| 603 | `workerPool` (a `WorkerPool` of warmed workers) is the option for a feed of |
| 604 | many bubbles; `docs/chat-feed-web.md`. |
| 605 |
| 606 | ## Desktop (C++ core) |
| 607 |
| 608 | `packages/desktop` is a CMake project (`add_subdirectory` or `FetchContent`), |
| 609 | targets `twidget-sandbox` (+ `twquickjs`), C++20, no Qt. It has no renderer of |
| 610 | its own: you implement `twidget::Renderer` (`renderer.h`) over the widget |
| 611 | toolkit you have, or go one level down and drive `SandboxEngine` with your own |
| 612 | delegate. `packages/desktop/README.md` § Embedding has the threading rules |
| 613 | (engine callbacks arrive on the engine thread; `onQuery` is synchronous). |
| 614 |
| 615 | ```cpp |
| 616 | #include <twidget/widget_host.h> |
| 617 | auto resources = twidget::SandboxResources::fromDirectory("<path to WidgetJS>"); // the three bundles and their bytecode |
| 618 | twidget::WidgetHostOptions options; // policy "strict" by default |
| 619 | options.features = {"webAnimations"}; |
| 620 | options.locale = "ru"; |
| 621 | options.storage = {savedLocal, savedSession}; // this message's Web Storage |
| 622 | if (!media.caption || message.invertMedia) options.contentSafeArea = {.bottom = timeBand, .cornerRight = timeWidth}; // no caption below: the time over the corner |
| 623 | options.data = {media.chatData, media.publicData}; // std::optional<std::string> each |
| 624 | options.context = {.isCopy = media.isCopy, .canQuery = media.canQuery, .backgroundQuery = media.backgroundQuery, .chatType = "private", .viewer = twidget::WidgetViewer{me.id, me.firstName, me.lastName, me.username, me.isPremium}}; |
| 625 | twidget::WidgetTheme theme{"light", {{"bg_color", "#ffffff"} /* … every key, this bubble's */}, {}, {.fontSize = 14, .padding = "6px 10px"}}; |
| 626 | twidget::WidgetHost host(html, theme, 360, options, resources, myRendererFactory); |
| 627 | host.onAction = [](const twidget::WidgetAction& a) { /* OpenLink: confirm, open; OpenTelegramLink; Haptic; Ready */ }; |
| 628 | host.onStorageCommit = [](const std::string& area, const std::map<std::string, std::string>& values) {}; |
| 629 | host.onGesture = [](const twidget::WidgetGestureClaim& c) { /* feed your bubble's twidget::GestureArbiter */ }; |
| 630 | host.onRequest = [](const twidget::WidgetRequest& r, std::function<void(const twidget::WidgetRequestOutcome&)> respond) { /* send r.data; respond({.answer = {.result = …}}) or respond({.failure = twidget::WidgetRequestFailure::Timeout}) */ }; |
| 631 | host.onCopyText = [](const std::string& text) { /* copy it, show the text */ }; |
| 632 | host.start(); |
| 633 | // the bot edited the state: host.setData({newChatData, newPublicData}); |
| 634 | // host.setVisible(false); host.setTheme(darkTheme); host.destroy(); |
| 635 | ``` |
| 636 |
| 637 | ## The conformance set |
| 638 |
| 639 | `packages/conformance` ships with the tag: 40 self-checking widgets |
| 640 | (`auto/`), 20 visual widgets and 17 client-SDK widgets for the test channel |
| 641 | (`visual/`), all of them mini-widgets, the feature catalogue, reference images, |
| 642 | the posting order (`channel.json`) and the report tool. **`packages/conformance/CLIENTS.md`** |
| 643 | is the step-by-step guide for a client team: configure the host as in |
| 644 | production, load each widget, read its result from the validated ops, perform |
| 645 | the scripted taps, crop the stages, and run `node packages/conformance/tools/report.mjs` |
| 646 | to get the per-renderer report that is compared across clients. Run it at |
| 647 | every framework update; `catalogue.json` `version` is the profile version. |
| 648 |
| 649 | ## What the host does not do |
| 650 |
| 651 | - Open a link, play a haptic or show a dialog: `onAction` is the widget |
| 652 | asking, already checked; the app confirms and does it (or ignores it). The |
| 653 | widget is never told the outcome. |
| 654 | - Talk to the bot by itself: a request reaches the bot only through the app's |
| 655 | `onRequest`, and the widget's state only through `data` and `setData`; the |
| 656 | sandbox has no network. |
| 657 | - Persist anything, or share anything between widgets: the framework hands |
| 658 | you each storage commit, the app stores it; each widget is a fresh runtime |
| 659 | with its own limits. |
| 660 | - Load fonts, media or remote images: `data:` images only (`docs/decisions.md`). |
| 661 | - Check the payload's size or origin: the server compresses it and enforces the |
| 662 | limits, the client trusts it and sandboxes the content. |
| 663 |