From 3d26371fa90db2d1e5c1047e33e5a10395e0c930 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 02:56:56 +0100 Subject: [PATCH 1/8] Make web pages pluggable Refactor the page handling of the web interface to allow plugins to add their own pages. --- packages/lib/plugin.js | 22 +++++++ packages/web_ui/src/components/SiteLayout.jsx | 57 ++++++------------- packages/web_ui/src/pages.jsx | 29 ++++++++++ 3 files changed, 67 insertions(+), 41 deletions(-) create mode 100644 packages/web_ui/src/pages.jsx diff --git a/packages/lib/plugin.js b/packages/lib/plugin.js index 960150a0..046190fd 100644 --- a/packages/lib/plugin.js +++ b/packages/lib/plugin.js @@ -439,6 +439,21 @@ class BaseControlPlugin { * form. */ +/** + * Plugin supplied pages + * @typedef {Object} module:Lib/plugin~Page + * @property {string} path - URL path to this page. + * @property {string=} sidebarPath - + * If present and this path matches one of the pages in the sidebar it + * will cause that sidebar entry to be highlighted as active. + * @property {string=} sidebarName - + * If present creates an entry in the sidebar for this page with the + * given text. + * @property {ReactNode} content - + * A react node which is rendered when this page is navigated to. + * Should render a PageLayout. + */ + /** * Base class for web interface plugins * @@ -477,6 +492,13 @@ class BaseWebPlugin { * @type {Array} */ this.loginForms = []; + + /** + * List of pages provided by this plugin + * + * @type {Array} + */ + this.pages = []; } /** diff --git a/packages/web_ui/src/components/SiteLayout.jsx b/packages/web_ui/src/components/SiteLayout.jsx index fda48ca9..eded71c2 100644 --- a/packages/web_ui/src/components/SiteLayout.jsx +++ b/packages/web_ui/src/components/SiteLayout.jsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useContext, useEffect, useState } from "react"; import { Switch, Route, useHistory } from "react-router-dom"; import { Dropdown, Layout, Menu } from "antd"; import UserOutlined from "@ant-design/icons/UserOutlined"; @@ -7,46 +7,21 @@ import webUiPackage from "../../package.json"; import { useAccount } from "../model/account"; import ErrorBoundary from "./ErrorBoundary"; import ErrorPage from "./ErrorPage"; +import PluginsContext from "./PluginsContext"; +import { pages } from "../pages"; const { Header, Sider } = Layout; -import MasterPage from "./MasterPage"; -import SlavesPage from "./SlavesPage"; -import InstancesPage from "./InstancesPage"; -import InstanceViewPage from "./InstanceViewPage"; -import UsersPage from "./UsersPage"; -import UserViewPage from "./UserViewPage"; -import RolesPage from "./RolesPage"; -import RoleViewPage from "./RoleViewPage"; -import PluginsPage from "./PluginsPage"; -import PluginViewPage from "./PluginViewPage"; - -const pages = [ - { path: "/instances/:id/view", sidebarPath: "/instances", content: }, - { path: "/users/:name/view", sidebarPath: "/users", content: }, - { path: "/roles/:id/view", sidebarPath: "/roles", content: }, - { path: "/plugins/:name/view", sidebarPath: "/plugins", content: }, -]; - -const sidebar = [ - { name: "Master", path: "/master", content: }, - { name: "Slaves", path: "/slaves", content: }, - { name: "Instances", path: "/instances", content: }, - { name: "Users", path: "/users", content: }, - { name: "Roles", path: "/roles", content: }, - { name: "Plugins", path: "/plugins", content: }, -]; - - export default function SiteLayout(props) { let history = useHistory(); - let [sidebarPath, setSidebarPath] = useState(null); + let [currentSidebarPath, setCurrentSidebarPath] = useState(null); let account = useAccount(); + let plugins = useContext(PluginsContext); function SetSidebar(setSidebarProps) { useEffect(() => { - setSidebarPath(setSidebarProps.path); + setCurrentSidebarPath(setSidebarProps.path); }); return null; } @@ -57,6 +32,10 @@ export default function SiteLayout(props) { { account.logOut(); }}>Log out ; + let combinedPages = [...pages]; + for (let plugin of plugins.values()) { + combinedPages.push(...plugin.pages); + } return
@@ -86,27 +65,23 @@ export default function SiteLayout(props) { > history.push(key)} > - {sidebar.map(({name, path}) => {name})} + {combinedPages.map(({sidebarName, path}) => ( + sidebarName ? {sidebarName} : null) + )} - {sidebar.map(({path, content}) => - + {combinedPages.map(({path, sidebarPath, content}) => + {content} )} - {pages.map(page => - - - {page.content} - - )} diff --git a/packages/web_ui/src/pages.jsx b/packages/web_ui/src/pages.jsx new file mode 100644 index 00000000..6ffe389b --- /dev/null +++ b/packages/web_ui/src/pages.jsx @@ -0,0 +1,29 @@ +import React from "react"; + +import MasterPage from "./components/MasterPage"; +import SlavesPage from "./components/SlavesPage"; +import InstancesPage from "./components/InstancesPage"; +import InstanceViewPage from "./components/InstanceViewPage"; +import UsersPage from "./components/UsersPage"; +import UserViewPage from "./components/UserViewPage"; +import RolesPage from "./components/RolesPage"; +import RoleViewPage from "./components/RoleViewPage"; +import PluginsPage from "./components/PluginsPage"; +import PluginViewPage from "./components/PluginViewPage"; + + +export const pages = [ + { path: "/master", sidebarName: "Master", content: }, + { path: "/slaves", sidebarName: "Slaves", content: }, + { path: "/instances", sidebarName: "Instances", content: }, + { path: "/instances/:id/view", sidebarPath: "/instances", content: }, + { path: "/users", sidebarName: "Users", content: }, + { path: "/users/:name/view", sidebarPath: "/users", content: }, + { path: "/roles", sidebarName: "Roles", content: }, + { path: "/roles/:id/view", sidebarPath: "/roles", content: }, + { path: "/plugins", sidebarName: "Plugins", content: }, + { path: "/plugins/:name/view", sidebarPath: "/plugins", content: }, +]; + +export const sidebarPages = [ +]; From 48786f1e59916b505401bafcd3593b054c4c0361 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 02:58:52 +0100 Subject: [PATCH 2/8] Fix --dev-plugin breaking after bd53339 The automatic determination of the public path for plugins works correctly when they are build for production and loaded from their respective paths. But when the dev middelware compiles it, it doesn't know the correct path to host it at withouth the publicPath being set. Fix by setting publicPath explicitly when compiling with the dev middleware. --- packages/master/master.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/master/master.js b/packages/master/master.js index f82e2b31..4f2e6ee6 100755 --- a/packages/master/master.js +++ b/packages/master/master.js @@ -2012,7 +2012,7 @@ async function startServer(args) { const webpackDevMiddleware = require("webpack-dev-middleware"); const webpackConfigs = []; if (args.dev) { - webpackConfigs.push(require("./webpack.config")); + webpackConfigs.push(require("./webpack.config")({})); } if (args.devPlugin) { for (let name of args.devPlugin) { @@ -2020,14 +2020,14 @@ async function startServer(args) { if (!info) { throw new libErrors.StartupError(`No plugin named ${name}`); } - webpackConfigs.push( - require(path.posix.join(info.requirePath, "webpack.config")) - ); + let config = require(path.posix.join(info.requirePath, "webpack.config"))({}); + config.output.publicPath = `/plugins/${name}/`; + webpackConfigs.push(config); } } /* eslint-enable global-require */ - const compiler = webpack(webpackConfigs.map(config => config({}))); + const compiler = webpack(webpackConfigs); devMiddleware = webpackDevMiddleware(compiler, {}); app.use(devMiddleware); } From de629d9416a89681000788cfd10b0651b5b84533 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 03:17:49 +0100 Subject: [PATCH 3/8] Pass link to plugin message handlers For master plugins a message can be received from any of the clients corrently connected to the master. In order for plugins to be able to handle link specific requests they need a reference to the link messages was received from. Add link as the third argument to plugin message handlers. --- packages/lib/plugin.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/lib/plugin.js b/packages/lib/plugin.js index 046190fd..74a27960 100644 --- a/packages/lib/plugin.js +++ b/packages/lib/plugin.js @@ -530,7 +530,7 @@ function attachPluginMessages(link, plugin) { messageFormat.attach(link); } else { - messageFormat.attach(link, async (message, format) => await plugin[handler](message, format)); + messageFormat.attach(link, async (message, format) => await plugin[handler](message, format, link)); } } catch (err) { From 0a6e26bb2db32760cf3efe1330e7ab2ad2df8899 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 03:20:32 +0100 Subject: [PATCH 4/8] Add connection events for control connections Add hooks for plugins to be able to handle connection state changes for control connections on the master server and in the web interface. --- packages/lib/plugin.js | 73 ++++++++++++++++++++++++++ packages/master/master.js | 8 +++ packages/web_ui/src/util/websocket.jsx | 8 +++ 3 files changed, 89 insertions(+) diff --git a/packages/lib/plugin.js b/packages/lib/plugin.js index 74a27960..a45bb7c9 100644 --- a/packages/lib/plugin.js +++ b/packages/lib/plugin.js @@ -329,6 +329,43 @@ class BaseMasterPlugin { */ onSlaveConnectionEvent(connection, event) { } + /** + * Called when an avent on a control connection happens + * + * The event param may be one of connect, drop, resume and close and has + * the following meaning: + * + * ##### connect + * + * Invoked when a new connection to the control has been established. + * + * ##### drop + * + * Invoked when a connection loss is detected between the master and a + * control. Plugins should respond to this event by throtteling + * messages it is sending to the given control connection to an absolute + * minimum. + * + * Messages sent over a dropped control connection will get queued up in + * memory on the master and sent all in one go when the connection is + * re-established again. + * + * ##### resume + * + * Invoked when a connection that had previously been dropped is + * re-established. + * + * ##### close + * + * Invoked when the connection to the control has been closed. + * + * @param {module:master/master~ControlConnection} connection - + * The connection the event occured on. + * @param {string} event - one of connect, drop, resume, and close. + */ + onControlConnectionEvent(connection, event) { } + + /** * Called when a slave is preparing to disconnect from the master * @@ -505,6 +542,42 @@ class BaseWebPlugin { * Called immediately after the class is instantiated. */ async init() { } + + /** + * Called when an event on the master connection happens + * + * The event param may be one of connect, drop, resume and close and has + * the following meaning: + * + * ##### connect + * + * Invoked when a new connection to the master has been established. + * + * ##### drop + * + * Invoked when a connection loss is detected between the control link + * and the master. Plugins should respond to this event by throtteling + * messages it is sending to the master to an absolute minimum. + * + * Messages sent over a dropped master connection will get queued up in + * memory in the browser and sent all in one go when the connection is + * re-established again. + * + * ##### resume + * + * Invoked when the connection that had previously dropped is + * re-established. + * + * ##### close + * + * Invoked when the connection to the master has been closed. This + * typically means the master server has shut down. Plugins should not + * send any messages that goes to or via the master server after the + * connection has been closed and before a new one is established. + * + * @param {string} event - one of connect, drop, resume and close + */ + onMasterConnectionEvent(event) { } } /** diff --git a/packages/master/master.js b/packages/master/master.js index 4f2e6ee6..e70b488b 100755 --- a/packages/master/master.js +++ b/packages/master/master.js @@ -696,6 +696,14 @@ class ControlConnection extends BaseConnection { debugEvents.off("message", this.ws_dumper); } }); + + for (let event of ["connect", "drop", "resume", "close"]) { + this.connector.on(event, () => { + for (let masterPlugin of masterPlugins.values()) { + masterPlugin.onControlConnectionEvent(this, event); + } + }); + } } async getMasterConfigRequestHandler() { diff --git a/packages/web_ui/src/util/websocket.jsx b/packages/web_ui/src/util/websocket.jsx index dd93c94a..1faeb891 100644 --- a/packages/web_ui/src/util/websocket.jsx +++ b/packages/web_ui/src/util/websocket.jsx @@ -73,6 +73,14 @@ export class Control extends libLink.Link { this.connector.on("close", () => { this.accountName = null; }); + + for (let event of ["connect", "drop", "resume", "close"]) { + this.connector.on(event, () => { + for (let plugin of this.plugins.values()) { + plugin.onMasterConnectionEvent(event); + } + }); + } } async logMessageEventHandler(message) { From 6c19145734fc17bfe7e6180b940c3c6da342de7d Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 03:21:59 +0100 Subject: [PATCH 5/8] Add control reference to web plugins Add reference to the Control instance in BaseWebPlugin for web plugin code to use in a similar manner to the instance reference in instance plugin code. --- packages/lib/plugin.js | 7 +++++++ packages/web_ui/src/util/websocket.jsx | 1 + 2 files changed, 8 insertions(+) diff --git a/packages/lib/plugin.js b/packages/lib/plugin.js index a45bb7c9..fbae5fed 100644 --- a/packages/lib/plugin.js +++ b/packages/lib/plugin.js @@ -514,6 +514,13 @@ class BaseWebPlugin { */ this.info = info; + /** + * Control link to the master server, not available until the + * connect event in onMasterConnectionEvent is signaled. + * @type {?module:lib/link.Link} + */ + this.control = null; + /** * Logger for this plugin * diff --git a/packages/web_ui/src/util/websocket.jsx b/packages/web_ui/src/util/websocket.jsx index 1faeb891..f683fea0 100644 --- a/packages/web_ui/src/util/websocket.jsx +++ b/packages/web_ui/src/util/websocket.jsx @@ -46,6 +46,7 @@ export class Control extends libLink.Link { */ this.plugins = plugins; for (let plugin of plugins.values()) { + plugin.control = this; libPlugin.attachPluginMessages(this, plugin); } From cebe83542f4916cb416f782c55bb51a64318813c Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 03:24:49 +0100 Subject: [PATCH 6/8] Add access to icons and locale from export Add models for accessing and using the icons and locale that's exported when an instance export is runned. --- .../src/images}/unknown-item.png | Bin packages/web_ui/src/index.css | 6 +++ packages/web_ui/src/index.jsx | 2 + packages/web_ui/src/model/item_metadata.jsx | 38 ++++++++++++++++++ packages/web_ui/src/model/locale.jsx | 24 +++++++++++ 5 files changed, 70 insertions(+) rename packages/{master/web/pictures => web_ui/src/images}/unknown-item.png (100%) create mode 100644 packages/web_ui/src/model/item_metadata.jsx create mode 100644 packages/web_ui/src/model/locale.jsx diff --git a/packages/master/web/pictures/unknown-item.png b/packages/web_ui/src/images/unknown-item.png similarity index 100% rename from packages/master/web/pictures/unknown-item.png rename to packages/web_ui/src/images/unknown-item.png diff --git a/packages/web_ui/src/index.css b/packages/web_ui/src/index.css index 3b906a8c..4f8cf73f 100644 --- a/packages/web_ui/src/index.css +++ b/packages/web_ui/src/index.css @@ -259,3 +259,9 @@ body { .json-input { font-family: monospace; } + +.factorio-icon.item-unknown-item { + background: url("./images/unknown-item.png"); + height: 32px; + width: 32px; +} diff --git a/packages/web_ui/src/index.jsx b/packages/web_ui/src/index.jsx index 9761a022..b411ddc0 100644 --- a/packages/web_ui/src/index.jsx +++ b/packages/web_ui/src/index.jsx @@ -3,6 +3,8 @@ export { default as notify, notifyErrorHandler } from "./util/notify.jsx"; export * from "./model/instance.jsx"; export * from "./model/slave.jsx"; +export * from "./model/locale.jsx"; +export * from "./model/item_metadata.jsx"; export { default as ControlContext } from "./components/ControlContext"; diff --git a/packages/web_ui/src/model/item_metadata.jsx b/packages/web_ui/src/model/item_metadata.jsx new file mode 100644 index 00000000..50ece427 --- /dev/null +++ b/packages/web_ui/src/model/item_metadata.jsx @@ -0,0 +1,38 @@ +import React, { useEffect, useState } from "react"; + + +let itemMetadataCache = null; +export function useItemMetadata() { + let [itemMetadata, setItemMetadata] = useState(itemMetadataCache || new Map()); + useEffect(() => { + async function load() { + let response = await fetch(`${webRoot}export/item-metadata.json`); + if (response.ok) { + let data = await response.json(); + itemMetadataCache = new Map(data); + let style = document.createElement("style"); + style.type = "text/css"; + document.head.appendChild(style); + for (let [name, meta] of itemMetadataCache) { + style.sheet.insertRule( + `.item-${CSS.escape(name)} { + background-image: url("${webRoot}export/item-spritesheet.png"); + background-repeat: no-repeat; + background-position: -${meta.x}px -${meta.y}px; + height: ${meta.size}px; + width: ${meta.size}px; +}` + ); + } + setItemMetadata(itemMetadataCache); + } + } + + if (!itemMetadataCache) { + load(); + } + }, []); + + return itemMetadata; +} + diff --git a/packages/web_ui/src/model/locale.jsx b/packages/web_ui/src/model/locale.jsx new file mode 100644 index 00000000..ad4b83d0 --- /dev/null +++ b/packages/web_ui/src/model/locale.jsx @@ -0,0 +1,24 @@ +import React, { useEffect, useState } from "react"; + + +let localeCache = null; +export function useLocale() { + let [locale, setLocale] = useState(localeCache || new Map()); + useEffect(() => { + async function load() { + let response = await fetch(`${webRoot}export/locale.json`); + if (response.ok) { + let data = await response.json(); + localeCache = new Map(data); + setLocale(localeCache); + } + } + + if (!localeCache) { + load(); + } + }, []); + + return locale; +} + From c16dc74ad91ce1563977e1aa25d18a191fbf9de9 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 03:27:26 +0100 Subject: [PATCH 7/8] Reimplement the Storage page Reimplement the functionality of the Storage page which shows which items are stored in the shared subspace on the master server. --- plugins/subspace_storage/info.js | 25 ++- plugins/subspace_storage/master.js | 19 +++ plugins/subspace_storage/web/index.css | 5 + plugins/subspace_storage/web/index.jsx | 184 +++++++++++++++++++++ plugins/subspace_storage/webpack.config.js | 4 +- 5 files changed, 234 insertions(+), 3 deletions(-) create mode 100644 plugins/subspace_storage/web/index.css diff --git a/plugins/subspace_storage/info.js b/plugins/subspace_storage/info.js index 52534a65..84c7d511 100644 --- a/plugins/subspace_storage/info.js +++ b/plugins/subspace_storage/info.js @@ -1,6 +1,7 @@ "use strict"; const libLink = require("@clusterio/lib/link"); const libConfig = require("@clusterio/lib/config"); +const libUsers = require("@clusterio/lib/users"); class MasterConfigGroup extends libConfig.PluginConfigGroup {} MasterConfigGroup.defaultAccess = ["master", "slave", "control"]; @@ -41,6 +42,13 @@ InstanceConfigGroup.define({ }); InstanceConfigGroup.finalize(); +libUsers.definePermission({ + name: "subspace_storage.storage.view", + title: "View Subspace Storage", + description: "View the items and fluids stored in the shared subspace.", + grantByDefault: true, +}); + // JSON schema for subspace storage items const items = { type: "array", @@ -65,6 +73,9 @@ module.exports = { masterEntrypoint: "master", MasterConfigGroup, + webEntrypoint: "./web", + routes: ["/storage"], + messages: { // XXX this should be a request to be reliable place: new libLink.Event({ @@ -90,7 +101,8 @@ module.exports = { }), getStorage: new libLink.Request({ type: "subspace_storage:get_storage", - links: ["instance-slave", "slave-master"], + links: ["instance-slave", "slave-master", "control-master"], + permission: "subspace_storage.storage.view", forwardTo: "master", responseProperties: { "items": items, @@ -98,11 +110,20 @@ module.exports = { }), updateStorage: new libLink.Event({ type: "subspace_storage:update_storage", - links: ["master-slave", "slave-instance"], + links: ["master-slave", "slave-instance", "master-control"], broadcastTo: "instance", eventProperties: { "items": items, }, }), + + setStorageSubscription: new libLink.Request({ + type: "subspace_storage:set_storage_subscription", + links: ["control-master"], + permission: "subspace_storage.storage.view", + requestProperties: { + "storage": { type: "boolean" }, + }, + }), }, }; diff --git a/plugins/subspace_storage/master.js b/plugins/subspace_storage/master.js index 6cf6e538..0472a379 100644 --- a/plugins/subspace_storage/master.js +++ b/plugins/subspace_storage/master.js @@ -72,6 +72,8 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin { } }, 1000); + this.subscribedControlLinks = new Set(); + routes.addApiRoutes(this.master.app, this.items, this.metrics.endpointHitCounter); } @@ -90,6 +92,9 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin { itemsToUpdate = [...itemsToUpdate.entries()]; this.broadcastEventToSlaves(this.info.messages.updateStorage, { items: itemsToUpdate }); + for (let link of this.subscribedControlLinks) { + this.info.messages.updateStorage.send(link, { items: itemsToUpdate }); + } this.itemsLastUpdate = new Map(this.items._items.entries()); } @@ -181,6 +186,20 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin { }; } + async setStorageSubscriptionRequestHandler(message, request, link) { + if (message.data.storage) { + this.subscribedControlLinks.add(link); + } else { + this.subscribedControlLinks.delete(link); + } + } + + onControlConnectionEvent(connection, event) { + if (event === "close") { + this.subscribedControlLinks.delete(connection); + } + } + onMetrics() { if (this.items) { for (let [key, count] of this.items._items) { diff --git a/plugins/subspace_storage/web/index.css b/plugins/subspace_storage/web/index.css new file mode 100644 index 00000000..e0e730c8 --- /dev/null +++ b/plugins/subspace_storage/web/index.css @@ -0,0 +1,5 @@ +.factorio-icon { + display: inline-block; + vertical-align: middle; + margin-right: 0.5em; +} diff --git a/plugins/subspace_storage/web/index.jsx b/plugins/subspace_storage/web/index.jsx index e69de29b..3336ac13 100644 --- a/plugins/subspace_storage/web/index.jsx +++ b/plugins/subspace_storage/web/index.jsx @@ -0,0 +1,184 @@ +import React, { useContext, useEffect, useState } from "react"; +import { Input, Table, Typography } from "antd"; + +import libPlugin from "@clusterio/lib/plugin"; +import { notifyErrorHandler, useItemMetadata, useLocale, PageLayout, ControlContext } from "@clusterio/web_ui"; +import info from "../info"; + +import "./index.css"; + +const { Paragraph } = Typography; + + +function useStorage(control) { + let plugin = control.plugins.get("subspace_storage"); + let [storage, setStorage] = useState([...plugin.storage]); + + useEffect(() => { + function update() { + setStorage([...plugin.storage]); + } + + plugin.onUpdate(update); + return () => { + plugin.offUpdate(update); + }; + }, []); + return storage; +} + +function StoragePage() { + let control = useContext(ControlContext); + let locale = useLocale(); + let itemMetadata = useItemMetadata(); + let storage = useStorage(control); + let [filter, setFilter] = useState(null); + + function getLocaleName(itemName) { + let localeName = itemName; + let meta = itemMetadata.get(itemName); + if (meta && meta.localized_name) { + // TODO: implement the locale to name conversion. + localeName = locale.get(meta.localized_name[0]); + } else { + for (let section of ["item-name", "entity-name", "fluid-name", "equipment-name"]) { + let name = locale.get(`${section}.${itemName}`); + if (name) { + localeName = name; + break; + } + } + } + + return localeName; + } + + let numberFormat = new Intl.NumberFormat("en-US"); + + return +

Storage

+ + { + let search = event.target.value.trim(); + if (!search) { + setFilter(null); + return; + } + search = search.replace(/(^| )(\w)/g, "$1\\b$2"); + search = search.replace(/ +/g, ".*"); + let filterExpr = new RegExp(search, "i"); + setFilter(() => (item => { + let name = getLocaleName(item[0]); + return filterExpr.test(name) || filterExpr.test(item[0]); + })); + }} + /> + + { + let aName = getLocaleName(a[0]); + let bName = getLocaleName(b[0]); + if (aName < bName) { return -1; } + if (aName > bName) { return 1; } + return 0; + }, + render: item => { + let localeName = getLocaleName(item[0]); + let hasMeta = itemMetadata.get(item[0]); + + return <> + + {localeName} + ; + }, + }, + { + title: "Quantity", + key: "quantity", + align: "right", + defaultSortOrder: "descend", + sorter: (a, b) => a[1] - b[1], + render: item => numberFormat.format(item[1]), + }, + ]} + dataSource={filter ? storage.filter(filter) : storage} + rowKey={item => item[0]} + pagination={false} + /> + ; +} + +export class WebPlugin extends libPlugin.BaseWebPlugin { + async init() { + this.pages = [ + { path: "/storage", sidebarName: "Storage", content: }, + ]; + + this.storage = new Map(); + this.callbacks = []; + } + + onMasterConnectionEvent(event) { + if (event === "connect") { + this.updateSubscription(); + } + } + + async updateStorageEventHandler(message) { + this.updateStorage(message.data.items); + } + + onUpdate(callback) { + this.callbacks.push(callback); + if (this.callbacks.length) { + this.updateSubscription(); + } + } + + offUpdate(callback) { + let index = this.callbacks.lastIndexOf(callback); + if (index === -1) { + throw new Error("callback is not registered"); + } + + this.callbacks.splice(index, 1); + if (!this.callbacks.length) { + this.updateSubscription(); + } + } + + updateStorage(items) { + for (let [name, amount] of items) { + this.storage.set(name, amount); + } + for (let callback of this.callbacks) { + callback(); + } + } + + updateSubscription() { + if (!this.control.connector.connected) { + return; + } + + info.messages.setStorageSubscription.send( + this.control, { storage: Boolean(this.callbacks.length) } + ).catch(notifyErrorHandler("Error subscribing to storage")); + + if (this.callbacks.length) { + info.messages.getStorage.send(this.control).then( + result => { + this.updateStorage(result.items); + } + ).catch(notifyErrorHandler("Error updating storage")); + } else { + this.storage.clear(); + } + } +} diff --git a/plugins/subspace_storage/webpack.config.js b/plugins/subspace_storage/webpack.config.js index 8305920b..491a9c31 100644 --- a/plugins/subspace_storage/webpack.config.js +++ b/plugins/subspace_storage/webpack.config.js @@ -21,12 +21,14 @@ module.exports = (env = {}) => merge(common(env), { exposes: { "./info": "./info.js", "./package.json": "./package.json", + "./web": "./web/index.jsx", }, shared: { "@clusterio/lib/config": { import: false }, "@clusterio/lib/link": { import: false }, + "@clusterio/lib/plugin": { import: false }, + "@clusterio/lib/users": { import: false }, "@clusterio/web_ui": { import: false }, - "ajv": { import: false }, "antd": { import: false }, "react": { import: false }, "react-dom": { import: false }, From 8fb67849647e1851ecda89ac90e981cf140f9d90 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Sat, 20 Mar 2021 17:03:23 +0100 Subject: [PATCH 8/8] Load plugin infos in integration tests Make sure the permisisons defined by plugins are included in the integration test environment by loading the plugin infos. --- test/integration/index.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/integration/index.js b/test/integration/index.js index d1588ae9..0d9b8bf1 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -13,6 +13,13 @@ const server = require("@clusterio/lib/factorio/server"); const { ConsoleTransport, logger } = require("@clusterio/lib/logging"); const libLoggingUtils = require("@clusterio/lib/logging_utils"); +// Make sure permissions from plugins are loaded +require("../../plugins/global_chat/info"); +require("../../plugins/player_auth/info"); +require("../../plugins/research_sync/info"); +require("../../plugins/statistics_exporter/info"); +require("../../plugins/subspace_storage/info"); + class TestControl extends libLink.Link { constructor(connector) {