Public: anyone can read this; the crew can change it.
The owner's inbox filters are saved and each change can be undone #15097
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15071-the-owner-s-inbox-filters-are-saved-and → main 3 commits fork 3 threads · 3 unresolved
docs/features/feed-filters.md +4
| @@ -25,3 +25,7 @@ Open the feed from the palette. Press `c` for Crew, `m` for Mine, `s` for Ships. | ||
| 25 | 25 | ## What it does not do |
| 26 | 26 | |
| 27 | 27 | One filter at a time. It does not combine with `?app=`: choosing an app shows that app's posts unfiltered. |
| 28 | ||
| 29 | ## Saved, and a way back | |
| 30 | ||
| 31 | The set you choose (one of the three, or one app) is saved on your account, so opening a bare `/feed` or the terminal feed starts with it. **Clear** and a second tap save "no filter" (`/feed?show=all`). After the first choice a **Back to the previous filter** button appears under the buttons: it undoes the last choice, one step each press, twenty kept. In the terminal press `b`. A choice that arrives from another site is not saved, and a stored value that is not a known filter, or an app you can no longer read, is ignored. Not saved: the kind and person chips (already saved apart) and an age filter (none exists yet). |
src/core/migration-pins/20261121150000-feed-filter-steps.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 2fbb04aee2acd1f36daecc78590576c1455456d168ae310967d23339a8c0932c |
src/core/migrations/20261121150000-feed-filter-steps.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | // The filter set a viewer chose on the feed (an app, or crew/mine/ships), kept as steps so the | |
| 2 | // last one can be taken back (#15071). A step with both columns empty is "no filter". | |
| 3 | export default ` | |
| 4 | CREATE TABLE feed_filter_step ( | |
| 5 | viewer_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 6 | seq INTEGER NOT NULL, | |
| 7 | show TEXT NOT NULL, | |
| 8 | app TEXT NOT NULL, | |
| 9 | PRIMARY KEY (viewer_id, seq) | |
| 10 | ) WITHOUT ROWID; | |
| 11 | `; |
src/feed/saved_filter.ts added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | /** | |
| 2 | * The filter set a viewer chose on the feed, kept per account and stepped back. A set is an app | |
| 3 | * (`?app=`) or a narrowing (`?show=`), never both: an app wins. Stored text is user text, so it is | |
| 4 | * read back through the same checks as the address (`parseShow`, `isAppName`) and a value that | |
| 5 | * fails them is no filter. The newest step is the current set; `stepBack` drops it. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { isAppName } from "./app_filter.ts"; | |
| 10 | import { parseShow, type Show } from "./mine.ts"; | |
| 11 | ||
| 12 | export interface FilterSet { | |
| 13 | readonly show?: Show; | |
| 14 | readonly app?: string; | |
| 15 | } | |
| 16 | ||
| 17 | /** Steps kept per viewer; older ones fall off. */ | |
| 18 | export const STEPS_KEPT = 20; | |
| 19 | ||
| 20 | /** The set a raw pair of values names, checked: an unknown value is no filter. */ | |
| 21 | export function filterSetOf(show: string | null | undefined, app: string | null | undefined): FilterSet { | |
| 22 | const a = app !== null && app !== undefined && isAppName(app) ? app : undefined; | |
| 23 | if (a !== undefined) return { app: a }; | |
| 24 | const s = parseShow(show ?? null); | |
| 25 | return s === undefined ? {} : { show: s }; | |
| 26 | } | |
| 27 | ||
| 28 | const same = (a: FilterSet, b: FilterSet): boolean => a.show === b.show && a.app === b.app; | |
| 29 | ||
| 30 | /** The query a set reads as on `/feed`; the empty set says so out loud (`show=all`). */ | |
| 31 | export function filterQuery(set: FilterSet): string { | |
| 32 | if (set.app !== undefined) return `app=${encodeURIComponent(set.app)}`; | |
| 33 | return `show=${set.show ?? "all"}`; | |
| 34 | } | |
| 35 | ||
| 36 | function steps(db: Database, viewerId: string): { seq: number; set: FilterSet }[] { | |
| 37 | return db | |
| 38 | .query<{ seq: number; show: string; app: string }, [string]>( | |
| 39 | "SELECT seq, show, app FROM feed_filter_step WHERE viewer_id = ?1 ORDER BY seq DESC", | |
| 40 | ) | |
| 41 | .all(viewerId) | |
| 42 | .map((r) => ({ seq: r.seq, set: filterSetOf(r.show, r.app) })); | |
| 43 | } | |
| 44 | ||
| 45 | /** The viewer's saved set: the empty one when nothing was saved. */ | |
| 46 | export function savedFilter(db: Database, viewerId: string): FilterSet { | |
| 47 | return steps(db, viewerId)[0]?.set ?? {}; | |
| 48 | } | |
| 49 | ||
| 50 | /** Whether there is a step to go back from. */ | |
| 51 | export function canStepBack(db: Database, viewerId: string): boolean { | |
| 52 | return ( | |
| 53 | db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM feed_filter_step WHERE viewer_id = ?1").get(viewerId)! | |
| 54 | .n > 0 | |
| 55 | ); | |
| 56 | } | |
| 57 | ||
| 58 | /** Save a set as the newest step; the one already current is not saved twice. */ | |
| 59 | export function saveFilter(db: Database, viewerId: string, set: FilterSet): void { | |
| 60 | const all = steps(db, viewerId); | |
| 61 | if (same(all[0]?.set ?? {}, set)) return; | |
| 62 | const seq = (all[0]?.seq ?? 0) + 1; | |
| 63 | db.query("INSERT INTO feed_filter_step (viewer_id, seq, show, app) VALUES (?1, ?2, ?3, ?4)").run( | |
| 64 | viewerId, | |
| 65 | seq, | |
| 66 | set.show ?? "", | |
| 67 | set.app ?? "", | |
| 68 | ); | |
| 69 | db.query("DELETE FROM feed_filter_step WHERE viewer_id = ?1 AND seq <= ?2").run(viewerId, seq - STEPS_KEPT); | |
| 70 | } | |
| 71 | ||
| 72 | /** Take the newest step back; the set that was current before it is current again. */ | |
| 73 | export function stepBack(db: Database, viewerId: string): FilterSet { | |
| 74 | const top = steps(db, viewerId)[0]; | |
| 75 | if (top !== undefined) db.query("DELETE FROM feed_filter_step WHERE viewer_id = ?1 AND seq = ?2").run(viewerId, top.seq); | |
| 76 | return savedFilter(db, viewerId); | |
| 77 | } |
src/http/server.ts +2
| @@ -367,6 +367,7 @@ import { keeperAnswer } from "../web/studio/keeper_row.ts"; | ||
| 367 | 367 | import { homeArchive, homeArchived, homeArchiveUndo } from "../web/studio/home_archive.ts"; |
| 368 | 368 | import { liveFeedFragment } from "../web/studio/feed.ts"; |
| 369 | 369 | import { likeSubmit } from "../web/studio/like.ts"; |
| 370 | import { filterBackSubmit } from "../web/studio/filter_back.ts"; | |
| 370 | 371 | import { HOME_REGIONS } from "../web/studio/home_last.ts"; |
| 371 | 372 | import { serviceWorker } from "../web/sw.ts"; |
| 372 | 373 | import { offlinePage } from "../web/pages/offline.ts"; |
| @@ -1461,6 +1462,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1461 | 1462 | router.add("GET", "/tell", shareTellPage); |
| 1462 | 1463 | // A like from a card without a script (#7751): the feed's `liked`, then back to the feed. |
| 1463 | 1464 | router.add("POST", "/feed/like", likeSubmit); |
| 1465 | router.add("POST", "/feed/back", filterBackSubmit); | |
| 1464 | 1466 | router.add("POST", "/:owner/:name/pulls/:number/checks", pullChecksSubmit); |
| 1465 | 1467 | router.add("POST", "/:owner/:name/stuck", stuckSubmit); |
| 1466 | 1468 | router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit); |
src/tui/screens/feed.ts +24 −1
| @@ -15,12 +15,14 @@ | ||
| 15 | 15 | * or only what shipped (its `show` option, the page's `?show=crew|mine|ships`; a second press |
| 16 | 16 | * clears it); `a` shows only the app of the post under the cursor, through the page's `appFilterOf` |
| 17 | 17 | * (`?app=`), and a second `a` shows every app again; `n` reads the next page from the cursor the |
| 18 | * last returned. | |
| 18 | * last returned. The filter is the one the page saved (`feed/saved_filter.ts`): the screen opens | |
| 19 | * with it, keeps each choice, and `b` takes the last choice back, as the page's button does. | |
| 19 | 20 | */ |
| 20 | 21 | |
| 21 | 22 | import { addCommentThrough } from "../../actions/issues.ts"; |
| 22 | 23 | import { getIssue } from "../../core/issues.ts"; |
| 23 | 24 | import { lastVisit } from "../../core/home_visit.ts"; |
| 25 | import { canStepBack, filterSetOf, saveFilter, savedFilter, stepBack, type FilterSet } from "../../feed/saved_filter.ts"; | |
| 24 | 26 | import { newLine, newSince } from "../../feed/last_seen.ts"; |
| 25 | 27 | import { appFilterOf, onlyLine } from "../../feed/app_filter.ts"; |
| 26 | 28 | import { parseCursor, readFeed } from "../../feed/feed.ts"; |
| @@ -99,6 +101,18 @@ export function feedScreen(f: Session, ctx: Ctx): Screen { | ||
| 99 | 101 | next = page.next_cursor; |
| 100 | 102 | ctx.invalidate(); |
| 101 | 103 | }; |
| 104 | /** Take a saved set as the screen's filter: an app the viewer can still read, or a narrowing. */ | |
| 105 | const apply = (set: FilterSet): void => { | |
| 106 | const found = set.app === undefined || f.user === undefined ? undefined : appFilterOf(f.db, f.user, set.app); | |
| 107 | only = found?.kind === "app" ? { repoId: found.repo.id, app: found.app } : undefined; | |
| 108 | show = only === undefined ? set.show : undefined; | |
| 109 | timeline = false; | |
| 110 | }; | |
| 111 | /** Keep what the screen now shows as the viewer's saved set, as the page does. */ | |
| 112 | const save = (): void => { | |
| 113 | if (f.user !== undefined) saveFilter(f.db, f.user.id, filterSetOf(show ?? null, only?.app)); | |
| 114 | }; | |
| 115 | if (f.user !== undefined) apply(savedFilter(f.db, f.user.id)); | |
| 102 | 116 | read(); |
| 103 | 117 | // The page's head line, read-only: the terminal never moves the mark. |
| 104 | 118 | if (f.user !== undefined) { |
| @@ -208,6 +222,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen { | ||
| 208 | 222 | binding(["t"], timeline || show !== undefined ? "ranked" : "newest first"), |
| 209 | 223 | binding(["c"], show === "crew" ? "everyone's" : "only crew"), |
| 210 | 224 | binding(["m"], show === "mine" ? "everyone's" : "only mine"), |
| 225 | ...(f.user !== undefined && canStepBack(f.db, f.user.id) ? [binding(["b"], "previous filter")] : []), | |
| 211 | 226 | binding(["s"], show === "ships" ? "everyone's" : "only ships"), |
| 212 | 227 | ...(only !== undefined || items[state.index] !== undefined ? [binding(["a"], only === undefined ? "only this app" : "every app")] : []), |
| 213 | 228 | binding(["esc", "q"], "back"), |
| @@ -285,6 +300,13 @@ export function feedScreen(f: Session, ctx: Ctx): Screen { | ||
| 285 | 300 | timeline = show !== undefined ? false : !timeline; |
| 286 | 301 | show = undefined; |
| 287 | 302 | } |
| 303 | save(); | |
| 304 | items.length = 0; | |
| 305 | state.index = 0; | |
| 306 | state.offset = 0; | |
| 307 | read(); | |
| 308 | } else if (e.key === "b" && f.user !== undefined && canStepBack(f.db, f.user.id)) { | |
| 309 | apply(stepBack(f.db, f.user.id)); | |
| 288 | 310 | items.length = 0; |
| 289 | 311 | state.index = 0; |
| 290 | 312 | state.offset = 0; |
| @@ -296,6 +318,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen { | ||
| 296 | 318 | only = found?.kind === "app" ? { repoId: found.repo.id, app: found.app } : undefined; |
| 297 | 319 | timeline = false; |
| 298 | 320 | show = undefined; |
| 321 | save(); | |
| 299 | 322 | items.length = 0; |
| 300 | 323 | state.index = 0; |
| 301 | 324 | state.offset = 0; |
src/web/studio/feed.ts +5 −3
| @@ -33,6 +33,7 @@ import { getRepo, getRepoById } from "../../core/repos.ts"; | ||
| 33 | 33 | import { DEFAULT_PAGE, looksForEnv, lookUrl } from "../../core/looks.ts"; |
| 34 | 34 | import { mayFetchLook, pictured } from "../pages/looks.ts"; |
| 35 | 35 | import { dividers } from "./day_divider.ts"; |
| 36 | import { backButton } from "./filter_back.ts"; | |
| 36 | 37 | import { html, raw, type Html } from "../html.ts"; |
| 37 | 38 | import { DISMISS_KEY } from "../script_keys.ts"; |
| 38 | 39 | import { fragment } from "../layout.ts"; |
| @@ -419,7 +420,7 @@ function showChips(show: Show | undefined): Html { | ||
| 419 | 420 | return html`<nav class="bar small" data-show="${show ?? "all"}" aria-label="Narrow the feed"> |
| 420 | 421 | ${SHOW_VALUES.map((v) => { |
| 421 | 422 | const on = show === v; |
| 422 | return html`<a class="btn" data-variant="${on ? "outline" : "ghost"}" data-size="sm" data-show-chip="${v}" href="${on ? "/feed" : `/feed?show=${v}`}" ${on ? html`aria-current="true"` : html``}>${SHOW_LABEL[v]}</a>`; | |
| 423 | return html`<a class="btn" data-variant="${on ? "outline" : "ghost"}" data-size="sm" data-show-chip="${v}" href="/feed?show=${on ? "all" : v}" ${on ? html`aria-current="true"` : html``}>${SHOW_LABEL[v]}</a>`; | |
| 423 | 424 | })} |
| 424 | 425 | </nav>`; |
| 425 | 426 | } |
| @@ -433,7 +434,7 @@ function filterLine(filter: AppFilter): Html | null { | ||
| 433 | 434 | if (filter.kind === "unknown") return html`<p class="small muted" data-app-filter="unknown">${APP_UNKNOWN_LINE}</p>`; |
| 434 | 435 | return html`<p class="bar small" data-app-filter="${filter.app}"> |
| 435 | 436 | <span>${ONLY_LEAD}<a href="/${filter.app}">${filter.app}</a></span> |
| 436 | <a href="/feed">Clear</a> | |
| 437 | <a href="/feed?show=all">Clear</a> | |
| 437 | 438 | </p>`; |
| 438 | 439 | } |
| 439 | 440 | |
| @@ -507,7 +508,7 @@ export function feedRegion(user: User, ctx: Ctx): Html { | ||
| 507 | 508 | */ |
| 508 | 509 | export function caughtUp(items: readonly FeedItem[], next: string | null, cursor?: unknown, timeline = false, show?: Show, app?: string): Html | null { |
| 509 | 510 | const keep = show === undefined ? "" : `&show=${show}`; |
| 510 | const only = show === undefined ? "" : `?show=${show}`; | |
| 511 | const only = `?show=${show ?? "all"}`; | |
| 511 | 512 | // Ranked by score, not time: the last card is not always the oldest. |
| 512 | 513 | const oldest = items.reduce<string | undefined>((min, item) => (min === undefined || item.at < min ? item.at : min), undefined); |
| 513 | 514 | // A page the filters emptied can still have older posts behind it: keep the way on. |
| @@ -565,6 +566,7 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>): | ||
| 565 | 566 | > |
| 566 | 567 | ${filterLine(filter)} |
| 567 | 568 | ${filter.kind === "app" ? null : showChips(show)} |
| 569 | ${backButton(ctx, user)} | |
| 568 | 570 | ${chipsBar(user, ctx, items)} |
| 569 | 571 | ${thoughts.map((t) => thoughtCard(t, user.username, placed.get(t.id)))} |
| 570 | 572 | ${items.length === 0 && thoughts.length === 0 |
src/web/studio/filter_back.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | /** | |
| 2 | * The feed's saved filter on the page: a bare `/feed` opens with the set the viewer last chose, a | |
| 3 | * chosen one is saved, and POST /feed/back takes the last choice back (`feed/saved_filter.ts`). | |
| 4 | */ | |
| 5 | ||
| 6 | import { appFilterOf } from "../../feed/app_filter.ts"; | |
| 7 | import { canStepBack, filterQuery, filterSetOf, saveFilter, savedFilter, stepBack } from "../../feed/saved_filter.ts"; | |
| 8 | import type { Ctx } from "../../http/context.ts"; | |
| 9 | import type { User } from "../../core/users.ts"; | |
| 10 | import { html, type Html } from "../html.ts"; | |
| 11 | import { signInFirst } from "../chrome.ts"; | |
| 12 | import { readForm } from "../form.ts"; | |
| 13 | import { flashOrJson } from "../layout.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * A `/feed` with no query goes to the saved set; one that names a set saves it, when the | |
| 17 | * browser says the request is the site's own. Other parameters, a place deeper in the timeline | |
| 18 | * (`before`, `cursor`) and any other request leave the saved set alone. | |
| 19 | */ | |
| 20 | export function applySavedFilter(ctx: Ctx, user: User): Response | undefined { | |
| 21 | const q = ctx.url.searchParams; | |
| 22 | if (q.has("before") || q.has("cursor")) return undefined; | |
| 23 | if (q.size === 0) { | |
| 24 | const saved = savedFilter(ctx.app.db, user.id); | |
| 25 | // An app the viewer can no longer read is no filter, not a line saying so. | |
| 26 | const app = saved.app === undefined ? undefined : appFilterOf(ctx.app.db, user, saved.app); | |
| 27 | if (saved.show === undefined && (app === undefined || app.kind !== "app")) return undefined; | |
| 28 | return new Response(null, { status: 302, headers: { location: `/feed?${filterQuery(saved)}`, "cache-control": "private, no-store" } }); | |
| 29 | } | |
| 30 | if (!q.has("show") && !q.has("app")) return undefined; | |
| 31 | // A save is a write: only a request the browser says came from this site, or from the address | |
| 32 | // bar, makes one. A missing header (old clients, prefetch) saves nothing. | |
outdated
HIGH: a state change on GET. Saving the filter here is a mutation without a real same-origin check; a request with no Sec-Fetch-Site header (older browsers, some clients, image/link prefetch) is saved. Require sec-fetch-site to be same-origin or none (or an Origin match), else do not save. Better: have the chips post. |
||
| 33 | const site = ctx.request.headers.get("sec-fetch-site"); | |
| 34 | if (site !== "same-origin" && site !== "none") return undefined; | |
| 35 | const asked = filterSetOf(q.get("show"), q.get("app")); | |
| 36 | const valid = q.get("show") === "all" || asked.show !== undefined || (asked.app !== undefined && appFilterOf(ctx.app.db, user, asked.app).kind === "app"); | |
| 37 | if (valid) saveFilter(ctx.app.db, user.id, asked); | |
| 38 | return undefined; | |
| 39 | } | |
| 40 | ||
| 41 | /** The visible way back: a button that posts, drawn only when there is a choice to take back. */ | |
| 42 | export function backButton(ctx: Ctx, user: User): Html | null { | |
| 43 | if (!canStepBack(ctx.app.db, user.id)) return null; | |
| 44 | return html`<form method="post" action="/feed/back" data-filter-back> | |
| 45 | <button type="submit" class="btn" data-variant="ghost" data-size="sm">Back to the previous filter</button> | |
| 46 | </form>`; | |
| 47 | } | |
| 48 | ||
| 49 | export async function filterBackSubmit(ctx: Ctx): Promise<Response> { | |
| 50 | const viewer = ctx.auth.user; | |
| 51 | if (!viewer) return signInFirst(ctx); | |
| 52 | const form = await readForm(ctx, "rw"); | |
| 53 | if (form instanceof Response) return form; | |
| 54 | const now = stepBack(ctx.app.db, viewer.id); | |
| 55 | return flashOrJson(ctx, "/feed", { message: "Back to the previous filter." }, { filter: now }); | |
| 56 | } |
src/web/studio/home.ts +5
| @@ -69,6 +69,7 @@ import { needsYouSection } from "./asks_page.ts"; | ||
| 69 | 69 | import { flowCards } from "./flow_card.ts"; |
| 70 | 70 | import { parseBefore } from "../../feed/timeline.ts"; |
| 71 | 71 | import { parseCursor } from "../../feed/feed.ts"; |
| 72 | import { applySavedFilter } from "./filter_back.ts"; | |
| 72 | 73 | import { composer, publicFeed, feedJs, feedNote, feedRegion } from "./feed.ts"; |
| 73 | 74 | import { heldLine } from "./held.ts"; |
| 74 | 75 | import { waitingLine } from "./kpi_row.ts"; |
| @@ -358,6 +359,10 @@ export async function feedPage(ctx: Ctx): Promise<Response> { | ||
| 358 | 359 | headers: { "content-type": "text/plain; charset=utf-8" }, |
| 359 | 360 | }); |
| 360 | 361 | } |
| 362 | if (user) { | |
| 363 | const moved = applySavedFilter(ctx, user); | |
| 364 | if (moved !== undefined) return moved; | |
| 365 | } | |
| 361 | 366 | if (!user) { |
| 362 | 367 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 363 | 368 | const ships = timePhase(ctx.request, "feed", () => publicShips(ctx.app.db)); |
test/feed-app-link.test.ts +1 −1
| @@ -58,7 +58,7 @@ describe("feed app link and argument", () => { | ||
| 58 | 58 | expect(one).toContain("<span>Only <a"); |
| 59 | 59 | expect(one).toContain("data-app-filter=\"alice/open\""); |
| 60 | 60 | expect(one).not.toContain("hello from other"); |
| 61 | expect(one).toContain('href="/feed">Clear'); | |
| 61 | expect(one).toContain('href="/feed?show=all">Clear'); | |
| 62 | 62 | }); |
| 63 | 63 | |
| 64 | 64 | test("the MCP feed tool takes app and says the same words", async () => { |
test/feed-caught-up.test.ts +1 −1
| @@ -67,7 +67,7 @@ describe("the timeline's caught-up line", () => { | ||
| 67 | 67 | const older = await home(href![1]!.replaceAll("&", "&")); |
| 68 | 68 | expect(older).toContain("data-item="); |
| 69 | 69 | expect(older).toContain("That's everything"); |
| 70 | expect(older).toContain('<a href="/feed">Newest</a>'); | |
| 70 | expect(older).toContain('<a href="/feed?show=all">Newest</a>'); | |
| 71 | 71 | expect(text).not.toContain(">Newest<"); |
| 72 | 72 | }); |
| 73 | 73 |
test/feed-filter.test.ts +1 −1
| @@ -59,7 +59,7 @@ describe("the one-app feed filter", () => { | ||
| 59 | 59 | const body = await (await get("/feed?app=alice/open")).text(); |
| 60 | 60 | expect(body).toContain('data-app-filter="alice/open"'); |
| 61 | 61 | expect(body).toContain("Only <a"); |
| 62 | expect(body).toContain('href="/feed">Clear'); | |
| 62 | expect(body).toContain('href="/feed?show=all">Clear'); | |
| 63 | 63 | expect(body).toContain("hello from open"); |
| 64 | 64 | expect(body).not.toContain("hello from other"); |
| 65 | 65 | }); |
test/feed-filters.test.ts +1 −1
| @@ -144,7 +144,7 @@ describe("the feed's three one-tap filters", () => { | ||
| 144 | 144 | for (const v of ["crew", "mine", "ships"] as const) { |
| 145 | 145 | const on = await get(`?show=${v}`); |
| 146 | 146 | expect(on).toContain(`data-show="${v}"`); |
| 147 | expect(on).toMatch(new RegExp(`data-show-chip="${v}" href="/feed" aria-current="true"`)); | |
| 147 | expect(on).toMatch(new RegExp(`data-show-chip="${v}" href="/feed\\?show=all" aria-current="true"`)); | |
| 148 | 148 | for (const other of ["crew", "mine", "ships"].filter((o) => o !== v)) |
| 149 | 149 | expect(on).toContain(`data-show-chip="${other}" href="/feed?show=${other}"`); |
| 150 | 150 | } |
test/feed-saved-filter.test.ts added +188
| @@ -0,0 +1,188 @@ | ||
| 1 | /** | |
| 2 | * The feed's filter is saved per account, validated when read back, and the last choice can be | |
| 3 | * taken back: a bare /feed opens with the saved set, POST /feed/back steps to the one before. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createIssue } from "../src/core/issues.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { feedScreen } from "../src/tui/screens/feed.ts"; | |
| 15 | import { Screen as Surface } from "../src/tui/term/screen.ts"; | |
| 16 | import { theme } from "../src/tui/ui/theme.ts"; | |
| 17 | import type { Ctx } from "../src/tui/app/app.ts"; | |
| 18 | import type { Session } from "../src/tui/session.ts"; | |
| 19 | import type { KeyEvent } from "../src/tui/term/input.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { canStepBack, filterSetOf, saveFilter, savedFilter, stepBack } from "../src/feed/saved_filter.ts"; | |
| 22 | import { promote } from "./helpers/members.ts"; | |
| 23 | ||
| 24 | describe("the saved filter set", () => { | |
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | let servers: Servers; | |
| 28 | let alice: User; | |
| 29 | let bob: User; | |
| 30 | let cookie: string; | |
| 31 | ||
| 32 | // Saving needs the browser's word that the request is the site's own. | |
| 33 | const get = (q: string, site = "same-origin", as = () => cookie) => | |
| 34 | fetch(`${servers.url}/feed${q}`, { headers: { cookie: as(), "sec-fetch-site": site }, redirect: "manual" }); | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | dataDir = await mkdtemp(join(tmpdir(), "forge-feed-saved-")); | |
| 38 | app = createApp({ dataDir, port: 0 }); | |
| 39 | servers = await serve(app); | |
| 40 | const mk = async (username: string, first = false) => { | |
| 41 | const r = await createUser(app.db, { | |
| 42 | origin: "seed", trusted: true, username, allowReserved: true, | |
| 43 | email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first, | |
| 44 | }); | |
| 45 | if (!r.ok) throw new Error(r.error); | |
| 46 | promote(app.db, r.value); | |
| 47 | return r.value; | |
| 48 | }; | |
| 49 | await mk("root", true); | |
| 50 | alice = await mk("alice"); | |
| 51 | bob = await mk("bob"); | |
| 52 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 53 | const r = await createRepo(app, bob, { name: "theirs", visibility: "public" }); | |
| 54 | if (!r.ok) throw new Error("repo"); | |
| 55 | const i = createIssue(app.db, { repoId: r.value.id, authorId: bob.id, title: "bob asks" }); | |
| 56 | if (!i.ok) throw new Error(i.error); | |
| 57 | app.bus.append({ kind: "issue.opened", repoId: r.value.id, actorId: bob.id, payload: { number: i.value.number } }); | |
| 58 | }, 30_000); | |
| 59 | ||
| 60 | afterAll(async () => { | |
| 61 | servers.stop(); | |
| 62 | app.close(); | |
| 63 | await rm(dataDir, { recursive: true, force: true }); | |
| 64 | }); | |
| 65 | ||
| 66 | test("a choice is saved, survives a reload, and can be stepped back", async () => { | |
| 67 | expect((await get("")).status).toBe(200); | |
| 68 | expect(await (await get("?show=mine")).text()).toContain("data-filter-back"); | |
| 69 | const reload = await get(""); | |
| 70 | expect(reload.status).toBe(302); | |
| 71 | expect(reload.headers.get("location")).toBe("/feed?show=mine"); | |
| 72 | ||
| 73 | await get("?app=bob/theirs"); | |
| 74 | expect((await get("")).headers.get("location")).toBe("/feed?app=bob%2Ftheirs"); | |
| 75 | expect(await (await get("?app=bob/theirs")).text()).toContain("data-filter-back"); | |
| 76 | ||
| 77 | const back = await fetch(`${servers.url}/feed/back`, { | |
| 78 | method: "POST", | |
| 79 | headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 80 | body: "", | |
outdated
This test passes without per-account storage: bob never saved anything, so a 200 is what any implementation gives. Save a set as alice, then assert bob's bare /feed is 200 while alice's is 302, and that bob's back button is absent. |
||
| 81 | redirect: "manual", | |
| 82 | }); | |
| 83 | expect(back.status).toBeLessThan(400); | |
| 84 | expect((await get("")).headers.get("location")).toBe("/feed?show=mine"); | |
| 85 | ||
| 86 | // Clearing is a choice too; back returns to it. | |
| 87 | await get("?show=all"); | |
| 88 | expect((await get("")).status).toBe(200); | |
| 89 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 90 | }); | |
| 91 | ||
| 92 | test("another account's choices are its own", async () => { | |
| 93 | await get("?show=ships"); | |
| 94 | const bobCookie = () => `forge_session=${createSession(app.db, bob.id).token}`; | |
| 95 | expect((await get("", "same-origin", () => cookie)).status).toBe(302); | |
| 96 | const theirs = await get("", "same-origin", bobCookie); | |
| 97 | expect(theirs.status).toBe(200); | |
| 98 | expect(await theirs.text()).not.toContain("data-filter-back"); | |
| 99 | expect(savedFilter(app.db, bob.id)).toEqual({}); | |
| 100 | await get("?show=all"); // leave alice as the other tests expect | |
| 101 | }); | |
| 102 | ||
| 103 | test("a bare /feed with other parameters is not redirected; one with none is", async () => { | |
| 104 | await get("?show=crew"); | |
| 105 | expect((await get("?kind=issue")).status).toBe(200); | |
| 106 | expect((await get("?person=bob")).status).toBe(200); | |
| 107 | expect((await get("")).status).toBe(302); | |
| 108 | await get("?show=all"); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a save needs a same-site request: no header, cross-site and same-site all save nothing", async () => { | |
| 112 | for (const site of ["", "cross-site", "same-site"]) { | |
| 113 | const headers: Record<string, string> = { cookie }; | |
| 114 | if (site !== "") headers["sec-fetch-site"] = site; | |
| 115 | const res = await fetch(`${servers.url}/feed?show=ships`, { headers, redirect: "manual" }); | |
| 116 | expect(res.status).toBe(200); | |
| 117 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 118 | } | |
| 119 | await get("?show=ships", "none"); // typed in the address bar | |
| 120 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "ships" }); | |
| 121 | await get("?show=all"); | |
| 122 | }); | |
| 123 | ||
| 124 | test("the terminal opens with the saved set, keeps c, m, s and a, and b steps back", () => { | |
| 125 | const ctx = { theme: theme("dark"), invalidate() {}, toast() {}, push() {}, pop() {}, copy() {}, hit() {}, setCursor() {} } as unknown as Ctx; | |
| 126 | const press = (screen: ReturnType<typeof feedScreen>, key: string) => | |
| 127 | screen.key!({ type: "key", key, ctrl: false, alt: false, shift: false } as KeyEvent); | |
| 128 | const open = () => feedScreen({ app, db: app.db, user: alice } as unknown as Session, ctx); | |
| 129 | const helps = (s: ReturnType<typeof feedScreen>) => s.keys.map((k) => k.help); | |
| 130 | const text = (s: ReturnType<typeof feedScreen>) => { | |
| 131 | const surface = new Surface(140, 44); | |
| 132 | s.render({ x: 0, y: 0, w: 140, h: 44 }, surface); | |
| 133 | return surface.toText(); | |
| 134 | }; | |
| 135 | ||
| 136 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 137 | app.db.run("DELETE FROM feed_filter_step WHERE viewer_id = ?1", [alice.id]); | |
| 138 | const first = open(); | |
| 139 | expect(helps(first)).not.toContain("previous filter"); | |
| 140 | press(first, "b"); // nothing to step back to | |
| 141 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 142 | ||
| 143 | press(first, "c"); | |
| 144 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "crew" }); | |
| 145 | press(first, "m"); | |
| 146 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "mine" }); | |
| 147 | press(first, "s"); | |
| 148 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "ships" }); | |
| 149 | expect(helps(first)).toContain("previous filter"); | |
| 150 | ||
| 151 | // A new screen opens with the saved set. | |
| 152 | const second = open(); | |
| 153 | expect(helps(second)).toContain("everyone's"); | |
| 154 | expect(text(second)).not.toContain("alice asks"); | |
| 155 | ||
| 156 | press(second, "b"); | |
| 157 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "mine" }); | |
| 158 | press(second, "b"); | |
| 159 | expect(savedFilter(app.db, alice.id)).toEqual({ show: "crew" }); | |
| 160 | ||
| 161 | // `a` saves the app of the post under the cursor. | |
| 162 | const third = open(); | |
| 163 | press(third, "c"); // second press clears: crew -> none | |
| 164 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 165 | press(third, "a"); | |
| 166 | expect(savedFilter(app.db, alice.id)).toEqual({ app: "bob/theirs" }); | |
| 167 | press(third, "a"); | |
| 168 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 169 | }); | |
| 170 | ||
| 171 | test("a stored value that fails the checks is no filter; stepping back unwinds to none", () => { | |
| 172 | app.db.run("INSERT INTO feed_filter_step (viewer_id, seq, show, app) VALUES (?1, 900, 'bogus', '../etc')", [bob.id]); | |
| 173 | expect(savedFilter(app.db, bob.id)).toEqual({}); | |
| 174 | expect(filterSetOf("crew", "not an app")).toEqual({ show: "crew" }); | |
| 175 | saveFilter(app.db, bob.id, { show: "ships" }); | |
| 176 | expect(savedFilter(app.db, bob.id)).toEqual({ show: "ships" }); | |
| 177 | saveFilter(app.db, bob.id, { show: "ships" }); | |
| 178 | expect(stepBack(app.db, bob.id)).toEqual({}); | |
| 179 | stepBack(app.db, bob.id); | |
| 180 | expect(canStepBack(app.db, bob.id)).toBe(false); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a choice from another site is not saved", async () => { | |
| 184 | const res = await get("?show=ships", "cross-site"); | |
| 185 | expect(res.status).toBe(200); | |
| 186 | expect(savedFilter(app.db, alice.id)).toEqual({}); | |
| 187 | }); | |
| 188 | }); |
MEDIUM: the redirect rebuilds the query from the saved set only, so any other bare-/feed parameter (chips/kind/person or others the feed reads) is dropped. Only redirect when the query has no params at all, or carry the others over; add a test.