Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 78996182e946bfe204dafbf962514b827e443c0e
parent cc07dadffe4d74662736e92b5a2345c1268886d7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 07:45:49 -0500

umtool: the Posts library page, /tools/library -- a private trending library read through the editor: topics on the left with their post, unjudged and new counts and what each watch is doing (paused and failing told apart), the posts of a view drawn with the archive viewer's body, their captured screenshot, pictures and video, the thread context a capture read, "Gone from the page at <time>" and a capture's own state verbatim; Keep / Drop / Later / Clear per post or per thread, a note, a selection, bulk over the filter behind a confirm that states the count, undo of the last press, and keys (j k a d l c t n x u / g m ?, Shift for bulk); filters by judgement, new since Mark seen, gone, media, author and words, in the URL; a Watch switch per topic with its interval, hours and "screenshot everything new"; Mark seen; and the two-press purge of dropped posts' captures. Every press is the editor's action as the operator; the page streams behind a placeholder of its shape, prefetches nothing, reads its view again through GET /api/library after a press, and says in a sentence when the editor is down or holds no library. Found from Tools, the rail and the jump palette

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/library/route.ts | 25+++++++++++++++++++++++++
Mumtool/app/globals.css | 3+++
Aumtool/app/tools/library/page.tsx | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/tools/page.tsx | 3++-
Mumtool/components/AppNav.tsx | 2++
Mumtool/components/shell/JumpPalette.tsx | 2++
Aumtool/components/tools/library/LibraryView.tsx | 864+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 6++++++
Mumtool/lib/library/filters.mjs | 2++
Aumtool/lib/library/load.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/library/media.mjs | 5+----
Aumtool/lib/library/mediaSrc.mjs | 12++++++++++++
Mumtool/lib/library/route.ts | 6+++++-
13 files changed, 1094 insertions(+), 6 deletions(-)

