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>
This commit is contained in:
lrnselfreliance 2026-08-11 18:57:01 -06:00 • committed by Roland
parent 57d842671f
commit e3fa68a53c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 361 additions and 15 deletions

View file

@ -1,7 +1,7 @@
import React, {useEffect, useState} from 'react';
import React, {useContext, useEffect, useState} from 'react';
import {Link, Route, Routes, useLocation, useNavigate, useParams, useSearchParams} from "react-router";
import {deleteFileGroups, getDocStatistics, tagFileGroup, untagFileGroup} from "../api";
import {Media} from "../contexts/contexts";
import {Media, ThemeContext} from "../contexts/contexts";
import {
APIButton,
BackButton,
@ -17,7 +17,18 @@ import {
toLocaleString,
useTitle
} from "./Common";
import {Button, ButtonGroup, Group, Header, Loading, Panel, Statistic, StatisticGroup, Tabs} from "./ui";
import {
Button,
ButtonGroup,
Group,
Header,
Loading,
MediaGate,
Panel,
Statistic,
StatisticGroup,
Tabs
} from "./ui";
import {BulkTagModal} from "./BulkTagModal";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
import {DeepSearchHint, docMimetypeFilterOptions, FilesView, SearchControlBar} from "./Files";
@ -157,6 +168,8 @@ function DocsPage() {
function DocPage() {
const {fileGroupId} = useParams();
const navigate = useNavigate();
// 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);
@ -344,11 +357,19 @@ function DocPage() {
{isCbz && activePath && <CbzViewer path={activePath}/>}
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
<iframe
src={embedUrl}
title={docFile.title || docFile.name}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
{/*
* 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>

View file

@ -0,0 +1,49 @@
import fs from 'fs';
import path from 'path';
/*
* The document page's embedded viewer, and which of them is withheld in a filtering theme.
*
* This is the surface that measured 55% non-red pixels in night mode: a PDF is drawn by the
* browser in its own out-of-process viewer, which the theme's SVG filter never reaches, so it
* arrives in full color however the iframe is styled. The EPUB viewer is a document of our own
* and tints correctly, so gating it would hide something for no reason.
*
* Read off the source. DocPage renders only after `useDoc` resolves a file group and reaches
* the embed through several branches of file selection; a render test here would assert more
* about the mocks than about the wiring. ui.test.js covers what MediaGate itself does, and
* FilePreview.test.js covers the same contract on the other embed surface.
*/
const source = fs.readFileSync(path.join(__dirname, 'Docs.js'), 'utf8');
describe('DocPage embed gating (source contract)', () => {
it('wraps the embedded viewer in a MediaGate', () => {
// The iframe must not be reachable without passing through the gate.
const embed = source.match(/<MediaGate[^>]*>\s*<iframe/);
expect(embed).not.toBeNull();
});
it('gates on the live filter state, not on the theme name', () => {
/*
* `mediaFilterEnabled` rather than `theme === 'night'`: 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.
*/
const gate = source.match(/<MediaGate[^>]*gated=\{([^}]*)\}/);
expect(gate).not.toBeNull();
expect(gate[1]).toContain('mediaFilterEnabled');
expect(gate[1]).toContain('isPdf');
// The theme's NAME must not appear in the condition.
expect(gate[1]).not.toMatch(/theme\s*===/);
});
it('remounts the gate per document, so revealing one does not reveal the next', () => {
// Selecting a different file reuses the same fiber otherwise, carrying `revealed` over.
const gate = source.match(/<MediaGate([^>]*)>/);
expect(gate[1]).toMatch(/key=\{/);
});
});

View file

@ -6,13 +6,14 @@ import {getFile, tagFileGroup, untagFileGroup} from "../api";
import {ArchivePreviewContent} from "./ArchivePreview";
import {CbzViewer} from "./CbzViewer";
import {StlViewer} from "react-stl-viewer";
import {Button, ButtonGroup, Header, Icon, IconButton, Menu, Modal, toast} from "./ui";
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
import {useOneQuery} from "../hooks/customHooks";
import {ShareButton} from "./Share";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {pathDirectory} from "./FileBrowser";
import {InlineErrorBoundary} from "./ErrorBoundary";
import {useLocation} from "react-router";
import {ThemeContext} from "../contexts/contexts";
// Routes where file views should not be tracked
const EXCLUDED_TRACKING_ROUTES = [
@ -93,9 +94,27 @@ function getEpubViewerURL(previewFile) {
return `/epub/epub.html?url=/media/${encodeMediaPath(url)}`
}
function getIframePreviewModal(previewFile, url) {
url = url || getMediaPathURL(previewFile);
return <Modal.Content>
/*
* The iframe body of a preview.
*
* A component rather than part of `getIframePreviewModal` because it reads the theme: the
* modal builders are plain functions called from an event handler, where hooks cannot run.
*/
function IframePreview({url, gatePdf}) {
const {mediaFilterEnabled} = React.useContext(ThemeContext);
/*
* `gatePdf` only for PDFs. Text and the EPUB viewer are documents of our own, which the
* theme's media filter tints; Chrome's PDF viewer is composited out of process and arrives
* in full color however the iframe is styled.
*
* Keyed by `url`, which is load-bearing rather than tidy. 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 MediaGate fiber survives, and a
* reader who revealed one PDF would get the next one in full color with no prompt -- the
* exact flash this exists to prevent. The key forces a remount per document.
*/
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
<div className='preview-fit'>
<iframe title='textModal' src={url}
style={{
@ -104,6 +123,13 @@ function getIframePreviewModal(previewFile, url) {
backgroundColor: '#ffffff',
}}/>
</div>
</MediaGate>
}
function getIframePreviewModal(previewFile, url, {gatePdf = false} = {}) {
url = url || getMediaPathURL(previewFile);
return <Modal.Content>
<IframePreview url={url} gatePdf={gatePdf}/>
</Modal.Content>
}
@ -589,7 +615,7 @@ export function FilePreviewProvider({children}) {
const viewerURL = getEpubViewerURL(previewFile);
setModalContent(getIframePreviewModal(previewFile, viewerURL), viewerURL, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/pdf')) {
setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable);
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('image/')) {
setModalContent(getImagePreviewModal(previewFile), url, null, path, taggable);
} else if (mimetype.startsWith('model/stl')) {

View file

@ -22,3 +22,81 @@ describe('getSlicerURL', () => {
expect(SLICERS.map(s => s.scheme)).not.toContain('prusaslicer');
});
});
describe('PDF gating (source contract)', () => {
/*
* Which previews withhold their content in a filtering theme.
*
* A PDF is the only one that must: the browser draws it in its own out-of-process viewer,
* which the theme's SVG filter never reaches, so it arrives in full color -- measured at
* 39.8% non-red pixels inside the preview modal on a device in night mode. Text and the
* EPUB viewer are documents of our own and filter correctly, so gating them would hide
* something for no reason.
*
* Read off the source rather than rendered: the modal builders are plain functions called
* from an event handler, reached only through a file-click on a mounted browser page. This
* checks the wiring; ui.test.js checks that MediaGate itself behaves.
*/
const fs = require('fs');
const path = require('path');
const source = fs.readFileSync(path.join(__dirname, 'FilePreview.js'), 'utf8');
/** The `setModalContent(...)` line for the branch guarded by `mimetype.startsWith(x)`. */
const branchCall = (mimetype) => {
const at = source.indexOf(`mimetype.startsWith('${mimetype}')`);
if (at < 0) return null;
const rest = source.slice(at, at + 400);
const call = rest.match(/setModalContent\([^\n]*/);
return call ? call[0] : null;
};
test('the PDF preview is gated', () => {
expect(branchCall('application/pdf')).toContain('gatePdf: true');
});
test.each([
['text/', 'text'],
['application/epub', 'the EPUB viewer'],
])('%s is not gated, because %s is filtered correctly', (mimetype) => {
const call = branchCall(mimetype);
// The premise: a branch that could not be found would vacuously "not be gated".
expect(call).not.toBeNull();
expect(call).not.toContain('gatePdf');
});
});
describe('preview gate remounting (source contract)', () => {
/*
* A revealed PDF must not carry its reveal over to the next document.
*
* The effect that rebuilds a preview sets the modal to null and then to the new content in
* a single pass, so React 18 batches both updates and reconciles rather than unmounting:
* the MediaGate fiber survives across documents. Without a key, a reader who revealed PDF
* A and then opened PDF B would get B in full color with no prompt -- the flash the whole
* feature exists to prevent.
*/
const fs = require('fs');
const path = require('path');
const source = fs.readFileSync(path.join(__dirname, 'FilePreview.js'), 'utf8');
test('the gate is keyed by the document URL', () => {
const gate = source.match(/<MediaGate([^>]*)>/);
expect(gate).not.toBeNull();
expect(gate[1]).toMatch(/key=\{url\}/);
});
test('the rebuild really does batch, which is why the key is needed', () => {
/*
* The premise for the test above. If the rebuild ever unmounted the modal between
* documents, the key would be redundant -- and if this assertion stopped holding, the
* reasoning in the comment above would be stale rather than merely belt-and-braces.
*/
const effects = source.split('React.useEffect');
const rebuild = effects.filter(body =>
body.includes('setPreviewModal(null)') && body.includes('setModalContent('));
expect(rebuild.length).toBeGreaterThan(0);
});
});

View file

@ -15,6 +15,7 @@ import {
Loading,
IconStack,
MediaFilterToggle,
MediaGate,
Message,
MultiSelect,
NumberInput,
@ -154,7 +155,7 @@ export const NavBarSample = ({color}) => {
let toastCounter = 0;
export function ThemeSamplePage() {
const {theme} = useContext(ThemeContext);
const {theme, mediaFilterEnabled} = useContext(ThemeContext);
const [confirmOpen, setConfirmOpen] = useState(false);
const [wideConfirmOpen, setWideConfirmOpen] = useState(false);
const [comments, setComments] = useState(true);
@ -233,7 +234,7 @@ export function ThemeSamplePage() {
</p>
</div>
<p style={{fontSize: '0.75rem', color: 'var(--muted)', margin: 0, maxWidth: 430}}>
Images, video, PDFs, embedded pages, and the map canvas cannot read theme
Images, video, embedded pages, and the map canvas cannot read theme
tokens, so a monochrome theme remaps them with an SVG color matrix instead.
Night filters to red unless you turn it off; amber tints to match only if
you ask. Light and dark offer no filter, so both images look the same here.
@ -258,6 +259,24 @@ export function ThemeSamplePage() {
show only this caption.
</p>
</div>
{/*
The one thing the matrix cannot reach. Gated on the live filter state, so in
night it withholds and in light it simply shows — the same behavior /docs has.
*/}
<div style={{marginTop: 18}}>
<MediaGate gated={!!mediaFilterEnabled}>
<img src='/icon.svg' alt='Stand-in for a PDF' width={104} height={104}/>
</MediaGate>
<p style={{fontSize: '0.75rem', color: 'var(--muted)', margin: '8px 0 0'}}>
<code>MediaGate</code>. A PDF is the one thing the filter cannot reach:
the browser draws it in its own viewer, outside the page, so it arrives
in full color however the frame is styled — and painting over it just
hides the document. So when a filter is on — night by default, amber if
you ask — it withholds the PDF and lets you choose. Light and dark offer
no filter and show it straight through, which is what you see here
unless a filter is on.
</p>
</div>
</Panel>
</Section>

View file

@ -0,0 +1,76 @@
import React from 'react';
import {Button} from './Button';
import {Message} from './Feedback';
/*
* A gate for media the theme's filter cannot reach.
*
* Night and amber pass media through an SVG color matrix so nothing a user opens costs them
* their dark adaptation. That filter reaches everything drawn in our own document -- images,
* video, canvases, and same-origin iframes such as the EPUB viewer.
*
* It does not reach a PDF. Chrome renders 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 on
* a device in night mode, a PDF covered 55% of the viewport in non-red pixels while the chrome
* around it was correctly red.
*
* Tinting it from outside does not work either. 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:
* the measurement reports zero non-red pixels while the document is entirely obliterated.
*
* So the options are to render PDFs ourselves or to not show one unasked. This is the second:
* the reader is told why, and chooses. Nothing renders until they do -- hiding it with CSS
* would still load and paint the viewer, which is the whole thing being avoided.
*
* `gated` is a prop rather than something read from ThemeContext, so this stays a component of
* the library like any other: it is told whether to gate, it does not decide. Call sites pass
* `isPdf && mediaFilterEnabled`.
*/
export interface MediaGateProps {
/** Whether to withhold `children` until the reader asks for them. */
gated: boolean;
/** What is being withheld, named in the reader's terms: "PDF", "document". */
kind?: string;
children: React.ReactNode;
}
export function MediaGate({gated, kind = 'PDF', children}: MediaGateProps) {
const [revealed, setRevealed] = React.useState(false);
// Re-gate when filtering comes back on, so revealing one document does not leave every
// later one unguarded.
React.useEffect(() => {
if (!gated) setRevealed(false);
}, [gated]);
if (!gated) return <>{children}</>
if (revealed) {
/*
* The control goes ABOVE the media, not after it. A preview fills
* `calc(100dvh - 18.75rem)`, a height calibrated with no room for a trailing button
* row, so a control placed 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 to undo it.
*/
return <>
<div className='wrolpi-button-row'>
<Button role='cancel' icon='eye slash' onClick={() => setRevealed(false)}>
Hide the {kind} again
</Button>
</div>
{children}
</>
}
return <Message kind='warning' icon='eye slash' title={`${kind} hidden`}>
<p>
This {kind} cannot be tinted to match the theme, so it would be shown in full color
and at full brightness.
</p>
<Button role='primary' onClick={() => setRevealed(true)}>
Show the full-color {kind}
</Button>
</Message>
}

View file

@ -20,6 +20,7 @@ export * from './DataTable';
export * from './Navigation';
export * from './SearchBox';
export * from './Inputs';
export * from './MediaGate';
export * from './Overlays';
export * from './ThemePicker';
export * from './toast';

View file

@ -20,6 +20,7 @@ import {
IconStack,
Loader,
Loading,
MediaGate,
Placeholder,
Pagination,
SearchBox,
@ -1694,3 +1695,78 @@ describe('modal sizes', () => {
expect(offenders).toEqual([]);
});
});
describe('MediaGate', () => {
/*
* Withholding media the theme's filter cannot reach.
*
* The case that matters is a PDF in night mode: Chrome renders it in an out-of-process
* viewer that the parent's filter never touches, so it arrives in full color -- measured at
* 55% non-red pixels on a device while the chrome around it was correctly red.
*/
it('renders its children untouched when nothing is being filtered', () => {
renderUI(<MediaGate gated={false}><p>the document</p></MediaGate>);
expect(screen.getByText('the document')).toBeInTheDocument();
expect(screen.queryByRole('button', {name: /Show the full-color/})).not.toBeInTheDocument();
});
it('withholds the media, and says why, when the theme is filtering', () => {
renderUI(<MediaGate gated={true}><p>the document</p></MediaGate>);
// Not merely hidden: absent. A CSS-hidden iframe still loads and paints the viewer,
// which is the bright flash this exists to prevent.
expect(screen.queryByText('the document')).not.toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent(/cannot be tinted/);
});
it('shows the media when the reader asks for it', async () => {
renderUI(<MediaGate gated={true}><p>the document</p></MediaGate>);
await userEvent.click(screen.getByRole('button', {name: 'Show the full-color PDF'}));
expect(screen.getByText('the document')).toBeInTheDocument();
});
it('lets the reader put it away again', async () => {
renderUI(<MediaGate gated={true}><p>the document</p></MediaGate>);
await userEvent.click(screen.getByRole('button', {name: 'Show the full-color PDF'}));
await userEvent.click(screen.getByRole('button', {name: 'Hide the PDF again'}));
expect(screen.queryByText('the document')).not.toBeInTheDocument();
});
it('re-gates a revealed document when filtering is turned back on', async () => {
/*
* Revealing one document must not leave every later one unguarded: the reader who turns
* the filter off, looks at a PDF, then turns it back on has re-stated the preference
* this respects.
*
* The reveal in the middle is the whole test. An earlier version went straight from
* `gated={false}` to `gated={true}` with `revealed` still false, which never reaches the
* reset effect at all -- it passed just as well with that effect deleted, so it was
* testing the `if (!gated)` early return and claiming to test the reset.
*/
const gate = (gated) =>
<MantineProvider theme={mantineTheme} cssVariablesResolver={cssVariablesResolver}>
<MediaGate gated={gated}><p>the document</p></MediaGate>
</MantineProvider>;
const {rerender} = render(gate(true));
await userEvent.click(screen.getByRole('button', {name: 'Show the full-color PDF'}));
expect(screen.getByText('the document')).toBeInTheDocument();
rerender(gate(false)); // filter off: shown because nothing is being filtered
rerender(gate(true)); // filter back on: must be withheld again, not still revealed
expect(screen.queryByText('the document')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Show the full-color PDF'})).toBeInTheDocument();
});
it('names what it is withholding', () => {
renderUI(<MediaGate gated={true} kind='document'><p>x</p></MediaGate>);
expect(screen.getByRole('button', {name: 'Show the full-color document'})).toBeInTheDocument();
});
});