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

Opening a feed item and pressing back returns to the same place on the feed #15693

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15680-opening-a-feed-item-and-pressing-back-re → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15680-opening-a-feed-item-and-pressing-back-re was merged into main as 9d461ee.

Review

Sign in to review this change.
8 files changed +99 −10
src/feed/anchor.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * The place a feed post keeps in the address bar: each post has an anchor
3 * made from its id, and the link into the post carries that anchor as the
4 * return target. Opening the post first marks the feed's own history entry
5 * with it, so Back lands on the same post, not the top.
6 */
7
8 const SAFE = /^[A-Za-z0-9-]$/;
9 /** The longest anchor kept; a longer id is cut and given a hash so two long ids stay apart. */
10 const LONGEST = 200;
11
12 /**
13 * A post's anchor id: its id with every character outside letters, digits and `-` spelled `_` +
14 * hex, never longer than the return target accepts.
15 */
16 export function anchorOf(itemId: string): string {
17 let out = "post-";
18 for (const ch of itemId) out += SAFE.test(ch) ? ch : `_${ch.codePointAt(0)!.toString(16)}_`;
19 return out.length <= LONGEST ? out : `${out.slice(0, LONGEST - 17)}-${Bun.hash(itemId).toString(16).padStart(16, "0")}`;
20 }
21
22 /** A return target is a bare fragment naming a post anchor: never a path, a host or a scheme. */
23 export const RETURN_TARGET = /^#post-[A-Za-z0-9_-]{1,400}$/;
24
25 /**
26 * The page script's check of a link's return target, built from RETURN_TARGET so the tested
27 * pattern is the served one.
28 */
29 export const returnTargetJs = `var RT=new RegExp(${JSON.stringify(RETURN_TARGET.source)});`;
src/web/studio/feed.ts +10 −3
@@ -26,6 +26,7 @@ import { parseBefore, readTimeline, TIMELINE_START } from "../../feed/timeline.t
2626 import type { FeedItem } from "../../feed/rank.ts";
2727 import { repliesWords } from "../../feed/replies.ts";
2828 import { permalinkOf, replyPath, replyRepo, threadOf } from "../../feed/reply.ts";
29 import { anchorOf, returnTargetJs } from "../../feed/anchor.ts";
2930 import { depthOf } from "../../feed/depth.ts";
3031 import { runLinkOf } from "../../feed/run_link.ts";
3132 import { getAppByRepo } from "../../core/apps.ts";
@@ -192,7 +193,7 @@ export function feedCard(
192193 // A run post links its headline only to a run page; one without (a sync failure) is plain text.
193194 const headline = item.kind === "run" && run === undefined
194195 ? html`<p class="break">${item.what}</p>`
195 : html`<p class="break"><a href="${item.link}" data-feed-open>${item.what}</a></p>`;
196 : html`<p class="break"><a href="${item.link}" data-feed-open data-return="#${anchorOf(item.id)}">${item.what}</a></p>`;
196197 const aged = item.kind === "run" && run !== undefined ? finishedLabel(item.at) : "";
197198 const head = html`${avatar(item.actor ?? item.app)}
198199 <strong class="break">${item.actor ?? item.app}</strong
@@ -242,7 +243,7 @@ export function feedCard(
242243 return card(body, {
243244 head,
244245 foot,
245 attrs: html`data-nav tabindex="0" data-item="${item.id}" data-app="${item.app}" data-kind="${item.kind}"`,
246 attrs: html`id="${anchorOf(item.id)}" data-nav tabindex="0" data-item="${item.id}" data-app="${item.app}" data-kind="${item.kind}"`,
246247 });
247248 }
248249
@@ -634,6 +635,7 @@ ${draftJs}
634635 ${sendChordJs}
635636 ${dayKeepJs}
636637 ${heldPostsJs}
638 ${returnTargetJs}
637639 (function () {
638640 var feed = document.getElementById('live-feed');
639641 if (!feed || typeof fetch === 'undefined') return;
@@ -738,7 +740,12 @@ ${heldPostsJs}
738740 var t = e.target && e.target.closest ? e.target.closest('[data-feed],[data-feed-open]') : null;
739741 var card = t && t.closest('[data-item]');
740742 if (!card) return;
741 if (t.hasAttribute('data-feed-open')) { send(card, 'opened'); return; }
743 if (t.hasAttribute('data-feed-open')) {
744 // Mark this history entry with the post, so Back lands on it. Only a post anchor is taken.
745 var back = t.getAttribute('data-return') || '';
outdated

Untested validation and JS-only behaviour; see points 2 and 3. Also a post id longer than 400 chars silently loses its return.

746 if (RT.test(back)) history.replaceState(history.state, '', location.pathname + location.search + back);
747 send(card, 'opened'); return;

Non-blocking: skip replaceState for modified or middle clicks (new tab), so the feed URL is not rewritten when the person leaves nothing behind.

748 }
742749 act(card, t.getAttribute('data-feed'));
743750 });
744751 // A like flips at once and then takes the count the forge answers; a
test/feed-back-place.test.ts added +53
@@ -0,0 +1,53 @@
1 import { describe, expect, test } from "bun:test";
2 import { anchorOf, RETURN_TARGET, returnTargetJs } from "../src/feed/anchor.ts";
3 import type { FeedItem } from "../src/feed/rank.ts";
4 import { feedCard, feedJs } from "../src/web/studio/feed.ts";
5
6 const item = (id: string): FeedItem =>
7 ({
8 id, kind: "pull", app: "alice/notes", actor: "scribe", at: new Date().toISOString(),
9 what: "Sorted the list", reason: "because", link: "/alice/notes/pulls/1",
10 }) as FeedItem;
11
12 describe("a feed post keeps its place", () => {
13 test("each post has a stable anchor and its deep link carries it", () => {

Only checks id and data-return are emitted. Nothing checks that a hostile target is refused (box 3).

14 const a = feedCard(item("pull:alice/notes#1")).text;
15 const again = feedCard(item("pull:alice/notes#1")).text;
16 const anchor = anchorOf("pull:alice/notes#1");
17 expect(a).toContain(`id="${anchor}"`);
18 expect(a).toContain(`data-return="#${anchor}"`);
19 expect(again).toContain(`id="${anchor}"`);
20 expect(anchorOf("a:b")).not.toBe(anchorOf("a_b"));
21 });
22 });
23
24 describe("the return target is only a post fragment", () => {
25 test("a hostile or foreign target is refused", () => {
26 for (const bad of [
27 "//evil.com", "https://evil.com", "http://evil.com/#post-a", "/feed", "/feed#post-a", "#other", "#", "#post-",
28 "javascript:alert(1)", "#post-a b", "#post-a/b", "#post-a?x=1", "", "post-a", `#post-${"a".repeat(401)}`,
29 ])
30 expect(RETURN_TARGET.test(bad)).toBe(false);
31 expect(RETURN_TARGET.test(`#${anchorOf("pull:alice/notes#1")}`)).toBe(true);
32 });
33
34 test("the page script checks with that very pattern, before it touches history", () => {
35 expect(feedJs).toContain(returnTargetJs);
36 const at = feedJs.indexOf("RT.test(back)");
37 expect(at).toBeGreaterThan(-1);
38 expect(feedJs.indexOf("replaceState", at)).toBeGreaterThan(at);
39 const built = new Function(`${returnTargetJs} return RT;`)() as RegExp;
40 expect(built.source).toBe(RETURN_TARGET.source);
41 expect(built.test("//evil.com")).toBe(false);
42 expect(built.test("#post-e1")).toBe(true);
43 });
44
45 test("a post id of any length keeps an accepted, distinct anchor", () => {
46 const a = anchorOf(`pull:${"x".repeat(900)}#1`);
47 const b = anchorOf(`pull:${"x".repeat(900)}#2`);
48 expect(RETURN_TARGET.test(`#${a}`)).toBe(true);
49 expect(a).not.toBe(b);
50 expect(anchorOf("é".repeat(500)).length).toBeLessThanOrEqual(200);
51 expect(RETURN_TARGET.test(`#${anchorOf("é".repeat(500))}`)).toBe(true);
52 });
53 });
test/feed-keys.test.ts +1 −1
@@ -67,7 +67,7 @@ test("a feed post is a focusable row, and its link is what Enter opens", async (
6767 feedCard({ id: "i1", app: "a/b", kind: "run", what: "Shipped", reason: "", link: "/a/b/runs/r1", at: Date.now(), actor: "a" } as never),
6868 );
6969 expect(html).toMatch(/data-nav\s+tabindex="0"/);
70 expect(html).toContain('<a href="/a/b/runs/r1" data-feed-open>');
70 expect(html).toContain('<a href="/a/b/runs/r1" data-feed-open data-return="#post-i1">');
7171 });
7272
7373 test("the key decision stays under the 1.5 KB the feature may add", () => {
test/feed-page.test.ts +1 −1
@@ -87,7 +87,7 @@ describe("the feed on the home page", () => {
8787 expect(text).toContain("alice/open");
8888 expect(text).not.toContain("<script>alert(1)</script>");
8989 expect(text).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
90 const order = [...text.matchAll(/class="card"\s+data-nav[^>]*data-item="([^"]+)"/g)].map((m) => m[1]);
90 const order = [...text.matchAll(/class="card"\s+id="[^"]*"\s+data-nav[^>]*data-item="([^"]+)"/g)].map((m) => m[1]);
9191 expect(order).toEqual(readFeed(app.db, alice).items.map((i) => i.id));
9292 });
9393
test/home-feed.test.ts +1 −1
@@ -152,7 +152,7 @@ describe("home is the feed", () => {
152152 // carries what was said.
153153 expect(text).toContain("Water the tomatoes at dawn");
154154 expect(text).toMatch(
155 /href="\/alice\/garden\/issues\/1"[^>]*data-feed-open>opened an issue: Water the tomatoes at dawn</,
155 /href="\/alice\/garden\/issues\/1"[^>]*data-feed-open[^>]*>opened an issue: Water the tomatoes at dawn</,
156156 );
157157 // A reply names the tell it answers.
158158 expect(text).toContain("on “Water the tomatoes at dawn”: Mulch them first");
test/home-walk.test.ts +1 −1
@@ -75,7 +75,7 @@ test("composer, timeline, a tell, a crew member's run and pull, a share, the app
7575 });
7676 expect(posted.status).toBe(303);
7777 expect(await home(alice)).toMatch(
78 /href="\/alice\/garden\/issues\/1"[^>]*data-feed-open>opened an issue: Plant the beans</,
78 /href="\/alice\/garden\/issues\/1"[^>]*data-feed-open[^>]*>opened an issue: Plant the beans</,
7979 );
8080
8181 // The crew member's run and pull are posts under its name.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs