diff --git a/app/public/index.html b/app/public/index.html index 3f327e57..8860fcf0 100644 --- a/app/public/index.html +++ b/app/public/index.html @@ -30,10 +30,14 @@ WROLPi: Create your own off-grid library diff --git a/app/src/components/Theme.tsx b/app/src/components/Theme.tsx index a4d9b050..2d325f30 100644 --- a/app/src/components/Theme.tsx +++ b/app/src/components/Theme.tsx @@ -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> => { + 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(() => resolveTheme(readSavedTheme())); + // Which themes the user has turned media filtering on or off for. + const [mediaFilters, setMediaFilters] = useState>>( + readMediaFilters); + // `data-theme` on 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, diff --git a/app/src/components/ThemeProvider.test.js b/app/src/components/ThemeProvider.test.js index 8e1616bb..98995e66 100644 --- a/app/src/components/ThemeProvider.test.js +++ b/app/src/components/ThemeProvider.test.js @@ -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 <> {theme} {String(savedTheme)} {String(isDark)} + {mediaFilter ? mediaFilter.id : 'none'} + {String(mediaFilterEnabled)} + + + + } const renderProvider = () => render(); 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; diff --git a/app/src/components/ThemeSamplePage.js b/app/src/components/ThemeSamplePage.js index bd33d0b2..67650f84 100644 --- a/app/src/components/ThemeSamplePage.js +++ b/app/src/components/ThemeSamplePage.js @@ -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}) =>
; 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

Component gallery

@@ -74,6 +81,67 @@ export function ThemeSamplePage() { +
+ +
+
+ {/* + A real , 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. + */} + The WROLPi logo, filtered like any other media +

+ Filtered +

+
+
+ {/* + 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 + ? The WROLPi logo, unfiltered + : } +

+ Real colors +

+
+

+ 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. +

+ Use the toggle in the theme picker above to see the difference. An + element can opt out with night-unfiltered — 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. +

+
+
+
+ +
+ +
Page title (h1)
+
Section (h2)
+
With an icon and a divider (h3)
+
Subsection (h4)
+
Smallest (h5)
+

+ 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. +

+
+
+
@@ -130,6 +198,12 @@ export function ThemeSamplePage() { HTTP 403 from the remote server after 3 attempts. Retry, or check the URL. + 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.'} +
@@ -200,6 +274,14 @@ export function ThemeSamplePage() {