chore(client/pdf): inject some CSS variables

This commit is contained in:
Elian Doran 2025-12-29 12:21:44 +02:00
parent f09a3e06f4
commit 446822a7ae
No known key found for this signature in database

View File

@ -1,9 +1,18 @@
import { useEffect } from "preact/hooks";
import { useEffect, useRef } from "preact/hooks";
import FNote from "../../../entities/fnote";
import server from "../../../services/server";
const VARIABLE_WHITELIST = new Set([
"root-background",
"main-background-color",
"main-border-color",
"main-text-color"
]);
export default function PdfPreview({ note }: { note: FNote }) {
const iframeRef = useRef<HTMLIFrameElement>(null);
useEffect(() => {
function handleMessage(event: MessageEvent) {
if (event.data?.type === "pdfjs-viewer-document-modified" && event.data?.data) {
@ -20,7 +29,39 @@ export default function PdfPreview({ note }: { note: FNote }) {
return (
<iframe
ref={iframeRef}
class="pdf-preview"
src={`pdfjs/web/viewer.html?file=../../api/notes/${note.noteId}/open`} />
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);
}}
/>
);
}
function getRootCssVariables() {
const styles = getComputedStyle(document.documentElement);
const vars = {};
for (let i = 0; i < styles.length; i++) {
const prop = styles[i];
if (prop.startsWith('--') && VARIABLE_WHITELIST.has(prop.substring(2))) {
vars[`--tn-${prop.substring(2)}`] = styles.getPropertyValue(prop).trim();
}
}
return vars;
}
function cssVarsToString(vars) {
return `:root {\n${Object.entries(vars)
.map(([k, v]) => ` ${k}: ${v};`)
.join('\n')}\n}`;
}