aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/features/messages.js58
-rw-r--r--src/style.css14
-rw-r--r--tools/feed-when-test.js134
3 files changed, 206 insertions, 0 deletions
diff --git a/src/features/messages.js b/src/features/messages.js
index 6875856..6b3ff4c 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -5420,6 +5420,7 @@ export function messagesFeature(ctx) {
lastScrollAt = Date.now();
if (!ui.profilePk && (!(ui.chatOpen && ui.msgView === 'feed') || ui.noteThread)) return;
windowScrolled(ui.profilePk ? notesCache.get(ui.profilePk) : feed);
+ scrollWhen(ui.profilePk ? notesCache.get(ui.profilePk) : feed);
// Starting to scroll up dismisses the notice: the reader is already
// heading toward the new posts. Keyed rows keep their positions.
// Upward only: holding the page still as posts go in above scrolls it
@@ -5442,6 +5443,63 @@ export function messagesFeature(ctx) {
else loadOlderFeed().catch(() => {});
}, { passive: true });
}
+ // How far back you've scrolled: while the feed (or a profile's posts)
+ // moves, a small chip under the top bar says when the post at the top of
+ // the screen was written, and fades a moment after the scrolling stops
+ // ("some sort of little counter that shows the date and time of posts
+ // where I'm in the timeline", Adam, 2026-11-17). Painted straight into the
+ // DOM, outside render(): it changes every frame of a fling.
+ let whenEl = null, whenRaf = 0, whenHide = 0, whenIdx = { list: null, map: null };
+ function whenLabel(sec) {
+ const d = new Date(sec * 1000), now = new Date();
+ const time = d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
+ const date = d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', ...(d.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}) });
+ const ago = Math.max(0, (now - d) / 1000);
+ let rel = '';
+ try {
+ const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
+ rel = ago < 3600 ? rtf.format(-Math.max(1, Math.round(ago / 60)), 'minute')
+ : ago < 86400 ? rtf.format(-Math.round(ago / 3600), 'hour')
+ : ago < 86400 * 60 ? rtf.format(-Math.round(ago / 86400), 'day')
+ : ago < 86400 * 730 ? rtf.format(-Math.round(ago / (86400 * 30.4)), 'month')
+ : rtf.format(-Math.round(ago / (86400 * 365)), 'year');
+ } catch {}
+ const today = d.toDateString() === now.toDateString();
+ return (today ? time : date + ' · ' + time) + (rel ? ' · ' + rel : '');
+ }
+ function scrollWhen(c) {
+ if (whenRaf || typeof document === 'undefined') return;
+ whenRaf = requestAnimationFrame(() => {
+ whenRaf = 0;
+ const list = c?.winList ? c.winList() : null;
+ const rows = list ? document.querySelectorAll('.notes-feed > .row[data-key]') : [];
+ const head = document.querySelector('.brand-header');
+ const top = head ? Math.max(0, head.getBoundingClientRect().bottom) : 0;
+ // the post at the top of the screen, below the bar
+ let key = null, box = null;
+ for (const r of rows) {
+ const b = r.getBoundingClientRect();
+ if (b.bottom > top + 12) { key = r.getAttribute('data-key'); box = r.parentElement.getBoundingClientRect(); break; }
+ }
+ if (whenIdx.list !== list) whenIdx = { list, map: list ? new Map(list.map((e) => [e.id, e])) : null };
+ const ev = key && whenIdx.map?.get(key);
+ // only once you're past the first screenful: at the top the posts' own times say it
+ if (!ev || (window.scrollY || 0) < window.innerHeight * 0.75) { if (whenEl) whenEl.classList.remove('on'); return; }
+ if (!whenEl) {
+ whenEl = document.createElement('div');
+ whenEl.className = 'feed-when';
+ whenEl.setAttribute('aria-hidden', 'true');
+ document.body.appendChild(whenEl);
+ }
+ const label = whenLabel(ev.created_at);
+ if (whenEl.textContent !== label) whenEl.textContent = label;
+ whenEl.style.top = (top + 8) + 'px';
+ whenEl.style.left = (box.left + box.width / 2) + 'px';
+ whenEl.classList.add('on');
+ clearTimeout(whenHide);
+ whenHide = setTimeout(() => whenEl && whenEl.classList.remove('on'), 1200);
+ });
+ }
async function loadOlderNotes(pk) {
const c = notesCache.get(pk);
if (!c || c.status !== 'ready' || c.loadingMore || c.end) return;
diff --git a/src/style.css b/src/style.css
index 9f2cd35..633d7f6 100644
--- a/src/style.css
+++ b/src/style.css
@@ -2197,3 +2197,17 @@ html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: aut
.balance-settings-row .bs-title { font-weight: 600; }
.balance-settings-row .bs-tail { color: var(--muted); font-size: 20px; line-height: 1; flex-shrink: 0; width: 14px; text-align: center; }
.settings-prefs select { flex: 1 1 0; min-width: 0; }
+
+/* How far back the feed is scrolled: the post at the top of the screen's
+ date, under the top bar while scrolling (scrollWhen in messages.js). */
+.feed-when {
+ position: fixed; z-index: 29; transform: translate(-50%, -4px);
+ padding: 5px 12px; border-radius: 999px; white-space: nowrap;
+ font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums;
+ background: color-mix(in srgb, var(--bg) 88%, transparent); color: var(--ink);
+ border: 1px solid var(--line-strong);
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ box-shadow: 0 2px 10px rgba(0, 0, 0, .14);
+ pointer-events: none; opacity: 0; transition: opacity .25s, transform .25s;
+}
+.feed-when.on { opacity: 1; transform: translate(-50%, 0); }
diff --git a/tools/feed-when-test.js b/tools/feed-when-test.js
new file mode 100644
index 0000000..d9baa50
--- /dev/null
+++ b/tools/feed-when-test.js
@@ -0,0 +1,134 @@
+// While the feed scrolls, a chip under the top bar says when the post at the
+// top of the screen was written, and fades once the scrolling stops.
+// Run: bun tools/feed-when-test.js
+import puppeteer from './puppeteer.js';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+import { cacheKeyFor } from '../src/wallet.js';
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+import { noteEncode, npubEncode } from 'nostr-tools/nip19';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (name, condition, detail = '') => {
+ console.log(`${condition ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`);
+ if (!condition) ok = false;
+};
+const sk = generateSecretKey(), pk = getPublicKey(sk);
+const otherKey = generateSecretKey(), other = getPublicKey(otherKey);
+const now = Math.floor(Date.now() / 1000);
+const event = (content, at, key = sk, kind = 1) => finalizeEvent({ kind, content, created_at: at, tags: [] }, key);
+const origin = 'http://localhost:5299';
+// two hours apart: the feed spans days
+const seeded = Array.from({ length: 45 }, (_, i) => event('Post ' + i + '\nEnough text to make each post a comfortable reading target, and a second line of it too.', now - 600 - i * 7200));
+const requested = new Map();
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 5299, fetch: async (req) => {
+ const path = new URL(req.url).pathname;
+ if (path === '/') return new Response(html, { headers: { 'content-type': 'text/html' } });
+ if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path));
+ requested.set(path, (requested.get(path) || 0) + 1);
+ const delay = 20;
+ await sleep(delay);
+ return new Response('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="100"><rect width="160" height="100" fill="teal"/></svg>', {
+ headers: { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=3600' },
+ });
+} });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
+const page = await browser.newPage();
+const errors = [];
+page.on('pageerror', (e) => errors.push(String(e)));
+await page.setViewport({ width: 390, height: 844 });
+await page.evaluateOnNewDocument((fixtures) => {
+ const sockets = [];
+ class FakeSocket extends EventTarget {
+ constructor(url) {
+ super(); this.url = url; this.readyState = 0; this.subs = new Map(); sockets.push(this);
+ setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0);
+ }
+ emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); }
+ message(data) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(data) })); }
+ send(raw) {
+ let m; try { m = JSON.parse(raw); } catch { return; }
+ if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; }
+ if (m[0] !== 'REQ') return;
+ const [_, id, filter] = m;
+ (window.__feedRequests ||= []).push(filter);
+ this.subs.set(id, filter);
+ let events = [];
+ if (filter.kinds?.includes(1) && !filter.since && !filter.until) events = window.__catchup || [];
+ setTimeout(() => {
+ if (!this.subs.has(id)) return;
+ for (const e of events) this.message(['EVENT', id, e]);
+ this.message(['EOSE', id]);
+ }, events.length ? 700 : 20);
+ }
+ close() { this.readyState = 3; this.emit('close', new Event('close')); }
+ }
+ Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 });
+ window.WebSocket = FakeSocket;
+ window.__inject = (e) => {
+ let count = 0;
+ for (const ws of sockets) for (const [id, f] of ws.subs) {
+ if (ws.readyState === 1 && f.kinds?.includes(1) && f.since) { ws.message(['EVENT', id, e]); count++; }
+ }
+ return count;
+ };
+}, {});
+const click = (text) => page.evaluate((text) => [...document.querySelectorAll('button')].find((e) => e.textContent.toLowerCase().includes(text))?.click(), text);
+const row = (id) => `.notes-feed > [data-key="${id}"]`;
+// the Feed is a tab in the bottom nav (it was a row on the chat home)
+const feedTab = () => [...document.querySelectorAll('.app-nav-button')].find((b) => b.getAttribute('aria-label') === 'Feed');
+const snapshot = () => page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-zap-post]')].map((n) => {
+ const b = n.getBoundingClientRect();
+ return { id: n.dataset.key, top: b.top, height: b.height, text: n.innerText, avatar: n.querySelector('.note-avatar')?.getAttribute('style') };
+}));
+try {
+ await page.goto(origin);
+ await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
+ await page.reload(); await sleep(300);
+ await click('create a new wallet'); await sleep(400);
+ await click('to import');
+ await page.waitForSelector('textarea');
+ const mnemonic = generateMnemonic(wordlist);
+ await page.type('textarea', mnemonic);
+ await click('open wallet');
+ await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive'));
+ const base = cacheKeyFor(mnemonic + '\n');
+ await page.evaluate(([base, pk, seeded, origin]) => {
+ localStorage.setItem(base + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) }));
+ localStorage.setItem(base + ':feedNotes', JSON.stringify(seeded));
+ localStorage.setItem(base + ':profiles', JSON.stringify({ [pk]: { name: 'Cached Author', picture: origin + '/avatar.png', t: Date.now() } }));
+ localStorage.setItem('btc-wallet-feed:' + base, 'following'); // a wallet with no feed remembered opens on Popular
+ }, [base, pk, seeded, origin]);
+ await page.reload();
+ await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive'));
+ await sleep(2000);
+ await page.evaluate((tab) => eval(tab)()?.click(), feedTab.toString());
+ await page.waitForSelector('.notes-feed:not([data-booting]) > .row', { timeout: 15000 });
+ await sleep(800);
+ await page.evaluate(() => scrollBy(0, 40)); await sleep(100);
+ check('no chip near the top of the feed', !(await page.$('.feed-when.on')));
+ for (let i = 0; i < 12; i++) { await page.evaluate(() => scrollBy(0, 300)); await sleep(30); }
+ await sleep(100);
+ const shown = await page.evaluate(() => {
+ const el = document.querySelector('.feed-when.on');
+ const top = document.querySelector('.brand-header').getBoundingClientRect().bottom;
+ const r = [...document.querySelectorAll('.notes-feed > .row[data-key]')].find((r) => r.getBoundingClientRect().bottom > top + 12);
+ return el && { text: el.textContent, key: r?.dataset.key, y: el.getBoundingClientRect().top, head: top };
+ });
+ const ev = shown && seeded.find((e) => e.id === shown.key);
+ check('the chip shows while scrolling, under the top bar', !!shown && shown.y >= shown.head, JSON.stringify(shown));
+ const want = ev && await page.evaluate((s) => new Date(s * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }), ev.created_at);
+ check('...with the time of the post at the top of the screen', !!want && shown.text.includes(want), shown?.text + ' / ' + want);
+ check('...and how long ago', /ago|yesterday/i.test(shown?.text || ''), shown?.text);
+ if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT });
+ await sleep(1700);
+ check('it fades once the scrolling stops', !(await page.$('.feed-when.on')));
+ check('no page errors', !errors.length, errors.join('; '));
+} finally {
+ await browser.close();
+ server.stop(true);
+}
+console.log(ok ? 'PASS' : 'FAIL');
+process.exit(ok ? 0 : 1);