diff --git a/umtool/app/api/library/route.ts b/umtool/app/api/library/route.ts @@ -0,0 +1,25 @@ +import { parseLibraryView } from "@/lib/library/filters.mjs"; +import { loadLibrary } from "@/lib/library/load"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library?lib=&topic=&state=&gone=1&media=1&author=&q=&new=1&offset= +// -> what the Posts library page shows for that view (lib/library/load.ts LibraryData): +// { ok: true, libraries, lib, name, view, topics, posts, total, authors, pageSize } +// or { ok: false, reason, sentence } when the editor cannot be asked or holds no such library +// +// THE PAGE'S OWN READ, ASKED AGAIN AFTER A PRESS (lane posts-library): the same read the page makes +// when it is opened, through the editor (GET /api/ops/trending), so the rows on screen are the +// editor's after every keep, drop, watch or purge. READ ONLY. It carries a private library's posts, +// so a cross-site request, or one naming a host that is not this machine, is refused, and nothing +// caches it. +const PRIVATE = { "cache-control": "private, no-store", "cross-origin-resource-policy": "same-origin" }; + +export async function GET(request: Request) { + if (crossSiteRefusal(request.headers)) return Response.json({ error: "refused: the library is read by umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const sp = new URL(request.url).searchParams; + const params: Record<string, string> = {}; + for (const [k, v] of sp) if (!(k in params)) params[k] = v; + return Response.json(await loadLibrary(parseLibraryView(params)), { headers: PRIVATE }); +} diff --git a/umtool/app/globals.css b/umtool/app/globals.css @@ -19,6 +19,9 @@ (their stylesheet is the import above) and the verdict chip they draw. Named, not detected, as above. */ @source "../../common/components/report"; +/* The Posts library draws a post with the archive viewer's own body (lane + posts-library): that one file, named. */ +@source "../../common/components/PostBody.tsx"; /* =========================================================================== THE DESK AND THE READER (plans/umtool-redesign.md, "Design direction"; the diff --git a/umtool/app/tools/library/page.tsx b/umtool/app/tools/library/page.tsx @@ -0,0 +1,76 @@ +import { Suspense } from "react"; +import AppShell from "@/components/shell/AppShell"; +import LibraryView from "@/components/tools/library/LibraryView"; +import { loadLibrary } from "@/lib/library/load"; +import { parseLibraryView } from "@/lib/library/filters.mjs"; +import { e2eStreamDelay } from "@/lib/streamDelay"; +import { toolsHref } from "@/lib/hrefs"; + +export const dynamic = "force-dynamic"; + +// THE POSTS LIBRARY (plans/x-trending.md, slice 3; lane posts-library): a +// private X trending library, browsed by topic and judged — keep, drop, later +// — before anything of it is published. No project: a library is no piece's. +// +// EVERYTHING IS THE EDITOR'S. The page reads the library through the editor +// (lib/library/load.ts) and every press is the editor's action, written as +// the operator's (/api/library/*). umtool writes no file of a library and +// asks X nothing. Nothing here puts a library post into a project, a report, +// an article, the post archive or a site: publishing is a later, explicit act. +// +// IT STREAMS: the head is sent at once, and the library — the read through +// the editor, the slow part — behind a placeholder of its shape (page-level +// Suspense; no loading.tsx). + +async function LibraryBody({ view }: { view: ReturnType<typeof parseLibraryView> }) { + await e2eStreamDelay(); + const data = await loadLibrary(view); + if (!data.ok) { + return ( + <div data-stream-filled="library"> + <p role="status" data-library-unavailable={data.reason} className="m-0 max-w-[70ch] text-[13px] leading-[1.5] text-text-2"> + {data.sentence} + </p> + </div> + ); + } + return ( + <div data-stream-filled="library"> + <LibraryView data={data} /> + </div> + ); +} + +// What holds the library's place: the topics' column and a few post-shaped +// rows, at the widths the filled page has. +function LibraryPlaceholder() { + return ( + <div data-stream-skeleton="library" aria-hidden="true" className="grid gap-x-6 gap-y-4 md:grid-cols-[260px_minmax(0,1fr)]"> + <div className="space-y-2"> + {[0, 1, 2].map((n) => ( + <div key={n} className="h-[44px] animate-pulse rounded-md border border-seam bg-panel" /> + ))} + </div> + <div className="min-w-0 space-y-3"> + <div className="h-[34px] animate-pulse rounded-md border border-seam bg-panel" /> + {[0, 1, 2, 3].map((n) => ( + <div key={n} className="h-[132px] animate-pulse rounded-md border border-seam bg-panel" /> + ))} + </div> + </div> + ); +} + +export default async function PostsLibraryPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) { + const view = parseLibraryView(await searchParams); + return ( + <div className="flex h-full flex-col"> + <AppShell active="library" crumbs={[{ href: toolsHref(), label: "Tools" }, { label: "Posts library" }]} note="private: on no site" /> + <main className="deck-main flex-1 px-4 pb-6 pt-4" data-posts-library=""> + <Suspense fallback={<LibraryPlaceholder />}> + <LibraryBody view={view} /> + </Suspense> + </main> + </div> + ); +} diff --git a/umtool/app/tools/page.tsx b/umtool/app/tools/page.tsx @@ -1,6 +1,6 @@ import AppShell from "@/components/shell/AppShell"; import ToolList, { PILE_WHAT, type ToolEntry } from "@/components/tools/ToolList"; -import { benchHref, digestContextHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; +import { benchHref, digestContextHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, postsLibraryHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; import { TRIM_SETS } from "@/lib/trim"; export const dynamic = "force-dynamic"; @@ -29,6 +29,7 @@ export default function ToolsPage() { ]; const corpus: ToolEntry[] = [ { href: digestContextHref(), name: "context notes", what: "Each channel's suggested digest context note, its evidence, and your Yes or No", testid: "context" }, + { href: postsLibraryHref(), name: "posts library", what: "A private trending library's topics and posts: keep, drop or later, watch a topic, purge what was dropped", testid: "library" }, ]; const n = song.length + articles.length + montage.length + corpus.length; return ( diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -3,6 +3,7 @@ import { MODES } from "@/lib/types"; import { benchHref, digestContextHref, + postsLibraryHref, findHref, facesHref, homeHref, @@ -46,6 +47,7 @@ const TOOL_ITEMS = [ { href: sourcesHref(), label: "sources" }, { href: benchHref(), label: "bench" }, { href: digestContextHref(), label: "context" }, + { href: postsLibraryHref(), label: "library" }, ]; const PLACE_OF: Record<string, string> = { diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { benchHref, digestContextHref, + postsLibraryHref, createHref, facesHref, findHref, @@ -92,6 +93,7 @@ const FIXED: Item[] = [ { id: "sources", section: "Tools", label: "Sources", hint: "where the palette comes from", href: sourcesHref() }, { id: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() }, { id: "context", section: "Tools", label: "Channel context notes", hint: "each suggested digest note, its evidence, Yes or No", href: digestContextHref() }, + { id: "library", section: "Tools", label: "Posts library", hint: "a private trending library: keep, drop, later, watch", href: postsLibraryHref() }, // Each opens one line of /create (P5), its form open. { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -0,0 +1,864 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { PostBody, type PostCaptureView } from "yt-dlp-transcript-common/components/PostBody"; +import type { Post } from "yt-dlp-transcript-common/lib/posts"; +import { Badge } from "@/components/ui/badge"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { captureSentence, filterWords, goneSentence, libraryHref } from "@/lib/library/filters.mjs"; +import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "@/lib/library/keys.mjs"; +import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; +import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; +import type { LibraryData, LibraryPost, LibraryTopic, LibraryView as View } from "@/lib/library/load"; +import { cn } from "@/lib/utils"; + +// THE POSTS LIBRARY (app/tools/library/page.tsx): topics on the left, the +// posts of the view with their captured media in the body, and the presses. +// +// EVERY PRESS IS A POST TO /api/library/*, which is the editor's action +// written as the operator's. Nothing here writes a library's file, asks X +// anything, or offers a post to a project, a report or a site. +// +// NO LINK HERE PREFETCHES: every address of this page is a read through the +// editor, and a prefetch is that read made for a view nobody opened. +// +// THE WORDS: a post a trending page no longer shows is "Gone from the page at +// <time>" (lib/library/filters.mjs goneSentence) — a ranked list dropped it, +// which says nothing about the post. A capture's own state is shown as the +// capture job recorded it ("capture: <state> at <time>"). + +type Ok = Extract<LibraryData, { ok: true }>; +type Target = { id: string } | { thread: string }; +type JudgeState = "keep" | "drop" | "later" | "undecided"; +type UndoItem = { id?: string; thread?: string; state: string; note?: string }; +type Shown = NonNullable<LibraryPost["judgement"]>; +type Entry = NonNullable<NonNullable<LibraryPost["detail"]>["ownJudgement"]>; + +/** + * The judgement in force, by the library's one rule (common's xTrendingEffectiveJudgement): the operator's + * entry outranks an agent's; between two of one hand the post's own outranks its thread's. + */ +function inForce(own: Entry | undefined, thread: Entry | undefined): Shown | undefined { + if (own && thread) return own.by === "agent" && thread.by === "operator" ? { ...thread, from: "thread" } : own; + return own ?? (thread ? { ...thread, from: "thread" } : undefined); +} + +type PurgePlan = { posts: number; files: number; bytes: number; confirm: string; sentence: string; captureInFlight?: boolean }; + +const STATE_LABEL: Record<string, string> = { keep: "kept", drop: "dropped", later: "later" }; +const STATE_TABS: Array<{ state: string | null; label: string }> = [ + { state: null, label: "All" }, + { state: "unjudged", label: "Unjudged" }, + { state: "keep", label: "Kept" }, + { state: "drop", label: "Dropped" }, + { state: "later", label: "Later" }, +]; + +// A time, said the same on the server and in the browser (no locale, no zone +// of the reader's): "17 Nov 2026, 11:00 UTC". +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +export function utc(iso: string): string { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return iso; + const p = (n: number) => String(n).padStart(2, "0"); + return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}, ${p(d.getUTCHours())}:${p(d.getUTCMinutes())} UTC`; +} + +async function send(path: string, body: unknown): Promise<Record<string, unknown>> { + const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); + return j; +} + +/** The archive row a library post is drawn from. Never marked deleted: the library records no such thing. */ +function postOf(lib: string, row: LibraryPost): Post { + const d = row.detail?.post; + return { + id: row.id, + slug: `${lib}/${row.id}`, + channelSlug: lib, + author: row.author, + ...(row.authorName ? { authorName: row.authorName } : {}), + createdAt: row.createdAt, + uploadDate: row.createdAt.slice(0, 10).replace(/-/g, ""), + text: row.text, + url: row.url, + platform: "twitter", + isReply: d?.isReply ?? false, + isRepost: d?.isRepost ?? false, + links: d?.links ?? [], + ...(d?.replyTo ? { replyTo: d.replyTo } : {}), + ...(d?.quoted ? { quoted: d.quoted } : {}), + ...(d?.engagement ? { engagement: d.engagement } : {}), + ...(row.media.count ? { mediaCount: row.media.count } : {}), + }; +} + +function captureOf(lib: string, row: LibraryPost): PostCaptureView | null { + const files = row.detail?.capture; + if (!row.capture || !files) return null; + return { + capturedAt: row.capture.at, + state: row.capture.state, + ...(files.shot ? { shot: { src: libraryMediaSrc(lib, row.id, files.shot) } } : {}), + media: files.media.map((m) => ({ src: libraryMediaSrc(lib, row.id, m.name), name: m.name })), + }; +} + +function viewParams(view: View): Record<string, string> { + return Object.fromEntries(new URL(libraryHref({ ...view, lib: null, offset: 0 }), "http://umtool.invalid").searchParams); +} + +export default function LibraryView({ data: opened }: { data: Ok }) { + // The rows on screen: the page's own when it opens (or the view changes), then the editor's again + // after every press (GET /api/library, the same read). + const [data, setData] = useState(opened); + const { lib, view, topics, total } = data; + const router = useRouter(); + const hydrated = useHydrated(); + // The view is being read again after a press. NOT router.refresh(): several in a row (a press a + // second, from the keys) were seen to leave the last one unapplied until the next press. The read + // is asked of /api/library, and only the newest ask's answer is taken. + const [refreshing, setRefreshing] = useState(false); + const asked = useRef(0); + // What the last presses wrote, shown at once and until the rows are read again: each post's own entry + // and each thread's (null: removed). The editor's answer replaces them. + const [written, setWritten] = useState<{ posts: Map<string, Entry | null>; threads: Map<string, Entry | null> }>({ posts: new Map(), threads: new Map() }); + const posts: LibraryPost[] = useMemo(() => { + if (written.posts.size === 0 && written.threads.size === 0) return data.posts; + return data.posts.map((row) => { + if (!written.posts.has(row.id) && !written.threads.has(row.thread)) return row; + const own = written.posts.has(row.id) ? (written.posts.get(row.id) ?? undefined) : row.detail?.ownJudgement; + const thread = written.threads.has(row.thread) ? (written.threads.get(row.thread) ?? undefined) : row.detail?.threadJudgement; + const { judgement: _was, ...rest } = row; + const { ownJudgement: _o, threadJudgement: _t, ...detail } = row.detail ?? { post: { isReply: false, isRepost: false, links: [] }, firstSeenAt: row.createdAt }; + const now = inForce(own, thread); + return { ...rest, ...(now ? { judgement: now } : {}), detail: { ...detail, ...(own ? { ownJudgement: own } : {}), ...(thread ? { threadJudgement: thread } : {}) } }; + }); + }, [data.posts, written]); + const wrote = useCallback((set: UndoItem[]) => { + const at = new Date().toISOString(); + setWritten((was) => { + const next = { posts: new Map(was.posts), threads: new Map(was.threads) }; + for (const item of set) { + const entry: Entry | null = item.state === "undecided" ? null : { state: item.state as Entry["state"], ...(item.note ? { note: item.note } : {}), by: "operator", at }; + if (item.thread !== undefined) next.threads.set(item.thread, entry); + else if (item.id !== undefined) next.posts.set(item.id, entry); + } + return next; + }); + }, []); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<{ text: string; error?: boolean } | null>(null); + const [focus, setFocus] = useState(0); + const [scope, setScope] = useState<"post" | "thread">("post"); + const [selected, setSelected] = useState<Set<string>>(new Set()); + const [last, setLast] = useState<{ set: UndoItem[]; label: string } | null>(null); + const [bulk, setBulk] = useState<JudgeState | null>(null); + const [noteFor, setNoteFor] = useState<string | null>(null); + const [noteText, setNoteText] = useState(""); + const [help, setHelp] = useState(false); + const searchRef = useRef<HTMLInputElement>(null); + const cards = useRef(new Map<string, HTMLElement>()); + + const topic = view.topic ? (topics.find((t) => t.id === view.topic) ?? null) : null; + const at = Math.min(focus, Math.max(0, posts.length - 1)); + const current = posts[at] ?? null; + const here = useCallback((patch: Partial<View>) => libraryHref({ ...view, offset: 0, ...patch }), [view]); + const threadSizes = useMemo(() => { + const m = new Map<string, number>(); + for (const p of posts) m.set(p.thread, (m.get(p.thread) ?? 0) + 1); + return m; + }, [posts]); + + // A selection is of the rows shown: one that left the page is not judged by a later press. + useEffect(() => { + setSelected((s) => { + const shown = new Set(posts.map((p) => p.id)); + const next = new Set([...s].filter((id) => shown.has(id))); + return next.size === s.size ? s : next; + }); + }, [posts]); + + // The page was opened on another view (a filter, a topic, a page of posts): its rows. + useEffect(() => { + asked.current++; + setData(opened); + setWritten({ posts: new Map(), threads: new Map() }); + setRefreshing(false); + }, [opened]); + + const refresh = useCallback(async () => { + const mine = ++asked.current; + setRefreshing(true); + try { + const r = await fetch(`/api/library${new URL(libraryHref(view), window.location.origin).search}`, { cache: "no-store" }); + const next = (await r.json()) as LibraryData | { error?: string }; + if (mine !== asked.current) return; + if ("ok" in next && next.ok) { + // The editor's rows: what the presses were shown as ahead of them is theirs to say now. + setData(next); + setWritten({ posts: new Map(), threads: new Map() }); + } else { + setStatus({ text: "ok" in next ? next.sentence : (next.error ?? `The library could not be read again (HTTP ${r.status}).`), error: true }); + } + } catch (err) { + if (mine === asked.current) setStatus({ text: `The library could not be read again: ${err instanceof Error ? err.message : String(err)}`, error: true }); + } finally { + if (mine === asked.current) setRefreshing(false); + } + }, [view]); + + const run = useCallback( + async (what: () => Promise<string | void>) => { + if (busy) return; + setBusy(true); + try { + const said = await what(); + if (said) setStatus({ text: said }); + void refresh(); + } catch (err) { + setStatus({ text: err instanceof Error ? err.message : String(err), error: true }); + } finally { + setBusy(false); + } + }, + [busy, refresh], + ); + + const judgeTargets = useCallback( + (targets: Target[], state: JudgeState, note = "") => + run(async () => { + if (!targets.length) return; + const undo = undoSetOf(posts, targets) as UndoItem[]; + const set = pressSetOf(targets, state, note) as UndoItem[]; + const r = await send("/api/library/judge", { lib, set }); + wrote(set); + setLast({ set: undo, label: String(r.sentence ?? "") }); + setNoteFor(null); + setNoteText(""); + return String(r.sentence ?? ""); + }), + [lib, posts, run, wrote], + ); + + /** What a press on a post judges: the selection when there is one, else the post, or its thread under the thread scope. */ + const targetsOf = useCallback( + (row: LibraryPost | null): Target[] => { + if (selected.size) return [...selected].map((id) => ({ id })); + if (!row) return []; + return scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }]; + }, + [scope, selected], + ); + + const undo = useCallback( + () => + run(async () => { + if (!last) return "Nothing to undo."; + const r = await send("/api/library/judge", { lib, set: last.set, undo: true }); + wrote(last.set); + setLast(null); + return `${String(r.sentence ?? "Undone.")} A capture already queued is not cancelled.`; + }), + [last, lib, run, wrote], + ); + + const confirmBulk = useCallback( + (state: JudgeState) => + run(async () => { + const r = await send("/api/library/judge", { lib, bulk: { view: viewParams(view), state }, expect: total }); + setLast({ set: (r.undo as UndoItem[]) ?? [], label: String(r.sentence ?? "") }); + setBulk(null); + setSelected(new Set()); + return String(r.sentence ?? ""); + }), + [lib, run, total, view], + ); + + const move = useCallback( + (by: number) => { + const next = Math.min(Math.max(0, at + by), Math.max(0, posts.length - 1)); + setFocus(next); + const id = posts[next]?.id; + if (id) cards.current.get(id)?.scrollIntoView({ block: "nearest" }); + }, + [at, posts], + ); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + setHelp(false); + setBulk(null); + setNoteFor(null); + return; + } + const action = libraryAction({ key: e.key, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, typing: isTyping(e.target) }); + if (!action) return; + e.preventDefault(); + const state = stateOfAction(action) as JudgeState | null; + if (action === "next") move(1); + else if (action === "prev") move(-1); + else if (action.startsWith("bulk-") && state) { + if (total > 0) setBulk(state); + } else if (state) void judgeTargets(targetsOf(current), state); + else if (action === "scope") setScope((s) => (s === "post" ? "thread" : "post")); + else if (action === "note" && current) { + setNoteFor(current.id); + setNoteText(current.detail?.ownJudgement?.note ?? ""); + } else if (action === "select" && current) { + setSelected((s) => { + const next = new Set(s); + if (next.has(current.id)) next.delete(current.id); + else next.add(current.id); + return next; + }); + } else if (action === "undo") void undo(); + else if (action === "search") searchRef.current?.focus(); + else if (action === "gone") router.push(here({ gone: !view.gone })); + else if (action === "media") router.push(here({ media: !view.media })); + else if (action === "help") setHelp((h) => !h); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [current, here, judgeTargets, move, router, targetsOf, total, undo, view.gone, view.media]); + + const off = !hydrated || busy; + const words = filterWords(view); + const first = total === 0 ? 0 : view.offset + 1; + const lastShown = view.offset + posts.length; + + return ( + <div data-library={lib} data-library-busy={busy || refreshing ? "true" : "false"} className="grid gap-x-6 gap-y-4 md:grid-cols-[260px_minmax(0,1fr)]"> + {/* ── topics: a column on a desk, a fold on a phone ── */} + <aside className="min-w-0"> + {data.libraries.length > 1 && ( + <label className="mb-2 block text-[12px] text-muted"> + <span className="micro mb-1 block">library</span> + <select data-library-pick="" className="w-full max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px] text-text" value={lib} onChange={(e) => router.push(libraryHref({ lib: e.target.value }))}> + {data.libraries.map((l) => ( + <option key={l.slug} value={l.slug}> + {l.name} ({l.unjudged} unjudged) + </option> + ))} + </select> + </label> + )} + <details className="md:hidden" data-library-topics="fold"> + <summary className="cursor-pointer rounded-[3px] border border-seam-2 px-2 py-1.5 text-[12.5px] text-text"> + Topics · {topic ? topic.title : "all"} + </summary> + <TopicList topics={topics} view={view} here={here} lib={lib} /> + </details> + <div className="hidden md:block" data-library-topics="rail"> + <div className="micro mb-1">topics</div> + <TopicList topics={topics} view={view} here={here} lib={lib} /> + </div> + </aside> + + <section className="min-w-0"> + <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} /> + + {/* ── filters: links and one plain form, so they work before the page is alive ── */} + <div data-library-filters="" className="mb-3 mt-3 flex flex-wrap items-center gap-x-2 gap-y-2"> + {STATE_TABS.map((t) => ( + <Link prefetch={false} key={t.label} href={here({ state: t.state })} data-library-state={t.state ?? "all"} aria-current={view.state === t.state ? "true" : undefined} className={buttonVariants({ size: "sm", variant: view.state === t.state ? "pressed" : "outline" })}> + {t.label} + {topic?.counts && t.state ? <span className="text-muted">{t.state === "unjudged" ? topic.counts.unjudged : topic.counts[t.state as "keep" | "drop" | "later"]}</span> : null} + </Link> + ))} + <span className="mx-1 h-4 w-px bg-seam-2" aria-hidden="true" /> + {topic ? ( + <Link prefetch={false} href={here({ fresh: !view.fresh })} data-library-toggle="new" aria-pressed={view.fresh} className={buttonVariants({ size: "sm", variant: view.fresh ? "pressed" : "outline" })} title={topic.seenAt ? `First shown since Mark seen (${utc(topic.seenAt)})` : "This topic was never marked seen: every post is new"}> + New <span className="text-muted">{topic.fresh}</span> + </Link> + ) : ( + <span data-library-toggle="new" aria-disabled="true" className={cn(buttonVariants({ size: "sm", variant: "outline" }), "opacity-50")} title="Pick a topic: each topic is marked seen on its own"> + New + </span> + )} + <Link prefetch={false} href={here({ gone: !view.gone })} data-library-toggle="gone" aria-pressed={view.gone} className={buttonVariants({ size: "sm", variant: view.gone ? "pressed" : "outline" })}> + Gone from the page{topic?.counts ? <span className="text-muted">{topic.counts.gone}</span> : null} + </Link> + <Link prefetch={false} href={here({ media: !view.media })} data-library-toggle="media" aria-pressed={view.media} className={buttonVariants({ size: "sm", variant: view.media ? "pressed" : "outline" })}> + Has media + </Link> + <select + data-library-author="" + aria-label="Author" + className="max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[11.5px] text-text" + value={view.author ?? ""} + onChange={(e) => router.push(here({ author: e.target.value || null }))} + > + <option value="">Any author</option> + {view.author && !data.authors.some((a) => a.author.toLowerCase() === view.author!.toLowerCase()) && <option value={view.author}>@{view.author}</option>} + {data.authors.map((a) => ( + <option key={a.author} value={a.author}> + @{a.author} ({a.posts}) + </option> + ))} + </select> + <form action={libraryHref({})} method="get" role="search" className="flex min-w-0 items-center gap-1"> + {Object.entries(viewParams({ ...view, q: "" })).map(([k, v]) => ( + <input key={k} type="hidden" name={k} value={v} /> + ))} + <input type="hidden" name="lib" value={lib} /> + <input ref={searchRef} type="search" name="q" defaultValue={view.q} placeholder="Search words, a handle" aria-label="Search the posts" data-library-search="" className="w-[11rem] min-w-0 max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12px] text-text" /> + <button type="submit" className={buttonVariants({ size: "sm" })}> + Search + </button> + </form> + </div> + + <p className="m-0 mb-2 text-[12px] text-muted" data-library-count={total}> + {total === 0 ? `No post${words ? ` ${words}` : ""}${topic ? ` in “${topic.title}”` : ""}.` : `${first}–${lastShown} of ${total}${words ? ` · ${words}` : ""}`} + </p> + + {/* ── the posts ── */} + <ol className="m-0 list-none space-y-3 p-0" data-library-posts=""> + {posts.map((row, i) => { + const j = row.judgement; + const own = row.detail?.ownJudgement; + const cap = row.detail?.capture; + const inThread = (threadSizes.get(row.thread) ?? 1) > 1 || row.thread !== row.id; + return ( + <li + key={row.id} + ref={(el) => { + if (el) cards.current.set(row.id, el); + else cards.current.delete(row.id); + }} + data-library-post={row.id} + data-library-judgement={j?.state ?? "unjudged"} + data-library-focus={i === at ? "true" : undefined} + onClick={() => setFocus(i)} + className={cn("rounded-md border bg-panel p-3", i === at ? "border-muted" : "border-seam")} + > + <div className="mb-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11.5px] text-muted"> + <label className="inline-flex items-center gap-1"> + <input + type="checkbox" + data-library-select="" + aria-label={`Select the post by @${row.author}`} + checked={selected.has(row.id)} + disabled={!hydrated} + onChange={(e) => + setSelected((s) => { + const next = new Set(s); + if (e.target.checked) next.add(row.id); + else next.delete(row.id); + return next; + }) + } + /> + </label> + <Badge size="sm" variant={j ? (j.state === "drop" ? "blocking" : j.state === "later" ? "open" : "on") : "state"} data-library-chip=""> + {j ? STATE_LABEL[j.state] : "unjudged"} + </Badge> + {j && ( + <span data-library-by=""> + by the {j.by} + {j.from === "thread" ? ", from its thread" : ""} · {utc(j.at)} + </span> + )} + {inThread && <span data-library-thread={row.thread}>{row.thread === row.id ? "thread root" : "in a thread"}</span>} + {!view.topic && <span>{topics.find((t) => t.id === row.topic)?.title ?? row.topic}</span>} + </div> + {j?.note && ( + <p className="m-0 mb-2 text-[12.5px] text-text-2" data-library-note=""> + Note: {j.note} + </p> + )} + + {/* The post, drawn as the archive's viewer draws one (common's PostBody). It formats its + time in the reader's own zone, so it is drawn once the page is alive; until then, its words. */} + {hydrated ? ( + // (The viewer's small badges are drawn on `bg-muted`, which in umtool's theme is a text colour.) + <div className="[&_.bg-muted]:bg-panel-2"> + <PostBody post={postOf(lib, row)} capture={captureOf(lib, row)} /> + </div> + ) : ( + <article data-post-id={row.id}> + <p className="m-0 text-xs text-muted"> + {row.authorName || row.author} @{row.author} + </p> + <p className="m-0 mt-2 whitespace-pre-wrap text-base">{row.text}</p> + </article> + )} + + {/* Thread context, as the capture read it. */} + {cap?.context?.parent && ( + <blockquote data-library-context="parent" className="m-0 mt-2 border-l-2 border-seam-2 pl-2 text-[12.5px] text-text-2"> + <span className="text-muted">In answer to {cap.context.parent.handle ? `@${cap.context.parent.handle.replace(/^@/, "")}` : "a post"}: </span> + {cap.context.parent.text} + </blockquote> + )} + {cap?.context?.quoted && ( + <blockquote data-library-context="quoted" className="m-0 mt-2 border-l-2 border-seam-2 pl-2 text-[12.5px] text-text-2"> + <span className="text-muted">Quoting {cap.context.quoted.handle ? `@${cap.context.quoted.handle.replace(/^@/, "")}` : "a post"}: </span> + {cap.context.quoted.text} + </blockquote> + )} + {cap?.threadShot && ( + <details className="mt-2" data-library-thread-shot=""> + <summary className="cursor-pointer text-[12px] text-muted">The post with the one it answers, as captured</summary> + {/* eslint-disable-next-line @next/next/no-img-element */} + <img src={libraryMediaSrc(lib, row.id, cap.threadShot)} alt="Screenshot of the reply with the post it answers" loading="lazy" className="mt-1 max-w-full rounded-md border border-seam" /> + </details> + )} + + <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[12px] text-muted"> + {row.gone && ( + <span data-library-gone="" className="text-doubt-text"> + {goneSentence(row.gone, utc)} + </span> + )} + {row.capture && <span data-library-capture={row.capture.state}>{captureSentence(row.capture, utc)}</span>} + {row.capture?.mediaOwed && <span>media owed: {row.capture.mediaOwed === "kept" ? "fetched once the post is kept" : "asked for again by the next capture"}</span>} + {!row.capture && row.media.count > 0 && <span>{row.media.count} media, not captured</span>} + <span>first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)}</span> + </div> + + <div className="mt-2 flex flex-wrap items-center gap-1.5" data-library-actions=""> + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" variant={own?.state === s ? "pressed" : "outline"} disabled={off} data-library-press={s} onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], s)}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : "Later"} + </Button> + ))} + <Button size="sm" variant="quiet" disabled={off} data-library-press="clear" onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], "undecided")}> + Clear + </Button> + <Button + size="sm" + variant="quiet" + disabled={off} + data-library-press="note" + onClick={() => { + setNoteFor(noteFor === row.id ? null : row.id); + setNoteText(own?.note ?? ""); + }} + > + Note + </Button> + {scope === "thread" && <span className="text-[11.5px] text-doubt-text">judges its whole thread</span>} + </div> + {noteFor === row.id && ( + <div className="mt-2 space-y-1.5" data-library-note-editor=""> + <textarea + aria-label="Note" + autoFocus + value={noteText} + maxLength={2000} + onChange={(e) => setNoteText(e.target.value)} + rows={2} + className="block w-full max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px] text-text" + /> + <div className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-muted"> + <span>A note is kept with a judgement:</span> + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off || !noteText.trim()} data-library-note-save={s} onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], s, noteText.trim())}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : "Later"} with the note + </Button> + ))} + </div> + </div> + )} + </li> + ); + })} + </ol> + + {(view.offset > 0 || lastShown < total) && ( + <nav className="mt-3 flex items-center gap-2 text-[12px]" aria-label="Pages" data-library-pages=""> + {view.offset > 0 ? ( + <Link prefetch={false} href={here({ offset: Math.max(0, view.offset - data.pageSize) })} className={buttonVariants({ size: "sm" })}> + Previous {data.pageSize} + </Link> + ) : null} + {lastShown < total ? ( + <Link prefetch={false} href={here({ offset: view.offset + data.pageSize })} className={buttonVariants({ size: "sm" })}> + Next {Math.min(data.pageSize, total - lastShown)} + </Link> + ) : null} + </nav> + )} + + {/* ── the bar: what a press judges, bulk over the filter, undo, the keys ── */} + <div data-library-bar="" className="sticky bottom-[var(--dock-h,0px)] z-10 mt-4 space-y-1.5 border-t border-seam-2 bg-ground py-2"> + {bulk && ( + <div role="alertdialog" aria-label="Confirm" data-library-confirm={bulk} className="rounded-md border border-doubt-text p-2 text-[12.5px] text-text"> + <p className="m-0"> + {bulk === "undecided" ? "Clear the judgement of" : bulk === "keep" ? "Keep" : bulk === "drop" ? "Drop" : "Mark later"} all <strong data-library-confirm-count="">{total}</strong> post{total === 1 ? "" : "s"} + {words ? ` (${words})` : ""} + {topic ? ` in “${topic.title}”` : " in every topic"}?{" "} + {bulk === "keep" ? `Each keep archives the post's screenshot and media through the editor's paced capture job: one job per ${500} posts, never one per post.` : "Nothing is deleted: a drop is reversible."} + </p> + <div className="mt-1.5 flex flex-wrap gap-1.5"> + <Button size="sm" variant="go" disabled={off} data-library-confirm-yes="" onClick={() => void confirmBulk(bulk)}> + {bulk === "keep" ? "Keep" : bulk === "drop" ? "Drop" : bulk === "later" ? "Mark later" : "Clear"} {total} + </Button> + <Button size="sm" disabled={busy} data-library-confirm-no="" onClick={() => setBulk(null)}> + Cancel + </Button> + </div> + </div> + )} + <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5"> + <Button size="sm" variant={scope === "thread" ? "pressed" : "outline"} disabled={!hydrated} aria-pressed={scope === "thread"} data-library-scope={scope} onClick={() => setScope((s) => (s === "post" ? "thread" : "post"))}> + {scope === "thread" ? "Judging: the whole thread" : "Judging: the post"} + </Button> + {selected.size > 0 && ( + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-text-2" data-library-selected={selected.size}> + {selected.size} selected: + {(["keep", "drop", "later", "undecided"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off} data-library-selected-press={s} onClick={() => void judgeTargets([...selected].map((id) => ({ id })), s)}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : s === "later" ? "Later" : "Clear"} + </Button> + ))} + <Button size="sm" variant="quiet" onClick={() => setSelected(new Set())}> + None + </Button> + </span> + )} + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted"> + All {total} in the filter: + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off || total === 0} data-library-bulk={s} onClick={() => setBulk(s)}> + {s === "keep" ? "Keep all" : s === "drop" ? "Drop all" : "Later all"} + </Button> + ))} + </span> + <Button size="sm" disabled={off || !last} data-library-undo="" title={UNDO_SAYS} onClick={() => void undo()}> + Undo + </Button> + <Button size="sm" variant="quiet" disabled={!hydrated} aria-expanded={help} data-library-help-toggle="" onClick={() => setHelp((h) => !h)}> + Keys ? + </Button> + </div> + <p className="m-0 text-[11.5px] text-muted" data-library-undo-says=""> + {UNDO_SAYS} + </p> + <p role="status" aria-live="polite" data-library-status={status?.error ? "error" : "ok"} className={cn("m-0 min-h-[1.2em] text-[12.5px]", status?.error ? "text-reject-text" : "text-text-2")}> + {status?.text ?? ""} + </p> + {help && ( + <dl data-library-help="" className="m-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-[12px] text-text-2"> + {LIBRARY_KEYS.map((k) => ( + <div key={k.key} className="contents"> + <dt> + <kbd>{k.key === "A" || k.key === "D" || k.key === "L" ? `Shift+${k.key}` : k.key}</kbd> + </dt> + <dd className="m-0">{k.label}</dd> + </div> + ))} + <div className="contents"> + <dt /> + <dd className="m-0 text-muted">With posts selected, a d l c judge the selection.</dd> + </div> + </dl> + )} + </div> + </section> + </div> + ); +} + +function TopicList({ topics, view, here, lib }: { topics: LibraryTopic[]; view: View; here: (patch: Partial<View>) => string; lib: string }) { + const all = topics.reduce((n, t) => n + t.posts, 0); + const unjudged = topics.reduce((n, t) => n + (t.counts?.unjudged ?? 0), 0); + if (topics.length === 0) { + return ( + <p className="m-0 mt-2 text-[12.5px] text-text-2" data-library-no-topics=""> + {lib} has no topic yet. A topic comes from reading a trending page in the editor. + </p> + ); + } + return ( + <ul className="m-0 mt-1 list-none space-y-1 p-0"> + <li> + <Link prefetch={false} href={here({ topic: null, fresh: false })} data-library-topic="" aria-current={view.topic ? undefined : "true"} className={cn("block rounded-[3px] border px-2 py-1.5 text-[12.5px]", view.topic ? "border-transparent text-text-2 hover:bg-panel-2" : "border-muted bg-panel-2 text-text")}> + All topics + <span className="ml-1 text-muted"> + {all} posts · {unjudged} unjudged + </span> + </Link> + </li> + {topics.map((t) => { + const on = view.topic === t.id; + const w = t.watch; + const watchState = !w ? "none" : w.ended ? "ended" : w.paused ? (w.paused.reason === "failing" ? "failing" : "paused") : w.on ? "on" : "off"; + return ( + <li key={t.id}> + <Link prefetch={false} href={here({ topic: t.id })} data-library-topic={t.id} data-library-watch={watchState} aria-current={on ? "true" : undefined} className={cn("block rounded-[3px] border px-2 py-1.5 text-[12.5px]", on ? "border-muted bg-panel-2 text-text" : "border-transparent text-text-2 hover:bg-panel-2")}> + <span className="block break-words font-medium">{t.title}</span> + <span className="block text-[11.5px] text-muted"> + <span data-library-topic-posts="">{t.posts}</span> posts · <span data-library-topic-unjudged="">{t.counts?.unjudged ?? 0}</span> unjudged + {t.fresh > 0 ? ( + <> + {" · "} + <span data-library-topic-new="">{t.fresh}</span> new + </> + ) : null} + </span> + {w && ( + <span className={cn("mt-0.5 block text-[11.5px]", watchState === "failing" ? "text-reject-text" : watchState === "paused" ? "text-doubt-text" : "text-muted")} data-library-topic-watch=""> + {watchState === "failing" ? "Watch failing · " : watchState === "paused" ? "Watch paused · " : ""} + {w.sentence} + </span> + )} + </Link> + </li> + ); + })} + </ul> + ); +} + +function TopicPanel({ lib, topic, topics, off, run }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void> }) { + const w = topic?.watch; + const live = !!w && w.on && !w.ended; + const failing = live && w?.paused?.reason === "failing"; + const [interval, setIntervalMinutes] = useState(String(w?.intervalMinutes ?? "")); + const [hours, setHours] = useState(""); + const [shots, setShots] = useState(w?.shots ?? false); + const [plan, setPlan] = useState<PurgePlan | null>(null); + + const watch = (on: boolean) => + run(async () => { + const r = await send("/api/library/watch", { + lib, + topic: topic!.id, + on, + ...(on && interval.trim() ? { intervalMinutes: Number(interval) } : {}), + ...(on && hours.trim() ? { hours: Number(hours) } : {}), + ...(on ? { shots } : {}), + }); + return String(r.sentence ?? ""); + }); + const scope = topic ? { topic: topic.id } : {}; + const dropped = topic ? (topic.counts?.drop ?? 0) : topics.reduce((n, t) => n + (t.counts?.drop ?? 0), 0); + + return ( + <div data-library-panel={topic?.id ?? "all"} className="rounded-md border border-seam p-3"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="m-0 break-words text-[15px] font-semibold text-text">{topic ? topic.title : "All topics"}</h2> + {topic && ( + <span className="text-[12px] text-muted"> + {topic.posts} posts · {topic.counts?.unjudged ?? 0} unjudged · {topic.counts?.keep ?? 0} kept · {topic.counts?.drop ?? 0} dropped · {topic.counts?.later ?? 0} later + </span> + )} + </div> + + {topic && ( + <div className="mt-2" data-library-watch-panel={!w ? "none" : w.ended ? "ended" : failing ? "failing" : w.paused ? "paused" : w.on ? "on" : "off"}> + <p className="m-0 text-[12.5px] text-text-2" data-library-watch-sentence=""> + {w ? w.sentence : "Not watched."} + </p> + {live && w?.paused && !failing && ( + <p className="m-0 mt-1 text-[12.5px] text-doubt-text" data-library-watch-why=""> + Paused: {w.paused.sentence} It resumes by itself at the first scan after the reason is gone (for a stale cookie jar: Refresh cookies in the editor, on /cookies). + </p> + )} + {failing && ( + <p className="m-0 mt-1 text-[12.5px] text-reject-text" data-library-watch-why=""> + Failing: three reads in a row did not end as read. {w?.paused?.sentence} Only the operator restarts a failing watch: press Watch again. + </p> + )} + <div className="mt-2 flex flex-wrap items-end gap-x-3 gap-y-2 text-[12px] text-muted"> + <label className="flex flex-col gap-0.5"> + every (minutes) + <input type="number" inputMode="numeric" min={15} max={1440} placeholder="30" value={interval} onChange={(e) => setIntervalMinutes(e.target.value)} data-library-watch-interval="" className="w-[6rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text" /> + </label> + <label className="flex flex-col gap-0.5"> + for (hours) + <input type="number" inputMode="numeric" min={1} max={168} placeholder="48" value={hours} onChange={(e) => setHours(e.target.value)} data-library-watch-hours="" className="w-[6rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text" /> + </label> + <label className="inline-flex items-center gap-1.5 pb-1 text-text-2"> + <input type="checkbox" checked={shots} onChange={(e) => setShots(e.target.checked)} data-library-watch-shots="" /> + Screenshot everything new + </label> + <Button size="sm" variant={live && !failing ? "outline" : "go"} disabled={off} data-library-watch-on="" onClick={() => void watch(true)}> + {failing ? "Watch again" : live ? "Change the watch" : "Watch"} + </Button> + {live && ( + <Button size="sm" disabled={off} data-library-watch-off="" onClick={() => void watch(false)}> + Stop watching + </Button> + )} + </div> + </div> + )} + + <div className="mt-3 flex flex-wrap items-center gap-x-2 gap-y-1.5 border-t border-seam pt-2"> + <Button + size="sm" + disabled={off || topics.length === 0} + data-library-seen="" + title="New means first shown since this press" + onClick={() => + void run(async () => { + const ids = topic ? [topic.id] : topics.map((t) => t.id); + await send("/api/library/seen", { lib, topics: ids }); + return topic ? `“${topic.title}” marked seen: a post is new when a read first shows it after now.` : `${ids.length} topic${ids.length === 1 ? "" : "s"} marked seen.`; + }) + } + > + Mark seen + </Button> + {topic?.seenAt && ( + <span className="text-[11.5px] text-muted" data-library-seen-at=""> + marked seen {utc(topic.seenAt)} + </span> + )} + <Button + size="sm" + disabled={off || dropped === 0} + data-library-purge="" + onClick={() => + void run(async () => { + const r = (await send("/api/library/purge", { lib, ...scope, dryRun: true })) as unknown as PurgePlan; + setPlan(r); + }) + } + > + Purge dropped posts’ captures… + </Button> + </div> + {plan && ( + <div role="alertdialog" aria-label="Purge" data-library-purge-plan={plan.posts} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-purge-sentence=""> + {plan.sentence} + </p> + {plan.posts > 0 && <p className="m-0 mt-1 text-muted">Removing them cannot be undone here; keeping a post again captures it again.</p>} + <div className="mt-1.5 flex flex-wrap gap-1.5"> + {plan.posts > 0 && ( + <Button + size="sm" + variant="go" + disabled={off || plan.captureInFlight === true} + data-library-purge-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/purge", { lib, ...scope, confirm: plan.confirm }); + setPlan(null); + return String(r.sentence ?? ""); + }) + } + > + Remove {plan.posts} capture{plan.posts === 1 ? "" : "s"} + </Button> + )} + <Button size="sm" data-library-purge-no="" onClick={() => setPlan(null)}> + {plan.posts > 0 ? "Cancel" : "Close"} + </Button> + </div> + </div> + )} + </div> + ); +} diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -19,6 +19,7 @@ // `node --test lib/hrefs.test.mjs` runs it without a bundler. // --------------------------------------------------------------------------- +import { libraryHref as libraryViewHref } from "./library/filters.mjs"; import { ARTICLES_KEY } from "./articles/key.mjs"; /** A query value; `undefined`, `null`, `false` and "" are left out. */ @@ -575,6 +576,11 @@ export function digestContextHref(): string { return "/tools/digest-context"; } +/** The Posts library (lane posts-library): a private trending library's topics and posts, judged. */ +export function postsLibraryHref(view: Parameters<typeof libraryViewHref>[0] = {}): string { + return libraryViewHref(view); +} + /** Every tool. */ export function toolsHref(): string { return "/tools"; diff --git a/umtool/lib/library/filters.mjs b/umtool/lib/library/filters.mjs @@ -54,6 +54,8 @@ export function libraryHref(view = {}) { * The editor's listing parameters for a view. `seenAt` is the topic's Mark * seen time: "new" means first shown by a read after it (never marked: every * post is new, so no `since`). + * @param {ReturnType<typeof parseLibraryView>} view + * @param {{ seenAt?: string | null }} [o] */ export function listingParamsOf(view, { seenAt = null } = {}) { return { diff --git a/umtool/lib/library/load.ts b/umtool/lib/library/load.ts @@ -0,0 +1,94 @@ +import type { XTrendingListing, XTrendingPostRow, XTrendingTopicRow } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { askEditor, EditorError, editorUrl } from "@/lib/articles/generation"; +import { listLibraries, listLibrary, listLibraryIds } from "@/lib/library/client.mjs"; +import { listingParamsOf, PAGE_SIZE, parseLibraryView } from "@/lib/library/filters.mjs"; +import { seenOf } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +// WHAT THE POSTS LIBRARY PAGE SHOWS (lane posts-library), read THROUGH THE +// EDITOR (GET /api/ops/trending): the libraries, one library's topics with +// their counts and watches, and one page of posts under the view's filters. +// umtool opens no file of a library here. The one thing it adds is its own: +// each topic's Mark seen time, and from it how many posts are new. +// +// SERVER-ONLY. + +export type LibraryView = ReturnType<typeof parseLibraryView>; +export type LibrarySummary = { slug: string; name: string; topics: number; posts: number; unjudged: number }; +export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number }; +export type LibraryPost = XTrendingPostRow; + +export type LibraryData = + | { ok: false; sentence: string; reason: string } + | { + ok: true; + libraries: LibrarySummary[]; + lib: string; + name: string; + view: LibraryView; + topics: LibraryTopic[]; + posts: LibraryPost[]; + total: number; + authors: Array<{ author: string; posts: number }>; + pageSize: number; + }; + +// ALWAYS ASKED AGAIN (`fresh`): a judge view shows what a press just wrote, and askEditor's two-second +// memo may hold an answer another render asked for while that press was still on its way to the editor. +const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, { ...init, fresh: true }); + +/** Why the library cannot be shown, as one sentence. */ +export function unavailableSentence(err: unknown): { sentence: string; reason: string } { + if (err instanceof EditorError) { + if (err.reason === "no-token") return { reason: err.reason, sentence: "umtool has no WORKER_TOKEN, so the editor cannot be asked. The library is read and judged through the editor: set WORKER_TOKEN to the value the editor runs with." }; + if (err.reason === "unreachable") return { reason: err.reason, sentence: `The editor is not answering at ${editorUrl()}. The library is read and judged through the editor: start it, then reload.` }; + if (err.reason === "editor-token") return { reason: err.reason, sentence: "The editor's own WORKER_TOKEN is not set, so its ops surface is off. The library is read and judged through it." }; + if (err.reason === "denied") return { reason: err.reason, sentence: "The editor refused umtool's WORKER_TOKEN: the two tokens differ. The library is read and judged through the editor." }; + return { reason: err.reason, sentence: err.message }; + } + return { reason: "error", sentence: err instanceof Error ? err.message : String(err) }; +} + +export async function loadLibrary(view: LibraryView): Promise<LibraryData> { + try { + const libraries = (await listLibraries(ask)) as LibrarySummary[]; + if (libraries.length === 0) { + return { ok: false, reason: "no-library", sentence: "The editor has no X trending library. One is made in the editor (a channel with the platform x-trending), and its topics come from reading a trending page there." }; + } + const lib = view.lib ?? libraries[0].slug; + if (!libraries.some((l) => l.slug === lib)) { + return { ok: false, reason: "no-library", sentence: `The editor has no library "${lib}". Its libraries: ${libraries.map((l) => l.slug).join(", ")}.` }; + } + const seen = (await seenOf(REPORTS_ROOT, lib)) as Record<string, string>; + const shown = { ...view, lib }; + const listing = (await listLibrary(ask, { + ...listingParamsOf(shown, { seenAt: view.topic ? (seen[view.topic] ?? null) : null }), + limit: PAGE_SIZE, + offset: view.offset, + detail: true, + })) as unknown as XTrendingListing & { name?: string }; + // New since Mark seen, per topic: a topic never marked is new in full; a + // marked one is asked for the ids a read first showed after its mark. + const topics: LibraryTopic[] = await Promise.all( + listing.topics.map(async (t) => { + const seenAt = seen[t.id] ?? null; + const fresh = seenAt ? ((await listLibraryIds(ask, { slug: lib, topic: t.id, since: seenAt })) as string[]).length : t.posts; + return { ...t, seenAt, fresh }; + }), + ); + return { + ok: true, + libraries, + lib, + name: listing.name ?? lib, + view: shown, + topics, + posts: listing.posts, + total: listing.total, + authors: listing.authors ?? [], + pageSize: PAGE_SIZE, + }; + } catch (err) { + return { ok: false, ...unavailableSentence(err) }; + } +} diff --git a/umtool/lib/library/media.mjs b/umtool/lib/library/media.mjs @@ -37,10 +37,7 @@ export const LIBRARY_MEDIA_TYPES = Object.freeze({ ".webm": "video/webm", }); -/** The address the page gives a captured file. */ -export function libraryMediaSrc(lib, id, name) { - return `/api/library/media/${encodeURIComponent(lib)}/${encodeURIComponent(id)}/${encodeURIComponent(name)}`; -} +export { libraryMediaSrc } from "./mediaSrc.mjs"; /** * The file a media request names, or why not. diff --git a/umtool/lib/library/mediaSrc.mjs b/umtool/lib/library/mediaSrc.mjs @@ -0,0 +1,12 @@ +// The address the Posts library page gives a captured file (lane posts-library): the route +// /api/library/media/<lib>/<id>/<name>. In a file of its own, with no import, so a browser bundle takes it +// without the resolver beside it (lib/library/media.mjs reads the disk). + +/** + * @param {string} lib + * @param {string} id + * @param {string} name + */ +export function libraryMediaSrc(lib, id, name) { + return `/api/library/media/${encodeURIComponent(lib)}/${encodeURIComponent(id)}/${encodeURIComponent(name)}`; +} diff --git a/umtool/lib/library/route.ts b/umtool/lib/library/route.ts @@ -1,4 +1,4 @@ -import { askEditor, EditorError } from "@/lib/articles/generation"; +import { askEditor, clearEditorMemo, EditorError } from "@/lib/articles/generation"; import { PressError } from "@/lib/library/presses.mjs"; // What the Posts library's press routes share (lane posts-library). @@ -30,5 +30,9 @@ export async function press(request: Request, run: (body: unknown) => Promise<un const status = err instanceof PressError || err instanceof EditorError ? err.status : 500; const reason = err instanceof EditorError ? { reason: err.reason } : {}; return Response.json({ error: err instanceof Error ? err.message : String(err), ...reason }, { status, headers: NO_STORE }); + } finally { + // askEditor drops its kept reads when a write STARTS; a read that crossed the write on its way is + // kept again with the old answer. Dropped once more now that the write has landed. + clearEditorMemo(); } }