mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-17 23:33:12 +09:00
Add typed hook system for plugins
Replace invokeHook and the per plugin on* methods with AsyncHook collections on the controller, host, instance, clusterioctl and web control objects. Plugin entrypoints export a default function that receives a load context and attaches handlers to the hooks it needs. Class exports still load through fromContext with a deprecation warning. The create templates and docs use the entrypoint function. This is clusterio/clusterio#921 recreated on top of master after the ESM migration and the PluginDeclaration permissions change. Closes #730 Co-Authored-By: Cooldude2606 <25043174+Cooldude2606@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
8c03ac15ab
commit
7122cbccf8
64 files changed
+1878
-1184
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import type React from "react";
|
||||
import type { AccountRole, FieldDefinition, Logger, PermissionName, PluginWebpackEnvInfo } from "@clusterio/lib";
|
||||
import type { Control } from "./util/websocket";
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
/**
|
||||
* Plugin supplied login form
|
||||
@@ -23,25 +23,17 @@ export interface PluginLoginForm {
|
||||
Component: React.ComponentType<{ setToken(token: string): void }>;
|
||||
}
|
||||
|
||||
export interface InputComponentProps {
|
||||
disabled?: boolean,
|
||||
fieldDefinition: FieldDefinition,
|
||||
value: null | boolean | number | string,
|
||||
onChange: (value: null | boolean | number | string) => void,
|
||||
}
|
||||
export type InputComponent = React.ComponentType<InputComponentProps>;
|
||||
|
||||
export type UserAccount = {
|
||||
/** Name of the currently logged in account. */
|
||||
name: string;
|
||||
/** Roles of the corrently logged in account. */
|
||||
roles: AccountRole[];
|
||||
/** Roles of the currently logged in account. */
|
||||
roles: lib.AccountRole[];
|
||||
/** Check if the currently logged in account has the given permission. */
|
||||
hasPermission: (permission: PermissionName) => boolean | null;
|
||||
hasPermission: (permission: lib.PermissionName) => boolean | null;
|
||||
/** Check if the currently logged in account has any of the given permissions. */
|
||||
hasAnyPermission: (...permissions: PermissionName[]) => boolean | null;
|
||||
hasAnyPermission: (...permissions: lib.PermissionName[]) => boolean | null;
|
||||
/** Check if the currently logged in account has all of given permissions. */
|
||||
hasAllPermission: (...permissions: PermissionName[]) => boolean | null;
|
||||
hasAllPermission: (...permissions: lib.PermissionName[]) => boolean | null;
|
||||
/** Logs out of the web interface. */
|
||||
logOut: () => void;
|
||||
};
|
||||
@@ -75,109 +67,91 @@ export interface PluginPage {
|
||||
/**
|
||||
* Permission to access page. function are expected to throw an error if access is deny.
|
||||
*/
|
||||
permission?: PermissionName | ((account: UserAccount) => (boolean|null));
|
||||
permission?: lib.PermissionName | ((account: UserAccount) => (boolean|null));
|
||||
};
|
||||
|
||||
/**
|
||||
* Base class for web interface plugins
|
||||
*/
|
||||
export default class BaseWebPlugin {
|
||||
export interface InputComponentProps {
|
||||
disabled?: boolean,
|
||||
fieldDefinition: lib.FieldDefinition,
|
||||
value: null | boolean | number | string,
|
||||
onChange: (value: null | boolean | number | string) => void,
|
||||
}
|
||||
|
||||
export type InputComponent = React.ComponentType<InputComponentProps>;
|
||||
|
||||
export type ExtensionSlotProps = {
|
||||
/** Placed at the end of the overview page. */
|
||||
OverviewPage: Record<never, never>;
|
||||
/** Placed at the end of the controller page. */
|
||||
ControllerPage: Record<never, never>;
|
||||
/** Placed at the end of the hosts list page. */
|
||||
HostsPage: Record<never, never>;
|
||||
/**
|
||||
* Contents of the plugin's package.json file
|
||||
* Placed at the end of each host page.
|
||||
* `host` is the host the page is displayed for.
|
||||
*/
|
||||
HostViewPage: {
|
||||
host: lib.HostDetails;
|
||||
};
|
||||
/** Placed at the end of the instance list page. */
|
||||
InstancesPage: Record<never, never>;
|
||||
/**
|
||||
* Placed at the end of each instance page.
|
||||
* `instance` is the instance the page is displayed for.
|
||||
*/
|
||||
InstanceViewPage: {
|
||||
instance: lib.InstanceDetails;
|
||||
};
|
||||
/** Placed at the end of the users list page. */
|
||||
UsersPage: Record<never, never>;
|
||||
/**
|
||||
* Placed at the end of each user page.
|
||||
* `user` is the user the page is displayed for.
|
||||
*/
|
||||
UserViewPage: {
|
||||
user: lib.UserDetails;
|
||||
};
|
||||
/** Placed at the end of the mods list page */
|
||||
ModsPage: Record<never, never>;
|
||||
/** Placed at the end of the roles list page. */
|
||||
RolesPage: Record<never, never>;
|
||||
/**
|
||||
* Placed at the end of each role page.
|
||||
* `role` is the role the page is displayed for.
|
||||
*/
|
||||
RoleViewPage: {
|
||||
role: lib.Role;
|
||||
search?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type PluginExtensionSlot = keyof ExtensionSlotProps;
|
||||
|
||||
export type PluginExtensionProps<K extends PluginExtensionSlot> = ExtensionSlotProps[K] & { component: K };
|
||||
|
||||
export type ExtensionComponent<K extends PluginExtensionSlot> = React.ComponentType<PluginExtensionProps<K>>;
|
||||
|
||||
export type ExtensionComponents = { [K in PluginExtensionSlot]: Map<string, ExtensionComponent<K>> };
|
||||
|
||||
export type WebPluginContext = lib.PluginLoadContext<{
|
||||
control: Control;
|
||||
container: any;
|
||||
package: any;
|
||||
/**
|
||||
* Logger for this plugin
|
||||
*
|
||||
* Instance of winston Logger for sending log messages from this
|
||||
* plugin. Supported methods and their corresponding log levels are
|
||||
* `error`, `warn`, `audit`, `info` and `verbose`.
|
||||
*/
|
||||
logger: Logger;
|
||||
/**
|
||||
* List of login forms provided by this plugin
|
||||
*/
|
||||
loginForms: PluginLoginForm[] = [];
|
||||
/**
|
||||
* List of pages provided by this plugin
|
||||
*/
|
||||
pages: PluginPage[] = [];
|
||||
/**
|
||||
* Additional Config inputComponent types available to render config
|
||||
* entries with.
|
||||
*/
|
||||
inputComponents: Record<string, InputComponent> = {};
|
||||
/**
|
||||
* Extra react component to add to core components
|
||||
*
|
||||
* Interface to augment core components of the web UI. Setting a
|
||||
* component as one of the supported properties of this object will
|
||||
* cause the web UI to render it when displaying that component,
|
||||
* usually at the end. Each component will receive a `plugin` param
|
||||
* which is the instance of the web plugin that contained the
|
||||
* component extra.
|
||||
*/
|
||||
componentExtra: {
|
||||
/** Placed at the end of the controller page. */
|
||||
ControllerPage?: React.ComponentType,
|
||||
/** Placed at the end of the hosts list page. */
|
||||
HostsPage?: React.ComponentType,
|
||||
/**
|
||||
* Placed at the end of each host page. Takes a `host` param which
|
||||
* is the host the page is displayed for.
|
||||
*/
|
||||
HostViewPage?: React.ComponentType,
|
||||
/** Placed at the end of the instance list page. */
|
||||
InstancesPage?: React.ComponentType,
|
||||
/**
|
||||
* Placed at the end of each instance page. Takes an `instance`
|
||||
* param which is the instance the page is displayed for.
|
||||
*/
|
||||
InstanceViewPage?: React.ComponentType,
|
||||
/** Placed at the end of the users list page. */
|
||||
UsersPage?: React.ComponentType,
|
||||
/**
|
||||
* Placed at the end of each user page. Takes a `user` param which
|
||||
* is the user object the page is displayed for.
|
||||
*/
|
||||
UserViewPage?: React.ComponentType,
|
||||
/** Placed at the end of the roles list page. */
|
||||
RolesPage?: React.ComponentType,
|
||||
/**
|
||||
* Placed at the end of each role page. Takes a `role` param which
|
||||
* is the role object the page is displayed for.
|
||||
*/
|
||||
RoleViewPage?: React.ComponentType,
|
||||
} = {};
|
||||
}, lib.PluginWebpackEnvInfo>;
|
||||
|
||||
|
||||
constructor(
|
||||
/**
|
||||
* Webpack container for this plugin
|
||||
*/
|
||||
public container: any,
|
||||
packageData: any,
|
||||
/**
|
||||
* The plugin's own info module
|
||||
*/
|
||||
public info: PluginWebpackEnvInfo,
|
||||
/**
|
||||
* Control link to the controller
|
||||
*
|
||||
* Not connected at the time init is invoked.
|
||||
*/
|
||||
public control: Control,
|
||||
logger: Logger,
|
||||
) {
|
||||
this.package = packageData;
|
||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
||||
/**
|
||||
* Collection of web plugin hooks
|
||||
*/
|
||||
export class WebHooks extends lib.AsyncHookCollection {
|
||||
constructor(logger: lib.Logger) {
|
||||
super(logger);
|
||||
this.controllerConnectionEvent = this.newHook();
|
||||
this.extensionComponents = this.newHook();
|
||||
this.inputComponents = this.newHook();
|
||||
this.loginForms = this.newHook();
|
||||
this.pages = this.newHook();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called immediately after the class is instantiated.
|
||||
*/
|
||||
async init() { }
|
||||
|
||||
/**
|
||||
* Called when an event on the controller connection happens
|
||||
*
|
||||
@@ -212,5 +186,99 @@ export default class BaseWebPlugin {
|
||||
*
|
||||
* @param event - one of connect, drop, resume and close
|
||||
*/
|
||||
onControllerConnectionEvent(event: "connect" | "drop" | "resume" | "close") { }
|
||||
readonly controllerConnectionEvent: lib.AsyncHook<[event: "connect" | "drop" | "resume" | "close"]>;
|
||||
|
||||
/**
|
||||
* Collect additional UI components to render in core ui extension points.
|
||||
*
|
||||
* Each plugin may return a partial mapping of extension slot names
|
||||
* to React components. All returned components are rendered.
|
||||
*
|
||||
* Multiple plugins may contribute to the same slot.
|
||||
*/
|
||||
readonly extensionComponents: lib.AsyncHook<[], Partial<{
|
||||
[K in PluginExtensionSlot]: ExtensionComponent<K>;
|
||||
}>>;
|
||||
|
||||
/**
|
||||
* Collect additional config input components provided by plugins.
|
||||
*
|
||||
* Each plugin may return a mapping of input component names to React components.
|
||||
* These mappings are merged together to form the final registry.
|
||||
*
|
||||
* If multiple plugins define the same key, the last attached handler wins.
|
||||
*/
|
||||
readonly inputComponents: lib.AsyncHook<[], Record<string, InputComponent>>;
|
||||
|
||||
/**
|
||||
* Additional methods used to login to the web ui.
|
||||
*
|
||||
* All returned components are rendered.
|
||||
* Each must has a unique name prefixed with the plugin name.
|
||||
*/
|
||||
readonly loginForms: lib.AsyncHook<[], PluginLoginForm[]>;
|
||||
|
||||
/**
|
||||
* Additional pages accessible on the web ui.
|
||||
*
|
||||
* Each page must have a unique path.
|
||||
*/
|
||||
readonly pages: lib.AsyncHook<[], PluginPage[]>;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||
export interface BaseWebPlugin {
|
||||
onControllerConnectionEvent?(event: "connect" | "drop" | "resume" | "close"): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for web interface plugins
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
||||
export class BaseWebPlugin {
|
||||
/**
|
||||
* Contents of the plugin's package.json file
|
||||
*/
|
||||
package: any;
|
||||
|
||||
pages: PluginPage[] = [];
|
||||
loginForms: PluginLoginForm[] = [];
|
||||
inputComponents: Record<string, InputComponent> = {};
|
||||
componentExtra: Partial<{
|
||||
[K in PluginExtensionSlot]: ExtensionComponent<K>;
|
||||
}> = {};
|
||||
|
||||
constructor(
|
||||
public container: any,
|
||||
packageData: any,
|
||||
public info: lib.PluginWebpackEnvInfo,
|
||||
public control: Control,
|
||||
public logger: lib.Logger,
|
||||
) {
|
||||
this.package = packageData; // strict mode complains if we don't assign it this way
|
||||
|
||||
if (this.onControllerConnectionEvent) {
|
||||
control.hooks.controllerConnectionEvent.attach(info.name, this.onControllerConnectionEvent.bind(this));
|
||||
}
|
||||
|
||||
// Subclasses populate these fields in init(), which runs after the
|
||||
// constructor, so the handlers read them when the hook is collected.
|
||||
control.hooks.inputComponents.attach(info.name, () => this.inputComponents);
|
||||
control.hooks.extensionComponents.attach(info.name, () => this.componentExtra);
|
||||
control.hooks.loginForms.attach(info.name, () => this.loginForms);
|
||||
control.hooks.pages.attach(info.name, () => this.pages);
|
||||
}
|
||||
|
||||
static fromContext(context: WebPluginContext): BaseWebPlugin {
|
||||
return new this(context.container, context.package, context.plugin, context.control, context.logger);
|
||||
}
|
||||
|
||||
detachHooks() {
|
||||
this.control.hooks.detachAll(this.info.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called immediately after the class is instantiated.
|
||||
*/
|
||||
async init() {}
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import { createRoot } from "react-dom/client";
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import App from "./components/App";
|
||||
import BaseWebPlugin, { InputComponent } from "./BaseWebPlugin";
|
||||
import InputRole from "./components/InputRole";
|
||||
import InputModPack from "./components/InputModPack";
|
||||
import { InputTargetVersion, InputPartialVersion, InputFullVersion } from "./components/InputVersion";
|
||||
import { Control, ControlConnector } from "./util/websocket";
|
||||
import { loadedPluginSetKey } from "./util/pluginSet";
|
||||
import * as WebPlugin from "./BaseWebPlugin";
|
||||
import { pages } from "./pages";
|
||||
|
||||
const { ConsoleTransport, WebConsoleFormat, logger } = lib;
|
||||
|
||||
@@ -78,26 +79,44 @@ async function loadPluginInfos(): Promise<[lib.PluginWebpackEnvInfo[], string]>
|
||||
return [pluginInfos, pluginSetKey];
|
||||
}
|
||||
|
||||
async function loadPlugins(pluginInfos: lib.PluginWebpackEnvInfo[], control: Control) {
|
||||
let plugins = new Map<string, BaseWebPlugin>();
|
||||
for (let pluginInfo of pluginInfos) {
|
||||
if (!pluginInfo.enabled) {
|
||||
async function loadPlugins(
|
||||
pluginInfos: lib.PluginWebpackEnvInfo[],
|
||||
control: Control
|
||||
) {
|
||||
const plugins = new Map<string, WebPlugin.BaseWebPlugin>();
|
||||
|
||||
for (const pluginInfo of pluginInfos) {
|
||||
if (!pluginInfo.enabled || !pluginInfo.webEntrypoint) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
let WebPluginClass = BaseWebPlugin;
|
||||
if (pluginInfo.webEntrypoint) {
|
||||
let webModule = (await pluginInfo.container.get(pluginInfo.webEntrypoint))();
|
||||
if (!webModule.WebPlugin) {
|
||||
pluginInfo.error = "Plugin webEntrypoint does not export WebPlugin class";
|
||||
throw new Error(pluginInfo.error);
|
||||
}
|
||||
WebPluginClass = webModule.WebPlugin;
|
||||
const moduleFactory = await pluginInfo.container.get(pluginInfo.webEntrypoint);
|
||||
const webModule = moduleFactory();
|
||||
|
||||
const pluginContext: WebPlugin.WebPluginContext = {
|
||||
control,
|
||||
plugin: pluginInfo,
|
||||
container: pluginInfo.container,
|
||||
package: pluginInfo.package,
|
||||
logger: logger.child({ plugin: pluginInfo.name }),
|
||||
};
|
||||
|
||||
if (typeof webModule.default === "function") {
|
||||
await lib.loadPluginEntrypoint(pluginInfo, "web", pluginContext, webModule);
|
||||
continue;
|
||||
}
|
||||
|
||||
let plugin = new WebPluginClass(pluginInfo.container, pluginInfo.package, pluginInfo, control, logger);
|
||||
await plugin.init();
|
||||
plugins.set(pluginInfo.name, plugin);
|
||||
// migrate: accept plugins which export classes
|
||||
if (webModule.WebPlugin) {
|
||||
logger.warn(`Plugin ${pluginInfo.name} is using deprecated class hooks`);
|
||||
plugins.set(pluginInfo.name, await lib.loadPluginClass(
|
||||
pluginInfo, "web", pluginContext, webModule, "WebPlugin", WebPlugin.BaseWebPlugin
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Plugin ${pluginInfo.name} must export either a default function or WebPlugin`);
|
||||
|
||||
} catch (err: any) {
|
||||
pluginInfo.error = `Error loading plugin: ${err.message}`;
|
||||
@@ -107,26 +126,80 @@ async function loadPlugins(pluginInfos: lib.PluginWebpackEnvInfo[], control: Con
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return plugins;
|
||||
}
|
||||
|
||||
function inputComponentsFromPlugins(plugins: Map<string, BaseWebPlugin>) {
|
||||
const inputComponents: Record<string, InputComponent> = {
|
||||
function mergeWithWarning<V>(
|
||||
entries: Iterable<[string, Iterable<V>]>,
|
||||
getKey: (item: V) => string,
|
||||
label: string
|
||||
): V[] {
|
||||
const map = new Map<string, V>();
|
||||
const sources = new Map<string, string>();
|
||||
|
||||
for (const [source, items] of entries) {
|
||||
for (const item of items) {
|
||||
const key = getKey(item);
|
||||
if (sources.has(key)) {
|
||||
lib.logger.warn(
|
||||
`Plugin ${source} is redefining ${label} "${key}" previously defined by ${sources.get(key)}`
|
||||
);
|
||||
}
|
||||
|
||||
sources.set(key, source);
|
||||
map.set(key, item);
|
||||
}
|
||||
}
|
||||
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
async function inputComponentsFromHooks(control: Control) {
|
||||
const result = await control.hooks.inputComponents.collectEntries();
|
||||
|
||||
result.unshift(["core", {
|
||||
"full_version": InputFullVersion,
|
||||
"partial_version": InputPartialVersion,
|
||||
"target_version": InputTargetVersion,
|
||||
"mod_pack": InputModPack,
|
||||
"role": InputRole,
|
||||
};
|
||||
for (let [pluginName, plugin] of plugins) {
|
||||
for (const [name, Component] of Object.entries(plugin.inputComponents)) {
|
||||
if (Object.prototype.hasOwnProperty.call(inputComponents, name)) {
|
||||
lib.logger.warn(`Plugin ${pluginName} is redefining config inputComponent ${name}`);
|
||||
}]);
|
||||
|
||||
const iterable = result.map(
|
||||
v => [v[0], Object.entries(v[1])] as [string, Iterable<[string, WebPlugin.InputComponent]>]
|
||||
);
|
||||
|
||||
return new Map(mergeWithWarning(iterable, ([key]) => key, "input component"));
|
||||
}
|
||||
|
||||
async function extensionComponentsFromHooks(control: Control) {
|
||||
const extensionComponents = {} as WebPlugin.ExtensionComponents;
|
||||
|
||||
const result = await control.hooks.extensionComponents.collectEntries();
|
||||
for (const [source, record] of result) {
|
||||
for (const [slot, Component] of Object.entries(record) as [
|
||||
WebPlugin.PluginExtensionSlot, React.ComponentType,
|
||||
][]) {
|
||||
if (!extensionComponents[slot]) {
|
||||
extensionComponents[slot] = new Map();
|
||||
}
|
||||
inputComponents[name] = Component;
|
||||
extensionComponents[slot].set(source, Component as any);
|
||||
}
|
||||
}
|
||||
return inputComponents;
|
||||
|
||||
return extensionComponents;
|
||||
}
|
||||
|
||||
async function loginFormsFromHooks(control: Control) {
|
||||
const results = await control.hooks.loginForms.collectEntries();
|
||||
return mergeWithWarning<WebPlugin.PluginLoginForm>(results, item => item.name, "login form");
|
||||
}
|
||||
|
||||
async function pagesFromHooks(control: Control) {
|
||||
const results = await control.hooks.pages.collectEntries();
|
||||
results.unshift(["core", pages]);
|
||||
return mergeWithWarning<WebPlugin.PluginPage>(results, item => item.path, "page");
|
||||
}
|
||||
|
||||
export default async function bootstrap() {
|
||||
@@ -134,16 +207,24 @@ export default async function bootstrap() {
|
||||
level: "verbose",
|
||||
format: new WebConsoleFormat(),
|
||||
}));
|
||||
let [pluginInfos, pluginSetKey] = await loadPluginInfos();
|
||||
const [pluginInfos, pluginSetKey] = await loadPluginInfos();
|
||||
const pluginInfoEntries = pluginInfos.map(p => [p.name, p] as const);
|
||||
lib.registerPluginMessages(pluginInfos);
|
||||
lib.registerPluginPermissions(pluginInfos);
|
||||
lib.addPluginConfigFields(pluginInfos);
|
||||
|
||||
let wsUrl = new URL(webRoot, document.location.href);
|
||||
let controlConnector = new ControlConnector(wsUrl.href, 120);
|
||||
let control = new Control(controlConnector, new Map(pluginInfos.map(p => [p.name, p])), pluginSetKey);
|
||||
let control = new Control(controlConnector, new Map(pluginInfoEntries), pluginSetKey);
|
||||
control.plugins = await loadPlugins(pluginInfos, control);
|
||||
control.inputComponents = inputComponentsFromPlugins(control.plugins);
|
||||
control.loadedPlugins = new Map(pluginInfoEntries.filter(
|
||||
([_, info]) => info.enabled && info.webEntrypoint && !info.error
|
||||
));
|
||||
|
||||
control.inputComponents = await inputComponentsFromHooks(control);
|
||||
control.extensionComponents = await extensionComponentsFromHooks(control);
|
||||
control.loginForms = await loginFormsFromHooks(control);
|
||||
control.pages = await pagesFromHooks(control);
|
||||
|
||||
const root = createRoot(document.getElementById("root") as HTMLDivElement);
|
||||
root.render(<App control={control}/>);
|
||||
|
||||
@@ -33,11 +33,11 @@ function getInitialValues(config: lib.Config<any>, props: BaseConfigTreeProps) {
|
||||
return initialValues;
|
||||
}
|
||||
|
||||
function renderInput(inputComponents: Record<string, InputComponent>, def: lib.FieldDefinition, readonly: boolean) {
|
||||
if (def.inputComponent && Object.prototype.hasOwnProperty.call(inputComponents, def.inputComponent)) {
|
||||
function renderInput(inputComponents: Map<string, InputComponent>, def: lib.FieldDefinition, readonly: boolean) {
|
||||
if (def.inputComponent && inputComponents.has(def.inputComponent)) {
|
||||
// Field.Item will provide the value and onChange props to the component.
|
||||
type InputPartial = React.ComponentClass<Omit<InputComponentProps, "value" | "onChange">>;
|
||||
const CustomInput = inputComponents[def.inputComponent] as unknown as InputPartial;
|
||||
const CustomInput = inputComponents.get(def.inputComponent) as unknown as InputPartial;
|
||||
return <CustomInput fieldDefinition={def} disabled={readonly} />;
|
||||
}
|
||||
if (def.type === "boolean") {
|
||||
@@ -291,7 +291,7 @@ function computeTreeData(
|
||||
children: [],
|
||||
};
|
||||
|
||||
if (def.type === "object" && !Object.keys(control.inputComponents).includes(def.inputComponent!)) {
|
||||
if (def.type === "object" && !control.inputComponents.has(def.inputComponent!)) {
|
||||
let restartRequiredProps = new Set(def.restartRequiredProps || []);
|
||||
childNode.title = <Form.Item
|
||||
label={<>
|
||||
|
||||
@@ -5,6 +5,7 @@ import LockOutlined from "@ant-design/icons/LockOutlined";
|
||||
import notify from "../util/notify";
|
||||
import logo from "../images/logo.png";
|
||||
import ControlContext from "./ControlContext";
|
||||
import { PluginLoginForm } from "../BaseWebPlugin";
|
||||
|
||||
const { Paragraph } = Typography;
|
||||
|
||||
@@ -36,7 +37,7 @@ function TokenAuth(props: SetTokenProps) {
|
||||
}
|
||||
|
||||
export default function LoginForm(props: SetTokenProps) {
|
||||
let plugins = useContext(ControlContext).plugins;
|
||||
const control = useContext(ControlContext);
|
||||
const [clusterName, setClusterName] = useState<string>("Clusterio");
|
||||
|
||||
useEffect(() => {
|
||||
@@ -55,16 +56,14 @@ export default function LoginForm(props: SetTokenProps) {
|
||||
})();
|
||||
}, []);
|
||||
|
||||
let loginForms = [];
|
||||
for (let plugin of plugins.values()) {
|
||||
loginForms.push(...plugin.loginForms);
|
||||
}
|
||||
|
||||
loginForms.push({
|
||||
name: "core.token",
|
||||
title: "Token",
|
||||
Component: TokenAuth,
|
||||
});
|
||||
const loginForms: PluginLoginForm[] = [
|
||||
...control.loginForms,
|
||||
{
|
||||
name: "core.token",
|
||||
title: "Token",
|
||||
Component: TokenAuth,
|
||||
},
|
||||
];
|
||||
|
||||
return <Card style={{ maxWidth: "30em" }}>
|
||||
<Space style={{ width: "100%" }} direction="vertical" align="center">
|
||||
|
||||
@@ -1,29 +1,17 @@
|
||||
import React, { useContext } from "react";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import ControlContext from "./ControlContext";
|
||||
import BaseWebPlugin from "../BaseWebPlugin";
|
||||
import { PluginExtensionSlot, ExtensionSlotProps } from "../BaseWebPlugin";
|
||||
|
||||
|
||||
type PluginExtraProps = {
|
||||
component: string;
|
||||
search?: string;
|
||||
instance?: lib.InstanceDetails;
|
||||
user?: lib.UserDetails;
|
||||
host?: lib.HostDetails;
|
||||
role?: lib.Role;
|
||||
};
|
||||
export default function PluginExtra(props: PluginExtraProps) {
|
||||
let control = useContext(ControlContext);
|
||||
|
||||
let components = [];
|
||||
for (let [name, plugin] of control.plugins) {
|
||||
if (Object.prototype.hasOwnProperty.call(plugin.componentExtra, props.component)) {
|
||||
type ComponentExtra = {[key: string]: React.ComponentType<PluginExtraProps & {plugin:BaseWebPlugin}>};
|
||||
let ComponentExtra = (plugin.componentExtra as ComponentExtra)[props.component];
|
||||
components.push(<ComponentExtra key={name} plugin={plugin} {...props}/>);
|
||||
}
|
||||
}
|
||||
return components;
|
||||
export default function PluginExtra<
|
||||
C extends PluginExtensionSlot
|
||||
> (
|
||||
props: { component: C } & ExtensionSlotProps[C]
|
||||
) {
|
||||
const control = useContext(ControlContext);
|
||||
const components = control.extensionComponents[props.component];
|
||||
return components && [...components].map(([source, Component]) => (
|
||||
<Component key={source} {...props} />
|
||||
));
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export default function PluginViewPage() {
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const plugin = control.plugins.get(pluginName);
|
||||
const loadedPlugin = control.loadedPlugins.get(pluginName);
|
||||
const pluginInfo = control.pluginInfos.get(pluginName);
|
||||
const pluginTitle = pluginInfo ? pluginInfo.title : pluginName;
|
||||
let nav = [{ name: "Plugins", path: "/plugins" }, { name: pluginTitle }];
|
||||
@@ -46,7 +46,7 @@ export default function PluginViewPage() {
|
||||
}
|
||||
|
||||
const pluginError = pluginMeta.web.error ?? pluginInfo?.error;
|
||||
if (!plugin) {
|
||||
if (!loadedPlugin) {
|
||||
return <PageLayout nav={nav}>
|
||||
<Descriptions bordered size="small" title={pluginTitle}>
|
||||
<Descriptions.Item label="Version">{pluginMeta.version}</Descriptions.Item>
|
||||
@@ -81,22 +81,22 @@ export default function PluginViewPage() {
|
||||
<Descriptions.Item label="Enabled on controller" span={2}>
|
||||
{pluginMeta.enabled ? "Yes" : "No"}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Description" span={3}>{plugin.info.description}</Descriptions.Item>
|
||||
{plugin.package.homepage ? <Descriptions.Item label="Homepage" span={3}>
|
||||
<a href={plugin.package.homepage}>{plugin.package.homepage}</a>
|
||||
<Descriptions.Item label="Description" span={3}>{loadedPlugin.description}</Descriptions.Item>
|
||||
{loadedPlugin.package.homepage ? <Descriptions.Item label="Homepage" span={3}>
|
||||
<a href={loadedPlugin.package.homepage}>{loadedPlugin.package.homepage}</a>
|
||||
</Descriptions.Item> : null}
|
||||
{plugin.package.author ? <Descriptions.Item label="Author" span={3}>
|
||||
{plugin.package.author}
|
||||
{loadedPlugin.package.author ? <Descriptions.Item label="Author" span={3}>
|
||||
{loadedPlugin.package.author}
|
||||
</Descriptions.Item> : null}
|
||||
<Descriptions.Item label="License" span={3}>{plugin.package.license}</Descriptions.Item>
|
||||
<Descriptions.Item label="License" span={3}>{loadedPlugin.package.license}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{pluginMeta.version !== plugin.package.version ? <Alert
|
||||
{pluginMeta.version !== loadedPlugin.package.version ? <Alert
|
||||
style={{
|
||||
marginTop: "1em",
|
||||
}}
|
||||
message="Version missmatch detected"
|
||||
description={
|
||||
`The version of the web interface module for this plugin (${plugin.package.version}) `+
|
||||
`The version of the web interface module for this plugin (${loadedPlugin.package.version}) `+
|
||||
`does not match the version running on the controller (${pluginMeta.version}), `+
|
||||
"spurious errors may occur. This usually happens when the plugin is updated but the "+
|
||||
"controller has not been restarted yet, but may also be due to an outdated build."
|
||||
|
||||
@@ -47,17 +47,15 @@ export default function PluginsPage() {
|
||||
|
||||
let tableContents: PluginRow[] = [];
|
||||
for (let meta of pluginList) {
|
||||
if (control.plugins.has(meta.name)) {
|
||||
let plugin = control.plugins.get(meta.name)!;
|
||||
const info = control.loadedPlugins.get(meta.name);
|
||||
if (info) {
|
||||
tableContents.push({
|
||||
meta,
|
||||
info: plugin.info,
|
||||
package: plugin.package,
|
||||
meta, info,
|
||||
package: info.package,
|
||||
});
|
||||
} else {
|
||||
tableContents.push({
|
||||
meta,
|
||||
info: control.pluginInfos.get(meta.name),
|
||||
meta, info: control.pluginInfos.get(meta.name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import ChangeLogModal from "./ChangeLogModal";
|
||||
import AboutModal from "./AboutModal";
|
||||
import Link from "./Link";
|
||||
|
||||
import { pages } from "../pages";
|
||||
import { saveJson } from "../util/save_file";
|
||||
import { useAccount } from "../model/account";
|
||||
import { DraggingContext } from "../model/is_dragging";
|
||||
@@ -60,7 +59,6 @@ export default function SiteLayout() {
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
let account = useAccount();
|
||||
let plugins = useContext(ControlContext).plugins;
|
||||
const control = useContext(ControlContext);
|
||||
const [dragging, setDragging] = useState(0);
|
||||
const [aboutOpen, setAboutOpen] = useState(false);
|
||||
@@ -110,13 +108,9 @@ export default function SiteLayout() {
|
||||
],
|
||||
};
|
||||
|
||||
let combinedPages = [...pages];
|
||||
for (let plugin of plugins.values()) {
|
||||
combinedPages.push(...plugin.pages);
|
||||
}
|
||||
|
||||
let menuItems: MenuItem[] = [];
|
||||
let menuGroups = new Map();
|
||||
const combinedPages = [...control.pages];
|
||||
for (let { sidebarName, sidebarGroup, permission, path } of combinedPages) {
|
||||
if (
|
||||
!sidebarName || permission && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// <reference path="../global.d.ts" preserve="true" />
|
||||
export { default as bootstrap } from "./bootstrap";
|
||||
export { default as notify, notifyErrorHandler } from "./util/notify";
|
||||
export { default as BaseWebPlugin } from "./BaseWebPlugin";
|
||||
export * from "./BaseWebPlugin";
|
||||
export * from "./util/websocket";
|
||||
|
||||
export * from "./model/account";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import packageJson from "../../package.json";
|
||||
import BaseWebPlugin, { type InputComponent } from "../BaseWebPlugin";
|
||||
import * as WebPlugin from "../BaseWebPlugin";
|
||||
|
||||
const { logFilter, logger } = lib;
|
||||
|
||||
@@ -51,9 +51,13 @@ export class Control extends lib.Link {
|
||||
/** Roles of the account this control link is connected as. */
|
||||
accountRoles: lib.AccountRole[] | null = null;
|
||||
|
||||
/** Plugins loaded in the web interface */
|
||||
public plugins = new Map<string, BaseWebPlugin>();
|
||||
public inputComponents: Record<string, InputComponent> = {};
|
||||
public hooks = new WebPlugin.WebHooks(logger);
|
||||
public plugins = new Map<string, WebPlugin.BaseWebPlugin>();
|
||||
public loadedPlugins = new Map<string, lib.PluginWebpackEnvInfo>();
|
||||
public inputComponents = new Map<string, WebPlugin.InputComponent>();
|
||||
public extensionComponents: Partial<WebPlugin.ExtensionComponents> = {};
|
||||
public loginForms: WebPlugin.PluginLoginForm[] = [];
|
||||
public pages: WebPlugin.PluginPage[] = [];
|
||||
|
||||
/** Updates not handled by the subscription service */
|
||||
accountUpdateHandlers: accountHandler[] = [];
|
||||
@@ -101,11 +105,7 @@ export class Control extends lib.Link {
|
||||
});
|
||||
|
||||
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||
this.connector.on(event, () => {
|
||||
for (let plugin of this.plugins.values()) {
|
||||
plugin.onControllerConnectionEvent(event);
|
||||
}
|
||||
});
|
||||
this.connector.on(event, this.hooks.controllerConnectionEvent.listener);
|
||||
}
|
||||
|
||||
this.handle(lib.AccountUpdateEvent, this.handleAccountUpdateEvent.bind(this));
|
||||
|
||||
Reference in new issue
Block a user