diff --git a/packages/web_ui/src/BaseWebPlugin.ts b/packages/web_ui/src/BaseWebPlugin.ts index 90a750d7..902775ce 100644 --- a/packages/web_ui/src/BaseWebPlugin.ts +++ b/packages/web_ui/src/BaseWebPlugin.ts @@ -140,6 +140,46 @@ export type ExtensionComponent = React.ComponentT export type ExtensionComponents = { [K in PluginExtensionSlot]: Map> }; +/** + * Action added by a plugin to the actions dropdown of a page. + */ +export type PluginPageAction = { + /** Unique within the plugin, the web UI prefixes it with the plugin name. */ + key: string; + label: React.ReactNode; + icon?: React.ReactNode; + disabled?: boolean; + danger?: boolean; + onClick?: () => void; +}; + +export type PageActionsSlotProps = { + /** Controller control button on the controller page. */ + ControllerPage: Record; + /** Host control button on each host page. */ + HostViewPage: { + host: lib.HostDetails; + }; + /** More dropdown on each instance and template page. */ + InstanceViewPage: { + instance: lib.InstanceDetails; + }; + /** More dropdown on each user page. */ + UserViewPage: { + user: lib.UserDetails; + }; +}; + +export type PageActionsSlot = keyof PageActionsSlotProps; + +/** + * Returns the actions to add to a page. It is called during render like a + * React hook, so it may call hooks such as useAccount or useState. + */ +export type PageActionsHook = (props: PageActionsSlotProps[K]) => PluginPageAction[]; + +export type PageActions = { [K in PageActionsSlot]: Map> }; + export type WebPluginContext = lib.PluginLoadContext<{ control: Control; container: any; @@ -156,6 +196,7 @@ export class WebHooks extends lib.AsyncHookCollection { this.extensionComponents = this.newHook(); this.inputComponents = this.newHook(); this.loginForms = this.newHook(); + this.pageActions = this.newHook(); this.pages = this.newHook(); } @@ -225,6 +266,28 @@ export class WebHooks extends lib.AsyncHookCollection { */ readonly loginForms: lib.AsyncHook<[], PluginLoginForm[]>; + /** + * Additional actions for the actions dropdown on resource pages. + * + * Each plugin may return a partial mapping of page names to + * functions returning the actions for that page. Plugin actions are + * placed after the built in ones and before stop and delete. + * + * @example + * ```ts + * control.hooks.pageActions.attach("my_plugin", () => ({ + * UserViewPage: ({ user }) => [{ + * key: "warn", + * label: "Warn", + * onClick: () => control.send(new WarnUserRequest(user.name)), + * }], + * })); + * ``` + */ + readonly pageActions: lib.AsyncHook<[], Partial<{ + [K in PageActionsSlot]: PageActionsHook; + }>>; + /** * Additional pages accessible on the web ui. * diff --git a/packages/web_ui/src/bootstrap.tsx b/packages/web_ui/src/bootstrap.tsx index b87d4852..69538deb 100644 --- a/packages/web_ui/src/bootstrap.tsx +++ b/packages/web_ui/src/bootstrap.tsx @@ -12,6 +12,7 @@ import { InputInstanceTemplate } from "./components/InputInstance"; import { InputTargetVersion, InputPartialVersion, InputFullVersion } from "./components/InputVersion"; import { Control, ControlConnector } from "./util/websocket"; import { loadedPluginSetKey } from "./util/pluginSet"; +import { pageActionsFromHooks } from "./util/plugin_actions"; import * as WebPlugin from "./BaseWebPlugin"; import { pages } from "./pages"; @@ -209,6 +210,7 @@ export default async function bootstrap() { control.inputComponents = await inputComponentsFromHooks(control); control.extensionComponents = await extensionComponentsFromHooks(control); + control.pageActions = await pageActionsFromHooks(control.hooks); control.loginForms = await loginFormsFromHooks(control); control.pages = await pagesFromHooks(control); diff --git a/packages/web_ui/src/components/ControllerPage.tsx b/packages/web_ui/src/components/ControllerPage.tsx index cc064e23..51ce66f7 100644 --- a/packages/web_ui/src/components/ControllerPage.tsx +++ b/packages/web_ui/src/components/ControllerPage.tsx @@ -19,6 +19,7 @@ import PageLayout from "./PageLayout"; import notify, { notifyErrorHandler } from "../util/notify"; import webUiPackage from "../../package.json"; import { hasNpmButtonPermission, NpmButton } from "./NpmButton"; +import usePluginActions from "../util/usePluginActions"; import VariableDropdownButton, { VariableDropdownButtonProps } from "./VariableDropdownButton"; const { Title } = Typography; @@ -30,6 +31,7 @@ function ControllerControlButton({ canRestart, restartRequired }: ControllerCont const control = useContext(ControlContext); const [modal, modalContext] = Modal.useModal(); const actions: VariableDropdownButtonProps["actions"] = []; + const pluginActions = usePluginActions("ControllerPage", {}); if (account.hasPermission("core.controller.restart") && canRestart) { actions.push({ @@ -71,6 +73,8 @@ function ControllerControlButton({ canRestart, restartRequired }: ControllerCont }); } + actions.push(...pluginActions); + if (account.hasPermission("core.controller.stop")) { actions.push({ key: "stop", diff --git a/packages/web_ui/src/components/HostViewPage.tsx b/packages/web_ui/src/components/HostViewPage.tsx index fef62835..b56f81ce 100644 --- a/packages/web_ui/src/components/HostViewPage.tsx +++ b/packages/web_ui/src/components/HostViewPage.tsx @@ -25,22 +25,25 @@ import { import { useSystems } from "../model/system"; import useResourceState from "../util/useResourceState"; import { hasNpmButtonPermission, NpmButton } from "./NpmButton"; +import usePluginActions from "../util/usePluginActions"; import VariableDropdownButton, { VariableDropdownButtonProps } from "./VariableDropdownButton"; const { Title } = Typography; type HostControlButtonProps = { - hostId: number, + host: lib.HostDetails, instances: ReadonlyMap, canRestart?: boolean, restartRequired?: boolean, }; -function HostControlButton({ hostId, instances, canRestart, restartRequired }: HostControlButtonProps) { +function HostControlButton({ host, instances, canRestart, restartRequired }: HostControlButtonProps) { const account = useAccount(); const control = useContext(ControlContext); const [modal, modalContext] = Modal.useModal(); + const hostId = host.id; const actions: VariableDropdownButtonProps["actions"] = []; + const pluginActions = usePluginActions("HostViewPage", { host }); if (account.hasPermission("core.host.restart") && canRestart) { actions.push({ @@ -93,6 +96,8 @@ function HostControlButton({ hostId, instances, canRestart, restartRequired }: H }); } + actions.push(...pluginActions); + if (account.hasPermission("core.host.stop")) { actions.push({ key: "stop", @@ -174,7 +179,7 @@ export default function HostViewPage() { let hostButtons = ["items"][number]; @@ -150,6 +151,7 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { let [host] = useHost(instance.assignedHost); const [instances] = useInstances(); const canCreate = account.hasPermission("core.instance.create"); + const pluginActions = usePluginActions("InstanceViewPage", { instance }); let instanceButtonMenuItems: MenuItem[] = []; if (account.hasPermission("core.instance.export_data")) { @@ -166,6 +168,7 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { label: "Extract players from save", }); } + instanceButtonMenuItems.push(...pluginActions); if (account.hasPermission("core.instance.delete")) { if (instanceButtonMenuItems.length) { instanceButtonMenuItems.push({ type: "divider" }); @@ -230,6 +233,10 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { icon={} onClick={confirmDelete} >Delete} + {pluginActions.length > 0 + && + + } ; } @@ -256,11 +263,7 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { buttonText="Create template" buttonType="default" />} - {account.hasAnyPermission( - "core.instance.export_data", - "core.instance.extract_players", - "core.instance.delete", - ) + {instanceButtonMenuItems.length > 0 && } diff --git a/packages/web_ui/src/components/UserViewPage.tsx b/packages/web_ui/src/components/UserViewPage.tsx index 5e3581c0..67e9867e 100644 --- a/packages/web_ui/src/components/UserViewPage.tsx +++ b/packages/web_ui/src/components/UserViewPage.tsx @@ -1,10 +1,11 @@ import React, { useEffect, useContext, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { - Button, Col, Descriptions, Form, Input, Popconfirm, + Button, Col, Descriptions, Dropdown, Form, Input, Popconfirm, Row, Table, Tag, Select, Space, Switch, } from "antd"; import DeleteOutlined from "@ant-design/icons/DeleteOutlined"; +import DownOutlined from "@ant-design/icons/DownOutlined"; import * as lib from "@clusterio/lib"; @@ -21,6 +22,7 @@ import ResourceNotes from "./ResourceNotes"; import ResourceState from "./ResourceState"; import useRowNavigation from "../util/useRowNavigation"; import useResourceState from "../util/useResourceState"; +import usePluginActions from "../util/usePluginActions"; import Link from "./Link"; import notify, { notifyErrorHandler } from "../util/notify"; import { formatDuration } from "../util/time_format"; @@ -29,6 +31,16 @@ import { formatFirstSeen, formatLastSeen, sortFirstSeen, sortLastSeen, useUser } const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare; +function UserPluginActions(props: { user: lib.UserDetails }) { + const pluginActions = usePluginActions("UserViewPage", { user: props.user }); + if (!pluginActions.length) { + return null; + } + return + + ; +} + // The user page has a lot of optional elements, that does not make it // praticularly complicated. // eslint-disable-next-line complexity @@ -167,6 +179,7 @@ export default function UserViewPage() { } + } />
; } + const mainDisabled = props.disabled || mainAction.disabled; const buttonProps: DropdownButtonProps = { ...props, danger: mainAction.danger, onClick: (event) => { event.stopPropagation(); - if (mainAction.onClick) { + if (!mainDisabled && mainAction.onClick) { mainAction.onClick(); } }, }; return menuActions.length === 0 - ? : e.domEvent.stopPropagation() }} buttonsRender={([left, right]) => [ - left, React.cloneElement(right as any, { onClick: (e: any) => e.stopPropagation() }), + React.cloneElement(left as any, { disabled: mainDisabled }), + React.cloneElement(right as any, { onClick: (e: any) => e.stopPropagation() }), ]} > {mainAction.label} diff --git a/packages/web_ui/src/util/plugin_actions.ts b/packages/web_ui/src/util/plugin_actions.ts new file mode 100644 index 00000000..fe4ab842 --- /dev/null +++ b/packages/web_ui/src/util/plugin_actions.ts @@ -0,0 +1,34 @@ +import type { + PageActions, PageActionsHook, PageActionsSlot, PageActionsSlotProps, PluginPageAction, WebHooks, +} from "../BaseWebPlugin"; + +export async function pageActionsFromHooks(hooks: WebHooks) { + const pageActions: Partial = {}; + for (const [source, record] of await hooks.pageActions.collectEntries()) { + for (const [slot, useActions] of Object.entries(record) as [PageActionsSlot, PageActionsHook][]) { + if (!pageActions[slot]) { + pageActions[slot] = new Map(); + } + pageActions[slot].set(source, useActions); + } + } + return pageActions; +} + +/** + * Call each plugin's actions hook for a page and prefix the keys with the + * plugin name. Must be called during render, the set of plugins is fixed + * after bootstrap so the hooks are called in the same order every time. + */ +export function callPageActions( + hooks: Map> | undefined, + props: PageActionsSlotProps[K], +) { + const actions: PluginPageAction[] = []; + for (const [source, useActions] of hooks ?? []) { + for (const action of useActions(props)) { + actions.push({ ...action, key: `${source}.${action.key}` }); + } + } + return actions; +} diff --git a/packages/web_ui/src/util/usePluginActions.ts b/packages/web_ui/src/util/usePluginActions.ts new file mode 100644 index 00000000..d80457d7 --- /dev/null +++ b/packages/web_ui/src/util/usePluginActions.ts @@ -0,0 +1,14 @@ +import { useContext } from "react"; + +import ControlContext from "../components/ControlContext"; +import type { PageActionsSlot, PageActionsSlotProps, PluginPageAction } from "../BaseWebPlugin"; +import { callPageActions } from "./plugin_actions"; + +/** Actions plugins add to the dropdown of a page. */ +export default function usePluginActions( + slot: K, + props: PageActionsSlotProps[K], +): PluginPageAction[] { + const control = useContext(ControlContext); + return callPageActions(control.pageActions[slot], props); +} diff --git a/packages/web_ui/src/util/websocket.ts b/packages/web_ui/src/util/websocket.ts index 805899a4..d0c492fe 100644 --- a/packages/web_ui/src/util/websocket.ts +++ b/packages/web_ui/src/util/websocket.ts @@ -64,6 +64,7 @@ export class Control extends lib.Link { public loadedPlugins = new Map(); public inputComponents = new Map(); public extensionComponents: Partial = {}; + public pageActions: Partial = {}; public loginForms: WebPlugin.PluginLoginForm[] = []; public pages: WebPlugin.PluginPage[] = []; diff --git a/test/web_ui/plugin_actions.js b/test/web_ui/plugin_actions.js new file mode 100644 index 00000000..a80f0846 --- /dev/null +++ b/test/web_ui/plugin_actions.js @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; + +import * as lib from "@clusterio/lib"; +import { callPageActions, pageActionsFromHooks } from "../../packages/web_ui/src/util/plugin_actions.ts"; + +// BaseWebPlugin.ts uses parameter properties, which Node can't strip +class WebHooks extends lib.AsyncHookCollection { + pageActions = this.newHook(); +} + +describe("web_ui/util/plugin_actions", function() { + it("should prefix keys with the plugin name and keep plugin order", async function() { + const hooks = new WebHooks(lib.logger); + hooks.pageActions.attach("alpha", () => ({ + UserViewPage: ({ user }) => [{ key: "greet", label: `Hello ${user.name}` }], + })); + hooks.pageActions.attach("beta", () => ({ + UserViewPage: () => [{ key: "a", label: "A" }, { key: "b", label: "B", danger: true }], + HostViewPage: () => [{ key: "c", label: "C" }], + })); + hooks.pageActions.attach("gamma", () => ({})); + + const pageActions = await pageActionsFromHooks(hooks); + assert.deepEqual(Object.keys(pageActions).sort(), ["HostViewPage", "UserViewPage"]); + assert.deepEqual(callPageActions(pageActions.UserViewPage, { user: { name: "bob" } }), [ + { key: "alpha.greet", label: "Hello bob" }, + { key: "beta.a", label: "A" }, + { key: "beta.b", label: "B", danger: true }, + ]); + assert.deepEqual(callPageActions(pageActions.InstanceViewPage, { instance: {} }), []); + }); +});