Compare commits

...

2 commits

Author SHA1 Message Date
Roland
efe84d17f1 ui: media filtering is a per-theme setting, not a night-mode hardcode
Some checks are pending
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Filtering media was keyed on `data-theme="night"`, which made it a property of
the theme that no user could turn off.  Some people want their media tinted to
match the interface; some want to see the actual image.

A theme now declares a filter and whether it starts on, and the user decides:

  night   night-red    on by default.  An unfiltered thumbnail undoes dark
                       adaptation, which is the whole point of the mode.
  amber   amber-mono   off by default.  Amber is a look, not a night-vision
                       aid, so media keeps its real colors until asked for.
  light   -            no filter offered, so no toggle is shown.
  dark    -

The choice is stored per theme, so wanting amber's tint says nothing about
wanting night's.  The toggle lives in the theme picker, which puts it on the
Settings page and in the gallery at once.

Mechanically the rules now key on a `data-media-filter` attribute rather than
`data-theme`: a rule keyed on the theme could not be turned off.  index.html
stamps that attribute before first paint alongside data-theme -- without it,
night mode paints a screen of unfiltered thumbnails while the bundle arrives
over a hotspot, costing the user the adaptation the theme exists to protect.
Tests cover both the attribute rule and the fact that the inline script's
duplicated ids and defaults still agree with names.ts.

The amber matrix is the same luminance collapse tinted to #ff9500 (red full,
green 0.584, blue zero) with a gentler gamma than night's: amber carries far
more luminance and clips to a flat wash otherwise.

The gallery gains a Media filtering section showing the WROLPi logo filtered,
beside an unfiltered copy that opts out with `night-unfiltered`.  That copy is
behind a click on purpose -- an unfiltered image is a bright patch, and night
mode should not spring one on someone reading in the dark.

ui-design.md gains the media filtering contract it never got in Phase 0,
including the note that a Phase 3 custom theme names an existing filter id and
cannot ship its own matrix, since that would be code rather than data.
2026-07-30 09:15:04 -06:00
Roland
973a61af28 ui: migrate the extension pages and Configs; five components they needed
Phase 2, part 1.  Three files leave Semantic UI (baseline 75 -> 72), and the
components they needed join the library and the gallery:

  Header       Semantic's shape (as/icon/subheader/dividing).  47 files use
               <Header>, and the level now picks the size, so the type scale
               stays a scale instead of each call site choosing a font size.
  Message      gains an icon and a dismiss button.
  ActionInput  input and button sharing one outline, for <Input action={...}/>.
  Loading      centered loader with a caption, replacing the
               <Loader active inline='centered'> + wrapper div in 19 places.
  Modal        becomes compound - Modal.Header/.Content/.Actions, plus
               Semantic's open, closeIcon, and size names - because 34 files
               are written against that shape.

test-utils mounts MantineProvider with ThemeProvider's exact configuration:
migrated components render Mantine internals and every one of their test files
would otherwise need its own provider.

One Semantic bleed found and fixed: semantic.min.css sets
`h1,h2,h3,h4,h5 { font-family: Lato }` and loads after Mantine's element rule,
so headings ignored the theme's body face.  Only visible in amber, where the
body is mono and the headings were not.  A class-level restatement outranks it;
the rule comes out when Semantic does.

Verified: 925 jest tests, clean production build, and a night-mode audit of
every painted pixel in the gallery (red-only, one known false positive).  The
Configs backup and restore flow was exercised against the real API.
2026-07-30 09:15:04 -06:00
21 changed files with 1167 additions and 241 deletions

View file

@ -30,10 +30,14 @@
<title>WROLPi: Create your own off-grid library</title>
<script>
/*
Stamp the saved theme on <html> before first paint. ThemeProvider sets the same
attribute once React mounts, but the bundle can take a while to arrive over a
hotspot — without this the page would paint in the wrong theme first. Keep the
storage key and theme names in sync with src/components/Theme.tsx.
Stamp the saved theme, and the media filter it resolves to, on <html> before first
paint. ThemeProvider sets the same attributes once React mounts, but the bundle can
take a while to arrive over a hotspot — without this the page would paint in the wrong
theme first, and in night mode a flash of unfiltered thumbnails would cost the user the
dark adaptation the theme exists to protect.
Keep the storage keys, theme names, and filter defaults in sync with
src/themes/names.ts.
*/
(function () {
var theme = 'light';
@ -52,6 +56,24 @@
theme = 'dark';
}
document.documentElement.setAttribute('data-theme', theme);
// Which filter each theme uses, and whether it applies unless the user says otherwise.
var filters = {night: 'night-red', amber: 'amber-mono'};
var defaults = {night: true, amber: false};
if (filters[theme]) {
var enabled = defaults[theme];
try {
var overrides = JSON.parse(localStorage.getItem('media-filter') || '{}');
if (typeof overrides[theme] === 'boolean') {
enabled = overrides[theme];
}
} catch (e) {
// Blocked storage or malformed JSON: fall back to the theme's default.
}
if (enabled) {
document.documentElement.setAttribute('data-media-filter', filters[theme]);
}
}
})();
</script>
</head>

View file

