feat(pdfjs): react to dark mode

This commit is contained in:
Elian Doran 2025-12-29 12:51:43 +02:00
parent 94039bd9b1
commit 480954ee87
No known key found for this signature in database
2 changed files with 44 additions and 17 deletions

View File

@ -1,4 +1,5 @@
import { useEffect, useRef } from "preact/hooks";
import { RefObject } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";
import FNote from "../../../entities/fnote";
import server from "../../../services/server";
@ -11,7 +12,8 @@ const VARIABLE_WHITELIST = new Set([
]);
export default function PdfPreview({ note }: { note: FNote }) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { onLoad } = useStyleInjection(iframeRef);
useEffect(() => {
function handleMessage(event: MessageEvent) {
@ -32,20 +34,43 @@ export default function PdfPreview({ note }: { note: FNote }) {
ref={iframeRef}
class="pdf-preview"
src={`pdfjs/web/viewer.html?file=../../api/notes/${note.noteId}/open`}
onLoad={() => {
const doc = iframeRef.current?.contentDocument;
if (!doc) return;
const style = doc.createElement('style');
style.id = 'client-root-vars';
style.textContent = cssVarsToString(getRootCssVariables());
doc.head.appendChild(style);
}}
onLoad={onLoad}
/>
);
}
function useStyleInjection(iframeRef: RefObject<HTMLIFrameElement>) {
const styleRef = useRef<HTMLStyleElement | null>(null);
// First load.
const onLoad = useCallback(() => {
const doc = iframeRef.current?.contentDocument;
if (!doc) return;
const style = doc.createElement('style');
style.id = 'client-root-vars';
style.textContent = cssVarsToString(getRootCssVariables());
styleRef.current = style;
doc.head.appendChild(style);
}, [ iframeRef ]);
// React to changes.
useEffect(() => {
const listener = () => {
styleRef.current!.textContent = cssVarsToString(getRootCssVariables());
};
const media = window.matchMedia("(prefers-color-scheme: dark)");
media.addEventListener("change", listener);
return () => media.removeEventListener("change", listener);
}, [ iframeRef ]);
return {
onLoad
};
}
function getRootCssVariables() {
const styles = getComputedStyle(document.documentElement);
const vars = {};

View File

@ -1,12 +1,14 @@
:root {
--main-color: var(--tn-main-text-color);
--body-bg-color: var(--tn-main-background);
--toolbar-bg-color: var(--tn-main-background);
--body-bg-color: var(--tn-main-background-color);
--toolbar-bg-color: var(--tn-main-background-color);
--toolbar-border-color: var(--tn-main-border-color);
--toolbar-icon-opacity: 1;
}
.page .canvasWrapper {
border: 1px solid var(--tn-main-border-color);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
.pdfViewer {
.page .canvasWrapper {
border: 1px solid var(--tn-main-border-color);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
}
}