2020-10-09 19:35:46 +02:00
|
|
|
import { useEffect, useState } from 'react';
|
2020-11-07 17:59:37 +02:00
|
|
|
import { themeStyle } from '@joplin/lib/theme';
|
|
|
|
import shim from '@joplin/lib/shim';
|
2021-01-22 19:41:11 +02:00
|
|
|
import Setting from '@joplin/lib/models/Setting';
|
2020-11-07 17:59:37 +02:00
|
|
|
const { camelCaseToDash, formatCssSize } = require('@joplin/lib/string-utils');
|
2020-10-09 19:35:46 +02:00
|
|
|
|
|
|
|
interface HookDependencies {
|
2020-11-12 21:29:22 +02:00
|
|
|
pluginId: string;
|
|
|
|
themeId: number;
|
2020-10-09 19:35:46 +02:00
|
|
|
}
|
|
|
|
|
2024-04-05 13:16:49 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
|
2020-11-12 21:13:28 +02:00
|
|
|
function themeToCssVariables(theme: any) {
|
2020-10-09 19:35:46 +02:00
|
|
|
const lines = [];
|
|
|
|
lines.push(':root {');
|
|
|
|
|
|
|
|
for (const name in theme) {
|
|
|
|
const value = theme[name];
|
|
|
|
if (typeof value === 'object') continue;
|
|
|
|
if (['appearance', 'codeThemeCss', 'codeMirrorTheme'].indexOf(name) >= 0) continue;
|
|
|
|
|
|
|
|
const newName = `--joplin-${camelCaseToDash(name)}`;
|
|
|
|
|
|
|
|
const formattedValue = typeof value === 'number' && newName.indexOf('opacity') < 0 ? formatCssSize(value) : value;
|
|
|
|
|
|
|
|
lines.push(`\t${newName}: ${formattedValue};`);
|
|
|
|
}
|
|
|
|
|
|
|
|
lines.push('}');
|
|
|
|
|
|
|
|
return lines.join('\n');
|
|
|
|
}
|
|
|
|
|
2020-11-12 21:13:28 +02:00
|
|
|
export default function useThemeCss(dep: HookDependencies) {
|
2020-10-09 19:35:46 +02:00
|
|
|
const { pluginId, themeId } = dep;
|
|
|
|
|
|
|
|
const [cssFilePath, setCssFilePath] = useState('');
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
let cancelled = false;
|
|
|
|
|
|
|
|
async function createThemeStyleSheet() {
|
|
|
|
const theme = themeStyle(themeId);
|
|
|
|
const css = themeToCssVariables(theme);
|
|
|
|
const filePath = `${Setting.value('tempDir')}/plugin_${pluginId}_theme_${themeId}.css`;
|
2023-08-25 10:20:44 +02:00
|
|
|
|
|
|
|
if (!(await shim.fsDriver().exists(filePath))) {
|
|
|
|
await shim.fsDriver().writeFile(filePath, css, 'utf8');
|
|
|
|
if (cancelled) return;
|
|
|
|
}
|
|
|
|
|
2020-10-09 19:35:46 +02:00
|
|
|
setCssFilePath(filePath);
|
|
|
|
}
|
|
|
|
|
2020-11-25 16:40:25 +02:00
|
|
|
void createThemeStyleSheet();
|
2020-10-09 19:35:46 +02:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
cancelled = true;
|
|
|
|
};
|
2023-08-25 10:20:44 +02:00
|
|
|
}, [pluginId, themeId]);
|
2020-10-09 19:35:46 +02:00
|
|
|
|
|
|
|
return cssFilePath;
|
|
|
|
}
|