@ -105,9 +105,12 @@ import {
isDarkTheme,
isThemeName,
lightTheme,
mediaFilterSessionKey,
nightTheme,
resolveMediaFilter,
systemTheme,
themeChoices,
themeMediaFilter,
themeNames,
themeSessionKey,
} from "../themes/names";
@ -127,6 +130,7 @@ export {
nightTheme,
systemTheme,
themeChoices,
themeMediaFilter,
themeNames,
themeSessionKey,
};
@ -155,6 +159,28 @@ const readSavedTheme = (): SavedThemeName => {
return null;
}
/**
* The user's per-theme media filter choices: `{night: false}` means "night, but
* do not filter media". A theme absent from the map follows its own default.
*/
const readMediaFilters = (): Partial<Record<ThemeName, boolean>> => {
try {
const raw = localStorage.getItem(mediaFilterSessionKey);
if (raw) {
const parsed = JSON.parse(raw);
// Only keep known themes with boolean values; the rest is someone else's data.
if (parsed && typeof parsed === 'object') {
return Object.fromEntries(Object.entries(parsed)
.filter(([key, value]) => isThemeName(key) && typeof value === 'boolean'));
}
}
} catch (e) {
// Blocked storage, or a value an older version wrote.
console.error('Unable to read the media filter settings', e);
}
return {};
}
interface ThemeProviderProps {
children: React.ReactNode;
}
@ -170,12 +196,28 @@ export function ThemeProvider({children, ...props}: ThemeProviderProps) {
// theme is what is currently applied.
const [theme, setThemeName] = useState<ThemeName>(() => resolveTheme(readSavedTheme()));
// Which themes the user has turned media filtering on or off for.
const [mediaFilters, setMediaFilters] = useState<Partial<Record<ThemeName, boolean>>>(
readMediaFilters);
// `data-theme` on <html> is what the token CSS keys off of. index.html stamps it before
// first paint from the same localStorage value, so the first render already matches.
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme);
}, [theme]);
// `data-media-filter` names the filter to apply, or is absent when nothing should be
// filtered. index.html stamps this too: a flash of unfiltered thumbnails before the
// bundle arrives would cost the user the dark adaptation night mode exists to protect.
useEffect(() => {
const filter = resolveMediaFilter(theme, mediaFilters);
if (filter) {
document.documentElement.setAttribute('data-media-filter', filter);
} else {
document.documentElement.removeAttribute('data-media-filter');
}
}, [theme, mediaFilters]);
// Follow the OS preference only while the user has not chosen a specific theme.
useEffect(() => {
if (isThemeName(savedTheme) || typeof window.matchMedia !== 'function') {
@ -210,6 +252,20 @@ export function ThemeProvider({children, ...props}: ThemeProviderProps) {
setThemeName(resolveTheme(value));
}
/**
* Turn the current theme's media filter on or off. Stored per theme, so a user who
* wants amber's tint but not night's — or the reverse — gets both.
*/
const setMediaFilterEnabled = (enabled: boolean) => {
const next = {...mediaFilters, [theme]: enabled};
setMediaFilters(next);
try {
localStorage.setItem(mediaFilterSessionKey, JSON.stringify(next));
} catch (e) {
console.error('Unable to save the media filter setting', e);
}
}
// Retained for callers written against the old two-theme API.
const setDarkTheme = (save = false) => {
setThemeName(darkTheme);
@ -256,6 +312,10 @@ export function ThemeProvider({children, ...props}: ThemeProviderProps) {
theme,
savedTheme,
isDark: dark,
// The filter this theme offers, if any, and whether it is currently applied.
mediaFilter: themeMediaFilter(theme),
mediaFilterEnabled: !!resolveMediaFilter(theme, mediaFilters),
setMediaFilterEnabled,
setTheme,
setDarkTheme,
setLightTheme,

View file

@ -1,3 +1,5 @@
import fs from 'fs';
import path from 'path';
import React, {useContext} from 'react';
import {act, render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@ -13,6 +15,7 @@ import {
ThemeProvider,
themeSessionKey,
} from './Theme';
import {mediaFilterSessionKey, resolveMediaFilter, themeMediaFilter} from '../themes/names';
// Lets a test drive `prefers-color-scheme` and assert on what the provider applied.
let prefersDark = false;
@ -38,26 +41,37 @@ const mockMatchMedia = () => {
};
function ThemeProbe() {
const {theme, savedTheme, isDark, setTheme, cycleSavedTheme} = useContext(ThemeContext);
const {
theme, savedTheme, isDark, setTheme, cycleSavedTheme,
mediaFilter, mediaFilterEnabled, setMediaFilterEnabled,
} = useContext(ThemeContext);
return <>
<span data-testid='theme'>{theme}</span>
<span data-testid='saved'>{String(savedTheme)}</span>
<span data-testid='dark'>{String(isDark)}</span>
<span data-testid='filter-offered'>{mediaFilter ? mediaFilter.id : 'none'}</span>
<span data-testid='filter-on'>{String(mediaFilterEnabled)}</span>
<button onClick={() => setTheme(nightTheme)}>night</button>
<button onClick={() => setTheme(amberTheme)}>amber</button>
<button onClick={() => setTheme(lightTheme)}>light</button>
<button onClick={() => setTheme(systemTheme)}>system</button>
<button onClick={cycleSavedTheme}>cycle</button>
<button onClick={() => setMediaFilterEnabled(false)}>filter off</button>
<button onClick={() => setMediaFilterEnabled(true)}>filter on</button>
</>
}
const renderProvider = () => render(<ThemeProvider><ThemeProbe/></ThemeProvider>);
const appliedTheme = () => document.documentElement.getAttribute('data-theme');
const appliedFilter = () => document.documentElement.getAttribute('data-media-filter');
describe('ThemeProvider', () => {
beforeEach(() => {
prefersDark = false;
localStorage.clear();
document.documentElement.removeAttribute('data-theme');
document.documentElement.removeAttribute('data-media-filter');
mockMatchMedia();
});
@ -140,6 +154,127 @@ describe('ThemeProvider', () => {
});
});
describe('ThemeProvider media filtering', () => {
beforeEach(() => {
prefersDark = false;
localStorage.clear();
document.documentElement.removeAttribute('data-theme');
document.documentElement.removeAttribute('data-media-filter');
mockMatchMedia();
});
it('filters media in night mode without being asked', async () => {
// An unfiltered thumbnail undoes dark adaptation, so night starts filtered.
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'night'}));
expect(appliedFilter()).toBe('night-red');
expect(screen.getByTestId('filter-on')).toHaveTextContent('true');
});
it('leaves amber media alone until the user asks for it', async () => {
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'amber'}));
expect(appliedFilter()).toBeNull();
expect(screen.getByTestId('filter-offered')).toHaveTextContent('amber-mono');
});
it('applies no filter, and offers none, in a theme without one', async () => {
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'light'}));
expect(appliedFilter()).toBeNull();
expect(screen.getByTestId('filter-offered')).toHaveTextContent('none');
});
it('turns the filter off when the user says so, and persists it', async () => {
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'night'}));
await userEvent.click(screen.getByRole('button', {name: 'filter off'}));
expect(appliedFilter()).toBeNull();
expect(JSON.parse(localStorage.getItem(mediaFilterSessionKey))).toEqual({night: false});
});
it('turns amber filtering on when the user asks', async () => {
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'amber'}));
await userEvent.click(screen.getByRole('button', {name: 'filter on'}));
expect(appliedFilter()).toBe('amber-mono');
});
it('keeps the choice separate for each theme', async () => {
// Wanting amber's tint says nothing about wanting night's, and turning night's off
// must not disarm a filter the user deliberately enabled elsewhere.
renderProvider();
await userEvent.click(screen.getByRole('button', {name: 'amber'}));
await userEvent.click(screen.getByRole('button', {name: 'filter on'}));
await userEvent.click(screen.getByRole('button', {name: 'night'}));
await userEvent.click(screen.getByRole('button', {name: 'filter off'}));
expect(appliedFilter()).toBeNull();
await userEvent.click(screen.getByRole('button', {name: 'amber'}));
expect(appliedFilter()).toBe('amber-mono');
});
it('restores the saved choice on the next load', () => {
localStorage.setItem(themeSessionKey, nightTheme);
localStorage.setItem(mediaFilterSessionKey, JSON.stringify({night: false}));
renderProvider();
expect(appliedFilter()).toBeNull();
});
it('falls back to the theme default when the stored settings are unusable', () => {
localStorage.setItem(themeSessionKey, nightTheme);
localStorage.setItem(mediaFilterSessionKey, 'not json');
renderProvider();
// Failing open would leave a user in the dark staring at a white thumbnail.
expect(appliedFilter()).toBe('night-red');
});
it('ignores stored entries for themes that no longer exist', () => {
localStorage.setItem(themeSessionKey, nightTheme);
localStorage.setItem(mediaFilterSessionKey, JSON.stringify({sepia: true, night: false}));
renderProvider();
expect(appliedFilter()).toBeNull();
});
});
describe('resolveMediaFilter', () => {
it('gives every filtering theme a filter defined in MediaFilterDefs', () => {
// A theme naming a filter that does not exist would silently filter nothing.
const defs = fs.readFileSync(
path.join(__dirname, '..', 'themes', 'MediaFilterDefs.tsx'), 'utf8');
[nightTheme, amberTheme].forEach(theme => {
const filter = themeMediaFilter(theme);
expect(defs).toContain(`id='wrolpi-${filter.id}'`);
});
});
it('honours an override in either direction', () => {
expect(resolveMediaFilter(nightTheme, {})).toBe('night-red');
expect(resolveMediaFilter(nightTheme, {night: false})).toBe('');
expect(resolveMediaFilter(amberTheme, {})).toBe('');
expect(resolveMediaFilter(amberTheme, {amber: true})).toBe('amber-mono');
expect(resolveMediaFilter(lightTheme, {light: true})).toBe('');
});
});
describe('theme helpers', () => {
beforeEach(() => {
prefersDark = false;

View file

@ -1,15 +1,19 @@
import React, {useContext, useState} from 'react';
import {ThemeContext} from '../contexts/contexts';
import {
ActionInput,
Button,
Card,
CardGroup,
Confirm,
Header,
Icon,
IconButton,
Label,
Loader,
Loading,
Message,
Modal,
Panel,
Placeholder,
Progress,
@ -52,10 +56,13 @@ const Row = ({children}) => <div style={{display: 'flex', gap: 10, flexWrap: 'wr
</div>;
export function ThemeSamplePage() {
const {theme, setTheme} = useContext(ThemeContext);
const {theme} = useContext(ThemeContext);
const [confirmOpen, setConfirmOpen] = useState(false);
const [comments, setComments] = useState(true);
const [hotspot, setHotspot] = useState(true);
const [dismissed, setDismissed] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [realColors, setRealColors] = useState(false);
return <div style={{maxWidth: 1060, margin: '0 auto', padding: '20px 16px 60px', color: 'var(--text)'}}>
<h1 style={{fontSize: 21, fontWeight: 600, margin: '8px 0 4px'}}>Component gallery</h1>
@ -74,6 +81,67 @@ export function ThemeSamplePage() {
</Panel>
</Section>
<Section label='Media filtering'>
<Panel>
<div style={{display: 'flex', gap: 18, flexWrap: 'wrap', alignItems: 'flex-start'}}>
<div>
{/*
A real <img>, so it goes through whatever filter the current theme
applies — this is the only way to see the filter working without
leaving the page. The unfiltered copy beside it opts out with
`night-unfiltered`, so the two can be compared side by side.
*/}
<img src='/icon.svg' alt='The WROLPi logo, filtered like any other media'
width={104} height={104}/>
<p style={{fontSize: 11, color: 'var(--muted)', margin: '4px 0 0'}}>
Filtered
</p>
</div>
<div>
{/*
Kept behind a click: an unfiltered image is a bright patch, and
leaving one on screen in night mode would cost a user the dark
adaptation they came here to protect. They can ask for it.
*/}
{realColors
? <img className='night-unfiltered' src='/icon.svg'
alt='The WROLPi logo, unfiltered' width={104} height={104}/>
: <Button role='cancel' icon='eye' style={{width: 104, height: 104}}
onClick={() => setRealColors(true)}>Show</Button>}
<p style={{fontSize: 11, color: 'var(--muted)', margin: '4px 0 0'}}>
Real colors
</p>
</div>
<p style={{fontSize: 12, color: 'var(--muted)', margin: 0, maxWidth: 430}}>
Images, video, PDFs, 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.
<br/><br/>
Use the toggle in the theme picker above to see the difference. An
element can opt out with <code>night-unfiltered</code> — that is what
the right-hand copy does, which is why it is behind a click: an
unfiltered image is a bright patch, and night mode should not spring
one on you.
</p>
</div>
</Panel>
</Section>
<Section label='Headers'>
<Panel>
<Header as='h1'>Page title (h1)</Header>
<Header as='h2'>Section (h2)</Header>
<Header as='h3' icon='folder' dividing>With an icon and a divider (h3)</Header>
<Header as='h4' subheader='And a subheader below it'>Subsection (h4)</Header>
<Header as='h5'>Smallest (h5)</Header>
<p style={{fontSize: 12, color: 'var(--muted)', marginBottom: 0}}>
The level picks the size, so the type scale stays a scale: call sites
choose a heading level for the document outline, never a font size.
</p>
</Panel>
</Section>
<Section label='Statistics'>
<StatisticGroup>
<Statistic value='1,432' label='Videos'/>
@ -130,6 +198,12 @@ export function ThemeSamplePage() {
<Message kind='error' title='Download failed'>
HTTP 403 from the remote server after 3 attempts. Retry, or check the URL.
</Message>
<Message kind='info' icon='puzzle piece' title='With an icon, and dismissible'
onDismiss={() => setDismissed(true)}>
{dismissed
? 'Dismissed — it would be gone in the real interface.'
: 'A nudge the user can clear. Only offer dismiss when clearing it is harmless.'}
</Message>
</div>
</Section>
@ -200,6 +274,14 @@ export function ThemeSamplePage() {
<div style={{marginTop: 12}}>
<Textarea label='Notes' placeholder='Notes about this download…' minRows={2}/>
</div>
<div style={{marginTop: 12}}>
<ActionInput
label="This WROLPi's URL"
readOnly
value='https://wrolpi.local'
action={<Button role='cancel' icon='copy'>Copy</Button>}
/>
</div>
<div style={{marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10}}>
<Checkbox label='Download comments' checked={comments}
onChange={e => setComments(e.currentTarget.checked)}/>
@ -261,6 +343,34 @@ export function ThemeSamplePage() {
<Section label='Loading placeholders'>
<Panel><Placeholder lines={4}/></Panel>
<div style={{marginTop: 10}}>
<Panel><Loading>Loading backups…</Loading></Panel>
</div>
</Section>
<Section label='Modal'>
<Panel>
<Row>
<Button role='cancel' icon='eye' onClick={() => setModalOpen(true)}>Open a modal</Button>
</Row>
<p style={{fontSize: 12, color: 'var(--muted)', marginBottom: 0, marginTop: 10}}>
Semantic's compound shape is kept — Modal.Header, Modal.Content,
Modal.Actions — so the 34 call sites written against it migrate by import.
</p>
<Modal open={modalOpen} onClose={() => setModalOpen(false)} size='small'>
<Modal.Header>Restore Backup: channels.yaml</Modal.Header>
<Modal.Content>
<p style={{marginTop: 0}}>
Actions sit below the body behind a hairline, right-aligned so the
confirming action lands where the eye finishes reading.
</p>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={() => setModalOpen(false)}>Close</Button>
<Button role='save' icon='check' onClick={() => setModalOpen(false)}>Apply</Button>
</Modal.Actions>
</Modal>
</Panel>
</Section>
<Section label='Danger zone'>

View file

@ -1,19 +1,16 @@
import {APIButton} from "../Common";
import {Button, Header, Icon, Loader, Modal, Popup, Table} from "../Theme";
import React, {useContext, useEffect, useState} from "react";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {TableRowPlaceholder} from "../Placeholder";
import {Button, Header, Icon, IconButton, Loader, Loading, Modal, Placeholder, Table, Tooltip} from "../ui";
import React, {useEffect, useState} from "react";
import {getConfigText, getConfigBackups, postConfigBackupImport, postConfigBackupPreview} from "../../api";
import {ThemeContext} from "../../contexts/contexts";
function WarningIcon({ok}) {
// null is empty, true is valid, false is invalid.
const trigger = <Icon
color={ok === true ? 'violet' : ok === false ? 'red' : 'grey'}
name={ok === true ? 'check' : ok === false ? 'close' : 'check'}
/>;
const content = ok === true ? 'Valid and can be imported.' : ok === false ? 'Invalid, can be overwritten.' : 'Empty config, can be overwritten.';
return <Popup trigger={trigger} content={content}/>
return <Tooltip label={content}>
<span style={{color: ok === true ? 'var(--violet)' : ok === false ? 'var(--red)' : 'var(--muted)'}}>
<Icon name={ok === false ? 'close' : 'check'} label={content}/>
</span>
</Tooltip>
}
const TYPE_LABELS = {
@ -51,22 +48,23 @@ function groupItemsByType(items) {
}));
}
function PreviewItemTable({items, negative, inverted}) {
function PreviewItemTable({items, negative}) {
if (!items.length) return null;
const columns = TYPE_COLUMNS[items[0].type] || [{key: 'type', header: 'Item'}];
return <Table compact basic='very' size='small' inverted={!!inverted} style={{marginBottom: '0.5em'}}>
<TableHeader>
<TableRow>
{columns.map(col => <TableHeaderCell key={col.key}>{col.header}</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
{items.map((item, i) => <TableRow key={i} negative={negative}>
return <Table style={{marginBottom: '0.5em'}}>
<Table.Header>
<Table.Row>
{columns.map(col => <Table.HeaderCell key={col.key}>{col.header}</Table.HeaderCell>)}
</Table.Row>
</Table.Header>
<Table.Body>
{/* Items being removed take the failed treatment: dashed, in every theme. */}
{items.map((item, i) => <Table.Row key={i} failed={negative}>
{columns.map(col =>
<TableCell key={col.key}>{item[col.key] || ''}</TableCell>
<Table.Cell key={col.key}>{item[col.key] || ''}</Table.Cell>
)}
</TableRow>)}
</TableBody>
</Table.Row>)}
</Table.Body>
</Table>;
}
@ -82,41 +80,44 @@ function BackupDateRow({date, previews, previewsLoaded, onSelect}) {
const mergeHasChanges = hasChanges(mergePreview);
const overwriteHasChanges = hasChanges(overwritePreview);
const noChanges = <span style={{color: 'var(--muted)', fontStyle: 'italic'}}>No changes</span>;
const previewFailed = <Tooltip label='Failed to load preview'>
<span style={{color: 'var(--red)'}}><Icon name='warning sign' label='Failed to load preview'/></span>
</Tooltip>;
let mergeCell;
if (!mergeLoaded) {
mergeCell = <Loader size='mini' active inline/>;
mergeCell = <Loader size='xs'/>;
} else if (mergePreview === null) {
mergeCell = <Popup trigger={<Icon name='warning sign' color='red'/>} content='Failed to load preview'/>;
mergeCell = previewFailed;
} else if (mergeHasChanges) {
mergeCell = <Button size='mini' color='green' onClick={() => onSelect(date, 'merge', mergePreview)}>
<Icon name='plus'/> Merge
</Button>;
mergeCell = <Button size='xs' role='save' icon='plus'
onClick={() => onSelect(date, 'merge', mergePreview)}>Merge</Button>;
} else {
mergeCell = <span style={{color: 'grey', fontStyle: 'italic'}}>No changes</span>;
mergeCell = noChanges;
}
let overwriteCell;
if (!overwriteLoaded) {
overwriteCell = <Loader size='mini' active inline/>;
overwriteCell = <Loader size='xs'/>;
} else if (overwritePreview === null) {
overwriteCell = <Popup trigger={<Icon name='warning sign' color='red'/>} content='Failed to load preview'/>;
overwriteCell = previewFailed;
} else if (overwriteHasChanges) {
overwriteCell = <Button size='mini' color='orange' onClick={() => onSelect(date, 'overwrite', overwritePreview)}>
<Icon name='refresh'/> Overwrite
</Button>;
// Overwrite discards whatever is in the database, so it warns rather than saves.
overwriteCell = <Button size='xs' role='retry' icon='refresh'
onClick={() => onSelect(date, 'overwrite', overwritePreview)}>Overwrite</Button>;
} else {
overwriteCell = <span style={{color: 'grey', fontStyle: 'italic'}}>No changes</span>;
overwriteCell = noChanges;
}
return <TableRow>
<TableCell>{formatDate(date)}</TableCell>
<TableCell>{mergeCell}</TableCell>
<TableCell>{overwriteCell}</TableCell>
</TableRow>;
return <Table.Row>
<Table.Cell>{formatDate(date)}</Table.Cell>
<Table.Cell>{mergeCell}</Table.Cell>
<Table.Cell>{overwriteCell}</Table.Cell>
</Table.Row>;
}
function BackupsModal({open, onClose, fileName, fetchConfigs}) {
const {inverted} = useContext(ThemeContext);
const [dates, setDates] = useState([]);
const [datesLoading, setDatesLoading] = useState(true);
const [previews, setPreviews] = useState({});
@ -202,52 +203,45 @@ function BackupsModal({open, onClose, fileName, fetchConfigs}) {
</Modal.Header>
<Modal.Content>
{applying
? <div style={{textAlign: 'center', padding: '2em'}}>
<Loader active inline='centered'>Applying backup...</Loader>
</div>
? <Loading>Applying backup...</Loading>
: <>
{preview.add.length > 0 && <>
<Header as='h4' color='green'>
<Icon name='plus'/> {preview.add.length} item{preview.add.length !== 1 ? 's' : ''} to add
<Header as='h4' icon='plus' style={{color: 'var(--green)'}}>
{preview.add.length} item{preview.add.length !== 1 ? 's' : ''} to add
</Header>
<div style={{maxHeight: '300px', overflowY: 'auto', marginBottom: '1em'}}>
{groupItemsByType(preview.add).map(group =>
<React.Fragment key={group.type}>
<Header as='h5' inverted={!!inverted}
style={{marginBottom: '0.3em'}}>{group.label}</Header>
<PreviewItemTable items={group.items} inverted={inverted}/>
<Header as='h5' style={{marginBottom: '0.3em'}}>{group.label}</Header>
<PreviewItemTable items={group.items}/>
</React.Fragment>
)}
</div>
</>}
{preview.remove.length > 0 && <>
<Header as='h4' color='red'>
<Icon name='minus'/> {preview.remove.length} item{preview.remove.length !== 1 ? 's' : ''} to
remove
<Header as='h4' icon='minus' style={{color: 'var(--red)'}}>
{preview.remove.length} item{preview.remove.length !== 1 ? 's' : ''} to remove
</Header>
<div style={{maxHeight: '300px', overflowY: 'auto', marginBottom: '1em'}}>
{groupItemsByType(preview.remove).map(group =>
<React.Fragment key={group.type}>
<Header as='h5' inverted={!!inverted}
style={{marginBottom: '0.3em'}}>{group.label}</Header>
<PreviewItemTable items={group.items} negative inverted={inverted}/>
<Header as='h5' style={{marginBottom: '0.3em'}}>{group.label}</Header>
<PreviewItemTable items={group.items} negative/>
</React.Fragment>
)}
</div>
</>}
<p style={{color: 'grey'}}>{preview.unchanged} unchanged
<p style={{color: 'var(--muted)'}}>{preview.unchanged} unchanged
item{preview.unchanged !== 1 ? 's' : ''}</p>
</>
}
</Modal.Content>
<Modal.Actions>
{!applying && <>
<Button onClick={handleBack}>Back</Button>
<Button color='green' onClick={handleApply}>
<Icon name='check'/> Apply
</Button>
<Button role='cancel' onClick={handleBack}>Back</Button>
<Button role='save' icon='check' onClick={handleApply}>Apply</Button>
</>}
</Modal.Actions>
</Modal>;
@ -258,21 +252,19 @@ function BackupsModal({open, onClose, fileName, fetchConfigs}) {
<Modal.Header>Restore Backup: {fileName}</Modal.Header>
<Modal.Content>
{datesLoading
? <div style={{textAlign: 'center', padding: '2em'}}>
<Loader active inline='centered'>Loading backups...</Loader>
</div>
? <Loading>Loading backups...</Loading>
: dates.length === 0
? <p>No backups available for this config.</p>
: <div style={{maxHeight: '400px', overflowY: 'auto'}}>
<Table compact unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell>Date</TableHeaderCell>
<TableHeaderCell>Merge</TableHeaderCell>
<TableHeaderCell>Overwrite</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Merge</Table.HeaderCell>
<Table.HeaderCell>Overwrite</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{dates.map(date =>
<BackupDateRow
key={date}
@ -282,13 +274,13 @@ function BackupsModal({open, onClose, fileName, fetchConfigs}) {
onSelect={handleSelect}
/>
)}
</TableBody>
</Table.Body>
</Table>
</div>
}
</Modal.Content>
<Modal.Actions>
<Button onClick={handleClose}>Close</Button>
<Button role='cancel' onClick={handleClose}>Close</Button>
</Modal.Actions>
</Modal>;
}
@ -318,14 +310,14 @@ function ConfigContentModal({open, onClose, fileName}) {
<Modal.Header>{fileName}</Modal.Header>
<Modal.Content scrolling>
{loading
? <Loader active inline='centered'/>
? <Loading/>
: content
? <pre style={{whiteSpace: 'pre-wrap', wordBreak: 'break-word'}}>{content}</pre>
: <p>Failed to load config contents.</p>
}
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Close</Button>
<Button role='cancel' onClick={onClose}>Close</Button>
</Modal.Actions>
</Modal>;
}
@ -369,20 +361,21 @@ function ConfigTableRow({config, importConfig, saveConfig, fetchConfigs}) {
/>;
}
return <TableRow>
<TableCell><span style={{cursor: 'pointer'}} onClick={() => setContentModalOpen(true)}>{file_name}</span></TableCell>
<TableCell><WarningIcon ok={successful_import}/></TableCell>
<TableCell><WarningIcon ok={valid}/></TableCell>
<TableCell className="hide-on-mobile">
return <Table.Row>
<Table.Cell>
<span style={{cursor: 'pointer'}} onClick={() => setContentModalOpen(true)}>{file_name}</span>
</Table.Cell>
<Table.Cell><WarningIcon ok={successful_import}/></Table.Cell>
<Table.Cell><WarningIcon ok={valid}/></Table.Cell>
<Table.Cell className="hide-on-mobile">
{has_backup_import
? <Button icon size='mini' onClick={() => setBackupsModalOpen(true)}>
<Icon name='undo'/>
</Button>
? <IconButton icon='undo' label='Restore a backup'
onClick={() => setBackupsModalOpen(true)}/>
: null
}
</TableCell>
<TableCell>{importButton}</TableCell>
<TableCell>{saveButton}</TableCell>
</Table.Cell>
<Table.Cell>{importButton}</Table.Cell>
<Table.Cell>{saveButton}</Table.Cell>
{backupsModalOpen && <BackupsModal
open={backupsModalOpen}
onClose={() => setBackupsModalOpen(false)}
@ -394,24 +387,24 @@ function ConfigTableRow({config, importConfig, saveConfig, fetchConfigs}) {
onClose={() => setContentModalOpen(false)}
fileName={file_name}
/>}
</TableRow>
</Table.Row>
}
export function ConfigsTable({configs, loading, importConfig, saveConfig, fetchConfigs}) {
let body = <TableRow>
<TableCell colSpan={6}><TableRowPlaceholder/></TableCell>
</TableRow>
let body = <Table.Row>
<Table.Cell colSpan={6}><Placeholder lines={2}/></Table.Cell>
</Table.Row>
if (loading) {
// Configs are being fetched again.
} else if (configs === undefined) {
body = <TableRow>
<TableCell colSpan={6}>Failed to fetch configs</TableCell>
</TableRow>;
body = <Table.Row>
<Table.Cell colSpan={6}>Failed to fetch configs</Table.Cell>
</Table.Row>;
} else if (configs && Object.keys(configs).length === 0) {
body = <TableRow>
<TableCell colSpan={6}>No configs exist. Try tagging some files.</TableCell>
</TableRow>;
body = <Table.Row>
<Table.Cell colSpan={6}>No configs exist. Try tagging some files.</Table.Cell>
</Table.Row>;
} else if (configs) {
body = Object.entries(configs).map(([key, value]) =>
<ConfigTableRow
@ -424,20 +417,20 @@ export function ConfigsTable({configs, loading, importConfig, saveConfig, fetchC
);
}
return <Table unstackable striped compact>
<TableHeader>
<TableRow>
<TableHeaderCell width={8}>File Name</TableHeaderCell>
<TableHeaderCell width={1}>Imported</TableHeaderCell>
<TableHeaderCell width={1}>Valid</TableHeaderCell>
<TableHeaderCell width={3} className="hide-on-mobile">Restore</TableHeaderCell>
<TableHeaderCell width={1}>Import</TableHeaderCell>
<TableHeaderCell width={1}>Save</TableHeaderCell>
</TableRow>
</TableHeader>
return <Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>File Name</Table.HeaderCell>
<Table.HeaderCell>Imported</Table.HeaderCell>
<Table.HeaderCell>Valid</Table.HeaderCell>
<Table.HeaderCell className="hide-on-mobile">Restore</Table.HeaderCell>
<Table.HeaderCell>Import</Table.HeaderCell>
<Table.HeaderCell>Save</Table.HeaderCell>
</Table.Row>
</Table.Header>
<TableBody>
<Table.Body>
{body}
</TableBody>
</Table.Body>
</Table>
}

View file

@ -1,6 +1,6 @@
import React from "react";
import {Link} from "react-router";
import {Button, Icon, Message} from "semantic-ui-react";
import {Button, Message} from "../ui";
import {useLocalStorage} from "../Common";
import {useExtensionInstalled} from "../../hooks/customHooks";
import {isExtensionSupportedBrowser} from "./browserDetect";
@ -25,18 +25,19 @@ export function ExtensionInstallSuggestion() {
// Also skip on browsers that cannot install the extension (e.g. Safari).
if (installed !== false || dismissed || !isExtensionSupportedBrowser()) return null;
return <Message info icon onDismiss={() => setDismissed(true)}>
<Icon name='puzzle piece'/>
<Message.Content>
<Message.Header>Install the WROLPi browser extension</Message.Header>
<p>
Send pages, videos, and feeds to this WROLPi straight from any
tab. Open-source and not distributed via the official browser
stores.
</p>
<Button as={Link} to='/admin/extension' primary size='small'>
Open install page
</Button>
</Message.Content>
return <Message
kind='info'
icon='puzzle piece'
title='Install the WROLPi browser extension'
onDismiss={() => setDismissed(true)}
>
<p>
Send pages, videos, and feeds to this WROLPi straight from any
tab. Open-source and not distributed via the official browser
stores.
</p>
<Button component={Link} to='/admin/extension' role='primary' size='xs'>
Open install page
</Button>
</Message>;
}

View file

@ -1,7 +1,5 @@
import React from "react";
import {Button, Header, Icon, Segment} from "../Theme";
import {Input, Message} from "semantic-ui-react";
import {ThemeContext} from "../../contexts/contexts";
import {ActionInput, Button, Header, Message, Panel, Stack} from "../ui";
import {detectBrowser} from "./browserDetect";
// The WROLPi browser extension is distributed off-store: Chrome users
@ -34,49 +32,46 @@ function DestinationHint() {
// Fall through silently — the user can still copy manually.
}
};
return <Segment style={{marginBottom: '1em'}}>
<Header as='h4'>
<Icon name='globe'/>
This WROLPi's URL
</Header>
<p style={{color: 'grey'}}>
return <Panel style={{marginBottom: '1em'}}>
<Header as='h4' icon='globe'>This WROLPi's URL</Header>
<p style={{color: 'var(--muted)'}}>
After installing the extension, paste this URL into the
destination field on the extension's options page.
</p>
<Input
fluid
<ActionInput
readOnly
value={origin}
action={
<Button
icon={copied ? 'check' : 'copy'}
color={copied ? 'green' : null}
content={copied ? 'Copied' : 'Copy'}
role={copied ? 'save' : 'cancel'}
onClick={onCopy}
/>
>
{copied ? 'Copied' : 'Copy'}
</Button>
}
/>
</Segment>;
</Panel>;
}
function FirefoxCard({metadata, version}) {
const file = (metadata && metadata.files && metadata.files['wrolpi-firefox.xpi']) || {};
const available = !!file.available;
return <Segment>
<Header as='h3'>
<Icon name='firefox'/>
return <Panel>
<Header as='h3' icon='firefox'>
Firefox{version ? ` — v${version}` : ''}
</Header>
<p>One-click install. Mozilla has signed this build.</p>
<Button
primary
as='a'
role='primary'
component='a'
href={FIREFOX_XPI_PATH}
disabled={!available}
icon='download'
content={available ? `Install for Firefox (${formatSize(file.size_bytes)})` : 'Not yet available'}
/>
<p style={{marginTop: '1em', color: 'grey'}}>
>
{available ? `Install for Firefox (${formatSize(file.size_bytes)})` : 'Not yet available'}
</Button>
<p style={{marginTop: '1em', color: 'var(--muted)'}}>
Firefox will ask you to confirm the install. Accept the prompt.
</p>
<Header as='h4' style={{marginTop: '1.5em'}}>After installing</Header>
@ -84,15 +79,14 @@ function FirefoxCard({metadata, version}) {
<li>Open the extension's <strong>Options</strong> page (right-click the toolbar icon &rarr; Manage Extension &rarr; Options) and add this WROLPi as a destination. Click <strong>Test</strong> to grant API access.</li>
<li>Click the extension icon in the toolbar &rarr; the permission dropdown &rarr; <strong>Always Allow on this site</strong>. Firefox requires this second click in addition to the Test grant — without it, the extension can talk to your WROLPi but can't mark its tabs as connected.</li>
</ol>
</Segment>;
</Panel>;
}
function ChromiumCard({metadata, version}) {
const file = (metadata && metadata.files && metadata.files['wrolpi-chrome.zip']) || {};
const available = !!file.available;
return <Segment>
<Header as='h3'>
<Icon name='chrome'/>
return <Panel>
<Header as='h3' icon='chrome'>
Chrome / Brave / Edge{version ? ` — v${version}` : ''}
</Header>
<p>
@ -100,14 +94,15 @@ function ChromiumCard({metadata, version}) {
outside the Web Store, so we sideload via the built-in developer flow.
</p>
<Button
primary
as='a'
role='primary'
component='a'
href={CHROME_ZIP_PATH}
disabled={!available}
icon='download'
content={available ? `Download .zip (${formatSize(file.size_bytes)})` : 'Not yet available'}
download
/>
>
{available ? `Download .zip (${formatSize(file.size_bytes)})` : 'Not yet available'}
</Button>
<Header as='h4' style={{marginTop: '1.5em'}}>Install steps</Header>
<ol style={{lineHeight: 1.7, paddingLeft: '1.2em'}}>
<li>Download the <code>.zip</code> above and extract it to a folder you'll keep around.</li>
@ -115,28 +110,27 @@ function ChromiumCard({metadata, version}) {
<li>Toggle <strong>Developer mode</strong> on (top-right).</li>
<li>Click <strong>Load unpacked</strong> and pick the extracted folder.</li>
</ol>
<p style={{color: 'grey'}}>
<p style={{color: 'var(--muted)'}}>
The extension stays installed across browser restarts. Don't delete the
extracted folder — the browser loads from it directly.
</p>
</Segment>;
</Panel>;
}
function UnknownCard() {
return <Segment>
return <Panel>
<Header as='h3'>Unsupported browser</Header>
<p>
The WROLPi extension supports Chrome, Brave, Edge, and Firefox. Open
this page in one of those browsers to install.
</p>
</Segment>;
</Panel>;
}
export function ExtensionPage() {
const [metadata, setMetadata] = React.useState(null);
const [error, setError] = React.useState(null);
const browser = detectBrowser();
const {s} = React.useContext(ThemeContext);
React.useEffect(() => {
let cancelled = false;
@ -148,47 +142,43 @@ export function ExtensionPage() {
}, []);
if (error) {
return <Segment>
<Message negative>
<Message.Header>Couldn't load extension info</Message.Header>
<p>{error}</p>
</Message>
</Segment>;
return <Message kind='error' title="Couldn't load extension info">{error}</Message>;
}
const versions = (metadata && metadata.versions) || {};
const anyAvailable = metadata && Object.values(metadata.files || {}).some(f => f.available);
return <>
<Header as='h1'>Browser Extension</Header>
<p {...s}>
Install the WROLPi browser extension to send pages, videos, and feeds to
this WROLPi from any tab. The extension is open-source and not distributed
via official browser stores — it ships with each WROLPi release.
</p>
return <Stack gap='md'>
<div>
<Header as='h1'>Browser Extension</Header>
<p>
Install the WROLPi browser extension to send pages, videos, and feeds to
this WROLPi from any tab. The extension is open-source and not distributed
via official browser stores — it ships with each WROLPi release.
</p>
</div>
<DestinationHint/>
{metadata && !anyAvailable && <Message warning>
<Message.Header>Extension binaries not yet installed</Message.Header>
<p>
The extension binaries aren't on this WROLPi yet. They ship with the
next release; pull the latest and they'll appear here.
</p>
{metadata && !anyAvailable && <Message kind='warning' title='Extension binaries not yet installed'>
The extension binaries aren't on this WROLPi yet. They ship with the
next release; pull the latest and they'll appear here.
</Message>}
{browser === 'firefox' && <FirefoxCard metadata={metadata} version={versions.firefox}/>}
{browser === 'chromium' && <ChromiumCard metadata={metadata} version={versions.chrome}/>}
{browser === 'unknown' && <UnknownCard/>}
<Segment basic style={{marginTop: '2em'}}>
<Header as='h4'>Both browsers, just in case</Header>
<p style={{color: 'grey'}}>
You can install for a different browser too — useful if you sync
between machines.
</p>
<Stack gap='sm' style={{marginTop: '1em'}}>
<div>
<Header as='h4' dividing>Both browsers, just in case</Header>
<p style={{color: 'var(--muted)'}}>
You can install for a different browser too — useful if you sync
between machines.
</p>
</div>
{browser !== 'firefox' && <FirefoxCard metadata={metadata} version={versions.firefox}/>}
{browser !== 'chromium' && <ChromiumCard metadata={metadata} version={versions.chrome}/>}
</Segment>
</>;
</Stack>
</Stack>;
}

View file

@ -25,10 +25,14 @@ export interface MessageProps {
kind?: MessageKind;
title?: React.ReactNode;
children?: React.ReactNode;
/** Semantic icon name or a Tabler component, shown to the left of the text. */
icon?: string | React.ComponentType<any>;
/** Renders a dismiss button. Omit for messages the user cannot clear. */
onDismiss?: () => void;
className?: string;
}
export function Message({kind = 'info', title, children, className}: MessageProps) {
export function Message({kind = 'info', title, children, icon, onDismiss, className}: MessageProps) {
return <div
// Errors and warnings interrupt; info and success are announced politely.
role={kind === 'error' ? 'alert' : 'status'}
@ -36,8 +40,21 @@ export function Message({kind = 'info', title, children, className}: MessageProp
.filter(Boolean).join(' ')}
style={{['--message-color' as string]: messageColors[kind]}}
>
{title && <div className='wrolpi-message-title'>{title}</div>}
{children && <div className='wrolpi-message-body'>{children}</div>}
{icon && <div className='wrolpi-message-icon'>
{typeof icon === 'string' ? <Icon name={icon} size={20}/> : <Icon component={icon} size={20}/>}
</div>}
<div className='wrolpi-message-content'>
{title && <div className='wrolpi-message-title'>{title}</div>}
{children && <div className='wrolpi-message-body'>{children}</div>}
</div>
{onDismiss && <button
type='button'
className='wrolpi-message-dismiss'
aria-label='Dismiss'
onClick={onDismiss}
>
<Icon name='close' size={16}/>
</button>}
</div>
}
@ -137,6 +154,28 @@ export function Loader({size = 'sm', label}: LoaderProps) {
return <MLoader size={size} color='var(--blue)' aria-label={label ?? 'Loading'}/>
}
export interface LoadingProps {
/** What is being waited on: "Loading backups…". Also the accessible name. */
children?: React.ReactNode;
size?: LoaderProps['size'];
/** Vertical padding around the loader. */
padding?: number | string;
}
/**
* A centered loader with a caption, for a region that has nothing to show yet.
* Replaces Semantic's `<Loader active inline='centered'>`, which 19 call sites
* used with their own wrapper div.
*/
export function Loading({children, size = 'sm', padding = '2em'}: LoadingProps) {
return <div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding,
}}>
<Loader size={size} label={typeof children === 'string' ? children : undefined}/>
{children && <div style={{fontSize: 13, color: 'var(--muted)'}}>{children}</div>}
</div>
}
/** Placeholder for content that has not arrived. Replaces Semantic's Placeholder. */
export function Placeholder({lines = 3, height = 12}: {lines?: number; height?: number}) {
return <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>

View file

@ -58,6 +58,27 @@ export function Toggle({style, className, ...props}: ToggleProps) {
/>
}
export interface ActionInputProps extends React.ComponentProps<typeof MTextInput> {
/** Button (or buttons) attached to the input's trailing edge. */
action?: React.ReactNode;
}
/**
* A text input with a button joined to its right edge. Replaces Semantic's
* `<Input action={...}/>`.
*
* The two share one outline rather than sitting side by side, so the pair reads
* as a single control — the input's own right border is dropped and the button
* supplies the edge.
*/
export function ActionInput({action, className, ...props}: ActionInputProps) {
if (!action) return <MTextInput className={className} {...props}/>
return <div className={['wrolpi-action-input', className].filter(Boolean).join(' ')}>
<MTextInput {...props}/>
{action}
</div>
}
export {
MTextInput as TextInput,
MTextarea as Textarea,

View file

@ -6,17 +6,76 @@ import {Button} from './Button';
* Overlays: modals, confirmations, tooltips, menus.
*/
export type ModalProps = React.ComponentProps<typeof MModal>;
/*
* Modals.
*
* Semantic's compound shape (`Modal.Header` / `Modal.Content` / `Modal.Actions`)
* is kept because 34 call sites are written against it. The subcomponents are
* markers: Modal reads them out of its children and places each in the right
* slot, so the children stay in source order at the call site.
*/
const ModalHeader = ({children}: {children?: React.ReactNode}) => <>{children}</>;
ModalHeader.displayName = 'Modal.Header';
const ModalContent = ({children}: {children?: React.ReactNode; scrolling?: boolean}) => <>{children}</>;
ModalContent.displayName = 'Modal.Content';
const ModalActions = ({children}: {children?: React.ReactNode}) => <>{children}</>;
ModalActions.displayName = 'Modal.Actions';
// Semantic's size names, mapped onto Mantine's scale.
const modalSizes: Record<string, string> = {
mini: 'xs',
tiny: 'sm',
small: 'md',
large: 'lg',
fullscreen: '100%',
};
export interface ModalProps extends Omit<React.ComponentProps<typeof MModal>, 'opened' | 'size'> {
/** Semantic's name for `opened`. Either works. */
open?: boolean;
opened?: boolean;
/** A title given directly, instead of a `Modal.Header` child. */
title?: React.ReactNode;
/** Semantic size name (mini/tiny/small/large/fullscreen) or a Mantine size. */
size?: string | number;
/** Accepted and ignored: the close button is always shown. */
closeIcon?: boolean;
}
function ModalBase({open, opened, size, closeIcon, title, children, ...props}: ModalProps) {
const slots: Record<string, React.ReactNode[]> = {header: [], actions: [], body: []};
React.Children.forEach(children, child => {
const type = React.isValidElement(child) ? child.type : undefined;
if (type === ModalHeader) slots.header.push((child as React.ReactElement).props.children);
else if (type === ModalActions) slots.actions.push((child as React.ReactElement).props.children);
else slots.body.push(child);
});
export function Modal(props: ModalProps) {
return <MModal
opened={opened ?? open ?? false}
centered
size={typeof size === 'string' ? (modalSizes[size] ?? size) : size}
title={slots.header.length ? slots.header : title}
// Flat surfaces: the overlay separates the modal from the page, not a shadow.
overlayProps={{backgroundOpacity: 0.55, blur: 0}}
{...props}
/>
>
{slots.body}
{slots.actions.length > 0 && <div className='wrolpi-modal-actions'>{slots.actions}</div>}
</MModal>
}
export const Modal = Object.assign(ModalBase, {
Header: ModalHeader,
Content: ModalContent,
Actions: ModalActions,
// Mantine's own names, for new code.
Body: ModalContent,
});
export interface ConfirmProps {
open: boolean;
title?: React.ReactNode;

View file

@ -1,12 +1,49 @@
import React from 'react';
import {Card as MCard, Tabs as MTabs, Accordion as MAccordion, Breadcrumbs} from '@mantine/core';
import {Icon} from './Icon';
/*
* Surfaces and structure: panels, cards, statistics, tabs, accordions,
* Surfaces and structure: headers, panels, cards, statistics, tabs, accordions,
* breadcrumbs. Elevation is expressed with borders and background steps —
* never a shadow (shadows are zeroed in the Mantine bridge).
*/
// ------------------------------------------------------------------- Headers
export type HeaderLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5';
export interface HeaderProps extends Omit<React.HTMLAttributes<HTMLHeadingElement>, 'color'> {
/** Heading level. Also the visual size — pick it for the outline, not the look. */
as?: HeaderLevel;
/** Semantic icon name or a Tabler component, shown before the text. */
icon?: string | React.ComponentType<any>;
/** Secondary line below, in muted text. */
subheader?: React.ReactNode;
/** Hairline rule underneath, separating the section from what follows. */
dividing?: boolean;
}
/**
* A section heading. Named and shaped like Semantic's Header (`as`, `icon`,
* `subheader`, `dividing`) so the app's 47 call sites migrate by import.
*
* Sizes come from ui.css, keyed on the level, rather than each call site
* choosing — that is what keeps the type scale a scale.
*/
export function Header({as = 'h3', icon, subheader, dividing, className, children, ...props}: HeaderProps) {
const Tag = as;
return <div className={['wrolpi-header', dividing ? 'wrolpi-header-dividing' : '', className]
.filter(Boolean).join(' ')}>
<Tag className={`wrolpi-header-text wrolpi-header-${as}`} {...props}>
{icon && (typeof icon === 'string'
? <Icon name={icon} size='medium'/>
: <Icon component={icon} size='medium'/>)}
<span>{children}</span>
</Tag>
{subheader && <div className='wrolpi-header-sub'>{subheader}</div>}
</div>
}
// -------------------------------------------------------------------- Panels
export interface PanelProps extends React.HTMLAttributes<HTMLDivElement> {

View file

@ -2,6 +2,7 @@ import React, {useContext} from 'react';
import {ThemeContext} from '../../contexts/contexts';
import {systemTheme, themeChoices} from '../../themes/names';
import {Icon} from './Icon';
import {Toggle} from './Inputs';
/*
* The theme picker.
@ -15,29 +16,52 @@ export interface ThemePickerProps {
withDescriptions?: boolean;
}
/**
* The media filter toggle for the current theme.
*
* Rendered only by themes that offer a filter, because there is nothing to say
* about it otherwise — light and dark have no monochrome media treatment.
*/
export function MediaFilterToggle() {
const {mediaFilter, mediaFilterEnabled, setMediaFilterEnabled} = useContext(ThemeContext);
if (!mediaFilter) return null;
return <div className='wrolpi-media-filter-setting'>
<Toggle
label={mediaFilter.label}
description={mediaFilter.description}
checked={mediaFilterEnabled}
onChange={event => setMediaFilterEnabled(event.currentTarget.checked)}
/>
</div>
}
export function ThemePicker({withDescriptions = true}: ThemePickerProps) {
const {savedTheme, setTheme} = useContext(ThemeContext);
// A user who has never chosen is following the system preference.
const selected = savedTheme ?? systemTheme;
return <div role='radiogroup' aria-label='Theme' className='wrolpi-theme-picker'>
{themeChoices.map(choice => {
const active = choice.value === selected;
return <button
key={choice.value}
type='button'
role='radio'
aria-checked={active}
className={`wrolpi-theme-option${active ? ' wrolpi-theme-option-active' : ''}`}
onClick={() => setTheme(choice.value)}
>
<span className='wrolpi-theme-option-name'>
<Icon name={choice.icon}/>
{choice.text}
</span>
{withDescriptions &&
<span className='wrolpi-theme-option-description'>{choice.description}</span>}
</button>
})}
</div>
return <>
<div role='radiogroup' aria-label='Theme' className='wrolpi-theme-picker'>
{themeChoices.map(choice => {
const active = choice.value === selected;
return <button
key={choice.value}
type='button'
role='radio'
aria-checked={active}
className={`wrolpi-theme-option${active ? ' wrolpi-theme-option-active' : ''}`}
onClick={() => setTheme(choice.value)}
>
<span className='wrolpi-theme-option-name'>
<Icon name={choice.icon}/>
{choice.text}
</span>
{withDescriptions &&
<span className='wrolpi-theme-option-description'>{choice.description}</span>}
</button>
})}
</div>
<MediaFilterToggle/>
</>
}

View file

@ -110,6 +110,56 @@ html[data-theme="amber"] .wrolpi-theme-option-active {
line-height: 1.4;
}
/* Separated from the theme grid: it configures the chosen theme, it is not a choice. */
.wrolpi-media-filter-setting {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
/* ---------------------------------------------------------------- Modals */
/*
* Actions sit below the body, separated by a hairline rather than a raised bar.
* Right-aligned, so the confirming action lands where the eye finishes reading.
*/
.wrolpi-modal-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 10px;
/* Bleed back out through the modal body's own padding so the rule spans the
full width; -1 * whatever Mantine padded the body with. */
margin: 18px calc(var(--mantine-spacing-md) * -1) calc(var(--mantine-spacing-md) * -1);
padding: 12px var(--mantine-spacing-md);
border-top: 1px solid var(--border);
}
/* ---------------------------------------------------------- Action inputs */
/*
* Input and button share one outline: the input gives up its right border and
* the button's left border becomes the seam between them.
*/
.wrolpi-action-input {
display: flex;
align-items: stretch;
width: 100%;
}
.wrolpi-action-input > .mantine-TextInput-root {
flex: 1;
min-width: 0;
}
.wrolpi-action-input .mantine-TextInput-input {
border-right-width: 0;
}
.wrolpi-action-input > :not(.mantine-TextInput-root) {
flex: none;
}
/* --------------------------------------------------------------- Switches */
/*
* Mantine's unchecked track is a gray from its own palette, which would put a
@ -165,9 +215,69 @@ html[data-theme="night"] .wrolpi-label {
border-color: var(--label-color);
}
/* ---------------------------------------------------------------- Headers */
.wrolpi-header {
margin: 0 0 10px;
}
.wrolpi-header-dividing {
border-bottom: 1px solid var(--border);
padding-bottom: 6px;
}
.wrolpi-header-text {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
/*
* Stated explicitly because semantic.min.css sets `h1,h2,h3,h4,h5 { font-family:
* Lato }` and loads after Mantine's element rule, so headings would ignore the
* theme's body face — visible in amber, where the body is mono and headings were
* not. A class outranks the element selector. Can go once Semantic is gone.
*/
font-family: var(--font-body);
font-weight: 600;
line-height: 1.25;
color: var(--text);
text-wrap: balance;
}
/* The scale lives here so no call site invents a size of its own. */
.wrolpi-header-h1 {
font-size: 26px;
}
.wrolpi-header-h2 {
font-size: 21px;
}
.wrolpi-header-h3 {
font-size: 17px;
}
.wrolpi-header-h4 {
font-size: 14px;
}
.wrolpi-header-h5 {
font-size: 13px;
letter-spacing: 0.02em;
}
.wrolpi-header-sub {
font-size: 12px;
color: var(--muted);
margin-top: 3px;
}
/* --------------------------------------------------------------- Messages */
.wrolpi-message {
display: flex;
align-items: flex-start;
gap: 10px;
border: 1px solid var(--border);
border-left: 3px solid var(--message-color, var(--border));
background: var(--panel);
@ -175,6 +285,39 @@ html[data-theme="night"] .wrolpi-label {
font-size: 13px;
}
.wrolpi-message-content {
flex: 1;
min-width: 0;
}
/* The icon repeats what the border color already says, so it takes that color. */
.wrolpi-message-icon {
color: var(--message-color, var(--text));
display: flex;
padding-top: 1px;
}
.wrolpi-message-dismiss {
background: none;
border: none;
padding: 0;
color: var(--muted);
cursor: pointer;
display: flex;
/* Widen the tap target past the glyph without moving it. */
margin: -6px -6px -6px 0;
padding: 6px;
}
.wrolpi-message-dismiss:hover {
color: var(--text);
}
.wrolpi-message-dismiss:focus-visible {
outline: 2px solid var(--blue);
outline-offset: -2px;
}
.wrolpi-message-title {
font-weight: 600;
margin-bottom: 2px;

View file

@ -7,8 +7,10 @@ import {ThemeContext} from '../../contexts/contexts';
import {cssVariablesResolver, mantineTheme, semanticColorNames} from '../../themes/mantine';
import {themeChoices} from '../../themes/names';
import {
ActionInput,
Button,
Confirm,
Header,
Icon,
IconButton,
Label,
@ -129,6 +131,78 @@ describe('Message', () => {
expect(screen.getByRole('alert')).toHaveClass('wrolpi-message-error');
});
it('dismisses when asked', async () => {
const onDismiss = jest.fn();
renderUI(<Message title='Install the extension' onDismiss={onDismiss}/>);
await userEvent.click(screen.getByRole('button', {name: 'Dismiss'}));
expect(onDismiss).toHaveBeenCalled();
});
it('offers no dismiss button when the message cannot be cleared', () => {
renderUI(<Message title='Refresh running'/>);
expect(screen.queryByRole('button', {name: 'Dismiss'})).not.toBeInTheDocument();
});
it('renders a leading icon when given one', () => {
const {container} = renderUI(<Message icon='puzzle piece' title='Extension'/>);
expect(container.querySelector('.wrolpi-message-icon svg')).toBeInTheDocument();
});
});
describe('Header', () => {
it('renders the requested heading level', () => {
renderUI(<Header as='h1'>Browser Extension</Header>);
expect(screen.getByRole('heading', {level: 1, name: 'Browser Extension'})).toBeInTheDocument();
});
it('defaults to h3 so a call site that omits the level still nests sanely', () => {
renderUI(<Header>Firefox</Header>);
expect(screen.getByRole('heading', {level: 3, name: 'Firefox'})).toBeInTheDocument();
});
it('takes its size from the level, not from the call site', () => {
// The class is what ui.css keys the type scale on; a call site passing its own
// font-size is the thing this component exists to prevent.
const {container} = renderUI(<Header as='h4'>Install steps</Header>);
expect(container.querySelector('.wrolpi-header-h4')).toBeInTheDocument();
});
it('renders an icon and a subheader', () => {
const {container} = renderUI(<Header icon='globe' subheader='Paste this into the extension'>
This WROLPi's URL
</Header>);
expect(container.querySelector('svg')).toBeInTheDocument();
expect(screen.getByText('Paste this into the extension')).toBeInTheDocument();
});
});
describe('ActionInput', () => {
it('joins the input and its action into one control', () => {
const {container} = renderUI(
<ActionInput label='URL' value='https://wrolpi.local' readOnly
action={<Button role='cancel'>Copy</Button>}/>
);
expect(container.querySelector('.wrolpi-action-input')).toBeInTheDocument();
expect(screen.getByRole('textbox', {name: 'URL'})).toHaveValue('https://wrolpi.local');
expect(screen.getByRole('button', {name: 'Copy'})).toBeInTheDocument();
});
it('is a plain input when no action is given', () => {
const {container} = renderUI(<ActionInput label='URL'/>);
expect(container.querySelector('.wrolpi-action-input')).not.toBeInTheDocument();
expect(screen.getByRole('textbox', {name: 'URL'})).toBeInTheDocument();
});
});
describe('Progress', () => {
@ -248,7 +322,13 @@ describe('Toggle', () => {
describe('ThemePicker', () => {
const renderPicker = (themeContext = {}) => {
const setTheme = jest.fn();
const value = {savedTheme: null, setTheme, ...themeContext};
const value = {
savedTheme: null,
setTheme,
mediaFilterEnabled: false,
setMediaFilterEnabled: jest.fn(),
...themeContext,
};
render(
<MantineProvider theme={mantineTheme} cssVariablesResolver={cssVariablesResolver}>
<ThemeContext.Provider value={value}><ThemePicker/></ThemeContext.Provider>
@ -294,6 +374,39 @@ describe('ThemePicker', () => {
expect(screen.getByText(/night vision/i)).toBeInTheDocument();
});
it('offers the media filter toggle in a theme that has one', () => {
renderPicker({
theme: 'night',
mediaFilter: {id: 'night-red', defaultOn: true, label: 'Filter media to red',
description: 'Videos, images, documents, and maps are remapped to red.'},
mediaFilterEnabled: true,
});
expect(screen.getByRole('switch', {name: /filter media to red/i})).toBeChecked();
});
it('offers no toggle in a theme with no filter to offer', () => {
// Light and dark have no monochrome media treatment, so there is nothing to say.
renderPicker({theme: 'light', mediaFilter: undefined, mediaFilterEnabled: false});
expect(screen.queryByRole('switch')).not.toBeInTheDocument();
});
it('turns the filter off when the user flips the toggle', async () => {
const setMediaFilterEnabled = jest.fn();
renderPicker({
theme: 'night',
mediaFilter: {id: 'night-red', defaultOn: true, label: 'Filter media to red',
description: 'Videos, images, documents, and maps are remapped to red.'},
mediaFilterEnabled: true,
setMediaFilterEnabled,
});
await userEvent.click(screen.getByRole('switch', {name: /filter media to red/i}));
expect(setMediaFilterEnabled).toHaveBeenCalledWith(false);
});
});
describe('Confirm', () => {

View file

@ -39,11 +39,8 @@
"src/components/VideoPlayer.js",
"src/components/Videos.js",
"src/components/Zim.js",
"src/components/admin/Configs.js",
"src/components/admin/ControllerPage.js",
"src/components/admin/Downloads.js",
"src/components/admin/ExtensionInstallSuggestion.js",
"src/components/admin/ExtensionPage.js",
"src/components/admin/Settings.js",
"src/components/admin/Status.js",
"src/components/calculators/DriveCalculator.js",

View file

@ -6,7 +6,9 @@
import React, {createContext, useContext} from 'react';
import {render} from '@testing-library/react';
import {BrowserRouter} from 'react-router';
import {MantineProvider} from '@mantine/core';
import {MediaContextProvider, ThemeContext} from './contexts/contexts';
import {cssVariablesResolver, mantineTheme} from './themes/mantine';
// Mock FileWorkerStatusContext for tests - avoids API calls during testing
const MockFileWorkerStatusContext = createContext(null);
@ -75,6 +77,10 @@ export function renderWithProviders(
theme: inverted ? 'dark' : 'light',
isDark: inverted,
savedTheme: null,
// Media filtering is off by default here; a test that needs it sets these.
mediaFilter: undefined,
mediaFilterEnabled: false,
setMediaFilterEnabled: jest.fn(),
setTheme: jest.fn(),
setDarkTheme: jest.fn(),
setLightTheme: jest.fn(),
@ -83,13 +89,21 @@ export function renderWithProviders(
};
function Wrapper({children}) {
// MantineProvider, configured exactly as ThemeProvider configures it: components
// from src/components/ui render Mantine internals and need it in the tree.
const content = (
<BrowserRouter>
<MockFileWorkerStatusProvider>
<ThemeContext.Provider value={defaultThemeContext}>
{children}
</ThemeContext.Provider>
</MockFileWorkerStatusProvider>
<MantineProvider
theme={mantineTheme}
cssVariablesResolver={cssVariablesResolver}
forceColorScheme={inverted ? 'dark' : 'light'}
>
<MockFileWorkerStatusProvider>
<ThemeContext.Provider value={defaultThemeContext}>
{children}
</ThemeContext.Provider>
</MockFileWorkerStatusProvider>
</MantineProvider>
</BrowserRouter>
);

View file

@ -32,6 +32,29 @@ export function MediaFilterDefs() {
<feFuncR type='gamma' amplitude='1' exponent='0.65' offset='0'/>
</feComponentTransfer>
</filter>
{/*
Amber: the same luminance collapse, then tinted to the theme's amber
(#ff9500) by scaling each channel to that hue's ratios — red at full,
green at 0.584, blue at zero. Amber carries far more luminance than
red, so it needs a gentler lift; 0.85 keeps highlights from clipping
to a flat wash.
This is opt-in: amber is a look, not a night-vision aid.
*/}
<filter id='wrolpi-amber-mono' colorInterpolationFilters='sRGB'>
<feColorMatrix
type='matrix'
values='0.2126 0.7152 0.0722 0 0
0.1242 0.4177 0.0422 0 0
0 0 0 0 0
0 0 0 1 0'
/>
<feComponentTransfer>
<feFuncR type='gamma' amplitude='1' exponent='0.85' offset='0'/>
<feFuncG type='gamma' amplitude='1' exponent='0.85' offset='0'/>
</feComponentTransfer>
</filter>
</defs>
</svg>
}

View file

@ -1,4 +1,4 @@
import {SavedThemeName, ThemeName} from '../types/theme';
import {SavedThemeName, ThemeMediaFilter, ThemeName} from '../types/theme';
/*
* Theme names and the choices offered by the pickers.
@ -29,6 +29,62 @@ export const isDarkTheme = (theme: ThemeName): boolean => darkThemes.includes(th
export const isThemeName = (value: unknown): value is ThemeName =>
themeNames.includes(value as ThemeName);
/*
* Media filtering.
*
* Images, video, PDFs, embedded pages, and the map canvas cannot consume theme
* tokens, so a monochrome theme can pass them through an SVG color matrix
* instead (see MediaFilterDefs.tsx for the filters, tokens.css for the rule).
*
* A theme declares which filter it uses and whether it is on to begin with; the
* user can then turn it on or off for that theme. Night defaults to on — an
* unfiltered thumbnail undoes dark adaptation, which is the whole point of the
* mode — and amber defaults to off, since it is a look rather than a night-vision
* aid. Neither is forced: some users want their media tinted to match, some
* want to see the actual image.
*
* The choice is stored per theme, so turning it off in amber does not disarm it
* in night.
*/
export const themeMediaFilters: Partial<Record<ThemeName, ThemeMediaFilter>> = {
[nightTheme]: {
id: 'night-red',
defaultOn: true,
label: 'Filter media to red',
description: 'Videos, images, documents, and maps are remapped to red. Turning this off '
+ 'shows their real colors, which will spoil your night vision.',
},
[amberTheme]: {
id: 'amber-mono',
defaultOn: false,
label: 'Filter media to amber',
description: 'Videos, images, documents, and maps are remapped to amber, matching the '
+ 'interface. Off by default so media keeps its real colors.',
},
};
/** The filter a theme offers, or undefined when it has none to offer. */
export const themeMediaFilter = (theme: ThemeName): ThemeMediaFilter | undefined =>
themeMediaFilters[theme];
export const mediaFilterSessionKey = 'media-filter';
/**
* Resolve the filter id to stamp on `<html>` — '' when nothing should be filtered.
*
* `overrides` is the stored map of theme name to boolean; a theme missing from it
* has never been changed and follows its own default.
*/
export const resolveMediaFilter = (
theme: ThemeName,
overrides: Partial<Record<ThemeName, boolean>>,
): string => {
const filter = themeMediaFilters[theme];
if (!filter) return '';
const enabled = overrides[theme] ?? filter.defaultOn;
return enabled ? filter.id : '';
}
export interface ThemeChoice {
value: SavedThemeName;
text: string;
@ -52,12 +108,13 @@ export const themeChoices: ThemeChoice[] = [
text: 'Night',
icon: 'eye',
description: 'Red only, to preserve your night vision in the dark. Videos, documents, ' +
'and maps are filtered to red as well.',
'and maps are filtered to red as well, unless you turn that off.',
},
{
value: amberTheme,
text: 'Amber',
icon: 'terminal',
description: 'Monochrome amber, like a classic terminal.',
description: 'Monochrome amber, like a classic terminal. Media keeps its real colors '
+ 'unless you ask for it to be tinted too.',
},
];

View file

@ -169,15 +169,25 @@ body {
/* ------------------------------------------------------------------------- */
/*
* Videos, images, PDFs, embedded pages, and the map canvas cannot consume
* tokens, so night mode passes them through an SVG color matrix that maps
* luminance onto the red channel and drives green and blue to zero. Nothing
* a user opens can break their dark adaptation.
* tokens, so a theme can pass them through an SVG color matrix instead. Night
* maps luminance onto the red channel so nothing a user opens can break their
* dark adaptation; amber tints media to match the interface.
*
* This targets the element types rather than an opt-in class on purpose: night
* mode has to fail safe. A library of thousands of files reaches the screen
* through many components, and one that forgot to opt in would undo half an
* hour of dark adaptation. `.media` stays available for a wrapper that needs
* filtering as a unit (a player with custom controls, say).
* These rules key on `data-media-filter`, not `data-theme`, because filtering is
* a per-theme setting the user controls rather than a property of the theme's
* palette: night is filtered unless turned off, amber is unfiltered unless
* turned on. An empty or absent attribute filters nothing, so light and dark —
* which offer no filter — match no rule at all. ThemeProvider stamps the
* attribute, and index.html stamps it before first paint (an unfiltered flash of
* thumbnails would cost the user their dark adaptation before React even loads).
*
* The selectors target element types rather than an opt-in class on purpose:
* filtering has to fail safe. A library of thousands of files reaches the
* screen through many components, and one that forgot to opt in would undo half
* an hour of dark adaptation. `.media` stays available for a wrapper that needs
* filtering as a unit (a player with custom controls, say), and
* `.night-unfiltered` opts a single element out — for media whose real colors
* are the point, like the side-by-side comparison on /theme-sample.
*
* Only leaf media is filtered, never an app-level ancestor: a CSS filter
* creates a containing block, which would break `position: fixed` descendants
@ -186,14 +196,22 @@ body {
*
* Filter definitions live in <MediaFilterDefs/> (mounted once by App).
*/
html[data-theme="night"] :is(img, video, canvas, iframe, embed, object, .media):not(.night-unfiltered) {
html[data-media-filter="night-red"] :is(img, video, canvas, iframe, embed, object, .media):not(.night-unfiltered) {
filter: url(#wrolpi-night-red);
}
html[data-media-filter="amber-mono"] :is(img, video, canvas, iframe, embed, object, .media):not(.night-unfiltered) {
filter: url(#wrolpi-amber-mono);
}
/*
* A filter on an ancestor stops applying once the browser promotes a video to
* native fullscreen, so the filter is restated on the fullscreened element.
*/
html[data-theme="night"] :fullscreen:not(.night-unfiltered) {
html[data-media-filter="night-red"] :fullscreen:not(.night-unfiltered) {
filter: url(#wrolpi-night-red);
}
html[data-media-filter="amber-mono"] :fullscreen:not(.night-unfiltered) {
filter: url(#wrolpi-amber-mono);
}

View file

@ -1,6 +1,7 @@
import fs from 'fs';
import path from 'path';
import {themeNames, themeSessionKey} from '../components/Theme';
import {mediaFilterSessionKey, themeMediaFilter} from './names';
const readFile = (...parts) => fs.readFileSync(path.join(__dirname, ...parts), 'utf8');
@ -73,4 +74,52 @@ describe('pre-paint theme script', () => {
const head = indexHtml.slice(0, indexHtml.indexOf('</head>'));
expect(head).toContain("document.documentElement.setAttribute('data-theme'");
});
it('stamps the media filter before the bundle loads too', () => {
// Otherwise night mode paints a screen of unfiltered thumbnails while the bundle
// arrives, which costs the user the dark adaptation the theme exists to protect.
const head = indexHtml.slice(0, indexHtml.indexOf('</head>'));
expect(head).toContain("document.documentElement.setAttribute('data-media-filter'");
expect(head).toContain(`localStorage.getItem('${mediaFilterSessionKey}')`);
});
it('duplicates the same filter ids and defaults the app uses', () => {
// The script cannot import from names.ts, so it restates both. These assertions
// fail if a theme's filter id or default changes on only one side.
themeNames.forEach(theme => {
const filter = themeMediaFilter(theme);
if (!filter) return;
expect(indexHtml).toContain(`${theme}: '${filter.id}'`);
expect(indexHtml).toContain(`${theme}: ${filter.defaultOn}`);
});
});
});
describe('media filter rules', () => {
it('keys on the filter, not on the theme', () => {
// Filtering is a per-theme setting the user controls, so a rule keyed on
// `data-theme` could not be turned off.
const filterRules = [...tokensCss.matchAll(/^html\[([^\]]+)][^{]*{\s*filter:/gm)]
.map(match => match[1]);
expect(filterRules.length).toBeGreaterThan(0);
filterRules.forEach(selector => expect(selector).toMatch(/^data-media-filter=/));
});
it('has a rule for every filter a theme offers', () => {
themeNames.forEach(theme => {
const filter = themeMediaFilter(theme);
if (!filter) return;
expect(tokensCss).toContain(`html[data-media-filter="${filter.id}"]`);
// Restated for native fullscreen, where an ancestor's filter stops applying.
expect(tokensCss).toMatch(
new RegExp(`html\\[data-media-filter="${filter.id}"] :fullscreen`));
});
});
it('never filters an ancestor, only leaf media', () => {
// A CSS filter creates a containing block, which would break `position: fixed`
// descendants — the nav bar and every modal.
expect(tokensCss).not.toMatch(/data-media-filter="[^"]+"]\s*{\s*filter:/);
});
});

View file

@ -5,6 +5,21 @@ import { CSSProperties } from 'react';
export type ThemeName = 'dark' | 'light' | 'night' | 'amber';
export type SavedThemeName = ThemeName | 'system' | null;
/**
* A theme's media filter: images, video, PDFs, and canvases cannot consume theme
* tokens, so a monochrome theme can remap them with an SVG color matrix instead.
* The theme declares the filter and whether it starts on; the user decides.
*/
export interface ThemeMediaFilter {
/** Matches a filter id in MediaFilterDefs, minus the `wrolpi-` prefix. */
id: string;
/** On unless the user says otherwise. */
defaultOn: boolean;
/** Label for the toggle, naming what the filter does. */
label: string;
description: string;
}
// Style objects used by theme
export interface InvertedProps {
inverted?: boolean;
@ -30,6 +45,12 @@ export interface ThemeContextValue {
savedTheme: SavedThemeName;
/** True when the applied theme is built on a dark background */
isDark: boolean;
/** The media filter this theme offers, or undefined when it offers none */
mediaFilter?: ThemeMediaFilter;
/** True when that filter is currently being applied to media */
mediaFilterEnabled: boolean;
/** Turn the current theme's media filter on or off */
setMediaFilterEnabled: (enabled: boolean) => void;
/** Apply and save a theme (or 'system' to follow the OS preference) */
setTheme: (value: SavedThemeName) => void;
/** Set dark theme */