| 6 | the `TelegramWidget` API in `docs/sdk-v1.md` §2, the payload in |
| 7 | `docs/tgw-format.md`. A block for a model's system prompt, which stands alone, is at |
| 8 | the end, and `sandbox-node.ts --guide` prints it.* |
| 9 |
| 10 | ## In one paragraph |
| 11 |
| 12 | A widget is **one self-contained HTML document** (or a bare fragment) with |
| 13 | inline CSS and JavaScript, sent by a bot in a message and drawn inside the |
| 14 | chat bubble. It has **no network access of any kind** and cannot navigate; no |
| 15 | library is bundled. It is drawn the same way on iOS, Android, macOS, desktop and |
| 16 | the web because every client removes what is outside the profile before it |
| 17 | reaches the renderer. The bubble is **200–600 px wide** (phones lay it out at |
| 18 | about 320–430) and at most 600 px tall; what does not fit is clipped, and |
| 19 | nothing scrolls inside a widget. A widget is fixed code plus changeable state: |
| 20 | the HTML never changes after sending, its state does, and only the bot writes |
| 21 | it. |
| 22 |
| 23 | ## Size: mini-HTML |
| 24 |
| 25 | - At most **32 768 bytes of HTML** and **4096 bytes compressed**. The server |
| 26 | compresses with zlib at level 9 (PHP `gzcompress($html, 9)`) and refuses |
| 27 | anything larger with `INPUT_MEDIA_WIDGET_TOO_LARGE`. |
| 28 | - Measure as the server does: `python3 -c 'import sys,zlib; print(len(zlib.compress(sys.stdin.buffer.read(), 9)))' < widget.html` |
| 29 | gives the same number (`gzip -9 -n` counts 12 bytes more). The harness |
| 30 | (`sandbox-node.ts widget.html`, the line `size:`) and the dev app's stats |
| 31 | panel count with Node's zlib, a few dozen bytes off the server's either way: |
| 32 | near 4096, trust the Python number. |
| 33 | - What costs bytes: `data:` images barely compress; repeated inline styles and |
| 34 | long class names compress well; SVG paths are cheap until they are long. |
| 35 |
| 36 | ## The bubble |
| 37 |
| 38 | - **Size.** The bot sends `width` and `height` with the widget (`0` = auto, each |
| 39 | axis on its own). Width `0`: the bubble's width; `W`: a fixed width clamped |
| 40 | to [200, the bubble's maximum]. Height `0`: the content height clamped to |
| 41 | [50, 600]; `H`: a fixed height clamp(H, 50, 600) that the content does not |
| 42 | change. Above the height the content is clipped hard: no inner scrolling, no |
| 43 | fullscreen. Lay out with `%`, flex or grid; never with `vh` (out of the |
| 44 | profile). |
| 45 | - **The bubble is the canvas.** The widget view fills the bubble with no |
| 46 | padding of its own, and the bubble clips it at its rounded corners. `html` |
| 47 | has no background: the bubble's colour (`--tg-theme-bg-color`) shows through, |
| 48 | and a background you set on `html` or `body` paints the whole bubble. |
| 49 | - **Defaults** (the renderer's own layer, `docs/sdk-v1.md` §2.4): the text is the |
| 50 | client's message text (`--tg-text-font-size`, `--tg-text-line-height`), in |
| 51 | `--tg-theme-text-color`; `body` has the client's text padding as its margin |
| 52 | (`--tg-text-padding`, about `8px 12px`), so `body { margin: 0 }` goes edge to |
| 53 | edge; headings, paragraphs, lists, tables, `pre`, quotes get native sizes |
| 54 | and margins; a `<button>` you do not style looks like the client's own. Any |
| 55 | CSS of yours wins over these defaults. |
| 56 | - **Theme.** The chat's palette is on the root as `--tg-theme-bg-color`, |
| 57 | `--tg-theme-text-color`, `--tg-theme-hint-color`, `--tg-theme-link-color`, |
| 58 | `--tg-theme-button-color`, `--tg-theme-button-text-color`, |
| 59 | `--tg-theme-secondary-bg-color`, … and `--tg-color-scheme`; in JS |
| 60 | `TelegramWidget.themeParams` and `colorScheme`. `prefers-color-scheme`, |
| 61 | `color-scheme: light dark` and `light-dark()` follow the **chat** theme, live. |
| 62 | - **Text is not selectable** unless you say `user-select: text` (and |
| 63 | `-webkit-user-select: text`) on what a user may want to copy. |
| 64 | - **The time in the corner.** Unless the message has a caption below the widget |
| 65 | (none, or one shown above it), the client draws the message |
| 66 | time over the widget's bottom corner (right, or left in a right-to-left |
| 67 | client), on a backing, as on a photo; taps on it are the client's. Keep |
| 68 | `env(safe-area-inset-bottom)` clear at the bottom (`padding-bottom: |
| 69 | max(12px, env(safe-area-inset-bottom))`; the defaults pad an unstyled body for |
| 70 | it, so when you pad for it yourself set `body { padding: 0 }` too, or you get |
| 71 | two bands). Only the corner of that band is covered, |
| 72 | `--tg-content-safe-area-corner-right` (or `-left`) wide, so content may run |
| 73 | into the band on the other side. With a caption below, all of it is 0. In JS: |
| 74 | `TelegramWidget.contentSafeAreaInset` (`docs/sdk-v1.md` §2.17); examples in |
| 75 | `corpus/safe-area`. |
| 76 |
| 77 | ## Input: who gets a press |
| 78 |
| 79 | Taps (`click`) and pointer events (`pointerdown`/`move`/`up`/`cancel`, |
| 80 | enter/leave/over/out, `setPointerCapture`) reach the widget, with the mouse |
| 81 | compatibility events. **Taps and double taps are always the widget's**, on every |
| 82 | element: a double tap arrives as both clicks and then `dblclick` (the chat's |
| 83 | reaction stays on the bubble outside the widget). **Vertical drags are always |
| 84 | the chat's**: the chat scrolls over every widget, whatever `touch-action` says. |
| 85 | Holds and horizontal drags are claimed **per element with CSS `touch-action`**, |
| 86 | decided when the finger goes down: |
| 87 |
| 88 | | over an element with | hold | horizontal drag | vertical drag | |
| 89 | |---|---|---|---| |
| 90 | | `auto` (the default) | the chat's message menu | swipe-to-reply | the chat scrolls | |
| 91 | | `pan-y` | menu | **the widget's** | the chat scrolls | |
| 92 | | `none` | **the widget's** (+ `contextmenu`) | **the widget's** | the chat scrolls | |
| 93 |
| 94 | `pan-x` claims nothing (it is `auto` here). The first move past 10 px decides |
| 95 | for the whole press, also after a hold: a drag that starts sideways on a |
| 96 | claimed element is the widget's on both axes until the finger lifts; one that |
| 97 | starts up or down is the chat's. When the chat takes a press, the widget gets |
| 98 | `pointercancel` and no `click`. The leading 20 px of the widget never take a claim (the system back |
| 99 | gesture), and the bubble outside the widget stays the chat's. With a mouse, a |
| 100 | right click follows the same claim; clicks, double clicks, holds and drags are |
| 101 | the widget's. Thresholds: a hold is 500 ms within 10 px, a double tap 300 ms and |
| 102 | 40 px apart. |
| 103 |
| 104 | **Rule of thumb: a button you hold, a game control, a canvas → `touch-action: |
| 105 | none` on it; a horizontal slider, carousel or paddle → `pan-y`; everything else |
| 106 | stays `auto`**, so people keep the chat's menu and reply over the rest of the |
| 107 | widget. Nothing vertical can be dragged: no vertical sliders, faders or wheel |
| 108 | pickers, no up/down swipes, no 2D joysticks, drawing or map panning. Lay such |
| 109 | controls out sideways or use taps (buttons for up and down). When the chat takes |
| 110 | a press, undo what `pointerdown` started (put the value back, re-centre the |
| 111 | stick). `touch-action` on a container covers its children, as in CSS. Keep |
| 112 | controls at least 20 px from the widget's leading edge. |
| 113 |
| 114 | Move events may be coalesced per frame: their coordinates are the latest, while |
| 115 | `movementX` and `movementY` sum all moves for that event type and pointer. |
| 116 |
| 117 | No keyboard and no focus at all: no key events, no text input, `focus()` does |
| 118 | nothing. No touch events (use pointer events), no wheel or scroll events. |
| 119 |
| 120 | ## What works |
| 121 |
| 122 | - **Markup:** text, headings, lists, tables, `<details>`/`<summary>`, `<a>`, |
| 123 | `<img>` (`data:` PNG, JPEG, GIF, WebP), `<canvas>`, `<button>`, inline SVG |
| 124 | (shapes, paths, text, `<use>`, gradients). `<form>` renders as a block, its |
| 125 | controls are removed. |
| 126 | - **CSS:** flexbox, grid, tables, positioning (`fixed` is inside the bubble), |
| 127 | box model, borders, radii, shadows, linear, radial and conic gradients, 2D |
| 128 | transforms, `opacity`, `filter` / `backdrop-filter` with `blur()`, |
| 129 | `brightness()`, `drop-shadow()`, transitions and `@keyframes`, custom |
| 130 | properties, `calc()`/`min()`/`max()`/`clamp()`, `:hover` (desktop only), |
| 131 | `:active`, structural pseudo-classes, `::before`/`::after`, |
| 132 | `text-overflow: ellipsis`, `font-variant-numeric`, `touch-action`, |
| 133 | `pointer-events`, `user-select`, `@media` on the width, |
| 134 | `prefers-color-scheme`, `prefers-reduced-motion`, `@supports`. Fonts: |
| 135 | `system-ui`, `sans-serif`, `serif`, `monospace`, `ui-*` only. |
| 136 | - **JavaScript:** ES2023, Promises, timers, `requestAnimationFrame`, the DOM |
| 137 | (`querySelector`, `innerHTML`, `classList`, `style`, observers), layout reads |
| 138 | (`getBoundingClientRect`, `getComputedStyle`, `offsetWidth`, `matchMedia`, |
| 139 | `measureText`), canvas 2D, Web Animations (`element.animate`), `Intl` in the |
| 140 | client's locale (`navigator.language`), `crypto.getRandomValues`, |
| 141 | `TextEncoder`, `URL`, `structuredClone`, `localStorage` / `sessionStorage`. |
| 142 | `new Image()` with a `data:` source loads (`load` / `error`, then |
| 143 | `drawImage`) without being inserted; the `width` / `height` of an inserted |
| 144 | image are its rendered size, a layout read (cache it in a drawing loop). |
| 145 | - **Element ids are not global variables** (a browser's named access): use |
| 146 | `document.getElementById('x')`, not `x`. |
| 147 |
| 148 | ## Out of the profile |
| 149 |
| 150 | Removed by every client before rendering: a declaration, a selector, an |
| 151 | element or an event that is out never reaches the renderer, the rest of the |
| 152 | widget still works. Detect anything newer with `CSS.supports`, `@supports` |
| 153 | or `TelegramWidget.isProfileAtLeast(n)`. `fetch`, `XMLHttpRequest`, |
| 154 | `WebSocket` and the like throw `NetworkDisabledError`; external `<script src>`, |
| 155 | stylesheets, fonts and images are never loaded. The full list, generated |
| 156 | from the profile: |
| 157 |
| 158 | <!-- profile:summary --> |
| 159 | *Generated from `packages/core/profile.json` (profile 1): 279 features, 201 in, 78 out; each one with how it is removed in `docs/profile-v1.md`.* |
| 160 |
| 161 | - **HTML elements and attributes** (20 in, 14 out): ruby, rt, rp, bdi, bdo · Legacy presentational elements: center, font, big, tt, strike, nobr · <img src="data:image/svg+xml"> · <img> with data: AVIF, BMP, ICO · <img src="https://…"> (any non-data: URL) · Form controls: form, input, select, option, optgroup, textarea, label, fieldset, legend, datalist, output · progress, meter · dialog, popover attribute · audio, video, source, track · script, iframe, frame, object, embed, link, meta, base, portal, template, slot, math, fencedframe, … · align, valign, bgcolor, border, cellpadding, cellspacing, color, face, nowrap · contenteditable, spellcheck, inputmode, enterkeyhint, autocapitalize · draggable · tabindex, autofocus, accesskey |
| 162 | - **Inline SVG** (5 in, 5 out): clipPath, mask, pattern, marker · SVG filter primitives · SMIL animation: animate, animateTransform, animateMotion · foreignObject · <image href="data:…"> inside SVG |
| 163 | - **CSS** (55 in, 21 out): display: flow-root, contents, list-item · Logical properties: margin-inline, padding-block, inset-inline, inline-size, … · Multi-column layout · position: sticky · overflow: auto / scroll · Colour functions: hwb(), lab(), lch(), oklab(), oklch(), color() · color-mix() · background-clip: text · url() / image-set() with anything but a data: image or #fragment · font-family naming a font · @font-face · -webkit-line-clamp / line-clamp · text-shadow · writing-mode, text-orientation · 3D transforms: rotateX/Y/3d, translateZ/3d, scaleZ/3d, matrix3d, perspective, transform-style, backface-visibility · filter: grayscale(), sepia(), saturate(), contrast(), hue-rotate(), invert(), opacity() · filter: url(#svg-filter) · mix-blend-mode, isolation, background-blend-mode · clip-path: inset(), circle(), ellipse(), polygon() · mask / -webkit-mask with gradients or data: images · vh / dvh / svh / vb: height-relative units |
| 164 | - **Selectors** (7 in, 6 out): :has() · ::first-letter, ::first-line, ::marker · :focus, :focus-visible, :focus-within · :checked, :disabled, :enabled, :valid, :invalid, :placeholder-shown, ::placeholder · :host, :host-context(), ::slotted(), ::part(), :scope · :target |
| 165 | - **At-rules** (5 in, 8 out): @media (hover: hover), (pointer: fine/coarse) · @media print, resolution, other media features · @import, @namespace · @container queries · @layer cascade layers · @property · @counter-style, @starting-style, @scope, @page, @font-feature-values, @font-palette-values, @position-try · CSS nesting |
| 166 | - **Animation** (7 in, 1 out): Magic move |
| 167 | - **Canvas 2D** (13 in, 8 out): createConicGradient · createPattern from a canvas or image · globalCompositeOperation · shadowBlur, shadowColor, shadowOffsetX/Y · ctx.filter · getImageData / putImageData / createImageData · toDataURL, toBlob, captureStream · WebGL, OffscreenCanvas, bitmaprenderer contexts |
| 168 | - **JavaScript runtime** (25 in, 9 out): element.focus() / blur() / select(), document.activeElement: the widget takes keyboard focus · Bundled libraries by CDN name: Chart.js 4, D3 7 · fetch, XMLHttpRequest, WebSocket, EventSource, RTCPeerConnection, sendBeacon, importScripts, Worker, BroadcastChannel · location assignment, history, window.open, form submission · alert, confirm, prompt, print · clipboard, share, vibrate, geolocation, mediaDevices, Notification · attachShadow, customElements.define · Blob, FileReader, URL.createObjectURL · requestFullscreen |
| 169 | - **TelegramWidget (SDK v1)** (17 in, 1 out): TelegramWidget.sendMessage |
| 170 | - **Input** (9 in, 5 out): touchstart / touchmove / touchend · Key events: keydown / keyup / keypress, beforeinput / input from keys, focus / blur / focusin / focusout from keys · Enter / Space activate a focused button or link · A key press counts as a user gesture for privileged bridge calls · wheel and scroll events |
| 171 | - **Limits** (21 in, 0 out) |
| 172 | - **Client behaviour** (17 in, 0 out) |
| 173 | <!-- /profile:summary --> |
| 174 |
| 175 | ## `TelegramWidget` in brief |
| 176 |
| 177 | ```js |
| 178 | TelegramWidget.profile; // 1; isProfileAtLeast(n) |
| 179 | TelegramWidget.colorScheme; // 'light' | 'dark', the chat's |
| 180 | TelegramWidget.themeParams.bg_color; // the palette, '#rrggbb' (Mini Apps keys) |
| 181 | TelegramWidget.onEvent('themeChanged', fn); // also 'activated' / 'deactivated'; isActive |
| 182 | TelegramWidget.openLink('https://…'); // in a tap handler: the user confirms the full URL |
| 183 | TelegramWidget.openTelegramLink('https://t.me/…'); // in a tap handler: opens inside Telegram, no confirmation |
| 184 | TelegramWidget.HapticFeedback.impactOccurred('light'); // notificationOccurred, selectionChanged |
| 185 | TelegramWidget.ready(); // optional: first state drawn |
| 186 | TelegramWidget.setResizeAnchor('bottom'); // v0.1.3: grow upward ('top', the default: downward) |
| 187 | TelegramWidget.contentSafeAreaInset; // { bottom, cornerLeft, cornerRight, … } px: the client's time over the corner; 'contentSafeAreaChanged' |
| 188 | TelegramWidget.chatData; // the chat state (this message, this chat), or null; publicData: the shared state |
| 189 | TelegramWidget.onEvent('chatDataChanged', fn); // and 'publicDataChanged': the bot changed the state: redraw from it |
| 190 | TelegramWidget.request('vote:2').then((a) => a.result, (e) => e.code); // ask the bot, in a tap handler |
| 191 | TelegramWidget.copyText('PROMO-2026'); // in a tap handler; the client shows what it copied |
| 192 | TelegramWidget.request('pay:1', { wallet: true }); // in a tap handler: the bot gets the user's wallet with it |
| 193 | TelegramWidget.wallet.sendTransaction(tx, 'paid:1'); // Gram Wallet: TON Connect's transaction; wallet.signData(payload, data); null where unavailable |
| 194 | TelegramWidget.isForward; TelegramWidget.viewer; TelegramWidget.chatType; // a forward? who looks ({ id, first_name, username, … }, only if you may ask the bot), where |
| 195 | ``` |
| 196 |
| 197 | - **Links:** `https:` only, at most 256 characters, one call per tap, only in |
| 198 | the handler of a real tap (not from a timer or a promise; nor from a finger's |
| 199 | `pointerdown`, which may still become the chat's scroll: use `click` or |
| 200 | `pointerup`); a bad URL throws `TypeError`. A tapped `<a href="https://…">` |
| 201 | does the same. `openLink` shows the user the full URL to confirm; |
| 202 | `openTelegramLink` opens the `t.me` link inside Telegram without a |
| 203 | confirmation, as a link in a message does. The widget is not told whether the |
| 204 | user opened it. |
| 205 | - **Storage:** `localStorage` is kept for this message on this device, there |
| 206 | from the first line of script, 4 KB per area (`QuotaExceededError` past |
| 207 | it: catch it); `sessionStorage` until the app restarts. A forwarded copy |
| 208 | starts empty. Your HTML never changes after the bot sends it: the bot changes |
| 209 | only the widget's state (below). |
| 210 | - **Haptics:** only while visible, 5 in a burst then 10 per second, freely |
| 211 | during a touch and 5 s after it; without a touch one 1 s series, the next one |
| 212 | after a touch or 10 s later (a timer cannot buzz the phone); desktop and web |
| 213 | play nothing. |
| 214 | - **The widget's state**: only the bot writes it; you read it and cannot |
| 215 | change it, only ask the bot (`request`, below). `chatData` is the **chat |
| 216 | state**: this message in its chat (in a group every member sees the same; a |
| 217 | forward never gets it), for a game in progress or whose turn it is. |
| 218 | `publicData` is the **shared state**: wherever the widget is shown (a forward |
| 219 | gets it as it was then, or, in a shared widget, the one state the bot keeps |
| 220 | changing for all of them), for poll results or a price. Each is a text of up |
| 221 | to 1024 bytes (UTF-8), `null` when there is none. Keep what everyone sees there |
| 222 | (votes, a board, a score) and draw it per `viewer.id`; when the bot changes it |
| 223 | you get `chatDataChanged` / `publicDataChanged`: redraw, nothing restarts. |
| 224 | - **Live shared state**: call `TelegramWidget.watchPublicData()` if the bot |
| 225 | sent the widget as a shared one (`is_shared`) and keeps changing its shared |
| 226 | state (a ticker, a poll others vote in): only then does the client poll it |
| 227 | while the widget is on screen, at the server's period (5–3600 s, 30 s by |
| 228 | default). Without it you get the shared state with the message and the bot's |
| 229 | edits of this message only. |
| 230 | - **Keep the newest state.** A poll can bring the shared state back older than |
| 231 | what you already drew from a `result` or an earlier poll, and the counts would |
| 232 | jump back and forth. Have the bot put a revision in the shared state (`"r": |
| 233 | 41`, raised on every edit, and in `result` too) and ignore anything older than |
| 234 | the newest you have seen. |
| 235 | - **A forward of a widget that is not shared never changes**: it keeps the |
| 236 | shared state as it was when forwarded. Draw it as a snapshot ("Cooking, as of |
| 237 | 19:40"), not as live progress the reader would wait on. |
| 238 | - **Requests**: `request(data)` is a callback button inside the widget: `data` |
| 239 | 1–64 bytes; the promise resolves with `{ result }` (the bot's answer for you, |
| 240 | up to 1024 bytes, or `null`) or rejects with `error.code`: `NOT_ALLOWED` (no |
| 241 | tap, a widget the bot did not allow to ask (`allow_queries`), a forward that may not ask), `BUSY` (one at a time), `RATE_LIMITED`, |
| 242 | `TIMEOUT` (the bot did not answer), `FAILED`, `INVALID_ANSWER`. Call it in a |
| 243 | tap handler (one call per tap, shared with links and `copyText`). The answer |
| 244 | does not change the state: the bot's edits arrive as the events; if you need |
| 245 | the new state at once, have the bot put it in `result`. In the private chat |
| 246 | with the bot it may also run without a tap: once when the widget appears on |
| 247 | screen, then once per 5 s while it is visible (poll a score); one asked while |
| 248 | the widget is off screen (at start, before the client shows the bubble) waits |
| 249 | and goes out when it appears, so ask for fresh state in the script's first |
| 250 | lines. Elsewhere (groups, via the bot, forwards) only on a tap. Show |
| 251 | "sending…" and handle every code. |
| 252 | - **A forward** (`isForward`) has no chat state (`chatData` is `null`) and no |
| 253 | `chatType` (a copy is told nothing about its chat). It can ask on a tap only |
| 254 | if the bot let forwards ask (a shared widget sent with `allow_queries`); |
| 255 | otherwise it has no `viewer` either and every |
| 256 | request is `NOT_ALLOWED`: show the shared state and point to the bot |
| 257 | (`openTelegramLink('https://t.me/<bot>?start=…')`). |
| 258 | - **copyText**: `copyText(text)`, 1–256 characters, in a tap handler; the |
| 259 | client copies and shows the text it copied. |
| 260 | - **The wallet** (Gram Wallet, TON Connect's formats): `TelegramWidget.wallet` |
| 261 | is `null` where the client has no wallet for this user, where the widget may |
| 262 | not ask the bot, and in a preview: check it before drawing a pay button. To |
| 263 | pay: on a tap, `request('pay:1', { wallet: true })` (the bot gets the user's |
| 264 | wallet address with it, a wallet is created if they had none), the bot |
| 265 | answers with a fresh transaction (TON Connect's `{ valid_until, messages: |
| 266 | [{ address, amount, payload?, stateInit? }] }`, 1–255 messages, a |
| 267 | user-friendly `address`, `amount` in nanotons as a string), and you pass it |
| 268 | on in the answer's handler: |
| 269 | `wallet.sendTransaction(tx, 'paid:1')` needs no new tap within 10 s of the |
| 270 | answer. The client's own window shows the bot and the amounts; the user |
| 271 | confirms; the bot gets the outcome and checks the chain; the promise resolves |
| 272 | with the bot's answer `{ result }`. `wallet.signData({ type: 'text', text }, |
| 273 | 'terms')` asks for a signature the same way (or `{ type: 'binary', bytes }`, |
| 274 | `{ type: 'cell', schema, cell }` in base64): it goes to the bot. One wallet |
| 275 | call per tap or per answer, one call in flight with requests, never from a |
| 276 | timer. Extra codes: `REJECTED` (the user declined), `BAD_REQUEST` (the wallet |
| 277 | refused it); a malformed transaction or payload throws `TypeError`. After |
| 278 | `TIMEOUT` the payment may have gone out: ask the bot about the order, do not |
| 279 | pay again. |
| 280 | - **A preview** (`isPreview`): sent via the bot's inline mode, the widget is |
| 281 | first shown in the list of results. There it has its state but gets no taps, |
| 282 | cannot ask, link or copy, knows no viewer and keeps nothing in Web Storage: |
| 283 | draw the state the user is about to send. |
| 284 | - **Resize anchor** (v0.1.3): when your height changes, the client keeps one |
| 285 | edge of the bubble still on screen. `'top'` (the default) grows and shrinks |
| 286 | downward: answers that expand, "show more", a summary that opens. |
| 287 | `'bottom'` keeps the bottom still and grows upward: a chat log or thread where |
| 288 | new lines appear at the bottom and older ones move up. Call it before the |
| 289 | change, at the start of the script if the widget always grows one way; it |
| 290 | applies until you call it again. Only `'top'` and `'bottom'` (anything else |
| 291 | throws `TypeError`); older clients lack it: |
| 292 | `if (typeof TelegramWidget.setResizeAnchor === 'function') …`. |
| 293 | - **Gone:** `sendMessage` (nothing is sent to the chat; ask the bot with |
| 294 | `request`), `alert` / `confirm` / `prompt` (no dialog), `navigator.clipboard` |
| 295 | (use `copyText`), share, fullscreen. |
| 296 | - Outside Telegram (a plain browser) `window.TelegramWidget` is undefined: |
| 297 | check for it. |
| 298 |
| 299 | ## Lifecycle and limits |
| 300 |
| 301 | - Off screen: `document.hidden`, no animation frames, timers at most once per |
| 302 | second. The widget can be destroyed and recreated at any time; only Web |
| 303 | Storage and the widget's state survive: keep the user's own choices in |
| 304 | `localStorage`; what the whole chat sees (a board, the votes) belongs in the |
| 305 | chat state, which the bot writes. |
| 306 | - CPU: a budget of 300 ms per second (timers and frames wait beyond it). One |
| 307 | task may run up to 500 ms, the first run included; one that runs longer stops |
| 308 | the widget. A task that runs past the second's 300 ms finishes, and what it |
| 309 | spent past it makes the next timers and frames wait longer. One task may make |
| 310 | 128 layout reads (and their time is at most 1000 ms), and what the widget costs the client's main |
| 311 | thread (its layout reads plus about 25 µs per DOM change it sends) is capped |
| 312 | at 100 ms per second: past it timers and frames wait. 8 MB of memory; 64 live |
| 313 | timers (`RangeError` past it); |
| 314 | 2000 nodes (elements, text, comments); one text value 32 K characters, the document's text 48 K, an |
| 315 | attribute 8 K; 10 000 element method calls (`scrollTo`, …) in one task; 400 CSS rules and 32 |
| 316 | `@keyframes`; 4000 canvas commands per canvas in one task (the next throws |
| 317 | `RangeError`); 64 running script animations; 2048 × 2048 pixels for all of |
| 318 | a widget's canvases together (a canvas is 300 × 150 until you size it). Past a |
| 319 | count or size limit the widget stops, as past the CPU or memory limit: a |
| 320 | widget over a limit or crashed keeps its last frame with a "Widget stopped" |
| 321 | badge. |
| 322 | - A `data:` image: PNG, JPEG, GIF or WebP of at most 1024 × 1024 pixels (larger: |
| 323 | the placeholder); other bytes behind an image type are a broken image. |
| 324 | - Paint: at most 16 elements at once with a blurred shadow, a `filter`, a |
| 325 | `backdrop-filter` or transparency (`opacity` below 1), animated ones included |
| 326 | (a `::before` / `::after` counts as an element of its own), and of them at most |
| 327 | 2 with `backdrop-filter`; past it the widget stops (`Paint limit exceeded`). |
| 328 | Mute text and small details with colour (`--tg-theme-hint-color`, `rgba()`, |
| 329 | `fill-opacity` / `stroke-opacity` in SVG), not `opacity`: it looks the same and |
| 330 | costs nothing. A shadow without blur (a ring, an inset border), an element |
| 331 | under `display: none` and the dimming of a disabled or pressed `<button>` |
| 332 | (its `opacity`) do not count. |
| 333 | - Keep the first render synchronous and fast; animate with |
| 334 | `requestAnimationFrame`, never read layout in every frame. |
| 335 |
| 336 | ## The bot's side (Bot API 10.4) |
| 337 |
| 338 | The names a bot uses; the whole mapping and what the beta does are in |
| 339 | `docs/tgw-format.md`, "The Bot API (10.4)". |
| 340 |
| 341 | - **Send:** `sendWidget` with `html`, `width`, `height` (`0` or none = auto), |
| 342 | `chat_data`, `public_data`, `caption`, `allow_queries` (taps may ask, and in |
| 343 | the private chat with the bot the widget may ask in the background), |
| 344 | `is_shared` (one shared state for every copy; the sent `Widget` has an `id`; |
| 345 | with `allow_queries` forwards may ask too) and `reply_markup` (an inline |
| 346 | keyboard under the widget). `sendSharedWidget(widget_id, chat_data)` posts the |
| 347 | same shared widget again. In inline mode: an article with |
| 348 | `InputWidgetMessageContent` (the same fields) or |
| 349 | `InputSharedWidgetMessageContent` (`widget_id`). `copyMessage` of a widget is |
| 350 | refused; a forward is the way to pass it on. |
| 351 | - **Answer:** a request from an original arrives as the update `widget_query` |
| 352 | (`from`, `chat` and `message_id` or `inline_message_id`, `data`, and |
| 353 | `widget_id` for a shared widget); one from a copy of a shared widget as |
| 354 | `shared_widget_query` (`from`, `data`, `widget_id`). Answer every one with |
| 355 | `answerWidgetQuery(widget_query_id, data)` (`data` = `result`, at most 1024 |
| 356 | bytes), also when something failed: an unanswered request ends in the widget |
| 357 | as `TIMEOUT`. |
| 358 | - **Change the state:** `editMessageWidgetData` (`chat_id` and `message_id`, or |
| 359 | `inline_message_id`; `chat_data`, `public_data`) for this message; |
| 360 | `editSharedWidgetData(widget_id, public_data, cache_time)` for a shared |
| 361 | widget's state everywhere (`cache_time`: the clients' poll period, 5–3600 s). |
| 362 | An edit that changes nothing fails with `message is not modified`: take it as |
| 363 | done. Put the user's move into your own state only once the edit went |
| 364 | through, so a failed edit does not take a turn away. |
| 365 | - **Examples:** `corpus/bot-demos` (an order, a shared poll, who's in, a duel, |
| 366 | a live quote, a shared leaderboard; the protocol of each in its README) and |
| 367 | the bot that sends them, `scripts/bot-demos.ts`. |
| 368 |
| 369 | ## How to test |
| 370 |
| 371 | - **The harness** (no browser window, prints text for people and agents): |
| 372 | `corepack pnpm tsx packages/core/scripts/sandbox-node.ts widget.html` runs the |
| 373 | widget in the real sandbox and prints the size, what the profile removed |
| 374 | (`diag` lines), errors and the actions it asked for. Add `--width 360` to lay |
| 375 | it out in the real renderer at that bubble width (the content height), and |
| 376 | presses to check gestures: `--tap x,y`, `--hold x,y[,ms]`, |
| 377 | `--double-tap x,y`, `--swipe x,y,dx,dy`, `--right-click x,y` (`--desktop` |
| 378 | for a mouse client). Each press reports the element, its claim, who got it, |
| 379 | what the widget received and a hint, for example |
| 380 | `hint: the hold went to the message menu and the widget got pointercancel: set touch-action: none on button#fire …` |
| 381 | or `hint: vertical drags always scroll the chat; a widget cannot claim them …`. |
| 382 | `--json` gives the whole result. The bot: `--message private|group|via-bot|no-queries|live-copy|copy|preview` |
| 383 | sets where the widget is (what it may ask), `--viewer id,first,last,username,premium`, `--chat-data`, |
| 384 | `--public-data` the rest, `--answer '{"result":"ok"}'` (or `--answer-error |
| 385 | TIMEOUT`) answers every request, `--set-data '{…}'` is the bot's edit of the state, `--offscreen` |
| 386 | starts the widget off screen and then shows it, as Telegram's clients do; a `request` |
| 387 | line per request says whether it went out and what came back. With `--width` a |
| 388 | `paint:` line counts the elements with a blurred shadow, a filter or transparency |
| 389 | (16 at most; a warning past 12). |
| 390 | - **The dev app** (`corepack pnpm dev`): drop the file, pick a width (200–600 or |
| 391 | free), toggle dark, and use the mouse as a finger (`gestures: phone`, the |
| 392 | default): the bubble takes holds and swipes as a phone does and says so over |
| 393 | the bubble. The **Bot (mock)** panel plays the bot: where the message is (the |
| 394 | private chat, a group, via the bot, sent without requests, a live or plain |
| 395 | forward, a preview), the chat type, the viewer, the chat state, the shared |
| 396 | state and the bot's edit of them, how it answers (a built-in bot, manual, or a |
| 397 | failure); `corpus/interactive` has a poll, tic-tac-toe, a live ticker and a |
| 398 | promo code that use it, and `corpus/bot-demos` the six demos of the real bot. |
| 399 | - **On clients:** send it with your bot (`sendWidget`, above) to your private |
| 400 | chat, a group and through inline mode, and forward it: each place gives the |
| 401 | widget different rights. `scripts/bot-demos.ts` is a bot to start from. |
| 402 |
| 403 | ## Agent block |
| 404 |
| 405 | For a model's system prompt (also `sandbox-node.ts --guide`). It stands alone: a |
| 406 | model that sees only this block, a bot's model or a cloud agent without this |
| 407 | repository, has everything it needs to write a correct widget; the links are for |
| 408 | depth. `{docs}` stands for the authors' documentation site, not published yet. |
| 409 | The out list between the `profile:agent` markers is generated from |
| 410 | `packages/core/profile.json` by `profile-build.ts` (`--guide` drops the marker lines). |
| 411 |
| 412 | <!-- agent-block --> |
| 413 | ```text |
| 414 | You write Telegram widgets. A widget is one self-contained HTML document (or a |
| 415 | fragment) with inline <style> and <script>, sent by a bot in a message and drawn |
| 416 | inside the chat bubble on every Telegram client (iOS, Android, desktop, web). |
| 417 | Every client silently removes what is outside the widget profile below and runs |
| 418 | the rest: an out feature is a bug you will not see. Docs: {docs}/guide, |
| 419 | {docs}/sdk (the API), {docs}/profile (every feature). |
| 420 |
| 421 | SIZE |
| 422 | - At most 32768 bytes of HTML and 4096 bytes after zlib level 9; the server |
| 423 | refuses anything bigger. Python's zlib.compress(html, 9) counts as the server |
| 424 | does; if you cannot measure, aim for 3800. Repeated CSS and markup compress |
| 425 | well; data: images and long unique text do not. No comments, no dead code. |
| 426 |
| 427 | THE BUBBLE |
| 428 | - 200-600 px wide (phones about 320-430: design for 320), as tall as the |
| 429 | content, at most 600 px; the rest is clipped. Nothing scrolls inside a |
| 430 | widget: overflow auto/scroll becomes hidden, position: sticky becomes |
| 431 | relative. Fit long content into 600 px with pages, tabs or "show more". |
| 432 | - Lay out with %, flex, grid, vw/vmin; never vh (removed). |
| 433 | - html has no background: the bubble's colour shows through, and a background |
| 434 | on html or body paints the whole bubble. body has the client's text padding |
| 435 | as its margin (about 8px 12px); body{margin:0} goes edge to edge. |
| 436 | - Defaults: the client's message text (system-ui, --tg-text-font-size about |
| 437 | 15px, --tg-text-line-height) in --tg-theme-text-color; headings, lists, |
| 438 | tables, pre get native margins; an unstyled <button> looks like the client's |
| 439 | own button. Any CSS of yours wins. |
| 440 | - Theme: CSS variables on the root, each '#rrggbb': --tg-theme-bg-color, |
| 441 | --tg-theme-text-color, --tg-theme-hint-color, --tg-theme-link-color, |
| 442 | --tg-theme-button-color, --tg-theme-button-text-color, |
| 443 | --tg-theme-secondary-bg-color, --tg-theme-accent-text-color, |
| 444 | --tg-theme-subtitle-text-color, --tg-theme-destructive-text-color, |
| 445 | --tg-theme-section-bg-color, --tg-theme-section-header-text-color, |
| 446 | --tg-theme-section-separator-color; --tg-color-scheme is light or dark. |
| 447 | prefers-color-scheme, color-scheme and light-dark() follow the chat's theme, |
| 448 | live. Build colours on these so both themes work. |
| 449 | - Fonts: system-ui, sans-serif, serif, monospace, ui-sans-serif, ui-serif, |
| 450 | ui-monospace, ui-rounded only; font names and @font-face are removed. |
| 451 | - Text is not selectable unless you set user-select:text and |
| 452 | -webkit-user-select:text on what a user may want to copy. |
| 453 | - Unless a caption is below, the client draws the message time in the bottom corner: |
| 454 | keep env(safe-area-inset-bottom) clear at the bottom (the defaults pad an |
| 455 | unstyled body; if you pad for it, set body{padding:0}); only |
| 456 | --tg-content-safe-area-corner-left|right of it is |
| 457 | covered, so content may enter the band on the other side. |
| 458 | More: {docs}/guide#the-bubble |
| 459 |
| 460 | WHAT WORKS |
| 461 | - HTML: div, span, p, h1-h6, ul/ol/li, dl, table, details/summary (toggle |
| 462 | event), figure, header/section/nav/article, b/i/em/strong/small/code/pre/ |
| 463 | mark/time/abbr, a, img (data: PNG, JPEG, GIF, WebP only), canvas, button. |
| 464 | - Inline SVG: svg, g, path, rect, circle, ellipse, line, polyline, polygon, |
| 465 | text, tspan, defs, symbol, use, linearGradient, radialGradient, stop. |
| 466 | - CSS: flex, grid, positioning (fixed = inside the bubble), box model, |
| 467 | borders, border-radius, box-shadow, opacity, linear/radial/conic gradients |
| 468 | (and repeating), 2D transforms, filter and backdrop-filter with blur(), |
| 469 | brightness() and drop-shadow() only, transitions, @keyframes, custom |
| 470 | properties, calc/min/max/clamp, rgb()/hsl()/hex/light-dark() colours, |
| 471 | ::before/::after, :hover (mouse only), :active, :not/:is/:where, structural |
| 472 | pseudo-classes, [disabled] and :disabled on buttons, @media on width, |
| 473 | aspect-ratio, orientation, prefers-color-scheme, prefers-reduced-motion, |
| 474 | @supports, one-line text-overflow: ellipsis, touch-action, pointer-events. |
| 475 | - JS: ES2023 in an interpreter (no JIT: keep per-frame work small), Promises, |
| 476 | async/await, setTimeout/setInterval, requestAnimationFrame, the DOM |
| 477 | (createElement, querySelector, innerHTML, textContent, classList, style, |
| 478 | dataset, addEventListener), MutationObserver, ResizeObserver, layout reads |
| 479 | (getBoundingClientRect, getComputedStyle, offsetWidth, clientWidth, an |
| 480 | inserted img's width: each is a round trip to the renderer, so cache them |
| 481 | and never read them every frame), matchMedia, canvas 2D (paths, rect, |
| 482 | roundRect, arc, fillText, measureText, gradients, setTransform, clip, |
| 483 | drawImage of a data: image; scale by devicePixelRatio for sharp lines), |
| 484 | new Image() with a data: src (load/error, then drawImage), Web Animations |
| 485 | (el.animate), Intl and toLocale*String in the user's locale |
| 486 | (navigator.language), crypto.getRandomValues, TextEncoder, URL, |
| 487 | structuredClone, localStorage, sessionStorage, CSS.supports. |
| 488 | - Element ids are not global variables: use document.getElementById('x'). |
| 489 |
| 490 | OUT OF THE PROFILE (removed by every client; the rest of the widget still runs) |
| 491 | <!-- profile:agent --> |
| 492 | - HTML: ruby, rt, rp, bdi, bdo; Legacy presentational elements: center, font, big, tt, strike, nobr; <img src="data:image/svg+xml">; <img> with data: AVIF, BMP, ICO; <img src="https://…"> (any non-data: URL); Form controls: form, input (all types), select, option, optgroup, textarea, label, fieldset, legend, datalist, output; progress, meter (native gauges); dialog (show/showModal), popover attribute; audio, video, source, track; script (as DOM), iframe, frame, object, embed, link, meta, base, portal, template, slot, math, fencedframe, …; align, valign, bgcolor, border, cellpadding, cellspacing, color, face, nowrap; contenteditable, spellcheck, inputmode, enterkeyhint, autocapitalize; draggable (HTML drag and drop); tabindex, autofocus, accesskey (keyboard focus and shortcuts). |
| 493 | - SVG: clipPath, mask, pattern, marker; SVG filter primitives (fe*); SMIL animation: animate, animateTransform, animateMotion; foreignObject (HTML inside SVG); <image href="data:…"> inside SVG. |
| 494 | - CSS: display: flow-root, contents, list-item; Logical properties: margin-inline, padding-block, inset-inline, inline-size, …; Multi-column layout (columns, column-count, column-gap); position: sticky; overflow: auto / scroll (scrolling inside the widget); Colour functions: hwb(), lab(), lch(), oklab(), oklch(), color(); color-mix(); background-clip: text (gradient text); url() / image-set() with anything but a data: image or #fragment; font-family naming a font ("Helvetica", "Courier New", "Comic Sans MS", …); @font-face (web fonts); -webkit-line-clamp / line-clamp (multi-line ellipsis); text-shadow; writing-mode, text-orientation (vertical text); 3D transforms: rotateX/Y/3d, translateZ/3d, scaleZ/3d, matrix3d, perspective, transform-style, backface-visibility; filter: grayscale(), sepia(), saturate(), contrast(), hue-rotate(), invert(), opacity(); filter: url(#svg-filter); mix-blend-mode, isolation, background-blend-mode; clip-path: inset(), circle(), ellipse(), polygon(); mask / -webkit-mask with gradients or data: images; vh / dvh / svh / vb: height-relative units. |
| 495 | - Selectors: :has(); ::first-letter, ::first-line, ::marker; :focus, :focus-visible, :focus-within; :checked, :disabled, :enabled, :valid, :invalid, :placeholder-shown, ::placeholder; :host, :host-context(), ::slotted(), ::part(), :scope; :target. |
| 496 | - At-rules: @media (hover: hover), (pointer: fine|coarse); @media print, resolution, other media features; @import, @namespace; @container queries (container-type in the widget); @layer cascade layers; @property (typed custom properties); @counter-style, @starting-style, @scope, @page, @font-feature-values, @font-palette-values, @position-try; CSS nesting (.a { .b { } }, &). |
| 497 | - Animation: Magic move (shared-element morph between renders). |
| 498 | - Canvas: createConicGradient; createPattern from a canvas or image; globalCompositeOperation (source-over, destination-out, multiply, …); shadowBlur, shadowColor, shadowOffsetX/Y; ctx.filter (CSS filter on canvas drawing); getImageData / putImageData / createImageData (pixel read-back); toDataURL, toBlob, captureStream; WebGL, OffscreenCanvas, bitmaprenderer contexts. |
| 499 | - JS: element.focus() / blur() / select(), document.activeElement: the widget takes keyboard focus; Bundled libraries by CDN name: Chart.js 4, D3 7 (nothing is fetched); fetch, XMLHttpRequest, WebSocket, EventSource, RTCPeerConnection, sendBeacon, importScripts, Worker, BroadcastChannel; location assignment, history, window.open (→ openLink), form submission; alert, confirm, prompt, print; clipboard, share, vibrate, geolocation, mediaDevices, Notification; attachShadow, customElements.define; Blob, FileReader, URL.createObjectURL; requestFullscreen. |
| 500 | - TelegramWidget: TelegramWidget.sendMessage. |
| 501 | - Input: touchstart / touchmove / touchend (touch clients only); Key events: keydown / keyup / keypress, beforeinput / input from keys, focus / blur / focusin / focusout from keys; Enter / Space activate a focused button or link (a click from the keyboard); A key press counts as a user gesture for privileged bridge calls; wheel and scroll events. |
| 502 | <!-- /profile:agent --> |
| 503 | More: {docs}/profile |
| 504 |
| 505 | INPUT |
| 506 | - Taps (click) and pointer events (pointerdown/move/up/cancel, enter/leave, |
| 507 | setPointerCapture), with the mouse events (a coalesced move sums |
| 508 | movementX/Y). No touch events (use pointer events), no keyboard, no focus, no |
| 509 | text input, no wheel or scroll events. |
| 510 | - A double tap is always the widget's: two clicks, then dblclick. |
| 511 | - Vertical drags always scroll the chat: nothing can be dragged up or down (no |
| 512 | vertical sliders, wheel pickers, joysticks, drawing or map panning); use |
| 513 | horizontal controls or buttons. |
| 514 | - Holds and horizontal drags are claimed per element with CSS touch-action, |
| 515 | which covers the element's children: auto (the default): a hold opens the |
| 516 | chat's message menu, a sideways swipe is the chat's reply, and the widget |
| 517 | gets pointercancel and no click. pan-y: the widget gets horizontal drags |
| 518 | (sliders, carousels, paddles). none: horizontal drags and holds, plus |
| 519 | contextmenu (held game buttons). pan-x claims nothing. Keep auto everywhere |
| 520 | else. On pointercancel undo what pointerdown started. |
| 521 | - The leading 20 px never take a claim (the system back gesture): keep |
| 522 | controls 20 px from the left edge (the right in RTL). |
| 523 | - A hold is 500 ms within 10 px; a double tap is two taps within 300 ms and |
| 524 | 40 px. |
| 525 | More: {docs}/guide#input |
| 526 |
| 527 | TELEGRAMWIDGET (window.TelegramWidget; undefined outside Telegram: check it) |
| 528 | - profile (1), isProfileAtLeast(n). colorScheme: 'light' | 'dark'. |
| 529 | themeParams: { bg_color, text_color, hint_color, ... } ('#rrggbb', the keys of |
| 530 | the CSS variables with _ for -). |
| 531 | - onEvent(type, fn) / offEvent(type, fn), type: 'themeChanged', 'activated' / |
| 532 | 'deactivated' (on and off screen; isActive), 'chatDataChanged', |
| 533 | 'publicDataChanged'. |
| 534 | - ready(): optional, once the first state is drawn. |
| 535 | - openLink(url): https only, at most 256 characters; the client shows the full |
| 536 | URL and the user confirms. openTelegramLink(url): https://t.me/..., opens |
| 537 | inside Telegram without a confirmation, as a t.me link in a message. A tapped |
| 538 | <a href="https://..."> does the same. A bad URL throws TypeError. |
| 539 | - copyText(text): 1-256 characters; the client copies it and shows a toast. |
| 540 | - openLink, openTelegramLink, copyText and request need a real tap: call them |
| 541 | synchronously in a click (or pointerup) handler, not after await, a timer or |
| 542 | a promise, nor a finger's pointerdown (it may still become the chat's |
| 543 | scroll); one of them per tap. Otherwise they are refused. |
| 544 | - HapticFeedback.impactOccurred('light'|'medium'|'heavy'|'rigid'|'soft'), |
| 545 | .notificationOccurred('error'|'success'|'warning'), .selectionChanged(): |
| 546 | only on screen, free during a touch and 5 s after it; without a touch one |
| 547 | short series, then nothing for 10 s (a timer cannot buzz the phone). |
| 548 | - setResizeAnchor('top' | 'bottom'): the edge of the bubble that stays still |
| 549 | when your height changes ('top' by default; 'bottom' for a log or thread |
| 550 | that grows at the bottom). Older clients lack it: |
| 551 | TelegramWidget.setResizeAnchor?.('bottom'). |
| 552 | - No sendMessage, alert/confirm/prompt, navigator.clipboard (use copyText), |
| 553 | window.open (use openLink), share or fullscreen. |
| 554 | More: {docs}/sdk |
| 555 |
| 556 | THE WIDGET'S STATE AND REQUESTS (only the bot writes the state) |
| 557 | - The HTML never changes after sending; the bot changes only the state. |
| 558 | chatData and publicData are strings of up to 1024 bytes, or null: |
| 559 | JSON.parse them yourself (in try/catch) and draw from them. |
| 560 | chatData is the chat state: this message in its chat, the same for every |
| 561 | member of a group (a board, whose turn). publicData is the shared state, |
| 562 | the same wherever the widget is shown, forwards included (poll results). |
| 563 | A change of either fires chatDataChanged / publicDataChanged: redraw from |
| 564 | it; nothing restarts. |
| 565 | - watchPublicData(): the client polls the shared state live while the widget |
| 566 | is on screen (a ticker, a poll others vote in); unwatchPublicData() stops. |
| 567 | A poll may bring a state older than a result gave you: keep a revision in |
| 568 | the state (the bot raises it per edit and returns it in result) and ignore |
| 569 | older ones. |
| 570 | - request(data): ask the bot, like a callback button; data is 1-64 bytes. |
| 571 | Resolves with { result }: the bot's text for this user (up to 1024 bytes) or |
| 572 | null. Rejects with an error whose code is 'NOT_ALLOWED' (no tap, requests not |
| 573 | allowed here, a forward, a preview), 'BUSY' (one request at a time), |
| 574 | 'RATE_LIMITED', 'TIMEOUT', 'FAILED' or 'INVALID_ANSWER'. Show a pending state |
| 575 | and every failure. The answer does not change the state: the bot's edit |
| 576 | arrives as the change events; for the new state at once, have the bot |
| 577 | return it in result. |
| 578 | - Without a tap request works only in the private chat with the bot: once |
| 579 | when the widget appears on screen, then at most once per 5 s while visible. |
| 580 | One made off screen (at start: the client creates the bubble before showing |
| 581 | it) waits and goes out when the widget appears, so ask in the first lines. |
| 582 | - viewer: { id, first_name, last_name?, username?, is_premium? } of the person |
| 583 | looking, or null where the widget may not ask the bot. Compare viewer.id |
| 584 | with the ids in the state (my turn, my vote). |
| 585 | - isForward: a forwarded copy. chatData is null and chatType too; it may ask |
| 586 | only if the bot allowed forwards to (otherwise viewer is null and every |
| 587 | request is NOT_ALLOWED): show the shared state read-only. A forward of a |
| 588 | widget that is not shared never changes: draw a snapshot ("as of 19:40"), |
| 589 | not live progress. |
| 590 | - chatType: 'private' | 'group' | 'supergroup' | 'channel', or null. |
| 591 | - isPreview: shown in the bot's inline results before it is sent: no taps, no |
| 592 | requests, links, copy or storage, viewer null. Draw the state as it will be |
| 593 | sent. |
| 594 | - wallet (Telegram's Gram Wallet, TON Connect's formats): null where the |
| 595 | client has no wallet for this user, the widget may not ask the bot, or in a |
| 596 | preview. To pay, on a tap: request('pay:1', { wallet: true }) gives the bot |
| 597 | the user's wallet address; the bot answers with a fresh transaction |
| 598 | { valid_until, messages: [{ address, amount, payload?, stateInit? }] } (1-255 |
| 599 | messages, address user-friendly, amount: nanotons as a decimal string); in |
| 600 | the answer's handler |
| 601 | wallet.sendTransaction(tx, 'paid:1') needs no new tap (within 10 s). The |
| 602 | client's window shows the bot and amounts; the promise resolves with the |
| 603 | bot's answer { result }. wallet.signData({ type: 'text', text }, data) |
| 604 | asks for a signature, which goes to the bot. One wallet call per tap or |
| 605 | answer, never from a timer. Codes: 'REJECTED' (declined), 'BAD_REQUEST' (the |
| 606 | wallet refused it); a malformed transaction throws TypeError. After TIMEOUT |
| 607 | ask the bot, do not pay again. |
| 608 | More: {docs}/sdk#state |
| 609 |
| 610 | STORAGE, LIFECYCLE, LIMITS |
| 611 | - localStorage: this message on this device, 4 KB (QuotaExceededError past |
| 612 | it: catch it); sessionStorage until the app restarts; a forward starts |
| 613 | empty. Keep this user's own choices there (best score, "voted"); what |
| 614 | everyone sees belongs in the bot's state. |
| 615 | - The widget can be destroyed and recreated at any time: restore from |
| 616 | localStorage and the state on load, and draw the first frame synchronously. |
| 617 | - Off screen: document.hidden, no animation frames, timers at most 1 Hz. |
| 618 | - CPU: 300 ms per second (timers and frames wait beyond it, longer after a |
| 619 | task that ran past it); one task may take 500 ms, longer stops the widget. |
| 620 | At most 128 layout reads in one task; they plus about 25 µs per DOM change |
| 621 | cost the client at most 100 ms per second (frames wait beyond it). |
| 622 | - Memory 8 MB; 64 live timers and 4000 canvas commands per canvas per task |
| 623 | (RangeError past them); 2000 nodes; one text value 32 K characters, all |
| 624 | text 48 K, an attribute 8 K; 10 000 element method calls per task; 400 CSS rules, 32 |
| 625 | @keyframes; 64 script animations; 2048 x 2048 canvas pixels together; a |
| 626 | data: image at most 1024 x 1024 pixels (larger: a placeholder). Past the |
| 627 | others, or the CPU or memory limit, the widget stops on its last frame |
| 628 | ("Widget stopped"). |
| 629 | - At most 16 elements at once with a blurred box-shadow, filter, |
| 630 | backdrop-filter or opacity below 1 (animated ones and ::before/::after |
| 631 | too), 2 with backdrop-filter; past it the widget stops. Mute with colour |
| 632 | (var(--tg-theme-hint-color), rgba(), fill-opacity), never opacity; a shadow |
| 633 | without blur is free. |
| 634 | - Animate with CSS or requestAnimationFrame; change only what moved, do not |
| 635 | rebuild the DOM every frame. |
| 636 |
| 637 | EXAMPLE (the patterns, not a template) |
| 638 | <style> |
| 639 | body{margin:0;padding:12px 14px} |
| 640 | .opt{display:block;width:100%;margin:6px 0;text-align:left} |
| 641 | .me{outline:2px solid var(--tg-theme-button-color)} |
| 642 | .bar{height:4px;margin-top:4px;border-radius:2px;background:var(--tg-theme-button-color)} |
| 643 | .hint{color:var(--tg-theme-hint-color);font-size:13px} |
| 644 | </style> |
| 645 | <div id="list"></div><div class="hint" id="msg"></div> |
| 646 | <script> |
| 647 | const TW = window.TelegramWidget, $ = (id) => document.getElementById(id); |
| 648 | const NAMES = ['Pizza', 'Sushi']; |
| 649 | const votes = () => { try { return JSON.parse(TW && TW.publicData).v; } catch { return [0, 0]; } }; |
| 650 | let mine = null; try { mine = JSON.parse(localStorage.getItem('vote')); } catch {} |
| 651 | function draw() { |
| 652 | const v = votes(), total = v.reduce((a, b) => a + b, 0) || 1; |
| 653 | $('list').replaceChildren(...NAMES.map((name, i) => { |
| 654 | const b = document.createElement('button'), pct = Math.round(v[i] / total * 100); |
| 655 | b.className = 'opt' + (mine === i ? ' me' : ''); |
| 656 | b.innerHTML = name + ' <span class="hint">' + pct + '%</span><div class="bar" style="width:' + pct + '%"></div>'; |
| 657 | b.onclick = () => vote(i); |
| 658 | return b; |
| 659 | })); |
| 660 | } |
| 661 | function vote(i) { |
| 662 | if (!TW) return; |
| 663 | $('msg').textContent = 'Sending...'; |
| 664 | TW.request('vote:' + i).then(() => { |
| 665 | mine = i; try { localStorage.setItem('vote', i); } catch {} |
| 666 | $('msg').textContent = ''; draw(); |
| 667 | }, (e) => { $('msg').textContent = e.code === 'NOT_ALLOWED' ? 'Open the bot to vote' : 'Not sent: ' + e.code; }); |
| 668 | } |
| 669 | if (TW) TW.onEvent('publicDataChanged', draw); |
| 670 | draw(); |
| 671 | </script> |
| 672 | ``` |
| 673 | <!-- /agent-block --> |
| 674 |