From 5989090d93119fd10c642db622986227e4ae1b03 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 20:15:06 -0700 Subject: Enlarge post text and use full width below author headers --- src/style.css | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/style.css') diff --git a/src/style.css b/src/style.css index 2facddc..6507ba5 100644 --- a/src/style.css +++ b/src/style.css @@ -626,6 +626,11 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; } /* The row under a post: reply, boost, quote, react, zap — spread across the post's full width so each is a comfortable target, quiet until one carries a count or you've used it. */ +.note-post { display: grid; grid-template-columns: 44px minmax(0, 1fr); gap: 8px 10px; align-items: center; } +.note-content { display: contents; } +.note-content > * { grid-column: 1 / -1; min-width: 0; } +.note-content > .note-header { grid-column: 2; grid-row: 1; } +.note-content > .note-text { font-size: 18px; line-height: 1.5; } .note-acts { margin-top: 8px; gap: 4px; width: min(100%, 340px); } .note-acts > .note-act { flex: 1 1 0; min-width: 0; justify-content: center; padding-inline: 2px; } /* server comparison table (Settings → Advanced → Ark server) */ -- cgit v1.2.3 From f95093a90637abfa9f0adbb3d7d28127ecd20569 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 20:22:06 -0700 Subject: Add scrolling feed navigation for home, messages and notifications --- src/features/messages.js | 27 +++++++++++++++- src/style.css | 18 +++++++++++ tools/feed-bottom-nav-test.js | 73 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 tools/feed-bottom-nav-test.js (limited to 'src/style.css') diff --git a/src/features/messages.js b/src/features/messages.js index 31a3e4d..3af968f 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -3472,6 +3472,9 @@ export function messagesFeature(ctx) { // only runs once a wallet opens. if (typeof window !== 'undefined') { window.addEventListener('scroll', () => { + // Update just the navigation visibility; scrolling must not repaint posts. + const nav = document.querySelector('.feed-bottom-nav'); + if (nav) nav.hidden = window.scrollY < 160; if (!ui.profilePk && (!(ui.chatOpen && ui.msgView === 'feed') || ui.noteThread)) return; windowScrolled(ui.profilePk ? notesCache.get(ui.profilePk) : feed); // back at the top by yourself: the new posts are under your eyes, so @@ -7524,6 +7527,27 @@ export function messagesFeature(ctx) { } catch {} }, 0); } + function feedBottomNav() { + const icon = (paths) => ''; + const button = (label, paths, onClick) => h('button', { + type: 'button', class: 'feed-nav-button', 'aria-label': label, onClick, + }, h('span', { html: icon(paths) }), h('span', {}, label)); + return h('nav', { + class: 'feed-bottom-nav', 'data-key': 'feed-bottom-nav', 'aria-label': t('feedTitle'), + hidden: typeof window === 'undefined' || window.scrollY < 160, + }, + button(t('home'), '', jumpToNew), + button(t('msgDmsTitle'), '', () => { + if (signinAsk()) return; + stopFeedWatch(); ui.msgView = 'home'; render(); + window.scrollTo({ top: 0 }); + }), + button(t('alertsTitle'), '', () => { + if (signinAsk()) return; + stopFeedWatch(); openNotifs(); + window.scrollTo({ top: 0 }); + })); + } function feedView() { syncFollowSets().catch(() => {}); // throttled inside syncReports().catch(() => {}); // likewise @@ -7563,7 +7587,7 @@ export function messagesFeature(ctx) { waiting === 1 ? t('feedOneNewWord') : t('feedNNewWord')) : null; // the chat shell draws the brand header; this is just the page under it - return h('div', { class: 'card col chat-page', style: 'gap:10px' }, + return h('div', { class: 'card col chat-page feed-page', style: 'gap:10px' }, h('div', { 'data-key': 'feed-notice', style: 'display:contents' }, pill), h('div', { class: 'row gap6', style: 'align-items:center' }, backBtn(() => { @@ -7618,6 +7642,7 @@ export function messagesFeature(ctx) { // the reader's language, right where a curated feed is judged by it ctx.languagePicker ? h('div', { class: 'row gap6 feed-lang', 'data-key': 'feed-lang', style: 'justify-content:center;align-items:center;padding:6px 0 2px' }, h('span', { class: 'small muted' }, t('feedLangLabel')), ctx.languagePicker()) : null, + feedBottomNav(), ...noteOverlays()); } diff --git a/src/style.css b/src/style.css index 6507ba5..d2ad443 100644 --- a/src/style.css +++ b/src/style.css @@ -770,6 +770,24 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } feed near the top, out of the way of the thumb, and takes you up to them when tapped. Fixed, not sticky: the feed is the page scroller, and a sticky element inside the card would scroll away with the card. */ +.feed-page { padding-bottom: calc(82px + env(safe-area-inset-bottom, 0px)); } +.feed-bottom-nav { + position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); + z-index: 30; display: flex; width: min(100%, 560px); box-sizing: border-box; + padding: 6px 12px calc(6px + env(safe-area-inset-bottom, 0px)); + background: var(--paper); border-top: 1px solid var(--line); + box-shadow: 0 -4px 18px rgba(0, 0, 0, .06); +} +.feed-bottom-nav[hidden] { display: none; } +.feed-nav-button { + display: flex; flex: 1; min-width: 0; flex-direction: column; align-items: center; + justify-content: center; gap: 3px; min-height: 52px; padding: 4px; + border: 0; background: transparent; color: var(--ink); font-size: 12px; +} +.feed-nav-button > span:first-child { display: flex; } +.feed-page:has(.feed-bottom-nav:not([hidden])) .feed-new-pill { + bottom: calc(env(safe-area-inset-bottom, 0px) + 82px); +} .feed-new-pill { /* Rides at the bottom of the window, where a thumb already is; the tap takes the reader up to the new posts. */ diff --git a/tools/feed-bottom-nav-test.js b/tools/feed-bottom-nav-test.js new file mode 100644 index 0000000..f277c4a --- /dev/null +++ b/tools/feed-bottom-nav-test.js @@ -0,0 +1,73 @@ +// Real feed/navigation views with local posts and no relay traffic. +// Run: bun tools/feed-bottom-nav-test.js +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer-core'; +const app = await Bun.file('src/app.js').text(); +const dom = app.slice(app.indexOf('function h(tag,'), app.indexOf("const root = document.getElementById('app');")); +const entry = ` +import { messagesFeature } from './src/features/messages.js'; +${dom} +const author = 'a'.repeat(64); +const ui = { screen: 'wallet', chatOpen: true, msgView: 'feed' }; +const wallet = { xpub: 'test-wallet', loaded: true, nostrRelays: () => [], + loadFeatureState: (k, d) => k === 'follows' ? { tags: [['p', author]], at: Date.now()/1000 } : d, + saveFeatureState() {}, registerCacheExtension() {} }; +let feature; +function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView()]); } +feature = messagesFeature({ h, ui, wallet, render, toast() {}, hook() {}, brandHeader: () => h('div', { style: 'height:60px' }, 'Coinos') }); +window.test = { ui, wallet, render, async feed() { + ui.chatOpen = true; ui.msgView = 'feed'; ui.noteThread = null; + await feature.testSeed(Array.from({length:20}, (_, i) => ({ id: i.toString(16).padStart(64,'0'), pubkey:author, kind:1, tags:[], created_at:Math.floor(Date.now()/1000)-i, + content: 'A post in the feed. Scroll to keep Home, messages and notifications within reach. '.repeat(3) }))); + render(); window.scrollTo(0,0); +}, unseen() { feature.testUnseen(); render(); } }; +await test.feed(); +`; +const bundle = await Bun.build({ entrypoints: ['nav-test-entry'], target: 'browser', plugins: [{ name: 'nav-test', setup(build) { + build.onResolve({filter:/^nav-test-entry$/},()=>({path:'entry',namespace:'nav-test'})); + build.onLoad({filter:/.*/,namespace:'nav-test'},()=>({contents:entry,loader:'js',resolveDir:process.cwd()})); + build.onLoad({filter:/src\/features\/messages\.js$/},async({path})=>({loader:'js',contents:(await Bun.file(path).text()).replace("id: 'messages',", "id: 'messages', testSeed: async (notes) => { const c = feedNow(); await c.boot; Object.assign(c, { notes, status: 'ready', booting: false, end: true, shown: 20 }); }, testUnseen: () => { feed.unseen = 2; },")})); + build.onLoad({filter:/src\/nostr\.js$/},async({path})=>({loader:'js',contents:(await Bun.file(path).text()) + .replace('export async function queryOn(relays, filter, maxWait = 1500) {','export async function queryOn(relays, filter, maxWait = 1500) { return [];') + .replace(/export function subscribeOn\(([^)]*)\) \{/,'export function subscribeOn($1) { return () => {};')})); +} }] }); +assert(bundle.success,bundle.logs.join('\n')); +const html=`
`; +const remote = !!process.env.BROWSER_URL; +const server=Bun.serve({port:remote ? 5303 : 0,fetch:()=>new Response(html,{headers:{'content-type':'text/html'}})}); +const browser=remote ? await puppeteer.connect({browserURL:process.env.BROWSER_URL}) : await puppeteer.launch({executablePath:'/usr/bin/google-chrome',headless:true,args:['--no-sandbox']}); +const page=await browser.newPage(), errors=[]; +page.on('pageerror', e=>errors.push(e.message)); +await page.setRequestInterception(true); +page.on('request',r=>r.url().startsWith(server.url.origin)?r.continue():r.abort()); +const scroll=async()=>{ await page.evaluate(()=>window.scrollTo(0,700)); await page.waitForFunction(()=>!document.querySelector('.feed-bottom-nav')?.hidden); }; +try { + await page.setViewport({width:390,height:844,isMobile:true,hasTouch:true}); + await page.emulateMediaFeatures([{name:'prefers-reduced-motion',value:'reduce'}]); + await page.goto(server.url.href); + await page.waitForSelector('.note-post', {timeout:5000}); + assert(await page.$eval('.feed-bottom-nav',e=>e.hidden),'hidden at top'); + await scroll(); + assert.deepEqual(await page.$$eval('.feed-nav-button',els=>els.map(e=>e.textContent)),['Home','Messages','Notifications']); + assert(await page.$eval('.feed-bottom-nav',e=>Math.abs(e.getBoundingClientRect().bottom-innerHeight)<1),'fixed at viewport bottom'); + await page.evaluate(()=>test.unseen()); + assert(await page.evaluate(()=>document.querySelector('.feed-new-pill').getBoundingClientRect().bottom < document.querySelector('.feed-bottom-nav').getBoundingClientRect().top),'new posts pill stays above navigation'); + await page.screenshot({path:'/tmp/feed-bottom-nav-mobile.png'}); + await page.tap('.feed-nav-button:nth-child(1)'); + await page.waitForFunction(()=>scrollY===0 && document.querySelector('.feed-bottom-nav').hidden); + assert.equal(await page.evaluate(()=>test.ui.msgView),'feed','Home stays in feed'); + await scroll(); await page.tap('.feed-nav-button:nth-child(2)'); + await page.waitForFunction(()=>test.ui.msgView==='home' && !document.querySelector('.feed-bottom-nav')); + assert((await page.evaluate(()=>document.body.innerText)).includes('Messages'),'chat list renders'); + await page.evaluate(()=>test.feed()); await scroll(); await page.tap('.feed-nav-button:nth-child(3)'); + await page.waitForFunction(()=>test.ui.msgView==='notifs' && !document.querySelector('.feed-bottom-nav')); + assert((await page.evaluate(()=>document.body.innerText)).includes('Notifications'),'notifications render'); + await page.evaluate(()=>test.feed()); await scroll(); await page.tap('.note-text'); + await page.waitForFunction(()=>!!test.ui.noteThread && !document.querySelector('.feed-bottom-nav')); + await page.evaluate(()=>test.feed()); + await page.evaluate(()=>{test.wallet.xpub=null;test.render();}); await scroll(); + await page.tap('.feed-nav-button:nth-child(2)'); + assert(await page.evaluate(()=>test.ui.signinAsk && test.ui.msgView==='feed'),'visitor gets sign-in prompt'); + assert.deepEqual(errors,[]); + console.log('✓ Feed nav appears on scroll; Home returns to top; Messages and Notifications open their views; nav leaves threads; visitor sign-in and new-post pill work'); +} finally { await page.close(); if (remote) await browser.disconnect(); else await browser.close(); server.stop(true); } -- cgit v1.2.3 From 59e6028b6e62820fcde93068347c44637b67c93d Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 21:03:31 -0700 Subject: Keep feed navigation visible and add a wallet shortcut --- src/features/messages.js | 10 ++++++---- src/style.css | 7 +++---- tools/feed-bottom-nav-test.js | 19 ++++++++++++++----- 3 files changed, 23 insertions(+), 13 deletions(-) (limited to 'src/style.css') diff --git a/src/features/messages.js b/src/features/messages.js index 3af968f..0b40a5a 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -3472,9 +3472,6 @@ export function messagesFeature(ctx) { // only runs once a wallet opens. if (typeof window !== 'undefined') { window.addEventListener('scroll', () => { - // Update just the navigation visibility; scrolling must not repaint posts. - const nav = document.querySelector('.feed-bottom-nav'); - if (nav) nav.hidden = window.scrollY < 160; if (!ui.profilePk && (!(ui.chatOpen && ui.msgView === 'feed') || ui.noteThread)) return; windowScrolled(ui.profilePk ? notesCache.get(ui.profilePk) : feed); // back at the top by yourself: the new posts are under your eyes, so @@ -7534,7 +7531,6 @@ export function messagesFeature(ctx) { }, h('span', { html: icon(paths) }), h('span', {}, label)); return h('nav', { class: 'feed-bottom-nav', 'data-key': 'feed-bottom-nav', 'aria-label': t('feedTitle'), - hidden: typeof window === 'undefined' || window.scrollY < 160, }, button(t('home'), '', jumpToNew), button(t('msgDmsTitle'), '', () => { @@ -7546,6 +7542,12 @@ export function messagesFeature(ctx) { if (signinAsk()) return; stopFeedWatch(); openNotifs(); window.scrollTo({ top: 0 }); + }), + button(t('settingsWallet'), '', () => { + if (isVisitor()) { toFrontDoor(); return; } + stopFeedWatch(); + ui.chatOpen = false; ui.msgView = null; ui.tab = 'receive'; + render(); window.scrollTo({ top: 0 }); })); } function feedView() { diff --git a/src/style.css b/src/style.css index d2ad443..3a8c036 100644 --- a/src/style.css +++ b/src/style.css @@ -774,18 +774,17 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } .feed-bottom-nav { position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); z-index: 30; display: flex; width: min(100%, 560px); box-sizing: border-box; - padding: 6px 12px calc(6px + env(safe-area-inset-bottom, 0px)); + padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--paper); border-top: 1px solid var(--line); box-shadow: 0 -4px 18px rgba(0, 0, 0, .06); } -.feed-bottom-nav[hidden] { display: none; } .feed-nav-button { display: flex; flex: 1; min-width: 0; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-height: 52px; padding: 4px; - border: 0; background: transparent; color: var(--ink); font-size: 12px; + border: 0; background: transparent; color: var(--ink); font-size: 11px; } .feed-nav-button > span:first-child { display: flex; } -.feed-page:has(.feed-bottom-nav:not([hidden])) .feed-new-pill { +.feed-page .feed-new-pill { bottom: calc(env(safe-area-inset-bottom, 0px) + 82px); } .feed-new-pill { diff --git a/tools/feed-bottom-nav-test.js b/tools/feed-bottom-nav-test.js index f277c4a..53b7529 100644 --- a/tools/feed-bottom-nav-test.js +++ b/tools/feed-bottom-nav-test.js @@ -13,7 +13,7 @@ const wallet = { xpub: 'test-wallet', loaded: true, nostrRelays: () => [], loadFeatureState: (k, d) => k === 'follows' ? { tags: [['p', author]], at: Date.now()/1000 } : d, saveFeatureState() {}, registerCacheExtension() {} }; let feature; -function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView()]); } +function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView() || h('div', { class: 'wallet-screen' }, 'Wallet')]); } feature = messagesFeature({ h, ui, wallet, render, toast() {}, hook() {}, brandHeader: () => h('div', { style: 'height:60px' }, 'Coinos') }); window.test = { ui, wallet, render, async feed() { ui.chatOpen = true; ui.msgView = 'feed'; ui.noteThread = null; @@ -46,15 +46,15 @@ try { await page.emulateMediaFeatures([{name:'prefers-reduced-motion',value:'reduce'}]); await page.goto(server.url.href); await page.waitForSelector('.note-post', {timeout:5000}); - assert(await page.$eval('.feed-bottom-nav',e=>e.hidden),'hidden at top'); + assert(await page.$eval('.feed-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'visible at top without scrolling'); await scroll(); - assert.deepEqual(await page.$$eval('.feed-nav-button',els=>els.map(e=>e.textContent)),['Home','Messages','Notifications']); + assert.deepEqual(await page.$$eval('.feed-nav-button',els=>els.map(e=>e.textContent)),['Home','Messages','Notifications','Wallet']); assert(await page.$eval('.feed-bottom-nav',e=>Math.abs(e.getBoundingClientRect().bottom-innerHeight)<1),'fixed at viewport bottom'); await page.evaluate(()=>test.unseen()); assert(await page.evaluate(()=>document.querySelector('.feed-new-pill').getBoundingClientRect().bottom < document.querySelector('.feed-bottom-nav').getBoundingClientRect().top),'new posts pill stays above navigation'); await page.screenshot({path:'/tmp/feed-bottom-nav-mobile.png'}); await page.tap('.feed-nav-button:nth-child(1)'); - await page.waitForFunction(()=>scrollY===0 && document.querySelector('.feed-bottom-nav').hidden); + await page.waitForFunction(()=>scrollY===0 && !document.querySelector('.feed-bottom-nav').hidden); assert.equal(await page.evaluate(()=>test.ui.msgView),'feed','Home stays in feed'); await scroll(); await page.tap('.feed-nav-button:nth-child(2)'); await page.waitForFunction(()=>test.ui.msgView==='home' && !document.querySelector('.feed-bottom-nav')); @@ -65,9 +65,18 @@ try { await page.evaluate(()=>test.feed()); await scroll(); await page.tap('.note-text'); await page.waitForFunction(()=>!!test.ui.noteThread && !document.querySelector('.feed-bottom-nav')); await page.evaluate(()=>test.feed()); + assert(await page.$eval('.feed-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'returning to feed restores nav immediately without a scroll'); + await page.evaluate(()=>{test.ui.tab='settings';}); + await page.tap('.feed-nav-button:nth-child(4)'); + await page.waitForSelector('.wallet-screen'); + assert(await page.evaluate(()=>!test.ui.chatOpen && test.ui.tab==='receive' && !document.querySelector('.feed-bottom-nav')),'Wallet opens main wallet instead of old settings tab'); + await page.evaluate(()=>test.feed()); + await page.setViewport({width:320,height:844,isMobile:true,hasTouch:true}); + assert(await page.$eval('.feed-bottom-nav',e=>e.scrollWidth<=e.clientWidth),'four buttons fit a narrow phone'); + await page.screenshot({path:'/tmp/feed-bottom-nav-always-mobile.png'}); await page.evaluate(()=>{test.wallet.xpub=null;test.render();}); await scroll(); await page.tap('.feed-nav-button:nth-child(2)'); assert(await page.evaluate(()=>test.ui.signinAsk && test.ui.msgView==='feed'),'visitor gets sign-in prompt'); assert.deepEqual(errors,[]); - console.log('✓ Feed nav appears on scroll; Home returns to top; Messages and Notifications open their views; nav leaves threads; visitor sign-in and new-post pill work'); + console.log('✓ Feed nav stays visible at top and on return; Home, Messages, Notifications and Wallet work; four buttons fit a narrow phone; threads, visitor sign-in and new-post pill work'); } finally { await page.close(); if (remote) await browser.disconnect(); else await browser.close(); server.stop(true); } -- cgit v1.2.3 From 292d5527cf36c119d74486061db3a44a608f5138 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 21:27:32 -0700 Subject: The bottom nav rides every page: Feed, Messages, Notifications, Wallet. It now shows across the signed-in app and a visitor's public pages (never over sign-in, onboarding or the lock prompt), marks the current page, and carries the unread dot. Home is renamed Feed, and the Messages button leaves the header. Co-Authored-By: Claude Opus 5.5 --- src/app.js | 24 ++++------------ src/features/messages.js | 47 ++++++++++++++++++++++---------- src/style.css | 13 ++++++--- tools/feed-bottom-nav-test.js | 62 +++++++++++++++++++++++------------------- tools/feed-wallet-back-test.js | 11 ++++---- 5 files changed, 87 insertions(+), 70 deletions(-) (limited to 'src/style.css') diff --git a/src/app.js b/src/app.js index 7dde883..5e3fba4 100644 --- a/src/app.js +++ b/src/app.js @@ -681,7 +681,11 @@ function renderInner() { ui.navAnimSkip = false; } applyAnim(screen, 'anim-page', (performance.now() - _navAt) < 340 ? performance.now() - _navAt : -1); - morphChildren(root, [screen, footer(), ...(ui.lightbox ? [imageViewer()] : [])]); + // The bottom nav rides every page of a signed-in wallet and a visitor's + // public pages — never over sign-in, onboarding or the lock prompt. + const navPage = ui.pubProf || (activeAccount() && ['wallet', 'accounts', 'accountSettings'].includes(ui.screen) && !(ui.onb || onbInProgress())); + const bottomNav = navPage && !lockAsk && !_bootDeciding ? featureHook('bottomNav') : null; + morphChildren(root, [screen, footer(), ...(bottomNav ? [bottomNav] : []), ...(ui.lightbox ? [imageViewer()] : [])]); promoteLazySrc(root); // sources on the nodes that actually made it into the page try { document.documentElement.classList.toggle('no-scroll', !!ui.lightbox); } catch {} if (fpath) { @@ -2488,23 +2492,6 @@ function lockBtn() { }, h('span', { style: 'font-size:15px;line-height:1;margin-right:6px' }, locked ? '\u{1F512}' : '\u{1F513}'), locked ? t('unlock') : t('lockWallet')); } -// Messages sit one tap away, left of the wallet selector. The dot is presence, -// not a count — it says "someone's waiting", and the chat list says who. -function messagesBtn() { - const me = (featureHook('nostrLoginIdentity') || {}).pubkey || (wallet.nostrPubkey && wallet.nostrPubkey()); - if (!me) return null; - const unread = featureHook('unreadMessages') || 0; - return h('button', { - class: 'header-msgs' + (unread ? ' unread' : ''), - title: t('msgDmsTitle'), - 'aria-label': t('msgDmsTitle'), - onClick: () => { clearFeatureNav(); ui.screen = 'wallet'; ui.chatOpen = true; ui.msgView = 'home'; render(); }, - }, h('span', { - class: 'hm-ico', - html: '', - })); -} - // Find anyone on nostr from the header — results open their profile. function searchBtn() { if (!featureHook('userSearchAvailable')) return null; @@ -2539,7 +2526,6 @@ function brandHeader(withLock) { withLock ? h('div', { class: 'row gap6', style: 'align-items:center' }, searchBtn(), - messagesBtn(), settingsBtn(), avatarMenu()) : ui.pubProf && !acc ? visitorButtons() : null diff --git a/src/features/messages.js b/src/features/messages.js index 0b40a5a..7be5f26 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -7524,28 +7524,47 @@ export function messagesFeature(ctx) { } catch {} }, 0); } - function feedBottomNav() { + function appBottomNav() { + const visitor = isVisitor(); + const active = ui.noteThread || ui.profilePk ? 'feed' : ui.chatOpen + ? ui.msgView === 'feed' ? 'feed' : ui.msgView === 'notifs' ? 'notifs' : 'messages' : 'wallet'; + const leavePage = () => { + stopFeedWatch(); stopNotifWatch(); + // Top-level destinations must leave any feature page covering the shell. + for (const key of ['profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'noteThread', 'userSearch', + 'zapSetup', 'hatShop', 'feedEdit', 'feedMenu', 'feedRelayEdit', 'noteSheet', 'reactPick', 'reportSheet', + 'msgReplyTo', 'msgSheet', 'arkCoinsPage', 'arkExitPage', 'nameEditOpen', 'nostrReconnect', 'nostrLoginOpen', + 'pos', 'lockedGift', 'viewGift', 'claimChoose', 'signinAsk']) ui[key] = null; + if (!visitor) { ui.screen = 'wallet'; ui.pubProf = null; } + }; const icon = (paths) => ''; - const button = (label, paths, onClick) => h('button', { - type: 'button', class: 'feed-nav-button', 'aria-label': label, onClick, + const button = (id, label, paths, onClick) => h('button', { + type: 'button', class: 'app-nav-button' + (id === 'messages' && !visitor && hook('unreadMessages') ? ' unread' : ''), + 'aria-label': label, 'aria-current': active === id ? 'page' : undefined, onClick, }, h('span', { html: icon(paths) }), h('span', {}, label)); return h('nav', { - class: 'feed-bottom-nav', 'data-key': 'feed-bottom-nav', 'aria-label': t('feedTitle'), + class: 'app-bottom-nav', 'data-key': 'app-bottom-nav', }, - button(t('home'), '', jumpToNew), - button(t('msgDmsTitle'), '', () => { - if (signinAsk()) return; - stopFeedWatch(); ui.msgView = 'home'; render(); + button('feed', t('feedTitle'), '', () => { + if (active === 'feed' && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread && !ui.feedEdit) { jumpToNew(); return; } + leavePage(); + if (visitor) { ui.pubProf = true; openFirehose(); } else showFeed(curFeedId); + window.scrollTo({ top: 0 }); + }), + button('messages', t('msgDmsTitle'), '', () => { + if (visitor) { toFrontDoor(); return; } + leavePage(); ui.chatOpen = true; ui.msgView = 'home'; render(); window.scrollTo({ top: 0 }); }), - button(t('alertsTitle'), '', () => { - if (signinAsk()) return; - stopFeedWatch(); openNotifs(); + button('notifs', t('alertsTitle'), '', () => { + if (visitor) { toFrontDoor(); return; } + leavePage(); openNotifs(); window.scrollTo({ top: 0 }); }), - button(t('settingsWallet'), '', () => { + button('wallet', t('settingsWallet'), '', () => { if (isVisitor()) { toFrontDoor(); return; } - stopFeedWatch(); + leavePage(); + ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null; ui.chatOpen = false; ui.msgView = null; ui.tab = 'receive'; render(); window.scrollTo({ top: 0 }); })); @@ -7644,7 +7663,6 @@ export function messagesFeature(ctx) { // the reader's language, right where a curated feed is judged by it ctx.languagePicker ? h('div', { class: 'row gap6 feed-lang', 'data-key': 'feed-lang', style: 'justify-content:center;align-items:center;padding:6px 0 2px' }, h('span', { class: 'small muted' }, t('feedLangLabel')), ctx.languagePicker()) : null, - feedBottomNav(), ...noteOverlays()); } @@ -9024,6 +9042,7 @@ export function messagesFeature(ctx) { if (!Object.keys(s.read || {}).length && !anyMsgs) return 1; return unreadCount(); }, + bottomNav: appBottomNav, notifySettingsCards() { return [notifyCard()]; }, screenView() { // A profile deep link mid-resolution holds the frame over EVERY screen diff --git a/src/style.css b/src/style.css index 3a8c036..9696e7b 100644 --- a/src/style.css +++ b/src/style.css @@ -770,20 +770,25 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } feed near the top, out of the way of the thumb, and takes you up to them when tapped. Fixed, not sticky: the feed is the page scroller, and a sticky element inside the card would scroll away with the card. */ -.feed-page { padding-bottom: calc(82px + env(safe-area-inset-bottom, 0px)); } -.feed-bottom-nav { +#app:has(> .app-bottom-nav) { padding-bottom: calc(82px + env(safe-area-inset-bottom, 0px)); } +.app-bottom-nav { position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); z-index: 30; display: flex; width: min(100%, 560px); box-sizing: border-box; padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--paper); border-top: 1px solid var(--line); box-shadow: 0 -4px 18px rgba(0, 0, 0, .06); } -.feed-nav-button { +.app-nav-button { display: flex; flex: 1; min-width: 0; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-height: 52px; padding: 4px; border: 0; background: transparent; color: var(--ink); font-size: 11px; } -.feed-nav-button > span:first-child { display: flex; } +.app-nav-button > span:first-child { display: flex; position: relative; } +.app-nav-button[aria-current="page"] { background: var(--accent-soft); } +.app-nav-button.unread > span:first-child::after { + content: ''; position: absolute; top: -2px; right: -4px; width: 7px; height: 7px; + border-radius: 50%; background: var(--green); border: 1px solid var(--paper); +} .feed-page .feed-new-pill { bottom: calc(env(safe-area-inset-bottom, 0px) + 82px); } diff --git a/tools/feed-bottom-nav-test.js b/tools/feed-bottom-nav-test.js index 53b7529..f16134c 100644 --- a/tools/feed-bottom-nav-test.js +++ b/tools/feed-bottom-nav-test.js @@ -1,5 +1,5 @@ // Real feed/navigation views with local posts and no relay traffic. -// Run: bun tools/feed-bottom-nav-test.js +// Run: bun tools/app-bottom-nav-test.js import assert from 'node:assert/strict'; import puppeteer from 'puppeteer-core'; const app = await Bun.file('src/app.js').text(); @@ -13,8 +13,8 @@ const wallet = { xpub: 'test-wallet', loaded: true, nostrRelays: () => [], loadFeatureState: (k, d) => k === 'follows' ? { tags: [['p', author]], at: Date.now()/1000 } : d, saveFeatureState() {}, registerCacheExtension() {} }; let feature; -function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView() || h('div', { class: 'wallet-screen' }, 'Wallet')]); } -feature = messagesFeature({ h, ui, wallet, render, toast() {}, hook() {}, brandHeader: () => h('div', { style: 'height:60px' }, 'Coinos') }); +function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView() || h('div', { class: 'wallet-screen' }, 'Wallet'), feature.bottomNav()]); } +feature = messagesFeature({ h, ui, wallet, render, toast() {}, hook: name => name === 'unreadMessages' ? 1 : null, brandHeader: () => h('div', { style: 'height:60px' }, 'Coinos') }); window.test = { ui, wallet, render, async feed() { ui.chatOpen = true; ui.msgView = 'feed'; ui.noteThread = null; await feature.testSeed(Array.from({length:20}, (_, i) => ({ id: i.toString(16).padStart(64,'0'), pubkey:author, kind:1, tags:[], created_at:Math.floor(Date.now()/1000)-i, @@ -40,43 +40,49 @@ const page=await browser.newPage(), errors=[]; page.on('pageerror', e=>errors.push(e.message)); await page.setRequestInterception(true); page.on('request',r=>r.url().startsWith(server.url.origin)?r.continue():r.abort()); -const scroll=async()=>{ await page.evaluate(()=>window.scrollTo(0,700)); await page.waitForFunction(()=>!document.querySelector('.feed-bottom-nav')?.hidden); }; +const scroll=async()=>{ await page.evaluate(()=>window.scrollTo(0,700)); await page.waitForFunction(()=>scrollY > 0 && document.querySelector('.app-bottom-nav')?.getBoundingClientRect().height > 0); }; try { await page.setViewport({width:390,height:844,isMobile:true,hasTouch:true}); await page.emulateMediaFeatures([{name:'prefers-reduced-motion',value:'reduce'}]); await page.goto(server.url.href); await page.waitForSelector('.note-post', {timeout:5000}); - assert(await page.$eval('.feed-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'visible at top without scrolling'); + assert(await page.$eval('.app-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'visible at top without scrolling'); await scroll(); - assert.deepEqual(await page.$$eval('.feed-nav-button',els=>els.map(e=>e.textContent)),['Home','Messages','Notifications','Wallet']); - assert(await page.$eval('.feed-bottom-nav',e=>Math.abs(e.getBoundingClientRect().bottom-innerHeight)<1),'fixed at viewport bottom'); + assert.deepEqual(await page.$$eval('.app-nav-button',els=>els.map(e=>e.textContent)),['Feed','Messages','Notifications','Wallet']); + assert(await page.$eval('.app-bottom-nav',e=>Math.abs(e.getBoundingClientRect().bottom-innerHeight)<1),'fixed at viewport bottom'); await page.evaluate(()=>test.unseen()); - assert(await page.evaluate(()=>document.querySelector('.feed-new-pill').getBoundingClientRect().bottom < document.querySelector('.feed-bottom-nav').getBoundingClientRect().top),'new posts pill stays above navigation'); - await page.screenshot({path:'/tmp/feed-bottom-nav-mobile.png'}); - await page.tap('.feed-nav-button:nth-child(1)'); - await page.waitForFunction(()=>scrollY===0 && !document.querySelector('.feed-bottom-nav').hidden); - assert.equal(await page.evaluate(()=>test.ui.msgView),'feed','Home stays in feed'); - await scroll(); await page.tap('.feed-nav-button:nth-child(2)'); - await page.waitForFunction(()=>test.ui.msgView==='home' && !document.querySelector('.feed-bottom-nav')); + assert(await page.evaluate(()=>document.querySelector('.feed-new-pill').getBoundingClientRect().bottom < document.querySelector('.app-bottom-nav').getBoundingClientRect().top),'new posts pill stays above navigation'); + await page.screenshot({path:'/tmp/app-bottom-nav-mobile.png'}); + await page.tap('.app-nav-button:nth-child(1)'); + await page.waitForFunction(()=>scrollY===0 && !document.querySelector('.app-bottom-nav').hidden); + assert.equal(await page.evaluate(()=>test.ui.msgView),'feed','Feed stays in feed'); + await scroll(); await page.tap('.app-nav-button:nth-child(2)'); + await page.waitForFunction(()=>test.ui.msgView==='home' && !!document.querySelector('.app-bottom-nav')); assert((await page.evaluate(()=>document.body.innerText)).includes('Messages'),'chat list renders'); - await page.evaluate(()=>test.feed()); await scroll(); await page.tap('.feed-nav-button:nth-child(3)'); - await page.waitForFunction(()=>test.ui.msgView==='notifs' && !document.querySelector('.feed-bottom-nav')); + assert(await page.$eval('.app-nav-button:nth-child(2)',e=>e.getAttribute('aria-current')==='page'),'messages marked active'); + await page.evaluate(()=>{test.ui.msgView='dm';test.ui.msgPeer='b'.repeat(64);test.render();}); + await page.waitForSelector('.chat-card'); + assert(await page.evaluate(()=>document.querySelector('.chat-card').getBoundingClientRect().bottom <= document.querySelector('.app-bottom-nav').getBoundingClientRect().top),'conversation and composer fit above bottom nav'); + await page.screenshot({path:'/tmp/app-nav-chat.png'}); + await page.tap('.app-nav-button:nth-child(3)'); + await page.waitForFunction(()=>test.ui.msgView==='notifs' && !!document.querySelector('.app-bottom-nav')); assert((await page.evaluate(()=>document.body.innerText)).includes('Notifications'),'notifications render'); - await page.evaluate(()=>test.feed()); await scroll(); await page.tap('.note-text'); - await page.waitForFunction(()=>!!test.ui.noteThread && !document.querySelector('.feed-bottom-nav')); - await page.evaluate(()=>test.feed()); - assert(await page.$eval('.feed-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'returning to feed restores nav immediately without a scroll'); + await page.tap('.app-nav-button:nth-child(1)'); await scroll(); await page.tap('.note-text'); + await page.waitForFunction(()=>!!test.ui.noteThread && !!document.querySelector('.app-bottom-nav')); + await page.tap('.app-nav-button:nth-child(1)'); + assert(await page.$eval('.app-bottom-nav',e=>!e.hidden && e.getBoundingClientRect().height>0),'returning to feed restores nav immediately without a scroll'); await page.evaluate(()=>{test.ui.tab='settings';}); - await page.tap('.feed-nav-button:nth-child(4)'); + await page.tap('.app-nav-button:nth-child(4)'); await page.waitForSelector('.wallet-screen'); - assert(await page.evaluate(()=>!test.ui.chatOpen && test.ui.tab==='receive' && !document.querySelector('.feed-bottom-nav')),'Wallet opens main wallet instead of old settings tab'); - await page.evaluate(()=>test.feed()); + assert(await page.evaluate(()=>!test.ui.chatOpen && test.ui.tab==='receive' && !!document.querySelector('.app-bottom-nav')),'Wallet opens main wallet instead of old settings tab'); + await page.tap('.app-nav-button:nth-child(1)'); + await page.waitForSelector('.feed-page'); await page.setViewport({width:320,height:844,isMobile:true,hasTouch:true}); - assert(await page.$eval('.feed-bottom-nav',e=>e.scrollWidth<=e.clientWidth),'four buttons fit a narrow phone'); - await page.screenshot({path:'/tmp/feed-bottom-nav-always-mobile.png'}); + assert(await page.$eval('.app-bottom-nav',e=>e.scrollWidth<=e.clientWidth),'four buttons fit a narrow phone'); + await page.screenshot({path:'/tmp/app-bottom-nav-always-mobile.png'}); await page.evaluate(()=>{test.wallet.xpub=null;test.render();}); await scroll(); - await page.tap('.feed-nav-button:nth-child(2)'); - assert(await page.evaluate(()=>test.ui.signinAsk && test.ui.msgView==='feed'),'visitor gets sign-in prompt'); + await page.tap('.app-nav-button:nth-child(2)'); + assert(await page.evaluate(()=>!test.ui.chatOpen && test.ui.msgView===null),'visitor reaches sign-in screen'); assert.deepEqual(errors,[]); - console.log('✓ Feed nav stays visible at top and on return; Home, Messages, Notifications and Wallet work; four buttons fit a narrow phone; threads, visitor sign-in and new-post pill work'); + console.log('✓ Global nav works across feed, chat list, conversations, notifications, threads and wallet; Feed restores the feed; composer remains above nav; visitor entry and narrow layout work'); } finally { await page.close(); if (remote) await browser.disconnect(); else await browser.close(); server.stop(true); } diff --git a/tools/feed-wallet-back-test.js b/tools/feed-wallet-back-test.js index cd61184..1b0abe7 100644 --- a/tools/feed-wallet-back-test.js +++ b/tools/feed-wallet-back-test.js @@ -13,12 +13,13 @@ try { await page.setRequestInterception(true); page.on('request', r => r.url().startsWith(server.url.origin) ? r.continue() : r.abort()); await page.goto(server.url.origin + '/feed', { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('.feed-bottom-nav', { visible: true }); - await page.tap('.feed-nav-button:nth-child(4)'); - await page.waitForFunction(() => !document.querySelector('.feed-bottom-nav')); + await page.waitForSelector('.app-bottom-nav', { visible: true }); + await page.tap('.app-nav-button:nth-child(4)'); + await page.waitForFunction(() => !document.querySelector('.app-bottom-nav')); + assert(!(await page.$('.app-bottom-nav')), 'no nav over the welcome screen'); await page.goBack({ waitUntil: 'domcontentloaded' }); - await page.waitForSelector('.feed-bottom-nav', { visible: true, timeout: 5000 }); - assert(await page.$eval('.feed-bottom-nav', e => !e.hidden && e.getBoundingClientRect().height > 0)); + await page.waitForSelector('.app-bottom-nav', { visible: true, timeout: 5000 }); + assert(await page.$eval('.app-bottom-nav', e => !e.hidden && e.getBoundingClientRect().height > 0)); assert.equal(await page.evaluate(() => scrollY), 0, 'visible on return without scrolling'); console.log('✓ Real browser Back restores the public feed and visible navigation after Wallet'); } finally { await browser.close(); server.stop(true); } -- cgit v1.2.3 From 63e7746f98d7910053cd0b9e1a4a2ed3e6612af3 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 21:31:16 -0700 Subject: The bottom nav spans the window; the chat list is just conversations. Feed and Notifications leave the chat list (the nav reaches both; the bell carries the notifications dot now). On a wide screen the bar runs edge to edge with its buttons over the page column; quiet muted tabs, a pill for the current one. Feed gets a newspaper icon instead of a house. Co-Authored-By: Claude Opus 5.5 --- src/features/messages.js | 50 +++++++++--------------------------------------- src/style.css | 13 ++++++++----- 2 files changed, 17 insertions(+), 46 deletions(-) (limited to 'src/style.css') diff --git a/src/features/messages.js b/src/features/messages.js index 7be5f26..64754d0 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -7537,15 +7537,22 @@ export function messagesFeature(ctx) { 'pos', 'lockedGift', 'viewGift', 'claimChoose', 'signinAsk']) ui[key] = null; if (!visitor) { ui.screen = 'wallet'; ui.pubProf = null; } }; + // The chat list used to carry the notifications row and its count; the + // nav's bell carries the dot now. + const notifsWaiting = () => { + if (!myPubkeys().length) return 0; + refreshNotifs(); // throttled inside; keeps the count honest + return notifUnread(); + }; const icon = (paths) => ''; const button = (id, label, paths, onClick) => h('button', { - type: 'button', class: 'app-nav-button' + (id === 'messages' && !visitor && hook('unreadMessages') ? ' unread' : ''), + type: 'button', class: 'app-nav-button' + (!visitor && (id === 'messages' ? hook('unreadMessages') : id === 'notifs' && notifsWaiting()) ? ' unread' : ''), 'aria-label': label, 'aria-current': active === id ? 'page' : undefined, onClick, }, h('span', { html: icon(paths) }), h('span', {}, label)); return h('nav', { class: 'app-bottom-nav', 'data-key': 'app-bottom-nav', }, - button('feed', t('feedTitle'), '', () => { + button('feed', t('feedTitle'), '', () => { if (active === 'feed' && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread && !ui.feedEdit) { jumpToNew(); return; } leavePage(); if (visitor) { ui.pubProf = true; openFirehose(); } else showFeed(curFeedId); @@ -8202,45 +8209,6 @@ export function messagesFeature(ctx) { if (st().noPushService && !st().push) kids.push(h('div', { class: 'notice info small' }, pushAdvice())); - // ---- the feed, above the conversations: it's the thing you read, they're - // the things you answer - kids.push(h('div', { class: 'list' }, - h('div', { - class: 'item chat-thread-row', - onClick: () => { ui.msgView = 'feed'; switchFeed(FOLLOWING); }, - }, - h('div', { class: 'chat-avatar fallback' }, '\u2605'), - h('div', { class: 'col grow', style: 'min-width:0;gap:1px' }, - h('span', { class: 'chat-name' }, t('feedTitle')), - h('div', { class: 'muted small' }, - followsNow().set.size === 1 ? t('feedFollowing1') - : followsNow().set.size ? t('feedFollowingN', { n: followsNow().set.size }) - : t('feedNoFollowsShort')))), - // ...the feeds you made, each its own row under it - ...st().feeds.map((f) => h('div', { - class: 'item chat-thread-row', - onClick: () => { ui.msgView = 'feed'; switchFeed(f.id); }, - }, - h('div', { class: 'chat-avatar fallback' }, feedTopics(f).length && !f.follows && !(f.authors || []).length && !(f.packs || []).length ? '#' : '\u2605'), - h('div', { class: 'col grow', style: 'min-width:0;gap:1px' }, - h('span', { class: 'chat-name' }, f.name), - h('div', { class: 'muted small chat-preview' }, feedSummary(f))))), - // ...and what happened to what you posted - (() => { - const n = myPubkeys().length ? notifUnread() : 0; - if (myPubkeys().length) refreshNotifs(); // throttled inside; keeps the count honest - return h('div', { - class: 'item chat-thread-row' + (n ? ' unread' : ''), - onClick: openNotifs, - }, - h('div', { class: 'chat-avatar fallback' }, '\ud83d\udd14'), - h('div', { class: 'col grow', style: 'min-width:0;gap:1px' }, - h('span', { class: 'chat-name' }, t('alertsTitle')), - h('div', { class: 'muted small' }, n ? t('alertsNew', { n }) : t('alertsSub'))), - // like a group row: the dot sits mid-height, padded off the edge - n ? h('i', { class: 'thread-dot' }) : null); - })())); - // ---- DMs kids.push(h('div', { class: 'row between', style: 'align-items:baseline' }, h('h3', { style: 'margin:0' }, t('msgDmsTitle')), diff --git a/src/style.css b/src/style.css index 9696e7b..c873ccb 100644 --- a/src/style.css +++ b/src/style.css @@ -772,19 +772,22 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } sticky element inside the card would scroll away with the card. */ #app:has(> .app-bottom-nav) { padding-bottom: calc(82px + env(safe-area-inset-bottom, 0px)); } .app-bottom-nav { - position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); - z-index: 30; display: flex; width: min(100%, 560px); box-sizing: border-box; - padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); + /* Edge to edge like a system bar; the buttons stay over the page column. */ + position: fixed; bottom: 0; left: 0; right: 0; + z-index: 30; display: flex; justify-content: center; box-sizing: border-box; + padding: 6px max(4px, calc((100% - 560px) / 2)) calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--paper); border-top: 1px solid var(--line); box-shadow: 0 -4px 18px rgba(0, 0, 0, .06); } .app-nav-button { display: flex; flex: 1; min-width: 0; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-height: 52px; padding: 4px; - border: 0; background: transparent; color: var(--ink); font-size: 11px; + border: 0; border-radius: 12px; background: transparent; color: var(--muted); font-size: 11px; + cursor: pointer; transition: color .15s ease, background-color .15s ease; } +@media (hover: hover) { .app-nav-button:hover { color: var(--ink); } } .app-nav-button > span:first-child { display: flex; position: relative; } -.app-nav-button[aria-current="page"] { background: var(--accent-soft); } +.app-nav-button[aria-current="page"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; } .app-nav-button.unread > span:first-child::after { content: ''; position: absolute; top: -2px; right: -4px; width: 7px; height: 7px; border-radius: 50%; background: var(--green); border: 1px solid var(--paper); -- cgit v1.2.3 From 6bd5397375e602d360982820aa7a749281053516 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 22:05:29 -0700 Subject: The post action bar spans the post's full width, like its body. Co-Authored-By: Claude Opus 5.5 --- src/style.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/style.css') diff --git a/src/style.css b/src/style.css index c873ccb..dc116a3 100644 --- a/src/style.css +++ b/src/style.css @@ -631,7 +631,7 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; } .note-content > * { grid-column: 1 / -1; min-width: 0; } .note-content > .note-header { grid-column: 2; grid-row: 1; } .note-content > .note-text { font-size: 18px; line-height: 1.5; } -.note-acts { margin-top: 8px; gap: 4px; width: min(100%, 340px); } +.note-acts { margin-top: 8px; gap: 4px; width: 100%; } .note-acts > .note-act { flex: 1 1 0; min-width: 0; justify-content: center; padding-inline: 2px; } /* server comparison table (Settings → Advanced → Ark server) */ .cmp-table { width: 100%; border-collapse: collapse; font-size: 12.5px; } -- cgit v1.2.3 From b1397fc6b0c6b91a0835911b9dd52c0b09432d56 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 22:17:56 -0700 Subject: New posts: the pill lands on the oldest one, and each wears a tint until you've seen it. The new-posts pill used to glide to the top of the feed; now it stops at the oldest post that came in, right above where you were reading, so you read on upward. Posts that arrive while you read are tinted until they've been in view about two seconds, then fade to the plain page (like Amethyst). Co-Authored-By: Claude Opus 5.5 --- src/features/messages.js | 83 ++++++++++++++++++++++++++++++++++++++++---- src/style.css | 9 +++++ tools/feed-new-posts-test.js | 74 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 6 deletions(-) create mode 100644 tools/feed-new-posts-test.js (limited to 'src/style.css') diff --git a/src/features/messages.js b/src/features/messages.js index 90410fb..8c8bb15 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -4299,7 +4299,7 @@ export function messagesFeature(ctx) { ui.feedId = id; stopFeedWatch(); const c = feedNow(); - c.unseen = 0; c.shown = FEED_PAGE; + c.unseen = 0; c.fresh = null; c.shown = FEED_PAGE; admitFeed(c.deferred || [], c, true); // An already warmed feed can paint synchronously on entry. if (!c.booting) c.presentations.clear(); @@ -4683,10 +4683,45 @@ export function messagesFeature(ctx) { } const prev = feedPaint; feedPaint = presentation; - try { return keyed(noteRow(ev.pubkey, ev, displayName(ev.pubkey)), ev.id); } + try { + const row = keyed(noteRow(ev.pubkey, ev, displayName(ev.pubkey)), ev.id); + if (c.fresh && c.fresh.has(ev.id)) { row.classList.add('note-fresh'); watchFresh(c); } + return row; + } finally { feedPaint = prev; } } + // New posts stay tinted until they've been in view for FRESH_SEEN_MS: a + // row at least half on screen (or filling most of it) starts its clock, + // leaving view stops it. Seen, it loses the tint in place — no repaint. + const FRESH_SEEN_MS = 2000; + let freshObserver = null; + const freshTimers = new Map(); + function watchFresh(c) { + if (typeof IntersectionObserver === 'undefined') return; + freshObserver ||= new IntersectionObserver((entries) => { + for (const en of entries) { + const el = en.target, id = el.getAttribute('data-key'); + const inView = en.isIntersecting && (en.intersectionRatio >= 0.5 || en.intersectionRect.height >= window.innerHeight * 0.5); + if (inView && !freshTimers.has(id)) { + freshTimers.set(id, setTimeout(() => { + freshTimers.delete(id); + if (!el.isConnected) return; + feed?.fresh?.delete(id); + el.classList.remove('note-fresh'); + freshObserver.unobserve(el); + }, FRESH_SEEN_MS)); + } else if (!inView && freshTimers.has(id)) { + clearTimeout(freshTimers.get(id)); freshTimers.delete(id); + } + } + }, { threshold: [0, 0.5, 1] }); + // after the paint, when the row nodes are the mounted ones + requestAnimationFrame(() => { + for (const el of document.querySelectorAll('.notes-feed > .row.note-fresh')) freshObserver.observe(el); + }); + } + // Posts at the door: filtered in synchronously, so the same note from a // second relay is dropped while the first copy is still warming. const feedStaged = new WeakMap(); @@ -4740,20 +4775,56 @@ export function messagesFeature(ctx) { for (const id of c.presentations.keys()) if (!retained.has(id)) c.presentations.delete(id); saveFeedCache(c); if (rows.length) { - c.unseen = (c.unseen || 0) + result.added.filter((e) => e.created_at > topBefore).length; + const fresh = result.added.filter((e) => e.created_at > topBefore); + c.unseen = (c.unseen || 0) + fresh.length; + c.fresh ||= new Set(); + for (const e of fresh) c.fresh.add(e.id); holdScroll(render); } } - // The pill's tap: the posts are already in, so this just goes up to them. - // Reaching the top by yourself clears it too (see the scroll listener). + // The pill's tap: the posts are already in, so this just goes up to them — + // to the OLDEST of them, the one right above where you were reading, so + // you read on upward through the rest. Reaching the top by yourself clears + // the pill too (see the scroll listener). function jumpToNew() { const c = feed; if (!c) return; admitFeed(c.deferred || [], c, true); c.unseen = 0; render(); - glideToTop(); + const list = c.winList ? c.winList() : []; + let i = -1; + for (let j = list.length - 1; j >= 0; j--) if (c.fresh && c.fresh.has(list[j].id)) { i = j; break; } + if (i < 0) { glideToTop(); return; } + glideToPost(c, list, i); + } + // Scroll so post i's top sits just under the top of the window. A row + // outside the rendered window is placed from the height cache first, then + // corrected once it's mounted. + function glideToPost(c, list, i) { + const id = list[i].id, MARGIN = 8; + const find = () => document.querySelector('.notes-feed > [data-key="' + CSS.escape(id) + '"]'); + try { + const H = window.innerHeight || 800; + if (!find() && c.heights) { + let sum = 0, n = 0; + for (const v of c.heights.values()) { sum += v; n++; } + const avg = n ? sum / n : 200; + let y = 0; + for (let j = 0; j < i; j++) y += (c.heights.get(list[j].id) || avg) + ROW_GAP; + window.scrollTo(0, Math.max(0, (c.listTop || 0) + y - MARGIN)); + render(); + } + const el = find(); + if (!el) { glideToTop(); return; } + const target = Math.max(0, window.scrollY + el.getBoundingClientRect().top - MARGIN); + const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + if (reduce) { window.scrollTo({ top: target }); return; } + // a long way off: close most of the distance in one step, glide the rest + if (Math.abs(window.scrollY - target) > H * 2) window.scrollTo({ top: target + Math.sign(window.scrollY - target) * H * 2 }); + requestAnimationFrame(() => { try { window.scrollTo({ top: target, behavior: 'smooth' }); } catch { window.scrollTo(0, target); } }); + } catch { glideToTop(); } } // Up to the new posts as a glide, not a cut: an instant scrollTo read as a // page refresh. A long way down, most of the distance is closed in one diff --git a/src/style.css b/src/style.css index dc116a3..e907bd5 100644 --- a/src/style.css +++ b/src/style.css @@ -903,6 +903,15 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } border-left: none; border-right: none; border-radius: 0; box-shadow: none; } +/* A post that arrived while you were reading wears a tint until it has been + on screen a couple of seconds; then it fades to the plain page. The side + shadows carry the tint through the list's padding to its edges. */ +.notes-feed > .row { transition: background-color .9s ease, box-shadow .9s ease; } +.notes-feed > .row.note-fresh { + --fresh-bg: color-mix(in srgb, var(--green) 9%, var(--paper)); + background-color: var(--fresh-bg); + box-shadow: -14px 0 0 var(--fresh-bg), 14px 0 0 var(--fresh-bg); +} /* Inline move-money panel on the balance card. */ diff --git a/tools/feed-new-posts-test.js b/tools/feed-new-posts-test.js new file mode 100644 index 0000000..c90f0d5 --- /dev/null +++ b/tools/feed-new-posts-test.js @@ -0,0 +1,74 @@ +// New posts arriving mid-read: the pill lands on the OLDEST new post, and +// each new post keeps a tint until it has been in view a couple of seconds. +// Run: bun tools/feed-new-posts-test.js +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer-core'; +const app = await Bun.file('src/app.js').text(); +const dom = app.slice(app.indexOf('function h(tag,'), app.indexOf("const root = document.getElementById('app');")); +const entry = ` +import { messagesFeature } from './src/features/messages.js'; +${dom} +const author = 'a'.repeat(64); +const ui = { screen: 'wallet', chatOpen: true, msgView: 'feed' }; +const wallet = { xpub: 'test-wallet', loaded: true, nostrRelays: () => [], + loadFeatureState: (k, d) => k === 'follows' ? { tags: [['p', author]], at: Date.now()/1000 } : d, + saveFeatureState() {}, registerCacheExtension() {} }; +let feature; +function render() { if (feature) morphChildren(document.querySelector('#app'), [feature.screenView() || h('div', { class: 'wallet-screen' }, 'Wallet'), feature.bottomNav()]); } +feature = messagesFeature({ h, ui, wallet, render, toast() {}, hook: name => name === 'unreadMessages' ? 1 : null, brandHeader: () => h('div', { style: 'height:60px' }, 'Coinos') }); +window.test = { ui, wallet, render, get feature() { return feature; }, async feed() { + ui.chatOpen = true; ui.msgView = 'feed'; ui.noteThread = null; + await feature.testSeed(Array.from({length:20}, (_, i) => ({ id: i.toString(16).padStart(64,'0'), pubkey:author, kind:1, tags:[], created_at:Math.floor(Date.now()/1000)-i, + content: 'A post in the feed. Scroll to keep Home, messages and notifications within reach. '.repeat(3) }))); + render(); window.scrollTo(0,0); +}, unseen() { feature.testUnseen(); render(); }, arrive(n) { const now = Math.floor(Date.now()/1000); feature.testArrive(Array.from({length:n}, (_, i) => ({ id: 'f' + i.toString(16).padStart(63,'0'), pubkey:author, kind:1, tags:[], created_at: now + 100 - i, content: 'Brand new post number ' + i + '. '.repeat(1) + 'Fresh words. '.repeat(20) }))); } }; +await test.feed(); +`; +const bundle = await Bun.build({ entrypoints: ['nav-test-entry'], target: 'browser', plugins: [{ name: 'nav-test', setup(build) { + build.onResolve({filter:/^nav-test-entry$/},()=>({path:'entry',namespace:'nav-test'})); + build.onLoad({filter:/.*/,namespace:'nav-test'},()=>({contents:entry,loader:'js',resolveDir:process.cwd()})); + build.onLoad({filter:/src\/features\/messages\.js$/},async({path})=>({loader:'js',contents:(await Bun.file(path).text()).replace("id: 'messages',", "id: 'messages', testSeed: async (notes) => { const c = feedNow(); await c.boot; Object.assign(c, { notes, status: 'ready', booting: false, end: true, shown: 20 }); }, testUnseen: () => { feed.unseen = 2; }, testArrive: (notes) => admitFeed(notes, feed), testChats: (n, m) => { stCache = null; if (m != null) st().communities = Array.from({ length: m }, (_, i) => ({ ...COMMUNITY, community_id: (i + 1).toString(16).padStart(64, 'd'), name: 'Room ' + i })); threads.clear(); for (let i = 0; i < n; i++) { const peer = (i + 1).toString(16).padStart(64, 'c'); threads.set(peer, new Map([['r' + i, { rumor: { id: 'r' + i, kind: 14, pubkey: peer, tags: [], content: 'hi ' + i, created_at: 1700000000 - i }, mine: false }]])); } },")})); + build.onLoad({filter:/src\/nostr\.js$/},async({path})=>({loader:'js',contents:(await Bun.file(path).text()) + .replace('export async function queryOn(relays, filter, maxWait = 1500) {','export async function queryOn(relays, filter, maxWait = 1500) { return [];') + .replace(/export function subscribeOn\(([^)]*)\) \{/,'export function subscribeOn($1) { return () => {};')})); +} }] }); +assert(bundle.success,bundle.logs.join('\n')); +const html=`
`; + +const server=Bun.serve({port:0,fetch:()=>new Response(html,{headers:{'content-type':'text/html'}})}); +const browser=await puppeteer.launch({executablePath:'/usr/bin/google-chrome',headless:true,args:['--no-sandbox']}); +const page=await browser.newPage(), errors=[]; +page.on('pageerror', e=>errors.push(e.message)); +await page.setRequestInterception(true); +page.on('request',r=>r.url().startsWith(server.url.origin)?r.continue():r.abort()); +const sleep=(ms)=>new Promise(r=>setTimeout(r,ms)); +const top=(id)=>page.evaluate((id)=>{const r=document.querySelector('.notes-feed > [data-key="'+id+'"]');return r?Math.round(r.getBoundingClientRect().top):null;},id); +const fresh=()=>page.$$eval('.notes-feed > .row.note-fresh',els=>els.map(e=>e.getAttribute('data-key').slice(0,2)+e.getAttribute('data-key').slice(-1))); +const F=(i)=>'f'+i.toString(16).padStart(63,'0'); +try { + await page.setViewport({width:390,height:844,isMobile:true,hasTouch:true}); + await page.emulateMediaFeatures([{name:'prefers-reduced-motion',value:'reduce'}]); + await page.goto(server.url.href); + await page.waitForSelector('.note-post',{timeout:5000}); + const reading='6'.padStart(64,'0'); + await page.evaluate((id)=>{const r=document.querySelector('.notes-feed > [data-key="'+id+'"]');window.scrollTo(0,scrollY+r.getBoundingClientRect().top-100);},reading); + await sleep(300); + const before=await top(reading); + await page.evaluate(()=>test.arrive(3)); await sleep(300); + assert(Math.abs((await top(reading))-before)<=2,'the row being read stays put when posts arrive above'); + assert.equal(await page.$eval('.feed-new-pill .n',e=>e.textContent),'3'); + assert.deepEqual((await fresh()).length,3,'all three new posts wear the tint'); + await page.tap('.feed-new-pill'); await sleep(400); + const oldest=await top(F(2)); + assert(oldest>=0&&oldest<=20,'pill lands on the oldest new post, not the top: '+oldest); + assert(await page.evaluate(()=>scrollY)>0,'not scrolled all the way to the top'); + assert(!(await page.$('.feed-new-pill')),'pill is gone after the tap'); + await page.screenshot({path:'/tmp/feed-new-posts.png'}); + await sleep(2600); + assert(!(await page.$('.notes-feed > .row.note-fresh[data-key="'+F(2)+'"]')),'the post you looked at loses its tint'); + assert(await page.$('.notes-feed > .row.note-fresh[data-key="'+F(0)+'"]'),'the newest, still offscreen above, keeps its tint'); + await page.evaluate(()=>window.scrollTo(0,0)); await sleep(2600); + assert.deepEqual(await fresh(),[],'back at the top, the rest fade once seen'); + assert.deepEqual(errors,[]); + console.log('✓ New posts: pill lands on the oldest new post; tints stay until each post has been in view ~2s; the reading row stays put'); +} finally { await page.close(); await browser.close(); server.stop(true); } -- cgit v1.2.3 From a31d97220c8acb858c71301972f38597c1eb2270 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 22:28:05 -0700 Subject: Pinch to zoom a full-screen picture. Pinch zooms around the fingers (up to 5x), one finger pans a zoomed picture within its edges, double-tap zooms in at a spot and again to reset, and the wheel zooms on a desktop. A tap still closes an unzoomed picture (after a beat, so it can be the first half of a double-tap); a gesture never does. Co-Authored-By: Claude Opus 5.5 --- src/app.js | 102 ++++++++++++++++++++++++++++++++++++++++++++++- src/style.css | 2 + tools/image-zoom-test.js | 84 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 2 deletions(-) create mode 100644 tools/image-zoom-test.js (limited to 'src/style.css') diff --git a/src/app.js b/src/app.js index febb2cd..4003e1b 100644 --- a/src/app.js +++ b/src/app.js @@ -561,12 +561,110 @@ setTimeout(() => { if (_bootDeciding) { _bootDeciding = false; render(); } }, 40 function imageViewer() { if (!ui.lightbox) return null; const close = () => goBack(() => { ui.lightbox = null; }); - return h('div', { + // a tap on the picture closes it too (the × is small and far) — unless + // it's zoomed, or the tap is half of a double-tap (see attachZoom) + const img = h('img', { src: ui.lightbox, alt: '', draggable: 'false' }); + const box = h('div', { class: 'lightbox', onClick: close, role: 'dialog', 'aria-modal': 'true', - }, h('img', { src: ui.lightbox, alt: '', onClick: (e) => { e.stopPropagation(); close(); } }), // a tap on the picture closes it too: the × is small and far + }, img, // stop the bubble: the backdrop closes too, and two pops walk out of the room h('button', { class: 'lightbox-x', 'aria-label': t('close'), onClick: (e) => { e.stopPropagation(); close(); } }, '\u00d7')); + attachZoom(box, img, close); + return box; +} +// Pinch to zoom (up to 5×) around the fingers, drag to pan a zoomed picture, +// double-tap (or double-click) to zoom in at a spot and again to reset, the +// wheel to zoom on a desktop. The page's viewport meta turns browser zoom +// off, so the picture does its own. Only the first-mounted nodes keep these +// listeners: later renders morph into them, and the img is left out of the +// morph so its transform survives a background render. +function attachZoom(box, img, close) { + img._skipMorph = true; + const MAX = 5, pts = new Map(); + let s = 1, x = 0, y = 0, pinch = null, pan = null, moved = false, lastTap = 0, tapTimer = 0; + const base = () => ({ bx: img.offsetLeft + img.offsetWidth / 2, by: img.offsetTop + img.offsetHeight / 2 }); + const clamp = () => { + if (s <= 1) { s = 1; x = 0; y = 0; return; } + const mx = Math.max(0, (img.offsetWidth * s - window.innerWidth) / 2), my = Math.max(0, (img.offsetHeight * s - window.innerHeight) / 2); + x = Math.min(mx, Math.max(-mx, x)); y = Math.min(my, Math.max(-my, y)); + }; + const apply = (animate) => { + img.style.transition = animate ? 'transform .2s ease' : 'none'; + img.style.transform = s === 1 && !x && !y ? '' : `translate(${x}px, ${y}px) scale(${s})`; + img.style.cursor = s > 1 ? 'grab' : ''; + }; + // scale to ns keeping the picture point under (cx, cy) where it is + const zoomAt = (ns, cx, cy) => { + const { bx, by } = base(); + const px = (cx - bx - x) / s, py = (cy - by - y) / s; + s = Math.min(MAX, Math.max(1, ns)); + x = cx - bx - px * s; y = cy - by - py * s; + }; + box.addEventListener('pointerdown', (e) => { + if (e.target.closest('.lightbox-x')) return; + pts.set(e.pointerId, { x: e.clientX, y: e.clientY }); + if (pts.size === 1) moved = false; + begin(); + }); + const begin = () => { + const p = [...pts.values()]; + if (p.length >= 2) { + const { bx, by } = base(); + const mx = (p[0].x + p[1].x) / 2, my = (p[0].y + p[1].y) / 2; + pinch = { d: Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y) || 1, s, px: (mx - bx - x) / s, py: (my - by - y) / s }; + pan = null; + } else if (p.length === 1) { + pinch = null; + pan = { sx: p[0].x, sy: p[0].y, x, y }; + } + }; + box.addEventListener('pointermove', (e) => { + if (!pts.has(e.pointerId)) return; + pts.set(e.pointerId, { x: e.clientX, y: e.clientY }); + const p = [...pts.values()]; + if (pinch && p.length >= 2) { + const { bx, by } = base(); + const d = Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y); + const mx = (p[0].x + p[1].x) / 2, my = (p[0].y + p[1].y) / 2; + s = Math.min(MAX, Math.max(0.8, pinch.s * d / pinch.d)); // a little give below 1, snapped back on release + x = mx - bx - pinch.px * s; y = my - by - pinch.py * s; + moved = true; + apply(false); + } else if (pan && p.length === 1) { + const dx = p[0].x - pan.sx, dy = p[0].y - pan.sy; + if (Math.abs(dx) + Math.abs(dy) > 8) moved = true; + if (s > 1) { x = pan.x + dx; y = pan.y + dy; clamp(); apply(false); } + } + }); + const end = (e) => { + if (!pts.delete(e.pointerId)) return; + if (pts.size) { begin(); return; } // one finger lifted mid-pinch: carry on as a pan + pinch = pan = null; + clamp(); apply(true); + }; + box.addEventListener('pointerup', end); + box.addEventListener('pointercancel', end); + // a drag or a pinch is not a tap: nothing closes after one + box.addEventListener('click', (e) => { + if (moved) { moved = false; e.stopImmediatePropagation(); e.preventDefault(); return; } + if (e.target !== img) return; + e.stopPropagation(); + const now = Date.now(); + if (now - lastTap < 300) { + clearTimeout(tapTimer); lastTap = 0; + if (s > 1) { s = 1; x = 0; y = 0; } else { zoomAt(2.5, e.clientX, e.clientY); clamp(); } + apply(true); + return; + } + lastTap = now; + if (s === 1) tapTimer = setTimeout(close, 300); + }, true); + box.addEventListener('wheel', (e) => { + e.preventDefault(); + zoomAt(s * Math.exp(-e.deltaY * 0.002), e.clientX, e.clientY); + clamp(); apply(false); + }, { passive: false }); } if (typeof window !== 'undefined') { window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && ui.lightbox) goBack(() => { ui.lightbox = null; }); }); diff --git a/src/style.css b/src/style.css index e907bd5..15fcad0 100644 --- a/src/style.css +++ b/src/style.css @@ -726,6 +726,7 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; } display: flex; align-items: center; justify-content: center; background: rgba(8, 10, 14, .94); padding: 16px; animation: lightbox-in .12s ease-out; + touch-action: none; /* pinch and drag are the picture's own (see attachZoom) */ } /* Nothing scrolls behind a picture that fills the screen — and the reserved scrollbar gutter (see html, top of file) stands down with it, or it shows @@ -737,6 +738,7 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } .lightbox img { max-width: 100%; max-height: 100svh; max-height: 100vh; object-fit: contain; border-radius: 6px; cursor: zoom-out; + user-select: none; -webkit-user-select: none; transform-origin: center center; will-change: transform; } .lightbox-x { position: absolute; top: max(10px, env(safe-area-inset-top)); right: 10px; diff --git a/tools/image-zoom-test.js b/tools/image-zoom-test.js new file mode 100644 index 0000000..3be5798 --- /dev/null +++ b/tools/image-zoom-test.js @@ -0,0 +1,84 @@ +// The full-screen picture: pinch to zoom, pan when zoomed, double-tap to zoom +// and reset, a background render keeps the zoom, taps after a gesture don't +// close it, a plain tap still does, and the wheel zooms on a desktop. +// Run: bun tools/image-zoom-test.js +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer-core'; +const app = await Bun.file('src/app.js').text(); +const dom = app.slice(app.indexOf('function h(tag,'), app.indexOf("const root = document.getElementById('app');")); +const viewer = app.slice(app.indexOf('function imageViewer()'), app.indexOf("if (typeof window !== 'undefined') {\n window.addEventListener('keydown'")); +const svg = encodeURIComponent(''); +const entry = ` +${dom} +${viewer} +const ui = { lightbox: 'data:image/svg+xml,${svg}' }; +const t = (k) => k; +const goBack = (fn) => { fn(); render(); }; +function render() { morphChildren(document.querySelector('#app'), ui.lightbox ? [imageViewer()] : []); } +window.test = { ui, render, open() { ui.lightbox = 'data:image/svg+xml,${svg}'; render(); } }; +render(); +`; +const bundle = await Bun.build({ entrypoints: ['zoom-entry'], target: 'browser', plugins: [{ name: 'zoom', setup(build) { + build.onResolve({ filter: /^zoom-entry$/ }, () => ({ path: 'entry', namespace: 'zoom' })); + build.onLoad({ filter: /.*/, namespace: 'zoom' }, () => ({ contents: entry, loader: 'js', resolveDir: process.cwd() })); +} }] }); +assert(bundle.success, bundle.logs.join('\n')); +const html = `
`; +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] }); +const page = await browser.newPage(), errors = []; +page.on('pageerror', (e) => errors.push(e.message)); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const zoom = () => page.evaluate(() => { const m = new DOMMatrix(getComputedStyle(document.querySelector('.lightbox img')).transform); return { s: +m.a.toFixed(2), x: Math.round(m.e), y: Math.round(m.f) }; }); +const open = () => page.evaluate(() => !!test.ui.lightbox && !!document.querySelector('.lightbox')); +try { + await page.setViewport({ width: 390, height: 844, isMobile: true, hasTouch: true }); + await page.goto(server.url.href); + await page.waitForSelector('.lightbox img'); + const cdp = await page.target().createCDPSession(); + const touch = (type, points) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: points.map(([x, y], id) => ({ x, y, id })) }); + const cx = 195, cy = 422; + // pinch out around the centre + await touch('touchStart', [[cx - 40, cy], [cx + 40, cy]]); + for (let i = 1; i <= 8; i++) { await touch('touchMove', [[cx - 40 - i * 15, cy], [cx + 40 + i * 15, cy]]); await sleep(16); } + await touch('touchEnd', []); await sleep(350); + let z = await zoom(); + assert(z.s > 3.8 && z.s < 4.2, 'pinch zooms with the fingers (80px → 320px apart = 4×): ' + JSON.stringify(z)); + assert(await open(), 'a pinch does not close the picture'); + // a background render keeps the zoom + await page.evaluate(() => test.render()); await sleep(50); + assert.equal((await zoom()).s, z.s, 'a background render keeps the zoom'); + // one finger pans the zoomed picture, clamped to its edges + await touch('touchStart', [[cx, cy]]); + for (let i = 1; i <= 10; i++) { await touch('touchMove', [[cx + i * 20, cy + i * 5]]); await sleep(16); } + await touch('touchEnd', []); await sleep(350); + const panned = await zoom(); + assert(panned.x > z.x + 50, 'drag pans: ' + JSON.stringify(panned)); + const maxX = await page.evaluate((s) => (document.querySelector('.lightbox img').offsetWidth * s - innerWidth) / 2, panned.s); + assert(panned.x <= maxX + 1, 'pan is held to the picture edge'); + assert(await open(), 'a drag does not close the picture'); + // a tap while zoomed does not close; a double-tap resets + await page.touchscreen.tap(cx, cy); await sleep(400); + assert(await open(), 'a tap while zoomed does not close'); + await page.touchscreen.tap(cx, cy); await sleep(80); await page.touchscreen.tap(cx, cy); await sleep(350); + assert.equal((await zoom()).s, 1, 'double-tap resets the zoom'); + // double-tap at 1× zooms in at the spot, without closing + await page.touchscreen.tap(cx + 60, cy); await sleep(80); await page.touchscreen.tap(cx + 60, cy); await sleep(400); + z = await zoom(); + assert(z.s === 2.5 && z.x < 0, 'double-tap zooms in toward the tapped spot: ' + JSON.stringify(z)); + assert(await open(), 'a double-tap does not close'); + await page.touchscreen.tap(cx, cy); await sleep(80); await page.touchscreen.tap(cx, cy); await sleep(350); + // a single tap at 1× still closes + await page.touchscreen.tap(cx, cy); await sleep(450); + assert(!(await open()), 'a single tap closes the picture'); + // desktop: the wheel zooms toward the cursor + await page.setViewport({ width: 1280, height: 800 }); + await page.evaluate(() => test.open()); await page.waitForSelector('.lightbox img'); + await page.mouse.move(700, 400); + for (let i = 0; i < 5; i++) { await page.mouse.wheel({ deltaY: -120 }); await sleep(30); } + z = await zoom(); + assert(z.s > 1.5, 'the wheel zooms in: ' + JSON.stringify(z)); + assert(await open(), 'wheel zoom leaves the picture open'); + assert.deepEqual(errors, []); + console.log('✓ Image viewer: pinch zooms, drag pans within the edges, double-tap zooms and resets, renders keep the zoom, gestures never close it, a tap does, the wheel zooms on desktop'); +} finally { await browser.close(); server.stop(true); } -- cgit v1.2.3 From c0e428aff3ff34fec56a434bc1837e49ab9c1a81 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 28 Sep 2026 22:58:40 -0700 Subject: Polls (NIP-88): options with each one's share of the vote, votable from the feed and the thread. A kind 1068 poll showed as "an event this app doesn't show". Now its options are rows with the vote share behind them (kind 1018 votes, each person's latest counts, single/multiple choice, endsAt honored); a tap votes, marked as yours at once. A quoted poll is pictured in its card. Feeds and profiles list polls alongside notes, and a thread's root is looked up by id with any kind, so replies to a poll find it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Du1qT1wbkYwYK6zkGH79Rp --- src/features/messages.js | 132 ++++++++++++++++++++++++++++++++++++++++----- src/feed-cache.js | 2 +- src/i18n.js | 5 ++ src/style.css | 18 +++++++ tools/poll-test.js | 93 ++++++++++++++++++++++++++++++++ tools/thread-cache-test.js | 3 +- 6 files changed, 238 insertions(+), 15 deletions(-) create mode 100644 tools/poll-test.js (limited to 'src/style.css') diff --git a/src/features/messages.js b/src/features/messages.js index 2a3b400..c6a99b5 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -446,6 +446,8 @@ export function messagesFeature(ctx) { if (wallet.nostr && wallet.nostr.sk) return { pubkey: wallet.nostr.pk, signer: wallet.nostr.sk }; return null; } + // what a feed or a profile lists: notes, and polls (NIP-88) + const FEED_KINDS = [1, 1068]; const myPubkeys = () => { const pks = []; const id = hook('nostrLoginIdentity'); @@ -3461,7 +3463,7 @@ export function messagesFeature(ctx) { : { status: 'loading', notes: seed }; notesCache.set(pk, c); (async () => { - const evs = await queryOn(await notesRelays(pk), { kinds: [1], authors: [pk], limit: 30 }, 4500); + const evs = await queryOn(await notesRelays(pk), { kinds: FEED_KINDS, authors: [pk], limit: 30 }, 4500); const seen = new Set(); const fresh = (evs || []) .filter((e) => !seen.has(e.id) && seen.add(e.id)) @@ -3507,7 +3509,7 @@ export function messagesFeature(ctx) { render(); try { const evs = await queryOn(await notesRelays(pk), - { kinds: [1], authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500); + { kinds: FEED_KINDS, authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500); const seen = new Set(c.notes.map((e) => e.id)); const older = (evs || []) .filter((e) => !seen.has(e.id) && seen.add(e.id)) @@ -4290,10 +4292,10 @@ export function messagesFeature(ctx) { return; } try { - const events = await queryOn(feedRelaysOr(def, def && def.all ? FIREHOSE_RELAYS : NOTE_RELAYS), { kinds: [1], limit: FEED_PAGE, + const events = await queryOn(feedRelaysOr(def, def && def.all ? FIREHOSE_RELAYS : NOTE_RELAYS), { kinds: FEED_KINDS, limit: FEED_PAGE, ...(authors.length ? { authors } : {}), ...(topics.length ? { '#t': topics } : {}) }, 3000); if (c.stopped) return; - await mergeFeed(events.filter((e) => e.kind === 1 && !isReply(e) && !hidden(e)) + await mergeFeed(events.filter((e) => FEED_KINDS.includes(e.kind) && !isReply(e) && !hidden(e)) .sort((a, b) => b.created_at - a.created_at).slice(0, FEED_PAGE), {}, c); } catch {} finally { if (!c.stopped) { @@ -4744,7 +4746,7 @@ export function messagesFeature(ctx) { if (!staged) feedStaged.set(c, staged = new Set()); const known = new Set([...c.notes, ...(c.catchup || []), ...(c.deferred || [])].map((e) => e.id)); for (const e of evs || []) noteForSpam(e); - let add = (evs || []).filter((e) => e.kind === 1 && !isReply(e) && !hidden(e) + let add = (evs || []).filter((e) => FEED_KINDS.includes(e.kind) && !isReply(e) && !hidden(e) && !known.has(e.id) && !staged.has(e.id) && known.add(e.id) && staged.add(e.id)); if (!add.length) return false; const def = feedDef(c.id); @@ -4872,7 +4874,7 @@ export function messagesFeature(ctx) { // the firehose asks its relays for everything if (!topics.length && !def.all) return false; const relays = feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS); - const evs = await queryOn(relays, { kinds: [1], ...tag, limit: FEED_LIMIT, ...extra }, 5000).catch(() => []); + const evs = await queryOn(relays, { kinds: FEED_KINDS, ...tag, limit: FEED_LIMIT, ...extra }, 5000).catch(() => []); if (await mergeFeed(evs, merge, c)) { got = true; scheduleRepaint(); } return got; } @@ -4883,7 +4885,7 @@ export function messagesFeature(ctx) { const chunks = []; for (let i = 0; i < a.length; i += REQ_AUTHORS) chunks.push(a.slice(i, i + REQ_AUTHORS)); return chunks.map(async (chunk) => { - const evs = await queryOn(relays, { kinds: [1], authors: chunk, ...tag, limit: FEED_LIMIT, ...extra }, 5000).catch(() => []); + const evs = await queryOn(relays, { kinds: FEED_KINDS, authors: chunk, ...tag, limit: FEED_LIMIT, ...extra }, 5000).catch(() => []); if (await mergeFeed(evs, merge, c)) { got = true; scheduleRepaint(); } }); })); @@ -5054,11 +5056,11 @@ export function messagesFeature(ctx) { const on = (ev) => { mergeFeed([ev], { live: true }, c).then((ok) => { if (ok) scheduleRepaint(); }).catch(() => {}); }; const authors = feedAuthors(def); if (def.curated) { const iv = setInterval(() => { if (c === feed && ui.chatOpen && ui.msgView === 'feed') refreshFeed({ force: true, live: true }, c).catch(() => {}); }, 120_000); feedUnsubs.push(() => clearInterval(iv)); return; } - if (!authors.length) { feedUnsubs.push(subscribeOn(feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds: [1], ...tag, since }, on)); return; } + if (!authors.length) { feedUnsubs.push(subscribeOn(feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds: FEED_KINDS, ...tag, since }, on)); return; } const plan = feedRelays(def) ? [{ relays: feedRelays(def), authors }] : outboxPlan(authors); for (const { relays, authors: a } of plan) for (let i = 0; i < a.length; i += REQ_AUTHORS) - feedUnsubs.push(subscribeOn(relays, { kinds: [1], authors: a.slice(i, i + REQ_AUTHORS), ...tag, since }, on)); + feedUnsubs.push(subscribeOn(relays, { kinds: FEED_KINDS, authors: a.slice(i, i + REQ_AUTHORS), ...tag, since }, on)); } function stopFeedWatch() { for (const u of feedUnsubs) { try { u(); } catch {} } @@ -5379,7 +5381,8 @@ export function messagesFeature(ctx) { h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, // one level deep only: a quote of a quote of a quote is a rabbit // hole, and the inner one stays a link you can follow - ...noteBody(ev.content, depth + 1, emojiTagMap(ev.tags)))); + ...noteBody(ev.content, depth + 1, emojiTagMap(ev.tags))), + ev.kind === POLL ? pollBox(ev, { interactive: false }) : null); } // One URL, rendered as whatever it points at. `isImage` is markdown saying @@ -5853,6 +5856,108 @@ export function messagesFeature(ctx) { } // React with whichever emoji was picked (NIP-25 takes any content). + // ---- polls (NIP-88) ------------------------------------------------------- + // A kind 1068 poll is its question (content) plus ["option", id, label] + // tags; votes are kind 1018 events e-tagging it with ["response", id]. + // Each person's LATEST vote counts (one option unless the poll says + // "multiplechoice"), and nothing cast after its endsAt. + const POLL = 1068, POLL_VOTE = 1018; + const pollOptions = (ev) => ev.tags.filter((x) => x[0] === 'option' && x[1] != null && x[2]) + .map((x) => ({ id: String(x[1]), label: String(x[2]) })); + const pollMulti = (ev) => (ev.tags.find((x) => x[0] === 'polltype') || [])[1] === 'multiplechoice'; + const pollEnds = (ev) => { const v = Number((ev.tags.find((x) => x[0] === 'endsAt') || [])[1]); return Number.isFinite(v) && v > 0 ? v : 0; }; + const pollEnded = (ev) => !!pollEnds(ev) && Date.now() / 1000 > pollEnds(ev); + const pollRelays = async (ev) => [...new Set([ + ...ev.tags.filter((x) => x[0] === 'relay' && /^wss?:\/\//i.test(x[1] || '')).map((x) => x[1]), + ...(await noteRelaysFor(ev).catch(() => zapRelays())), + ])].slice(0, 12); + const pollVotes = new Map(); // poll id -> { at, loaded, loading, by: Map(pk -> { t, ids }) } + function pollState(ev) { + let st = pollVotes.get(ev.id); + if (!st) { st = { at: 0, loaded: false, loading: false, by: new Map() }; pollVotes.set(ev.id, st); } + return st; + } + function pollCount(poll, v) { + const st = pollState(poll); + const ends = pollEnds(poll); + if (ends && v.created_at > ends) return; + const prev = st.by.get(v.pubkey); + if (prev && prev.t >= v.created_at) return; + const valid = new Set(pollOptions(poll).map((o) => o.id)); + let ids = [...new Set(v.tags.filter((x) => x[0] === 'response').map((x) => String(x[1])))].filter((id) => valid.has(id)); + if (!pollMulti(poll)) ids = ids.slice(0, 1); + st.by.set(v.pubkey, { t: v.created_at, ids }); + } + // Votes are asked for when a poll is painted, and again a minute on. + function pollTally(ev) { + const st = pollState(ev); + if (!st.loading && Date.now() - st.at > 60_000) { + st.loading = true; st.at = Date.now(); + (async () => { + const evs = await queryOn(await pollRelays(ev), { kinds: [POLL_VOTE], '#e': [ev.id], limit: 1000 }, 5000).catch(() => []); + for (const v of evs || []) if (v.kind === POLL_VOTE) pollCount(ev, v); + })().finally(() => { st.loading = false; st.loaded = true; scheduleRepaint(); }); + } + return st; + } + async function votePoll(poll, optId) { + if (pollEnded(poll)) return; + const id = await requireIdentity(); + const st = pollState(poll); + const prev = st.by.get(id.pubkey); + const mine = prev?.ids || []; + const ids = pollMulti(poll) ? (mine.includes(optId) ? mine.filter((x) => x !== optId) : [...mine, optId]) : [optId]; + if (!pollMulti(poll) && mine[0] === optId) return; + const partial = { + kind: POLL_VOTE, content: '', + // strictly newer than our last vote, or relays and counters keep the old one + created_at: Math.max(Math.floor(Date.now() / 1000), (prev?.t || 0) + 1), + tags: [['e', poll.id], ['p', poll.pubkey], ...ids.map((x) => ['response', x]), CLIENT_TAG], + }; + const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); + pollCount(poll, evt); // counted on screen before the relays answer + render(); + const ok = await publishOn(await pollRelays(poll), evt).catch(() => false); + if (!ok) toast(t('msgSendFailed')); + } + // The options as rows with their share of the vote. In a quote card + // (`interactive` off) they are a picture of the poll — the tap opens it. + function pollBox(ev, { interactive = true } = {}) { + const opts = pollOptions(ev); + if (!opts.length) return null; + const st = pollTally(ev); + const counts = new Map(opts.map((o) => [o.id, 0])); + let voters = 0; + for (const v of st.by.values()) { + if (!v.ids.length) continue; + voters++; + for (const x of v.ids) counts.set(x, (counts.get(x) || 0) + 1); + } + const mine = new Set(myPubkeys().flatMap((pk) => st.by.get(pk)?.ids || [])); + const ended = pollEnded(ev); + const canVote = interactive && !ended; + const shown = st.loaded || voters > 0; + const foot = [ + shown ? t(voters === 1 ? 'pollVoter' : 'pollVoters', { n: voters }) : null, + pollMulti(ev) ? t('pollMulti') : null, + ended ? t('pollEnded') : pollEnds(ev) ? t('pollEndsAt', { when: new Date(pollEnds(ev) * 1000).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) }) : null, + ].filter(Boolean).join(' \u00b7 '); + return h('div', { class: 'poll' }, + ...opts.map((o) => { + const n = counts.get(o.id) || 0; + const pct = voters ? Math.round((n / voters) * 100) : 0; + return h(canVote ? 'button' : 'div', { + class: 'poll-opt' + (mine.has(o.id) ? ' mine' : '') + (canVote ? '' : ' static'), + type: canVote ? 'button' : undefined, + onClick: canVote ? (e) => { e.stopPropagation(); votePoll(ev, o.id).catch(() => {}); } : undefined, + }, + h('span', { class: 'poll-bar', style: 'width:' + (shown ? pct : 0) + '%' }), + h('span', { class: 'poll-label' }, (mine.has(o.id) ? '\u2713 ' : '') + o.label), + shown ? h('span', { class: 'poll-pct' }, pct + '%') : null); + }), + foot ? h('div', { class: 'small faint poll-foot' }, foot) : null); + } + async function reactTo(ev, emoji) { const id = await requireIdentity(); const relays = await noteRelaysFor(ev); @@ -6495,7 +6600,7 @@ export function messagesFeature(ctx) { // An event of a kind this app has no renderer for (a chess game, kind // 64, reached through a reaction to it) is shown as what its author's // client said it is (NIP-31 alt), never as raw content dressed as a post. - const foreign = ev.kind !== 1 && ev.kind !== 30023; + const foreign = ev.kind !== 1 && ev.kind !== 30023 && ev.kind !== POLL; const altText = foreign ? ((ev.tags.find((x) => x[0] === 'alt') || [])[1] || t('noteForeignKind', { kind: ev.kind })) : null; const isReply = !foreign && ev.tags.some((x) => x[0] === 'e'); const canZap = canZapPk(pk); @@ -6545,6 +6650,7 @@ export function messagesFeature(ctx) { foreign ? h('div', { class: 'note-text small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, (ev.kind === 64 ? '\u265f ' : '') + altText) : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...noteBody(ev.content, 0, emojiTagMap(ev.tags))), + ev.kind === POLL ? pollBox(ev) : null, pending ? null : noteActions(pk, ev, { canZap }), !pending && whoOpen(ev.id) ? whoPanel(ev) : null)); } @@ -6667,7 +6773,7 @@ export function messagesFeature(ctx) { }; let relays = await relaysFor(c.root || seed); const [roots, replies] = await Promise.all([ - c.root ? Promise.resolve([]) : queryOn(relays, { kinds: [1], ids: [rootId] }, 4000), + c.root ? Promise.resolve([]) : queryOn(relays, { ids: [rootId] }, 4000), // a root can be a poll queryOn(relays, { kinds: [1], '#e': [rootId], limit: 80 }, 4500), ]); if (!c.root) c.root = (roots || [])[0] || null; @@ -6681,7 +6787,7 @@ export function messagesFeature(ctx) { if (up === top.id) break; relays = [...new Set([...relays, ...(await relaysFor(top))])].slice(0, 14); const [ups, more] = await Promise.all([ - queryOn(relays, { kinds: [1], ids: [up] }, 4000), + queryOn(relays, { ids: [up] }, 4000), queryOn(relays, { kinds: [1], '#e': [up], limit: 80 }, 4500), ]); const upNote = (ups || [])[0]; diff --git a/src/feed-cache.js b/src/feed-cache.js index ea562f7..7394393 100644 --- a/src/feed-cache.js +++ b/src/feed-cache.js @@ -3,7 +3,7 @@ export const FEED_CACHE_POSTS = 30; const MAX_FEEDS = 4, MAX_UNITS = 256_000, MAX_AGE = 7 * 86400_000; export function createFeedCache(storage, prefix, now = Date.now) { const keyOf = (id) => id === 'following' ? prefix : prefix + ':' + id; - const valid = (e) => e?.kind === 1 && typeof e.id === 'string' && typeof e.pubkey === 'string' + const valid = (e) => (e?.kind === 1 || e?.kind === 1068) && typeof e.id === 'string' && typeof e.pubkey === 'string' && typeof e.content === 'string' && Number.isFinite(e.created_at) && Array.isArray(e.tags); function compact(notes) { const kept = []; let size = 0; diff --git a/src/i18n.js b/src/i18n.js index ce5bf7f..02c60aa 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -460,6 +460,11 @@ const STR = { arkFeeService: 'Service fee', arkCoinsExpired: 'expired', noteForeignKind: 'A kind {kind} event this app doesn’t show.', + pollVoter: '{n} vote', + pollVoters: '{n} votes', + pollMulti: 'Pick any', + pollEnded: 'Poll closed', + pollEndsAt: 'Closes {when}', arkExpiredDust: '{amount} has expired and is too small to renew. You can forget it from the Manage page.', arkCoinForget: 'Forget', arkCoinForgetTitle: 'Give this coin up: it has expired and is too small to renew or exit.', diff --git a/src/style.css b/src/style.css index 15fcad0..9b0bf45 100644 --- a/src/style.css +++ b/src/style.css @@ -768,6 +768,24 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } .quote-card.clickable { cursor: pointer; } .quote-card.clickable:hover { border-color: var(--line-strong); } .quote-loading { flex-direction: row; align-items: center; gap: 8px; } +/* A poll (NIP-88): each option a row with its share of the vote as a bar + behind the label. Only the bar's width changes as votes arrive, so the + post never changes height under the reader. */ +.poll { display: flex; flex-direction: column; gap: 6px; margin-top: 8px; } +.poll-opt { + position: relative; overflow: hidden; display: flex; align-items: center; gap: 8px; + width: 100%; min-height: 40px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 10px; + background: var(--surface2); color: inherit; font: inherit; text-align: left; cursor: pointer; +} +.poll-opt.static { cursor: inherit; min-height: 34px; padding: 6px 10px; } +.poll-opt:not(.static):hover { border-color: var(--line-strong); } +.poll-opt.mine { border-color: var(--accent); } +.poll-bar { position: absolute; inset: 0 auto 0 0; background: var(--line); transition: width .3s ease; pointer-events: none; } +.poll-opt.mine .poll-bar { background: var(--line-strong); } +.poll-label { position: relative; flex: 1; min-width: 0; overflow-wrap: anywhere; } +.poll-opt.mine .poll-label { font-weight: 600; } +.poll-pct { position: relative; font-variant-numeric: tabular-nums; color: var(--muted); font-size: 14px; } +.poll-foot { margin-top: 2px; } /* Posts that landed while you were reading further down. Floats over the feed near the top, out of the way of the thumb, and takes you up to them when tapped. Fixed, not sticky: the feed is the page scroller, and a diff --git a/tools/poll-test.js b/tools/poll-test.js new file mode 100644 index 0000000..e9cb0d6 --- /dev/null +++ b/tools/poll-test.js @@ -0,0 +1,93 @@ +// Polls (NIP-88, kind 1068): shown as their options with each one's share of +// the vote (kind 1018), votable from the feed and the thread, and pictured +// in a quote card. Uses a real poll from the relays; outgoing votes are +// caught at the socket so the test never votes on someone's real poll. +// +// Run: bun tools/poll-test.js +import puppeteer from 'puppeteer-core'; +import { SimplePool } from 'nostr-tools/pool'; +import { cacheKeyFor } from '../src/wallet.js'; +import { neventOf } from '../src/nostr.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; + +const POLL_ID = '000002f7c6a38223a9843d6e93ce8c15a3048bc95003690d74341cf9de372bfc'; +const pool = new SimplePool(); +const [poll] = await pool.querySync(['wss://relay.coinos.io', 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net'], { ids: [POLL_ID] }, { maxWait: 6000 }); +if (!poll) { console.log(' ✗ the poll is not on the relays'); process.exit(1); } +const labels = poll.tags.filter((x) => x[0] === 'option').map((x) => x[2]); + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5273, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.evaluateOnNewDocument(() => { + window.__votes = []; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (d) { + if (typeof d === 'string' && d.startsWith('["EVENT"') && /"kind":1018\b/.test(d)) { window.__votes.push(JSON.parse(d)[1]); return; } + return send.call(this, d); + }; +}); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const waitFor = async (fn, ms = 15000) => { for (let i = 0; i < ms / 200; i++) { if (await page.evaluate(fn)) return true; await sleep(200); } return false; }; +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5273/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('create a new wallet'); await sleep(600); + await page.waitForSelector('.words .w .t'); + const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await click('skip verification'); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + const Q = 'a'.repeat(63) + '9'; + await page.evaluate(([k, poll, q, ref]) => { + const now = Math.floor(Date.now() / 1000); + const quoting = { id: 'd'.repeat(64), pubkey: q, kind: 1, created_at: now, content: 'vote on this nostr:' + ref, tags: [] }; + localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', poll.pubkey], ['p', q]], c: '', at: now })); + localStorage.setItem(k + ':feedNotes', JSON.stringify([quoting, poll])); + localStorage.setItem(k + ':profiles', JSON.stringify({ [poll.pubkey]: { name: 'Poll Author', t: Date.now() }, [q]: { name: 'Quoter', t: Date.now() } })); + }, [base, poll, Q, neventOf(poll.id, poll.pubkey)]); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-bottom-nav .app-nav-button').click()); + await waitFor(() => document.querySelectorAll('.notes-feed .poll').length >= 2, 20000); + + const feedPoll = await page.evaluate(() => { + const row = [...document.querySelectorAll('.notes-feed [data-key]')].find((r) => r.querySelector(':scope .poll button.poll-opt')); + return row && { opts: [...row.querySelectorAll('.poll-opt .poll-label')].map((n) => n.textContent), text: row.innerText }; + }); + check('a poll in the feed shows its options', !!feedPoll && JSON.stringify(feedPoll.opts) === JSON.stringify(labels), JSON.stringify(feedPoll?.opts)); + check('...and not the "doesn’t show" placeholder', !(await page.evaluate(() => document.body.innerText.includes('doesn’t show')))); + check('its votes come in from the relays', await waitFor(() => /\d+ votes?/.test(document.querySelector('.notes-feed .poll-foot')?.textContent || ''), 15000), + await page.evaluate(() => document.querySelector('.notes-feed .poll-foot')?.textContent)); + const quoted = await page.evaluate(() => { const q = document.querySelector('.quote-card .poll'); return q && { n: q.querySelectorAll('.poll-opt.static').length, buttons: q.querySelectorAll('button').length }; }); + check('a quoted poll is pictured in its card, not votable there', !!quoted && quoted.n === labels.length && quoted.buttons === 0, JSON.stringify(quoted)); + + // vote for the last option from the feed + const before = await page.evaluate(() => location.href); + await page.evaluate(() => { const b = [...document.querySelectorAll('.notes-feed button.poll-opt')].pop(); b.click(); }); + await waitFor(() => window.__votes.length > 0, 10000); + const vote = await page.evaluate(() => window.__votes[0]); + const lastId = poll.tags.filter((x) => x[0] === 'option').pop()[1]; + check('tapping an option publishes a kind 1018 vote for it', vote && vote.kind === 1018 + && vote.tags.some((x) => x[0] === 'e' && x[1] === poll.id) && vote.tags.filter((x) => x[0] === 'response').map((x) => x[1]).join() === lastId, + JSON.stringify(vote?.tags)); + check('...marked as mine at once', await waitFor(() => !!document.querySelector('.notes-feed button.poll-opt.mine'), 3000)); + check('...without opening the thread', (await page.evaluate(() => location.href)) === before); + + // the thread: the poll as its root + await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.querySelector(':scope .poll button.poll-opt')); r.querySelector('.note-text').click(); }); + check('the poll opens as a thread', await waitFor(() => !!document.querySelector('.thread-page .poll button.poll-opt'), 10000)); + check('...still showing my vote', await page.evaluate(() => !!document.querySelector('.thread-page .poll-opt.mine'))); + if (process.env.SHOT) { await page.evaluate(() => window.scrollTo(0, 0)); await sleep(500); await page.screenshot({ path: process.env.SHOT }); } + check('...with its replies', await waitFor(() => document.querySelectorAll('.thread-page [data-zap-post]').length > 1, 15000)); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ polls read and vote' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/thread-cache-test.js b/tools/thread-cache-test.js index e8b0ccf..6bac353 100644 --- a/tools/thread-cache-test.js +++ b/tools/thread-cache-test.js @@ -84,7 +84,8 @@ try { const { messagesFeature } = await import(path); let requests = [], waiting = []; globalThis.__threadQuery = (filter) => { - if (filter.kinds?.includes(1) && (filter.ids || filter['#e'])) { + // root lookups by id carry no kind (a root can be a poll); reply queries are kind 1 + if (filter.ids || (filter.kinds?.includes(1) && filter['#e'])) { requests.push(filter); return new Promise((resolve) => waiting.push({ filter, resolve })); } -- cgit v1.2.3 From 689e21d5e77765661c44d60c10b18134b995162a Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Tue, 29 Sep 2026 11:18:21 -0700 Subject: Composers take pictures from the keyboard: the reply, post and chat fields are contenteditable. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Android keyboards (Gboard GIFs, stickers) only offer images to fields that accept them, and Chrome says so for contenteditable, never