siyuan/app/src/plugin/loader.ts

37 lines
1.2 KiB
TypeScript
Raw Normal View History

import {fetchPost} from "../util/fetch";
import {App} from "../index";
import {Plugin} from "./index";
const getObject = (key: string) => {
const api = {
siyuan: {
Plugin: Plugin
}
};
// @ts-ignore
return api[key];
2023-05-05 14:04:43 +08:00
};
const runCode = (code: string, sourceURL: string) => {
2023-05-05 14:04:43 +08:00
return window.eval("(function anonymous(require, module){".concat(code, "\n})\n//# sourceURL=").concat(sourceURL, "\n"));
};
export const loadPlugins = (app: App) => {
fetchPost("/api/petal/loadPetals", {}, response => {
let css = "";
response.data.forEach((item: { id: string, name: string, jsCode: string, cssCode: string, lang: IObject }) => {
2023-05-05 14:04:43 +08:00
const moduleObj = {};
const execResult = runCode(item.jsCode, "plugin:" + encodeURIComponent(item.id));
execResult(getObject, moduleObj);
// @ts-ignore
2023-05-05 14:04:43 +08:00
const plugin: Plugin = new moduleObj.exports.default({app, id: item.id, lang: item.lang});
app.plugins.push(plugin);
plugin.onload();
css += item.cssCode + "\n";
2023-05-05 14:04:43 +08:00
});
const styleElement = document.createElement("style");
styleElement.textContent = css;
document.head.append(styleElement);
2023-05-05 14:04:43 +08:00
});
};