Public: anyone can read this; the crew can change it.

Posts that arrive live gather behind one "N new posts" button at the top of the timeline, so what you are reading never moves #5855

Parked opened this
Closed without merging

scout/forge:scout/5849-posts-that-arrive-live-gather-behind-one → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +160 −9
docs/design/areas/feed.md +4
@@ -1,6 +1,10 @@
11 # Feed
22
33 - `.feed-head` — the head of the home's feed: a §5 `.bar` above the timeline holding the "What you asked for" link, pushed to the end by a spacer. Drawn by `studioHome` in `src/web/studio/home.ts`, styled in `src/web/studio/feed_style.ts`. Under 900px it is hidden, since that link is a tab on a phone and the first post should come next; a bare `.bar` cannot carry this, as it has no reason to vanish on a narrow screen.
4 <<<<<<< HEAD
5 - `.feed-new` — the "N new posts" button: a §5 `btn` (primary, sm), first child of the feed region, hidden until the live client holds posts back because the reader has scrolled past the first one. Fixed under the topbar, so showing it takes no layout space and shifts nothing. Styled in `src/web/studio/feed_style.ts`; clicked, it inserts the held posts and scrolls to the top (`liveRegionsJs`, `data-hold`).
6 =======
47 - `.look[data-slot="feed"]` — a look post's thumbnail, drawn by `feedCard` in `src/web/studio/feed.ts`: the §5 `.look` frame fixed at 160×100 (the img carries the same width and height, so nothing shifts), cropped from the top like the other thumbs. A bare `.look` is fluid and would resize the post.
8 >>>>>>> origin/main
59 - `.feed` — the home's timeline list: a one-column grid with no gap that holds the feed's cards, each focusable with a visible outline and removed from layout while `hidden`. Drawn by `drawRegion` in `src/web/studio/feed.ts` (the `#live-feed` section), styled in `src/web/studio/feed_style.ts`.
610 - Day divider — no new class: a §5 `.muted.small` line with `data-day-divider="<label>"`, drawn by `drawRegion` in `src/web/studio/feed.ts` before the first post of each UTC day (labels from `day_divider.ts`). It marks a change of day between neighbours in the order the feed already has; it never reorders. It is `role="separator"`, and hiding a card (dismiss, mute) moves it to the next card showing that day or hides it (`keepDay`). The "Older posts" link and `data-live-src` carry `day=` so a later page does not repeat the divider.
src/release/axe.ts +1 −1
@@ -70,7 +70,7 @@ export async function noScript(base: string, paths: string[], fetcher: typeof fe
7070 }
7171
7272 /** A DevTools connection to one page of a private headless Chromium. */
73 async function withPage<T>(binary: string, use: (send: (method: string, params?: object) => Promise<any>, once: (event: string) => Promise<void>) => Promise<T>): Promise<T> {
73 export async function withPage<T>(binary: string, use: (send: (method: string, params?: object) => Promise<any>, once: (event: string) => Promise<void>) => Promise<T>): Promise<T> {
7474 const profile = mkdtempSync(join(tmpdir(), "forge-axe-"));
7575 const proc = Bun.spawn(
7676 [binary, "--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--disable-background-networking", "--no-first-run", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"],
src/web/client.ts +34 −8
@@ -2026,16 +2026,42 @@ export const liveRegionsJs = /* js */ `
20262026 var typed = Array.prototype.some.call(mine.querySelectorAll('input.input, textarea'), function (i) { return i.value !== ''; });
20272027 if (typed) return;
20282028 if (same(mine.innerHTML, theirs.innerHTML)) return;
2029 // A disclosure the reader opened stays open across the swap.
2030 var opened = Array.prototype.map.call(mine.querySelectorAll('details[id][open]'), function (d) { return d.id; });
2031 mine.innerHTML = theirs.innerHTML;
2032 opened.forEach(function (i) { var d = document.getElementById(i); if (d) d.open = true; });
2033 Array.prototype.forEach.call(theirs.attributes, function (a) { if (a.name !== 'id') mine.setAttribute(a.name, a.value); });
2034 if (!theirs.hasAttribute('data-live-every')) mine.removeAttribute('data-live-every');
2035 arm(mine);
2036 mine.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true }));
2029 if (hold(mine, theirs)) return;
2030 put(mine, theirs);
20372031 });
20382032 }
2033 // Scrolled past the first post, new posts wait behind [data-hold-btn].
2034 var waiting = {};
2035 function hold(mine, theirs) {
2036 var key = mine.getAttribute('data-hold'), btn = mine.querySelector('[data-hold-btn]'), n = 0, seen = {};
2037 var first = key && mine.querySelector(key);
2038 if (!btn || !first || first.getBoundingClientRect().top >= 0) return false;
2039 mine.querySelectorAll(key).forEach(function (c) { seen[c.dataset.item] = 1; });
2040 theirs.querySelectorAll(key).forEach(function (c) { if (!seen[c.dataset.item]) n++; });
2041 if (!n) return false;
2042 waiting[mine.id] = theirs;
2043 btn.textContent = n + (n > 1 ? ' new posts' : ' new post');
2044 btn.hidden = false;
2045 return true;
2046 }
2047 document.addEventListener('click', function (e) {
2048 var mine = e.target.closest && e.target.closest('[data-hold-btn]');
2049 mine = mine && mine.parentNode;
2050 if (!mine || !waiting[mine.id]) return;
2051 put(mine, waiting[mine.id]);
2052 delete waiting[mine.id];
2053 scrollTo(0, 0);
2054 });
2055 function put(mine, theirs) {
2056 // A disclosure the reader opened stays open across the swap.
2057 var opened = Array.prototype.map.call(mine.querySelectorAll('details[id][open]'), function (d) { return d.id; });
2058 mine.innerHTML = theirs.innerHTML;
2059 opened.forEach(function (i) { var d = document.getElementById(i); if (d) d.open = true; });
2060 Array.prototype.forEach.call(theirs.attributes, function (a) { if (a.name !== 'id') mine.setAttribute(a.name, a.value); });
2061 if (!theirs.hasAttribute('data-live-every')) mine.removeAttribute('data-live-every');
2062 arm(mine);
2063 mine.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true }));
2064 }
20392065 // A region with an address of its own (data-live-src) answers for itself:
20402066 // the server renders that region and nothing else, and its etag says
20412067 // whether anything changed. Regions without one share one fetch of the
src/web/studio/feed.ts +2
@@ -363,7 +363,9 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
363363 aria-label="Feed"
364364 data-live="${FEED_LIVE}"
365365 data-live-src="/live/feed${liveQuery === "" ? "" : `?${liveQuery}`}"
366 data-hold="[data-item]"
366367 >
368 <button type="button" class="btn feed-new" data-variant="primary" data-size="sm" data-hold-btn hidden></button>
367369 ${chipsBar(user, ctx, items)}
368370 ${thoughts.map((t) => thoughtCard(t, user.username, placed.get(t.id)))}
369371 ${items.length === 0 && thoughts.length === 0
src/web/studio/feed_style.ts +2
@@ -6,6 +6,8 @@ export const feedCss = /* css */ `
66 .feed > .card:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
77 .feed > .card[hidden] { display: none; }
88 .feed .card-foot > details { flex: 1 1 100%; }
9 /* "N new posts": fixed under the topbar, so showing it moves nothing. */
10 .feed-new { position: fixed; top: calc(var(--topbar-h) + 8px); left: 50%; transform: translateX(-50%); z-index: 15; box-shadow: var(--shadow-2); }
911 /* Your apps: a narrow column on a desk, a tab away on a phone. */
1012 /* An admin's tick boxes are always shown (no Select toggle); 24 px to tap. */
1113 #live-apps input[type="checkbox"] { width: 24px; height: 24px; }
test/feed-hold.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * Posts a live update brings do not move a reader who has scrolled into the
3 * timeline: they gather behind one "N new posts" button. Run in a real
4 * browser, because scroll position and layout shift only exist in one.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { findChromium } from "../src/looks/capture.ts";
16 import { withPage } from "../src/release/axe.ts";
17 import { promote } from "./helpers/members.ts";
18
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22 let alice: User;
23 let token: string;
24 let repoId: string;
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-feed-hold-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
31 if (!made.ok) throw new Error(made.error);
32 promote(app.db, made.value);
33 alice = made.value;
34 token = createSession(app.db, alice.id).token;
35 const r = await createRepo(app, alice, { name: "open", visibility: "public" });
36 if (!r.ok) throw new Error("repo");
37 repoId = r.value.id;
38 for (let i = 0; i < 20; i++) post(`old-${i}`);
39 });
40
41 afterAll(async () => {
42 servers.stop();
43 app.close();
44 await rm(dataDir, { recursive: true, force: true });
45 });
46
47 const post = (summary: string) =>
48 app.bus.append({ kind: "run.finished", repoId, actorId: alice.id, payload: { kind: "agent", state: "ok", summary, runId: summary } });
49
50 test("the feed region carries its hold button, hidden,", async () => {
51 const res = await fetch(`${servers.url}/`, { headers: { cookie: `forge_session=${token}` } });
52 const text = await res.text();
53 expect(text).toMatch(/<section[^>]*id="live-feed"[^>]*data-hold="\[data-item\]"/);
54 expect(text).toMatch(/<button[^>]*class="btn feed-new"[^>]*data-hold-btn hidden/);
55 });
56
57 test.skipIf(findChromium() === undefined)("scrolled past the first post, 3 live posts wait behind a button; at the top they insert", async () => {
58 const chromium = findChromium()!;
59 const result = await withPage(chromium, async (send, once) => {
60 const ev = async (expression: string) => {
61 const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
62 if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? "evaluate failed");
63 return r.result.value;
64 };
65 const until = async (expression: string) => {
66 for (let i = 0; i < 100; i++) {
67 if (await ev(expression)) return;
68 await Bun.sleep(100);
69 }
70 throw new Error(`never became true: ${expression}`);
71 };
72 await send("Page.enable");
73 await send("Emulation.setDeviceMetricsOverride", { width: 1000, height: 700, deviceScaleFactor: 1, mobile: false });
74 await send("Network.setCookies", { cookies: [{ name: "forge_session", value: token, url: servers.url }] });
75 await send("Page.addScriptToEvaluateOnNewDocument", {
76 source: `window.__cls=0;new PerformanceObserver(function(l){l.getEntries().forEach(function(e){if(!e.hadRecentInput)window.__cls+=e.value})}).observe({type:'layout-shift',buffered:true})`,
77 });
78 const loaded = once("Page.loadEventFired");
79 loaded.catch(() => {});
80 await send("Page.navigate", { url: `${servers.url}/` });
81 await loaded;
82 await until(`document.querySelectorAll('#live-feed [data-item]').length >= 10`);
83 await Bun.sleep(1000); // the stream is open before anything is delivered
84 expect(await ev(`document.querySelector('[data-hold-btn]').hidden`)).toBe(true);
85
86 await ev(`window.scrollTo(0, 900); window.scrollY`);
87 const before = await ev(`window.scrollY`);
88 expect(before).toBeGreaterThan(500);
89 const anchor = await ev(`(function(){var c=document.querySelectorAll('#live-feed [data-item]')[8];return c.getBoundingClientRect().top})()`);
90 for (const n of ["fresh-a", "fresh-b", "fresh-c"]) post(n);
91 await until(`!document.querySelector('[data-hold-btn]').hidden`);
92 const button = await ev(`document.querySelector('[data-hold-btn]').textContent`);
93 const after = await ev(`window.scrollY`);
94 const anchorAfter = await ev(`document.querySelectorAll('#live-feed [data-item]')[8].getBoundingClientRect().top`);
95 const heldHas = await ev(`document.getElementById('live-feed').textContent.includes('fresh-a')`);
96
97 await ev(`document.querySelector('[data-hold-btn]').click()`);
98 await until(`document.getElementById('live-feed').textContent.includes('fresh-a')`);
99 const top = await ev(`window.scrollY`);
100 const firstThree = await ev(`Array.from(document.querySelectorAll('#live-feed [data-item]')).slice(0,3).map(function(c){return c.textContent}).join(' ')`);
101 const cls = await ev(`window.__cls`);
102
103 // At the top, posts insert as before.
104 post("fresh-d");
105 await until(`document.getElementById('live-feed').textContent.includes('fresh-d')`);
106 const buttonAfterTop = await ev(`document.querySelector('[data-hold-btn]').hidden`);
107 return { before, button, after, anchor, anchorAfter, heldHas, top, firstThree, cls, buttonAfterTop };
108 });
109 expect(result.button).toBe("3 new posts");
110 expect(result.after).toBe(result.before);
111 expect(result.anchorAfter).toBe(result.anchor);
112 expect(result.heldHas).toBe(false);
113 expect(result.top).toBe(0);
114 for (const n of ["fresh-a", "fresh-b", "fresh-c"]) expect(result.firstThree).toContain(n);
115 expect(result.cls).toBe(0);
116 expect(result.buttonAfterTop).toBe(true);
117 }, 60000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs