refactor(plugin): refactor plugin loader and add dynamic loading

This commit is contained in:
Su-Yong
2023-11-12 00:09:56 +09:00
parent c7ff0dcbf6
commit bc916f3a6e
3 changed files with 168 additions and 93 deletions

View File

@ -1,33 +1,42 @@
import fs from 'node:fs';
const cssToInject = new Map<string, (() => void) | undefined>();
const cssToInjectFile = new Map<string, (() => void) | undefined>();
export const injectCSS = (webContents: Electron.WebContents, css: string, cb: (() => void) | undefined = undefined) => {
if (cssToInject.size === 0 && cssToInjectFile.size === 0) {
setupCssInjection(webContents);
}
type Unregister = () => void;
cssToInject.set(css, cb);
const cssToInject = new Map<string, ((unregister: Unregister) => void) | undefined>();
const cssToInjectFile = new Map<string, ((unregister: Unregister) => void) | undefined>();
export const injectCSS = (webContents: Electron.WebContents, css: string): Promise<Unregister> => {
return new Promise((resolve) => {
if (cssToInject.size === 0 && cssToInjectFile.size === 0) {
setupCssInjection(webContents);
}
cssToInject.set(css, resolve);
});
};
export const injectCSSAsFile = (webContents: Electron.WebContents, filepath: string, cb: (() => void) | undefined = undefined) => {
if (cssToInject.size === 0 && cssToInjectFile.size === 0) {
setupCssInjection(webContents);
}
export const injectCSSAsFile = (webContents: Electron.WebContents, filepath: string): Promise<Unregister> => {
return new Promise((resolve) => {
if (cssToInject.size === 0 && cssToInjectFile.size === 0) {
setupCssInjection(webContents);
}
cssToInjectFile.set(filepath, cb);
cssToInjectFile.set(filepath, resolve);
});
};
const setupCssInjection = (webContents: Electron.WebContents) => {
webContents.on('did-finish-load', () => {
cssToInject.forEach(async (callback, css) => {
await webContents.insertCSS(css);
callback?.();
const key = await webContents.insertCSS(css);
const remove = async () => await webContents.removeInsertedCSS(key);
callback?.(remove);
});
cssToInjectFile.forEach(async (callback, filepath) => {
await webContents.insertCSS(fs.readFileSync(filepath, 'utf-8'));
callback?.();
const key = await webContents.insertCSS(fs.readFileSync(filepath, 'utf-8'));
const remove = async () => await webContents.removeInsertedCSS(key);
callback?.(remove);
});
});
};