| 1 | // SDK v1 on the web host (docs/sdk-v1.md): the theme variables on the |
| 2 | // renderer root, gesture claims, Web Storage across a restart, the client |
| 3 | // locale and the actions a tap produces, and the bot's data and requests (the bot's data, |
| 4 | // requests through the dev app's mock bot, copyText), on the iframe and the |
| 5 |
| 6 | // (packages/core/tests/unit/sdk.test.ts). |
| 7 |
| 8 | import { expect, test, type Locator, type Page } from '@playwright/test'; |
| 9 | import { PNG } from 'pngjs'; |
| 10 |
| 11 | test.skip(process.env.VITE_TW_POLICY === 'compat', 'user activation belongs to the strict policy'); |
| 12 |
| 13 | const tw = (page: Page) => page.evaluate(() => (window as any).__tw.state); |
| 14 |
| 15 | async function load(page: Page, html: string, opts: { shadow?: boolean; name?: string | null; query?: string } = {}) { |
| 16 | await page.goto('/' + (opts.query ?? (opts.shadow ? '?shadow=1' : ''))); |
| 17 | await page.evaluate(([h, n]) => (window as any).__tw.load(h, n), [html, opts.name ?? null] as const); |
| 18 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 19 | await page.waitForTimeout(100); |
| 20 | return opts.shadow ? page.locator('#sandbox-wrap .widget-shadow') : page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 21 | } |
| 22 | const css = (l: Locator, prop: string) => l.evaluate((e, p) => getComputedStyle(e).getPropertyValue(p).trim(), prop); |
| 23 |
| 24 | const THEME_WIDGET = `<style> |
| 25 | :root { --tg-theme-bg-color: #ff0000 !important; } |
| 26 | html:root:root { --tg-theme-text-color: #ff0000 !important; } |
| 27 | #inner { --tg-theme-link-color: #123456; } |
| 28 | </style> |
| 29 | <div id="probe">probe</div><div id="inner"><span id="shadowed">x</span></div><p id="seen"></p> |
| 30 | <script> |
| 31 | document.documentElement.style.setProperty('--tg-theme-hint-color', '#00ff00', 'important'); |
| 32 | function show() { document.getElementById('seen').textContent = TelegramWidget.colorScheme + ' ' + TelegramWidget.themeParams.bg_color; } |
| 33 | TelegramWidget.onEvent('themeChanged', show); |
| 34 | show(); |
| 35 | </script>`; |
| 36 |
| 37 | for (const shadow of [false, true]) { |
| 38 | const renderer = shadow ? 'shadow' : 'iframe'; |
| 39 |
| 40 | test(`${renderer}: the theme variables are on the root, the widget cannot override them there, only shadow them`, async ({ page }) => { |
| 41 | const root = await load(page, THEME_WIDGET, { shadow }); |
| 42 | const probe = root.locator('#probe'); |
| 43 | expect(await css(probe, '--tg-theme-bg-color')).toBe('#ffffff'); |
| 44 | expect(await css(probe, '--tg-theme-text-color')).toBe('#000000'); |
| 45 | expect(await css(probe, '--tg-theme-hint-color')).toBe('#707579'); |
| 46 | expect(await css(probe, '--tg-color-scheme')).toBe('light'); |
| 47 | expect(await css(root.locator('#shadowed'), '--tg-theme-link-color')).toBe('#123456'); |
| 48 | await expect(root.locator('#seen')).toHaveText('light #ffffff'); |
| 49 |
| 50 | await page.evaluate(() => (window as any).__tw.setTheme('dark')); |
| 51 | await expect(root.locator('#seen')).toHaveText('dark #212121'); |
| 52 | expect(await css(probe, '--tg-theme-bg-color')).toBe('#212121'); |
| 53 | expect(await css(probe, '--tg-color-scheme')).toBe('dark'); |
| 54 | }); |
| 55 |
| 56 | test(`${renderer}: a theme with params and button tokens reaches the widget and the root`, async ({ page }) => { |
| 57 | const root = await load(page, THEME_WIDGET, { shadow }); |
| 58 | await page.evaluate(() => (window as any).__tw.host.setTheme({ colorScheme: 'light', params: { bg_color: '#FAFAFA', button_color: 'blue' }, button: { radius: '12px', font: '15px Helvetica' } })); |
| 59 | await expect(root.locator('#seen')).toHaveText('light #fafafa'); |
| 60 | const probe = root.locator('#probe'); |
| 61 | expect(await css(probe, '--tg-theme-bg-color')).toBe('#fafafa'); |
| 62 | expect(await css(probe, '--tg-theme-button-color')).toBe('#3390ec'); |
| 63 | expect(await css(probe, '--tg-button-radius')).toBe('12px'); |
| 64 | expect(await css(probe, '--tg-button-font')).toBe(''); |
| 65 | }); |
| 66 |
| 67 | test(`${renderer}: the UA layer draws an unstyled widget on the text tokens, the bubble behind it; author CSS wins`, async ({ page }) => { |
| 68 | const root = await load(page, `<h1 id="h">Title</h1><p id="p">Text <a id="a" href="https://telegram.org">link</a></p><ul id="ul"><li>x</li></ul>`, { shadow }); |
| 69 | const html = shadow ? root.locator('html') : root; |
| 70 | const body = root.locator('body'); |
| 71 | const h = root.locator('#h'); |
| 72 | // no background of its own: the bubble behind the transparent renderer is the canvas |
| 73 | expect(await css(html, 'background-color')).toBe('rgba(0, 0, 0, 0)'); |
| 74 | expect(await css(html, 'color')).toBe('rgb(0, 0, 0)'); |
| 75 | expect([await css(html, 'font-size'), await css(html, 'line-height')]).toEqual(['15px', '20.25px']); |
| 76 | expect([await css(body, 'margin'), await css(body, 'padding')]).toEqual(['8px 12px', '0px']); |
| 77 | expect([await css(h, 'font-size'), await css(h, 'margin-top'), await css(h, 'font-weight')]).toEqual(['24px', '0px', '600']); |
| 78 | expect(await css(root.locator('#a'), 'color')).toBe('rgb(51, 144, 236)'); |
| 79 | expect(await css(root.locator('#ul'), 'padding-left')).toBe('22.5px'); |
| 80 | expect(await css(h, '--tg-text-font-size')).toBe('15px'); |
| 81 | const height = (await tw(page)).height; |
| 82 |
| 83 | await page.evaluate(() => (window as any).__tw.host.setTheme({ colorScheme: 'dark', params: { bg_color: '#101820' }, text: { fontSize: 18, lineHeight: 1.5, padding: '4px 6px' } })); |
| 84 | await expect.poll(() => css(html, 'font-size')).toBe('18px'); |
| 85 | expect(await css(html, '--tg-theme-bg-color')).toBe('#101820'); |
| 86 | expect(await css(html, 'background-color')).toBe('rgba(0, 0, 0, 0)'); |
| 87 | expect(await css(html, 'color')).toBe('rgb(255, 255, 255)'); |
| 88 | expect(await css(html, 'line-height')).toBe('27px'); |
| 89 | expect(await css(body, 'margin')).toBe('4px 6px'); |
| 90 | expect(await css(h, 'font-size')).toBe('28.8px'); |
| 91 | await expect.poll(async () => (await tw(page)).height).toBeGreaterThan(height); |
| 92 |
| 93 | await page.evaluate(() => (window as any).__tw.host.setTheme({ colorScheme: 'light', text: { fontSize: 100, lineHeight: '2em', padding: 'auto' } })); |
| 94 | await expect.poll(() => css(html, 'font-size')).toBe('15px'); |
| 95 | expect([await css(html, 'line-height'), await css(body, 'margin')]).toEqual(['20.25px', '8px 12px']); |
| 96 |
| 97 | const styled = await load(page, `<style>body { margin: 0 } h1 { margin-top: 5px; font-size: 10px } a { color: #ff0000 }</style><h1 id="h">T</h1><a id="a" href="https://telegram.org">l</a>`, { shadow }); |
| 98 | expect(await css(styled.locator('body'), 'margin')).toBe('0px'); |
| 99 | expect([await css(styled.locator('#h'), 'margin-top'), await css(styled.locator('#h'), 'font-size')]).toEqual(['5px', '10px']); |
| 100 | expect(await css(styled.locator('#a'), 'color')).toBe('rgb(255, 0, 0)'); |
| 101 | }); |
| 102 |
| 103 | test(`${renderer}: a body background reaches the whole bubble, its margins included (root background propagation)`, async ({ page }) => { |
| 104 | await load(page, `<style>body { background: #2b5278; color: #fff }</style><p>Body background, no margin reset.</p>`, { shadow }); |
| 105 | const frame = page.locator('#sandbox-wrap .widget-frame'); |
| 106 | const box = (await frame.boundingBox())!; |
| 107 | // pixels in the body's margins (12 px at the sides, 8 px at the top), away from the bubble's rounded corners |
| 108 | const shot = await page.screenshot({ clip: { x: box.x, y: box.y, width: box.width, height: Math.min(box.height, 40) } }); |
| 109 | const png = PNG.sync.read(shot); |
| 110 | const at = (x: number, y: number) => { const i = (y * png.width + x) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; }; |
| 111 | const scale = png.width / box.width; |
| 112 | for (const [x, y] of [[3, 20], [Math.round(box.width / 2), 3], [Math.round(box.width) - 3, 20]]) expect(at(Math.round(x * scale), Math.round(y * scale)), `${x},${y}`).toEqual([0x2b, 0x52, 0x78]); |
| 113 | }); |
| 114 |
| 115 | test(`${renderer}: the demo bubble is the canvas: a body background fills it to the rounded corners (visual/15-body-background)`, async ({ page }) => { |
| 116 | for (const theme of ['light', 'dark'] as const) { |
| 117 | const q = new URLSearchParams({ file: 'conformance/visual/15-body-background.html', ...(shadow ? { shadow: '1' } : {}), ...(theme === 'dark' ? { theme: 'dark' } : {}) }); |
| 118 | await page.goto('/?' + q); |
| 119 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 120 | await page.waitForTimeout(300); |
| 121 | // The whole bubble the dev app draws, not only the renderer's element: a padded bubble would leave a strip of its own colour. |
| 122 | const bubble = page.locator('#sandbox-wrap').locator('xpath=..'); |
| 123 | const png = PNG.sync.read(await bubble.screenshot()); |
| 124 | const at = (x: number, y: number) => { const i = (y * png.width + x) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; }; |
| 125 | const w = png.width, h = png.height, s = Math.round(png.width / ((await bubble.boundingBox())!.width)); |
| 126 | const blue = [0x2b, 0x52, 0x78]; |
| 127 | // just inside the 14 px radius at each corner, and the middle of each edge |
| 128 | for (const [x, y] of [[6, 6], [w / s - 7, 6], [6, h / s - 7], [w / s - 7, h / s - 7], [w / s / 2, 1], [1, h / s / 2], [w / s - 2, h / s / 2], [w / s / 2, h / s - 2]]) { |
| 129 | expect(at(Math.round(x * s), Math.round(y * s)), `${theme} ${x},${y}`).toEqual(blue); |
| 130 | } |
| 131 | // the very corner is outside the radius: clipped, not blue |
| 132 | expect(at(0, 0), `${theme} corner`).not.toEqual(blue); |
| 133 | } |
| 134 | }); |
| 135 |
| 136 | test(`${renderer}: an unstyled widget sits on the bubble's own colour in both themes (the renderer stays transparent)`, async ({ page }) => { |
| 137 | for (const theme of ['light', 'dark'] as const) { |
| 138 | const q = new URLSearchParams({ file: 'defaults/static/01-text-card.html', ...(shadow ? { shadow: '1' } : {}), ...(theme === 'dark' ? { theme: 'dark' } : {}) }); |
| 139 | await page.goto('/?' + q); |
| 140 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 141 | await page.waitForTimeout(300); |
| 142 | const bubble = page.locator('#sandbox-wrap').locator('xpath=..'); |
| 143 | const png = PNG.sync.read(await bubble.screenshot()); |
| 144 | const at = (x: number, y: number) => { const i = (y * png.width + x) * 4; return [png.data[i], png.data[i + 1], png.data[i + 2]]; }; |
| 145 | const s = Math.round(png.width / ((await bubble.boundingBox())!.width)); |
| 146 | const want = theme === 'dark' ? [0x21, 0x21, 0x21] : [0xff, 0xff, 0xff]; |
| 147 | // in the body's margin: the bubble's colour shows through the renderer, never a canvas of the renderer's own |
| 148 | for (const [x, y] of [[6, 6], [png.width / s - 7, png.height / s - 4], [png.width / s / 2, 3]]) expect(at(Math.round(x * s), Math.round(y * s)), `${theme} ${x},${y}`).toEqual(want); |
| 149 | } |
| 150 | }); |
| 151 |
| 152 | test(`${renderer}: text is not selectable by default; user-select: text enables it, children included`, async ({ page }) => { |
| 153 | const root = await load(page, `<p id="off">This text cannot be selected.</p><p id="on" style="user-select: text; -webkit-user-select: text">This text <b id="kid">can</b> be selected.</p>`, { shadow }); |
| 154 | // The renderer frame is sandboxed (an opaque origin): read its selection through Playwright, not from the page. |
| 155 | const frame = shadow ? null : await (await page.locator('#sandbox-wrap iframe').elementHandle())!.contentFrame(); |
| 156 | const selected = () => frame ? frame.evaluate(() => getSelection()!.toString()) : page.evaluate(() => { |
| 157 | const host = document.querySelector('#sandbox-wrap .widget-shadow')!; |
| 158 | const r = (host.shadowRoot as any).getSelection?.() ?? document.getSelection(); |
| 159 | return r ? r.toString() : ''; |
| 160 | }); |
| 161 | const drag = async (sel: string) => { |
| 162 | const b = (await root.locator(sel).boundingBox())!; |
| 163 | await page.mouse.move(b.x + 2, b.y + b.height / 2); |
| 164 | await page.mouse.down(); |
| 165 | await page.mouse.move(b.x + b.width - 2, b.y + b.height / 2, { steps: 8 }); |
| 166 | await page.mouse.up(); |
| 167 | }; |
| 168 | // Blink inherits user-select; the spec's `auto` would follow the parent to the same used value |
| 169 | expect(await css(root.locator('#off'), 'user-select')).toMatch(/^(none|auto)$/); |
| 170 | expect(await css(root.locator('#on'), 'user-select')).toBe('text'); |
| 171 | expect(await css(root.locator('#kid'), 'user-select')).toMatch(/^(text|auto)$/); |
| 172 | await drag('#off'); |
| 173 | expect(await selected()).toBe(''); |
| 174 | await drag('#on'); |
| 175 | expect(await selected()).toContain('can be selected'); |
| 176 | }); |
| 177 |
| 178 | test(`${renderer}: each primary pointerdown reports the horizontal drags and holds the widget takes (never vertical ones)`, async ({ page }) => { |
| 179 | const root = await load(page, `<style>div { height: 30px; margin: 4px; background: #ddd; }</style> |
| 180 | <div id="none" style="touch-action: none">none</div><div id="pany" style="touch-action: pan-y">pan-y</div> |
| 181 | <div id="panx" style="touch-action: pan-x">pan-x</div><div id="auto">auto</div> |
| 182 | <div id="pd">prevented</div><script>document.getElementById('pd').addEventListener('pointerdown', function (e) { e.preventDefault(); });</script>`, { shadow }); |
| 183 | for (const id of ['none', 'pany', 'panx', 'auto', 'pd', 'pd']) await root.locator('#' + id).click(); |
| 184 | await expect.poll(async () => (await tw(page)).gestures.length).toBe(6); |
| 185 | const gestures = (await tw(page)).gestures as { x: boolean; y: boolean; hold: boolean }[]; |
| 186 | // The first press on #pd teaches the renderer that the widget prevents it; the second one claims horizontal drags |
| 187 | // (never holds). No claim has vertical drags since v0.1.3: pan-x claims nothing, none horizontal drags and holds. |
| 188 | const c = (x: boolean, hold = false) => ({ x, y: false, hold }); |
| 189 | expect(gestures).toEqual([c(true, true), c(true), c(false), c(false), c(false), c(true)]); |
| 190 | }); |
| 191 |
| 192 | test(`${renderer}: setResizeAnchor reaches the host with the height, and the dev app keeps the anchored edge`, async ({ page }) => { |
| 193 | // Taller than the 50 px minimum from the start: the anchor reaches the client with a size report (the height's). |
| 194 | const root = await load(page, `<style>body{margin:0}#g div{height:40px}</style><button id="b">grow</button><button id="t">top</button><div id="g"><div></div></div><script> |
| 195 | TelegramWidget.setResizeAnchor('bottom'); |
| 196 | document.getElementById('b').addEventListener('click', function () { document.getElementById('g').appendChild(document.createElement('div')); }); |
| 197 | document.getElementById('t').addEventListener('click', function () { TelegramWidget.setResizeAnchor('top'); }); |
| 198 | </script>`, { shadow }); |
| 199 | const bubble = () => page.locator('#chat-sandbox .bubble').evaluate((e) => { const r = e.getBoundingClientRect(); return { top: Math.round(r.top), bottom: Math.round(r.bottom) }; }); |
| 200 | await expect.poll(async () => (await tw(page)).resizeAnchor).toBe('bottom'); |
| 201 | const before = await bubble(), h0 = (await tw(page)).height; |
| 202 | await root.locator('#b').click(); |
| 203 | await expect.poll(async () => (await tw(page)).height).toBe(h0 + 40); |
| 204 | const after = await bubble(); |
| 205 | // Anchored at the bottom: the bottom edge stays, the bubble grows upward. |
| 206 | expect(after.bottom).toBe(before.bottom); |
| 207 | expect(after.top).toBe(before.top - 40); |
| 208 | expect((await tw(page)).bridge.map((b: { method: string }) => b.method)).not.toContain('setResizeAnchor'); |
| 209 | expect((await tw(page)).actions).toEqual([]); |
| 210 | await root.locator('#t').click(); |
| 211 | await root.locator('#b').click(); |
| 212 | await expect.poll(async () => (await tw(page)).height).toBe(h0 + 80); |
| 213 | expect((await tw(page)).resizeAnchor).toBe('top'); |
| 214 | }); |
| 215 |
| 216 | test(`${renderer}: a widget that never calls setResizeAnchor grows downward (top)`, async ({ page }) => { |
| 217 | await load(page, '<p>x</p>', { shadow }); |
| 218 | expect((await tw(page)).resizeAnchor).toBe('top'); |
| 219 | }); |
| 220 |
| 221 | test(`${renderer}: a tap opens one link and plays haptics; the actions reach the client`, async ({ page }) => { |
| 222 | const root = await load(page, `<button id="b">go</button><a id="t" href="https://t.me/durov">t</a><script> |
| 223 | document.getElementById('b').addEventListener('click', function () { |
| 224 | TelegramWidget.HapticFeedback.impactOccurred('light'); |
| 225 | TelegramWidget.openLink('https://Example.com/é'); |
| 226 | TelegramWidget.openLink('https://example.com/second'); |
| 227 | });</script>`, { shadow }); |
| 228 | await root.locator('#b').click(); |
| 229 | await root.locator('#t').click(); |
| 230 | await expect.poll(async () => (await tw(page)).actions.length).toBe(3); |
| 231 | expect((await tw(page)).actions).toEqual([ |
| 232 | { kind: 'haptic', haptic: 'impact', value: 'light' }, |
| 233 | { kind: 'openLink', url: 'https://example.com/%C3%A9' }, |
| 234 | { kind: 'openTelegramLink', url: 'https://t.me/durov' }, |
| 235 | ]); |
| 236 | expect((await tw(page)).diags['activation-blocked']?.count).toBe(1); |
| 237 | }); |
| 238 |
| 239 | // ───────────── the bot's data, requests, copyText (docs/sdk-v1.md §2.13–§2.15; the dev app's mock bot) ───────────── |
| 240 |
| 241 | const REQUEST_WIDGET = `<button id="b">ask</button><p id="out"></p><p id="data"></p><script> |
| 242 | var T = TelegramWidget, out = document.getElementById('out'); |
| 243 | function show() { document.getElementById('data').textContent = [T.chatData, T.publicData, T.isForward, T.chatType, T.viewer && T.viewer.id].join('|'); } |
| 244 | T.onEvent('chatDataChanged', show); |
| 245 | T.onEvent('publicDataChanged', show); |
| 246 | show(); |
| 247 | document.getElementById('b').addEventListener('click', function () { |
| 248 | T.request('hello').then(function (a) { out.textContent = 'ok ' + a.result; }, function (e) { out.textContent = 'err ' + e.code; }); |
| 249 | T.copyText('never: the request took the tap'); |
| 250 | }); |
| 251 | setTimeout(function () { T.request('timer').catch(function (e) { out.textContent = 'timer ' + e.code; }); }, 30); |
| 252 | </script>`; |
| 253 | const withContext = async (page: Page, patch: Record<string, unknown>) => { |
| 254 | await page.goto('/' + (shadow ? '?shadow=1' : '')); |
| 255 | await page.evaluate((p) => { const tw = (window as any).__tw; Object.assign(tw.bot.context, p); tw.bot.bot = 'echo'; tw.bot.delayMs = 50; }, patch); |
| 256 | }; |
| 257 | const open = async (page: Page, html: string, name: string) => { |
| 258 | await page.evaluate(([h, n]) => (window as any).__tw.load(h, n), [html, name] as const); |
| 259 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 260 | return shadow ? page.locator('#sandbox-wrap .widget-shadow') : page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 261 | }; |
| 262 |
| 263 | test(`${renderer}: a tap sends one request to the bot and gets its result; a timer cannot (a group); the bot's edit fires the data events`, async ({ page }) => { |
| 264 | await withContext(page, { message: 'group', chatType: 'supergroup', viewer: 1001 }); |
| 265 | const root = await open(page, REQUEST_WIDGET, 'sdk/request.html'); |
| 266 | await expect(page.locator('#net-marker')).toBeVisible(); |
| 267 | await expect(root.locator('#data')).toHaveText('||false|supergroup|1001'); |
| 268 | await expect(root.locator('#out')).toHaveText('timer NOT_ALLOWED'); |
| 269 | await root.locator('#b').click(); |
| 270 | await expect(root.locator('#out')).toHaveText('ok hello'); |
| 271 | const state = await tw(page); |
| 272 | expect(state.requests.map((r: any) => [r.data, r.answer?.result])).toEqual([['hello', 'hello']]); |
| 273 | expect(state.copiedTexts).toEqual([]); |
| 274 | expect(state.diags['request-blocked']?.count).toBe(1); |
| 275 | expect(state.diags['activation-blocked']?.count).toBe(1); |
| 276 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/request.html', { chatData: '{"turn":2}', publicData: 'score 1:0' })); |
| 277 | await expect(root.locator('#data')).toHaveText('{"turn":2}|score 1:0|false|supergroup|1001'); |
| 278 | }); |
| 279 |
| 280 | test(`${renderer}: a forwarded copy without fwd_allow_queries knows only publicData and cannot request, even with a tap; its publicData can change`, async ({ page }) => { |
| 281 | await withContext(page, { message: 'copy', chatType: null, viewer: 1001 }); |
| 282 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/copy.html', { chatData: 'secret', publicData: 'snapshot' })); |
| 283 | const root = await open(page, REQUEST_WIDGET, 'sdk/copy.html'); |
| 284 | await expect(page.locator('#net-marker')).toBeHidden(); |
| 285 | await expect(root.locator('#data')).toHaveText('|snapshot|true||'); |
| 286 | await root.locator('#b').click(); |
| 287 | await expect(root.locator('#out')).toHaveText('err NOT_ALLOWED'); |
| 288 | expect((await tw(page)).requests).toEqual([]); |
| 289 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/copy.html', { chatData: 'secret 2', publicData: 'shared value' })); |
| 290 | await expect(root.locator('#data')).toHaveText('|shared value|true||'); |
| 291 | }); |
| 292 |
| 293 | test(`${renderer}: the client polls a shared widget's publicData only while it watches (watchPublicData); otherwise it comes with the message`, async ({ page }) => { |
| 294 | await withContext(page, { message: 'private', chatType: null, viewer: 1001 }); |
| 295 | await page.evaluate(() => Object.assign((window as any).__tw.bot, { pollMs: 100, shared: true })); |
| 296 | const html = (watch: boolean) => `<p id="p"></p><script>${watch ? 'TelegramWidget.watchPublicData();' : ''} |
| 297 | function show() { document.getElementById('p').textContent = String(TelegramWidget.publicData); } |
| 298 | TelegramWidget.onEvent('publicDataChanged', show); show();</script>`; |
| 299 | let root = await open(page, html(true), 'sdk/watch.html'); |
| 300 | await expect(root.locator('#p')).toHaveText('null'); |
| 301 | await page.evaluate(() => (window as any).__tw.bot.editShared('sdk/watch.html', 'v2')); |
| 302 | await expect(root.locator('#p')).toHaveText('v2'); |
| 303 | expect(await page.evaluate(() => (window as any).__tw.bot.watching)).toBe(true); |
| 304 | root = await open(page, html(false), 'sdk/still.html'); |
| 305 | await page.evaluate(() => (window as any).__tw.bot.editShared('sdk/still.html', 'v2')); |
| 306 | await page.waitForTimeout(500); |
| 307 | await expect(root.locator('#p')).toHaveText('null'); |
| 308 | expect(await page.evaluate(() => (window as any).__tw.bot.watching)).toBe(false); |
| 309 | root = await open(page, html(false), 'sdk/still.html'); |
| 310 | await expect(root.locator('#p')).toHaveText('v2'); |
| 311 | }); |
| 312 |
| 313 | test(`${renderer}: the viewer is a WebAppUser (id, names, username, Premium) where the widget may ask; a broken field is left out`, async ({ page }) => { |
| 314 | await withContext(page, { message: 'private', chatType: null, viewer: 1001, profile: 'Ann,Lee,ann_lee,premium' }); |
| 315 | const html = '<p id="v"></p><script>document.getElementById("v").textContent = JSON.stringify(TelegramWidget.viewer) + "|" + Object.isFrozen(TelegramWidget.viewer);</script>'; |
| 316 | let root = await open(page, html, 'sdk/viewer.html'); |
| 317 | await expect(root.locator('#v')).toHaveText('{"id":1001,"first_name":"Ann","last_name":"Lee","username":"ann_lee","is_premium":true}|true'); |
| 318 | await page.evaluate(() => Object.assign((window as any).__tw.bot.context, { message: 'group', profile: 'Ann,,a-b' })); |
| 319 | root = await open(page, html, 'sdk/viewer.html'); |
| 320 | await expect(root.locator('#v')).toHaveText('{"id":1001,"first_name":"Ann"}|true'); |
| 321 | expect((await tw(page)).diags['data-rejected']?.details).toEqual(['viewer.username: not 5–32 characters of A–Z, a–z, 0–9 and _; the widget does not see it']); |
| 322 | }); |
| 323 |
| 324 | test(`${renderer}: an original sent without allow_queries has its data and the chat but no viewer, cannot request, tap or not, and shows no network marker`, async ({ page }) => { |
| 325 | await withContext(page, { message: 'no-queries', chatType: null, viewer: 1001 }); |
| 326 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/no-queries.html', { chatData: 'mine', publicData: 'p' })); |
| 327 | const root = await open(page, REQUEST_WIDGET, 'sdk/no-queries.html'); |
| 328 | await expect(page.locator('#net-marker')).toBeHidden(); |
| 329 | await expect(root.locator('#data')).toHaveText('mine|p|false|private|'); |
| 330 | await expect(root.locator('#out')).toHaveText('timer NOT_ALLOWED'); |
| 331 | await root.locator('#b').click(); |
| 332 | await expect(root.locator('#out')).toHaveText('err NOT_ALLOWED'); |
| 333 | expect((await tw(page)).requests).toEqual([]); |
| 334 | }); |
| 335 |
| 336 | test(`${renderer}: a live copy (fwd_allow_queries) asks on a tap and knows the viewer, never the chat or chatData`, async ({ page }) => { |
| 337 | await withContext(page, { message: 'live-copy', chatType: null, viewer: 1001 }); |
| 338 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/live-copy.html', { chatData: 'secret', publicData: 'live' })); |
| 339 | const root = await open(page, REQUEST_WIDGET, 'sdk/live-copy.html'); |
| 340 | await expect(page.locator('#net-marker')).toBeVisible(); |
| 341 | await expect(root.locator('#data')).toHaveText('|live|true||1001'); |
| 342 | await expect(root.locator('#out')).toHaveText('timer NOT_ALLOWED'); |
| 343 | await root.locator('#b').click(); |
| 344 | await expect(root.locator('#out')).toHaveText('ok hello'); |
| 345 | expect((await tw(page)).requests.map((r: any) => r.data)).toEqual(['hello']); |
| 346 | }); |
| 347 |
| 348 | test(`${renderer}: a preview (an inline result not sent yet) has its data but gets no tap, asks nothing and knows no viewer`, async ({ page }) => { |
| 349 | await withContext(page, { message: 'preview', chatType: null, viewer: 1001 }); |
| 350 | await page.evaluate(() => (window as any).__tw.bot.edit('sdk/preview.html', { chatData: 'c', publicData: 'p' })); |
| 351 | const root = await open(page, `<button id="b" style="width:200px;height:60px">tap</button><p id="out"></p><p id="data"></p><script> |
| 352 | var T = TelegramWidget, taps = 0; |
| 353 | document.getElementById('data').textContent = [T.isPreview, T.chatData, T.publicData, T.chatType, T.viewer].join('|'); |
| 354 | document.getElementById('b').addEventListener('click', function () { taps++; document.getElementById('out').textContent = 'tapped ' + taps; T.copyText('x'); }); |
| 355 | T.request('boot').catch(function (e) { document.getElementById('out').textContent = 'boot ' + e.code; }); |
| 356 | </script>`, 'sdk/preview.html'); |
| 357 | await expect(root.locator('#data')).toHaveText('true|c|p||'); |
| 358 | await expect(page.locator('#net-marker')).toBeHidden(); |
| 359 | await expect(root.locator('#out')).toHaveText('boot NOT_ALLOWED'); |
| 360 | await root.locator('#b').click(); |
| 361 | await page.waitForTimeout(400); |
| 362 | await expect(root.locator('#out')).toHaveText('boot NOT_ALLOWED'); |
| 363 | const state = await tw(page); |
| 364 | expect(state.requests).toEqual([]); |
| 365 | expect(state.copiedTexts).toEqual([]); |
| 366 | expect(state.gestures).toEqual([]); |
| 367 | }); |
| 368 |
| 369 | test(`${renderer}: a failed request rejects with the client's code; copyText reaches the client with a toast`, async ({ page }) => { |
| 370 | await withContext(page, { message: 'group' }); |
| 371 | await page.evaluate(() => { (window as any).__tw.bot.mode = 'TIMEOUT'; }); |
| 372 | let root = await open(page, REQUEST_WIDGET, 'sdk/fail.html'); |
| 373 | await root.locator('#b').click(); |
| 374 | await expect(root.locator('#out')).toHaveText('err TIMEOUT'); |
| 375 | root = await open(page, `<button id="c">copy</button><script>document.getElementById('c').onclick = function () { TelegramWidget.copyText('PROMO-2026'); TelegramWidget.copyText('second'); };</script>`, 'sdk/copy-text.html'); |
| 376 | await root.locator('#c').click(); |
| 377 | await expect.poll(async () => (await tw(page)).copiedTexts).toEqual(['PROMO-2026']); |
| 378 | await expect(page.locator('#chat-sandbox .bubble-copied')).toHaveText('Copied: PROMO-2026'); |
| 379 | }); |
| 380 | } |
| 381 |
| 382 | test('the poll demo: a tap votes through the mock bot, the widget redraws from the edited chatData', async ({ page }) => { |
| 383 | await page.goto('/?file=interactive/01-poll.html'); |
| 384 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 385 | const root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 386 | await expect(root.locator('#hint')).toHaveText(/^9 votes/); |
| 387 | await root.locator('.opt').nth(2).click(); |
| 388 | await expect(root.locator('.opt').nth(2)).toHaveClass(/mine/); |
| 389 | await expect(root.locator('#hint')).toHaveText(/^10 votes/); |
| 390 | const data = await page.evaluate(() => (window as any).__tw.bot.dataFor('interactive/01-poll.html')); |
| 391 | expect(JSON.parse(data.chatData).u['1001']).toBe(2); |
| 392 | expect(data.publicData).toBe('{"v":[3,5,2]}'); |
| 393 | }); |
| 394 |
| 395 | test('the wallet demo: a tap pays through the client\'s wallet window, the bot gets the outcome; a decline is REJECTED; without the wallet the widget says so', async ({ page }) => { |
| 396 | await page.goto('/?file=interactive/05-wallet.html'); |
| 397 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 398 | const root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 399 | await root.locator('.item button').first().click(); |
| 400 | // The window is the client's, outside the bubble: the bot of the message and what is paid. |
| 401 | await expect(page.locator('.wallet-sheet')).toContainText('@shop_bot asks you to send'); |
| 402 | await expect(page.locator('.wallet-sheet')).toContainText('1.5 TON'); |
| 403 | await page.locator('#wallet-confirm').click(); |
| 404 | await expect(root.locator('#note')).toHaveText('Paid for Coffee. Thank you!'); |
| 405 | await expect(root.locator('#paid')).toHaveText('Paid: Coffee'); |
| 406 | let state = await tw(page); |
| 407 | expect(state.requests.map((r: any) => [r.data, r.kind])).toEqual([['pay:0', 'wallet'], ['paid:0', 'sendTransaction']]); |
| 408 | await root.locator('#terms').click(); |
| 409 | await expect(page.locator('.wallet-sheet pre')).toHaveText('I accept the Corner café terms of 30 October 2026.'); |
| 410 | await page.locator('#wallet-decline').click(); |
| 411 | await expect(root.locator('#note')).toHaveText('You declined in the wallet.'); |
| 412 | state = await tw(page); |
| 413 | expect(state.requests.at(-1)).toMatchObject({ data: 'terms', kind: 'signData', error: 'REJECTED' }); |
| 414 | await page.goto('/?file=interactive/05-wallet.html&wallet=0'); |
| 415 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 416 | await expect(root.locator('#note')).toHaveText('No wallet here: pay in the bot.'); |
| 417 | await root.locator('.item button').first().click(); |
| 418 | await expect(page.locator('.wallet-sheet')).toHaveCount(0); |
| 419 | expect((await tw(page)).requests).toEqual([]); |
| 420 | }); |
| 421 |
| 422 | test('background requests: allowed in the private chat with the bot (backgroundQuery) while visible, one at once, then one per 5 s', async ({ page }) => { |
| 423 | await page.goto('/'); |
| 424 | await page.evaluate(() => { const tw = (window as any).__tw; Object.assign(tw.bot.context, { message: 'private' }); tw.bot.bot = 'echo'; tw.bot.delayMs = 0; }); |
| 425 | await page.evaluate((h) => (window as any).__tw.load(h, 'sdk/background.html'), `<p id="log"></p><script> |
| 426 | var log = []; |
| 427 | function ask() { TelegramWidget.request('bg').then(function () { log.push('ok'); next(); }, function (e) { log.push(e.code); next(); }); } |
| 428 | function next() { document.getElementById('log').textContent = log.join(' '); if (log.length < 8) setTimeout(ask, 800); } |
| 429 | ask(); |
| 430 | </script>`); |
| 431 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 432 | const root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 433 | await expect(root.locator('#log')).toHaveText(/^ok( RATE_LIMITED){5,6} ok/, { timeout: 15_000 }); |
| 434 | expect((await tw(page)).requests).toHaveLength(2); |
| 435 | }); |
| 436 |
| 437 | test('background requests: the widget appearing on screen again may ask at once, before the 5 s are up', async ({ page }) => { |
| 438 | await page.goto('/'); |
| 439 | await page.evaluate(() => { const tw = (window as any).__tw; Object.assign(tw.bot.context, { message: 'private' }); tw.bot.bot = 'echo'; tw.bot.delayMs = 0; }); |
| 440 | await page.evaluate((h) => (window as any).__tw.load(h, 'sdk/background-show.html'), `<p id="log"></p><script> |
| 441 | var log = []; |
| 442 | function ask() { TelegramWidget.request('bg').then(function () { log.push('ok'); next(); }, function (e) { log.push(e.code); next(); }); } |
| 443 | function next() { document.getElementById('log').textContent = log.join(' '); if (log.length < 40) setTimeout(ask, 300); } |
| 444 | ask(); |
| 445 | </script>`); |
| 446 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 447 | const t0 = Date.now(); |
| 448 | const root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 449 | await expect(root.locator('#log')).toHaveText(/^ok RATE_LIMITED/); |
| 450 | await page.evaluate(() => (window as any).__tw.setVisible(false)); |
| 451 | // Off screen the next ask (its 300 ms timer fires at the hidden 1 Hz) waits in the host: no answer, nothing sent. |
| 452 | await page.waitForTimeout(1500); |
| 453 | const held = (await root.locator('#log').textContent()) ?? ''; |
| 454 | expect(held).not.toMatch(/NOT_ALLOWED|BUSY/); |
| 455 | expect((await tw(page)).requests).toHaveLength(1); |
| 456 | await page.evaluate(() => (window as any).__tw.setVisible(true)); |
| 457 | await expect.poll(async () => (await tw(page)).requests.length, { timeout: 3000 }).toBe(2); |
| 458 | await expect(root.locator('#log')).toHaveText(new RegExp('^' + held + ' ok')); |
| 459 | expect(Date.now() - t0).toBeLessThan(5000); |
| 460 | await page.evaluate(() => (window as any).__tw.setVisible(null)); |
| 461 | }); |
| 462 |
| 463 | test('background requests: one at boot off screen (as Telegram\'s clients create a bubble) goes out when the widget appears; one on activated is BUSY', async ({ page }) => { |
| 464 | await page.goto('/'); |
| 465 | // The bot takes 300 ms, as a real one does: the boot request is still in flight when the widget hears it is visible. |
| 466 | await page.evaluate(() => { const tw = (window as any).__tw; Object.assign(tw.bot.context, { message: 'private' }); tw.bot.bot = 'echo'; tw.bot.delayMs = 300; tw.setVisible(false); }); |
| 467 | await page.evaluate((h) => (window as any).__tw.load(h, 'sdk/background-boot.html'), `<p id="log"></p><p id="active"></p><script> |
| 468 | var log = []; |
| 469 | function ask(t) { TelegramWidget.request(t).then(function (a) { log.push(t + ':' + a.result); show(); }, function (e) { log.push(t + ':' + e.code); show(); }); } |
| 470 | function show() { document.getElementById('log').textContent = log.slice().sort().join(' '); } |
| 471 | document.getElementById('active').textContent = 'active ' + TelegramWidget.isActive; |
| 472 | TelegramWidget.onEvent('activated', function () { ask('activated'); }); |
| 473 | ask('boot'); |
| 474 | </script>`); |
| 475 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 476 | const root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 477 | await expect(root.locator('#active')).toHaveText('active false'); |
| 478 | await page.waitForTimeout(500); |
| 479 | await expect(root.locator('#log')).toHaveText(''); |
| 480 | expect((await tw(page)).requests).toEqual([]); |
| 481 | await page.evaluate(() => (window as any).__tw.setVisible(true)); |
| 482 | await expect(root.locator('#log')).toHaveText('activated:BUSY boot:boot'); |
| 483 | expect((await tw(page)).requests.map((r: any) => r.data)).toEqual(['boot']); |
| 484 | await page.evaluate(() => (window as any).__tw.setVisible(null)); |
| 485 | }); |
| 486 |
| 487 | test('Web Storage: the client keeps what the widget commits and preloads it after a restart and a reload', async ({ page }) => { |
| 488 | const widget = `<button id="b">+1</button><p id="n"></p><script> |
| 489 | var n = Number(localStorage.getItem('n') || 0), s = Number(sessionStorage.getItem('s') || 0); |
| 490 | function show() { document.getElementById('n').textContent = n + '/' + s; } |
| 491 | document.getElementById('b').addEventListener('click', function () { localStorage.setItem('n', String(++n)); sessionStorage.setItem('s', String(++s)); show(); }); |
| 492 | show();</script>`; |
| 493 | let root = await load(page, widget, { name: 'sdk/storage.html' }); |
| 494 | await page.evaluate(() => (window as any).__tw.clearStorage()); |
| 495 | root = await load(page, widget, { name: 'sdk/storage.html' }); |
| 496 | await expect(root.locator('#n')).toHaveText('0/0'); |
| 497 | await root.locator('#b').click(); |
| 498 | await root.locator('#b').click(); |
| 499 | await expect(root.locator('#n')).toHaveText('2/2'); |
| 500 | await page.evaluate(() => (window as any).__tw.restart()); |
| 501 | await page.waitForFunction(() => (window as any).__tw.state.loaded); |
| 502 | root = page.frameLocator('#sandbox-wrap iframe').locator(':root'); |
| 503 | await expect(root.locator('#n')).toHaveText('2/2'); |
| 504 | expect(await page.evaluate(() => (window as any).__tw.storage())).toEqual({ local: { n: '2' }, session: { s: '2' } }); |
| 505 | // A reload is an app restart: `local` survives, `session` does not. |
| 506 | root = await load(page, widget, { name: 'sdk/storage.html' }); |
| 507 | await expect(root.locator('#n')).toHaveText('2/0'); |
| 508 | }); |
| 509 |
| 510 | test('the client locale is navigator.language and the Intl default', async ({ page }) => { |
| 511 | const root = await load(page, `<p id="l"></p><script>document.getElementById('l').textContent = navigator.language + ' ' + (1234.5).toLocaleString();</script>`, { query: '?locale=ru' }); |
| 512 | await expect(root.locator('#l')).toHaveText('ru 1 234,5'); |
| 513 | }); |
| 514 |