diff options
Diffstat (limited to 'tools/feed-when-test.js')
| -rw-r--r-- | tools/feed-when-test.js | 134 |
1 files changed, 134 insertions, 0 deletions
diff --git a/tools/feed-when-test.js b/tools/feed-when-test.js new file mode 100644 index 0000000..d9baa50 --- /dev/null +++ b/tools/feed-when-test.js @@ -0,0 +1,134 @@ +// While the feed scrolls, a chip under the top bar says when the post at the +// top of the screen was written, and fades once the scrolling stops. +// Run: bun tools/feed-when-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; +import { noteEncode, npubEncode } from 'nostr-tools/nip19'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (name, condition, detail = '') => { + console.log(`${condition ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); + if (!condition) ok = false; +}; +const sk = generateSecretKey(), pk = getPublicKey(sk); +const otherKey = generateSecretKey(), other = getPublicKey(otherKey); +const now = Math.floor(Date.now() / 1000); +const event = (content, at, key = sk, kind = 1) => finalizeEvent({ kind, content, created_at: at, tags: [] }, key); +const origin = 'http://localhost:5299'; +// two hours apart: the feed spans days +const seeded = Array.from({ length: 45 }, (_, i) => event('Post ' + i + '\nEnough text to make each post a comfortable reading target, and a second line of it too.', now - 600 - i * 7200)); +const requested = new Map(); +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5299, fetch: async (req) => { + const path = new URL(req.url).pathname; + if (path === '/') return new Response(html, { headers: { 'content-type': 'text/html' } }); + if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); + requested.set(path, (requested.get(path) || 0) + 1); + const delay = 20; + await sleep(delay); + return new Response('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="100"><rect width="160" height="100" fill="teal"/></svg>', { + headers: { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=3600' }, + }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (e) => errors.push(String(e))); +await page.setViewport({ width: 390, height: 844 }); +await page.evaluateOnNewDocument((fixtures) => { + const sockets = []; + class FakeSocket extends EventTarget { + constructor(url) { + super(); this.url = url; this.readyState = 0; this.subs = new Map(); sockets.push(this); + setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0); + } + emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); } + message(data) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(data) })); } + send(raw) { + let m; try { m = JSON.parse(raw); } catch { return; } + if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; } + if (m[0] !== 'REQ') return; + const [_, id, filter] = m; + (window.__feedRequests ||= []).push(filter); + this.subs.set(id, filter); + let events = []; + if (filter.kinds?.includes(1) && !filter.since && !filter.until) events = window.__catchup || []; + setTimeout(() => { + if (!this.subs.has(id)) return; + for (const e of events) this.message(['EVENT', id, e]); + this.message(['EOSE', id]); + }, events.length ? 700 : 20); + } + close() { this.readyState = 3; this.emit('close', new Event('close')); } + } + Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }); + window.WebSocket = FakeSocket; + window.__inject = (e) => { + let count = 0; + for (const ws of sockets) for (const [id, f] of ws.subs) { + if (ws.readyState === 1 && f.kinds?.includes(1) && f.since) { ws.message(['EVENT', id, e]); count++; } + } + return count; + }; +}, {}); +const click = (text) => page.evaluate((text) => [...document.querySelectorAll('button')].find((e) => e.textContent.toLowerCase().includes(text))?.click(), text); +const row = (id) => `.notes-feed > [data-key="${id}"]`; +// the Feed is a tab in the bottom nav (it was a row on the chat home) +const feedTab = () => [...document.querySelectorAll('.app-nav-button')].find((b) => b.getAttribute('aria-label') === 'Feed'); +const snapshot = () => page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-zap-post]')].map((n) => { + const b = n.getBoundingClientRect(); + return { id: n.dataset.key, top: b.top, height: b.height, text: n.innerText, avatar: n.querySelector('.note-avatar')?.getAttribute('style') }; +})); +try { + await page.goto(origin); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload(); await sleep(300); + await click('create a new wallet'); await sleep(400); + await click('to import'); + await page.waitForSelector('textarea'); + const mnemonic = generateMnemonic(wordlist); + await page.type('textarea', mnemonic); + await click('open wallet'); + await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive')); + const base = cacheKeyFor(mnemonic + '\n'); + await page.evaluate(([base, pk, seeded, origin]) => { + localStorage.setItem(base + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(base + ':feedNotes', JSON.stringify(seeded)); + localStorage.setItem(base + ':profiles', JSON.stringify({ [pk]: { name: 'Cached Author', picture: origin + '/avatar.png', t: Date.now() } })); + localStorage.setItem('btc-wallet-feed:' + base, 'following'); // a wallet with no feed remembered opens on Popular + }, [base, pk, seeded, origin]); + await page.reload(); + await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive')); + await sleep(2000); + await page.evaluate((tab) => eval(tab)()?.click(), feedTab.toString()); + await page.waitForSelector('.notes-feed:not([data-booting]) > .row', { timeout: 15000 }); + await sleep(800); + await page.evaluate(() => scrollBy(0, 40)); await sleep(100); + check('no chip near the top of the feed', !(await page.$('.feed-when.on'))); + for (let i = 0; i < 12; i++) { await page.evaluate(() => scrollBy(0, 300)); await sleep(30); } + await sleep(100); + const shown = await page.evaluate(() => { + const el = document.querySelector('.feed-when.on'); + const top = document.querySelector('.brand-header').getBoundingClientRect().bottom; + const r = [...document.querySelectorAll('.notes-feed > .row[data-key]')].find((r) => r.getBoundingClientRect().bottom > top + 12); + return el && { text: el.textContent, key: r?.dataset.key, y: el.getBoundingClientRect().top, head: top }; + }); + const ev = shown && seeded.find((e) => e.id === shown.key); + check('the chip shows while scrolling, under the top bar', !!shown && shown.y >= shown.head, JSON.stringify(shown)); + const want = ev && await page.evaluate((s) => new Date(s * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }), ev.created_at); + check('...with the time of the post at the top of the screen', !!want && shown.text.includes(want), shown?.text + ' / ' + want); + check('...and how long ago', /ago|yesterday/i.test(shown?.text || ''), shown?.text); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); + await sleep(1700); + check('it fades once the scrolling stops', !(await page.$('.feed-when.on'))); + check('no page errors', !errors.length, errors.join('; ')); +} finally { + await browser.close(); + server.stop(true); +} +console.log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); |
