Archilyzer · Source

archilyzer

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

commit 8f6ac97eb4822cabf862de63258340fa0123278a
parent a6940462fd7493349c156638f4f79ebfb9fa5a6d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 14 Nov 2026 17:08:55 -0500

Merge lane/site-nav: secondary tags and a channel finder on a site's filters -- a tag may be presented as secondary on a site (the tags op present, the Tags tab's Placement), which moves its chip under a More filters disclosure that opens by itself when one of them is selected; past 12 channels the channel list gains a small finder that narrows groups and channels by name, a filtered group's box, count and All/None acting on what it lists; present writes only the site's presentation file, refuses one that does not parse and leaves the corpus vocabulary alone; sites with no secondary tag and 12 channels or fewer draw as before

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

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 5+++++
Mcommon/components/FiltersContainer.tsx | 6++++++
Mcommon/components/FiltersPanel.tsx | 435+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/components/SearchDataContext.tsx | 5+++++
Mcommon/controller/curatedTagsIndex.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/controller/curatedTagsIndex.ts | 3+++
Acommon/lib/channelFind.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/channelFind.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/curatedTags.test.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/curatedTags.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/publishedTags.test.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/publishedTags.ts | 15+++++++++++++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/tags/route.test.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/tags/route.ts | 33++++++++++++++++++++++++++++++---
Meditor/app/sites/[siteId]/tags/page.tsx | 2+-
Meditor/app/sites/components/SiteTagsClient.tsx | 55++++++++++++++++++++++++++++++++++++++-----------------
Meditor/app/tags/actions.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/tags/components/EditorTagsClient.tsx | 17+++++++++++++++++
Meditor/e2e/tags.spec.ts | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mexport/CHANGELOG.md | 1+
Aexport/e2e/channel-find.spec.ts | 355+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mexport/e2e/tag-chips.spec.ts | 193++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mplans/FACTS.md | 11++++++++---
Mscripts/archilyzer-ops.mjs | 9++++++++-
26 files changed, 1733 insertions(+), 88 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -183,7 +183,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | | `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. An auto-queue lane also takes "operations": \[ids\] \| null (dispatch only these — \["diarization"\] is speakers only; null widens it again) and "order" ("space" on backfill: corpus-disk channels first, then the most audio bytes per audio-hour). The backfill (Speakers) lane takes "speakers": "work" (the deck's Work through speakers: arm, lift the hold, start a run) \| "pause" (hold; stays armed). | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'`<br>`pnpm ops lane --json '{"lane":"backfill","speakers":"work"}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` | | `render-mode` | render-mode gives a render the operator is waiting for the machine: {"on": true, "for"?: "90m" \| &lt;minutes&gt;, "note"?} opens a window (default 2h) in which every other heavy job — e2e suites, next builds, the publish stages, other renders — waits at the heavy slot's door, and holds the transcription, download and Speakers lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` | -| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` | +| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "&lt;id&gt;"}, or how ONE site shows a corpus tag: {"op": "present", "site", "tag": {"id", "label"?, "groupLabel"?, "color"?, "order"?, "hidden"?, "secondary"?}} — merged into that row of sites/&lt;site&gt;/tags.json, other fields kept, null clears one (the site inherits it again). "secondary": true offers the tag under the site's "More filters" instead of the main Tags row; false keeps it in the main row over a corpus true. `get tags [<id>]` reads the vocabulary. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'`<br>`pnpm ops tags --json '{"op":"present","site":"demo-site","tag":{"id":"case-collab","secondary":true}}'` | | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` | | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality; "below-height" one whose height (recorded, else ffprobed) is below what that quality gives -- its ceiling, capped by the tallest format the record's metadata lists -- and keeps the old copy as its proxy ("keptAs": "proxy" on the alternate, once the new copy is taller); one that cannot be compared, with a taller alternate already beside it, or already downloaded at that quality (unless its metadata is newer than the copy) is left alone (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, lowerHeight, heightUnknown, tallerAlternate, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`) or kept as the proxy; nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` | diff --git a/OPERATING.md b/OPERATING.md @@ -771,6 +771,7 @@ pnpm ops fetch-chat --json '{"slug":"example","id":"<videoId>"}' --wait ```sh pnpm ops get tags pnpm ops tags --json '{"op":"define","tag":{"id":"example-collab","label":"Collab"}}' +pnpm ops tags --json '{"op":"present","site":"example-site","tag":{"id":"example-collab","secondary":true}}' pnpm ops tag-videos --json '{"tag":"example-collab","op":"add","videos":[{"slug":"example","id":"<videoId>"}]}' pnpm ops tag-videos --file ids.json ``` @@ -778,6 +779,10 @@ pnpm ops tag-videos --file ids.json - `transcripts/tags.json` has one writer, and `tags` and `tag-videos` go through it, recording who asked (`ARCHILYZER_AGENT`). `remove` unpins; `suppress` rejects a rule's hit. - A tag's `sites` limits the sites it exists on. +- `present` sets how ONE site shows a corpus tag — one row of `sites/<site>/tags.json`: `label`, `groupLabel`, + `color`, `order`, `hidden`, `secondary` (offered under the site's **More filters** rather than its main Tags + row); other fields are kept, `null` clears one. The site's Tags tab (**Placement**) is the same. Rebuild and + deploy the site to publish it. - Read side: the MCP's `list_tags`, and `tags` on `search_transcripts` / `enumerate_matches`. ## Prepare and export reports diff --git a/common/components/FiltersContainer.tsx b/common/components/FiltersContainer.tsx @@ -64,6 +64,12 @@ export function FiltersTrigger({ side={fromSide ? "right" : "bottom"} aria-describedby={undefined} className="max-h-[90dvh] gap-0 overflow-y-auto sm:max-w-md" + onEscapeKeyDown={(e) => { + // A field that uses Esc itself (the channel finder: clear and close) + // keeps it — the sheet closes on the NEXT Esc, not under the reader. + const target = e.target as Element | null; + if (target?.closest?.("[data-escape-local]")) e.preventDefault(); + }} > <SheetTitle className="px-4 pt-4 text-base">Filters</SheetTitle> <div className="px-4 pb-4 pt-2"> diff --git a/common/components/FiltersPanel.tsx b/common/components/FiltersPanel.tsx @@ -13,8 +13,15 @@ // to be the outer one. It also doubles as the inline collapse, driven by the // session's persisted `filtersCollapsed`. -import { Fragment, useCallback, useMemo, useState } from "react"; -import { ChevronRightIcon } from "lucide-react"; +import { + Fragment, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { ChevronRightIcon, SearchIcon } from "lucide-react"; import { MISSING_STATES, VIDEO_STATE_LABELS, @@ -36,8 +43,16 @@ import { useSearchData } from "./SearchDataContext"; import { groupPublishedTags, selectableTags, + splitSecondaryTags, + type PublishedTagGroup, } from "../lib/publishedTags"; import type { PublishedTag } from "../lib/curatedTags"; +import { + CHANNEL_FIND_MIN_CHANNELS, + findChannels, + type FoundGrouping, +} from "../lib/channelFind"; +import type { ChannelGroup } from "../lib/channelGroups"; export default function FiltersPanel({ // Inside the sheet the sheet itself IS the disclosure, so the wrapper stays @@ -134,6 +149,88 @@ export default function FiltersPanel({ const allMissingKept = MISSING_STATES.every((s) => draftStates.has(s)); const someMissingKept = MISSING_STATES.some((s) => draftStates.has(s)); + // ─── The channel finder (lib/channelFind.ts) ─── + // Offered only on a site with many channels. While it holds a query the + // listed groups are the matching ones, shown open WITHOUT touching the + // persisted `collapsedGroups`: clearing the query gives back exactly the + // panel the reader had. A listed group's box, count and All/None act on + // the channels it lists — the matches — so nothing hidden changes. + const { channels: channelModel } = useSearchData(); + const showFind = channelOptions.length > CHANNEL_FIND_MIN_CHANNELS; + const [findOpen, setFindOpen] = useState(false); + const [findQuery, setFindQuery] = useState(""); + const findButtonRef = useRef<HTMLButtonElement>(null); + const findReturnFocus = useRef(false); + // For the deferred fold on blur (below): read from listeners that outlive + // the render that registered them. + const findQueryRef = useRef(""); + const findFocused = useRef(false); + const pointerHeld = useRef(false); + useEffect(() => { + if (!findOpen) return; + const down = () => { + pointerHeld.current = true; + }; + const up = () => { + pointerHeld.current = false; + }; + document.addEventListener("pointerdown", down, true); + document.addEventListener("pointerup", up, true); + document.addEventListener("pointercancel", up, true); + return () => { + pointerHeld.current = false; + document.removeEventListener("pointerdown", down, true); + document.removeEventListener("pointerup", up, true); + document.removeEventListener("pointercancel", up, true); + }; + }, [findOpen]); + // An EMPTY field folds back to the magnifier when it loses focus — but + // never under a pressed pointer. The field is wider than the magnifier, so + // folding on the blur that a press elsewhere in the row causes slides the + // row left before the press is released, and the click (on All, a Reset + // link) lands on whatever slid under it, or on nothing. So a blur by + // pointer waits for the release, and the fold runs after the click that + // release makes; a blur by keyboard folds at once (nothing is under a + // pointer). Either way it only folds if the field is still empty and has + // not taken focus back meanwhile. + const foldFindIfIdle = useCallback(() => { + window.setTimeout(() => { + if (!findFocused.current && findQueryRef.current.trim() === "") { + setFindOpen(false); + } + }, 0); + }, []); + const slugByKey = useMemo( + () => new Map(channelModel.map((c) => [c.key, c.slug])), + [channelModel], + ); + const found = useMemo( + () => + showFind && findOpen + ? findChannels(channelGroupings, findQuery, (key) => [ + channelLabelByKey.get(key) ?? key, + slugByKey.get(key), + ]) + : null, + [showFind, findOpen, channelGroupings, findQuery, channelLabelByKey, slugByKey], + ); + const closeFind = useCallback(() => { + findReturnFocus.current = true; + findQueryRef.current = ""; + setFindQuery(""); + setFindOpen(false); + }, []); + useEffect(() => { + // Esc hands focus back to the magnifier it came from, once it exists again. + if (!findOpen && findReturnFocus.current) { + findReturnFocus.current = false; + findButtonRef.current?.focus(); + } + }, [findOpen]); + const listedGroupings: FoundGrouping<ChannelGroup>[] = found ?? channelGroupings; + const foundCount = + found?.reduce((n, g) => n + g.channels.length, 0) ?? 0; + return ( <details data-testid="filters-panel" @@ -198,6 +295,86 @@ export default function FiltersPanel({ <span className="text-xs uppercase tracking-wide text-muted-foreground"> Channels </span> + {showFind && + (findOpen ? ( + // The field opens where the magnifier was, its icon on + // the same spot, so nothing moves under the pointer. + <span className="relative flex items-center"> + <SearchIcon + aria-hidden="true" + className="pointer-events-none absolute left-[7px] size-3.5 text-muted-foreground" + /> + <input + type="search" + autoFocus + data-testid="channel-find" + data-escape-local="" + aria-label="Find a channel" + placeholder="Find channel" + value={findQuery} + onChange={(e) => { + findQueryRef.current = e.target.value; + setFindQuery(e.target.value); + }} + onFocus={() => { + findFocused.current = true; + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + closeFind(); + } + }} + onBlur={() => { + findFocused.current = false; + if (findQueryRef.current.trim() !== "") return; + if (!pointerHeld.current) { + foldFindIfIdle(); + return; + } + const release = () => { + document.removeEventListener("pointerup", release, true); + document.removeEventListener("pointercancel", release, true); + foldFindIfIdle(); + }; + document.addEventListener("pointerup", release, true); + document.addEventListener("pointercancel", release, true); + }} + className="h-7 w-40 rounded-md border border-border bg-card pl-7 pr-2 text-xs text-foreground placeholder:text-muted-foreground" + /> + </span> + ) : ( + <button + ref={findButtonRef} + type="button" + data-testid="channel-find-open" + aria-label="Find a channel" + title="Find a channel" + onClick={() => setFindOpen(true)} + className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground" + > + <SearchIcon aria-hidden="true" className="size-3.5" /> + </button> + ))} + {/* Mounted with the field, before the first query, so the + first count is announced too: a live region only speaks + about changes it was already there to see. */} + {showFind && findOpen && ( + <span + className="sr-only" + aria-live="polite" + data-testid="channel-find-live" + > + {found === null + ? "" + : foundCount === 0 + ? "No channel matches" + : foundCount === 1 + ? "1 channel matches" + : `${foundCount} channels match`} + </span> + )} <ChannelAllToggle channelOptions={channelOptions} draftExcludedChannels={draftExcludedChannels} @@ -232,8 +409,20 @@ export default function FiltersPanel({ Reset everything </Button> </div> + {found && found.length === 0 && ( + <p + data-testid="channel-find-empty" + className="text-xs text-muted-foreground" + > + No channel matches “{findQuery.trim()}”. + </p> + )} <div className="flex flex-wrap items-start gap-1.5"> - {channelGroupings.map(({ group, channels }) => { + {listedGroupings.map(({ group, channels }) => { + // While the finder holds a query, `channels` is what it + // lists — the matches, or the whole group when the group's + // name matched — and the box, the count and All/None act on + // exactly that. if (group.inline) { // Inline group: no collapsible box — each member channel // renders as its own loose chip flowing among the group @@ -264,7 +453,7 @@ export default function FiltersPanel({ </Fragment> ); } - const isOpen = !collapsedGroups.has(group.id); + const isOpen = found !== null || !collapsedGroups.has(group.id); const selectedCount = channels.reduce( (n, name) => draftExcludedChannels.has(name) ? n : n + 1, @@ -285,7 +474,11 @@ export default function FiltersPanel({ // browser's default toggle action — same rationale // as the outer Filters summary above. e.preventDefault(); - toggleGroupCollapsed(group.id, !isOpen); + // A found group is shown open by the finder, not + // by the reader's choice: nothing to persist. + if (found === null) { + toggleGroupCollapsed(group.id, !isOpen); + } }} className="cursor-pointer select-none flex items-center gap-2 px-2.5 py-1.5 text-sm min-w-0" title={!isOpen ? group.description : undefined} @@ -588,6 +781,8 @@ export default function FiltersPanel({ </div> )} + <MoreTagFilters /> + {/* Throughput knobs: nobody sets these on a first visit, and on a phone they were four more rows between the query and the results. */} <details className="text-sm text-muted-foreground"> @@ -791,28 +986,38 @@ function ProfilesRow({ ); } -// The curated-tag chip row (lib/curatedTags.ts) — "Eva: Collab · In chat · -// Discussed" beside the channel-group chips. +// The curated tags this site publishes (lib/curatedTags.ts), in their two +// places: the main Tags row beside the channel-group chips, and — for the tags +// the operator marked `secondary` — the "More filters" disclosure above +// Advanced options. // // Built ONLY from this site's published /tags.json, which is the operator's // decision and the reason there is no static list anywhere in this file: a tag // defined corpus-wide but matching nothing on THIS site does not appear here, // and neither does a hidden one, because compose-site never wrote it into this -// site's document. The whole row is absent when the site publishes nothing — +// site's document. Both places are absent when the site publishes nothing — // which is every site until someone curates a tag, and every site built before // corpus spec 4. // -// OR across the chips: selecting Collab and In chat is every stream with +// OR across the chips, in both places: selecting two tags is every video with // either, never only the ones with both. A selected chip clears on click, so -// the row is its own reset and needs no second control. -function TagChipRow() { +// the chips are their own reset and need no second control. +function useTagPlaces() { const { curatedTags } = useSearchData(); const { draftTags, toggleDraftTag } = useSearchSession(); // selectableTags is the belt to compose-site's braces: a stale or // hand-written document must not be able to offer a chip that finds nothing. const publishable = useMemo(() => selectableTags(curatedTags), [curatedTags]); - const groups = useMemo(() => groupPublishedTags(publishable), [publishable]); + const { primary, secondary } = useMemo( + () => splitSecondaryTags(publishable), + [publishable], + ); + const primaryGroups = useMemo(() => groupPublishedTags(primary), [primary]); + const secondaryGroups = useMemo( + () => groupPublishedTags(secondary), + [secondary], + ); // Tags the SELECTION carries that this site does not publish. A `?tg=` link // written against another site in the family, or against this one before a @@ -820,7 +1025,7 @@ function TagChipRow() { // this the Filters badge and the "N selected" line would say a filter is on // while nothing in the row is lit, and (if it is the only tag) the results // would go to zero with nothing to click off. So the selection ALWAYS has a - // chip, even when the vocabulary does not have the tag. + // chip, even when the vocabulary does not have the tag — in the main row. const unpublished = useMemo(() => { const known = new Set(publishable.map((t) => t.id)); return Array.from(draftTags) @@ -828,6 +1033,71 @@ function TagChipRow() { .sort(); }, [publishable, draftTags]); + return { + draftTags, + toggleDraftTag, + primaryGroups, + secondaryGroups, + secondary, + unpublished, + // Whether the main row renders at all. + hasMainRow: primaryGroups.length > 0 || unpublished.length > 0, + }; +} + +function TagChip({ + tag, + selected, + onToggle, +}: { + tag: PublishedTag; + selected: boolean; + onToggle: (id: string) => void; +}) { + return ( + <button + type="button" + aria-pressed={selected} + data-testid="tag-chip" + data-tag-id={tag.id} + title={ + selected + ? `Clear "${tag.label}"` + : `Keep only videos tagged "${tag.label}"` + } + onClick={() => onToggle(tag.id)} + className={cn( + "flex items-center gap-1.5 rounded border px-2.5 py-1.5 text-sm select-none min-w-0 transition-colors", + selected + ? "border-primary bg-primary/10 text-foreground" + : "border-border bg-card/60 hover:bg-accent hover:text-accent-foreground", + )} + > + {tag.color && ( + <span + aria-hidden="true" + className="inline-block size-2 shrink-0 rounded-full" + style={{ background: tag.color }} + /> + )} + <span className="truncate">{tag.label}</span> + {/* The count is this site's, computed at index time — the same number + the chip's filter will produce. */} + <span className="text-xs text-muted-foreground shrink-0"> + {tag.count} + </span> + </button> + ); +} + +function tagSelectionLine(n: number): string { + return n === 0 ? "any" : `${n} selected — a video with ANY of them`; +} + +function TagChipRow() { + const { draftTags, toggleDraftTag, primaryGroups: groups, unpublished, hasMainRow } = + useTagPlaces(); + // Collapse is per-group and LOCAL, unlike the channel groups' persisted // `collapsedGroups`: a tag row is a handful of chips a reader folds away to // get the results back on screen, not a filter shape worth carrying into @@ -845,46 +1115,16 @@ function TagChipRow() { }); }, []); - const renderChip = (tag: PublishedTag) => { - const selected = draftTags.has(tag.id); - return ( - <button - key={tag.id} - type="button" - aria-pressed={selected} - data-testid="tag-chip" - data-tag-id={tag.id} - title={ - selected - ? `Clear "${tag.label}"` - : `Keep only videos tagged "${tag.label}"` - } - onClick={() => toggleDraftTag(tag.id)} - className={cn( - "flex items-center gap-1.5 rounded border px-2.5 py-1.5 text-sm select-none min-w-0 transition-colors", - selected - ? "border-primary bg-primary/10 text-foreground" - : "border-border bg-card/60 hover:bg-accent hover:text-accent-foreground", - )} - > - {tag.color && ( - <span - aria-hidden="true" - className="inline-block size-2 shrink-0 rounded-full" - style={{ background: tag.color }} - /> - )} - <span className="truncate">{tag.label}</span> - {/* The count is this site's, computed at index time — the same number - the chip's filter will produce. */} - <span className="text-xs text-muted-foreground shrink-0"> - {tag.count} - </span> - </button> - ); - }; + const renderChip = (tag: PublishedTag) => ( + <TagChip + key={tag.id} + tag={tag} + selected={draftTags.has(tag.id)} + onToggle={toggleDraftTag} + /> + ); - if (groups.length === 0 && unpublished.length === 0) return null; + if (!hasMainRow) return null; return ( <div @@ -896,9 +1136,7 @@ function TagChipRow() { Tags </span> <span className="text-xs text-muted-foreground"> - {draftTags.size === 0 - ? "any" - : `${draftTags.size} selected — a video with ANY of them`} + {tagSelectionLine(draftTags.size)} </span> </div> {/* One wrapping flow, phone-first: a group is a disclosure — its label @@ -1014,6 +1252,93 @@ function TagChipRow() { ); } +// The secondary tags: still published, still filtering, still in `?tg=` +// links — offered one step further down, where "Advanced options" already +// lives, so the main filters read as the site's own and an investigation's +// tags as a refinement. +// +// Closed by default. It opens itself while one of its tags is selected and the +// reader has not toggled it — a `?tg=` link, a restored profile — because a +// filter that is narrowing the results must be visible; once the reader opens +// or closes it, their choice holds. (No effect: the open state is derived, so +// there is nothing to get out of step with hydration.) +function MoreTagFilters() { + const { draftTags, toggleDraftTag, secondaryGroups, secondary } = + useTagPlaces(); + const [chosenOpen, setChosenOpen] = useState<boolean | null>(null); + const selectedCount = secondary.reduce( + (n, tag) => (draftTags.has(tag.id) ? n + 1 : n), + 0, + ); + const isOpen = chosenOpen ?? selectedCount > 0; + + if (secondaryGroups.length === 0) return null; + + const renderGroup = (group: PublishedTagGroup) => ( + <div + key={group.id || "ungrouped"} + data-testid="tag-chip-group" + data-group-id={group.id} + className="flex flex-wrap items-center gap-1.5 min-w-0" + > + {group.label && ( + <span className="mr-1 text-xs font-medium text-foreground"> + {group.label} + </span> + )} + {group.tags.map((tag) => ( + <TagChip + key={tag.id} + tag={tag} + selected={draftTags.has(tag.id)} + onToggle={(id) => { + // Clearing the last selected tag from in here must not fold the + // disclosure shut under the reader's pointer. + setChosenOpen((was) => was ?? true); + toggleDraftTag(id); + }} + /> + ))} + </div> + ); + + return ( + <details + data-testid="tag-more" + open={isOpen} + className="text-sm text-muted-foreground" + > + <summary + data-testid="tag-more-summary" + onClick={(e) => { + // React owns the open state — same rationale as the Filters summary. + e.preventDefault(); + setChosenOpen(!isOpen); + }} + className="cursor-pointer select-none text-xs uppercase tracking-wide text-muted-foreground hover:text-foreground" + > + More filters + {selectedCount > 0 && ( + <span + data-testid="tag-more-selected" + className="normal-case tracking-normal" + > + {" "} + · {selectedCount} selected + {/* Two or more: say how they combine, once, here. */} + {selectedCount > 1 && ", any of them"} + </span> + )} + </summary> + {/* Set in like Advanced options' content, so the chips read as inside + the disclosure and not as one more row of the panel. */} + <div className="mt-3 flex flex-col gap-2 rounded-md border border-border bg-card/60 p-4"> + {secondaryGroups.map(renderGroup)} + </div> + </details> + ); +} + function ChannelAllToggle({ channelOptions, draftExcludedChannels, diff --git a/common/components/SearchDataContext.tsx b/common/components/SearchDataContext.tsx @@ -44,6 +44,9 @@ export type ChannelOption = { key: string; name: string; groupId: string; + // The channel's slug, when the manifest carries one — for the channel + // finder only (lib/channelFind.ts); never a selection identity. + slug?: string; }; // Minimal shape of a summary needed to derive its channel key. @@ -188,6 +191,7 @@ export function SingleSiteDataProvider({ children }: { children: ReactNode }) { key: c.name, name: c.name, groupId: resolveChannelGroupId(c.groupId, groups, defaultGroupId), + ...(c.slug ? { slug: c.slug } : {}), })) .sort((a, b) => a.name.localeCompare(b.name)); } @@ -610,6 +614,7 @@ export function MultiSiteDataProvider({ key: makeId(s.origin, c.slug), name: c.name, groupId: s.origin, + slug: c.slug, }); } }); diff --git a/common/controller/curatedTagsIndex.test.ts b/common/controller/curatedTagsIndex.test.ts @@ -571,6 +571,38 @@ test("publishedTagsFrom drops hidden and zero-count tags and sorts by order", () assert.deepEqual(publishedTagsFrom(defs, null).tags, []); }); +test("publishedTagsFrom writes `secondary` only when it is true", () => { + const counts = { + version: 1, + generatedAt: "", + tags: { + "case-collab": { count: 2, channels: { lm: 2 } }, + "case-topic": { count: 1, channels: { lm: 1 } }, + }, + }; + const published = publishedTagsFrom( + [ + { id: "case-collab", label: "Collab", order: 1, secondary: true }, + // A site row's `false` survives the merge; on the wire it is the default. + { id: "case-topic", label: "Discussed", order: 2, secondary: false }, + ], + counts, + ); + assert.equal(published.tags[0].secondary, true); + // Byte-identical for a site that does not use it: no key at all. + assert.equal("secondary" in published.tags[1], false); + assert.equal( + JSON.stringify(published.tags[1]), + JSON.stringify({ + id: "case-topic", + label: "Discussed", + order: 2, + count: 1, + channels: { lm: 1 }, + }), + ); +}); + // ─── site-scoped tags (`sites`) ─── test("a site-scoped tag: rule hits and pins only on its sites' channels; no scope, no hash change", async () => { diff --git a/common/controller/curatedTagsIndex.ts b/common/controller/curatedTagsIndex.ts @@ -625,6 +625,9 @@ export function publishedTagsFrom( ...(def.groupLabel ? { groupLabel: def.groupLabel } : {}), ...(def.color ? { color: def.color } : {}), ...(def.order !== undefined ? { order: def.order } : {}), + // Only when true: a site that uses no secondary tag publishes the same + // document, byte for byte, as before the field existed. + ...(def.secondary === true ? { secondary: true as const } : {}), count: entry!.count, channels: entry!.channels, })); diff --git a/common/lib/channelFind.test.ts b/common/lib/channelFind.test.ts @@ -0,0 +1,72 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + CHANNEL_FIND_MIN_CHANNELS, + findChannels, + foldForFind, +} from "./channelFind"; + +type G = { id: string; name: string }; + +const GROUPINGS: { group: G; channels: string[] }[] = [ + { group: { id: "g1", name: "Group One" }, channels: ["Alpha", "Beta"] }, + { group: { id: "g2", name: "Reviews" }, channels: ["Gamma", "Delta"] }, + { group: { id: "g3", name: "" }, channels: ["Café Corner", "Epsilon"] }, +]; + +const SLUGS: Record<string, string> = { + Alpha: "alpha-channel", + Beta: "beta", + Gamma: "gamma", + Delta: "delta_desk", + "Café Corner": "cafe-corner", + Epsilon: "epsilon", +}; + +const textsOf = (key: string) => [key, SLUGS[key]]; + +test("the finder is offered only past a constant number of channels", () => { + assert.equal(CHANNEL_FIND_MIN_CHANNELS, 12); +}); + +test("foldForFind ignores case, accents and punctuation", () => { + assert.equal(foldForFind(" Café-Corner! "), "cafe corner"); + assert.equal(foldForFind("@some_channel"), "some channel"); +}); + +test("an empty or punctuation-only query filters nothing", () => { + assert.equal(findChannels(GROUPINGS, "", textsOf), null); + assert.equal(findChannels(GROUPINGS, " - ", textsOf), null); +}); + +test("a channel name narrows its group to the matching channels", () => { + assert.deepEqual(findChannels(GROUPINGS, "alp", textsOf), [ + { group: GROUPINGS[0].group, channels: ["Alpha"] }, + ]); +}); + +test("a slug matches, separators read as spaces", () => { + const found = findChannels(GROUPINGS, "delta desk", textsOf); + assert.deepEqual(found?.map((g) => g.channels), [["Delta"]]); + const bySlug = findChannels(GROUPINGS, "alpha-chan", textsOf); + assert.deepEqual(bySlug?.map((g) => g.channels), [["Alpha"]]); +}); + +test("a group name lists the whole group", () => { + const found = findChannels(GROUPINGS, "review", textsOf); + assert.deepEqual(found, [ + { group: GROUPINGS[1].group, channels: ["Gamma", "Delta"] }, + ]); +}); + +test("accents fold on both sides, groups keep their order, no match is []", () => { + assert.deepEqual( + findChannels(GROUPINGS, "CAFE", textsOf)?.map((g) => g.group.id), + ["g3"], + ); + assert.deepEqual( + findChannels(GROUPINGS, "a", textsOf)?.map((g) => g.group.id), + ["g1", "g2", "g3"], + ); + assert.deepEqual(findChannels(GROUPINGS, "zzz", textsOf), []); +}); diff --git a/common/lib/channelFind.ts b/common/lib/channelFind.ts @@ -0,0 +1,52 @@ +// The channel finder in the filter panel's Channels row: a small magnifier that +// opens into a field and narrows the group cards and channel chips to the ones +// whose channel name, channel slug or group name holds what was typed. +// +// Pure and local: it filters what the page already has (the manifest's +// channels and groups), so it works on a static site with no server and no AI. + +// Offered only on a site with MORE than this many channels: below it the whole +// list fits on a screen and a search field is chrome. A constant, not a +// setting — a knob nobody would turn. +export const CHANNEL_FIND_MIN_CHANNELS = 12; + +// Case, accents and punctuation do not count: "cafe" finds "Café", and +// "some channel" finds the slug "some-channel" (or "@some_channel"). +export function foldForFind(s: string): string { + return s + .normalize("NFKD") + .replace(/\p{M}+/gu, "") + .toLowerCase() + .replace(/[^\p{L}\p{N}]+/gu, " ") + .trim(); +} + +export type FoundGrouping<G> = { + group: G; + // The channels to SHOW: every one when the group's name matched, else only + // the matching ones. While a query is on these are also what the group's + // box, its count and All/None act on — what you see is what you change. + channels: string[]; +}; + +// null when there is nothing to filter by (an empty or punctuation-only +// query): the caller renders the panel exactly as it does with no finder. +// Otherwise the groupings that keep at least one channel, in their order. +export function findChannels<G extends { name: string }>( + groupings: readonly { group: G; channels: readonly string[] }[], + query: string, + textsOf: (key: string) => readonly (string | undefined)[], +): FoundGrouping<G>[] | null { + const q = foldForFind(query); + if (q === "") return null; + const hit = (text: string | undefined) => + text !== undefined && foldForFind(text).includes(q); + const out: FoundGrouping<G>[] = []; + for (const { group, channels } of groupings) { + const shown = hit(group.name) + ? channels.slice() + : channels.filter((key) => textsOf(key).some(hit)); + if (shown.length > 0) out.push({ group, channels: shown }); + } + return out; +} diff --git a/common/lib/curatedTags.test.ts b/common/lib/curatedTags.test.ts @@ -9,6 +9,7 @@ import { evaluateTagRules, isTagId, mergeTagDefs, + patchSiteOverlay, sanitizeTagsConfig, TAG_ID_RE, TAGS_FILENAME, @@ -604,3 +605,106 @@ test("all three kinds can fire on one video and the result is sorted", () => { ["eva-collab", "eva-in-chat", "eva-topic"], ); }); + +// ─── the two presentation switches: hidden and secondary ─── + +test("the corpus layer stores hidden/secondary only when true", () => { + const { tags } = sanitizeTagsConfig({ + tags: [ + { id: "case-a", hidden: false, secondary: false }, + { id: "case-b", hidden: true, secondary: true }, + { id: "case-c", secondary: "yes" }, + ], + }); + assert.deepEqual(tags, [ + { id: "case-a", label: "case-a" }, + { id: "case-b", label: "case-b", hidden: true, secondary: true }, + { id: "case-c", label: "case-c" }, + ]); +}); + +test("the site layer keeps an explicit false, on read and on write", () => { + const once = sanitizeTagsConfig( + { tags: [{ id: "case-a", hidden: false, secondary: false }] }, + { layer: "site" }, + ); + assert.deepEqual(once.tags, [ + { id: "case-a", hidden: false, secondary: false }, + ]); + assert.deepEqual(sanitizeTagsConfig(once, { layer: "site" }), once); +}); + +test("a site's false shows a corpus-hidden tag and keeps a corpus-secondary one in the main row", () => { + const global = sanitizeTagsConfig({ + tags: [ + { id: "case-a", label: "A", hidden: true }, + { id: "case-b", label: "B", secondary: true }, + { id: "case-c", label: "C" }, + ], + }).tags; + const site = sanitizeTagsConfig( + { + tags: [ + { id: "case-a", hidden: false }, + { id: "case-b", secondary: false }, + { id: "case-c", secondary: true }, + ], + }, + { layer: "site" }, + ).tags; + const merged = mergeTagDefs(global, site); + assert.equal(merged.find((d) => d.id === "case-a")?.hidden, false); + assert.equal(merged.find((d) => d.id === "case-b")?.secondary, false); + assert.equal(merged.find((d) => d.id === "case-c")?.secondary, true); + // Presentation only: the labels came through untouched. + assert.deepEqual( + merged.map((d) => d.label), + ["A", "B", "C"], + ); +}); + +test("patchSiteOverlay merges one row field by field and keeps the rest", () => { + const rows = sanitizeTagsConfig( + { + tags: [ + { id: "case-a", color: "#fff" }, + { id: "case-b", label: "Bee" }, + ], + }, + { layer: "site" }, + ).tags; + const r = patchSiteOverlay(rows, { id: "case-a", secondary: true }); + assert.ok(r.ok); + assert.deepEqual(r.row, { id: "case-a", color: "#fff", secondary: true }); + assert.deepEqual(r.tags, [ + { id: "case-a", color: "#fff", secondary: true }, + { id: "case-b", label: "Bee" }, + ]); + // A new row is appended; ids are normalised. + const added = patchSiteOverlay(rows, { id: " Case-C ", secondary: true }); + assert.ok(added.ok); + assert.deepEqual(added.tags.at(-1), { id: "case-c", secondary: true }); +}); + +test("patchSiteOverlay: null clears a field, and a row saying nothing is removed", () => { + const rows = [{ id: "case-a", secondary: true }] as CuratedTagDef[]; + const r = patchSiteOverlay(rows, { id: "case-a", secondary: null }); + assert.ok(r.ok); + assert.equal(r.row, null); + assert.deepEqual(r.tags, []); +}); + +test("patchSiteOverlay refuses what is not a site presentation field, or not a value", () => { + const no = (patch: Record<string, unknown>) => { + const r = patchSiteOverlay([], patch); + assert.equal(r.ok, false); + return r.ok ? "" : r.error; + }; + assert.match(no({ id: "case-a", rules: [] }), /"rules" is not a site presentation field/); + assert.match(no({ id: "case-a", sites: ["x"] }), /"sites" is not/); + assert.match(no({ id: "case-a" }), /name at least one/); + assert.match(no({ id: "Bad Id!", secondary: true }), /"id" must be a tag id/); + assert.match(no({ id: "case-a", secondary: "yes" }), /"secondary" has no usable value/); + assert.match(no({ id: "case-a", order: "3" }), /"order" has no usable value/); + assert.match(no({ id: "case-a", label: " " }), /"label" has no usable value/); +}); diff --git a/common/lib/curatedTags.ts b/common/lib/curatedTags.ts @@ -70,7 +70,7 @@ export type CuratedTagDef = { // one and rename the tag on that site. Absent means "whatever the layer below // says", and the display fallback everywhere is `label ?? id`. label?: string; - // Optional grouping so a chip row can read "Eva: Collab · In chat · Discussed". + // Optional grouping so a chip row can read "Case: Collab · In chat · Discussed". group?: string; groupLabel?: string; description?: string; @@ -80,12 +80,17 @@ export type CuratedTagDef = { // Presentation only: hidden tags are dropped from a published /tags.json but // still ride on records (a site hides a chip; it does not erase a fact). hidden?: boolean; + // Presentation only: a secondary tag is still published and still filters, + // but the viewer offers it under "More filters" (closed until one of its tags + // is selected) instead of in the main Tags row. Per tag, like `hidden`; a + // group whose members disagree is split across the two places. + secondary?: boolean; // The sites this tag EXISTS on (site ids). Absent or empty = every site. // Unlike `hidden`, this is not presentation: a scoped tag is never derived for // a video whose channel is not a member of one of these sites (its rules do // not fire there and its pins do not apply), and a site outside the list // drops it from its summaries and its /tags.json — so it is on no record, - // chip or count of another site (the Eva tags: Anilyzer's only). Corpus layer + // chip or count of another site (one investigation's tags on one site). Corpus layer // only: a site's own tags.json cannot widen or narrow it. sites?: string[]; // Optional — a purely manual tag is legal. @@ -128,6 +133,9 @@ export type PublishedTag = { groupLabel?: string; color?: string; order?: number; + // Written only when true, so a site that uses no secondary tag publishes the + // same bytes as before the field existed. + secondary?: true; count: number; // slug -> number of videos carrying this tag on that channel. channels: Record<string, number>; @@ -251,6 +259,14 @@ function coerceTagDef(raw: unknown, layer: TagLayer): CuratedTagDef | null { : undefined; // Corpus layer only (see the field): a site row's `sites` is dropped. const sites = layer === "site" ? [] : siteIdList(r.sites); + // The two presentation switches. At the corpus layer `false` is the default + // and is not stored. At the site layer it is an answer — "shown here" over a + // corpus `hidden`, "main row here" over a corpus `secondary` — and dropping it + // would make the site page's choice vanish on save. + const flag = (v: unknown): boolean | undefined => + v === true ? true : v === false && layer === "site" ? false : undefined; + const hidden = flag(r.hidden); + const secondary = flag(r.secondary); return { id, ...(label !== undefined ? { label } : {}), @@ -263,7 +279,8 @@ function coerceTagDef(raw: unknown, layer: TagLayer): CuratedTagDef | null { : {}), ...(trimmedString(r.color) ? { color: trimmedString(r.color) } : {}), ...(order !== undefined ? { order } : {}), - ...(r.hidden === true ? { hidden: true } : {}), + ...(hidden !== undefined ? { hidden } : {}), + ...(secondary !== undefined ? { secondary } : {}), ...(sites.length > 0 ? { sites } : {}), ...(rules.length > 0 ? { rules } : {}), }; @@ -434,7 +451,7 @@ export function sanitizeTagsConfig( // Layer a site's tags.json over the corpus one. // // For an id the corpus already defines, the site entry is a FIELD-WISE OVERLAY -// of label/groupLabel/color/order/hidden — presentation, and nothing else. It +// of label/groupLabel/color/order/hidden/secondary — presentation, and nothing else. It // can never delete a corpus rule, and it cannot add one: coerceTagDef drops // rules from a site layer entirely (see there for why a per-site rule cannot // tag anything), so there is nothing here to append. Assignments do not live at @@ -464,12 +481,85 @@ export function mergeTagDefs( if (overlay.color !== undefined) base.color = overlay.color; if (overlay.order !== undefined) base.order = overlay.order; if (overlay.hidden !== undefined) base.hidden = overlay.hidden; + if (overlay.secondary !== undefined) base.secondary = overlay.secondary; // No rule branch: a sanitized site def has none, and the corpus rules on // `base` are left exactly as the corpus wrote them. } return out; } +// The fields a site row may set: exactly the ones mergeTagDefs applies. +export const SITE_OVERLAY_FIELDS = [ + "label", + "groupLabel", + "color", + "order", + "hidden", + "secondary", +] as const; + +export type SiteOverlayField = (typeof SITE_OVERLAY_FIELDS)[number]; + +// Change ONE row of a site's overlay, keeping every other row and every field +// of this one the patch does not name. A field set to `null` is cleared (the +// site inherits it again); a row left saying nothing is removed. Used by the +// `tags` op `present`, which holds one tag, where the site page saves the whole +// list. Pure: the caller reads and writes the file. +export function patchSiteOverlay( + rows: readonly CuratedTagDef[], + patch: Record<string, unknown>, +): + | { ok: true; tags: CuratedTagDef[]; row: CuratedTagDef | null } + | { ok: false; error: string } { + const id = normalizeTagId(patch.id); + if (!id) { + return { + ok: false, + error: + '"id" must be a tag id — lowercase letters, digits, ".", "_" and "-", starting with a letter or digit', + }; + } + const fields = SITE_OVERLAY_FIELDS as readonly string[]; + const foreign = Object.keys(patch).find((k) => k !== "id" && !fields.includes(k)); + if (foreign !== undefined) { + return { + ok: false, + error: `"${foreign}" is not a site presentation field — a site sets ${SITE_OVERLAY_FIELDS.join(", ")}; rules, sites and assignments belong to the corpus vocabulary`, + }; + } + const named = SITE_OVERLAY_FIELDS.filter((k) => k in patch); + if (named.length === 0) { + return { + ok: false, + error: `name at least one of ${SITE_OVERLAY_FIELDS.join(", ")} (null clears one)`, + }; + } + const current = rows.find((r) => r.id === id); + const merged: Record<string, unknown> = { ...(current ?? { id }) }; + for (const k of named) { + if (patch[k] === null) delete merged[k]; + else merged[k] = patch[k]; + } + const row = coerceTagDef(merged, "site"); + if (!row) return { ok: false, error: `"${id}" is not a valid tag id` }; + // A value the coercion dropped was not one: say so rather than write a row + // that silently ignored half the ask. + const dropped = named.find((k) => patch[k] !== null && row[k] === undefined); + if (dropped !== undefined) { + return { + ok: false, + error: `"${dropped}" has no usable value (${JSON.stringify(patch[dropped])})`, + }; + } + const says = SITE_OVERLAY_FIELDS.some((k) => row[k] !== undefined); + const tags = !says + ? rows.filter((r) => r.id !== id) + : current + ? rows.map((r) => (r.id === id ? row : r)) + : [...rows, row]; + return { ok: true, tags, row: says ? row : null }; +} + // (rule hits ∪ manual pins) − suppressions, with a pin beating a suppression of // the same tag, sorted by def `order` then id so a record's `curatedTags` array // is stable across builds. diff --git a/common/lib/publishedTags.test.ts b/common/lib/publishedTags.test.ts @@ -4,6 +4,7 @@ import { coercePublishedTags, groupPublishedTags, selectableTags, + splitSecondaryTags, tagLabels, } from "./publishedTags"; @@ -121,3 +122,43 @@ test("tagLabels falls back to the id for a tag this site does not publish", () = assert.equal(labels.get("eva-collab"), "Collab"); assert.equal(labels.get("eva-topic"), undefined); }); + +test("coercePublishedTags keeps `secondary` only when it is exactly true", () => { + const tags = coercePublishedTags({ + version: 1, + tags: [ + tag({ id: "case-a", secondary: true }), + tag({ id: "case-b", secondary: "true" }), + tag({ id: "case-c", secondary: false }), + ], + }); + assert.deepEqual( + tags.map((t) => [t.id, "secondary" in t ? t.secondary : "-"]), + [ + ["case-a", true], + ["case-b", "-"], + ["case-c", "-"], + ], + ); +}); + +test("splitSecondaryTags keeps each side in order, so grouping either is stable", () => { + const tags = coercePublishedTags({ + version: 1, + tags: [ + tag({ id: "case-a", group: "one", order: 1 }), + tag({ id: "case-b", group: "two", order: 2, secondary: true }), + tag({ id: "case-c", group: "one", order: 3, secondary: true }), + tag({ id: "case-d", order: 4 }), + ], + }); + const { primary, secondary } = splitSecondaryTags(tags); + assert.deepEqual(primary.map((t) => t.id), ["case-a", "case-d"]); + assert.deepEqual(secondary.map((t) => t.id), ["case-b", "case-c"]); + assert.deepEqual( + groupPublishedTags(secondary).map((g) => g.id), + ["two", "one"], + ); + // A site with no secondary tag: everything is primary, nothing moves. + assert.deepEqual(splitSecondaryTags(primary).secondary, []); +}); diff --git a/common/lib/publishedTags.ts b/common/lib/publishedTags.ts @@ -60,6 +60,7 @@ function coerceTag(raw: unknown): PublishedTag | null { ...(str(r.groupLabel) ? { groupLabel: str(r.groupLabel) } : {}), ...(str(r.color) ? { color: str(r.color) } : {}), ...(num(r.order) !== undefined ? { order: num(r.order) } : {}), + ...(r.secondary === true ? { secondary: true as const } : {}), count: Math.floor(count), channels: coerceChannels(r.channels), }; @@ -140,6 +141,20 @@ export function groupPublishedTags( return out.sort((a, b) => (a.id === "" ? 1 : b.id === "" ? -1 : 0)); } +// The chip row's two places: the main Tags row and the "More filters" +// disclosure. A tag is secondary by its own flag (CuratedTagDef.secondary); +// each side keeps the input order, so grouping either one with +// groupPublishedTags gives the same group order the whole list would. +export function splitSecondaryTags(tags: readonly PublishedTag[]): { + primary: PublishedTag[]; + secondary: PublishedTag[]; +} { + const primary: PublishedTag[] = []; + const secondary: PublishedTag[] = []; + for (const tag of tags) (tag.secondary ? secondary : primary).push(tag); + return { primary, secondary }; +} + // id -> label, for rendering a record's `curatedTags` on a card. A tag the // site does not publish (hidden, zero-count here, or defined after this page // was built) falls back to its id — the fact is on the record either way, and diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A tag can be offered under the site's More filters, per site or for the whole corpus.** A site's Tags tab (Sites → a site → Tags) replaces Visibility with **Placement**: Inherit, Main row, More filters, Hidden. Main row and More filters both override a tag the corpus hides, which "Shown here" said it did but never saved. On /tags, a definition's **More filters** box sets the corpus default. The CLI twin is a new `tags` op, `present`: `pnpm ops tags --json '{"op":"present","site":"<site>","tag":{"id":"<tag>","secondary":true}}'` changes one row of `sites/<site>/tags.json`, keeping its other rows and fields; `null` clears a field so the site inherits it again. It is refused, with nothing written, for an unknown site, a tag the corpus does not define, or a field a site cannot set (rules, sites). Needs a rebuild and deploy of the site. - **umtool: a `take --priority` or `render-mode on -- …` signalled while it turns render mode on lets it go before it exits.** The signal handlers used to go on only after the claim (the state file and the editor's lanes, held over HTTP), so a signal in that time killed the process with its hold and its lanes left for the heartbeat to find. Now the claim diff --git a/editor/app/api/ops/tags/route.test.ts b/editor/app/api/ops/tags/route.test.ts @@ -0,0 +1,123 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/tags/route.test.ts" +// +// `tags` op `present` (presentSiteTagAction): ONE row of a site's +// sites/<site>/tags.json, merged field by field. Every refusal is answered +// before anything is written. The write ends in safeRevalidate, which a bare +// tsx process (no request store) skips, so the write path runs here too. + +const corpus = await setupOpsCorpus(null); +await corpus.writeSite("demo-site"); +const globalTags = { + version: 1, + tags: [ + { id: "case-collab", label: "Collab", group: "case", groupLabel: "Case" }, + { id: "case-topic", label: "Discussed", group: "case", groupLabel: "Case" }, + ], + assignments: {}, +}; +await writeFile( + path.join(corpus.transcripts, "tags.json"), + JSON.stringify(globalTags, null, 2), +); +const siteFile = path.join(corpus.transcripts, "sites", "demo-site", "tags.json"); +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); + +const present = (tag: unknown, site: unknown = "demo-site") => + callPost(POST, { op: "present", site, tag }); +const siteText = () => readFile(siteFile, "utf8").catch(() => null); +const siteRows = async () => JSON.parse((await siteText()) ?? "{}").tags; + +test("present merges one row, keeps the others, and null clears a field", async () => { + await rm(siteFile, { force: true }); + const a = await present({ id: "case-collab", secondary: true }); + assert.equal(a.status, 200, JSON.stringify(a.body)); + assert.deepEqual(a.body.row, { id: "case-collab", secondary: true }); + + const b = await present({ id: "case-topic", color: "#b48ead", order: 3 }); + assert.equal(b.status, 200, JSON.stringify(b.body)); + // The first row is kept; a later patch of it keeps its other fields. + const c = await present({ id: "case-collab", label: "With", hidden: false }); + assert.deepEqual(c.body.row, { + id: "case-collab", + label: "With", + hidden: false, + secondary: true, + }); + assert.deepEqual(await siteRows(), [ + { id: "case-collab", label: "With", hidden: false, secondary: true }, + { id: "case-topic", color: "#b48ead", order: 3 }, + ]); + + // Every allowed field can be cleared; a row left saying nothing goes. + const d = await present({ + id: "case-collab", + label: null, + hidden: null, + secondary: null, + }); + assert.equal(d.status, 200); + assert.equal(d.body.row, null); + assert.deepEqual(await siteRows(), [ + { id: "case-topic", color: "#b48ead", order: 3 }, + ]); + // A groupLabel is a site presentation field too. + const e = await present({ id: "case-topic", groupLabel: "Elsewhere" }); + assert.equal(e.status, 200); + assert.equal((e.body.row as { groupLabel?: string }).groupLabel, "Elsewhere"); +}); + +test("present refuses, writing nothing", async () => { + await rm(siteFile, { force: true }); + await present({ id: "case-topic", secondary: true }); + const before = await siteText(); + for (const [body, re] of [ + [{ op: "present", site: "demo-site", tag: { id: "case-nope", secondary: true } }, /no tag "case-nope" is defined in the corpus vocabulary — define it/], + [{ op: "present", site: "no-such-site", tag: { id: "case-topic", secondary: true } }, /Site "no-such-site" not found/], + [{ op: "present", site: "Bad Site!", tag: { id: "case-topic", secondary: true } }, /not a valid site id/], + [{ op: "present", tag: { id: "case-topic", secondary: true } }, /"site" must be a site id/], + [{ op: "present", site: "demo-site", tag: "case-topic" }, /"tag" must be an object/], + [{ op: "present", site: "demo-site", tag: { id: "case-topic", rules: [] } }, /"rules" is not a site presentation field/], + [{ op: "present", site: "demo-site", tag: { id: "case-topic", sites: ["x"] } }, /"sites" is not a site presentation field/], + [{ op: "present", site: "demo-site", tag: { id: "case-topic" } }, /name at least one/], + [{ op: "present", site: "demo-site", tag: { id: "case-topic", secondary: "yes" } }, /"secondary" has no usable value/], + [{ op: "define", site: "demo-site", tag: { id: "case-topic" } }, /"site" is for op "present" only/], + [{ op: "present", site: "demo-site", tag: { id: "case-topic", secondary: true }, extra: 1 }, /extra/], + ] as const) { + const r = await callPost(POST, body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.body.error), re, JSON.stringify(r.body)); + } + assert.equal(await siteText(), before, "nothing written"); +}); + +test("a site-only tag is refused without the advice to define it", async () => { + await writeFile( + siteFile, + JSON.stringify({ version: 1, tags: [{ id: "site-only", label: "Here only" }], assignments: {} }), + ); + const before = await siteText(); + const r = await present({ id: "site-only", secondary: true }); + assert.equal(r.status, 400); + assert.match(String(r.body.error), /"site-only" is a site-only tag of "demo-site"/); + assert.doesNotMatch(String(r.body.error), /define/); + assert.equal(await siteText(), before); +}); + +test("a site tags file that does not parse is named and left as it is", async () => { + await mkdir(path.dirname(siteFile), { recursive: true }); + const broken = '{"version":1,"tags":[{"id":"case-topic","color":"#fff"},'; + await writeFile(siteFile, broken); + const r = await present({ id: "case-collab", secondary: true }); + assert.equal(r.status, 400); + assert.ok(String(r.body.error).includes(siteFile), String(r.body.error)); + assert.match(String(r.body.error), /cannot be read as JSON/); + assert.equal(await siteText(), broken, "the file is untouched"); +}); diff --git a/editor/app/api/ops/tags/route.ts b/editor/app/api/ops/tags/route.ts @@ -2,7 +2,11 @@ import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { sanitizeTagsConfig } from "yt-dlp-transcript-common/lib/curatedTags"; import { readGlobalTags } from "../../../../lib/tagsStore"; -import { defineTagAction, removeTagDefAction } from "../../../tags/actions"; +import { + defineTagAction, + presentSiteTagAction, + removeTagDefAction, +} from "../../../tags/actions"; import { OpsInputError, oneOf, ops, opsAuth, opsFail } from "../_lib"; export const dynamic = "force-dynamic"; @@ -10,6 +14,7 @@ export const dynamic = "force-dynamic"; // GET /api/ops/tags -> { ok, tags: [ def + { pinned, suppressed } ] } // GET /api/ops/tags?tag=<id> -> { ok, tag, assignments: [...] } // POST /api/ops/tags { op: "define"|"remove", tag } +// POST /api/ops/tags { op: "present", site, tag: { id, <presentation fields> } } // // THE READ SIDE IS THE COUNTS A PERSON OR AN AGENT ASSERTED, and it says so: // pins and suppressions are stored, RULE HITS ARE NOT. A rule is re-evaluated @@ -89,8 +94,30 @@ export async function GET(request: Request) { // id and drops the DEFINITION ONLY: assignments survive, because an assignment // is a fact about a video and a definition is a label for it. export async function POST(request: Request) { - return ops(request, ["op", "tag"], async (body) => { - const op = oneOf(body, "op", ["define", "remove"] as const); + return ops(request, ["op", "tag", "site"], async (body) => { + const op = oneOf(body, "op", ["define", "remove", "present"] as const); + if (body.site !== undefined && op !== "present") { + throw new OpsInputError('"site" is for op "present" only'); + } + // `present` is a SITE's presentation of a corpus tag — one row of + // sites/<site>/tags.json, merged field by field (null clears a field). + if (op === "present") { + const site = typeof body.site === "string" ? body.site.trim() : ""; + if (!site) throw new OpsInputError('"site" must be a site id'); + const raw = body.tag; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new OpsInputError( + '"tag" must be an object { id, label?, groupLabel?, color?, order?, hidden?, secondary? }', + ); + } + const result = await presentSiteTagAction( + site, + raw as Record<string, unknown>, + ); + return result.ok + ? NextResponse.json({ ok: true, site, row: result.row }) + : opsFail(result.error); + } if (op === "remove") { const id = typeof body.tag === "string" ? body.tag.trim() : ""; if (!id) throw new OpsInputError('"tag" must be a tag id string'); diff --git a/editor/app/sites/[siteId]/tags/page.tsx b/editor/app/sites/[siteId]/tags/page.tsx @@ -14,7 +14,7 @@ export const metadata: Metadata = { title: "Tags" }; // // The corpus file is authoritative for what a tag IS, which rules derive it and // which videos carry it. This tab is presentation only: label, group label, -// colour, order, visibility. +// colour, order, placement (main row, More filters, hidden). // // No rule editor, deliberately. A rule decides whether a tag lands on a RECORD, // and a record is shared by every site carrying its channel — a site-layer rule diff --git a/editor/app/sites/components/SiteTagsClient.tsx b/editor/app/sites/components/SiteTagsClient.tsx @@ -2,7 +2,7 @@ // One site's overlay on the corpus vocabulary — PRESENTATION ONLY. // -// A row per corpus tag, with label / group label / colour / order / visibility. +// A row per corpus tag, with label / group label / colour / order / placement. // Every field is optional and a blank one inherits, so the site's file holds // only what this site actually changed. // @@ -11,7 +11,8 @@ // carries its channel — so a site-layer rule would be one site editing another // site's data. Rules and assignments live in the corpus vocabulary at /tags; // what a site owns is how the tag READS: its wording, its colour, its position -// in the chip row, and whether it appears at all. +// in the chip row, whether it sits in the main row or under "More filters", +// and whether it appears at all. // // For the same reason there is nothing here that deletes a corpus rule or an // assignment: an assignment is a fact about a video, not a presentation choice. @@ -28,11 +29,28 @@ type OverlayRow = { groupLabel: string; color: string; order: string; - // Three states, not two: inherit / shown / hidden. A site that has said - // nothing about a tag must not start writing `hidden: false` into its file. - hidden: "" | "true" | "false"; + // Where the chip goes on this site. "" inherits the corpus, and writes + // neither flag — a site that has said nothing about a tag must not start + // writing `hidden: false` into its file. "main" and "secondary" both say + // `hidden: false` (shown here, over a corpus `hidden`), and differ in + // `secondary`; "hidden" says `hidden: true` alone. + placement: Placement; }; +type Placement = "" | "main" | "secondary" | "hidden"; + +function placementOf(site: CuratedTagDef | undefined): Placement { + if (site?.hidden === true) return "hidden"; + if (site?.secondary === true) return "secondary"; + if (site?.hidden === false || site?.secondary === false) return "main"; + return ""; +} + +function inheritedPlacement(def: CuratedTagDef): string { + if (def.hidden) return "hidden"; + return def.secondary ? "more filters" : "main row"; +} + function overlayRowFor(id: string, site: CuratedTagDef | undefined): OverlayRow { return { id, @@ -40,7 +58,7 @@ function overlayRowFor(id: string, site: CuratedTagDef | undefined): OverlayRow groupLabel: site?.groupLabel ?? "", color: site?.color ?? "", order: site?.order === undefined ? "" : String(site.order), - hidden: site?.hidden === undefined ? "" : site.hidden ? "true" : "false", + placement: placementOf(site), }; } @@ -51,7 +69,7 @@ function overlayToDef(row: OverlayRow): CuratedTagDef | null { const groupLabel = row.groupLabel.trim(); const color = row.color.trim(); const hasOrder = row.order.trim() !== "" && Number.isFinite(order); - if (!label && !groupLabel && !color && !hasOrder && row.hidden === "") { + if (!label && !groupLabel && !color && !hasOrder && row.placement === "") { return null; } // mergeTagDefs applies only the fields that are PRESENT, so an overlay with @@ -63,7 +81,11 @@ function overlayToDef(row: OverlayRow): CuratedTagDef | null { if (groupLabel) def.groupLabel = groupLabel; if (color) def.color = color; if (hasOrder) def.order = order; - if (row.hidden !== "") def.hidden = row.hidden === "true"; + if (row.placement === "hidden") def.hidden = true; + else if (row.placement !== "") { + def.hidden = false; + def.secondary = row.placement === "secondary"; + } return def; } @@ -200,22 +222,21 @@ export function SiteTagsClient({ /> </label> <label className="flex flex-col gap-1 text-xs text-muted-foreground"> - Visibility + Placement <select - value={row.hidden} + value={row.placement} onChange={(e) => patch(g.id, { - hidden: e.target.value as OverlayRow["hidden"], + placement: e.target.value as Placement, }) } - aria-label={`visibility for ${g.id}`} + aria-label={`placement for ${g.id}`} className="rounded border border-border bg-card px-2 py-1 text-sm text-foreground" > - <option value=""> - Inherit ({g.hidden ? "hidden" : "shown"}) - </option> - <option value="false">Shown here</option> - <option value="true">Hidden here</option> + <option value="">Inherit ({inheritedPlacement(g)})</option> + <option value="main">Main row</option> + <option value="secondary">More filters</option> + <option value="hidden">Hidden here</option> </select> </label> </div> diff --git a/editor/app/tags/actions.ts b/editor/app/tags/actions.ts @@ -3,8 +3,16 @@ import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; +import { existsSync, readFileSync } from "node:fs"; +import { + isValidSiteId, + siteConfigFile, + siteTagsFile, +} from "yt-dlp-transcript-common/lib/site"; +import { safeRevalidate } from "../lib/safeRevalidate"; import { TAG_ID_RE, + patchSiteOverlay, sanitizeTagsConfig, type CuratedTagAssignment, type CuratedTagDef, @@ -94,6 +102,61 @@ export async function saveSiteTagDefsAction( return { ok: true }; } +// ONE row of one site's overlay — the `tags` op `present`. The site page saves +// the whole list; an agent holding one tag sends only the fields it changes +// (`null` clears one), and every other row and field is kept. Refused before +// anything is written: +// - an unknown site; +// - a site tags file that exists but does not parse. readSiteTags reads that +// as "no overlay", and writing the patched row over it would drop every +// row the file held — the opposite of what this op promises; +// - a tag the corpus does not define. A site row for an undefined id would +// be a new site-only tag, which is a vocabulary decision, not a +// presentation one — and usually a typo. A site-only tag the site already +// has is refused too, without the advice to `define` it: that would make +// it a corpus tag on every site. +export async function presentSiteTagAction( + siteId: string, + patch: Record<string, unknown>, +): Promise< + { ok: true; row: CuratedTagDef | null } | { ok: false; error: string } +> { + if (!isValidSiteId(siteId)) { + return { ok: false, error: `"${siteId}" is not a valid site id` }; + } + const paths = getPaths(); + if (!existsSync(siteConfigFile(paths, siteId))) { + return { ok: false, error: `Site "${siteId}" not found` }; + } + const file = siteTagsFile(paths, siteId); + if (existsSync(file)) { + try { + JSON.parse(readFileSync(file, "utf8")); + } catch (err) { + return { + ok: false, + error: `${file} cannot be read as JSON (${err instanceof Error ? err.message : String(err)}) — fix or remove it first; nothing was written, so its rows are as they were`, + }; + } + } + const current = readSiteTags(paths, siteId); + const id = typeof patch.id === "string" ? patch.id.trim().toLowerCase() : ""; + if (id && !readGlobalTags(paths).tags.some((t) => t.id === id)) { + return { + ok: false, + error: current.tags.some((t) => t.id === id) + ? `"${id}" is a site-only tag of "${siteId}" (in ${file}), not a corpus tag — "present" sets how a site shows a corpus tag` + : `no tag "${id}" is defined in the corpus vocabulary — define it with op "define" first`, + }; + } + const result = patchSiteOverlay(current.tags, patch); + if (!result.ok) return result; + writeSiteTags(paths, siteId, { ...current, assignments: {}, tags: result.tags }); + // Guarded: the ops route and a unit test call this outside a page request. + safeRevalidate([`/sites/${siteId}/tags`]); + return { ok: true, row: result.row }; +} + // Upsert ONE definition, keeping the rest of the vocabulary and every // assignment. The list-shaped save above is what the page uses; this is what a // caller holding a single tag (the ops route, a seeding script) needs, and diff --git a/editor/app/tags/components/EditorTagsClient.tsx b/editor/app/tags/components/EditorTagsClient.tsx @@ -54,6 +54,8 @@ type TagRow = { color: string; order: string; hidden: boolean; + // Offered under the viewer's "More filters" rather than in the main row. + secondary: boolean; // `sites`, comma-separated: the sites this tag exists on (empty = every site). sitesText: string; rules: RuleRow[]; @@ -78,6 +80,7 @@ function toRow(def: CuratedTagDef): TagRow { color: def.color ?? "", order: def.order === undefined ? "" : String(def.order), hidden: def.hidden === true, + secondary: def.secondary === true, sitesText: (def.sites ?? []).join(", "), rules: (def.rules ?? []).map((r) => ({ ...r, @@ -99,6 +102,7 @@ function toDef(row: TagRow): CuratedTagDef { ...(row.color.trim() ? { color: row.color.trim() } : {}), ...(row.order.trim() !== "" && Number.isFinite(order) ? { order } : {}), ...(row.hidden ? { hidden: true } : {}), + ...(row.secondary ? { secondary: true } : {}), ...(siteList(row.sitesText).length > 0 ? { sites: siteList(row.sitesText) } : {}), ...(row.rules.length > 0 ? { @@ -202,6 +206,7 @@ export function EditorTagsClient({ color: "", order: "", hidden: false, + secondary: false, sitesText: "", rules: [], }, @@ -526,6 +531,18 @@ function TagCard({ /> Hidden </label> + <label + className="flex items-center gap-1.5 pb-1.5 text-xs" + title="Still published and filterable, but offered under the site's More filters instead of the main Tags row" + > + <input + type="checkbox" + checked={row.secondary} + onChange={(e) => onPatch({ secondary: e.target.checked })} + aria-label="tag secondary" + /> + More filters + </label> <button type="button" onClick={onRemove} diff --git a/editor/e2e/tags.spec.ts b/editor/e2e/tags.spec.ts @@ -485,7 +485,7 @@ test("a site overlays presentation and cannot touch rules, assignments or a labe // COLOUR ONLY. Nothing here says anything about the label, and the tag must // not come out of the merge renamed to its id. await overlay.getByLabel("colour for eva-collab").fill("#b48ead"); - await overlay.getByLabel("visibility for eva-collab").selectOption("true"); + await overlay.getByLabel("placement for eva-collab").selectOption("hidden"); await page.getByRole("button", { name: "save site tags" }).click(); await expect(page.getByTestId("site-tags-saved")).toBeVisible(); @@ -525,3 +525,89 @@ test("a site overlays presentation and cannot touch rules, assignments or a labe .tags[0].label, ).toBeUndefined(); }); + +test("a site places a tag under More filters, in the main row or hidden — and the ops op `present` sets one row", async ({ + page, +}) => { + await resetData("curated-tags-channel"); + await writeSite("testsite", { + channels: [{ slug: SLUG, groupId: "default" }], + }); + await addTag(page, "case-collab", "Collab"); + await addTag(page, "case-topic", "Discussed"); + + // The corpus switch: a "More filters" box on the definition itself. + await page.goto("/tags"); + const cards = page.getByTestId("tag-card"); + await expect(cards).toHaveCount(2); + let topicCard = cards.first(); + for (let i = 0; i < 2; i++) { + if ((await cards.nth(i).getByLabel("tag id").inputValue()) === "case-topic") { + topicCard = cards.nth(i); + } + } + await topicCard.getByLabel("tag secondary").check(); + await page.getByRole("button", { name: "save tags" }).click(); + await expect(page.getByTestId("tags-saved")).toBeVisible(); + const topicDef = (await tagsFile()).tags.find((t) => t.id === "case-topic"); + expect((topicDef as { secondary?: boolean } | undefined)?.secondary).toBe(true); + + // The site overlay: More filters for one, Main row over the corpus for the + // other. "Main row" is an ANSWER at the site layer, so its `false`s are kept. + await page.goto("/sites/testsite/tags"); + await expect( + page.getByLabel("placement for case-topic").locator("option").first(), + ).toHaveText("Inherit (more filters)"); + await page.getByLabel("placement for case-collab").selectOption("secondary"); + await page.getByLabel("placement for case-topic").selectOption("main"); + await page.getByRole("button", { name: "save site tags" }).click(); + await expect(page.getByTestId("site-tags-saved")).toBeVisible(); + const siteFile = `${testPaths().transcriptsDir}/sites/testsite/tags.json`; + expect((await readJson<TagsFile>(siteFile)).tags).toEqual([ + { id: "case-collab", hidden: false, secondary: true }, + { id: "case-topic", hidden: false, secondary: false }, + ]); + await page.reload(); + await expect(page.getByLabel("placement for case-collab")).toHaveValue("secondary"); + await expect(page.getByLabel("placement for case-topic")).toHaveValue("main"); + + // The CLI twin: one row, merged — the colour joins, the placement stays. + const base = new URL(page.url()).origin; + const post = (data: unknown) => + page.request.post(`${base}/api/ops/tags`, { + headers: { authorization: "Bearer test-worker-token" }, + data, + }); + const ok = await post({ + op: "present", + site: "testsite", + tag: { id: "case-collab", color: "#b48ead" }, + }); + expect(ok.ok()).toBe(true); + expect((await ok.json()).row).toEqual({ + id: "case-collab", + color: "#b48ead", + hidden: false, + secondary: true, + }); + // null clears a field; the other row is untouched. + expect( + (await post({ op: "present", site: "testsite", tag: { id: "case-topic", secondary: null, hidden: null } })).ok(), + ).toBe(true); + expect((await readJson<TagsFile>(siteFile)).tags).toEqual([ + { id: "case-collab", color: "#b48ead", hidden: false, secondary: true }, + ]); + // Refused by name, nothing written: an undefined tag, an unknown site, a rule. + const refusals = [ + [{ op: "present", site: "testsite", tag: { id: "case-nope", secondary: true } }, /no tag "case-nope" is defined/], + [{ op: "present", site: "no-such-site", tag: { id: "case-collab", secondary: true } }, /Site "no-such-site" not found/], + [{ op: "present", site: "testsite", tag: { id: "case-collab", rules: [] } }, /"rules" is not a site presentation field/], + [{ op: "define", site: "testsite", tag: { id: "case-collab" } }, /"site" is for op "present" only/], + ] as const; + for (const [body, error] of refusals) { + const res = await post(body); + expect(res.status()).toBe(400); + expect((await res.json()).error).toMatch(error); + } + expect((await readJson<TagsFile>(siteFile)).tags).toHaveLength(1); +}); diff --git a/export/CHANGELOG.md b/export/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A site's secondary tags sit under More filters, and a site with many channels can find one.** A curated tag the operator marked secondary is still published, still filters and still rides on `?tg=` links, but its chips sit in a **More filters** disclosure above Advanced options instead of the main Tags row, its group's name beside them. It is closed by default and opens on its own when a link or a saved profile selects one of its tags; once you open or close it, it stays as you left it, and its summary says how many of its tags are selected. On a site with more than 12 channels, a small magnifier beside **Channels** opens a field that narrows the groups as you type to the channels whose name or slug holds the text (case, accents and punctuation ignored), or to a whole group whose name does. Esc clears it and gives the panel back as it was; in the phone sheet the first Esc clears the field and the next closes the sheet. A site with no secondary tag and 12 channels or fewer looks as it did. Needs a rebuild and deploy of each site. - **`corpus.json` is spec 6: each channel says where it is.** A channel's entry adds `platform` (youtube, rumble, …) and `url`, its page on that platform, when the archive's operator configured them, and `llms.txt` shows them beside the channel's name — what a machine with no copy of the channel needs to fetch a cited moment's media (a fresh Archilyzer clone pointed at the archive). Additive: a reader that does not know spec 6 reads the archive as before, and a reader of an older archive takes the platform from a transcript record's `webpageUrl`. Needs a rebuild and deploy of each site. ## [0.11.2] - 2026-10-21 diff --git a/export/e2e/channel-find.spec.ts b/export/e2e/channel-find.spec.ts @@ -0,0 +1,355 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +// The channel finder (common/lib/channelFind.ts) in the filter panel's +// Channels row: a magnifier, offered only on a site with more than +// CHANNEL_FIND_MIN_CHANNELS (12) channels, that opens into a small field and +// narrows the group cards to the channels whose name, slug or group name holds +// the text. Self-contained fixtures, like channel-group-chips.spec.ts. + +type Chan = { name: string; slug: string; groupId: string }; + +const CHANNELS: Chan[] = [ + { name: "Alpha Works", slug: "alpha-works", groupId: "g1" }, + { name: "Beta Desk", slug: "beta-desk", groupId: "g1" }, + { name: "Gamma Talk", slug: "gamma_talk_live", groupId: "g1" }, + { name: "Delta Notes", slug: "delta-notes", groupId: "g1" }, + { name: "Epsilon", slug: "epsilon", groupId: "g2" }, + { name: "Zeta Review", slug: "zeta-review", groupId: "g2" }, + { name: "Eta Corner", slug: "eta-corner", groupId: "g2" }, + { name: "Théta Café", slug: "theta-cafe", groupId: "g2" }, + { name: "Iota", slug: "iota", groupId: "g3" }, + { name: "Kappa", slug: "kappa", groupId: "g3" }, + { name: "Lambda", slug: "lambda", groupId: "g3" }, + { name: "Mu Stream", slug: "mu-stream", groupId: "g3" }, + { name: "Nu Show", slug: "nu-show", groupId: "g4" }, + { name: "Xi Clips", slug: "xi-clips", groupId: "g4" }, +]; + +const GROUPS = [ + { id: "g1", name: "Group One", selectedByDefault: true, order: 1 }, + { id: "g2", name: "Reviewers", selectedByDefault: true, order: 2 }, + { id: "g3", name: "Group Three", selectedByDefault: true, order: 3 }, + { id: "g4", name: "Group Four", selectedByDefault: true, order: 4 }, +]; + +function summary(c: Chan) { + return { + slug: `${c.slug}/vid-${c.slug}`, + id: `vid-${c.slug}`, + channelSlug: c.slug, + title: `Video from ${c.name}`, + uploadDate: "20250101", + date: "2025-01-01", + duration: "5:00", + channel: c.name, + isLivestream: false, + ageRestricted: false, + isDeleted: false, + isUnlisted: false, + platform: "youtube" as const, + webpageUrl: `https://example.com/vid-${c.slug}`, + }; +} + +async function fulfillJson(route: Route, body: unknown) { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(body), + }); +} + +async function installRoutes(page: Page, channels: Chan[] = CHANNELS) { + const list = channels.map(summary); + await page.route("**/summaries/manifest.json", async (route) => { + await fulfillJson(route, { + version: 3, + totalCount: list.length, + pageSize: 1000, + pageCount: 1, + generatedAt: new Date().toISOString(), + channels: channels.map((c) => ({ + name: c.name, + slug: c.slug, + count: 1, + groupId: c.groupId, + })), + groups: GROUPS, + defaultGroupId: "g1", + }); + }); + await page.route("**/summaries/page-*.json", async (route) => { + await fulfillJson(route, list); + }); + await page.route(/\/transcripts\/[^/]+\/manifest\.json$/, async (route) => { + await fulfillJson(route, { + version: 1, + channelSlug: "unused", + pageCount: 0, + maxPageBytes: 8388608, + generatedAt: new Date().toISOString(), + slugToPage: {}, + }); + }); + await page.route(/\/transcripts\/[^/]+\/page-\d+\.json$/, async (route) => { + await fulfillJson(route, []); + }); + await page.route("**/subs/manifest.json", async (route) => { + await fulfillJson(route, { + version: 4, + channels: [], + totalCount: 0, + liveChatTotalCount: 0, + generatedAt: new Date().toISOString(), + }); + }); + // No curated tags: their disclosures are <details> too. + await page.route("**/tags.json", async (route) => { + await route.fulfill({ status: 404, contentType: "application/json", body: "{}" }); + }); +} + +async function waitForHydration(page: Page) { + await page.getByTestId("query-builder").waitFor(); +} + +function groupCard(page: Page, name: string) { + return groupCards(page).filter({ hasText: name }); +} + +// Every group card, and only group cards: "Advanced options" (and a tag +// disclosure) is a nested <details> too, so the count goes by the group's +// select-all box. +function groupCards(page: Page) { + return page + .locator("details details") + .filter({ has: page.getByRole("checkbox", { name: /^Select all in / }) }); +} + +function memberCheckbox(page: Page, group: string, channel: string) { + return groupCard(page, group).getByRole("checkbox", { + name: channel, + exact: true, + }); +} + +const opener = (page: Page) => page.getByTestId("channel-find-open"); +const field = (page: Page) => page.getByTestId("channel-find"); + +test.describe("channel finder", () => { + test("is not offered on a site with 12 channels or fewer", async ({ page }) => { + await installRoutes(page, CHANNELS.slice(0, 12)); + await page.goto("/"); + await waitForHydration(page); + await expect(page.getByText("12 of 12 channels")).toBeVisible(); + await expect(opener(page)).toHaveCount(0); + }); + + test("is offered from 13 channels", async ({ page }) => { + await installRoutes(page, CHANNELS.slice(0, 13)); + await page.goto("/"); + await waitForHydration(page); + await expect(page.getByText("13 of 13 channels")).toBeVisible(); + await expect(opener(page)).toBeVisible(); + }); + + test("an empty open field never moves the row under a click: All and Reset channels land", async ({ + page, + }) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + const all = page.getByRole("checkbox", { name: "All", exact: true }); + await expect(all).toBeChecked(); + + // Open, leave empty, click All with a real press and release. + await opener(page).click(); + await expect(field(page)).toBeFocused(); + const at = await all.boundingBox(); + await page.mouse.move(at!.x + at!.width / 2, at!.y + at!.height / 2); + await page.mouse.down(); + // While the press is held the field is still there, so All has not moved. + await expect(field(page)).toBeVisible(); + expect((await all.boundingBox())!.x).toBe(at!.x); + await page.mouse.up(); + await expect(page.getByText("0 of 14 channels")).toBeVisible(); + await expect(all).not.toBeChecked(); + // …and only then does the empty field fold back to the magnifier. + await expect(field(page)).toHaveCount(0); + + // Reset channels from an open empty field: the click lands too. + await opener(page).click(); + await expect(field(page)).toBeFocused(); + await page.getByRole("button", { name: "Reset channels" }).click(); + await expect(page.getByText("14 of 14 channels")).toBeVisible(); + await expect(field(page)).toHaveCount(0); + }); + + test("while filtering, a group's None, box and count act on the channels listed", async ({ + page, + }) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + await opener(page).click(); + + // One match in a four-channel group: the count is matches-selected/matches. + await field(page).fill("talk"); + const one = groupCard(page, "Group One"); + await expect(one.locator("summary")).toContainText("1/1"); + await one.getByRole("button", { name: "None" }).click(); + await expect(page.getByText("13 of 14 channels")).toBeVisible(); + await expect(one.locator("summary")).toContainText("0/1"); + // The group's box re-selects just the match. + await page.getByRole("checkbox", { name: "Select all in Group One" }).click(); + await expect(page.getByText("14 of 14 channels")).toBeVisible(); + await one.getByRole("button", { name: "None" }).click(); + + // A matched group NAME lists the whole group, so None is the whole group. + await field(page).fill("reviewer"); + await groupCard(page, "Reviewers").getByRole("button", { name: "None" }).click(); + await expect(page.getByText("9 of 14 channels")).toBeVisible(); + + // No query: the whole group again. + await field(page).press("Escape"); + await expect(groupCard(page, "Group One").locator("summary")).toContainText("3/4"); + }); + + test("the live region is there before the first query, so the first count is announced", async ({ + page, + }) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + await opener(page).click(); + const live = page.getByTestId("channel-find-live"); + await expect(live).toHaveCount(1); + await expect(live).toHaveText(""); + await field(page).fill("kappa"); + await expect(live).toHaveText("1 channel matches"); + await field(page).fill("zzz"); + await expect(live).toHaveText("No channel matches"); + }); + + test("narrows the groups by channel name, slug or group name, and Esc gives the panel back", async ({ + page, + }, testInfo) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + await expect(page.getByText("14 of 14 channels")).toBeVisible(); + + // A multi-group site starts with every group folded. + await expect(groupCards(page).and(page.locator("details[open]"))).toHaveCount(0); + const where = await opener(page).boundingBox(); + await page.getByTestId("filters-panel").screenshot({ + path: testInfo.outputPath("channel-find-closed-desktop.png"), + }); + + await opener(page).click(); + await expect(field(page)).toBeFocused(); + // The field opened where the magnifier was. + const at = await field(page).boundingBox(); + expect(Math.abs(at!.x - where!.x)).toBeLessThan(2); + expect(Math.abs(at!.height - where!.height)).toBeLessThan(2); + + // A channel name: its group alone, open, listing that channel alone. + await field(page).fill("gamma"); + await expect(groupCards(page)).toHaveCount(1); + await expect(groupCard(page, "Group One")).toHaveAttribute("open", ""); + await expect(memberCheckbox(page, "Group One", "Gamma Talk")).toBeVisible(); + await expect(memberCheckbox(page, "Group One", "Alpha Works")).toHaveCount(0); + // While filtering the count is the matches': selected of listed. + await expect(groupCard(page, "Group One").locator("summary")).toContainText("1/1"); + + // A slug: separators read as spaces. + await field(page).fill("talk live"); + await expect(memberCheckbox(page, "Group One", "Gamma Talk")).toBeVisible(); + + // Accents fold. + await field(page).fill("theta cafe"); + await expect(memberCheckbox(page, "Reviewers", "Théta Café")).toBeVisible(); + + // A group name: the whole group. + await field(page).fill("reviewer"); + await expect(groupCards(page)).toHaveCount(1); + await expect(groupCard(page, "Reviewers").getByRole("checkbox")).toHaveCount(5); + await page.getByTestId("filters-panel").screenshot({ + path: testInfo.outputPath("channel-find-open-desktop.png"), + }); + + // Nothing: said, not a blank panel. + await field(page).fill("no such thing"); + await expect(page.getByTestId("channel-find-empty")).toContainText("no such thing"); + await expect(groupCards(page)).toHaveCount(0); + + // Esc: cleared, closed, focus back on the magnifier, the folded panel back. + await field(page).press("Escape"); + await expect(field(page)).toHaveCount(0); + await expect(opener(page)).toBeFocused(); + await expect(groupCards(page)).toHaveCount(4); + await expect(groupCards(page).and(page.locator("details[open]"))).toHaveCount(0); + }); + + test("keyboard: Enter opens it, a channel toggles from the found list", async ({ + page, + }) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + + await opener(page).focus(); + await page.keyboard.press("Enter"); + await expect(field(page)).toBeFocused(); + await page.keyboard.type("kappa"); + const box = memberCheckbox(page, "Group Three", "Kappa"); + await expect(box).toBeVisible(); + await box.click(); + await expect(page.getByText("13 of 14 channels")).toBeVisible(); + + // Clearing the query keeps the selection and the reader's fold state. + await field(page).fill(""); + await field(page).press("Escape"); + await expect(page.getByText("13 of 14 channels")).toBeVisible(); + await expect(groupCards(page).and(page.locator("details[open]"))).toHaveCount(0); + }); + + test.describe("on a phone", () => { + test.use({ viewport: { width: 390, height: 844 } }); + + test("fits the sheet and does not scroll the page sideways", async ({ + page, + }, testInfo) => { + await installRoutes(page); + await page.goto("/"); + await waitForHydration(page); + await page.getByTestId("filters-trigger").click(); + + await expect(opener(page)).toBeVisible(); + await page.screenshot({ + path: testInfo.outputPath("channel-find-closed-phone.png"), + }); + await opener(page).click(); + await field(page).fill("show"); + await expect(memberCheckbox(page, "Group Four", "Nu Show")).toBeVisible(); + const at = await field(page).boundingBox(); + expect(at!.x + at!.width).toBeLessThanOrEqual(390); + const sideways = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(sideways).toBe(false); + await page.screenshot({ + path: testInfo.outputPath("channel-find-open-phone.png"), + }); + // Esc is the finder's first: the sheet stays, the magnifier comes back. + await field(page).press("Escape"); + await expect(field(page)).toHaveCount(0); + await expect(opener(page)).toBeVisible(); + await expect(opener(page)).toBeFocused(); + // The second Esc is the sheet's. + await page.keyboard.press("Escape"); + await expect(page.getByTestId("filters-panel")).toHaveCount(0); + await expect(page.getByTestId("filters-trigger")).toBeVisible(); + }); + }); +}); diff --git a/export/e2e/tag-chips.spec.ts b/export/e2e/tag-chips.spec.ts @@ -1,6 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; -import { installRoutes, installTagRoutes, showAll } from "./helpers"; +import { installRoutes, installTagRoutes, openFilters, showAll } from "./helpers"; import { + tagsJson, CHANNEL_SLUG, TAG_COLLAB, TAG_TOPIC, @@ -90,7 +91,7 @@ test.describe("curated tag chips", () => { await expect(chipRow(page)).toBeVisible(); // The group label comes from the document, not from anything in the - // code: "Eva: Collab · Discussed". + // code: "<group label>: Collab · Discussed". const group = page.locator('[data-testid="tag-chip-group"][data-group-id="eva"]'); await expect(group).toContainText("Eva"); @@ -371,6 +372,194 @@ test.describe("curated tag chips", () => { }); }); + // `secondary` (CuratedTagDef.secondary): the operator's way to keep a tag + // published and filterable while it reads as a refinement rather than as + // one of the site's main filters. The chips move under "More filters". + test.describe("secondary tags", () => { + // The shared fixture's two tags, relabelled into a neutral group, with the + // given ids marked secondary. + async function installSecondary(page: Page, secondaryIds: string[]) { + await page.route("**/tags.json", async (route) => { + const doc = tagsJson(); + doc.tags = doc.tags.map((t) => ({ + ...t, + group: "case", + groupLabel: "Case", + ...(secondaryIds.includes(t.id) ? { secondary: true as const } : {}), + })); + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(doc), + }); + }); + } + const more = (page: Page) => page.getByTestId("tag-more"); + const moreSummary = (page: Page) => page.getByTestId("tag-more-summary"); + + test("all secondary: no main Tags row, a closed More filters that still filters", async ({ + page, + }, testInfo) => { + await installRoutes(page); + await installSecondary(page, [TAG_COLLAB, TAG_TOPIC]); + await page.goto("/"); + await waitForHydration(page); + await openFilters(page); + + await expect(chipRow(page)).toHaveCount(0); + await expect(more(page)).toBeVisible(); + await expect(more(page)).not.toHaveAttribute("open"); + await expect(moreSummary(page)).toHaveText("More filters"); + await expect(chip(page, TAG_COLLAB)).toBeHidden(); + await page.getByTestId("filters-panel").screenshot({ + path: testInfo.outputPath("tag-more-closed-desktop.png"), + }); + + await moreSummary(page).click(); + await expect(more(page)).toHaveAttribute("open", ""); + // The group label is inside, beside its chips. + await expect(tagGroup(page, "case")).toContainText("Case"); + // No second "N selected" line inside: the summary says it. + await expect(more(page)).not.toContainText("Tags:"); + await chip(page, TAG_TOPIC).click(); + await expect(moreSummary(page)).toHaveText("More filters · 1 selected"); + await chip(page, TAG_COLLAB).click(); + await expect(moreSummary(page)).toHaveText( + "More filters · 2 selected, any of them", + ); + await chip(page, TAG_COLLAB).click(); + await page.getByTestId("filters-panel").screenshot({ + path: testInfo.outputPath("tag-more-open-desktop.png"), + }); + await apply(page); + await expect(card(page, VIDEO_CHAT_LARGE)).toBeVisible(); + await expect(card(page, VIDEO_TRANSCRIPT_ONLY)).toHaveCount(0); + // The same `tg` link as a main-row chip makes. + await expect + .poll(() => new URL(page.url()).searchParams.getAll("tg")) + .toEqual([TAG_TOPIC]); + + // Clearing the selection from inside does not fold it shut. + await chip(page, TAG_TOPIC).click(); + await expect(more(page)).toHaveAttribute("open", ""); + await expect(moreSummary(page)).toHaveText("More filters"); + }); + + test("a tg link opens More filters with its chip lit; the reader can close it", async ({ + page, + }) => { + await installRoutes(page); + await installSecondary(page, [TAG_COLLAB, TAG_TOPIC]); + await page.goto(`/?tg=${TAG_TOPIC}`); + await waitForHydration(page); + await openFilters(page); + + await expect(more(page)).toHaveAttribute("open", ""); + await expect(chip(page, TAG_TOPIC)).toHaveAttribute("aria-pressed", "true"); + await expect(card(page, VIDEO_TRANSCRIPT_ONLY)).toHaveCount(0); + + // Closed by hand, it stays closed — and still admits what it is doing. + await moreSummary(page).click(); + await expect(more(page)).not.toHaveAttribute("open"); + await expect(moreSummary(page)).toContainText("1 selected"); + }); + + test("a saved profile with a secondary tag opens More filters with it lit", async ({ + page, + }) => { + await installRoutes(page); + await installSecondary(page, [TAG_COLLAB, TAG_TOPIC]); + // A window to seed localStorage on, then a reload so hydration reads + // it — the same route filter-profile-persistence.spec.ts takes. + await page.goto("/"); + await waitForHydration(page); + await page.evaluate((tag) => { + const snap = { channels: { included: [], excluded: [] }, tg: [tag] }; + window.localStorage.setItem( + "ytdlp-tb:export-filters", + JSON.stringify({ + v: 1, + working: snap, + profiles: { p1: snap }, + activeProfileName: "p1", + }), + ); + }, TAG_TOPIC); + await page.reload(); + await waitForHydration(page); + await openFilters(page); + + await expect(more(page)).toHaveAttribute("open", ""); + await expect(chip(page, TAG_TOPIC)).toHaveAttribute("aria-pressed", "true"); + await expect(moreSummary(page)).toHaveText("More filters · 1 selected"); + }); + + test("mixed: the main row keeps its own tags, More filters the rest", async ({ + page, + }) => { + await installRoutes(page); + await installSecondary(page, [TAG_TOPIC]); + await page.goto("/"); + await waitForHydration(page); + await openFilters(page); + + await expect(chipRow(page).getByTestId("tag-chip")).toHaveCount(1); + await expect(chipRow(page)).toContainText("Collab"); + await expect(more(page)).not.toHaveAttribute("open"); + await expect(more(page).getByTestId("tag-chip")).toHaveCount(1); + // The ANY line is the main row's; the disclosure does not repeat it. + await moreSummary(page).click(); + await expect(more(page)).not.toContainText("Tags:"); + + // ORed across the two places. + await chip(page, TAG_COLLAB).click(); + await chip(page, TAG_TOPIC).click(); + await apply(page); + await expect(card(page, VIDEO_CHAT_SMALL)).toBeVisible(); + await expect(card(page, VIDEO_CHAT_LARGE)).toBeVisible(); + await expect(card(page, VIDEO_TRANSCRIPT_ONLY)).toHaveCount(0); + }); + + test("a site with no secondary tag has no More filters", async ({ page }) => { + await installRoutes(page); + await installTagRoutes(page); + await page.goto("/"); + await waitForHydration(page); + await openFilters(page); + await expect(chipRow(page)).toBeVisible(); + await expect(more(page)).toHaveCount(0); + }); + + test.describe("on a phone", () => { + test.use({ viewport: { width: 390, height: 844 } }); + + test("More filters is one line in the sheet, and opens", async ({ + page, + }, testInfo) => { + await installRoutes(page); + await installSecondary(page, [TAG_COLLAB, TAG_TOPIC]); + await page.goto("/"); + await waitForHydration(page); + await page.getByTestId("filters-trigger").click(); + + await more(page).scrollIntoViewIfNeeded(); + const box = await moreSummary(page).boundingBox(); + expect(box).not.toBeNull(); + expect(box!.width).toBeLessThanOrEqual(390); + expect(box!.height).toBeLessThan(40); + await page.screenshot({ + path: testInfo.outputPath("tag-more-closed-phone.png"), + }); + await moreSummary(page).click(); + await expect(chip(page, TAG_COLLAB)).toBeVisible(); + await more(page).scrollIntoViewIfNeeded(); + await page.screenshot({ + path: testInfo.outputPath("tag-more-open-phone.png"), + }); + }); + }); + }); + test.describe("on a site that publishes none", () => { test("there is no chip row at all", async ({ page }) => { // installRoutes alone: /tags.json 404s, which is the real default for a diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -337,8 +337,12 @@ untagged corpus** because an empty derivation leaves each summary byte-identical re-read 76k video directories to reach exactly the same state. **The site layer is presentation-only.** `sites/<id>/tags.json` relabels, recolours, -reorders, hides and may add site-only tags; it can never delete a corpus rule or an -assignment. A site-layer RULE is accepted by `mergeTagDefs` (harmless on a published def) +reorders, hides, moves a tag under the viewer's "More filters" (`secondary`) and may add +site-only tags; it can never delete a corpus rule or an assignment. At the site layer an +explicit `hidden: false` / `secondary: false` is KEPT (it overrides a corpus `true`); at the +corpus layer only `true` is stored. One row is changed by the `tags` op `present` +(`patchSiteOverlay`, `editor/app/tags/actions.ts` `presentSiteTagAction`), which refuses a +site tags file that does not parse rather than write over it. A site-layer RULE is accepted by `mergeTagDefs` (harmless on a published def) but **never tags a record**: rules are evaluated once at index time over records SHARED by every site carrying the channel, so there is no per-site record for a per-site hit to live in. Rules bind only from `transcripts/tags.json` — promote one there to make it fire. The @@ -5410,7 +5414,8 @@ Three branches off `4ac8ceda`, merged in order: `1a011d96` alone, then `tags/rul `curatedTagsStore.ts:9-17`. - Why, restated because it is the kind of rule people "fix": a record is shared by every site that carries its channel, so a site-layer rule could only tag records the OTHER sites also - publish. The site layer is presentation — `label/groupLabel/color/order/hidden`. + publish. The site layer is presentation — `label/groupLabel/color/order/hidden/secondary` + (`SITE_OVERLAY_FIELDS`, `common/lib/curatedTags.ts`). ### `--wait` polls a log route, and a dropped poll is not a failure diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -133,6 +133,7 @@ // pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}' // (a define is the WHOLE def: rules, and `sites` — the site ids the // tag exists on, absent = every site — included) +// pnpm ops tags --json '{"op":"present","site":"demo-site","tag":{"id":"case-collab","secondary":true}}' // pnpm ops tag-videos --file ids.json // pnpm ops persist-videos --file list.json --wait // pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}' @@ -1585,7 +1586,13 @@ export function usage() { 'tags edits the curated-tag vocabulary through its one writer: {"op":', ' "define", "tag": {...}} (the WHOLE definition: id, label, rules and', ' "sites", the sites it exists on, absent = every site) or {"op":', - ' "remove", "tag": "<id>"}. `get tags [<id>]` reads it.', + ' "remove", "tag": "<id>"}, or how ONE site shows a corpus tag: {"op":', + ' "present", "site", "tag": {"id", "label"?, "groupLabel"?, "color"?,', + ' "order"?, "hidden"?, "secondary"?}} — merged into that row of', + ' sites/<site>/tags.json, other fields kept, null clears one (the site', + ' inherits it again). "secondary": true offers the tag under the site\'s', + ' "More filters" instead of the main Tags row; false keeps it in the main', + ' row over a corpus true. `get tags [<id>]` reads the vocabulary.', "", 'tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos', ' in ONE write: {"tag", "op": "add" | "remove" | "suppress" | "unsuppress",',