feat(reader): make white image backgrounds transparent (#7270)

* feat(reader): make white image backgrounds transparent

Add an opt-in image transparency setting to Theme settings and View Options.
Remove pixels with all RGB channels at least 245 while preserving other
colors and existing alpha. Apply it before optional dark-mode inversion,
cover SVG-wrapped bitmaps and fixed-layout images, and preserve the filter
in the image viewer. Leave PDF page canvases unchanged.

Verified on origin/main at 179603780:
- Full unit suite: 1229 files passed, 14934 tests passed, 16 skipped.
- Final targeted suites: 46 tests passed.
- Browser rendering: 4 tests passed, including exact RGBA pixels and
  reflowable/fixed-layout selector behavior.
- pnpm lint and git diff --check passed.
- Synthetic EPUB exercised in the web reader and Linux CEF, including sepia;
  inspected dark mode and phone-width RTL/e-ink presentation in the browser.
- WebKit could not launch: missing libicudata.so.74. Physical devices were
  not tested.

Before implementation, image-background.test.ts failed five assertions:
undefined default instead of false, absent transparency filters in reflowable
and fixed-layout styles, and absent ordering before inversion. The tests pass
with the change.

Reported by noideaforeal on GitHub (#7045).

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

* fix(reader): announce image transparency toggle state

Use MenuItem's existing toggled prop so the image transparency row exposes
its ON/OFF state to screen readers while retaining its checkmark.

Verification: the updated ViewMenu test failed before the fix because the
accessible name lacked OFF; all 17 ViewMenu tests pass with the fix and
assert the accessible name changes to ON after activation. TypeScript,
Biome lint, formatting, and git diff --check passed.

Reported by coderabbitai[bot] on GitHub.

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

* fix(reader): preserve image behavior when transparency is off

Limit SVG bitmap style capture to the new transparency filter so disabling
the option keeps the image viewer's previous behavior. Add regression
coverage for SVG capture before and after activation and browser coverage
for restoring image styles in reflowable and fixed-layout books.

Verification: the SVG regression failed before the fix, receiving an
inversion style instead of the previous null result. With the fix, all 47
focused unit tests and 6 browser tests pass. Lint, formatting, and whitespace
checks pass. A temporary baseline harness compared pre-feature CSS against
the disabled path across 288 reflowable and 1,728 fixed-layout combinations;
all declarations match after whitespace normalization, including after
turning the option on and off for fixed layout.

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

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-03 02:00:22 +08:00 • committed by GitHub
parent d5d5cbdb03
commit ab8025cb4c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 432 additions and 6 deletions

View file

@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
captureImageRenderStyle,
isLightColor,
isTransparentColor,
plateColorFromBoxShadow,
@ -75,6 +76,16 @@ describe('readImageRenderStyle', () => {
expect(style.filter).toBe('invert(100%)');
});
it('reads the filter from an SVG-wrapped bitmap (#7045)', () => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('style', 'filter: invert(100%)');
svg.appendChild(image);
document.body.appendChild(svg);
expect(readImageRenderStyle(image).filter).toBe('invert(100%)');
svg.remove();
});
it('prefers the element background over a shadow', () => {
const style = readImageRenderStyle(
makeImage('background-color: rgb(250, 250, 250); box-shadow: inset 0 0 0 999px #fff;'),
@ -83,10 +94,45 @@ describe('readImageRenderStyle', () => {
});
});
describe('captureImageRenderStyle for SVG images (#7045)', () => {
it('keeps the previous viewer behavior unless white transparency is enabled', () => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('href', 'blob:diagram');
image.setAttribute('style', 'filter: invert(100%)');
svg.appendChild(image);
document.body.appendChild(svg);
const view = {
renderer: { getContents: () => [{ doc: document }] },
} as unknown as Parameters<typeof captureImageRenderStyle>[0];
try {
expect(captureImageRenderStyle(view, 'blob:diagram')).toBeNull();
image.style.filter = 'url("#readest-white-transparent") invert(100%)';
expect(captureImageRenderStyle(view, 'blob:diagram')?.filter).toContain(
'readest-white-transparent',
);
image.style.filter = 'invert(100%)';
expect(captureImageRenderStyle(view, 'blob:diagram')).toBeNull();
} finally {
svg.remove();
}
});
});
describe('resolveImagePlate', () => {
const lineArt = { transparentRatio: 0.7, darkInkRatio: 0.95 };
const photo = { transparentRatio: 0, darkInkRatio: 0.1 };
it('does not restore paper behind intentionally transparent image backgrounds (#7045)', () => {
expect(
resolveImagePlate({
pagePlate: '#ffffff',
filter: 'url("data:image/svg+xml,...#readest-white-transparent")',
ink: lineArt,
}),
).toBeNull();
});
it('uses the page plate whenever the page had one', () => {
expect(resolveImagePlate({ pagePlate: 'rgb(250, 250, 250)', filter: 'none', ink: photo })).toBe(
'rgb(250, 250, 250)',

View file

@ -118,6 +118,43 @@ vi.mock('@/utils/window', async (importOriginal) => ({
tauriHandleToggleFullScreen: vi.fn(),
}));
describe('ViewMenu transparent image backgrounds (#7045)', () => {
afterEach(() => {
cleanup();
mockBookData.book.format = 'PDF';
});
it('announces the image toggle state and persists it for EPUBs', async () => {
vi.clearAllMocks();
mockBookData.book.format = 'EPUB';
render(<ViewMenu bookKey='book-1' />);
fireEvent.click(
screen.getByRole('menuitem', { name: 'Make White Image Backgrounds Transparent - OFF' }),
);
expect(
screen.getByRole('menuitem', { name: 'Make White Image Backgrounds Transparent - ON' }),
).toBeTruthy();
await waitFor(() =>
expect(mockSaveViewSettings).toHaveBeenCalledWith(
expect.anything(),
'book-1',
'transparentImageBackground',
true,
true,
true,
),
);
});
it('does not offer image transparency for PDF pages', () => {
mockBookData.book.format = 'PDF';
render(<ViewMenu bookKey='book-1' />);
expect(
screen.queryByRole('menuitem', { name: 'Make White Image Backgrounds Transparent' }),
).toBeNull();
});
});
describe('ViewMenu fullscreen', () => {
const requestFullscreen = vi.fn();

View file

@ -0,0 +1,147 @@
import { describe, expect, it } from 'vitest';
import { WHITE_TRANSPARENCY_FILTER } from '@/utils/imageBackground';
import { applyFixedlayoutStyles, getStyles, type ThemeCode } from '@/utils/style';
import {
DEFAULT_BOOK_STYLE,
DEFAULT_BOOK_FONT,
DEFAULT_BOOK_LAYOUT,
DEFAULT_BOOK_LANGUAGE,
DEFAULT_VIEW_CONFIG,
DEFAULT_TTS_CONFIG,
DEFAULT_TRANSLATOR_CONFIG,
DEFAULT_ANNOTATOR_CONFIG,
DEFAULT_SCREEN_CONFIG,
} from '@/services/constants';
import type { ViewSettings } from '@/types/book';
const settings = {
...DEFAULT_BOOK_STYLE,
...DEFAULT_BOOK_FONT,
...DEFAULT_BOOK_LAYOUT,
...DEFAULT_BOOK_LANGUAGE,
...DEFAULT_VIEW_CONFIG,
...DEFAULT_TTS_CONFIG,
...DEFAULT_TRANSLATOR_CONFIG,
...DEFAULT_ANNOTATOR_CONFIG,
...DEFAULT_SCREEN_CONFIG,
transparentImageBackground: true,
} as ViewSettings;
const theme = {
bg: '#eee0c0',
fg: '#202020',
primary: '#3366cc',
isDarkMode: false,
palette: {},
} as ThemeCode;
// Exercise the browser's SVG filter pipeline, including the threshold, color
// preservation, existing alpha, and ordering with dark-mode inversion.
const renderPixels = async (invert = false) => {
const source = document.createElement('canvas');
source.width = 8;
source.height = 1;
const ctx = source.getContext('2d')!;
const colors = [
[255, 255, 255, 255],
[245, 245, 245, 255],
[244, 244, 244, 255],
[255, 244, 255, 255],
[255, 0, 0, 255],
[0, 0, 0, 255],
[0, 0, 255, 128],
[255, 255, 255, 0],
];
ctx.putImageData(new ImageData(new Uint8ClampedArray(colors.flat()), 8, 1), 0, 0);
const image = new Image();
image.src = source.toDataURL();
await image.decode();
const output = document.createElement('canvas');
output.width = 8;
output.height = 1;
const result = output.getContext('2d')!;
result.filter = `${WHITE_TRANSPARENCY_FILTER}${invert ? ' invert(100%)' : ''}`;
result.drawImage(image, 0, 0);
return [...result.getImageData(0, 0, 8, 1).data];
};
describe('white transparency rendered pixels (#7045)', () => {
it.each([
false,
true,
])('matches images despite inline-image blend rules (fixed layout: %s)', async (fixed) => {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const doc = frame.contentDocument!;
doc.body.innerHTML =
'<p width="100" height="100"><img class="has-text-siblings"/><svg><image/></svg></p>';
if (fixed) {
applyFixedlayoutStyles(doc, settings, theme, 'EPUB');
} else {
const style = doc.createElement('style');
style.textContent = getStyles(settings, theme);
doc.head.appendChild(style);
}
try {
for (const image of doc.querySelectorAll('img, image')) {
const computed = frame.contentWindow!.getComputedStyle(image);
expect(computed.filter).toContain('readest-white-transparent');
expect(computed.mixBlendMode).toBe('normal');
}
} finally {
frame.remove();
}
});
it.each([
false,
true,
])('restores the original image styles when turned off (fixed: %s)', (fixed) => {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const doc = frame.contentDocument!;
doc.body.innerHTML = '<p><img/></p><svg><image/></svg>';
const style = doc.createElement('style');
doc.head.appendChild(style);
try {
for (const isDarkMode of [false, true]) {
for (const overrideColor of [false, true]) {
for (const invertImgColorInDark of [false, true]) {
const current = { ...settings, overrideColor, invertImgColorInDark };
const currentTheme = { ...theme, isDarkMode };
const apply = (transparentImageBackground: boolean) => {
const next = { ...current, transparentImageBackground };
if (fixed) applyFixedlayoutStyles(doc, next, currentTheme, 'EPUB');
else style.textContent = getStyles(next, currentTheme);
};
const read = () =>
Array.from(doc.querySelectorAll('img, image'), (image) => {
const computed = frame.contentWindow!.getComputedStyle(image);
return [computed.filter, computed.mixBlendMode, computed.backgroundColor];
});
apply(false);
const original = read();
apply(true);
expect(read()[0]![0]).toContain('readest-white-transparent');
apply(false);
expect(read()).toEqual(original);
expect(read()[0]![0]).not.toContain('readest-white-transparent');
}
}
}
} finally {
frame.remove();
}
});
it('removes only near-white pixels and preserves color and alpha', async () => {
expect(await renderPixels()).toEqual([
0, 0, 0, 0, 0, 0, 0, 0, 244, 244, 244, 255, 255, 244, 255, 255, 255, 0, 0, 255, 0, 0, 0, 255,
0, 0, 255, 128, 0, 0, 0, 0,
]);
});
it('removes the original white before inversion', async () => {
const pixels = await renderPixels(true);
expect(pixels.slice(0, 8)).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
expect(pixels.slice(16, 24)).toEqual([0, 255, 255, 255, 255, 255, 255, 255]);
});
});

View file

@ -0,0 +1,98 @@
import { describe, expect, it } from 'vitest';
import { getStyles, applyFixedlayoutStyles, type ThemeCode } from '@/utils/style';
import {
DEFAULT_BOOK_STYLE,
DEFAULT_BOOK_FONT,
DEFAULT_BOOK_LAYOUT,
DEFAULT_BOOK_LANGUAGE,
DEFAULT_VIEW_CONFIG,
DEFAULT_TTS_CONFIG,
DEFAULT_TRANSLATOR_CONFIG,
DEFAULT_ANNOTATOR_CONFIG,
DEFAULT_SCREEN_CONFIG,
} from '@/services/constants';
import type { ViewSettings } from '@/types/book';
const DEFAULT_VIEW_SETTINGS = {
...DEFAULT_BOOK_STYLE,
...DEFAULT_BOOK_FONT,
...DEFAULT_BOOK_LAYOUT,
...DEFAULT_BOOK_LANGUAGE,
...DEFAULT_VIEW_CONFIG,
...DEFAULT_TTS_CONFIG,
...DEFAULT_TRANSLATOR_CONFIG,
...DEFAULT_ANNOTATOR_CONFIG,
...DEFAULT_SCREEN_CONFIG,
} as ViewSettings;
const theme = {
bg: '#eee0c0',
fg: '#202020',
primary: '#3366cc',
isDarkMode: false,
palette: {},
} as ThemeCode;
describe('transparent image backgrounds (#7045)', () => {
it('defaults off', () => {
expect(DEFAULT_VIEW_SETTINGS.transparentImageBackground).toBe(false);
});
it.each([false, true])('applies independently of Override Book Color (%s)', (overrideColor) => {
const css = getStyles(
{
...DEFAULT_VIEW_SETTINGS,
overrideColor,
transparentImageBackground: true,
},
theme,
);
expect(css).toContain('readest-white-transparent');
expect(css).toContain('mix-blend-mode: normal !important;');
expect(css).not.toContain('filter: grayscale(');
});
it('removes white before applying the requested dark-mode inversion', () => {
const css = getStyles(
{
...DEFAULT_VIEW_SETTINGS,
transparentImageBackground: true,
invertImgColorInDark: true,
},
{ ...theme, isDarkMode: true },
);
expect(css).toMatch(/filter: url\([^;]+\) invert\(100%\)/);
});
it('also applies to fixed-layout image pages', () => {
const doc = document.implementation.createHTMLDocument('comic');
applyFixedlayoutStyles(
doc,
{
...DEFAULT_VIEW_SETTINGS,
transparentImageBackground: true,
},
theme,
'CBZ',
);
expect(doc.getElementById('fixed-layout-styles')?.textContent).toContain(
'readest-white-transparent',
);
});
it('leaves PDF pages alone', () => {
const doc = document.implementation.createHTMLDocument('pdf');
applyFixedlayoutStyles(
doc,
{
...DEFAULT_VIEW_SETTINGS,
transparentImageBackground: true,
},
theme,
'PDF',
);
expect(doc.getElementById('fixed-layout-styles')?.textContent).not.toContain(
'readest-white-transparent',
);
});
});

View file

@ -1267,6 +1267,7 @@ const FoliateViewer: React.FC<{
isDarkMode,
viewSettings?.scrolled,
viewSettings?.overrideColor,
viewSettings?.transparentImageBackground,
viewSettings?.invertImgColorInDark,
viewSettings?.applyThemeToPDF,
viewSettings?.contrast,

View file

@ -101,6 +101,9 @@ const ViewMenu: React.FC<ViewMenuProps> = ({
const [invertImgColorInDark, setInvertImgColorInDark] = useState(
viewSettings!.invertImgColorInDark,
);
const [transparentImageBackground, setTransparentImageBackground] = useState(
!!viewSettings.transparentImageBackground,
);
const [applyThemeToPDF, setApplyThemeToPDF] = useState(viewSettings!.applyThemeToPDF!);
const [rtlSpread, setRtlSpread] = useState(bookData?.bookDoc?.dir === 'rtl');
@ -280,6 +283,19 @@ const ViewMenu: React.FC<ViewMenuProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [invertImgColorInDark]);
useEffect(() => {
if (transparentImageBackground === !!viewSettings.transparentImageBackground) return;
saveViewSettings(
envConfig,
bookKey,
'transparentImageBackground',
transparentImageBackground,
true,
true,
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transparentImageBackground]);
useEffect(() => {
if (applyThemeToPDF === viewSettings.applyThemeToPDF) return;
saveViewSettings(envConfig, bookKey, 'applyThemeToPDF', applyThemeToPDF, true, true);
@ -549,6 +565,14 @@ const ViewMenu: React.FC<ViewMenuProps> = ({
onClick={() => setInvertImgColorInDark(!invertImgColorInDark)}
/>
{bookData.book?.format !== 'PDF' && (
<MenuItem
label={_('Make White Image Backgrounds Transparent')}
toggled={transparentImageBackground}
onClick={() => setTransparentImageBackground(!transparentImageBackground)}
/>
)}
<hr aria-hidden='true' className='border-base-300 my-1' />
{bookData.isFixedLayout ? (

View file

@ -89,7 +89,7 @@ const plateColorFor = (style: CSSStyleDeclaration): string | null => {
};
/** Read the render style the page gave an image element. */
export const readImageRenderStyle = (img: HTMLImageElement): ImageRenderStyle => {
export const readImageRenderStyle = (img: HTMLImageElement | SVGImageElement): ImageRenderStyle => {
const view = img.ownerDocument.defaultView;
const style = view?.getComputedStyle(img);
if (!style) return NO_RENDER_STYLE;
@ -114,6 +114,14 @@ export const captureImageRenderStyle = (
for (const img of doc.querySelectorAll('img')) {
if (img.src === src) return readImageRenderStyle(img);
}
for (const image of doc.querySelectorAll('image')) {
const href =
image.getAttribute('href') || image.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
if (href === src) {
const style = readImageRenderStyle(image);
return style.filter.includes('readest-white-transparent') ? style : null;
}
}
}
return null;
};
@ -250,6 +258,7 @@ export const resolveImagePlate = ({
filter?: string | null;
ink?: ImageInk | null;
}): string | null => {
if (filter?.includes('readest-white-transparent')) return null;
const inverts = !!filter && /invert\s*\(/i.test(filter);
if (inverts) return pagePlate ?? null;
const darkDrawing =

View file

@ -35,7 +35,13 @@ import { PREDEFINED_TEXTURES } from '@/styles/textures';
import { useAtmosphereStore } from '@/store/atmosphereStore';
import { DefaultHighlightColor, HighlightColor, UserHighlightColor } from '@/types/book';
import clsx from 'clsx';
import { ScopeSwitch, SectionTitle, SettingLabel } from './primitives';
import {
BoxedList,
SettingsSwitchRow,
ScopeSwitch,
SectionTitle,
SettingLabel,
} from './primitives';
import { HIGHLIGHT_COLOR_HEX } from '@/services/constants';
import ThemeEditor from './theme/ThemeEditor';
import ThemeModeSelector from './theme/ThemeModeSelector';
@ -94,6 +100,9 @@ const ThemePanel: React.FC<SettingsPanelPanelProp> = ({ bookKey, onRegisterReset
const [invertImgColorInDark, setInvertImgColorInDark] = useState(
viewSettings.invertImgColorInDark,
);
const [transparentImageBackground, setTransparentImageBackground] = useState(
!!viewSettings.transparentImageBackground,
);
const [editTheme, setEditTheme] = useState<CustomTheme | null>(null);
const [customThemes, setCustomThemes] = useState<Theme[]>([]);
const [showCustomThemeEditor, setShowCustomThemeEditor] = useState(false);
@ -155,6 +164,7 @@ const ThemePanel: React.FC<SettingsPanelPanelProp> = ({ bookKey, onRegisterReset
resetToDefaults({
overrideColor: setOverrideColor,
invertImgColorInDark: setInvertImgColorInDark,
transparentImageBackground: setTransparentImageBackground,
highlightOpacity: setHighlightOpacity,
codeHighlighting: setcodeHighlighting,
codeLanguage: setCodeLanguage,
@ -217,6 +227,12 @@ const ThemePanel: React.FC<SettingsPanelPanelProp> = ({ bookKey, onRegisterReset
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [invertImgColorInDark]);
useEffect(() => {
if (transparentImageBackground === !!viewSettings.transparentImageBackground) return;
saveViewSettings(envConfig, bookKey, 'transparentImageBackground', transparentImageBackground);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transparentImageBackground]);
useEffect(() => {
if (overrideColor === viewSettings.overrideColor) return;
saveViewSettings(envConfig, bookKey, 'overrideColor', overrideColor);
@ -577,6 +593,22 @@ const ThemePanel: React.FC<SettingsPanelPanelProp> = ({ bookKey, onRegisterReset
/>
</label>
<BoxedList>
<SettingsSwitchRow
data-setting-id='settings.color.transparentImageBackground'
label={_('Make White Image Backgrounds Transparent')}
description={_(
'Remove white and near-white pixels from images while preserving other colors',
)}
checked={transparentImageBackground}
disabled={
!!bookKey &&
useBookDataStore.getState().getBookData(bookKey)?.book?.format === 'PDF'
}
onChange={() => setTransparentImageBackground(!transparentImageBackground)}
/>
</BoxedList>
<label
data-setting-id='settings.color.overrideBookColor'
className='flex cursor-pointer items-center justify-between px-4'

View file

@ -376,6 +376,12 @@ const colorPanelItems = [
keywords: ['invert', 'image', 'dark', 'mode', 'photo'],
section: 'Theme',
},
{
id: 'settings.color.transparentImageBackground',
labelKey: _('Make White Image Backgrounds Transparent'),
keywords: ['image', 'white', 'background', 'transparent', 'diagram'],
section: 'Theme',
},
{
id: 'settings.color.overrideBookColor',
labelKey: _('Override Book Color'),

View file

@ -444,6 +444,7 @@ export const DEFAULT_BOOK_STYLE: BookStyle = {
spreadMode: 'auto',
keepCoverSpread: true,
invertImgColorInDark: false,
transparentImageBackground: false,
applyThemeToPDF: false,
contrast: 100,
};

View file

@ -335,6 +335,7 @@ export interface BookStyle {
spreadMode: 'auto' | 'none';
keepCoverSpread: boolean;
invertImgColorInDark: boolean;
transparentImageBackground: boolean;
applyThemeToPDF: boolean;
contrast: number;
}

View file

@ -0,0 +1,7 @@
// Classify the original sRGB channels before inversion or contrast. Only pixels
// whose three channels are at least 245 become transparent; other colors and
// existing alpha are preserved. A data URL also works in footnotes and the image
// viewer without referring back to an iframe's document.
const whiteTransparencySvg = `<svg xmlns="http://www.w3.org/2000/svg"><filter id="readest-white-transparent" color-interpolation-filters="sRGB"><feComponentTransfer><feFuncR type="linear" slope="255" intercept="-244"/><feFuncG type="linear" slope="255" intercept="-244"/><feFuncB type="linear" slope="255" intercept="-244"/></feComponentTransfer><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 -2"/><feComposite in="SourceGraphic" operator="out"/></filter></svg>`;
export const WHITE_TRANSPARENCY_FILTER = `url("data:image/svg+xml,${encodeURIComponent(whiteTransparencySvg)}#readest-white-transparent")`;

View file

@ -19,6 +19,7 @@ import { isDialogueHighlightActive } from './dialogueHighlight';
import { readStoredAmbientIsDarkMode } from './ambientLight';
import { INLINE_FORMATTING_SELECTOR } from './inlineTags';
import { getOSPlatform } from './misc';
import { WHITE_TRANSPARENCY_FILTER } from './imageBackground';
import {
LINK_HIT_AREA_CLASS,
LINK_HIT_AREA_PX,
@ -351,6 +352,7 @@ const getColorStyles = (
themeCode: ThemeCode,
backgroundTextureId: string,
isEink: boolean,
transparentImageBackground: boolean,
) => {
const { bg, fg, primary, isDarkMode } = themeCode;
const hasBackgroundTexture = !!backgroundTextureId && backgroundTextureId !== 'none';
@ -403,9 +405,15 @@ const getColorStyles = (
(a later filter declaration would discard it), and multiply must not
apply: multiply with a dark page background erases the image (#5250). */
img {
${isDarkMode && invertImgColorInDark ? 'filter: invert(100%);' : ''}
${isDarkMode && !invertImgColorInDark && overrideColor ? 'filter: grayscale(100%) contrast(1.2) brightness(1.2);' : ''}
${overrideColor && !(isDarkMode && invertImgColorInDark) ? 'mix-blend-mode: multiply;' : ''}
${transparentImageBackground ? `filter: ${WHITE_TRANSPARENCY_FILTER}${isDarkMode && invertImgColorInDark ? ' invert(100%)' : ''};` : isDarkMode && invertImgColorInDark ? 'filter: invert(100%);' : ''}
${!transparentImageBackground && isDarkMode && !invertImgColorInDark && overrideColor ? 'filter: grayscale(100%) contrast(1.2) brightness(1.2);' : ''}
${!transparentImageBackground && overrideColor && !(isDarkMode && invertImgColorInDark) ? 'mix-blend-mode: multiply;' : ''}
}
${
transparentImageBackground
? `svg image { filter: ${WHITE_TRANSPARENCY_FILTER}${isDarkMode && invertImgColorInDark ? ' invert(100%)' : ''}; }
img, svg image { mix-blend-mode: normal !important; background-color: transparent !important; }`
: ''
}
svg, img {
${overrideColor ? `background-color: transparent !important;` : ''};
@ -1211,6 +1219,7 @@ export const getStyles = (
themeCode,
viewSettings.backgroundTextureId,
viewSettings.isEink,
!!viewSettings.transparentImageBackground,
);
const translationStyles = getTranslationStyles(viewSettings);
const warichuStyles = getWarichuStyles();
@ -1959,6 +1968,8 @@ export const applyFixedlayoutStyles = (
// are to be inverted; inverting or blending it again would darken or flip the
// theme colors (#6548).
const isThemedPDF = format === 'PDF' && viewSettings.applyThemeToPDF;
const transparentImages = !!viewSettings.transparentImageBackground && format !== 'PDF';
if (transparentImages) imgFilters.push(WHITE_TRANSPARENCY_FILTER);
// hue-rotate flips the hues back, so a blue link stays blue
if (isDarkMode && invertImgColorInDark && !isThemedPDF) {
imgFilters.push('invert(100%) hue-rotate(180deg)');
@ -1997,7 +2008,13 @@ export const applyFixedlayoutStyles = (
}
img, canvas {
${imgFilter}
${overrideColor && !isThemedPDF ? `mix-blend-mode: ${isDarkMode ? darkMixBlendMode : 'multiply'};` : ''}
${!transparentImages && overrideColor && !isThemedPDF ? `mix-blend-mode: ${isDarkMode ? darkMixBlendMode : 'multiply'};` : ''}
}
${
transparentImages
? `svg image { ${imgFilter} }
img, svg image { mix-blend-mode: normal !important; background-color: transparent !important; }`
: ''
}
img.singlePage {
position: relative;