wrolpi/app/src/components/Docs.js

630 lines
23 KiB
JavaScript
Raw Normal View History

ui: a PDF asks before it lights up a night-adapted eye (#654) * ui: a PDF asks before it lights up a night-adapted eye Night and amber pass media through an SVG color matrix so nothing a user opens costs them their dark adaptation. It reaches everything drawn in our own document -- images, video, canvases, and same-origin iframes like the EPUB viewer. It does not reach a PDF, and the miss is not subtle. Chrome draws PDFs in its own out-of-process viewer, which the compositor paints outside the parent's filter: the computed style on the iframe really does say `filter: url(#wrolpi-night-red)` and the page still arrives in full color. Measured in night mode on a device, a PDF covered 55% of the doc page in non-red pixels -- a full-brightness photograph of a blue sky -- while the chrome around it was correctly red. The preview modal measured 39.8%. Tinting from outside was tried and does not work. A red `mix-blend-mode: multiply` overlay above the iframe cannot see the plugin's pixels, so it stops blending and paints flat opaque red: zero non-red pixels by measurement, document entirely obliterated. So the PDF is withheld and the reader chooses. Nothing renders until they do; hiding it with CSS would still load and paint the viewer, which is the flash being avoided. Gated on whether the theme is CURRENTLY filtering, not on its name. A reader who turns night's filter off has said they do not want this, and amber with its filter on has the same unreachable PDF and does. Only PDFs: text and the EPUB viewer are documents of our own and tint correctly, so gating them would hide something for no reason. The gallery paragraph claiming the matrix remaps PDFs is corrected -- it was the one place we told users something this measurement disproves. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * review: the reveal that outlived its document, and a test that proved nothing Five review comments, all correct. The bug: MediaGate was not keyed in FilePreview. The effect that rebuilds a preview sets the modal to null and then to the new content in one pass, so React 18 batches both and reconciles instead of unmounting -- the fiber survives, and a reader who revealed PDF A would get PDF B in full color with no prompt. Keyed by url, which is what Docs already did with activePath. The test named "re-gates when filtering is turned back on" never revealed anything first, so it went from gated=false to gated=true with `revealed` already false. That path never reaches the reset effect: the test passed with the effect deleted. It now clicks Show first, and fails without the effect. The hide control moved above the media. A preview fills `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button row, so a control after it lands below the fold of a full-screen modal -- leaving the reader who just lit up their eyes scrolling to find the way back. Docs' embed -- the surface measured at 55% non-red -- had no contract test where FilePreview had one. It has one now, asserting the gate wraps the iframe, keys per document, and reads mediaFilterEnabled rather than the theme's name. Gallery copy said "night and amber withhold it"; amber's filter is off unless asked for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 18:57:01 -06:00
import React, {useContext, useEffect, useState} from 'react';
import {Link, Route, Routes, useLocation, useNavigate, useParams, useSearchParams} from "react-router";
2026-05-03 18:50:22 -06:00
import {deleteFileGroups, getDocStatistics, tagFileGroup, untagFileGroup} from "../api";
ui: a PDF asks before it lights up a night-adapted eye (#654) * ui: a PDF asks before it lights up a night-adapted eye Night and amber pass media through an SVG color matrix so nothing a user opens costs them their dark adaptation. It reaches everything drawn in our own document -- images, video, canvases, and same-origin iframes like the EPUB viewer. It does not reach a PDF, and the miss is not subtle. Chrome draws PDFs in its own out-of-process viewer, which the compositor paints outside the parent's filter: the computed style on the iframe really does say `filter: url(#wrolpi-night-red)` and the page still arrives in full color. Measured in night mode on a device, a PDF covered 55% of the doc page in non-red pixels -- a full-brightness photograph of a blue sky -- while the chrome around it was correctly red. The preview modal measured 39.8%. Tinting from outside was tried and does not work. A red `mix-blend-mode: multiply` overlay above the iframe cannot see the plugin's pixels, so it stops blending and paints flat opaque red: zero non-red pixels by measurement, document entirely obliterated. So the PDF is withheld and the reader chooses. Nothing renders until they do; hiding it with CSS would still load and paint the viewer, which is the flash being avoided. Gated on whether the theme is CURRENTLY filtering, not on its name. A reader who turns night's filter off has said they do not want this, and amber with its filter on has the same unreachable PDF and does. Only PDFs: text and the EPUB viewer are documents of our own and tint correctly, so gating them would hide something for no reason. The gallery paragraph claiming the matrix remaps PDFs is corrected -- it was the one place we told users something this measurement disproves. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * review: the reveal that outlived its document, and a test that proved nothing Five review comments, all correct. The bug: MediaGate was not keyed in FilePreview. The effect that rebuilds a preview sets the modal to null and then to the new content in one pass, so React 18 batches both and reconciles instead of unmounting -- the fiber survives, and a reader who revealed PDF A would get PDF B in full color with no prompt. Keyed by url, which is what Docs already did with activePath. The test named "re-gates when filtering is turned back on" never revealed anything first, so it went from gated=false to gated=true with `revealed` already false. That path never reaches the reset effect: the test passed with the effect deleted. It now clicks Show first, and fails without the effect. The hide control moved above the media. A preview fills `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button row, so a control after it lands below the fold of a full-screen modal -- leaving the reader who just lit up their eyes scrolling to find the way back. Docs' embed -- the surface measured at 55% non-red -- had no contract test where FilePreview had one. It has one now, asserting the gate wraps the iframe, keys per document, and reads mediaFilterEnabled rather than the theme's name. Gallery copy said "night and amber withhold it"; amber's filter is off unless asked for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 18:57:01 -06:00
import {Media, ThemeContext} from "../contexts/contexts";
import {
APIButton,
BackButton,
DirectoryLink,
encodeMediaPath,
ErrorMessage,
humanFileSize,
isoDatetimeToAgoPopup,
PageContainer,
PreviewPath,
SearchInput,
TabLinks,
toLocaleString,
useTitle
} from "./Common";
ui: a PDF asks before it lights up a night-adapted eye (#654) * ui: a PDF asks before it lights up a night-adapted eye Night and amber pass media through an SVG color matrix so nothing a user opens costs them their dark adaptation. It reaches everything drawn in our own document -- images, video, canvases, and same-origin iframes like the EPUB viewer. It does not reach a PDF, and the miss is not subtle. Chrome draws PDFs in its own out-of-process viewer, which the compositor paints outside the parent's filter: the computed style on the iframe really does say `filter: url(#wrolpi-night-red)` and the page still arrives in full color. Measured in night mode on a device, a PDF covered 55% of the doc page in non-red pixels -- a full-brightness photograph of a blue sky -- while the chrome around it was correctly red. The preview modal measured 39.8%. Tinting from outside was tried and does not work. A red `mix-blend-mode: multiply` overlay above the iframe cannot see the plugin's pixels, so it stops blending and paints flat opaque red: zero non-red pixels by measurement, document entirely obliterated. So the PDF is withheld and the reader chooses. Nothing renders until they do; hiding it with CSS would still load and paint the viewer, which is the flash being avoided. Gated on whether the theme is CURRENTLY filtering, not on its name. A reader who turns night's filter off has said they do not want this, and amber with its filter on has the same unreachable PDF and does. Only PDFs: text and the EPUB viewer are documents of our own and tint correctly, so gating them would hide something for no reason. The gallery paragraph claiming the matrix remaps PDFs is corrected -- it was the one place we told users something this measurement disproves. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * review: the reveal that outlived its document, and a test that proved nothing Five review comments, all correct. The bug: MediaGate was not keyed in FilePreview. The effect that rebuilds a preview sets the modal to null and then to the new content in one pass, so React 18 batches both and reconciles instead of unmounting -- the fiber survives, and a reader who revealed PDF A would get PDF B in full color with no prompt. Keyed by url, which is what Docs already did with activePath. The test named "re-gates when filtering is turned back on" never revealed anything first, so it went from gated=false to gated=true with `revealed` already false. That path never reaches the reset effect: the test passed with the effect deleted. It now clicks Show first, and fails without the effect. The hide control moved above the media. A preview fills `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button row, so a control after it lands below the fold of a full-screen modal -- leaving the reader who just lit up their eyes scrolling to find the way back. Docs' embed -- the surface measured at 55% non-red -- had no contract test where FilePreview had one. It has one now, asserting the gate wraps the iframe, keys per document, and reads mediaFilterEnabled rather than the theme's name. Gallery copy said "night and amber withhold it"; amber's filter is off unless asked for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 18:57:01 -06:00
import {
Button,
ButtonGroup,
Group,
Header,
Loading,
MediaGate,
Panel,
Statistic,
StatisticGroup,
Tabs
} from "./ui";
import {BulkTagModal} from "./BulkTagModal";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
Search: fast ABC mode by default, opt-in deep search The file_group.textsearch tsvector indexes all four text columns; d_text (captions, document text, zip contents) is ~90% of the data, making ts_rank searches take seconds on large libraries. Add a textsearch_abc generated column (title/author/description only, ~8x smaller) and default all searches to it, with deep=true opting into the full column. Database: - Migration adds the generated column and a GIN index (rewrites the table; a few minutes on large libraries). Backend: - FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and DocSearchRequest accept `deep`; each search function picks the column. - /api/search_file_estimates returns both counts in one index-bound query (COUNT FILTER on the abc subset): `file_groups` (fast) and `file_groups_deep`. UI (one coherent story across the count surfaces): - The typing dropdown always suggests the deep count (what is findable). - The tab badge shows the active mode's count so it matches the result list. - The gap is reconciled by a hint offering deep search: count-aware on the global search ("No results in fast search. N results available in deep search." / "N more results available..."), generic on the module pages (no deep estimate there). The hint resets pagination. - "Search Depth" toggle in the search filter modals, persisted as ?deep=true. Tests that relied on d_text matches now pass deep=True, with fast-mode assertions alongside. Also skip flaky test_download_channel on CircleCI. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
import {DeepSearchHint, docMimetypeFilterOptions, FilesView, SearchControlBar} from "./Files";
import {useAuthors, useDoc, useOneQuery, useSearchDocs, useSubjects} from "../hooks/customHooks";
import {TagsSelector} from "../Tags";
ui: keep the unmigrated pages' notifications working Greptile P1, and a real one: App.js migrated and took `<SemanticToastContainer/>` with it, but seven pages -- Archive, Channels, Docs, FilePreview, Playlists, Zim, ControllerPage -- still raised their toasts through the Semantic library. With no container mounted those notifications went nowhere. No error, no warning; a user deletes a document and is simply never told whether it worked. Fixed by pointing those seven at the library's `toast`, which takes the same options, rather than by mounting a second toast system. Nothing calls the Semantic toast library now, so a test asserts that at zero: a file that goes back to it would raise notifications that silently never appear, and that is not something a reviewer would spot. Also reverted Archive.js to its last good state. An interrupted agent had migrated part of it -- Panel, Tabs, and Mantine's Grid.Col -- while the rest of the file still used Semantic's Segment, Tab and Grid.Row, so a single `Grid` identifier had to be two different components at once. A half-migrated 1400-line file is worse than an unmigrated one; it goes back on the list and gets done in one piece. That break was masked: react-scripts caches ESLint results per file, so the earlier build passed while Archive.js sat on a stale pass. Editing its import invalidated the entry and the errors appeared. Verified with the cache cleared this time, which is the only way that check means anything after a wide change.
2026-07-30 12:31:40 -06:00
import {toast} from "./ui";
import {CollectionTable} from "./collections/CollectionTable";
Add ordered collections (playlists): polymorphic items + item API (#475) * Add Playlists: ordered, mixed-type collections A playlist (Collection kind='playlist') is a manually-curated, ordered list that mixes item types. Squash of the playlists feature branch (24 commits). Data model & API: - CollectionItem is polymorphic via item_kind: 'file' (FileGroup), 'zim' (zim_id + zim_entry), or 'url' (link to anything the WROLPi browser opens, e.g. /map?lat=&lon=&z=). CHECK constraint enforces exactly one kind; per-kind unique constraints; migration a7b1c2d3e4f5. - Endpoints: create playlist; add/remove/reorder items (idempotent adds: 201 new, 200 existing); GET returns the ordered items. All mutations wrol_mode_check'd. Config (source of truth): - playlists.yaml (PlaylistsConfig) stores each playlist's metadata AND ordered items (file by relative path, zim by path+entry, url inline); round-trips a DB wipe. Supports backup import (DB_CONFIG_FILE_NAMES). - The redundant generic CollectionsConfig (collections.yaml) is deleted: channels/domains own their configs, authors/subjects are re-derived. On-disk sync (sync_playlists_directory switch): - Each playlist materializes into the configurable Playlists Directory (playlists_destination, Settings UI input, excluded from indexing) with position-prefixed entries: NNNN_<file> hard links (copy fallback across filesystems) and NNNN_<title>.html stubs for zim/url items. - Tagged playlists are namespaced like channels: <playlists>/<tag>/<name>; a tag change moves the directory and prunes the empty old tag dir. - Deletion safety: managed files are only removed when they are our marked stubs or still have another hard link (st_nlink > 1) -- never a last copy. Stray loose files at the playlists root are removed; stub URLs are scheme-allowlisted (no javascript:/data:). Frontend: - /playlists list page (CollectionTable, name filter, New Playlist modal, Tag column) between Files and Zim in the nav. - View-only detail page (Name link) and edit page (Edit button): themed table with model icons/colors + poster thumbnails, items link to their model page (video/archive/doc) or preview, up/down reorder, remove, add-URL form, single-tag selector; all editing disabled in WROL Mode. - Reusable green "Add to Playlist" button on Video/Archive/Doc detail pages, the FilePreview toolbar, Zim search results, and Map pins (added as a /map URL item with a map-marker icon). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Playlist edit page parity: rename, custom directory, tag modal move suggestion Match the ChannelEditPage/DomainEditPage UX on the playlist edit page: Back/View buttons, an edit form (name, description, directory), and the shared CollectionTagModal with the violet "Tag" button. The tag modal now suggests moving the playlist to its managed tag location (playlists/<tag>/<name>); accepting the suggestion stores directory=None so the sync keeps auto-managing the location. Tag buttons on the Channel and Domain edit pages are now violet to match. Backend: update_collection learns rename (with per-kind validation and duplicate checks) and playlist custom directories (cleanup of the abandoned directory, config round-trip, commit-before-switch to avoid the background sync racing pre-commit state). tag_collection's duplicated untag/tag branches are merged, and the per-kind config-save dispatch is consolidated into _activate_config_save(). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Deduplicate Collection error handling and Tag creation Delete the duplicate UnknownCollection in wrolpi/collections/errors.py and re-export the canonical one from wrolpi/errors.py, which carries status_code=NOT_FOUND (the local copy inherited 500). Replace the repeated query/raise pattern in reorganize.py with Collection.find_by_id. Add Tag.get_or_create_tag and use it for collection tagging; flush the new Tag before returning so callers can read .id immediately -- previously tagging a collection with a brand-new tag name set tag_id=None. Regression test included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:37:34 -06:00
import {AddToPlaylistButton} from "./AddToPlaylist";
import {CbzViewer} from "./CbzViewer";
import _ from "lodash";
function DocsPage() {
useTitle('Documents');
const searchInputRef = React.useRef();
const {
docs,
totalPages,
activePage,
setPage,
searchStr,
setSearchStr,
author,
subject,
fetchDocs,
} = useSearchDocs();
const [selectedDocs, setSelectedDocs] = useState([]);
const [bulkTagOpen, setBulkTagOpen] = useState(false);
const [taggedFileGroups, setTaggedFileGroups] = useState(null);
const onSelect = (path, checked) => {
if (checked && path) {
setSelectedDocs([...selectedDocs, path]);
} else if (path) {
setSelectedDocs(selectedDocs.filter(i => i !== path));
}
}
const onDelete = async (force = false) => {
2026-05-03 18:50:22 -06:00
const fileGroupIds = docs.filter(i => selectedDocs.indexOf(i['primary_path']) >= 0).map(i => i['id']);
const result = await deleteFileGroups(fileGroupIds, force);
if (result && result.tagged) {
setTaggedFileGroups(result.file_groups);
return;
}
await fetchDocs();
setSelectedDocs([]);
}
const invertSelection = () => {
const newSelectedDocs = docs.map(doc => doc['key']).filter(i => selectedDocs.indexOf(i) < 0);
setSelectedDocs(newSelectedDocs);
}
const clearSelection = (e) => {
if (e) e.preventDefault();
setSelectedDocs([]);
}
const onBulkTagComplete = async () => {
await fetchDocs();
setSelectedDocs([]);
}
const selectElm = <div className='wrolpi-button-row' style={{marginTop: '0.5em'}}>
<Button color='violet' disabled={_.isEmpty(selectedDocs)}
onClick={() => setBulkTagOpen(true)}>Tag</Button>
<APIButton
role='danger'
disabled={_.isEmpty(selectedDocs)}
confirmButton='Delete'
confirmContent='Are you sure you want to delete these documents? This cannot be undone.'
onClick={() => onDelete(false)}
obeyWROLMode={true}
>Delete</APIButton>
<Button role='cancel' onClick={invertSelection} disabled={_.isEmpty(docs)}>Invert</Button>
<Button role='cancel' onClick={clearSelection}
disabled={_.isEmpty(docs) || _.isEmpty(selectedDocs)}>Clear</Button>
<BulkTagModal
open={bulkTagOpen}
onClose={() => setBulkTagOpen(false)}
paths={selectedDocs}
onComplete={onBulkTagComplete}
/>
</div>;
let docOrders = [
{value: 'published_datetime', text: 'Published Date', short: 'P.Date'},
{value: 'size', text: 'Size'},
{value: 'title', text: 'Title'},
];
if (searchStr) {
docOrders = [{value: 'rank', text: 'Rank'}, ...docOrders];
}
Consolidate search options into a single Filter modal (#497) * Consolidate search options into a single Filter modal Reworks the file-search UI on the Dashboard, Videos, Archives, and Docs pages. The crowded row of controls (sort, tags, limit, file-type filter, date selector) is replaced with a single "Filter" button that opens one comprehensive modal. - Add SearchFilterModal + SearchFilterButton (violet + count badge when active). Sections (Sort, File Type, Tags, Results Per Page, Published Date) are shown per-page via props; layout uses a Semantic Grid. - Selections are drafted locally and applied in a single updateQuery only on close/Done, so the search isn't re-run on every field change. - Results Per Page and Sort use buttons (fewer clicks, no clipped dropdown). - Extract shared SearchControlBar (view toggle + input + Filter) for the three results pages; move the global-search view toggle onto the tab row. - Rework the Dashboard search line into one adaptive flex row; clear button only shows when there's an active search. - Remove now-dead FilesView limit/tag returns and SearchLimitDropdown. * Address review: reset limit on Clear All; use replace over replaceAll - handleClearAll now resets Results Per Page to the default page size (DEFAULT_SEARCH_LIMIT = 24) so "Clear All" actually clears every setting. - Replace start-anchored replaceAll(/^-/g) with replace(/^-/) for the sort key. - Add a test covering the Clear All limit reset. * Remove now-unused Media import from Files.js The FilesSearchView refactor dropped the last <Media> usage in this file, leaving an unused import (a build warning). Remove it. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:49:15 -06:00
const {body, paginator, viewButton} = FilesView(
{
files: docs,
activePage: activePage,
totalPages: totalPages,
selectElem: selectElm,
selectedKeys: selectedDocs,
onSelect: onSelect,
setPage: setPage,
},
);
return <>
{author && <Header as='h1'>Author: {author}</Header>}
{subject && <Header as='h1'>Subject: {subject}</Header>}
Consolidate search options into a single Filter modal (#497) * Consolidate search options into a single Filter modal Reworks the file-search UI on the Dashboard, Videos, Archives, and Docs pages. The crowded row of controls (sort, tags, limit, file-type filter, date selector) is replaced with a single "Filter" button that opens one comprehensive modal. - Add SearchFilterModal + SearchFilterButton (violet + count badge when active). Sections (Sort, File Type, Tags, Results Per Page, Published Date) are shown per-page via props; layout uses a Semantic Grid. - Selections are drafted locally and applied in a single updateQuery only on close/Done, so the search isn't re-run on every field change. - Results Per Page and Sort use buttons (fewer clicks, no clipped dropdown). - Extract shared SearchControlBar (view toggle + input + Filter) for the three results pages; move the global-search view toggle onto the tab row. - Rework the Dashboard search line into one adaptive flex row; clear button only shows when there's an active search. - Remove now-dead FilesView limit/tag returns and SearchLimitDropdown. * Address review: reset limit on Clear All; use replace over replaceAll - handleClearAll now resets Results Per Page to the default page size (DEFAULT_SEARCH_LIMIT = 24) so "Clear All" actually clears every setting. - Replace start-anchored replaceAll(/^-/g) with replace(/^-/) for the sort key. - Add a test covering the Clear All limit reset. * Remove now-unused Media import from Files.js The FilesSearchView refactor dropped the last <Media> usage in this file, leaving an unused import (a build warning). Remove it. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:49:15 -06:00
<SearchControlBar
searchStr={searchStr}
setSearchStr={setSearchStr}
placeholder='Search Documents...'
inputRef={searchInputRef}
viewButton={viewButton}
sorts={docOrders}
fileFilterOptions={docMimetypeFilterOptions}
Search: fast ABC mode by default, opt-in deep search The file_group.textsearch tsvector indexes all four text columns; d_text (captions, document text, zip contents) is ~90% of the data, making ts_rank searches take seconds on large libraries. Add a textsearch_abc generated column (title/author/description only, ~8x smaller) and default all searches to it, with deep=true opting into the full column. Database: - Migration adds the generated column and a GIN index (rewrites the table; a few minutes on large libraries). Backend: - FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and DocSearchRequest accept `deep`; each search function picks the column. - /api/search_file_estimates returns both counts in one index-bound query (COUNT FILTER on the abc subset): `file_groups` (fast) and `file_groups_deep`. UI (one coherent story across the count surfaces): - The typing dropdown always suggests the deep count (what is findable). - The tab badge shows the active mode's count so it matches the result list. - The gap is reconciled by a hint offering deep search: count-aware on the global search ("No results in fast search. N results available in deep search." / "N more results available..."), generic on the module pages (no deep estimate there). The hint resets pagination. - "Search Depth" toggle in the search filter modals, persisted as ?deep=true. Tests that relied on d_text matches now pass deep=True, with fast-mode assertions alongside. Also skip flaky test_download_channel on CircleCI. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
showDeep={true}
Consolidate search options into a single Filter modal (#497) * Consolidate search options into a single Filter modal Reworks the file-search UI on the Dashboard, Videos, Archives, and Docs pages. The crowded row of controls (sort, tags, limit, file-type filter, date selector) is replaced with a single "Filter" button that opens one comprehensive modal. - Add SearchFilterModal + SearchFilterButton (violet + count badge when active). Sections (Sort, File Type, Tags, Results Per Page, Published Date) are shown per-page via props; layout uses a Semantic Grid. - Selections are drafted locally and applied in a single updateQuery only on close/Done, so the search isn't re-run on every field change. - Results Per Page and Sort use buttons (fewer clicks, no clipped dropdown). - Extract shared SearchControlBar (view toggle + input + Filter) for the three results pages; move the global-search view toggle onto the tab row. - Rework the Dashboard search line into one adaptive flex row; clear button only shows when there's an active search. - Remove now-dead FilesView limit/tag returns and SearchLimitDropdown. * Address review: reset limit on Clear All; use replace over replaceAll - handleClearAll now resets Results Per Page to the default page size (DEFAULT_SEARCH_LIMIT = 24) so "Clear All" actually clears every setting. - Replace start-anchored replaceAll(/^-/g) with replace(/^-/) for the sort key. - Add a test covering the Clear All limit reset. * Remove now-unused Media import from Files.js The FilesSearchView refactor dropped the last <Media> usage in this file, leaving an unused import (a build warning). Remove it. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:49:15 -06:00
/>
{body}
Search: fast ABC mode by default, opt-in deep search The file_group.textsearch tsvector indexes all four text columns; d_text (captions, document text, zip contents) is ~90% of the data, making ts_rank searches take seconds on large libraries. Add a textsearch_abc generated column (title/author/description only, ~8x smaller) and default all searches to it, with deep=true opting into the full column. Database: - Migration adds the generated column and a GIN index (rewrites the table; a few minutes on large libraries). Backend: - FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and DocSearchRequest accept `deep`; each search function picks the column. - /api/search_file_estimates returns both counts in one index-bound query (COUNT FILTER on the abc subset): `file_groups` (fast) and `file_groups_deep`. UI (one coherent story across the count surfaces): - The typing dropdown always suggests the deep count (what is findable). - The tab badge shows the active mode's count so it matches the result list. - The gap is reconciled by a hint offering deep search: count-aware on the global search ("No results in fast search. N results available in deep search." / "N more results available..."), generic on the module pages (no deep estimate there). The hint resets pagination. - "Search Depth" toggle in the search filter modals, persisted as ?deep=true. Tests that relied on d_text matches now pass deep=True, with fast-mode assertions alongside. Also skip flaky test_download_channel on CircleCI. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
<DeepSearchHint searchStr={searchStr} files={docs}/>
{paginator}
<TaggedDeleteConfirmModal
open={taggedFileGroups !== null}
taggedFileGroups={taggedFileGroups}
onCancel={() => setTaggedFileGroups(null)}
onConfirm={async () => {
setTaggedFileGroups(null);
await onDelete(true);
}}
/>
</>;
}
function DocPage() {
const {fileGroupId} = useParams();
const navigate = useNavigate();
ui: a PDF asks before it lights up a night-adapted eye (#654) * ui: a PDF asks before it lights up a night-adapted eye Night and amber pass media through an SVG color matrix so nothing a user opens costs them their dark adaptation. It reaches everything drawn in our own document -- images, video, canvases, and same-origin iframes like the EPUB viewer. It does not reach a PDF, and the miss is not subtle. Chrome draws PDFs in its own out-of-process viewer, which the compositor paints outside the parent's filter: the computed style on the iframe really does say `filter: url(#wrolpi-night-red)` and the page still arrives in full color. Measured in night mode on a device, a PDF covered 55% of the doc page in non-red pixels -- a full-brightness photograph of a blue sky -- while the chrome around it was correctly red. The preview modal measured 39.8%. Tinting from outside was tried and does not work. A red `mix-blend-mode: multiply` overlay above the iframe cannot see the plugin's pixels, so it stops blending and paints flat opaque red: zero non-red pixels by measurement, document entirely obliterated. So the PDF is withheld and the reader chooses. Nothing renders until they do; hiding it with CSS would still load and paint the viewer, which is the flash being avoided. Gated on whether the theme is CURRENTLY filtering, not on its name. A reader who turns night's filter off has said they do not want this, and amber with its filter on has the same unreachable PDF and does. Only PDFs: text and the EPUB viewer are documents of our own and tint correctly, so gating them would hide something for no reason. The gallery paragraph claiming the matrix remaps PDFs is corrected -- it was the one place we told users something this measurement disproves. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * review: the reveal that outlived its document, and a test that proved nothing Five review comments, all correct. The bug: MediaGate was not keyed in FilePreview. The effect that rebuilds a preview sets the modal to null and then to the new content in one pass, so React 18 batches both and reconciles instead of unmounting -- the fiber survives, and a reader who revealed PDF A would get PDF B in full color with no prompt. Keyed by url, which is what Docs already did with activePath. The test named "re-gates when filtering is turned back on" never revealed anything first, so it went from gated=false to gated=true with `revealed` already false. That path never reaches the reset effect: the test passed with the effect deleted. It now clicks Show first, and fails without the effect. The hide control moved above the media. A preview fills `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button row, so a control after it lands below the fold of a full-screen modal -- leaving the reader who just lit up their eyes scrolling to find the way back. Docs' embed -- the surface measured at 55% non-red -- had no contract test where FilePreview had one. It has one now, asserting the gate wraps the iframe, keys per document, and reads mediaFilterEnabled rather than the theme's name. Gallery copy said "night and amber withhold it"; amber's filter is off unless asked for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 18:57:01 -06:00
// Whether the theme is currently filtering media; a PDF is the one embed it cannot reach.
const {mediaFilterEnabled} = useContext(ThemeContext);
const {docFile, doc, fetchDoc} = useDoc(parseInt(fileGroupId));
const [searchParams] = useSearchParams();
const [taggedFileGroups, setTaggedFileGroups] = useState(null);
// Deep-link params: `loc` = EPUB spine index, `page` = PDF page, `q` = search term.
const locParam = searchParams.get('loc');
const pageParam = searchParams.get('page');
const qParam = searchParams.get('q');
const title = docFile ? (docFile.title || docFile.name) : null;
useTitle(title);
const [selectedFileIndex, setSelectedFileIndex] = useState(0);
if (docFile === null) {
return <Panel><Loading/></Panel>;
}
if (docFile === undefined) {
return <>
<Header as='h2'>Unknown document</Header>
<Header as='h4'>This document does not exist</Header>
</>;
}
const {data, size, directory} = docFile;
// Cover image.
const coverPath = data && data.cover_path ? data.cover_path : null;
const coverUrl = coverPath ? `/media/${encodeMediaPath(coverPath)}` : null;
// Filter files to those that can be viewed inline (EPUB, PDF, comic books).
const CBZ_EXTENSIONS = ['cbz', 'cbr', 'cbt', 'cb7'];
const isViewableMimetype = (mt) => {
if (!mt) return false;
if (mt.startsWith('application/epub')) return true;
if (mt === 'application/pdf') return true;
if (mt.includes('cbz') || mt.includes('cbr') || mt.includes('comicbook+zip') || mt.includes('comicbook-rar')) return true;
return false;
};
const viewableFiles = (docFile.files || [])
.filter(f => isViewableMimetype(f.mimetype) || CBZ_EXTENSIONS.includes((f.path || '').toLowerCase().split('.').pop()))
.sort((a, b) => {
if (String(a.path) === String(docFile.primary_path)) return -1;
if (String(b.path) === String(docFile.primary_path)) return 1;
return 0;
});
const selectedFile = viewableFiles[selectedFileIndex] || viewableFiles[0];
// Derive viewer state from the selected file (or fall back to primary).
const activePath = selectedFile ? selectedFile.path : docFile.primary_path;
const activeMimetype = selectedFile ? (selectedFile.mimetype || '') : (docFile.mimetype || '');
const activeExt = (String(activePath) || '').toLowerCase().split('.').pop();
const downloadUrl = activePath ? `/download/${encodeMediaPath(activePath)}` : null;
const isEpub = activeMimetype.startsWith('application/epub');
const isPdf = activeMimetype === 'application/pdf';
const isCbz = activeMimetype.includes('cbz') || activeMimetype.includes('cbr')
|| activeMimetype.includes('comicbook+zip') || activeMimetype.includes('comicbook-rar')
|| CBZ_EXTENSIONS.includes(activeExt);
// Build EPUB viewer URL, propagating any deep-link params through to epub.html.
let viewerUrl = null;
if (isEpub) {
const epubParams = new URLSearchParams();
epubParams.set('url', downloadUrl);
if (locParam) epubParams.set('loc', locParam);
if (qParam) epubParams.set('q', qParam);
viewerUrl = `/epub/epub.html?${epubParams.toString()}`;
}
const openUrl = viewerUrl || (activePath ? `/media/${encodeMediaPath(activePath)}` : null);
const canEmbed = isEpub || isPdf;
// PDFs use the browser's built-in viewer, which honors `#page=N` fragments.
const pdfSrc = isPdf && activePath
? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}`
: null;
const embedUrl = isEpub ? viewerUrl : pdfSrc;
const handleDelete = async (force = false) => {
if (doc && doc.id) {
2026-05-03 18:50:22 -06:00
const result = await deleteFileGroups([docFile.id], force);
if (result && result.tagged) {
setTaggedFileGroups(result.file_groups);
return;
}
toast({
type: 'success',
title: 'Document Deleted',
description: 'Document was successfully deleted.',
time: 2000,
});
navigate(-1);
}
};
const localAddTag = async (name) => {
await tagFileGroup(docFile, name);
await fetchDoc();
};
const localRemoveTag = async (name) => {
await untagFileGroup(docFile, name);
await fetchDoc();
};
const publishedDatetimeString = docFile.published_datetime
? isoDatetimeToAgoPopup(docFile.published_datetime, true)
: null;
// Format badge based on mimetype.
const formatLabel = (overrideMt) => {
const mt = overrideMt || activeMimetype;
if (mt.startsWith('application/epub')) return 'EPUB';
if (mt === 'application/x-mobipocket-ebook') return 'MOBI';
if (mt === 'application/pdf') return 'PDF';
if (mt.includes('wordprocessingml')) return 'DOCX';
if (mt === 'application/msword') return 'DOC';
if (mt.includes('opendocument.text')) return 'ODT';
if (mt.includes('cbz') || mt.includes('comicbook+zip')) return 'CBZ';
if (mt.includes('cbr') || mt.includes('comicbook-rar')) return 'CBR';
if (mt.includes('cbt')) return 'CBT';
if (mt.includes('cb7') || mt.includes('x-7z')) return 'CB7';
return mt.split('/').pop().toUpperCase();
};
// About tab.
const aboutTab = <>
{doc && doc.description && <>
<Header as='h3'>Description</Header>
<p>{doc.description}</p>
</>}
{doc && doc.publisher && <>
<Header as='h3'>Publisher</Header>
<p>{doc.publisher}</p>
</>}
{doc && doc.language && <>
<Header as='h3'>Language</Header>
<p>{doc.language}</p>
</>}
{doc && doc.subject && <>
<Header as='h3'>Subject</Header>
<p><Link to={`/docs?subject=${encodeURIComponent(doc.subject)}`}>{doc.subject}</Link></p>
</>}
{doc && doc.page_count && <>
<Header as='h3'>Page Count</Header>
<p>{doc.page_count}</p>
</>}
<Header as='h3'>Size</Header>
<p>{humanFileSize(size)}</p>
</>;
// Files tab.
const tableStyle = {width: '100%', borderCollapse: 'separate', borderSpacing: '0 0.7em'};
const labelStyle = {whiteSpace: 'nowrap', paddingRight: '1.5em', verticalAlign: 'top'};
const filesTab = <table style={tableStyle}>
<tbody>
{docFile.files && docFile.files.map((file, idx) =>
<tr key={idx}>
<td style={labelStyle}>
<strong>{file.path.split('.').pop().toUpperCase()}</strong>
</td>
<td>
<PreviewPath path={file.path} mimetype={file.mimetype} taggable={false}>
{file.path}
</PreviewPath>
{file.size && <span style={{marginLeft: '1em', color: 'var(--muted)'}}>
({humanFileSize(file.size)})
</span>}
</td>
</tr>
)}
<tr>
<td style={labelStyle}><strong>Directory</strong></td>
<td><DirectoryLink path={directory}/></td>
</tr>
</tbody>
</table>;
return <>
<div className='wrolpi-button-row'><BackButton/></div>
{isCbz && activePath && <CbzViewer path={activePath}/>}
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
ui: a PDF asks before it lights up a night-adapted eye (#654) * ui: a PDF asks before it lights up a night-adapted eye Night and amber pass media through an SVG color matrix so nothing a user opens costs them their dark adaptation. It reaches everything drawn in our own document -- images, video, canvases, and same-origin iframes like the EPUB viewer. It does not reach a PDF, and the miss is not subtle. Chrome draws PDFs in its own out-of-process viewer, which the compositor paints outside the parent's filter: the computed style on the iframe really does say `filter: url(#wrolpi-night-red)` and the page still arrives in full color. Measured in night mode on a device, a PDF covered 55% of the doc page in non-red pixels -- a full-brightness photograph of a blue sky -- while the chrome around it was correctly red. The preview modal measured 39.8%. Tinting from outside was tried and does not work. A red `mix-blend-mode: multiply` overlay above the iframe cannot see the plugin's pixels, so it stops blending and paints flat opaque red: zero non-red pixels by measurement, document entirely obliterated. So the PDF is withheld and the reader chooses. Nothing renders until they do; hiding it with CSS would still load and paint the viewer, which is the flash being avoided. Gated on whether the theme is CURRENTLY filtering, not on its name. A reader who turns night's filter off has said they do not want this, and amber with its filter on has the same unreachable PDF and does. Only PDFs: text and the EPUB viewer are documents of our own and tint correctly, so gating them would hide something for no reason. The gallery paragraph claiming the matrix remaps PDFs is corrected -- it was the one place we told users something this measurement disproves. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * review: the reveal that outlived its document, and a test that proved nothing Five review comments, all correct. The bug: MediaGate was not keyed in FilePreview. The effect that rebuilds a preview sets the modal to null and then to the new content in one pass, so React 18 batches both and reconciles instead of unmounting -- the fiber survives, and a reader who revealed PDF A would get PDF B in full color with no prompt. Keyed by url, which is what Docs already did with activePath. The test named "re-gates when filtering is turned back on" never revealed anything first, so it went from gated=false to gated=true with `revealed` already false. That path never reaches the reset effect: the test passed with the effect deleted. It now clicks Show first, and fails without the effect. The hide control moved above the media. A preview fills `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button row, so a control after it lands below the fold of a full-screen modal -- leaving the reader who just lit up their eyes scrolling to find the way back. Docs' embed -- the surface measured at 55% non-red -- had no contract test where FilePreview had one. It has one now, asserting the gate wraps the iframe, keys per document, and reads mediaFilterEnabled rather than the theme's name. Gallery copy said "night and amber withhold it"; amber's filter is off unless asked for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 18:57:01 -06:00
{/*
* Only the PDF is gated. The EPUB viewer is our own same-origin document, so the
* theme's media filter reaches it; Chrome's PDF viewer is composited out of
* process and cannot be tinted. Keyed on the path so selecting a different file
* re-gates rather than inheriting the last one's reveal.
*/}
<MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}>
<iframe
src={embedUrl}
title={docFile.title || docFile.name}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
</MediaGate>
</div>}
<Panel>
<Header as='h2'>{docFile.title || docFile.name}</Header>
{docFile.author && <Header as='h3'>
Author: <Link to={`/docs?author=${encodeURIComponent(docFile.author)}`}>{docFile.author}</Link>
</Header>}
<Group gap='xl' wrap='wrap'>
<Header as='h4'>Format: {formatLabel()}{doc && doc.page_count && ` (${doc.page_count} pages)`}</Header>
{publishedDatetimeString && <Header as='h4'>Published: {publishedDatetimeString}</Header>}
</Group>
{(() => {
const formatButtons = viewableFiles.length > 1 ? <ButtonGroup>
{viewableFiles.map((file, idx) => {
const mt = file.mimetype || '';
let btnColor;
if (mt.startsWith('application/epub')) btnColor = 'yellow';
else if (mt === 'application/pdf') btnColor = 'red';
const isSelected = idx === selectedFileIndex;
return <Button
key={file.path}
onClick={() => setSelectedFileIndex(idx)}
color={isSelected ? btnColor : undefined}
variant={isSelected ? 'filled' : 'default'}
>
{formatLabel(file.mimetype)}
</Button>;
})}
</ButtonGroup> : null;
const actionButtons = <>
{openUrl && <Button component='a' href={openUrl} target='_blank' rel='noreferrer'
color='violet' icon='expand arrows alternate'>
Open
</Button>}
{downloadUrl && <Button component='a' href={downloadUrl} icon='download'>
Download
</Button>}
<APIButton
role='danger'
confirmContent='Are you sure you want to delete this document? All files will be deleted.'
confirmButton='Delete'
onClick={() => handleDelete(false)}
obeyWROLMode={true}
>Delete</APIButton>
Add ordered collections (playlists): polymorphic items + item API (#475) * Add Playlists: ordered, mixed-type collections A playlist (Collection kind='playlist') is a manually-curated, ordered list that mixes item types. Squash of the playlists feature branch (24 commits). Data model & API: - CollectionItem is polymorphic via item_kind: 'file' (FileGroup), 'zim' (zim_id + zim_entry), or 'url' (link to anything the WROLPi browser opens, e.g. /map?lat=&lon=&z=). CHECK constraint enforces exactly one kind; per-kind unique constraints; migration a7b1c2d3e4f5. - Endpoints: create playlist; add/remove/reorder items (idempotent adds: 201 new, 200 existing); GET returns the ordered items. All mutations wrol_mode_check'd. Config (source of truth): - playlists.yaml (PlaylistsConfig) stores each playlist's metadata AND ordered items (file by relative path, zim by path+entry, url inline); round-trips a DB wipe. Supports backup import (DB_CONFIG_FILE_NAMES). - The redundant generic CollectionsConfig (collections.yaml) is deleted: channels/domains own their configs, authors/subjects are re-derived. On-disk sync (sync_playlists_directory switch): - Each playlist materializes into the configurable Playlists Directory (playlists_destination, Settings UI input, excluded from indexing) with position-prefixed entries: NNNN_<file> hard links (copy fallback across filesystems) and NNNN_<title>.html stubs for zim/url items. - Tagged playlists are namespaced like channels: <playlists>/<tag>/<name>; a tag change moves the directory and prunes the empty old tag dir. - Deletion safety: managed files are only removed when they are our marked stubs or still have another hard link (st_nlink > 1) -- never a last copy. Stray loose files at the playlists root are removed; stub URLs are scheme-allowlisted (no javascript:/data:). Frontend: - /playlists list page (CollectionTable, name filter, New Playlist modal, Tag column) between Files and Zim in the nav. - View-only detail page (Name link) and edit page (Edit button): themed table with model icons/colors + poster thumbnails, items link to their model page (video/archive/doc) or preview, up/down reorder, remove, add-URL form, single-tag selector; all editing disabled in WROL Mode. - Reusable green "Add to Playlist" button on Video/Archive/Doc detail pages, the FilePreview toolbar, Zim search results, and Map pins (added as a /map URL item with a map-marker icon). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Playlist edit page parity: rename, custom directory, tag modal move suggestion Match the ChannelEditPage/DomainEditPage UX on the playlist edit page: Back/View buttons, an edit form (name, description, directory), and the shared CollectionTagModal with the violet "Tag" button. The tag modal now suggests moving the playlist to its managed tag location (playlists/<tag>/<name>); accepting the suggestion stores directory=None so the sync keeps auto-managing the location. Tag buttons on the Channel and Domain edit pages are now violet to match. Backend: update_collection learns rename (with per-kind validation and duplicate checks) and playlist custom directories (cleanup of the abandoned directory, config round-trip, commit-before-switch to avoid the background sync racing pre-commit state). tag_collection's duplicated untag/tag branches are merged, and the per-kind config-save dispatch is consolidated into _activate_config_save(). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Deduplicate Collection error handling and Tag creation Delete the duplicate UnknownCollection in wrolpi/collections/errors.py and re-export the canonical one from wrolpi/errors.py, which carries status_code=NOT_FOUND (the local copy inherited 500). Replace the repeated query/raise pattern in reorganize.py with Collection.find_by_id. Add Tag.get_or_create_tag and use it for collection tagging; flush the new Tag before returning so callers can read .id immediately -- previously tagging a collection with a brand-new tag name set tag_id=None. Regression test included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:37:34 -06:00
<AddToPlaylistButton fileGroupId={docFile.id}/>
</>;
return <>
<Media at='mobile'>
{formatButtons && <div style={{marginTop: '1em'}}>{formatButtons}</div>}
ui: a row of buttons is spaced by the row The archive page's six actions shared edges, and Update sat lower than the rest. Both come from the same thing: Semantic's Button carried `margin: 0 .25em .25em 0`, so a page could list buttons as bare siblings and they arrived spaced -- and separated from the line below when the row wrapped. Nothing replaced that margin. Two of those six answered with `marginTop: 0.5em`, which is the wrong axis: a Button is `display: inline-flex; vertical-align: middle`, and `vertical-align` is measured on the MARGIN box, so half of any top margin shows up as the visible button dropping. It was covering the wrapped-row case in the only axis a margin can, and paying for it in the other one. `.wrolpi-button-row` is a flex row with a gap, so both axes are covered at once and no button needs a margin of its own -- the same rule as `.wrolpi-stack`, along the other axis. Applied to the five rows in the app that had no gap: the archive page, the shared collection edit form (which three pages hand action buttons to, and where nine buttons plus Cancel carried `margin-top: 1em` each while Save carried none), the doc page's two responsive branches, and the downloads table's edit/restart pair. `.action-button-spacing` goes with them; it was that same margin, on Cancel. Guarded four ways. ui-layout.cy.js measures that the row really spaces what it holds, wraps rather than overflows, centres its buttons against a taller item beside them, and counts a confirmed APIButton as one item rather than two -- that one returns a fragment holding a `<Confirm/>`, which would open a hole in the row if it did not portal. Common.test.js scans for the two ways this comes back: a button in a row stamping a vertical margin, and a row of buttons that is not a row. Neither throws, which is how the app got here. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:39:03 -06:00
<div className='wrolpi-button-row' style={{marginTop: '1em'}}>
{actionButtons}
</div>
</Media>
<Media greaterThanOrEqual='tablet'>
review: the scan the first two commits needed Five findings, all valid. The substantive one: the video page's Download / Delete / Refresh / AddToPlaylist strip was still four bare buttons in a `<p>` -- the direct analogue of the archive row this PR started with -- and the scan that was supposed to catch exactly that reported the app clean. It only ever saw `{fooButton}` interpolations, and most of the app writes its buttons out in place. Scanning for adjacent button ELEMENTS finds twelve more rows in the same state: reorder icons in the playlist and field-schema tables, both service tables on the controller page, its hotspot Save/QR pair and its Restart/Shutdown pair, the downloads footer, the one-time pad's Generate/Cheat Sheet, and the ration calculator's CSV/Print. All rowed. Two holes had to be closed before that scan could be trusted, because a scan that reports noise is worse than one with a stated limit: - `tagsIn` never captured the tag NAME, so `ROW_COMPONENTS.has(undefined)` was false for every tag and the list of components that lay out their own children -- Group, ButtonGroup, Modal.Actions -- silently accepted none of them. 56 false positives, every modal footer in the app among them. - A row whose style is a const (`style={seasonRowStyle}`) says nothing in its own attributes. Resolved now; the dates selector's seasons row is a four-column grid with a gap and was reported three times. Also from review: the row body is found by walking to the MATCHING close rather than the first `</div>`, which one nested div would have truncated -- and the collection form now nests one, so this was about to matter. Cancel and Save travel together in a row of their own pushed to the end; `margin-left: auto` on Save alone was right for a row that could not wrap, and would now drop Save onto a second line by itself with Cancel left among the action buttons. The doc page's comment no longer implies the picker's 1em separation was not a change. One more found on the way: the file browser's filter row is flex with no gap, and its collapse-all button carried `margin-left: 0.5em` for it. The gap is the container's. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 17:06:56 -06:00
{/*
* The format picker and the actions are one row, separated by its gap.
*
* This IS a change: the picker used to sit 1em from the actions, held
* there by a span with `margin-right`, and it now sits at the row's
* 0.625rem like everything else in a row. The two groups read as slightly
* closer than before. Deliberate -- one spacing rule for buttons in a row
* beats a second one for buttons in a row that happen to be a picker --
* but it is a visual change and not a pure refactor.
*/}
ui: a row of buttons is spaced by the row The archive page's six actions shared edges, and Update sat lower than the rest. Both come from the same thing: Semantic's Button carried `margin: 0 .25em .25em 0`, so a page could list buttons as bare siblings and they arrived spaced -- and separated from the line below when the row wrapped. Nothing replaced that margin. Two of those six answered with `marginTop: 0.5em`, which is the wrong axis: a Button is `display: inline-flex; vertical-align: middle`, and `vertical-align` is measured on the MARGIN box, so half of any top margin shows up as the visible button dropping. It was covering the wrapped-row case in the only axis a margin can, and paying for it in the other one. `.wrolpi-button-row` is a flex row with a gap, so both axes are covered at once and no button needs a margin of its own -- the same rule as `.wrolpi-stack`, along the other axis. Applied to the five rows in the app that had no gap: the archive page, the shared collection edit form (which three pages hand action buttons to, and where nine buttons plus Cancel carried `margin-top: 1em` each while Save carried none), the doc page's two responsive branches, and the downloads table's edit/restart pair. `.action-button-spacing` goes with them; it was that same margin, on Cancel. Guarded four ways. ui-layout.cy.js measures that the row really spaces what it holds, wraps rather than overflows, centres its buttons against a taller item beside them, and counts a confirmed APIButton as one item rather than two -- that one returns a fragment holding a `<Confirm/>`, which would open a hole in the row if it did not portal. Common.test.js scans for the two ways this comes back: a button in a row stamping a vertical margin, and a row of buttons that is not a row. Neither throws, which is how the app got here. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:39:03 -06:00
<div className='wrolpi-button-row' style={{marginTop: '1em'}}>
{formatButtons}
{actionButtons}
</div>
</Media>
</>;
})()}
</Panel>
<Panel>
<TagsSelector selectedTagNames={docFile.tags} onAdd={localAddTag} onRemove={localRemoveTag}/>
</Panel>
<Tabs defaultValue='about'>
<Tabs.List>
<Tabs.Tab value='about'>About</Tabs.Tab>
<Tabs.Tab value='files'>Files</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value='about' pt='md'>{aboutTab}</Tabs.Panel>
<Tabs.Panel value='files' pt='md'>{filesTab}</Tabs.Panel>
</Tabs>
<TaggedDeleteConfirmModal
open={taggedFileGroups !== null}
taggedFileGroups={taggedFileGroups}
onCancel={() => setTaggedFileGroups(null)}
onConfirm={async () => {
setTaggedFileGroups(null);
await handleDelete(true);
}}
/>
</>;
}
const AUTHOR_COLUMNS = [
{key: 'name', label: 'Author', sortable: true, width: 10},
{key: 'item_count', label: 'Documents', sortable: true, align: 'right', width: 6},
];
const AUTHOR_ROUTES = {
search: '/docs',
searchParam: 'author',
};
const SUBJECT_COLUMNS = [
{key: 'name', label: 'Subject', sortable: true, width: 10},
{key: 'item_count', label: 'Documents', sortable: true, align: 'right', width: 6},
];
const SUBJECT_ROUTES = {
search: '/docs',
searchParam: 'subject',
};
function AuthorsPage() {
useTitle('Doc Authors');
const [authors] = useAuthors();
const [searchStr, setSearchStr] = useOneQuery('author');
const searchInputRef = React.useRef();
review: finish the sweep the first pass claimed The review was right that completeness was not done. Every finding held up. Three more pages mounted a `PageContainer` inside a route that already provides page chrome -- `ManageMap`, `MapPins`, `ManageZim` -- so they sat a further 1em down and 1em in from the tab bar than the viewers beside them. The same defect as ArchiveSettings, in a shape the scan could not see: it keyed on `PageContainer` route wrappers, and Map and Zim wrap their content in a `wrolpi-stack` div instead. It now locates routers first and asks whether the enclosing return provides chrome either way, resolves `element={<ErrorBoundary><Page/></ErrorBoundary>}` as well as the bare form, and knows about `class` components -- `ManageZim` is one, and a scan that only knew functions reported it clean. Five top-level blocks still added their own margin to the stack's gap: the dashboard search row (52.8px against 17.6px, on the most-looked-at page in the app), the Playlists filter row, both Docs filter rows, and the Map pins filter. The extension page's hint panel had the same compound against a Mantine Stack's gap. ControllerPage held its four panel sections in a plain wrapper, so the admin page's stack saw one child and the panels kept sharing edges -- the exact hole Settings had. The dashboard was reported clean in the first pass and was not. The sweep measured wrapper-to-wrapper gaps, and that row's margin is INSIDE a Media wrapper, so it never appeared: the measurement, not the page, was at fault. Cypress gap assertions now derive from the stack's own `row-gap` instead of a 12-28px range that assumed the default interface scale and would have false-failed a correct layout at a larger one. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:09:12 -06:00
// No `marginBottom`: a top-level block of the page, spaced by the page's stack.
const header = <div>
<SearchInput
placeholder='Author filter...'
size='large'
searchStr={searchStr}
disabled={!Array.isArray(authors) || authors.length === 0}
onClear={() => setSearchStr('')}
onChange={setSearchStr}
onSubmit={null}
inputRef={searchInputRef}
/>
</div>;
return <>
{header}
<CollectionTable
collections={authors}
columns={AUTHOR_COLUMNS}
routes={AUTHOR_ROUTES}
searchStr={searchStr}
emptyMessage='No authors found. Index some documents with author metadata!'
/>
</>;
}
function SubjectsPage() {
useTitle('Doc Subjects');
const [subjects] = useSubjects();
const [searchStr, setSearchStr] = useOneQuery('subject');
const searchInputRef = React.useRef();
review: finish the sweep the first pass claimed The review was right that completeness was not done. Every finding held up. Three more pages mounted a `PageContainer` inside a route that already provides page chrome -- `ManageMap`, `MapPins`, `ManageZim` -- so they sat a further 1em down and 1em in from the tab bar than the viewers beside them. The same defect as ArchiveSettings, in a shape the scan could not see: it keyed on `PageContainer` route wrappers, and Map and Zim wrap their content in a `wrolpi-stack` div instead. It now locates routers first and asks whether the enclosing return provides chrome either way, resolves `element={<ErrorBoundary><Page/></ErrorBoundary>}` as well as the bare form, and knows about `class` components -- `ManageZim` is one, and a scan that only knew functions reported it clean. Five top-level blocks still added their own margin to the stack's gap: the dashboard search row (52.8px against 17.6px, on the most-looked-at page in the app), the Playlists filter row, both Docs filter rows, and the Map pins filter. The extension page's hint panel had the same compound against a Mantine Stack's gap. ControllerPage held its four panel sections in a plain wrapper, so the admin page's stack saw one child and the panels kept sharing edges -- the exact hole Settings had. The dashboard was reported clean in the first pass and was not. The sweep measured wrapper-to-wrapper gaps, and that row's margin is INSIDE a Media wrapper, so it never appeared: the measurement, not the page, was at fault. Cypress gap assertions now derive from the stack's own `row-gap` instead of a 12-28px range that assumed the default interface scale and would have false-failed a correct layout at a larger one. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:09:12 -06:00
// No `marginBottom`: a top-level block of the page, spaced by the page's stack.
const header = <div>
<SearchInput
placeholder='Subject filter...'
size='large'
searchStr={searchStr}
disabled={!Array.isArray(subjects) || subjects.length === 0}
onClear={() => setSearchStr('')}
onChange={setSearchStr}
onSubmit={null}
inputRef={searchInputRef}
/>
</div>;
return <>
{header}
<CollectionTable
collections={subjects}
columns={SUBJECT_COLUMNS}
routes={SUBJECT_ROUTES}
searchStr={searchStr}
emptyMessage='No subjects found. Index some documents with subject metadata!'
/>
</>;
}
function DocsStatisticsPage() {
useTitle('Doc Statistics');
const [statistics, setStatistics] = useState(null);
useEffect(() => {
const fetchStats = async () => {
try {
const response = await getDocStatistics();
if (response.ok) {
const data = await response.json();
setStatistics(data.statistics);
}
} catch (e) {
setStatistics(undefined);
}
};
fetchStats();
}, []);
if (statistics === null) {
return <Loading/>;
}
if (statistics === undefined) {
return <ErrorMessage>Unable to fetch Doc Statistics</ErrorMessage>;
}
return <Panel>
<Header as='h1' style={{textAlign: 'center'}}>Documents</Header>
<StatisticGroup>
<Statistic value={toLocaleString(statistics.doc_count)} label='Documents'/>
<Statistic value={toLocaleString(statistics.epub_count)} label='eBooks'/>
<Statistic value={toLocaleString(statistics.pdf_count)} label='PDFs'/>
<Statistic value={toLocaleString(statistics.other_count)} label='Other'/>
<Statistic value={humanFileSize(statistics.total_size)} label='Total Size'/>
<Statistic value={toLocaleString(statistics.author_count)} label='Authors'/>
<Statistic value={toLocaleString(statistics.subject_count)} label='Subjects'/>
</StatisticGroup>
</Panel>;
}
export function DocsRoute() {
const location = useLocation();
const path = location.pathname;
const links = [
{
text: 'Docs',
to: '/docs',
end: true,
isActive: () => path === '/docs' || /^\/docs\/\d+$/.test(path)
},
{text: 'Subjects', to: '/docs/subjects', isActive: () => path.startsWith('/docs/subjects')},
{text: 'Authors', to: '/docs/authors', isActive: () => path.startsWith('/docs/authors')},
{text: 'Statistics', to: '/docs/statistics'},
];
return <PageContainer>
<TabLinks links={links}/>
<Routes>
<Route path='/' element={<DocsPage/>}/>
<Route path=':fileGroupId' element={<DocPage/>}/>
<Route path='subjects' element={<SubjectsPage/>}/>
<Route path='authors' element={<AuthorsPage/>}/>
<Route path='statistics' element={<DocsStatisticsPage/>}/>
</Routes>
</PageContainer>;
}