2023-05-04 18:28:57 +08:00
|
|
|
import {fetchPost} from "../util/fetch";
|
|
|
|
|
import {App} from "../index";
|
|
|
|
|
import {Plugin} from "./index";
|
2023-05-07 17:31:50 +08:00
|
|
|
import {API} from "./API";
|
2023-05-04 18:28:57 +08:00
|
|
|
|
|
|
|
|
const getObject = (key: string) => {
|
|
|
|
|
const api = {
|
2023-05-07 17:31:50 +08:00
|
|
|
siyuan: API
|
2023-05-04 18:28:57 +08:00
|
|
|
};
|
|
|
|
|
// @ts-ignore
|
|
|
|
|
return api[key];
|
2023-05-05 14:04:43 +08:00
|
|
|
};
|
2023-05-04 18:28:57 +08:00
|
|
|
|
|
|
|
|
const runCode = (code: string, sourceURL: string) => {
|
2023-05-06 00:10:30 +08:00
|
|
|
return window.eval("(function anonymous(require, module, exports){".concat(code, "\n})\n//# sourceURL=").concat(sourceURL, "\n"));
|
2023-05-05 14:04:43 +08:00
|
|
|
};
|
2023-05-04 18:28:57 +08:00
|
|
|
|
|
|
|
|
export const loadPlugins = (app: App) => {
|
2023-05-04 19:48:03 +08:00
|
|
|
fetchPost("/api/petal/loadPetals", {}, response => {
|
2023-05-04 18:28:57 +08:00
|
|
|
let css = "";
|
2023-05-06 00:10:30 +08:00
|
|
|
response.data.forEach((item: { id: string, name: string, js: string, css: string, i18n: IObject }) => {
|
|
|
|
|
const exportsObj: { [key: string]: any } = {};
|
|
|
|
|
const moduleObj = {exports: exportsObj};
|
|
|
|
|
try {
|
2023-05-06 19:36:54 +08:00
|
|
|
runCode(item.js, "plugin:" + encodeURIComponent(item.name))(getObject, moduleObj, exportsObj);
|
2023-05-06 00:10:30 +08:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(`eval plugin ${item.name} error:`, e);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2023-05-07 09:57:14 +08:00
|
|
|
const pluginClass = (moduleObj.exports || exportsObj).default || moduleObj.exports;
|
2023-05-06 00:10:30 +08:00
|
|
|
if (typeof pluginClass !== "function") {
|
|
|
|
|
console.error(`plugin ${item.name} has no export`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (!(pluginClass.prototype instanceof Plugin)) {
|
|
|
|
|
console.error(`plugin ${item.name} does not extends Plugin`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2023-05-07 17:31:50 +08:00
|
|
|
const plugin = new pluginClass({
|
|
|
|
|
app,
|
|
|
|
|
name: item.name,
|
|
|
|
|
id: item.id,
|
|
|
|
|
i18n: item.i18n
|
|
|
|
|
});
|
2023-05-04 18:28:57 +08:00
|
|
|
app.plugins.push(plugin);
|
|
|
|
|
plugin.onload();
|
2023-05-06 00:10:30 +08:00
|
|
|
css += item.css || "" + "\n";
|
2023-05-05 14:04:43 +08:00
|
|
|
});
|
2023-05-04 18:28:57 +08:00
|
|
|
const styleElement = document.createElement("style");
|
|
|
|
|
styleElement.textContent = css;
|
|
|
|
|
document.head.append(styleElement);
|
2023-05-05 14:04:43 +08:00
|
|
|
});
|
|
|
|
|
};
|