| 1 | // Dev UI (trusted host page). Loads corpus files or dropped files into a |
| 2 | // WidgetHost, shows diagnostics, and optionally the native reference render |
| 3 | // side by side. Exposes `window.__tw` for the Playwright suites. |
| 4 | |
| 5 | import './style.css'; |
| 6 | import { BlitzRenderer } from './renderers/blitz-renderer'; |
| 7 | import { LitehtmlRenderer } from './renderers/litehtml-renderer'; |
| 8 | import { ShadowDomRenderer } from '@telegram/widget-sandbox/host/shadow-renderer'; |
| 9 | import { WidgetHost, type BubbleGesture, type GestureClaim } from '@telegram/widget-sandbox/host/widget-host'; |
| 10 | import { WorkerPool } from '@telegram/widget-sandbox/host/worker-pool'; |
| 11 | import { WIDGET_FEATURES, WIDGET_POLICY } from './policy'; |
| 12 | import { GESTURE_MODES, bubbleGestureLabel, bubbleGesturesOption, claimLabel, gestureMode, showBubbleGesture, type GestureMode } from './bubble-gestures'; |
| 13 | import type { FeedApi } from './feed'; |
| 14 | import { DEFAULT_PROFILE, MODES, MockBot, botOf, mountPanel, showCopied, showWalletWindow, type Mode, type RequestRecord } from './mock-bot'; |
| 15 | import type { Stats } from '@telegram/widget-sandbox/shared/protocol'; |
| 16 | import { CHAT_TYPES, DEFAULT_RESIZE_ANCHOR, DEFAULT_THEME_PARAMS, WIDGET_MESSAGE_KINDS, checkContentSafeArea, themeVariables, type ChatType, type ContentSafeArea, type ResizeAnchor, type StorageCommit, type WidgetAction, type WidgetMessageKind } from '@telegram/widget-sandbox/shared/sdk-policy'; |
| 17 | import { REFERENCE_TIME_LABEL, referenceSafeArea, timeCornerStyle } from '@telegram/widget-sandbox/shared/reference'; |
| 18 | import { sizeVerdict, type WidgetSize } from '@telegram/widget-sandbox/shared/widget-size'; |
| 19 | |
| 20 | const $ = <T extends HTMLElement = HTMLElement>(sel: string) => document.querySelector(sel) as T; |
| 21 | const el = { |
| 22 | corpus: $('#corpus'), drop: $('#drop'), file: $<HTMLInputElement>('#file'), title: $('#title'), |
| 23 | dark: $<HTMLInputElement>('#dark'), reference: $<HTMLInputElement>('#reference'), blitz: $<HTMLInputElement>('#blitz'), litehtml: $<HTMLInputElement>('#litehtml'), shadow: $<HTMLInputElement>('#shadow' |
| 24 | app: $('#app'), feedView: $('#feed-view'), |
| 25 | sandboxWrap: $('#sandbox-wrap'), referenceWrap: $('#reference-wrap'), chatReference: $('#chat-reference'), compareChats: $('#compare-chats'), stage: $('.stage'), |
| 26 | status: $('#status'), stats: $('#stats'), diags: $('#diags'), bridge: $('#bridge'), console: $('#console'), |
| 27 | widgetError: $('#widget-error'), width: $<HTMLSelectElement>('#width'), widthValue: $('#width-value'), gestureMode: $<HTMLSelectElement>('#gesture-mode'), |
| 28 | chatSandbox: $('#chat-sandbox'), bubble: $('#chat-sandbox .bubble'), gestures: $('#gestures'), botPanel: $('#bot-panel'), |
| 29 | netMarker: $('#net-marker'), timeCorner: $<HTMLSelectElement>('#time-corner'), timeCornerView: $('#time-corner-view'), timeCornerRef: $('#time-corner-ref'), |
| 30 | }; |
| 31 | |
| 32 | export interface TwState { |
| 33 | file: string | null; |
| 34 | html: string; |
| 35 | theme: 'light' | 'dark'; |
| 36 | loaded: boolean; |
| 37 | dead: string | null; |
| 38 | diags: Record<string, { count: number; details: string[] }>; |
| 39 | logs: { level: string; text: string }[]; |
| 40 | bridge: { method: string; args: unknown[] }[]; |
| 41 | /** What the widget asked the client to do (SDK v1 `onAction`), in order. */ |
| 42 | actions: WidgetAction[]; |
| 43 | /** Gesture claims of the primary pointerdowns (`onGestureClaim`), in order. */ |
| 44 | gestures: GestureClaim[]; |
| 45 | /** Presses the bubble took (`onBubbleGesture`: the message menu, the reaction, a swipe, the list scroll), in order. */ |
| 46 | bubbleGestures: BubbleGesture[]; |
| 47 | stats: (Stats & { nodes: number }) | null; |
| 48 | height: number; |
| 49 | /** The edge of the bubble that stays put when the height changes (`setResizeAnchor`, reported with the height). */ |
| 50 | resizeAnchor: ResizeAnchor; |
| 51 | /** Last uncaught widget error, shown under the bubble until a later task completes without one. */ |
| 52 | lastError: string | null; |
| 53 | /** The HTML's size as the server counts it (zlib, UTF-8 bytes; widget-size.ts): null until measured. */ |
| 54 | size: WidgetSize | null; |
| 55 | /** The widget's requests to the mock bot (`onRequest`) and what each got, in order (all files; the bot keeps the last 200). */ |
| 56 | requests: RequestRecord[]; |
| 57 | /** Texts the widget copied (`onCopyText`), in order. */ |
| 58 | copiedTexts: string[]; |
| 59 | } |
| 60 | |
| 61 | // The mock bot (mock-bot.ts): the message's chatData / publicData, the bot's answers and edits, the client's context. |
| 62 | const bot = new MockBot({ |
| 63 | restart: () => { if (state.html) load(state.html, state.file); }, |
| 64 | setData: (data) => { for (const h of [host, ...compareHosts]) h?.setData(data); }, |
| 65 | changed: () => { coalesce(renderBot); coalesce(syncUrl); }, |
| 66 | confirmWallet: (call) => showWalletWindow(bot.bot + '_bot', call), |
| 67 | }); |
| 68 | const state: TwState = { file: null, html: '', theme: 'light', loaded: false, dead: null, diags: {}, logs: [], bridge: [], actions: [], gestures: [], bubbleGestures: [], stats: null, height: 0, resizeAnchor: DEFAULT_RESIZE_ANCHOR, lastError: null, size: null, requests: bot.requests, copiedTexts: [] }; |
| 69 | /** The file whose `<meta name="tw-bot">` chose the bot: a restart of the same file keeps the bot the panel shows. */ |
| 70 | let botFile: string | null | undefined; |
| 71 | /** The bubble's own presses (docs/sdk-v1.md §5.5): `?gestures=phone` (default), `desktop` or `off`. */ |
| 72 | let gestures: GestureMode = gestureMode(new URLSearchParams(location.search).get('gestures')); |
| 73 | /** Bubble widths a client lays out (CSS px); 0 = the default column, -1 = free (drag the column's corner). */ |
| 74 | const WIDTH_PRESETS = [200, 320, 360, 390, 430, 600]; |
| 75 | let bubbleWidth = 0; |
| 76 | /** |
| 77 | * Where the client draws the message time (docs/sdk-v1.md §2.17, `?time=`): `caption` (a caption below the widget: the |
| 78 | * time in its line, nothing over the widget, the safe area is 0), `corner` (no caption, or one shown above the widget: |
| 79 | * the time over its bottom right corner, a left-to-right client) or `corner-rtl` (the left one). `__tw.setSafeArea(area)` passes any other numbers (the conformance runners). |
| 80 | */ |
| 81 | const TIME_MODES = [ |
| 82 | { mode: 'caption', label: 'in the caption', title: 'a widget with a caption below it: the time is in the caption\'s line, nothing over the widget' }, |
| 83 | { mode: 'corner', label: 'over the corner', title: 'a widget without a caption, or with its caption above it (invert_media): the time over its bottom right corner' }, |
| 84 | { mode: 'corner-rtl', label: 'over the corner, RTL', title: 'a right-to-left client: the time over the bottom left corner' }, |
| 85 | ] as const; |
| 86 | type TimeMode = (typeof TIME_MODES)[number]['mode']; |
| 87 | let timeMode: TimeMode = 'caption'; |
| 88 | let customSafeArea: ContentSafeArea | null = null; |
| 89 | /** What the hosts get as `contentSafeArea`. */ |
| 90 | const safeArea = (): ContentSafeArea => customSafeArea ?? (timeMode === 'caption' ? checkContentSafeArea(null) : referenceSafeArea(timeMode === |
| 91 | /** `?locale=ru`: the client's UI language passed to the widget (navigator.language, the Intl default); en-US otherwise. */ |
| 92 | const LOCALE = new URLSearchParams(location.search).get('locale') ?? undefined; |
| 93 | |
| 94 | // Web Storage as a client keeps it (docs/sdk-v1.md §5.4), per file: `local` in this page's localStorage (it survives a |
| 95 | // reload, as it survives an app restart), `session` in memory. `__tw.restart()` and reopening the file get it back. |
| 96 | const sessionAreas = new Map<string, Record<string, string>>(); |
| 97 | const storageKey = (file: string) => 'tw-widget-storage:' + file; |
| 98 | function storageFor(file: string | null): StorageCommit | undefined { |
| 99 | if (!file) return undefined; |
| 100 | let local: Record<string, string> = {}; |
| 101 | try { local = JSON.parse(localStorage.getItem(storageKey(file)) ?? '{}'); } catch {} |
| 102 | return { local, session: sessionAreas.get(file) ?? {} }; |
| 103 | } |
| 104 | function commitStorage(file: string | null, area: 'local' | 'session', values: Record<string, string>) { |
| 105 | if (!file) return; |
| 106 | if (area === 'session') sessionAreas.set(file, values); |
| 107 | else try { localStorage.setItem(storageKey(file), JSON.stringify(values)); } catch {} |
| 108 | } |
| 109 | function clearStorage(file: string | null) { |
| 110 | if (!file) return; |
| 111 | sessionAreas.delete(file); |
| 112 | try { localStorage.removeItem(storageKey(file)); } catch {} |
| 113 | } |
| 114 | let tasksAtError = 0; |
| 115 | /** Runtime limits overridable from the URL for the Playwright suites (?cpuQuotaMs=…&cpuKillAfterMs=…&maxTimers=…). */ |
| 116 | const LIMIT_PARAMS = ['cpuLimitMs', 'cpuQuotaMs', 'cpuQuotaWindowMs', 'cpuKillAfterMs', 'mainThreadQuotaMs', 'maxTimers', 'memoryLimitBytes'] as const; |
| 117 | const limits: Partial<Record<(typeof LIMIT_PARAMS)[number], number>> = {}; |
| 118 | let host: WidgetHost | null = null; |
| 119 | /** `?pool=N`: sandbox workers from a pool of N warmed ones (worker-pool.ts), as a feed would do; prewarmed at init. */ |
| 120 | let workerPool: WorkerPool | null = null; |
| 121 | /** `?feed=1`: the chat feed demo (src/feed.ts) takes over the centre column; the single-widget panels are hidden and `host` stays null. */ |
| 122 | const FEED_MODE = new URLSearchParams(location.search).get('feed') === '1'; |
| 123 | let feed: FeedApi | null = null; |
| 124 | /** Compare mode: the renderers the main bubble is not using, one WidgetHost each (same HTML, same limits). */ |
| 125 | let compareHosts: WidgetHost[] = []; |
| 126 | let referenceFrame: HTMLIFrameElement | null = null; |
| 127 | /** Off-screen pause: the bubble's intersection with the viewport, combined with the page's own visibility. `forcedVisible` (tests) overrides both. */ |
| 128 | let intersecting = true; |
| 129 | let forcedVisible: boolean | null = null; |
| 130 | const visibilityObserver = new IntersectionObserver((entries) => { intersecting = entries[entries.length - 1].isIntersecting; applyVisibility(); }); |
| 131 | function applyVisibility() { |
| 132 | host?.setVisible(forcedVisible ?? (intersecting && !document.hidden)); |
| 133 | } |
| 134 | document.addEventListener('visibilitychange', applyVisibility); |
| 135 | |
| 136 | // The client's poll of a shared widget's public_data (docs/integration.md): only while the widget watches |
| 137 | // (`watchPublicData`), is on screen and is a shared object (the mock bot's `shared`), every `bot.pollMs`. |
| 138 | let lastPoll = 0; |
| 139 | setInterval(() => { |
| 140 | const now = performance.now(); |
| 141 | if (now - lastPoll < bot.pollMs) return; |
| 142 | if (!host || !state.loaded || state.dead || !host.watchesPublicData || !(forcedVisible ?? (intersecting && !document.hidden))) return; |
| 143 | lastPoll = now; |
| 144 | const next = bot.poll(state.file); |
| 145 | if (next) for (const h of [host, ...compareHosts]) h?.setData(next); |
| 146 | }, 50); |
| 147 | let referenceTimer = 0; |
| 148 | let loadWaiters: (() => void)[] = []; |
| 149 | |
| 150 | // ───────────── rendering of the panels ───────────── |
| 151 | |
| 152 | // Panels are re-rendered at most once per frame: a misbehaving widget can emit |
| 153 | // thousands of diagnostics per second, and per-event DOM rebuilds froze the page. |
| 154 | const pending = new Set<() => void>(); |
| 155 | let frame = 0; |
| 156 | function coalesce(fn: () => void) { |
| 157 | pending.add(fn); |
| 158 | if (!frame) frame = requestAnimationFrame(() => { frame = 0; const fns = [...pending]; pending.clear(); for (const f |
| 159 | } |
| 160 | |
| 161 | function renderStatus() { |
| 162 | el.status.textContent = state.dead ? `✖ sandbox terminated: ${state.dead}` : state.loaded ? '● loaded' : host ? '… loading' : '—'; |
| 163 | el.status.className = state.dead ? 'dead' : state.loaded ? 'ok' : ''; |
| 164 | // What a product would show under the bubble: the widget stays on screen (frozen) with a one-line reason. |
| 165 | const line = state.dead ? `Widget stopped: ${state.dead.split('\n')[0]}` : state.lastError ? state.lastError.split(' |
| 166 | el.widgetError.textContent = line; |
| 167 | el.widgetError.classList.toggle('hidden', !line); |
| 168 | } |
| 169 | /** Bytes after zlib compression (CompressionStream 'deflate' is RFC 1950, at zlib's default level 6: a few bytes over the server's level 9) and of the HTML. */ |
| 170 | async function measureSize(html: string): Promise<WidgetSize> { |
| 171 | const raw = new TextEncoder().encode(html); |
| 172 | const z = await new Response(new Blob([raw]).stream().pipeThrough(new CompressionStream('deflate'))).arrayBuffer(); |
| 173 | return { zlib: z.byteLength, raw: raw.length }; |
| 174 | } |
| 175 | |
| 176 | /** The size row: green under 3800 B compressed, a warning up to the 4096 B limit, an error past it or past 32 KB of HTML. */ |
| 177 | function sizeRow(size: WidgetSize): HTMLTableRowElement { |
| 178 | const v = sizeVerdict(size); |
| 179 | const tr = document.createElement('tr'); |
| 180 | tr.className = 'size size-' + v.level; |
| 181 | const th = document.createElement('th'); th.textContent = 'size (server)'; |
| 182 | const td = document.createElement('td'); |
| 183 | td.textContent = `${size.zlib} B zlib / ${(size.raw / 1024).toFixed(1)} KB raw (limit 4096 / 32768)`; |
| 184 | if (v.message) { const d = document.createElement('div'); d.textContent = v.message; td.appendChild(d); } |
| 185 | tr.title = 'zlib, as the server counts it (level 9 there, 6 here; docs/tgw-format.md); past either limit it answers INPUT_MEDIA_WIDGET_TOO_LARGE'; |
| 186 | tr.append(th, td); |
| 187 | return tr; |
| 188 | } |
| 189 | |
| 190 | function renderStats() { |
| 191 | const s = state.stats; |
| 192 | const size = state.size ? [sizeRow(state.size)] : []; |
| 193 | if (!s) { el.stats.replaceChildren(...size); return; } |
| 194 | const rows: [string, string][] = [ |
| 195 | ['JS time', `${s.jsMs.toFixed(0)} ms in ${s.tasks} tasks`], |
| 196 | ['memory', `${(s.memoryBytes / 1024 / 1024).toFixed(1)} MB`], |
| 197 | ['ops sent', String(s.ops)], |
| 198 | ['nodes', String(s.nodes)], |
| 199 | ['sync queries', `${s.queries} (${s.queryMs.toFixed(0)} ms, avg ${s.queries ? (s.queryMs / s. |
| 200 | ['missed mutations', String(s.missedMutations)], |
| 201 | ['CPU quota', `${s.cpuWindowMs.toFixed(0)} ms used in the current window, ${s.throttledTasks} tasks deferred`], |
| 202 | ['bubble height', `${state.height} px, anchor ${state.resizeAnchor}: ${state.resizeAnchor === 'bottom' ? 'grows and shrinks upward, its bottom stays' : 'grows and shrinks downward, its top stays'}`], |
| 203 | ]; |
| 204 | el.stats.replaceChildren(...size, ...rows.map(([k, v]) => { |
| 205 | const tr = document.createElement('tr'); |
| 206 | const th = document.createElement('th'); th.textContent = k; |
| 207 | const td = document.createElement('td'); td.textContent = v; |
| 208 | tr.append(th, td); |
| 209 | return tr; |
| 210 | })); |
| 211 | } |
| 212 | function renderDiags() { |
| 213 | el.diags.replaceChildren(...Object.entries(state.diags).map(([kind, d]) => { |
| 214 | const li = document.createElement('li'); |
| 215 | li.className = 'diag diag-' + kind; |
| 216 | const b = document.createElement('b'); b.textContent = `${kind} ×${d.count}`; |
| 217 | const span = document.createElement('span'); span.textContent = d.details.slice(-3).join(' · '); |
| 218 | li.append(b, ' ', span); |
| 219 | li.title = d.details.join('\n'); |
| 220 | return li; |
| 221 | })); |
| 222 | } |
| 223 | function renderBridge() { |
| 224 | el.bridge.replaceChildren(...state.bridge.slice(-20).map((b) => { |
| 225 | const li = document.createElement('li'); |
| 226 | li.textContent = `${b.method}(${b.args.map((a) => JSON.stringify(a)).join(', ')})`; |
| 227 | return li; |
| 228 | })); |
| 229 | } |
| 230 | function renderGestures() { |
| 231 | const rows = state.gestures.slice(-6).map((c) => `press on ${claimLabel(c)}`); |
| 232 | const taken = state.bubbleGestures.slice(-4).map((g) => `bubble: ${bubbleGestureLabel(g)} (${g.gesture}; the widget got pointercancel)`); |
| 233 | el.gestures.replaceChildren(...[...rows, ...taken].map((t) => Object.assign(document.createElement('li'), { textContent: t }))); |
| 234 | } |
| 235 | const botPanel = mountPanel(el.botPanel, bot, () => state.file); |
| 236 | function renderBot() { botPanel.render(); } |
| 237 | function renderConsole() { |
| 238 | el.console.replaceChildren(...state.logs.slice(-300).map((l) => { |
| 239 | const div = document.createElement('div'); |
| 240 | div.className = 'log log-' + l.level; |
| 241 | div.textContent = `[${l.level}] ${l.text}`; |
| 242 | return div; |
| 243 | })); |
| 244 | el.console.scrollTop = el.console.scrollHeight; |
| 245 | } |
| 246 | |
| 247 | // ───────────── loading widgets ───────────── |
| 248 | |
| 249 | function load(html: string, name: string | null) { |
| 250 | host?.destroy(); |
| 251 | host = null; |
| 252 | Object.assign(state, { file: name, html, loaded: false, dead: null, diags: {}, logs: [], bridge: [], actions: [], gestures: [], bubbleGestures: [], stats: null, height: 0, resizeAnchor: DEFAULT_RESIZE_ANCHOR, lastError: null, size: null, copiedTexts: [] }); |
| 253 | if (name !== botFile || name === null) { botFile = name; bot.bot = botOf(html); } |
| 254 | applyAnchor(); |
| 255 | void measureSize(html).then((size) => { if (state.html === html) { state.size = size; coalesce(renderStats); } }); |
| 256 | tasksAtError = 0; |
| 257 | // ───────────── the resize anchor (docs/sdk-v1.md §5.6) ───────────── |
| 258 | |
| 259 | // The bubble's anchored edge stays put on the stage, as in a chat: anchored at the bottom, the bubble sits at the |
| 260 | // stage's bottom and grows upward (style.css `.anchor-bottom`); once the stage scrolls, its scroll keeps the bottom edge. |
| 261 | // The anchor comes with the size reports, so a widget that sets it at start is laid out at the bottom from the first one. |
| 262 | let anchoredHeight = 0; |
| 263 | function applyAnchor() { |
| 264 | el.chatSandbox.classList.toggle('anchor-bottom', state.resizeAnchor === 'bottom' && !FEED_MODE); |
| 265 | } |
| 266 | new ResizeObserver(() => { |
| 267 | const h = el.chatSandbox.offsetHeight, delta = h - anchoredHeight; |
| 268 | anchoredHeight = h; |
| 269 | if (delta && state.resizeAnchor === 'bottom' && el.stage.scrollHeight > el.stage.clientHeight) el.stage.scrollTop += delta; |
| 270 | }).observe(el.chatSandbox); |
| 271 | |
| 272 | el.title.textContent = name ?? 'dropped file'; |
| 273 | el.sandboxWrap.replaceChildren(); |
| 274 | renderStatus(); renderStats(); renderDiags(); renderBridge(); renderConsole(); renderGestures(); renderBot(); |
| 275 | const context = bot.hostContext(); |
| 276 | bot.loaded(name); |
| 277 | // The network marker, as a client draws it: exactly when the message has can_query (a preview has no flags). |
| 278 | el.netMarker.classList.toggle('hidden', !context.canQuery || !!context.preview); |
| 279 | host = new WidgetHost(el.sandboxWrap, html, { |
| 280 | policy: WIDGET_POLICY, |
| 281 | features: WIDGET_FEATURES, |
| 282 | theme: state.theme, |
| 283 | locale: LOCALE, |
| 284 | contentSafeArea: safeArea(), |
| 285 | storage: storageFor(name), |
| 286 | data: bot.dataFor(name), |
| 287 | context, |
| 288 | // Forced off (tests): created off screen, as Telegram's clients create a bubble before it is shown. |
| 289 | ...(forcedVisible !== null ? { visible: forcedVisible } : {}), |
| 290 | onRequest: (request) => bot.request(name, request), |
| 291 | onWallet: (call) => bot.walletCall(name, call), |
| 292 | onCopyText: (text) => { |
| 293 | state.copiedTexts.push(text); |
| 294 | showCopied(el.bubble, text); |
| 295 | navigator.clipboard?.writeText(text).catch(() => {}); |
| 296 | }, |
| 297 | ...limits, |
| 298 | // Blitz / litehtml (dev tooling): a native renderer compiled to wasm instead of the sandboxed iframe; sandbox and validator unchanged. |
| 299 | // Shadow DOM (prototype): the same renderer core on a shadow root in this page, no iframe. |
| 300 | rendererFactory: el.litehtml.checked ? LitehtmlRenderer.factory : el.blitz.checked ? BlitzRenderer.factory : el.shadow.checked ? ShadowDomRenderer.factory : undefined, |
| 301 | workerPool: workerPool ?? undefined, |
| 302 | onLog: (level, text) => { if (state.logs.length < 5000) state.logs.push({ level, text }); coalesce(renderConsole); }, |
| 303 | onError: (text) => { state.lastError = text; tasksAtError = state.stats?.tasks ?? 0; coalesce(renderStatus); }, |
| 304 | onDiag: (kind, detail) => { |
| 305 | const d = (state.diags[kind] ??= { count: 0, details: [] }); |
| 306 | d.count++; |
| 307 | if (d.details.length < 50) d.details.push(detail); |
| 308 | coalesce(renderDiags); |
| 309 | }, |
| 310 | onStats: (s) => { |
| 311 | state.stats = s; |
| 312 | if (state.lastError && s.tasks > tasksAtError + 1) { state.lastError = null; coalesce(renderStatus); } |
| 313 | coalesce(renderStats); |
| 314 | }, |
| 315 | onBridge: (method, args) => { state.bridge.push({ method, args }); coalesce(renderBridge); }, |
| 316 | onAction: (action) => { state.actions.push(action); }, |
| 317 | onStorageCommit: (area, values) => commitStorage(name, area, values), |
| 318 | onGestureClaim: (claim) => { if (state.gestures.length < 1000) state.gestures.push(claim); coalesce(renderGestures); }, |
| 319 | bubbleGestures: bubbleGesturesOption(gestures), |
| 320 | onBubbleGesture: (g) => { if (state.bubbleGestures.length < 1000) state.bubbleGestures.push(g); showBubbleGesture(el.bubble, g); coalesce(renderGestures); }, |
| 321 | onDead: (reason) => { state.dead = reason; renderStatus(); settle(); }, |
| 322 | onLoaded: () => { state.loaded = true; renderStatus(); settle(); }, |
| 323 | onResize: (h, anchor) => { state.height = h; state.resizeAnchor = anchor; applyAnchor(); coalesce(renderStats); }, |
| 324 | onWatchPublicData: (on) => { bot.watching = on; coalesce(renderBot); }, |
| 325 | }); |
| 326 | visibilityObserver.disconnect(); |
| 327 | intersecting = true; |
| 328 | visibilityObserver.observe(host.element); |
| 329 | applyVisibility(); |
| 330 | updateCompare(); |
| 331 | updateReference(); |
| 332 | syncUrl(); |
| 333 | } |
| 334 | |
| 335 | type RendererKind = 'iframe' | 'shadow' | 'blitz' | 'litehtml'; |
| 336 | const RENDERERS: { kind: RendererKind; title: string; factory?: typeof BlitzRenderer.factory }[] = [ |
| 337 | { kind: 'iframe', title: 'sandbox · iframe renderer (product)' }, |
| 338 | { kind: 'shadow', title: 'sandbox · Shadow DOM renderer (no iframe, prototype)', factory: ShadowDomRenderer.factory }, |
| 339 | { kind: 'blitz', title: 'sandbox · Blitz renderer (wasm, dev tooling)', factory: BlitzRenderer.factory }, |
| 340 | { kind: 'litehtml', title: 'sandbox · litehtml renderer (wasm, dev tooling)', factory: LitehtmlRenderer.factory }, |
| 341 | ]; |
| 342 | function mainRenderer(): RendererKind { return el.litehtml.checked ? 'litehtml' : el.blitz.checked ? 'blitz' : el.shadow.checked ? 'shadow' : 'iframe'; } |
| 343 | |
| 344 | /** Compare mode (dev tooling): the other two renderers next to the main bubble, each on its own sandbox from the same |
| 345 | * HTML, plus the native reference. The right-hand panels keep describing the main bubble; each extra column shows its |
| 346 | * own one-line status (loaded / dead, the renderer's paint line). The sandboxes boot one after another — three QuickJS |
| 347 | * workers starting at once contend for the CPU and the boot slice (cpuLimitMs) kills them. */ |
| 348 | let compareGeneration = 0; |
| 349 | function updateCompare() { |
| 350 | compareGeneration++; |
| 351 | for (const h of compareHosts) h.destroy(); |
| 352 | compareHosts = []; |
| 353 | el.compareChats.replaceChildren(); |
| 354 | const on = el.compare.checked && !!state.html; |
| 355 | el.stage.classList.toggle('compare', on); |
| 356 | if (!on) return; |
| 357 | const generation = compareGeneration; |
| 358 | const html = state.html; |
| 359 | const columns = RENDERERS.filter((r) => r.kind !== mainRenderer()).map((r) => { |
| 360 | const chat = document.createElement('div'); |
| 361 | chat.className = 'chat'; |
| 362 | chat.dataset.renderer = r.kind; |
| 363 | const head = document.createElement('div'); |
| 364 | head.className = 'bubble-head'; |
| 365 | head.textContent = r.title; |
| 366 | const bubble = document.createElement('div'); |
| 367 | bubble.className = 'bubble'; |
| 368 | const wrap = document.createElement('div'); |
| 369 | wrap.className = 'frame-wrap'; |
| 370 | bubble.appendChild(wrap); |
| 371 | const status = document.createElement('div'); |
| 372 | status.className = 'compare-status'; |
| 373 | status.textContent = '… waiting for the previous sandbox to boot'; |
| 374 | chat.append(head, bubble, status); |
| 375 | el.compareChats.appendChild(chat); |
| 376 | return { r, wrap, status }; |
| 377 | }); |
| 378 | let i = 0; |
| 379 | const startNext = () => { |
| 380 | if (generation !== compareGeneration || i >= columns.length) return; |
| 381 | const { r, wrap, status } = columns[i++]; |
| 382 | const t0 = performance.now(); |
| 383 | const lines: Record<string, string> = { status: '… loading' }; |
| 384 | const show = () => { status.textContent = Object.entries(lines).map(([k, v]) => `${k}: ${v}`).join('\n |
| 385 | show(); |
| 386 | let settled = false; |
| 387 | const settle = () => { if (!settled) { settled = true; startNext(); } }; |
| 388 | // `current` (what __tw.tap / __tw.blitz / __tw.litehtml talk to) stays the main bubble's renderer. |
| 389 | const mainBlitz = BlitzRenderer.current, mainLitehtml = LitehtmlRenderer.current; |
| 390 | const h = new WidgetHost(wrap, html, { |
| 391 | policy: WIDGET_POLICY, |
| 392 | features: WIDGET_FEATURES, |
| 393 | theme: state.theme, |
| 394 | contentSafeArea: safeArea(), |
| 395 | data: bot.dataFor(state.file), |
| 396 | context: bot.hostContext(), |
| 397 | ...limits, |
| 398 | rendererFactory: r.factory, |
| 399 | bubbleGestures: bubbleGesturesOption(gestures), |
| 400 | onLoaded: () => { lines.status = `loaded in ${(performance.now() - t0).toFixed(0)} ms`; coalesce(show); settle(); }, |
| 401 | onDead: (reason) => { lines.status = `dead: ${reason.split('\n')[0]}`; coalesce(show); settle(); }, |
| 402 | onError: (text) => { lines.error = text.split('\n')[0]; coalesce(show); }, |
| 403 | onDiag: (kind, detail) => { if (kind === 'renderer' || /-(init|paint|build)$/.test(kind)) { lines[kind] = detail; coalesce(show); } }, |
| 404 | }); |
| 405 | BlitzRenderer.current = mainBlitz; |
| 406 | LitehtmlRenderer.current = mainLitehtml; |
| 407 | compareHosts.push(h); |
| 408 | setTimeout(settle, 15_000); |
| 409 | }; |
| 410 | ready().then(startNext); |
| 411 | } |
| 412 | |
| 413 | function settle() { |
| 414 | const w = loadWaiters; |
| 415 | loadWaiters = []; |
| 416 | for (const f of w) f(); |
| 417 | } |
| 418 | |
| 419 | /** Resolves once the current widget has finished loading (or died). */ |
| 420 | function ready(): Promise<void> { |
| 421 | if (state.loaded || state.dead) return Promise.resolve(); |
| 422 | return new Promise((r) => loadWaiters.push(r)); |
| 423 | } |
| 424 | |
| 425 | async function openFile(rel: string) { |
| 426 | const res = await fetch('/corpus/' + rel); |
| 427 | if (!res.ok) throw new Error('no such corpus file: ' + rel); |
| 428 | load(await res.text(), rel); |
| 429 | for (const li of el.corpus.children) li.classList.toggle('active', (li as HTMLElement).dataset.file === rel); |
| 430 | } |
| 431 | |
| 432 | // Reference mode (dev tooling): native render of a repo corpus file in a |
| 433 | // sandboxed iframe served with connect-src 'none'. Never used for attacks. |
| 434 | /** |
| 435 | * The dev app's theme in the reference frame: the palette of the toggle (the reference stylesheet alone follows the |
| 436 | * browser's prefers-color-scheme), and the frame's root in the same scheme as its element, or the frame gets an opaque |
| 437 | * canvas over the bubble, as the renderer's frame would (core.ts frameColorScheme). The time control's content safe |
| 438 | * area comes with the frame's URL (`?safeArea=`, vite.config.ts) as the root variables; the frame's |
| 439 | * `env(safe-area-inset-*)` stays the browser's own (0, unless the page runs with Chromium's safe-area override, as |
| 440 | * `pnpm test:safe-area-corpus` does). |
| 441 | */ |
| 442 | function referenceScheme(f: HTMLIFrameElement, theme: 'light' | 'dark') { |
| 443 | try { |
| 444 | const d = f.contentDocument; |
| 445 | if (!d?.head) return; |
| 446 | const style = d.getElementById('tw-ref-scheme') ?? d.head.appendChild(Object.assign(d.createElement('style'), { id: 'tw-ref-scheme' })); |
| 447 | const vars = Object.entries(themeVariables({ colorScheme: theme })).map(([k, v]) => `${k}:${v}`).join(';'); |
| 448 | style.textContent = `@layer tw-ua{:where(html){color-scheme:${theme}}}:root{${vars}}`; |
| 449 | } catch {} |
| 450 | } |
| 451 | |
| 452 | function updateReference() { |
| 453 | // compare mode shows the reference too (never for attacks: reference mode has no sandbox) |
| 454 | const on = (el.reference.checked || el.compare.checked) && state.file && !state.file.startsWith('attacks/'); |
| 455 | el.chatReference.classList.toggle('hidden', !on); |
| 456 | referenceFrame?.remove(); |
| 457 | referenceFrame = null; |
| 458 | clearInterval(referenceTimer); |
| 459 | if (!on) return; |
| 460 | const f = document.createElement('iframe'); |
| 461 | f.className = 'widget-frame'; |
| 462 | // allow-same-origin only so that the dev UI can read the document height; |
| 463 | // allow-forms so that `submit` events fire, like in the product renderer. |
| 464 | f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms'); |
| 465 | f.style.colorScheme = state.theme; |
| 466 | f.addEventListener('load', () => referenceScheme(f, state.theme)); |
| 467 | const a = safeArea(); |
| 468 | f.src = '/reference/' + state.file + (a.bottom || a.cornerLeft || a.cornerRight ? `?safeArea=${a.bottom},${a.cornerRight},${a.cornerLeft}` : |
| 469 | el.referenceWrap.replaceChildren(f); |
| 470 | referenceFrame = f; |
| 471 | const size = () => { |
| 472 | try { |
| 473 | const d = f.contentDocument; |
| 474 | if (d?.documentElement) f.style.height = Math.min(Math.max(Math.ceil(d.documentElement.getBoundingClientRect().height), 50), 600) + 'px'; |
| 475 | } catch {} |
| 476 | }; |
| 477 | // Same-origin frame: size it from inside (ResizeObserver) plus a slow fallback poll. |
| 478 | f.addEventListener('load', () => { |
| 479 | size(); |
| 480 | try { |
| 481 | const d = f.contentDocument!; |
| 482 | new (f.contentWindow as any).ResizeObserver(size).observe(d.documentElement); |
| 483 | new (f.contentWindow as any).ResizeObserver(size).observe(d.body); |
| 484 | } catch {} |
| 485 | }); |
| 486 | referenceTimer = window.setInterval(size, 1000); |
| 487 | } |
| 488 | |
| 489 | function setTheme(theme: 'light' | 'dark') { |
| 490 | state.theme = theme; |
| 491 | el.dark.checked = theme === 'dark'; |
| 492 | document.documentElement.dataset.theme = theme; |
| 493 | // The bubbles are the widgets' canvas: their colour is the bg_color the hosts get (the scheme's default palette here). |
| 494 | document.documentElement.style.setProperty('--bubble', DEFAULT_THEME_PARAMS[theme].bg_color); |
| 495 | host?.setTheme(theme); |
| 496 | for (const h of compareHosts) h.setTheme(theme); |
| 497 | if (referenceFrame) { referenceFrame.style.colorScheme = theme; referenceScheme(referenceFrame, theme); } |
| 498 | feed?.setTheme(theme); |
| 499 | syncUrl(); |
| 500 | } |
| 501 | |
| 502 | function syncUrl() { |
| 503 | if (FEED_MODE) return; // the feed owns the URL (its own switches, plus the theme) |
| 504 | const p = new URLSearchParams(); |
| 505 | if (state.file) p.set('file', state.file); |
| 506 | if (state.theme === 'dark') p.set('theme', 'dark'); |
| 507 | if (el.reference.checked) p.set('reference', '1'); |
| 508 | if (el.blitz.checked) p.set('blitz', '1'); |
| 509 | if (el.litehtml.checked) p.set('litehtml', '1'); |
| 510 | if (el.shadow.checked) p.set('shadow', '1'); |
| 511 | if (el.compare.checked) p.set('compare', '1'); |
| 512 | for (const k of LIMIT_PARAMS) if (limits[k] !== undefined) p.set(k, String(limits[k])); |
| 513 | if (workerPool) p.set('pool', String(workerPool.size)); |
| 514 | if (bubbleWidth) p.set('width', bubbleWidth > 0 ? String(bubbleWidth) : 'free'); |
| 515 | if (gestures !== 'phone') p.set('gestures', gestures); |
| 516 | if (timeMode !== 'caption') p.set('time', timeMode); |
| 517 | // The mock bot's context and answers, when not the defaults (the original in the private chat with the bot, viewer 1001). |
| 518 | const c = bot.context; |
| 519 | if (c.message !== 'private') p.set('message', c.message); |
| 520 | if (c.chatType) p.set('chat', c.chatType); |
| 521 | if (c.viewer !== 1001 || c.profile !== DEFAULT_PROFILE) p.set('viewer', c.viewer === null ? 'none' : `${c.viewer |
| 522 | if (bot.mode !== 'bot') p.set('botmode', bot.mode); |
| 523 | if (!bot.wallet) p.set('wallet', '0'); |
| 524 | history.replaceState(null, '', '?' + p.toString()); |
| 525 | } |
| 526 | |
| 527 | /** The bubble's width (every column of the stage: sandbox, reference, compare): a preset, the default column, or free. */ |
| 528 | function setWidth(w: number | 'free') { |
| 529 | bubbleWidth = w === 'free' ? -1 : WIDTH_PRESETS.includes(w) || (w >= 200 && w <= 1200) ? |
| 530 | el.stage.classList.toggle('free-width', bubbleWidth < 0); |
| 531 | if (bubbleWidth > 0) el.stage.style.setProperty('--chat-width', bubbleWidth + 'px'); |
| 532 | else el.stage.style.removeProperty('--chat-width'); |
| 533 | if (bubbleWidth >= 0) el.chatSandbox.style.width = ''; |
| 534 | el.width.value = bubbleWidth < 0 ? 'free' : String(bubbleWidth); |
| 535 | if (el.width.value === '' && bubbleWidth > 0) el.width.value = String(bubbleWidth); // a width from the URL outside the presets |
| 536 | showWidth(); |
| 537 | syncUrl(); |
| 538 | } |
| 539 | function showWidth() { el.widthValue.textContent = `${Math.round(el.chatSandbox.getBoundingClientRect().width)} px`; } |
| 540 | // Free width: the sandbox column has a resize handle; the reference column follows it. |
| 541 | new ResizeObserver(() => { |
| 542 | showWidth(); |
| 543 | if (bubbleWidth < 0) el.stage.style.setProperty('--chat-width', Math.round(el.chatSandbox.getBoundingClientRect().width) + 'px'); |
| 544 | }).observe(el.chatSandbox); |
| 545 | |
| 546 | /** |
| 547 | * The time over the bubble (docs/sdk-v1.md §2.17): drawn here, outside the widget, as a client draws it (a view over the |
| 548 | * widget that takes its own taps), and passed to the live hosts; a new widget starts with it. |
| 549 | */ |
| 550 | function setTimeCorner(mode: TimeMode | null, area: Partial<ContentSafeArea> | null = null) { |
| 551 | if (mode) timeMode = mode; |
| 552 | customSafeArea = area ? checkContentSafeArea(area) : null; |
| 553 | el.timeCorner.value = timeMode; |
| 554 | const style = timeCornerStyle(safeArea()); |
| 555 | el.timeCornerView.classList.toggle('hidden', !style); |
| 556 | el.timeCornerView.setAttribute('style', style); |
| 557 | el.timeCornerView.textContent = REFERENCE_TIME_LABEL; |
| 558 | // The reference column is a client's bubble too: the same time over it and the same variables in its frame. |
| 559 | el.timeCornerRef.classList.toggle('hidden', !style); |
| 560 | el.timeCornerRef.setAttribute('style', style); |
| 561 | el.timeCornerRef.textContent = REFERENCE_TIME_LABEL; |
| 562 | // The reference frame reads the band from its URL before its scripts run: a new one. |
| 563 | if (referenceFrame) updateReference(); |
| 564 | for (const h of [host, ...compareHosts]) h?.setContentSafeArea(safeArea()); |
| 565 | syncUrl(); |
| 566 | } |
| 567 | |
| 568 | /** The bubble's presses: `phone` (the mouse as a finger), `desktop` (as a mouse) or `off`; applied to the live hosts. */ |
| 569 | function setGestures(mode: GestureMode) { |
| 570 | gestures = mode; |
| 571 | el.gestureMode.value = mode; |
| 572 | for (const h of [host, ...compareHosts]) h?.setBubbleGestures(bubbleGesturesOption(mode)); |
| 573 | feed?.setGestures(mode); |
| 574 | syncUrl(); |
| 575 | } |
| 576 | |
| 577 | // ───────────── wiring ───────────── |
| 578 | |
| 579 | async function init() { |
| 580 | const files: string[] = await (await fetch('/api/corpus')).json(); |
| 581 | el.corpus.replaceChildren(...files.map((f) => { |
| 582 | const li = document.createElement('li'); |
| 583 | li.textContent = f; |
| 584 | li.dataset.file = f; |
| 585 | li.addEventListener('click', () => openFile(f)); |
| 586 | return li; |
| 587 | })); |
| 588 | const params = new URLSearchParams(location.search); |
| 589 | for (const k of LIMIT_PARAMS) if (params.has(k) && Number.isFinite(Number(params.get(k)))) limits[k] = Number(params.get(k)); |
| 590 | if (FEED_MODE) { |
| 591 | // Feed demo: the theme toggle and the feed checkbox are the only toolbar controls left; everything else is per bubble inside the feed. |
| 592 | el.feed.checked = true; |
| 593 | el.app.classList.add('feed-mode'); |
| 594 | el.feedView.classList.remove('hidden'); |
| 595 | el.gestureMode.value = gestures; |
| 596 | setTheme(params.get('theme') === 'dark' ? 'dark' : 'light'); |
| 597 | const { startFeed } = await import('./feed'); |
| 598 | feed = startFeed(el.feedView, { theme: state.theme, params, gestures }); |
| 599 | (window as any).__tw.feed = feed; |
| 600 | return; |
| 601 | } |
| 602 | const poolSize = Number(params.get('pool') ?? 0); |
| 603 | if (poolSize > 0) { |
| 604 | workerPool = new WorkerPool(poolSize); |
| 605 | await workerPool.prewarm(); |
| 606 | } |
| 607 | el.reference.checked = params.get('reference') === '1'; |
| 608 | el.blitz.checked = params.get('blitz') === '1'; |
| 609 | el.litehtml.checked = params.get('litehtml') === '1'; |
| 610 | el.shadow.checked = params.get('shadow') === '1'; |
| 611 | el.compare.checked = params.get('compare') === '1'; |
| 612 | // The mock bot's context from the URL (`?message=group&chat=supergroup&viewer=42,Ann,Lee,ann_lee,premium&botmode=TIMEOUT`), before the first widget. |
| 613 | const kind = params.get('message'); |
| 614 | if (kind && kind in WIDGET_MESSAGE_KINDS) bot.context.message = kind as WidgetMessageKind; |
| 615 | const chat = params.get('chat'); |
| 616 | if (chat) bot.context.chatType = (CHAT_TYPES as readonly string[]).includes(chat) ? (chat as ChatType) : null; |
| 617 | const viewer = params.get('viewer'); |
| 618 | if (viewer) { |
| 619 | // `?viewer=42` keeps the default names; `?viewer=42,Ann,,ann_lee,premium` sets them (`viewerFromList`). |
| 620 | const [id, ...rest] = viewer.split(','); |
| 621 | bot.context.viewer = Number(id) > 0 ? Number(id) : null; |
| 622 | if (rest.length) bot.context.profile = rest.join(','); |
| 623 | } |
| 624 | const botMode = params.get('botmode'); |
| 625 | if (botMode && (MODES as readonly string[]).includes(botMode)) bot.mode = botMode as Mode; |
| 626 | // ?wallet=0: the client has no wallet for this user (TelegramWidget.wallet is null). |
| 627 | if (params.get('wallet') === '0') bot.wallet = false; |
| 628 | renderBot(); |
| 629 | const w = params.get('width'); |
| 630 | setWidth(w === 'free' ? 'free' : Number(w) || 0); |
| 631 | setGestures(gestures); |
| 632 | const time = params.get('time'); |
| 633 | setTimeCorner(TIME_MODES.some((t) => t.mode === time) ? (time as TimeMode) : 'caption'); |
| 634 | setTheme(params.get('theme') === 'dark' ? 'dark' : 'light'); |
| 635 | // ?offscreen=1: the widget boots off screen until __tw.setVisible(true | null), as Telegram's clients create a bubble. |
| 636 | if (params.get('offscreen') === '1') forcedVisible = false; |
| 637 | const file = params.get('file'); |
| 638 | if (file && files.includes(file)) await openFile(file); |
| 639 | } |
| 640 | |
| 641 | el.dark.addEventListener('change', () => setTheme(el.dark.checked ? 'dark' : 'light')); |
| 642 | el.width.replaceChildren(...[['0', 'default'], ...WIDTH_PRESETS.map((w) => [String(w), `${w} px`]), ['free', 'free (drag)']].map(([ |
| 643 | el.width.addEventListener('change', () => setWidth(el.width.value === 'free' ? 'free' : Number(el.width.value))); |
| 644 | el.gestureMode.replaceChildren(...GESTURE_MODES.map((g) => Object.assign(document.createElement('option'), { value: g.mode, textContent: g.mode, title: g.title }))); |
| 645 | el.gestureMode.addEventListener('change', () => setGestures(gestureMode(el.gestureMode.value))); |
| 646 | el.timeCorner.replaceChildren(...TIME_MODES.map((t) => Object.assign(document.createElement('option'), { value: t.mode, textContent: t.label, title: t.title }))); |
| 647 | el.timeCorner.addEventListener('change', () => setTimeCorner(el.timeCorner.value as TimeMode)); |
| 648 | el.reference.addEventListener('change', () => { updateReference(); syncUrl(); }); |
| 649 | el.compare.addEventListener('change', () => { updateCompare(); updateReference(); syncUrl(); }); |
| 650 | // The two native renderers are exclusive: ticking one unticks the other. |
| 651 | el.blitz.addEventListener('change', () => { if (el.blitz.checked) { el.litehtml.checked = false; el.shadow.checked = false; } if (state.html) load(state.html, state.file); else syncUrl(); }); |
| 652 | el.litehtml.addEventListener('change', () => { if (el.litehtml.checked) { el.blitz.checked = false; el.shadow.checked = false; } if (state.html) load(state.html, state.file); else syncUrl(); }); |
| 653 | el.shadow.addEventListener('change', () => { if (el.shadow.checked) { el.blitz.checked = false; el.litehtml.checked = false; } if (state.html) load(state.html, state.file); else syncUrl(); }); |
| 654 | el.reload.addEventListener('click', () => { if (state.html) load(state.html, state.file); }); |
| 655 | // The feed is a different app mode: a reload with `?feed=1` (keeping the theme), or back to the single-widget UI. |
| 656 | el.feed.addEventListener('change', () => { location.search = el.feed.checked ? `?feed=1${state.theme === 'dark' ? '&theme=dark' : ''}` : state.theme |
| 657 | el.drop.addEventListener('click', () => el.file.click()); |
| 658 | el.file.addEventListener('change', async () => { |
| 659 | const f = el.file.files?.[0]; |
| 660 | if (f) load(await f.text(), null); |
| 661 | }); |
| 662 | el.drop.addEventListener('dragover', (e) => { e.preventDefault(); el.drop.classList.add('over'); }); |
| 663 | el.drop.addEventListener('dragleave', () => el.drop.classList.remove('over')); |
| 664 | el.drop.addEventListener('drop', async (e) => { |
| 665 | e.preventDefault(); |
| 666 | el.drop.classList.remove('over'); |
| 667 | const f = e.dataTransfer?.files[0]; |
| 668 | if (f) load(await f.text(), null); |
| 669 | }); |
| 670 | |
| 671 | (window as any).__tw = { |
| 672 | state, |
| 673 | load: (html: string, name: string | null = null) => load(html, name), |
| 674 | openFile, |
| 675 | ready, |
| 676 | setTheme, |
| 677 | /** Re-create the WidgetHost from the same HTML (what a "Restart" action in a product would do). */ |
| 678 | restart: () => { if (state.html) load(state.html, state.file); }, |
| 679 | /** The bubble's width in CSS px (200–1200; 0 = the default column) or 'free'. */ |
| 680 | setWidth, |
| 681 | /** The bubble's presses: 'phone' (default: a hold is the menu, a double tap the reaction, swipes the chat's, unless touch-action claims them), 'desktop' or 'off'. */ |
| 682 | setGestures: (mode: GestureMode) => setGestures(mode), |
| 683 | /** Where the client draws the message time: 'caption' (default), 'corner' or 'corner-rtl'; live, and for the next widget. */ |
| 684 | setTimeCorner: (mode: TimeMode) => setTimeCorner(mode), |
| 685 | /** Any content safe area (docs/sdk-v1.md §2.17), drawn and passed as the time control's are; null = back to the control's. */ |
| 686 | setSafeArea: (area: Partial<ContentSafeArea> | null) => setTimeCorner(null, area), |
| 687 | /** Force the widget's visibility (null = back to the IntersectionObserver / page visibility). */ |
| 688 | setVisible: (v: boolean | null) => { forcedVisible = v; applyVisibility(); }, |
| 689 | /** The Web Storage the dev app keeps for a file (`local` survives a page reload), and forgetting it. */ |
| 690 | storage: (file: string | null = state.file) => storageFor(file), |
| 691 | clearStorage: (file: string | null = state.file) => clearStorage(file), |
| 692 | get host() { return host; }, |
| 693 | /** Native renderers only: a tap at CSS px inside the bubble, hit-tested by the native document (the runners cannot click into a canvas). */ |
| 694 | tap: (x: number, y: number) => { const r = BlitzRenderer.current ?? LitehtmlRenderer.current; if (r) { r.touch(0, x, y); r.touch |
| 695 | /** Blitz renderer only: paint statistics. */ |
| 696 | get blitz() { return BlitzRenderer.current?.stats ?? null; }, |
| 697 | /** litehtml renderer only: paint statistics. */ |
| 698 | get litehtml() { return LitehtmlRenderer.current?.stats ?? null; }, |
| 699 | /** Compare mode: the extra hosts (the renderers the main bubble is not using). */ |
| 700 | get compareHosts() { return compareHosts; }, |
| 701 | /** `?pool=N`: the worker pool's counters. */ |
| 702 | get pool() { return workerPool ? { size: workerPool.size, warm: workerPool.warm, ...workerPool.stats } : null; }, |
| 703 | /** `?feed=1`: the chat feed demo's API (src/feed.ts); null otherwise. */ |
| 704 | feed: null as FeedApi | null, |
| 705 | /** |
| 706 | * The mock bot (mock-bot.ts): `bot.bot` (echo, poll, tictactoe, ticker, promo), `bot.mode` (bot, manual, TIMEOUT, |
| 707 | * RATE_LIMITED, FAILED), `bot.delayMs`, `bot.context` (then `restart()`), `bot.requests`, `bot.dataFor(file)`, |
| 708 | * `bot.edit(file, { chatData, publicData })`, `bot.answer(record)` / `bot.fail(record, code)` for manual answers. |
| 709 | */ |
| 710 | bot, |
| 711 | /** Set the client's context for the widget (the kind of message: its server flags; the chat type; the viewer) and re-create it. */ |
| 712 | setContext: (patch: Partial<MockBot['context']>) => { Object.assign(bot.context, patch); renderBot(); if (state.html) load(state.html, state.file); else syncUrl(); }, |
| 713 | }; |
| 714 | |
| 715 | init().catch((e) => { el.status.textContent = String(e); }); |
| 716 | |