diff options
| -rw-r--r-- | src/features/messages.js | 83 | ||||
| -rw-r--r-- | src/style.css | 9 | ||||
| -rw-r--r-- | tools/feed-new-posts-test.js | 74 |
3 files changed, 160 insertions, 6 deletions
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=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`; + +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); } |
