mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-22 16:13:12 +09:00
Port packages/web_ui to TypeScript (#508)
* .jsx to .tsx * controller: tsc --build before webpack-cli * Type Annotation * disabled move into the <Input/> and <Checkbox/> * cleanup debug left over * documentation * default ModPack * modPackUpdateHandlers no undefined * PluginInfo changes proposition * PluginInfo changes proposition miss * ModRecord & ModInfo feedback loop at const mods = [ ? * ["connect", "drop", "resume", "close"] as const * .tsx to .ts when possible
This commit is contained in:
1 parent
a4893751e9
commit
838170a9ff
92 files changed
+1104
-707
No files matched your search
@@ -194,7 +194,7 @@ interface InitializeParameters {
|
|||||||
args: ControllerArgs;
|
args: ControllerArgs;
|
||||||
shouldRun: boolean;
|
shouldRun: boolean;
|
||||||
clusterLogger: winston.Logger;
|
clusterLogger: winston.Logger;
|
||||||
pluginInfos: any[] | null;
|
pluginInfos: lib.PluginNodeEnvInfo[] | null;
|
||||||
controllerConfigPath: string | null;
|
controllerConfigPath: string | null;
|
||||||
controllerConfig: lib.ControllerConfig | null;
|
controllerConfig: lib.ControllerConfig | null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,7 @@
|
|||||||
"version": "2.0.0-alpha.13",
|
"version": "2.0.0-alpha.13",
|
||||||
"main": "dist/controller/controller.js",
|
"main": "dist/controller/controller.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "webpack-cli --env production && pnpm build",
|
"prepare": "tsc --build && webpack-cli --env production",
|
||||||
"build": "tsc --build",
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -76,13 +76,10 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"]) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
for (let controllerPlugin of this._controller.plugins.values()) {
|
for (let controllerPlugin of this._controller.plugins.values()) {
|
||||||
controllerPlugin.onControlConnectionEvent(
|
controllerPlugin.onControlConnectionEvent(this, event);
|
||||||
this,
|
|
||||||
event as "connect" | "drop" | "resume" | "close"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ const logSizeGauge = new Gauge(
|
|||||||
export default class Controller {
|
export default class Controller {
|
||||||
clusterLogger: winston.Logger;
|
clusterLogger: winston.Logger;
|
||||||
/** Array of plugin info objects for known plugins */
|
/** Array of plugin info objects for known plugins */
|
||||||
pluginInfos: lib.PluginInfo[];
|
pluginInfos: lib.PluginNodeEnvInfo[];
|
||||||
configPath: string;
|
configPath: string;
|
||||||
/** Controller config. */
|
/** Controller config. */
|
||||||
config: lib.ControllerConfig;
|
config: lib.ControllerConfig;
|
||||||
|
|||||||
@@ -54,11 +54,11 @@ export default class HostConnection extends BaseConnection {
|
|||||||
plugins: registerData.plugins,
|
plugins: registerData.plugins,
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"]) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
// eslint-disable-next-line no-loop-func
|
// eslint-disable-next-line no-loop-func
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
for (let plugin of this._controller.plugins.values()) {
|
for (let plugin of this._controller.plugins.values()) {
|
||||||
plugin.onHostConnectionEvent(this, event as "connect"|"drop"|"resume"|"close");
|
plugin.onHostConnectionEvent(this, event);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type { IncomingMessage } from "http";
|
import type { IncomingMessage } from "http";
|
||||||
import type { Duplex } from "stream";
|
import type { Duplex } from "stream";
|
||||||
import type Controller from "./Controller";
|
import type Controller from "./Controller";
|
||||||
import type { WebSocketClusterio } from "./WsServerConnector";
|
|
||||||
|
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import WebSocket, { WebSocketServer } from "ws";
|
import WebSocket, { WebSocketServer } from "ws";
|
||||||
@@ -55,7 +54,7 @@ export default class WsServer {
|
|||||||
noServer: true,
|
noServer: true,
|
||||||
path: "/api/socket",
|
path: "/api/socket",
|
||||||
});
|
});
|
||||||
this.wss.on("connection", (socket: WebSocketClusterio, req: IncomingMessage) => this.handleConnection(socket, req));
|
this.wss.on("connection", (socket: lib.WebSocketClusterio, req: IncomingMessage) => this.handleConnection(socket, req));
|
||||||
}
|
}
|
||||||
|
|
||||||
async stop(): Promise<void> {
|
async stop(): Promise<void> {
|
||||||
@@ -98,19 +97,19 @@ export default class WsServer {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
handleConnection(socket: WebSocketClusterio, req: IncomingMessage) {
|
handleConnection(socket: lib.WebSocketClusterio, req: IncomingMessage) {
|
||||||
logger.verbose(`WsServer | new connection from ${req.socket.remoteAddress}`);
|
logger.verbose(`WsServer | new connection from ${req.socket.remoteAddress}`);
|
||||||
|
|
||||||
// Track statistics
|
// Track statistics
|
||||||
wsConnectionsCounter.inc();
|
wsConnectionsCounter.inc();
|
||||||
socket.on("message", (message) => {
|
socket.on("message", (message: WebSocket.RawData) => {
|
||||||
wsMessageCounter.labels("in").inc();
|
wsMessageCounter.labels("in").inc();
|
||||||
if (!socket.clusterio_ignore_dump) {
|
if (!socket.clusterio_ignore_dump) {
|
||||||
this.controller.debugEvents.emit("message", { direction: "in", content: message });
|
this.controller.debugEvents.emit("message", { direction: "in", content: message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let originalSend = socket.send;
|
let originalSend = socket.send;
|
||||||
socket.send = (...args) => {
|
socket.send = (...args: any[]) => {
|
||||||
wsMessageCounter.labels("out").inc();
|
wsMessageCounter.labels("out").inc();
|
||||||
if (typeof args[0] === "string" && !socket.clusterio_ignore_dump) {
|
if (typeof args[0] === "string" && !socket.clusterio_ignore_dump) {
|
||||||
this.controller.debugEvents.emit("message", { direction: "out", content: args[0] });
|
this.controller.debugEvents.emit("message", { direction: "out", content: args[0] });
|
||||||
@@ -120,7 +119,7 @@ export default class WsServer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Start connection handshake.
|
// Start connection handshake.
|
||||||
let loadedPlugins: any = {};
|
let loadedPlugins: {[key:string]: string} = {};
|
||||||
for (let [name, plugin] of this.controller.plugins) {
|
for (let [name, plugin] of this.controller.plugins) {
|
||||||
loadedPlugins[name] = plugin.info.version;
|
loadedPlugins[name] = plugin.info.version;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ import events from "events";
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
export interface WebSocketClusterio extends WebSocket {
|
|
||||||
clusterio_ignore_dump?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connector for controller connections
|
* Connector for controller connections
|
||||||
@@ -18,7 +14,6 @@ export interface WebSocketClusterio extends WebSocket {
|
|||||||
*/
|
*/
|
||||||
export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
export default class WsServerConnector extends lib.WebSocketBaseConnector {
|
||||||
_timeoutId: ReturnType<typeof setTimeout> | null = null;
|
_timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
declare _socket: WebSocketClusterio | null;
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
dst: lib.Address,
|
dst: lib.Address,
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ async function getMetrics(req: Request, res: Response, next: any) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: results seem to mix deserialized and serialized lib.CollectorResult ?
|
// TODO: results seem to mix deserialized and serialized lib.CollectorResult ?
|
||||||
// mergeSamples imply samples be [string, [string, number][]]
|
// mergeSamples imply samples be [string, [string, number][]]
|
||||||
// but lib.defaultRegistry.collect() imply Map<string, Map<string, number>>
|
// but lib.defaultRegistry.collect() imply Map<string, Map<string, number>>
|
||||||
@@ -99,8 +99,21 @@ async function getMetrics(req: Request, res: Response, next: any) {
|
|||||||
res.send(text);
|
res.send(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export type PluginWebApi = {
|
||||||
|
name: string;
|
||||||
|
version: string;
|
||||||
|
enabled: boolean;
|
||||||
|
loaded: boolean;
|
||||||
|
web: {
|
||||||
|
main: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
requirePath: string;
|
||||||
|
}
|
||||||
|
|
||||||
function getPlugins(req: Request, res: Response) {
|
function getPlugins(req: Request, res: Response) {
|
||||||
let plugins = [];
|
let plugins: PluginWebApi[] = [];
|
||||||
for (let pluginInfo of req.app.locals.controller.pluginInfos) {
|
for (let pluginInfo of req.app.locals.controller.pluginInfos) {
|
||||||
let name = pluginInfo.name;
|
let name = pluginInfo.name;
|
||||||
let loaded = req.app.locals.controller.plugins.has(name);
|
let loaded = req.app.locals.controller.plugins.has(name);
|
||||||
|
|||||||
@@ -325,7 +325,7 @@ instanceConfigCommands.add(new lib.Command({
|
|||||||
let instanceId = await lib.resolveInstance(control, args.instance);
|
let instanceId = await lib.resolveInstance(control, args.instance);
|
||||||
let response = await control.send(new lib.InstanceConfigGetRequest(instanceId));
|
let response = await control.send(new lib.InstanceConfigGetRequest(instanceId));
|
||||||
|
|
||||||
for (let group of (response.config as any).groups) {
|
for (let group of response.serializedConfig.groups) {
|
||||||
for (let [name, value] of Object.entries(group.fields)) {
|
for (let [name, value] of Object.entries(group.fields)) {
|
||||||
print(`${group.name}.${name} ${JSON.stringify(value)}`);
|
print(`${group.name}.${name} ${JSON.stringify(value)}`);
|
||||||
}
|
}
|
||||||
@@ -425,7 +425,7 @@ instanceConfigCommands.add(new lib.Command({
|
|||||||
}
|
}
|
||||||
let disallowedList = {"instance.id": 0, "instance.assigned_host": 0, "factorio.settings": 0};
|
let disallowedList = {"instance.id": 0, "instance.assigned_host": 0, "factorio.settings": 0};
|
||||||
let allConfigElements = await serializedConfigToString(
|
let allConfigElements = await serializedConfigToString(
|
||||||
response.config,
|
response.serializedConfig,
|
||||||
lib.InstanceConfig,
|
lib.InstanceConfig,
|
||||||
disallowedList
|
disallowedList
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export class HostConnector extends lib.WebSocketClientConnector {
|
|||||||
constructor(
|
constructor(
|
||||||
public hostConfig: lib.HostConfig,
|
public hostConfig: lib.HostConfig,
|
||||||
tlsCa: string | undefined,
|
tlsCa: string | undefined,
|
||||||
public pluginInfos: lib.PluginInfo[]
|
public pluginInfos: lib.PluginNodeEnvInfo[]
|
||||||
) {
|
) {
|
||||||
super(
|
super(
|
||||||
hostConfig.get("host.controller_url"),
|
hostConfig.get("host.controller_url"),
|
||||||
|
|||||||
@@ -238,7 +238,7 @@ export default class Host extends lib.Link {
|
|||||||
* Certificate authority used to validate TLS connections to the controller.
|
* Certificate authority used to validate TLS connections to the controller.
|
||||||
*/
|
*/
|
||||||
tlsCa?: string;
|
tlsCa?: string;
|
||||||
pluginInfos: lib.PluginInfo[];
|
pluginInfos: lib.PluginNodeEnvInfo[];
|
||||||
config: lib.HostConfig;
|
config: lib.HostConfig;
|
||||||
|
|
||||||
instanceConnections = new Map<number, InstanceConnection>();
|
instanceConnections = new Map<number, InstanceConnection>();
|
||||||
@@ -260,7 +260,7 @@ export default class Host extends lib.Link {
|
|||||||
connector: HostConnector,
|
connector: HostConnector,
|
||||||
hostConfig: lib.HostConfig,
|
hostConfig: lib.HostConfig,
|
||||||
tlsCa: string | undefined,
|
tlsCa: string | undefined,
|
||||||
pluginInfos: lib.PluginInfo[]
|
pluginInfos: lib.PluginNodeEnvInfo[]
|
||||||
) {
|
) {
|
||||||
super(connector);
|
super(connector);
|
||||||
this.tlsCa = tlsCa;
|
this.tlsCa = tlsCa;
|
||||||
|
|||||||
@@ -490,7 +490,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
this._saveStats().catch(err => this.logger.error(`Error saving stats:\n${err.stack}`));
|
this._saveStats().catch(err => this.logger.error(`Error saving stats:\n${err.stack}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
async _loadPlugin(pluginInfo: lib.PluginInfo, host: Host) {
|
async _loadPlugin(pluginInfo: lib.PluginNodeEnvInfo, host: Host) {
|
||||||
let pluginLoadStarted = Date.now();
|
let pluginLoadStarted = Date.now();
|
||||||
let InstancePluginClass = await lib.loadInstancePluginClass(pluginInfo);
|
let InstancePluginClass = await lib.loadInstancePluginClass(pluginInfo);
|
||||||
let instancePlugin = new InstancePluginClass(pluginInfo, this, host);
|
let instancePlugin = new InstancePluginClass(pluginInfo, this, host);
|
||||||
@@ -524,7 +524,7 @@ rcon.print(game.table_to_json(players))`.replace(/\r?\n/g, " ");
|
|||||||
await lib.safeOutputFile(this.path("instance-stats.json"), content);
|
await lib.safeOutputFile(this.path("instance-stats.json"), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async init(pluginInfos: lib.PluginInfo[]) {
|
async init(pluginInfos: lib.PluginNodeEnvInfo[]) {
|
||||||
this.notifyStatus("starting");
|
this.notifyStatus("starting");
|
||||||
try {
|
try {
|
||||||
await this._loadStats();
|
await this._loadStats();
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
// Configuration classes
|
// Configuration classes
|
||||||
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import events from "events";
|
import events from "events";
|
||||||
|
|
||||||
import isDeepStrictEqual from "../is_deep_strict_equal";
|
import isDeepStrictEqual from "../is_deep_strict_equal";
|
||||||
@@ -317,8 +318,34 @@ export class Config extends events.EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: remove after config refactor
|
||||||
|
export class RawConfig {
|
||||||
|
constructor(
|
||||||
|
public serializedConfig: SerializedConfig
|
||||||
|
) { }
|
||||||
|
|
||||||
|
static jsonSchema = Type.Object({
|
||||||
|
"serializedConfig": Type.Object({
|
||||||
|
"groups": Type.Array(
|
||||||
|
Type.Object({
|
||||||
|
"name": Type.String(),
|
||||||
|
"fields": Type.Record(
|
||||||
|
Type.String(),
|
||||||
|
Type.Unknown(),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||||
|
return new this(json.serializedConfig);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
type FieldType = "boolean" | "string" | "number" | "object";
|
type FieldType = "boolean" | "string" | "number" | "object";
|
||||||
interface FieldDefinition {
|
export interface FieldDefinition {
|
||||||
type: FieldType;
|
type: FieldType;
|
||||||
name: string;
|
name: string;
|
||||||
fullName: string;
|
fullName: string;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Core definitions for the configuration system
|
// Core definitions for the configuration system
|
||||||
import * as classes from "./classes";
|
import * as classes from "./classes";
|
||||||
import type { PluginInfo } from "../plugin";
|
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -503,14 +503,14 @@ export class ControlConfig extends classes.Config { }
|
|||||||
ControlConfig.registerGroup(ControlGroup);
|
ControlConfig.registerGroup(ControlGroup);
|
||||||
|
|
||||||
|
|
||||||
function validateGroup(pluginInfo: PluginInfo, groupName: string) {
|
function validateGroup(pluginInfo: PluginNodeEnvInfo|PluginWebpackEnvInfo, groupName: "ControllerConfigGroup"|"InstanceConfigGroup") {
|
||||||
if (!(pluginInfo[groupName].prototype instanceof classes.PluginConfigGroup)) {
|
if (!(pluginInfo[groupName]?.prototype instanceof classes.PluginConfigGroup)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Expected ${groupName} for ${pluginInfo.name} to be a subclass of PluginConfigGroup`
|
`Expected ${groupName} for ${pluginInfo.name} to be a subclass of PluginConfigGroup`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pluginInfo[groupName].groupName !== pluginInfo.name) {
|
if (pluginInfo[groupName]?.groupName !== pluginInfo.name) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Expected ${groupName} for ${pluginInfo.name} to be named after the plugin`
|
`Expected ${groupName} for ${pluginInfo.name} to be named after the plugin`
|
||||||
);
|
);
|
||||||
@@ -522,7 +522,7 @@ function validateGroup(pluginInfo: PluginInfo, groupName: string) {
|
|||||||
*
|
*
|
||||||
* @param {Array<Object>} pluginInfos - Array of plugin info objects.
|
* @param {Array<Object>} pluginInfos - Array of plugin info objects.
|
||||||
*/
|
*/
|
||||||
export function registerPluginConfigGroups(pluginInfos: PluginInfo[]) {
|
export function registerPluginConfigGroups(pluginInfos: PluginNodeEnvInfo[]|PluginWebpackEnvInfo[]) {
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
if (pluginInfo.ControllerConfigGroup) {
|
if (pluginInfo.ControllerConfigGroup) {
|
||||||
validateGroup(pluginInfo, "ControllerConfigGroup");
|
validateGroup(pluginInfo, "ControllerConfigGroup");
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type { Logger } from "../logging";
|
|||||||
/**
|
/**
|
||||||
* A setting for a mod.
|
* A setting for a mod.
|
||||||
*/
|
*/
|
||||||
interface ModSetting {
|
export interface ModSetting {
|
||||||
/** Value of the given mod setting. */
|
/** Value of the given mod setting. */
|
||||||
value: boolean | number | string;
|
value: boolean | number | string;
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ const ModSettingsJsonSchema = Type.Record(Type.String(), ModSettingJsonSchema);
|
|||||||
/**
|
/**
|
||||||
* A mod in a mod pack
|
* A mod in a mod pack
|
||||||
*/
|
*/
|
||||||
interface ModRecord {
|
export interface ModRecord {
|
||||||
/** name of the mod. */
|
/** name of the mod. */
|
||||||
name: string,
|
name: string,
|
||||||
/** if mod is to be loaded. */
|
/** if mod is to be loaded. */
|
||||||
@@ -35,6 +35,8 @@ interface ModRecord {
|
|||||||
version: string,
|
version: string,
|
||||||
/** SHA1 hash of the zip file. */
|
/** SHA1 hash of the zip file. */
|
||||||
sha1?: string,
|
sha1?: string,
|
||||||
|
/** Used inside packages\web_ui\src\components\ModPackViewPage.tsx to define an error type. */
|
||||||
|
error?: "missing"|"bad_checksum",
|
||||||
}
|
}
|
||||||
|
|
||||||
const ModRecordJsonSchema = Type.Object({
|
const ModRecordJsonSchema = Type.Object({
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
*/
|
*/
|
||||||
export { default as ExportManifest } from "./ExportManifest";
|
export { default as ExportManifest } from "./ExportManifest";
|
||||||
export { default as ModInfo } from "./ModInfo";
|
export { default as ModInfo } from "./ModInfo";
|
||||||
export { default as ModPack } from "./ModPack";
|
export { default as ModPack, ModSetting, ModRecord } from "./ModPack";
|
||||||
export { default as ModuleInfo } from "./ModuleInfo";
|
export { default as ModuleInfo } from "./ModuleInfo";
|
||||||
export * from "./composites";
|
export * from "./composites";
|
||||||
export * from "./messages_core";
|
export * from "./messages_core";
|
||||||
|
|||||||
@@ -1,21 +1,7 @@
|
|||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import { JsonString, StringEnum } from "./composites";
|
import { JsonString, StringEnum } from "./composites";
|
||||||
import { levels } from "../logging";
|
import { levels } from "../logging";
|
||||||
|
import { RawConfig } from "../config";
|
||||||
// TODO: remove after config refactor
|
|
||||||
export class RawConfig {
|
|
||||||
constructor(
|
|
||||||
public serializedConfig: object
|
|
||||||
) { }
|
|
||||||
|
|
||||||
static jsonSchema = Type.Object({
|
|
||||||
"serializedConfig": Type.Object({}),
|
|
||||||
});
|
|
||||||
|
|
||||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
|
||||||
return new this(json.serializedConfig);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ControllerConfigGetRequest {
|
export class ControllerConfigGetRequest {
|
||||||
declare ["constructor"]: typeof ControllerConfigGetRequest;
|
declare ["constructor"]: typeof ControllerConfigGetRequest;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import { TSchema, Type, Static } from "@sinclair/typebox";
|
import { TSchema, Type, Static } from "@sinclair/typebox";
|
||||||
import messageValidate from "./message_validate";
|
import messageValidate from "./message_validate";
|
||||||
import { StringEnum } from "./composites";
|
import { StringEnum } from "./composites";
|
||||||
|
import { AccountRole } from "../plugin";
|
||||||
|
|
||||||
export type AddressType = "controller" | "host" | "instance" | "control" | "broadcast";
|
export type AddressType = "controller" | "host" | "instance" | "control" | "broadcast";
|
||||||
export type AddressShorthand =
|
export type AddressShorthand =
|
||||||
@@ -288,7 +289,7 @@ export class MessageRegisterControl extends Message {
|
|||||||
export class AccountDetails {
|
export class AccountDetails {
|
||||||
constructor(
|
constructor(
|
||||||
public name: string,
|
public name: string,
|
||||||
public roles: { name: string, id: number, permissions: string[] }[],
|
public roles: AccountRole[],
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
static jsonSchema = Type.Object({
|
static jsonSchema = Type.Object({
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import PlayerStats from "../PlayerStats";
|
import PlayerStats from "../PlayerStats";
|
||||||
import { JsonString, StringEnum, jsonArray } from "./composites";
|
import { JsonString, StringEnum, jsonArray } from "./composites";
|
||||||
|
import { RawConfig } from "../config";
|
||||||
import type { User } from "../users";
|
import type { User } from "../users";
|
||||||
import type { MessageRequest } from "./messages_core";
|
import type { MessageRequest } from "./messages_core";
|
||||||
|
import type { SerializedConfig } from "../config";
|
||||||
|
|
||||||
|
|
||||||
export type InstanceStatus =
|
export type InstanceStatus =
|
||||||
"unknown" | "unassigned" | "stopped" | "starting" | "running"
|
"unknown" | "unassigned" | "stopped" | "starting" | "running"
|
||||||
@@ -134,6 +137,8 @@ export class InstanceConfigGetRequest {
|
|||||||
static src = "control" as const;
|
static src = "control" as const;
|
||||||
static dst = "controller" as const;
|
static dst = "controller" as const;
|
||||||
static permission = "core.instance.get_config" as const;
|
static permission = "core.instance.get_config" as const;
|
||||||
|
// TODO replace with InstanceConfig after config refactor
|
||||||
|
static Response = RawConfig;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public instanceId: number,
|
public instanceId: number,
|
||||||
@@ -146,21 +151,6 @@ export class InstanceConfigGetRequest {
|
|||||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||||
return new this(json.instanceId);
|
return new this(json.instanceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO replace with InstanceConfig after config refactor
|
|
||||||
static Response = class Response {
|
|
||||||
constructor(
|
|
||||||
public config: object,
|
|
||||||
) { }
|
|
||||||
|
|
||||||
static jsonSchema = Type.Object({
|
|
||||||
"config": Type.Object({}),
|
|
||||||
});
|
|
||||||
|
|
||||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
|
||||||
return new this(json.config);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class InstanceConfigSetFieldRequest {
|
export class InstanceConfigSetFieldRequest {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Type, Static } from "@sinclair/typebox";
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
import PlayerStats from "../PlayerStats";
|
import PlayerStats from "../PlayerStats";
|
||||||
import { JsonNumber, jsonArray } from "./composites";
|
import { JsonNumber, jsonArray } from "./composites";
|
||||||
|
import { AccountRole } from "../plugin";
|
||||||
|
|
||||||
export class RawPermission { // TODO refactor into lib/user.Permission
|
export class RawPermission { // TODO refactor into lib/user.Permission
|
||||||
constructor(
|
constructor(
|
||||||
@@ -436,7 +437,7 @@ export class AccountUpdateEvent {
|
|||||||
static dst = "control" as const;
|
static dst = "control" as const;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public roles?: { name: string, id: number, permissions: string[] }[],
|
public roles?: AccountRole[],
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
static jsonSchema = Type.Object({
|
static jsonSchema = Type.Object({
|
||||||
|
|||||||
@@ -82,6 +82,10 @@ export abstract class BaseConnector extends events.EventEmitter {
|
|||||||
|
|
||||||
type ConnectorState = "closed" | "connecting" | "connected" | "resuming";
|
type ConnectorState = "closed" | "connecting" | "connected" | "resuming";
|
||||||
|
|
||||||
|
export type WebSocketClusterio = WebSocket.WebSocket & {
|
||||||
|
clusterio_ignore_dump?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base connector for links
|
* Base connector for links
|
||||||
*
|
*
|
||||||
@@ -91,7 +95,7 @@ export abstract class WebSocketBaseConnector extends BaseConnector {
|
|||||||
// One of closed, connecting (client only), connected and resuming.
|
// One of closed, connecting (client only), connected and resuming.
|
||||||
_state: ConnectorState = "closed";
|
_state: ConnectorState = "closed";
|
||||||
_closing = false;
|
_closing = false;
|
||||||
_socket: WebSocket | null = null;
|
_socket: WebSocketClusterio | null = null;
|
||||||
_lastHeartbeat: number | null = null;
|
_lastHeartbeat: number | null = null;
|
||||||
_heartbeatId: ReturnType<typeof setInterval> | null = null;
|
_heartbeatId: ReturnType<typeof setInterval> | null = null;
|
||||||
_heartbeatInterval: number | null = null;
|
_heartbeatInterval: number | null = null;
|
||||||
@@ -451,12 +455,12 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector {
|
|||||||
|
|
||||||
// eslint-disable-next-line node/no-process-env
|
// eslint-disable-next-line node/no-process-env
|
||||||
if (process.env.APP_ENV === "browser") {
|
if (process.env.APP_ENV === "browser") {
|
||||||
this._socket = new WebSocket(url);
|
this._socket = new WebSocket(url) as WebSocketClusterio;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
let options: { ca?: string } = {};
|
let options: { ca?: string } = {};
|
||||||
if (this._tlsCa) { options.ca = this._tlsCa; }
|
if (this._tlsCa) { options.ca = this._tlsCa; }
|
||||||
this._socket = new WebSocket(url, options);
|
this._socket = new WebSocket(url, options) as WebSocketClusterio;
|
||||||
}
|
}
|
||||||
|
|
||||||
this._attachSocketHandlers();
|
this._attachSocketHandlers();
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import * as libSchema from "../schema";
|
|||||||
import { dataClasses } from "./messages";
|
import { dataClasses } from "./messages";
|
||||||
import { BaseConnector, WebSocketBaseConnector } from "./connectors";
|
import { BaseConnector, WebSocketBaseConnector } from "./connectors";
|
||||||
import { strict as assert } from "assert";
|
import { strict as assert } from "assert";
|
||||||
import type { PluginInfo } from "../plugin";
|
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
|
||||||
import type { User } from "../users";
|
import type { User } from "../users";
|
||||||
import type { AddressType, JSONDeserialisable, MessageRoutable, MessageRequest, MessageEvent } from "../data";
|
import type { AddressType, JSONDeserialisable, MessageRoutable, MessageRequest, MessageEvent } from "../data";
|
||||||
|
|
||||||
@@ -778,7 +778,7 @@ for (let Class of dataClasses) {
|
|||||||
Link.register(Class as RequestClass<unknown, unknown>);
|
Link.register(Class as RequestClass<unknown, unknown>);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerPluginMessages(pluginInfos: PluginInfo[]) {
|
export function registerPluginMessages(pluginInfos: PluginNodeEnvInfo[]|PluginWebpackEnvInfo[]) {
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
for (let Class of pluginInfo.messages || []) {
|
for (let Class of pluginInfo.messages || []) {
|
||||||
if (Class.plugin !== pluginInfo.name) {
|
if (Class.plugin !== pluginInfo.name) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type { Link } from "./link";
|
|||||||
import type { CommandTree } from "./command";
|
import type { CommandTree } from "./command";
|
||||||
import type { User } from "./users";
|
import type { User } from "./users";
|
||||||
import type { MessageRequest, MessageEvent } from "./data";
|
import type { MessageRequest, MessageEvent } from "./data";
|
||||||
|
import type { PluginConfigGroup } from "./config";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Conceptual base for controller and instance plugins.
|
* Conceptual base for controller and instance plugins.
|
||||||
@@ -21,11 +21,41 @@ export type BasePlugin =
|
|||||||
| BaseControllerPlugin
|
| BaseControllerPlugin
|
||||||
| BaseInstancePlugin
|
| BaseInstancePlugin
|
||||||
| BaseControlPlugin
|
| BaseControlPlugin
|
||||||
| BaseWebPlugin
|
|
||||||
;
|
;
|
||||||
|
|
||||||
// TODO Add proper typing for plugins
|
// TODO Add proper typing for plugins
|
||||||
export type PluginInfo = any;
|
/* Used to define the export of info.ts from plugins */
|
||||||
|
export type PluginDeclaration = {
|
||||||
|
name: string;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
instanceEntrypoint?: string;
|
||||||
|
InstanceConfigGroup?: typeof PluginConfigGroup;
|
||||||
|
|
||||||
|
controllerEntrypoint?: string;
|
||||||
|
ControllerConfigGroup?: typeof PluginConfigGroup;
|
||||||
|
|
||||||
|
controlEntrypoint?: string;
|
||||||
|
ControlConfigGroup?: typeof PluginConfigGroup;
|
||||||
|
|
||||||
|
messages?: any[];
|
||||||
|
|
||||||
|
webEntrypoint?: string;
|
||||||
|
routes?: string[];
|
||||||
|
}
|
||||||
|
export type PluginNodeEnvInfo = PluginDeclaration & {
|
||||||
|
requirePath: string;
|
||||||
|
version: string;
|
||||||
|
manifest: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PluginWebpackEnvInfo = PluginDeclaration & {
|
||||||
|
container: any;
|
||||||
|
package: any;
|
||||||
|
enabled?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
type Controller = any;
|
type Controller = any;
|
||||||
type Instance = any;
|
type Instance = any;
|
||||||
type Host = any;
|
type Host = any;
|
||||||
@@ -96,7 +126,7 @@ export class BaseInstancePlugin {
|
|||||||
/**
|
/**
|
||||||
* The plugin's own info module
|
* The plugin's own info module
|
||||||
*/
|
*/
|
||||||
public info: PluginInfo,
|
public info: PluginNodeEnvInfo,
|
||||||
/**
|
/**
|
||||||
* Instance the plugin started for
|
* Instance the plugin started for
|
||||||
*/
|
*/
|
||||||
@@ -332,7 +362,7 @@ export class BaseControllerPlugin {
|
|||||||
logger: Logger;
|
logger: Logger;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public info: PluginInfo,
|
public info: PluginNodeEnvInfo,
|
||||||
public controller: Controller,
|
public controller: Controller,
|
||||||
public metrics: any[],
|
public metrics: any[],
|
||||||
logger: Logger
|
logger: Logger
|
||||||
@@ -600,7 +630,7 @@ export class BaseControlPlugin {
|
|||||||
/**
|
/**
|
||||||
* The plugin's own info module
|
* The plugin's own info module
|
||||||
*/
|
*/
|
||||||
public info: PluginInfo,
|
public info: PluginNodeEnvInfo,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
) {
|
) {
|
||||||
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
this.logger = logger.child({ plugin: this.info.name }) as unknown as Logger;
|
||||||
@@ -647,6 +677,26 @@ export interface PluginLoginForm {
|
|||||||
Component: React["Component"];
|
Component: React["Component"];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type AccountRole = {
|
||||||
|
name: string;
|
||||||
|
id: number;
|
||||||
|
permissions: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UserAccount = {
|
||||||
|
/** Name of the currently logged in account. */
|
||||||
|
name: string;
|
||||||
|
/** Roles of the corrently logged in account. */
|
||||||
|
roles: AccountRole[];
|
||||||
|
/** Check if the currently logged in account has the given permission. */
|
||||||
|
hasPermission: (permission: string) => boolean | null;
|
||||||
|
/** Check if the currently logged in account has any of the given permissions. */
|
||||||
|
hasAnyPermission: (...permissions: string[]) => boolean | null;
|
||||||
|
/** Check if the currently logged in account has all of given permissions. */
|
||||||
|
hasAllPermission: (...permissions: string[]) => boolean | null;
|
||||||
|
/** Logs out of the web interface. */
|
||||||
|
logOut: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin supplied pages
|
* Plugin supplied pages
|
||||||
@@ -677,7 +727,7 @@ export interface PluginPage {
|
|||||||
/**
|
/**
|
||||||
* Permission to access page. function are expected to throw an error if access is deny.
|
* Permission to access page. function are expected to throw an error if access is deny.
|
||||||
*/
|
*/
|
||||||
permission?: string | ((user: User, message: MessageRequest|MessageEvent) => void);
|
permission?: string | ((account: UserAccount) => (boolean|null));
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -762,7 +812,7 @@ export class BaseWebPlugin {
|
|||||||
/**
|
/**
|
||||||
* The plugin's own info module
|
* The plugin's own info module
|
||||||
*/
|
*/
|
||||||
public info: PluginInfo,
|
public info: PluginWebpackEnvInfo,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
) {
|
) {
|
||||||
this.package = packageData;
|
this.package = packageData;
|
||||||
|
|||||||
@@ -21,9 +21,9 @@ import { logger } from "./logging";
|
|||||||
* @returns Array of plugin info modules.
|
* @returns Array of plugin info modules.
|
||||||
*/
|
*/
|
||||||
export async function loadPluginInfos(pluginList: Map<string, string>) {
|
export async function loadPluginInfos(pluginList: Map<string, string>) {
|
||||||
let plugins: libPlugin.PluginInfo[] = [];
|
let plugins: libPlugin.PluginNodeEnvInfo[] = [];
|
||||||
for (let [pluginName, pluginPath] of pluginList) {
|
for (let [pluginName, pluginPath] of pluginList) {
|
||||||
let pluginInfo: libPlugin.PluginInfo;
|
let pluginInfo: libPlugin.PluginNodeEnvInfo;
|
||||||
let pluginPackage: { version: string, main?: string };
|
let pluginPackage: { version: string, main?: string };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -53,12 +53,12 @@ export async function loadPluginInfos(pluginList: Map<string, string>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function loadPluginClass(
|
function loadPluginClass(
|
||||||
entrypointName: string,
|
entrypointName: "controllerEntrypoint"|"instanceEntrypoint"|"controlEntrypoint",
|
||||||
className: string,
|
className: string,
|
||||||
pluginClass: any,
|
pluginClass: any,
|
||||||
pluginInfo: libPlugin.PluginInfo
|
pluginInfo: libPlugin.PluginNodeEnvInfo
|
||||||
) {
|
) {
|
||||||
let resolvedPath = path.posix.join(pluginInfo.requirePath, pluginInfo[entrypointName]);
|
let resolvedPath = path.posix.join(pluginInfo.requirePath, pluginInfo[entrypointName]!);
|
||||||
let entrypoint = require(resolvedPath);
|
let entrypoint = require(resolvedPath);
|
||||||
if (!entrypoint[className]) {
|
if (!entrypoint[className]) {
|
||||||
throw new libErrors.PluginError(pluginInfo.name,
|
throw new libErrors.PluginError(pluginInfo.name,
|
||||||
@@ -82,7 +82,7 @@ function loadPluginClass(
|
|||||||
* @returns plugin class
|
* @returns plugin class
|
||||||
*/
|
*/
|
||||||
export async function loadControllerPluginClass(
|
export async function loadControllerPluginClass(
|
||||||
pluginInfo: libPlugin.PluginInfo
|
pluginInfo: libPlugin.PluginNodeEnvInfo
|
||||||
): Promise<typeof libPlugin.BaseControllerPlugin> {
|
): Promise<typeof libPlugin.BaseControllerPlugin> {
|
||||||
return loadPluginClass("controllerEntrypoint", "ControllerPlugin", libPlugin.BaseControllerPlugin, pluginInfo);
|
return loadPluginClass("controllerEntrypoint", "ControllerPlugin", libPlugin.BaseControllerPlugin, pluginInfo);
|
||||||
}
|
}
|
||||||
@@ -96,7 +96,7 @@ export async function loadControllerPluginClass(
|
|||||||
* @returns plugin class
|
* @returns plugin class
|
||||||
*/
|
*/
|
||||||
export async function loadInstancePluginClass(
|
export async function loadInstancePluginClass(
|
||||||
pluginInfo: libPlugin.PluginInfo
|
pluginInfo: libPlugin.PluginNodeEnvInfo
|
||||||
): Promise<typeof libPlugin.BaseInstancePlugin> {
|
): Promise<typeof libPlugin.BaseInstancePlugin> {
|
||||||
return loadPluginClass("instanceEntrypoint", "InstancePlugin", libPlugin.BaseInstancePlugin, pluginInfo);
|
return loadPluginClass("instanceEntrypoint", "InstancePlugin", libPlugin.BaseInstancePlugin, pluginInfo);
|
||||||
}
|
}
|
||||||
@@ -110,7 +110,7 @@ export async function loadInstancePluginClass(
|
|||||||
* @returns plugin class
|
* @returns plugin class
|
||||||
*/
|
*/
|
||||||
export async function loadControlPluginClass(
|
export async function loadControlPluginClass(
|
||||||
pluginInfo: libPlugin.PluginInfo
|
pluginInfo: libPlugin.PluginNodeEnvInfo
|
||||||
): Promise<typeof libPlugin.BaseControlPlugin> {
|
): Promise<typeof libPlugin.BaseControlPlugin> {
|
||||||
return loadPluginClass("controlEntrypoint", "ControlPlugin", libPlugin.BaseControlPlugin, pluginInfo);
|
return loadPluginClass("controlEntrypoint", "ControlPlugin", libPlugin.BaseControlPlugin, pluginInfo);
|
||||||
}
|
}
|
||||||
Vendored
+12
@@ -0,0 +1,12 @@
|
|||||||
|
declare module '*.png' {
|
||||||
|
const value: import('react-native').ImageSourcePropType;
|
||||||
|
export default value;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare interface Window {
|
||||||
|
webRoot: string;
|
||||||
|
staticRoot: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare const __webpack_init_sharing__: (shareScope: string) => Promise<void>;
|
||||||
|
declare const __webpack_share_scopes__: { default: any };
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
"author": "Hornwitser",
|
"author": "Hornwitser",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"version": "2.0.0-alpha.13",
|
"version": "2.0.0-alpha.13",
|
||||||
"browser": "src/index.jsx",
|
"browser": "src/index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
},
|
},
|
||||||
@@ -32,12 +32,15 @@
|
|||||||
"os-browserify": "^0.3.0",
|
"os-browserify": "^0.3.0",
|
||||||
"path-browserify": "^1.0.1",
|
"path-browserify": "^1.0.1",
|
||||||
"process": "^0.11.10",
|
"process": "^0.11.10",
|
||||||
|
"rc-field-form": "^1.37.0",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"react-router-dom": "^6.14.2",
|
"react-router-dom": "^6.14.2",
|
||||||
"stream-browserify": "^3.0.0",
|
"stream-browserify": "^3.0.0",
|
||||||
"style-loader": "^3.3.3",
|
"style-loader": "^3.3.3",
|
||||||
"terser-webpack-plugin": "^5.3.9",
|
"terser-webpack-plugin": "^5.3.9",
|
||||||
|
"ts-loader": "^9.4.4",
|
||||||
|
"typescript": "^5.1.6",
|
||||||
"util": "^0.12.5",
|
"util": "^0.12.5",
|
||||||
"webpack": "^5.88.2",
|
"webpack": "^5.88.2",
|
||||||
"webpack-cli": "^5.1.4",
|
"webpack-cli": "^5.1.4",
|
||||||
@@ -45,5 +48,10 @@
|
|||||||
},
|
},
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"access": "public"
|
"access": "public"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.4.5",
|
||||||
|
"@types/react": "^18.2.21",
|
||||||
|
"@types/react-dom": "^18.2.7"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,13 +4,14 @@ import React from "react";
|
|||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
import type { PluginWebApi } from "@clusterio/controller/src/routes";
|
||||||
|
|
||||||
import App from "./components/App";
|
import App from "./components/App";
|
||||||
import { Control, ControlConnector } from "./util/websocket";
|
import { Control, ControlConnector } from "./util/websocket";
|
||||||
|
|
||||||
const { ConsoleTransport, WebConsoleFormat, logger } = lib;
|
const { ConsoleTransport, WebConsoleFormat, logger } = lib;
|
||||||
|
|
||||||
async function loadScript(url) {
|
async function loadScript(url: string) {
|
||||||
let script = document.createElement("script");
|
let script = document.createElement("script");
|
||||||
script.src = url;
|
script.src = url;
|
||||||
script.type = "text/javascript";
|
script.type = "text/javascript";
|
||||||
@@ -25,9 +26,9 @@ async function loadScript(url) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPluginInfos() {
|
async function loadPluginInfos(): Promise<lib.PluginWebpackEnvInfo[]> {
|
||||||
let response = await fetch(`${webRoot}api/plugins`);
|
let response = await fetch(`${window.webRoot}api/plugins`);
|
||||||
let pluginList;
|
let pluginList: PluginWebApi[];
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
pluginList = await response.json();
|
pluginList = await response.json();
|
||||||
|
|
||||||
@@ -44,8 +45,8 @@ async function loadPluginInfos() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await loadScript(`${webRoot}${meta.web.main}`);
|
await loadScript(`${window.webRoot}${meta.web.main}`);
|
||||||
let container = window[`plugin_${meta.name}`];
|
let container: any = (window as { [key: string]: any })[`plugin_${meta.name}`];
|
||||||
if (!container) {
|
if (!container) {
|
||||||
throw new Error(`Plugin did not expose its container via plugin_${meta.name}`);
|
throw new Error(`Plugin did not expose its container via plugin_${meta.name}`);
|
||||||
}
|
}
|
||||||
@@ -56,7 +57,7 @@ async function loadPluginInfos() {
|
|||||||
pluginInfo.enabled = meta.enabled;
|
pluginInfo.enabled = meta.enabled;
|
||||||
pluginInfos.push(pluginInfo);
|
pluginInfos.push(pluginInfo);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
logger.error(`Failed to load plugin info for ${meta.name}`);
|
logger.error(`Failed to load plugin info for ${meta.name}`);
|
||||||
if (err.stack) {
|
if (err.stack) {
|
||||||
logger.error(err.stack);
|
logger.error(err.stack);
|
||||||
@@ -66,7 +67,7 @@ async function loadPluginInfos() {
|
|||||||
return pluginInfos;
|
return pluginInfos;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPlugins(pluginInfos) {
|
async function loadPlugins(pluginInfos: lib.PluginWebpackEnvInfo[]) {
|
||||||
let plugins = new Map();
|
let plugins = new Map();
|
||||||
for (let pluginInfo of pluginInfos) {
|
for (let pluginInfo of pluginInfos) {
|
||||||
if (!pluginInfo.enabled) {
|
if (!pluginInfo.enabled) {
|
||||||
@@ -86,7 +87,7 @@ async function loadPlugins(pluginInfos) {
|
|||||||
await plugin.init();
|
await plugin.init();
|
||||||
plugins.set(pluginInfo.name, plugin);
|
plugins.set(pluginInfo.name, plugin);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
logger.error(`Failed to load plugin ${pluginInfo.name}`);
|
logger.error(`Failed to load plugin ${pluginInfo.name}`);
|
||||||
if (err.stack) {
|
if (err.stack) {
|
||||||
logger.error(err.stack);
|
logger.error(err.stack);
|
||||||
@@ -107,10 +108,10 @@ export default async function bootstrap() {
|
|||||||
lib.finalizeConfigs();
|
lib.finalizeConfigs();
|
||||||
let plugins = await loadPlugins(pluginInfos);
|
let plugins = await loadPlugins(pluginInfos);
|
||||||
|
|
||||||
let wsUrl = new URL(window.webRoot, document.location);
|
let wsUrl = new URL(window.webRoot, document.location.href);
|
||||||
let controlConnector = new ControlConnector(wsUrl, 120);
|
let controlConnector = new ControlConnector(wsUrl.href, 120, undefined);
|
||||||
let control = new Control(controlConnector, plugins);
|
let control = new Control(controlConnector, plugins);
|
||||||
|
|
||||||
const root = createRoot(document.getElementById("root"));
|
const root = createRoot(document.getElementById("root") as HTMLDivElement);
|
||||||
root.render(<App control={control}/>);
|
root.render(<App control={control}/>);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { Control } from "../util/websocket";
|
||||||
|
|
||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { BrowserRouter } from "react-router-dom";
|
import { BrowserRouter } from "react-router-dom";
|
||||||
|
|
||||||
@@ -13,7 +15,10 @@ import { Card, ConfigProvider, Spin, Typography, theme } from "antd";
|
|||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
|
|
||||||
|
|
||||||
function ErrorCard(props) {
|
export type ErrorProps = {
|
||||||
|
error: Error;
|
||||||
|
};
|
||||||
|
function ErrorCard(props: ErrorProps) {
|
||||||
return <div className="login-container">
|
return <div className="login-container">
|
||||||
<Card>
|
<Card>
|
||||||
<h1>An unexpected error occured</h1>
|
<h1>An unexpected error occured</h1>
|
||||||
@@ -22,7 +27,11 @@ function ErrorCard(props) {
|
|||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function App(props) {
|
|
||||||
|
type AppProps = {
|
||||||
|
control: Control;
|
||||||
|
};
|
||||||
|
export default function App(props: AppProps) {
|
||||||
let [connected, setConnected] = useState(false);
|
let [connected, setConnected] = useState(false);
|
||||||
let [token, setToken] = useState(localStorage.getItem("controller_token") || null);
|
let [token, setToken] = useState(localStorage.getItem("controller_token") || null);
|
||||||
let connector = props.control.connector;
|
let connector = props.control.connector;
|
||||||
@@ -35,7 +44,11 @@ export default function App(props) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function onConnect() {
|
function onConnect() {
|
||||||
localStorage.setItem("controller_token", token);
|
if (token === null) {
|
||||||
|
localStorage.removeItem("controller_token");
|
||||||
|
} else {
|
||||||
|
localStorage.setItem("controller_token", token);
|
||||||
|
}
|
||||||
setConnected(true);
|
setConnected(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,7 +56,7 @@ export default function App(props) {
|
|||||||
setConnected(false);
|
setConnected(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
function onError(err) {
|
function onError(err: any) {
|
||||||
logger.error(`Unexpected error in connector:\n${err.stack}`);
|
logger.error(`Unexpected error in connector:\n${err.stack}`);
|
||||||
clearToken();
|
clearToken();
|
||||||
setConnected(false);
|
setConnected(false);
|
||||||
@@ -96,7 +109,7 @@ export default function App(props) {
|
|||||||
theme={{ algorithm: theme.darkAlgorithm }}
|
theme={{ algorithm: theme.darkAlgorithm }}
|
||||||
>
|
>
|
||||||
<ControlContext.Provider value={props.control}>
|
<ControlContext.Provider value={props.control}>
|
||||||
<BrowserRouter basename={webRoot}>
|
<BrowserRouter basename={window.webRoot}>
|
||||||
{page}
|
{page}
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</ControlContext.Provider>
|
</ControlContext.Provider>
|
||||||
+10
-2
@@ -1,3 +1,4 @@
|
|||||||
|
import type { BaseButtonProps } from "antd/es/button/button";
|
||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { Button, Form, Modal, Select, Typography } from "antd";
|
import { Button, Form, Modal, Select, Typography } from "antd";
|
||||||
|
|
||||||
@@ -10,7 +11,14 @@ import { useHostList } from "../model/host";
|
|||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
|
|
||||||
|
|
||||||
export default function AssignInstanceModal(props) {
|
type AssignInstanceModalProps = {
|
||||||
|
id?: number;
|
||||||
|
hostId?: number;
|
||||||
|
buttonProps: BaseButtonProps & { style: React.CSSProperties };
|
||||||
|
buttonContent: string;
|
||||||
|
onFinish?: () => void;
|
||||||
|
};
|
||||||
|
export default function AssignInstanceModal(props: AssignInstanceModalProps) {
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [hostList] = useHostList();
|
let [hostList] = useHostList();
|
||||||
let [applying, setApplying] = useState(false);
|
let [applying, setApplying] = useState(false);
|
||||||
@@ -30,7 +38,7 @@ export default function AssignInstanceModal(props) {
|
|||||||
|
|
||||||
setApplying(true);
|
setApplying(true);
|
||||||
control.send(
|
control.send(
|
||||||
new lib.InstanceAssignRequest(props.id, hostId)
|
new lib.InstanceAssignRequest(props.id!, hostId)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
if (props.onFinish) {
|
if (props.onFinish) {
|
||||||
+37
-15
@@ -1,11 +1,13 @@
|
|||||||
|
import type * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { Button, Card, Checkbox, Form, Input, InputNumber, Space, Spin, Tooltip, Tree, Typography } from "antd";
|
import { Button, Card, Checkbox, Form, Input, InputNumber, Space, Spin, Tooltip, Tree, Typography } from "antd";
|
||||||
import ReloadOutlined from "@ant-design/icons/ReloadOutlined";
|
import ReloadOutlined from "@ant-design/icons/ReloadOutlined";
|
||||||
|
|
||||||
const { Title } = Typography;
|
const { Title } = Typography;
|
||||||
|
|
||||||
function getInitialValues(config, props) {
|
function getInitialValues(config: lib.Config, props: BaseConfigTreeProps) {
|
||||||
let initialValues = {};
|
let initialValues: any = {};
|
||||||
for (let [name, GroupClass] of props.ConfigClass.groups) {
|
for (let [name, GroupClass] of props.ConfigClass.groups) {
|
||||||
let group = config.group(name);
|
let group = config.group(name);
|
||||||
for (let def of GroupClass.definitions.values()) {
|
for (let def of GroupClass.definitions.values()) {
|
||||||
@@ -13,7 +15,7 @@ function getInitialValues(config, props) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let value = group.get(def.name);
|
let value = group.get(def.name) as any;
|
||||||
let fieldName = `${group.name}.${def.name}`;
|
let fieldName = `${group.name}.${def.name}`;
|
||||||
|
|
||||||
if (def.type === "object") {
|
if (def.type === "object") {
|
||||||
@@ -29,10 +31,18 @@ function getInitialValues(config, props) {
|
|||||||
return initialValues;
|
return initialValues;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function BaseConfigTree(props) {
|
type BaseConfigTreeProps = {
|
||||||
let [config, setConfig] = useState(null);
|
ConfigClass: typeof lib.Config;
|
||||||
|
retrieveConfig: () => Promise<lib.SerializedConfig>;
|
||||||
|
setField: (field:string, value:any) => Promise<void>;
|
||||||
|
setProp: (field:string, prop:string, value:any) => Promise<void>;
|
||||||
|
id?: number;
|
||||||
|
onApply?: () => void;
|
||||||
|
};
|
||||||
|
export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||||
|
let [config, setConfig] = useState<lib.Config|null>(null);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
let [changedFields, setChangedFields] = useState(new Set());
|
let [changedFields, setChangedFields] = useState<Set<string>>(new Set());
|
||||||
let [errorFields, setErrorFields] = useState(new Map());
|
let [errorFields, setErrorFields] = useState(new Map());
|
||||||
let [applying, setApplying] = useState(false);
|
let [applying, setApplying] = useState(false);
|
||||||
|
|
||||||
@@ -49,7 +59,7 @@ export default function BaseConfigTree(props) {
|
|||||||
});
|
});
|
||||||
}, [props.id]);
|
}, [props.id]);
|
||||||
|
|
||||||
function renderInput(def) {
|
function renderInput(def: lib.FieldDefinition) {
|
||||||
if (def.type === "boolean") {
|
if (def.type === "boolean") {
|
||||||
return <Checkbox/>;
|
return <Checkbox/>;
|
||||||
}
|
}
|
||||||
@@ -67,8 +77,8 @@ export default function BaseConfigTree(props) {
|
|||||||
return <Spin/>;
|
return <Spin/>;
|
||||||
}
|
}
|
||||||
|
|
||||||
let initialValues = {};
|
let initialValues: any = {};
|
||||||
function onValuesChange(changedValues) {
|
function onValuesChange(changedValues: object) {
|
||||||
let newChangedFields = new Set(changedFields);
|
let newChangedFields = new Set(changedFields);
|
||||||
let changed = false;
|
let changed = false;
|
||||||
for (let [key, value] of Object.entries(changedValues)) {
|
for (let [key, value] of Object.entries(changedValues)) {
|
||||||
@@ -93,11 +103,23 @@ export default function BaseConfigTree(props) {
|
|||||||
title="A restart is required for this setting to take effect"
|
title="A restart is required for this setting to take effect"
|
||||||
><ReloadOutlined/></Tooltip>;
|
><ReloadOutlined/></Tooltip>;
|
||||||
|
|
||||||
|
|
||||||
|
type ChildNode = {
|
||||||
|
key: string;
|
||||||
|
children: any[];
|
||||||
|
title?: React.ReactElement;
|
||||||
|
};
|
||||||
|
type TreeNode = {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
children: ChildNode[];
|
||||||
|
};
|
||||||
|
|
||||||
let treeData = [];
|
let treeData = [];
|
||||||
let propsMap = new Map();
|
let propsMap = new Map();
|
||||||
for (let [name, GroupClass] of props.ConfigClass.groups) {
|
for (let [name, GroupClass] of props.ConfigClass.groups) {
|
||||||
let group = config.group(name);
|
let group = config.group(name);
|
||||||
let treeNode = {
|
let treeNode: TreeNode = {
|
||||||
key: group.name,
|
key: group.name,
|
||||||
title: group.name,
|
title: group.name,
|
||||||
children: [],
|
children: [],
|
||||||
@@ -108,9 +130,9 @@ export default function BaseConfigTree(props) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let value = group.get(def.name);
|
let value = group.get(def.name) as any;
|
||||||
let fieldName = `${group.name}.${def.name}`;
|
let fieldName = `${group.name}.${def.name}`;
|
||||||
let childNode = {
|
let childNode: ChildNode = {
|
||||||
key: fieldName,
|
key: fieldName,
|
||||||
children: [],
|
children: [],
|
||||||
};
|
};
|
||||||
@@ -127,7 +149,7 @@ export default function BaseConfigTree(props) {
|
|||||||
for (let prop of Object.keys(value)) {
|
for (let prop of Object.keys(value)) {
|
||||||
let propPath = `${group.name}.${def.name}.${prop}`;
|
let propPath = `${group.name}.${def.name}.${prop}`;
|
||||||
let restart = Boolean(
|
let restart = Boolean(
|
||||||
def.restartRequiredProps && def.restartRequired ^ restartRequiredProps.has(prop)
|
def.restartRequiredProps && Number(def.restartRequired) ^ Number(restartRequiredProps.has(prop))
|
||||||
);
|
);
|
||||||
childNode.children.push({
|
childNode.children.push({
|
||||||
key: propPath,
|
key: propPath,
|
||||||
@@ -180,7 +202,7 @@ export default function BaseConfigTree(props) {
|
|||||||
let propValue = form.getFieldValue(`${newPropPath}.value`);
|
let propValue = form.getFieldValue(`${newPropPath}.value`);
|
||||||
if (!Object.prototype.hasOwnProperty.call(value, propName)) {
|
if (!Object.prototype.hasOwnProperty.call(value, propName)) {
|
||||||
let newConfig = new props.ConfigClass("control");
|
let newConfig = new props.ConfigClass("control");
|
||||||
await newConfig.load(config.serialize());
|
await newConfig.load(config!.serialize());
|
||||||
newConfig.setProp(fieldName, propName, null);
|
newConfig.setProp(fieldName, propName, null);
|
||||||
setConfig(newConfig);
|
setConfig(newConfig);
|
||||||
}
|
}
|
||||||
@@ -252,7 +274,7 @@ export default function BaseConfigTree(props) {
|
|||||||
return newChanged;
|
return newChanged;
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
setErrorFields(errors => {
|
setErrorFields(errors => {
|
||||||
let newErrors = new Map(errors);
|
let newErrors = new Map(errors);
|
||||||
newErrors.set(field, err.message);
|
newErrors.set(field, err.message);
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
|
|
||||||
export default React.createContext();
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import type { Control } from "../util/websocket";
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
|
||||||
|
export default React.createContext<Control>({} as Control);
|
||||||
+3
-3
@@ -6,7 +6,7 @@ import BaseConfigTree from "./BaseConfigTree";
|
|||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
|
|
||||||
|
|
||||||
export default function ControllerConfigTree(props) {
|
export default function ControllerConfigTree() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
|
|
||||||
async function retrieveConfig() {
|
async function retrieveConfig() {
|
||||||
@@ -14,14 +14,14 @@ export default function ControllerConfigTree(props) {
|
|||||||
return result.serializedConfig;
|
return result.serializedConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setField(field, value) {
|
async function setField(field: string, value: any) {
|
||||||
await control.send(new lib.ControllerConfigSetFieldRequest(
|
await control.send(new lib.ControllerConfigSetFieldRequest(
|
||||||
field,
|
field,
|
||||||
String(value),
|
String(value),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setProp(field, prop, value) {
|
async function setProp(field: string, prop: string, value: any) {
|
||||||
if (value) {
|
if (value) {
|
||||||
try {
|
try {
|
||||||
value = JSON.parse(value);
|
value = JSON.parse(value);
|
||||||
File renamed without changes.
+9
-5
@@ -7,7 +7,11 @@ import ControlContext from "./ControlContext";
|
|||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
|
||||||
|
|
||||||
export default function CreateSaveModal(props) {
|
type CreateSaveModalProps = {
|
||||||
|
instance: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function CreateSaveModal(props: CreateSaveModalProps) {
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [creatingSave, setCreatingSave] = useState(false);
|
let [creatingSave, setCreatingSave] = useState(false);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
@@ -23,7 +27,7 @@ export default function CreateSaveModal(props) {
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = lib.readMapExchangeString(values.exchangeString);
|
result = lib.readMapExchangeString(values.exchangeString);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -34,7 +38,7 @@ export default function CreateSaveModal(props) {
|
|||||||
if (values.mapGenSettings && values.mapGenSettings.trim()) {
|
if (values.mapGenSettings && values.mapGenSettings.trim()) {
|
||||||
try {
|
try {
|
||||||
mapGenSettings = JSON.parse(values.mapGenSettings);
|
mapGenSettings = JSON.parse(values.mapGenSettings);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "mapGenSettings", errors: [err.message] }]);
|
form.setFields([{ name: "mapGenSettings", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -43,7 +47,7 @@ export default function CreateSaveModal(props) {
|
|||||||
if (values.mapSettings && values.mapSettings.trim()) {
|
if (values.mapSettings && values.mapSettings.trim()) {
|
||||||
try {
|
try {
|
||||||
mapSettings = JSON.parse(values.mapSettings);
|
mapSettings = JSON.parse(values.mapSettings);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "mapSettings", errors: [err.message] }]);
|
form.setFields([{ name: "mapSettings", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -69,7 +73,7 @@ export default function CreateSaveModal(props) {
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = lib.readMapExchangeString(exchangeString);
|
result = lib.readMapExchangeString(exchangeString);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
|
|
||||||
|
|
||||||
export default class ErrorBoundary extends React.Component {
|
|
||||||
constructor(props) {
|
|
||||||
super(props);
|
|
||||||
this.state = { error: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
static getDerivedStateFromError(error) {
|
|
||||||
return { error };
|
|
||||||
}
|
|
||||||
|
|
||||||
render() {
|
|
||||||
if (this.state.error) {
|
|
||||||
return <this.props.Component error={this.state.error} />;
|
|
||||||
}
|
|
||||||
return this.props.children;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import React from "react";
|
||||||
|
|
||||||
|
import type { ErrorProps } from "./App";
|
||||||
|
|
||||||
|
type ErrorBoundaryProps = {
|
||||||
|
Component: (props: ErrorProps) => React.JSX.Element;
|
||||||
|
children?: React.ReactElement;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ErrorBoundaryState = {
|
||||||
|
error: Error | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||||
|
state: ErrorBoundaryState = { error: null };
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error: any) {
|
||||||
|
return { error };
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.error) {
|
||||||
|
return <this.props.Component error={this.state.error} />;
|
||||||
|
}
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -2,11 +2,12 @@ import React from "react";
|
|||||||
import { Typography } from "antd";
|
import { Typography } from "antd";
|
||||||
|
|
||||||
import PageLayout from "./PageLayout";
|
import PageLayout from "./PageLayout";
|
||||||
|
import type { ErrorProps } from "./App";
|
||||||
|
|
||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
|
|
||||||
|
|
||||||
export default function ErrorPage(props) {
|
export default function ErrorPage(props: ErrorProps) {
|
||||||
return <PageLayout nav={[{ name: "Error" }]}>
|
return <PageLayout nav={[{ name: "Error" }]}>
|
||||||
<h2>An unexpected error occured</h2>
|
<h2>An unexpected error occured</h2>
|
||||||
<Paragraph code className="error-traceback">{props.error.stack}</Paragraph>
|
<Paragraph code className="error-traceback">{props.error.stack}</Paragraph>
|
||||||
+4
-5
@@ -13,8 +13,7 @@ import PluginExtra from "./PluginExtra";
|
|||||||
|
|
||||||
const { Title } = Typography;
|
const { Title } = Typography;
|
||||||
|
|
||||||
|
export default function HostViewPage() {
|
||||||
export default function HostViewPage(props) {
|
|
||||||
let params = useParams();
|
let params = useParams();
|
||||||
let hostId = Number(params.id);
|
let hostId = Number(params.id);
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
@@ -23,20 +22,20 @@ export default function HostViewPage(props) {
|
|||||||
|
|
||||||
instanceList = instanceList.filter(instance => instance.assignedHost === hostId);
|
instanceList = instanceList.filter(instance => instance.assignedHost === hostId);
|
||||||
|
|
||||||
let nav = [{ name: "Hosts", path: "/hosts" }, { name: host.name || hostId }];
|
let nav = [{ name: "Hosts", path: "/hosts" }, { name: host.name || String(hostId) }];
|
||||||
if (host.loading) {
|
if (host.loading) {
|
||||||
return <PageLayout nav={nav}><Spin size="large" /></PageLayout>;
|
return <PageLayout nav={nav}><Spin size="large" /></PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (host.missing) {
|
if (host.missing) {
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<PageHeader title={hostId} />
|
<PageHeader title={String(hostId)} />
|
||||||
<p>Host with id {hostId} was not found on the controller.</p>
|
<p>Host with id {hostId} was not found on the controller.</p>
|
||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<PageHeader title={host.name || hostId} />
|
<PageHeader title={host.name || String(hostId)} />
|
||||||
|
|
||||||
<Descriptions bordered size="small" column={{ xs: 1, sm: 2, xl: 4 }}>
|
<Descriptions bordered size="small" column={{ xs: 1, sm: 2, xl: 4 }}>
|
||||||
<Descriptions.Item label="Name">{host["name"]}</Descriptions.Item>
|
<Descriptions.Item label="Name">{host["name"]}</Descriptions.Item>
|
||||||
+28
-18
@@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom";
|
|||||||
import { Button, Form, InputNumber, Modal, Table, Tag, Typography } from "antd";
|
import { Button, Form, InputNumber, Modal, Table, Tag, Typography } from "antd";
|
||||||
import CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
|
import CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
|
||||||
|
|
||||||
|
import type { PluginWebApi } from "@clusterio/controller/src/routes";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
@@ -13,19 +14,19 @@ import PluginExtra from "./PluginExtra";
|
|||||||
import { useHostList } from "../model/host";
|
import { useHostList } from "../model/host";
|
||||||
import notify, { notifyErrorHandler } from "../util/notify";
|
import notify, { notifyErrorHandler } from "../util/notify";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
function GenerateHostTokenButton(props) {
|
function GenerateHostTokenButton() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [token, setToken] = useState(null);
|
let [token, setToken] = useState<string|null>(null);
|
||||||
let [hostId, setHostId] = useState(null);
|
let [hostId, setHostId] = useState<number|null>(null);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
let [pluginList, setPluginList] = useState([]);
|
let [pluginList, setPluginList] = useState<PluginWebApi[]>([]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
let response = await fetch(`${webRoot}api/plugins`);
|
let response = await fetch(`${window.webRoot}api/plugins`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const plugins = await response.json();
|
const plugins = await response.json();
|
||||||
setPluginList(plugins);
|
setPluginList(plugins);
|
||||||
@@ -36,7 +37,7 @@ function GenerateHostTokenButton(props) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
async function generateToken() {
|
async function generateToken() {
|
||||||
let id = null;
|
let id = undefined;
|
||||||
let values = form.getFieldsValue();
|
let values = form.getFieldsValue();
|
||||||
if (values.hostId) {
|
if (values.hostId) {
|
||||||
id = Number.parseInt(values.hostId, 10);
|
id = Number.parseInt(values.hostId, 10);
|
||||||
@@ -49,7 +50,7 @@ function GenerateHostTokenButton(props) {
|
|||||||
|
|
||||||
let newToken = await control.send(new lib.HostGenerateTokenRequest(id));
|
let newToken = await control.send(new lib.HostGenerateTokenRequest(id));
|
||||||
setToken(newToken);
|
setToken(newToken);
|
||||||
setHostId(id);
|
setHostId(id??null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a new random
|
// Generate a new random
|
||||||
@@ -60,6 +61,7 @@ function GenerateHostTokenButton(props) {
|
|||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
// Only install plugins that aren't filesystem paths. Npm modules have max 1 forward slash in their name.
|
// Only install plugins that aren't filesystem paths. Npm modules have max 1 forward slash in their name.
|
||||||
|
//@ts-ignore TODO::: this doesn't filter anything, `x.split("/") <= 1` is always = true. repair or shouldn't filter ?
|
||||||
const pluginString = pluginList.map(p => `"${p.requirePath}"`).filter(x => x.split("/") <= 1).join(" ");
|
const pluginString = pluginList.map(p => `"${p.requirePath}"`).filter(x => x.split("/") <= 1).join(" ");
|
||||||
return <>
|
return <>
|
||||||
<Button
|
<Button
|
||||||
@@ -138,10 +140,11 @@ function GenerateHostTokenButton(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function CopyButton({ text, message }) {
|
function CopyButton({ text, message }: { text:string, message:string }) {
|
||||||
let [clipboardPermision, setClipboardPermission] = useState("granted");
|
let [clipboardPermision, setClipboardPermission] = useState("granted");
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
|
//@ts-ignore https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write
|
||||||
let result = await navigator.permissions.query({ name: "clipboard-write" });
|
let result = await navigator.permissions.query({ name: "clipboard-write" });
|
||||||
// result.state is "granted", "denied" or "prompt"
|
// result.state is "granted", "denied" or "prompt"
|
||||||
setClipboardPermission(result.state);
|
setClipboardPermission(result.state);
|
||||||
@@ -152,13 +155,20 @@ function CopyButton({ text, message }) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
async function checkClipboardPermission() {
|
async function checkClipboardPermission() {
|
||||||
let result = await navigator.permissions.query({ name: "clipboard-write" });
|
try {
|
||||||
// result.state is "granted", "denied" or "prompt"
|
//@ts-ignore https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write
|
||||||
setClipboardPermission(result.state);
|
let result = await navigator.permissions.query({ name: "clipboard-write" });
|
||||||
result.onchange = function () {
|
// result.state is "granted", "denied" or "prompt"
|
||||||
setClipboardPermission(result.state);
|
setClipboardPermission(result.state);
|
||||||
};
|
result.onchange = function () {
|
||||||
return result.state === "granted";
|
setClipboardPermission(result.state);
|
||||||
|
};
|
||||||
|
return result.state === "granted";
|
||||||
|
|
||||||
|
} catch (err: any) {
|
||||||
|
//If it fail because "clipboard-write" is not supported.
|
||||||
|
return err.name === "TypeError";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return <Button
|
return <Button
|
||||||
@@ -184,7 +194,7 @@ export default function HostsPage() {
|
|||||||
return <PageLayout nav={[{ name: "Hosts" }]}>
|
return <PageLayout nav={[{ name: "Hosts" }]}>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Hosts"
|
title="Hosts"
|
||||||
extra={account.hasPermission("core.host.generate_token") && <GenerateHostTokenButton />}
|
extra={account.hasPermission("core.host.generate_token") && <GenerateHostTokenButton /> || undefined}
|
||||||
/>
|
/>
|
||||||
<Table
|
<Table
|
||||||
columns={[
|
columns={[
|
||||||
@@ -208,7 +218,7 @@ export default function HostsPage() {
|
|||||||
{
|
{
|
||||||
title: "Public address",
|
title: "Public address",
|
||||||
dataIndex: "publicAddress",
|
dataIndex: "publicAddress",
|
||||||
sorter: (a, b) => strcmp(a.publicAddress, b.publicAddress),
|
sorter: (a, b) => strcmp(a.publicAddress??"", b.publicAddress??""),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Connected",
|
title: "Connected",
|
||||||
@@ -218,7 +228,7 @@ export default function HostsPage() {
|
|||||||
>
|
>
|
||||||
{host.connected ? "Connected" : "Disconnected"}
|
{host.connected ? "Connected" : "Disconnected"}
|
||||||
</Tag>,
|
</Tag>,
|
||||||
sorter: (a, b) => a.connected - b.connected,
|
sorter: (a, b) => Number(a.connected) - Number(b.connected),
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
dataSource={hostList}
|
dataSource={hostList}
|
||||||
+8
-4
@@ -6,19 +6,23 @@ import BaseConfigTree from "./BaseConfigTree";
|
|||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
|
|
||||||
|
|
||||||
export default function InstanceConfigTree(props) {
|
type InstanceConfigTreeProps = {
|
||||||
|
id: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function InstanceConfigTree(props: InstanceConfigTreeProps) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
|
|
||||||
async function retrieveConfig() {
|
async function retrieveConfig() {
|
||||||
let result = await control.send(new lib.InstanceConfigGetRequest(props.id));
|
let result = await control.send(new lib.InstanceConfigGetRequest(props.id));
|
||||||
return result.config;
|
return result.serializedConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setField(field, value) {
|
async function setField(field: string, value: any) {
|
||||||
await control.send(new lib.InstanceConfigSetFieldRequest(props.id, field, value));
|
await control.send(new lib.InstanceConfigSetFieldRequest(props.id, field, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setProp(field, prop, value) {
|
async function setProp(field: string, prop: string, value: any) {
|
||||||
if (value) {
|
if (value) {
|
||||||
try {
|
try {
|
||||||
value = JSON.parse(value);
|
value = JSON.parse(value);
|
||||||
+23
-11
@@ -2,21 +2,30 @@ import React from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { message, Button, Space, Table } from "antd";
|
import { message, Button, Space, Table } from "antd";
|
||||||
import CopyOutlined from "@ant-design/icons/CopyOutlined";
|
import CopyOutlined from "@ant-design/icons/CopyOutlined";
|
||||||
|
import type { SizeType } from "antd/es/config-provider/SizeContext";
|
||||||
|
import type { ColumnsType } from "antd/es/table";
|
||||||
|
|
||||||
import { useAccount } from "../model/account";
|
import { useAccount } from "../model/account";
|
||||||
import { useHostList } from "../model/host";
|
import { useHostList } from "../model/host";
|
||||||
import InstanceStatusTag from "./InstanceStatusTag";
|
import InstanceStatusTag from "./InstanceStatusTag";
|
||||||
import StartStopInstanceButton from "./StartStopInstanceButton";
|
import StartStopInstanceButton from "./StartStopInstanceButton";
|
||||||
|
import { InstanceDetails } from "@clusterio/lib";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
export default function InstanceList(props) {
|
type InstanceListProps = {
|
||||||
|
instances: InstanceDetails[];
|
||||||
|
size?: SizeType;
|
||||||
|
hideAssignedHost?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function InstanceList(props: InstanceListProps) {
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
let [hostList] = useHostList();
|
let [hostList] = useHostList();
|
||||||
|
|
||||||
function hostName(hostId) {
|
function hostName(hostId?: number|null) {
|
||||||
if (hostId === null) {
|
if (hostId === null ||hostId === undefined) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
let host = hostList.find(s => s.id === hostId);
|
let host = hostList.find(s => s.id === hostId);
|
||||||
@@ -26,7 +35,7 @@ export default function InstanceList(props) {
|
|||||||
return String(hostId);
|
return String(hostId);
|
||||||
}
|
}
|
||||||
|
|
||||||
function instancePublicAddress(instance) {
|
function instancePublicAddress(instance: InstanceDetails) {
|
||||||
let host = hostList.find(s => s.id === instance.assignedHost);
|
let host = hostList.find(s => s.id === instance.assignedHost);
|
||||||
if (host && host.publicAddress) {
|
if (host && host.publicAddress) {
|
||||||
if (instance.gamePort) {
|
if (instance.gamePort) {
|
||||||
@@ -37,7 +46,7 @@ export default function InstanceList(props) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
let columns = [
|
let columns: ColumnsType<InstanceDetails> = [
|
||||||
{
|
{
|
||||||
title: "Name",
|
title: "Name",
|
||||||
dataIndex: "name",
|
dataIndex: "name",
|
||||||
@@ -63,13 +72,13 @@ export default function InstanceList(props) {
|
|||||||
icon={<CopyOutlined/>}
|
icon={<CopyOutlined/>}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
navigator.clipboard.writeText(publicAddress);
|
navigator.clipboard.writeText(publicAddress??"");
|
||||||
message.success("Copied public address!");
|
message.success("Copied public address!");
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</> : "";
|
</> : "";
|
||||||
},
|
},
|
||||||
sorter: (a, b) => strcmp(hostPublicAddress(a.assignedHost), hostPublicAddress(b.assignedHost)),
|
sorter: (a, b) => strcmp(instancePublicAddress(a)||"", instancePublicAddress(b)||""),
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -78,7 +87,10 @@ export default function InstanceList(props) {
|
|||||||
render: instance => <InstanceStatusTag status={instance["status"]} />,
|
render: instance => <InstanceStatusTag status={instance["status"]} />,
|
||||||
sorter: (a, b) => strcmp(a["status"], b["status"]),
|
sorter: (a, b) => strcmp(a["status"], b["status"]),
|
||||||
},
|
},
|
||||||
...(account.hasAnyPermission("core.instance.start", "core.instance.stop") ? [{
|
];
|
||||||
|
|
||||||
|
if (account.hasAnyPermission("core.instance.start", "core.instance.stop")) {
|
||||||
|
columns.push({
|
||||||
key: "action",
|
key: "action",
|
||||||
render: instance => <StartStopInstanceButton
|
render: instance => <StartStopInstanceButton
|
||||||
buttonProps={{ size: "small" }}
|
buttonProps={{ size: "small" }}
|
||||||
@@ -87,8 +99,8 @@ export default function InstanceList(props) {
|
|||||||
responsive: ["sm"],
|
responsive: ["sm"],
|
||||||
align: "right",
|
align: "right",
|
||||||
width: 100,
|
width: 100,
|
||||||
}] : []),
|
})
|
||||||
];
|
}
|
||||||
|
|
||||||
if (props.hideAssignedHost) {
|
if (props.hideAssignedHost) {
|
||||||
columns.splice(1, 1);
|
columns.splice(1, 1);
|
||||||
+7
-3
@@ -9,12 +9,16 @@ import { notifyErrorHandler } from "../util/notify";
|
|||||||
const { Title, Paragraph } = Typography;
|
const { Title, Paragraph } = Typography;
|
||||||
|
|
||||||
|
|
||||||
export default function InstanceRcon(props) {
|
type InstanceRconProps = {
|
||||||
|
id: number;
|
||||||
|
disabled: boolean;
|
||||||
|
};
|
||||||
|
export default function InstanceRcon(props: InstanceRconProps) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [output, setOutput] = useState(null);
|
let [output, setOutput] = useState<string|null>(null);
|
||||||
let [running, setRunning] = useState(false);
|
let [running, setRunning] = useState(false);
|
||||||
|
|
||||||
async function sendCommand(command) {
|
async function sendCommand(command: string) {
|
||||||
if (!command) {
|
if (!command) {
|
||||||
setOutput(null);
|
setOutput(null);
|
||||||
return;
|
return;
|
||||||
+4
-2
@@ -13,8 +13,10 @@ export const statusColors = {
|
|||||||
deleted: "#262626",
|
deleted: "#262626",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type InstanceStatusTag = {
|
||||||
export default function InstanceStatusTag(props) {
|
status: keyof typeof statusColors;
|
||||||
|
};
|
||||||
|
export default function InstanceStatusTag(props: InstanceStatusTag) {
|
||||||
return <Tag color={statusColors[props.status]}>
|
return <Tag color={statusColors[props.status]}>
|
||||||
{props.status.replace("_", " ")}
|
{props.status.replace("_", " ")}
|
||||||
</Tag>;
|
</Tag>;
|
||||||
+19
-15
@@ -1,6 +1,7 @@
|
|||||||
import React, { useContext, useState } from "react";
|
import React, { useContext, useState } from "react";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import { Alert, Button, Descriptions, Dropdown, Menu, Modal, Space, Spin, Typography } from "antd";
|
import { Alert, Button, Descriptions, Dropdown, Menu, MenuProps, Modal, Space, Spin, Typography } from "antd";
|
||||||
|
import type { ItemType } from 'antd/es/menu/hooks/useItems';
|
||||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||||
import DownOutlined from "@ant-design/icons/DownOutlined";
|
import DownOutlined from "@ant-design/icons/DownOutlined";
|
||||||
|
|
||||||
@@ -19,14 +20,17 @@ import StartStopInstanceButton from "./StartStopInstanceButton";
|
|||||||
import LoadScenarioModal from "./LoadScenarioModal";
|
import LoadScenarioModal from "./LoadScenarioModal";
|
||||||
import SavesList from "./SavesList";
|
import SavesList from "./SavesList";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
import { useInstance } from "../model/instance";
|
import { InstanceState, useInstance } from "../model/instance";
|
||||||
import { useHost } from "../model/host";
|
import { HostState, useHost } from "../model/host";
|
||||||
import InstanceStatusTag from "./InstanceStatusTag";
|
import InstanceStatusTag from "./InstanceStatusTag";
|
||||||
|
|
||||||
const { Title } = Typography;
|
const { Title } = Typography;
|
||||||
|
|
||||||
|
type InstanceDescriptionProps = {
|
||||||
function InstanceDescription(props) {
|
host: HostState;
|
||||||
|
instance: InstanceState;
|
||||||
|
};
|
||||||
|
function InstanceDescription(props: InstanceDescriptionProps) {
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
|
|
||||||
const { host, instance } = props;
|
const { host, instance } = props;
|
||||||
@@ -45,18 +49,18 @@ function InstanceDescription(props) {
|
|||||||
hostId={instance.assignedHost}
|
hostId={instance.assignedHost}
|
||||||
buttonProps={{
|
buttonProps={{
|
||||||
size: "small",
|
size: "small",
|
||||||
style: { float: "Right" },
|
style: { float: "right" },
|
||||||
type: assigned ? "default" : "primary",
|
type: assigned ? "default" : "primary",
|
||||||
disabled: !["unknown", "unassigned", "stopped"].includes(instance.status),
|
disabled: !["unknown", "unassigned", "stopped"].includes(instance.status!),
|
||||||
}}
|
}}
|
||||||
buttonContent={assigned ? "Reassign" : "Assign"}
|
buttonContent={assigned ? "Reassign" : "Assign"}
|
||||||
/>}
|
/>}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="Status"><InstanceStatusTag status={instance.status} /></Descriptions.Item>
|
<Descriptions.Item label="Status"><InstanceStatusTag status={instance.status!} /></Descriptions.Item>
|
||||||
</Descriptions>;
|
</Descriptions>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function InstanceViewPage(props) {
|
export default function InstanceViewPage() {
|
||||||
let params = useParams();
|
let params = useParams();
|
||||||
let instanceId = Number(params.id);
|
let instanceId = Number(params.id);
|
||||||
|
|
||||||
@@ -93,7 +97,7 @@ export default function InstanceViewPage(props) {
|
|||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
|
|
||||||
let instanceButtonMenuItems = [];
|
let instanceButtonMenuItems: ItemType[] = [];
|
||||||
if (account.hasPermission("core.instance.export_data")) {
|
if (account.hasPermission("core.instance.export_data")) {
|
||||||
instanceButtonMenuItems.push({
|
instanceButtonMenuItems.push({
|
||||||
disabled: exportingData || instance.status !== "stopped",
|
disabled: exportingData || instance.status !== "stopped",
|
||||||
@@ -110,7 +114,7 @@ export default function InstanceViewPage(props) {
|
|||||||
}
|
}
|
||||||
if (account.hasPermission("core.instance.kill")) {
|
if (account.hasPermission("core.instance.kill")) {
|
||||||
instanceButtonMenuItems.push({
|
instanceButtonMenuItems.push({
|
||||||
disabled: ["unknown", "unassigned", "stopped"].includes(instance.status),
|
disabled: ["unknown", "unassigned", "stopped"].includes(instance.status!),
|
||||||
key: "kill",
|
key: "kill",
|
||||||
label: "Kill process",
|
label: "Kill process",
|
||||||
});
|
});
|
||||||
@@ -120,16 +124,16 @@ export default function InstanceViewPage(props) {
|
|||||||
instanceButtonMenuItems.push({ type: "divider" });
|
instanceButtonMenuItems.push({ type: "divider" });
|
||||||
}
|
}
|
||||||
instanceButtonMenuItems.push({
|
instanceButtonMenuItems.push({
|
||||||
disabled: !["unknown", "unassigned", "stopped"].includes(instance.status),
|
disabled: !["unknown", "unassigned", "stopped"].includes(instance.status!),
|
||||||
danger: true,
|
danger: true,
|
||||||
key: "delete",
|
key: "delete",
|
||||||
icon: <DeleteOutlined />,
|
icon: <DeleteOutlined />,
|
||||||
label: "Delete",
|
label: "Delete",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let instanceButtonsMenuProps = {
|
let instanceButtonsMenuProps: MenuProps = {
|
||||||
items: instanceButtonMenuItems,
|
items: instanceButtonMenuItems,
|
||||||
onClick: ({ key }) => {
|
onClick: ({ key }: { key:string }) => {
|
||||||
if (key === "export") {
|
if (key === "export") {
|
||||||
setExportingData(true);
|
setExportingData(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
@@ -188,7 +192,7 @@ export default function InstanceViewPage(props) {
|
|||||||
|
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={instance.name}
|
title={instance.name??""}
|
||||||
extra={instanceButtons}
|
extra={instanceButtons}
|
||||||
/>
|
/>
|
||||||
<InstanceDescription host={host} instance={instance} />
|
<InstanceDescription host={host} instance={instance} />
|
||||||
+4
-3
@@ -13,7 +13,7 @@ import { useInstanceList } from "../model/instance";
|
|||||||
import InstanceList from "./InstanceList";
|
import InstanceList from "./InstanceList";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
|
||||||
function CreateInstanceButton(props) {
|
function CreateInstanceButton() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
@@ -72,8 +72,9 @@ export default function InstancesPage() {
|
|||||||
{account.hasPermission("core.instance.start")
|
{account.hasPermission("core.instance.start")
|
||||||
&& <Button onClick={e => instanceList.forEach(instance => {
|
&& <Button onClick={e => instanceList.forEach(instance => {
|
||||||
if (instance.status === "stopped") {
|
if (instance.status === "stopped") {
|
||||||
control.send(
|
control.sendTo(
|
||||||
new lib.InstanceStartRequest(undefined), { instanceId: instance.id }
|
{ instanceId: instance.id },
|
||||||
|
new lib.InstanceStartRequest(undefined),
|
||||||
).catch(notifyErrorHandler("Error starting instance"));
|
).catch(notifyErrorHandler("Error starting instance"));
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
+10
-7
@@ -5,9 +5,12 @@ import * as lib from "@clusterio/lib";
|
|||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
import { InstanceState } from "../model/instance";
|
||||||
|
|
||||||
|
type LoadScenarioModalProps = {
|
||||||
export default function LoadScenarioModal(props) {
|
instance: InstanceState;
|
||||||
|
};
|
||||||
|
export default function LoadScenarioModal(props: LoadScenarioModalProps) {
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [loadingScenario, setLoadingScenario] = useState(false);
|
let [loadingScenario, setLoadingScenario] = useState(false);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
@@ -23,7 +26,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = lib.readMapExchangeString(values.exchangeString);
|
result = lib.readMapExchangeString(values.exchangeString);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -34,7 +37,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
if (values.mapGenSettings && values.mapGenSettings.trim()) {
|
if (values.mapGenSettings && values.mapGenSettings.trim()) {
|
||||||
try {
|
try {
|
||||||
mapGenSettings = JSON.parse(values.mapGenSettings);
|
mapGenSettings = JSON.parse(values.mapGenSettings);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "mapGenSettings", errors: [err.message] }]);
|
form.setFields([{ name: "mapGenSettings", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -43,7 +46,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
if (values.mapSettings && values.mapSettings.trim()) {
|
if (values.mapSettings && values.mapSettings.trim()) {
|
||||||
try {
|
try {
|
||||||
mapSettings = JSON.parse(values.mapGenSettings);
|
mapSettings = JSON.parse(values.mapGenSettings);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "mapSettings", errors: [err.message] }]);
|
form.setFields([{ name: "mapSettings", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -52,7 +55,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
|
|
||||||
setLoadingScenario(true);
|
setLoadingScenario(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: props.instance.id },
|
{ instanceId: props.instance.id! },
|
||||||
new lib.InstanceLoadScenarioRequest(scenario, seed, mapGenSettings, mapSettings),
|
new lib.InstanceLoadScenarioRequest(scenario, seed, mapGenSettings, mapSettings),
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
@@ -68,7 +71,7 @@ export default function LoadScenarioModal(props) {
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = lib.readMapExchangeString(exchangeString);
|
result = lib.readMapExchangeString(exchangeString);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
form.setFields([{ name: "exchangeString", errors: [err.message] }]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
+31
-12
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useContext, useRef, useState } from "react";
|
import React, { useEffect, useContext, useRef, useState, ReactElement } from "react";
|
||||||
import { Typography } from "antd";
|
import { Typography } from "antd";
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
@@ -8,18 +8,27 @@ import ControlContext from "./ControlContext";
|
|||||||
|
|
||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
|
|
||||||
|
type Parsed = {
|
||||||
|
format: string;
|
||||||
|
type: string;
|
||||||
|
level: string;
|
||||||
|
time: string;
|
||||||
|
file: string;
|
||||||
|
action: string;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
|
||||||
function formatParsedOutput(parsed, key) {
|
function formatParsedOutput(parsed: Parsed, key: number) {
|
||||||
let time = "";
|
let time: ReactElement|string = "";
|
||||||
if (parsed.format === "seconds") {
|
if (parsed.format === "seconds") {
|
||||||
time = <span className="factorio-time">{parsed.time.padStart(8)} </span>;
|
time = <span className="factorio-time">{parsed.time.padStart(8)} </span>;
|
||||||
} else if (parsed.format === "date") {
|
} else if (parsed.format === "date") {
|
||||||
time = <span className="factorio-time">{parsed.time} </span>;
|
time = <span className="factorio-time">{parsed.time} </span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
let info = "";
|
let info: ReactElement|string = "";
|
||||||
if (parsed.type === "log") {
|
if (parsed.type === "log") {
|
||||||
let level = parsed.level;
|
let level: ReactElement|string = parsed.level;
|
||||||
if (level === "Script") {
|
if (level === "Script") {
|
||||||
level = <span className="factorio-script">{level}</span>;
|
level = <span className="factorio-script">{level}</span>;
|
||||||
} else if (level === "Verbose") {
|
} else if (level === "Verbose") {
|
||||||
@@ -41,7 +50,12 @@ function formatParsedOutput(parsed, key) {
|
|||||||
return <span key={key}>{time}{info}{parsed.message}<br/></span>;
|
return <span key={key}>{time}{info}{parsed.message}<br/></span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatLog(info, key) {
|
type Info = {
|
||||||
|
level: string;
|
||||||
|
message: string;
|
||||||
|
parsed?: Parsed;
|
||||||
|
};
|
||||||
|
function formatLog(info: Info, key: number): ReactElement {
|
||||||
if (info.level === "server" && info.parsed) {
|
if (info.level === "server" && info.parsed) {
|
||||||
return formatParsedOutput(info.parsed, key);
|
return formatParsedOutput(info.parsed, key);
|
||||||
}
|
}
|
||||||
@@ -49,12 +63,18 @@ function formatLog(info, key) {
|
|||||||
return <span key={key}>[{level}] {info.message}<br/></span>;
|
return <span key={key}>[{level}] {info.message}<br/></span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LogConsole(props) {
|
type LogConsoleProps = {
|
||||||
|
all?: boolean;
|
||||||
|
controller?: boolean;
|
||||||
|
hosts?: number[];
|
||||||
|
instances?: number[];
|
||||||
|
};
|
||||||
|
export default function LogConsole(props: LogConsoleProps) {
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let anchor = useRef();
|
let anchor = useRef<any>();
|
||||||
let [pastLines, setPastLines] = useState([<span key={0}>{"Loading past entries..."}<br/></span>]);
|
let [pastLines, setPastLines] = useState([<span key={0}>{"Loading past entries..."}<br/></span>]);
|
||||||
let [lines, setLines] = useState([]);
|
let [lines, setLines] = useState<ReactElement[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let logFilter = {
|
let logFilter = {
|
||||||
@@ -79,7 +99,7 @@ export default function LogConsole(props) {
|
|||||||
400,
|
400,
|
||||||
"desc",
|
"desc",
|
||||||
)).then(result => {
|
)).then(result => {
|
||||||
setPastLines(result.log.map((info, index) => formatLog(info, -index - 1)).reverse());
|
setPastLines(result.log.map((info, index) => formatLog(info as Info, -index - 1)).reverse());
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
setPastLines([<span key={0}>{`Error loading log: ${err.message}`}<br/></span>]);
|
setPastLines([<span key={0}>{`Error loading log: ${err.message}`}<br/></span>]);
|
||||||
});
|
});
|
||||||
@@ -87,7 +107,7 @@ export default function LogConsole(props) {
|
|||||||
setPastLines([]);
|
setPastLines([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function logHandler(info) {
|
function logHandler(info: Info) {
|
||||||
setLines(currentLines => currentLines.concat(
|
setLines(currentLines => currentLines.concat(
|
||||||
[formatLog(info, currentLines.length)]
|
[formatLog(info, currentLines.length)]
|
||||||
));
|
));
|
||||||
@@ -107,4 +127,3 @@ export default function LogConsole(props) {
|
|||||||
</Paragraph>
|
</Paragraph>
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
+5
-3
@@ -7,8 +7,10 @@ import ControlContext from "./ControlContext";
|
|||||||
|
|
||||||
const { Paragraph } = Typography;
|
const { Paragraph } = Typography;
|
||||||
|
|
||||||
|
type SetTokenProps = {
|
||||||
function TokenAuth(props) {
|
setToken: (token: string) => void;
|
||||||
|
};
|
||||||
|
function TokenAuth(props: SetTokenProps) {
|
||||||
return <>
|
return <>
|
||||||
<Paragraph>If you have generated an authentication token from the controller, use that here.</Paragraph>
|
<Paragraph>If you have generated an authentication token from the controller, use that here.</Paragraph>
|
||||||
<Form
|
<Form
|
||||||
@@ -32,7 +34,7 @@ function TokenAuth(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LoginForm(props) {
|
export default function LoginForm(props: SetTokenProps) {
|
||||||
let plugins = useContext(ControlContext).plugins;
|
let plugins = useContext(ControlContext).plugins;
|
||||||
|
|
||||||
let loginForms = [];
|
let loginForms = [];
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
import React, { Fragment } from "react";
|
|
||||||
import { Descriptions, Grid, Typography } from "antd";
|
|
||||||
import ExclamationCircleOutlined from "@ant-design/icons/ExclamationCircleOutlined";
|
|
||||||
|
|
||||||
import * as lib from "@clusterio/lib";
|
|
||||||
|
|
||||||
const { useBreakpoint } = Grid;
|
|
||||||
|
|
||||||
|
|
||||||
export default function ModDetails(props) {
|
|
||||||
let screens = useBreakpoint();
|
|
||||||
const mod = props.mod;
|
|
||||||
|
|
||||||
return <Descriptions className="borderless" bordered size="small" column={{ xs: 1, sm: 1, md: 1, lg: 2 }}>
|
|
||||||
{mod.error && <Descriptions.Item label={<><ExclamationCircleOutlined/> Error</>} span={2}>
|
|
||||||
{mod.error === "missing" && "The given version of this mod is missing from the controller storage."}
|
|
||||||
{mod.error === "bad_checksum"
|
|
||||||
&& "Checksum of the mod in the controller storage does not match the checksum provided " +
|
|
||||||
"by this mod pack."
|
|
||||||
}
|
|
||||||
</Descriptions.Item>}
|
|
||||||
{props.actions && !screens.lg
|
|
||||||
&& <Descriptions.Item label="Action">{props.actions(mod)}</Descriptions.Item>
|
|
||||||
}
|
|
||||||
{mod.title && <Descriptions.Item label="Title">{mod.title}</Descriptions.Item>}
|
|
||||||
{mod.version && <Descriptions.Item label="Version" span={mod.title ? 1 : 2}>{mod.version}</Descriptions.Item>}
|
|
||||||
{mod.description && <Descriptions.Item label="Description" span={2}>{mod.description}</Descriptions.Item> }
|
|
||||||
{mod.author && <Descriptions.Item label="Author" span={2}>{mod.author}</Descriptions.Item>}
|
|
||||||
<Descriptions.Item label="Mod Portal" span={2}>
|
|
||||||
<Typography.Link href={`https://mods.factorio.com/mod/${mod.name}`}>
|
|
||||||
{`https://mods.factorio.com/mod/${mod.name}`}
|
|
||||||
</Typography.Link>
|
|
||||||
</Descriptions.Item>
|
|
||||||
{mod.contact && <Descriptions.Item label="Contact" span={2}>{mod.contact}</Descriptions.Item>}
|
|
||||||
{mod.homepage && <Descriptions.Item label="Homepage" span={2}>{mod.homepage}</Descriptions.Item>}
|
|
||||||
<Descriptions.Item label="Internal Name" span={mod.factorioVersion ? 1 : 2}>{mod.name}</Descriptions.Item>
|
|
||||||
{mod.factorioVersion
|
|
||||||
&& <Descriptions.Item label="Factorio Version">{mod.factorioVersion}</Descriptions.Item>
|
|
||||||
}
|
|
||||||
{mod.filename && <Descriptions.Item label="Filename">{mod.filename}</Descriptions.Item>}
|
|
||||||
{mod.size !== undefined
|
|
||||||
&& <Descriptions.Item label="Size">{lib.formatBytes(mod.size)}</Descriptions.Item>
|
|
||||||
}
|
|
||||||
{mod.sha1 && <Descriptions.Item label="SHA1" span={2}>{mod.sha1}</Descriptions.Item>}
|
|
||||||
{mod.dependencies && mod.dependencies.length
|
|
||||||
&& <Descriptions.Item label="Dependencies" span={2}>
|
|
||||||
{mod.dependencies
|
|
||||||
.filter(e => !e.startsWith("(?)"))
|
|
||||||
.map((e, i) => <Fragment key={i}>{e}<br/></Fragment>)
|
|
||||||
}
|
|
||||||
</Descriptions.Item>
|
|
||||||
}
|
|
||||||
</Descriptions>;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import React, { Fragment } from "react";
|
||||||
|
import { Descriptions, Grid, Typography } from "antd";
|
||||||
|
import ExclamationCircleOutlined from "@ant-design/icons/ExclamationCircleOutlined";
|
||||||
|
|
||||||
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
const { useBreakpoint } = Grid;
|
||||||
|
|
||||||
|
type ModDetailsProps = {
|
||||||
|
mod: lib.ModInfo|lib.ModRecord;
|
||||||
|
actions: (mod: lib.ModInfo|lib.ModRecord) => React.JSX.Element;
|
||||||
|
};
|
||||||
|
export default function ModDetails(props: ModDetailsProps) {
|
||||||
|
let screens = useBreakpoint();
|
||||||
|
const mod = props.mod;
|
||||||
|
|
||||||
|
return <Descriptions className="borderless" bordered size="small" column={{ xs: 1, sm: 1, md: 1, lg: 2 }}>
|
||||||
|
{!(mod instanceof lib.ModInfo) && mod.error && <Descriptions.Item label={<><ExclamationCircleOutlined/> Error</>} span={2}>
|
||||||
|
{mod.error === "missing" && "The given version of this mod is missing from the controller storage."}
|
||||||
|
{mod.error === "bad_checksum"
|
||||||
|
&& "Checksum of the mod in the controller storage does not match the checksum provided " +
|
||||||
|
"by this mod pack."
|
||||||
|
}
|
||||||
|
</Descriptions.Item>}
|
||||||
|
{props.actions && !screens.lg
|
||||||
|
&& <Descriptions.Item label="Action">{props.actions(mod)}</Descriptions.Item>
|
||||||
|
}
|
||||||
|
|
||||||
|
{ (mod instanceof lib.ModInfo) && <>
|
||||||
|
{mod.title && <Descriptions.Item label="Title">{mod.title}</Descriptions.Item>}
|
||||||
|
{mod.version && <Descriptions.Item label="Version" span={mod.title ? 1 : 2}>{mod.version}</Descriptions.Item>}
|
||||||
|
{mod.description && <Descriptions.Item label="Description" span={2}>{mod.description}</Descriptions.Item> }
|
||||||
|
{mod.author && <Descriptions.Item label="Author" span={2}>{mod.author}</Descriptions.Item>}
|
||||||
|
</>}
|
||||||
|
|
||||||
|
<Descriptions.Item label="Mod Portal" span={2}>
|
||||||
|
<Typography.Link href={`https://mods.factorio.com/mod/${mod.name}`}>
|
||||||
|
{`https://mods.factorio.com/mod/${mod.name}`}
|
||||||
|
</Typography.Link>
|
||||||
|
</Descriptions.Item>
|
||||||
|
|
||||||
|
{ (mod instanceof lib.ModInfo) && <>
|
||||||
|
{mod.contact && <Descriptions.Item label="Contact" span={2}>{mod.contact}</Descriptions.Item>}
|
||||||
|
{mod.homepage && <Descriptions.Item label="Homepage" span={2}>{mod.homepage}</Descriptions.Item>}
|
||||||
|
<Descriptions.Item label="Internal Name" span={mod.factorioVersion ? 1 : 2}>{mod.name}</Descriptions.Item>
|
||||||
|
{mod.factorioVersion
|
||||||
|
&& <Descriptions.Item label="Factorio Version">{mod.factorioVersion}</Descriptions.Item>
|
||||||
|
}
|
||||||
|
{mod.filename && <Descriptions.Item label="Filename">{mod.filename}</Descriptions.Item>}
|
||||||
|
{mod.size !== undefined
|
||||||
|
&& <Descriptions.Item label="Size">{lib.formatBytes(mod.size)}</Descriptions.Item>
|
||||||
|
}
|
||||||
|
{mod.sha1 && <Descriptions.Item label="SHA1" span={2}>{mod.sha1}</Descriptions.Item>}
|
||||||
|
{mod.dependencies && mod.dependencies.length
|
||||||
|
&& <Descriptions.Item label="Dependencies" span={2}>
|
||||||
|
{mod.dependencies
|
||||||
|
.filter(e => !e.startsWith("(?)"))
|
||||||
|
.map((e, i) => <Fragment key={i}>{e}<br/></Fragment>)
|
||||||
|
}
|
||||||
|
</Descriptions.Item>
|
||||||
|
}
|
||||||
|
</>}
|
||||||
|
</Descriptions>;
|
||||||
|
}
|
||||||
+170
-88
@@ -3,7 +3,11 @@ import { useNavigate, useParams } from "react-router-dom";
|
|||||||
import {
|
import {
|
||||||
Button, Card, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination,
|
Button, Card, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination,
|
||||||
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip,
|
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip,
|
||||||
|
TablePaginationConfig,
|
||||||
} from "antd";
|
} from "antd";
|
||||||
|
import { FieldData } from "rc-field-form/lib/interface";
|
||||||
|
|
||||||
|
import type { SorterResult, FilterValue, TableCurrentDataSource } from "antd/es/table/interface";
|
||||||
import ExportOutlined from "@ant-design/icons/ExportOutlined";
|
import ExportOutlined from "@ant-design/icons/ExportOutlined";
|
||||||
import FileUnknownOutlined from "@ant-design/icons/FileUnknownOutlined";
|
import FileUnknownOutlined from "@ant-design/icons/FileUnknownOutlined";
|
||||||
import FileExclamationOutlined from "@ant-design/icons/FileExclamationOutlined";
|
import FileExclamationOutlined from "@ant-design/icons/FileExclamationOutlined";
|
||||||
@@ -25,18 +29,48 @@ import ModDetails from "./ModDetails";
|
|||||||
|
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
const { Paragraph, Text } = Typography;
|
const { Paragraph, Text } = Typography;
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
function SearchModsTable(props) {
|
|
||||||
|
type ModChange =
|
||||||
|
{
|
||||||
|
type: "name" | "description" | "factorioVersion",
|
||||||
|
name?: never,
|
||||||
|
scope?: never,
|
||||||
|
value: string,
|
||||||
|
} | {
|
||||||
|
type: "settings.set" | "settings.delete",
|
||||||
|
name: string,
|
||||||
|
scope: "startup" | "runtime-global" | "runtime-per-user",
|
||||||
|
value: lib.ModSetting,
|
||||||
|
} | {
|
||||||
|
type: "mods.set" | "mods.delete",
|
||||||
|
name: string,
|
||||||
|
scope?: never,
|
||||||
|
value: lib.ModRecord | lib.ModInfo,
|
||||||
|
}
|
||||||
|
;
|
||||||
|
|
||||||
|
type ModResult = {
|
||||||
|
name: string;
|
||||||
|
versions: lib.ModInfo[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type SearchModsTableProps = {
|
||||||
|
modPack: lib.ModPack;
|
||||||
|
changes: ModChange[];
|
||||||
|
onChange: (change: ModChange) => void;
|
||||||
|
};
|
||||||
|
function SearchModsTable(props: SearchModsTableProps) {
|
||||||
const control = useContext(ControlContext);
|
const control = useContext(ControlContext);
|
||||||
const [searchText, setSearchText] = useState("");
|
const [searchText, setSearchText] = useState<string>("");
|
||||||
const [modResultSort, setModResultSort] = useState("title");
|
const [modResultSort, setModResultSort] = useState<string|undefined>("title");
|
||||||
const [modResultSortOrder, setModResultSortOrder] = useState("asc");
|
const [modResultSortOrder, setModResultSortOrder] = useState<string|undefined>("asc");
|
||||||
const [modResults, setModResults] = useState([]);
|
const [modResults, setModResults] = useState<ModResult[]>([]);
|
||||||
const [modResultPage, setModResultPage] = useState(1);
|
const [modResultPage, setModResultPage] = useState<number>(1);
|
||||||
const [modResultPageSize, setModResultPageSize] = useState(10);
|
const [modResultPageSize, setModResultPageSize] = useState<number>(10);
|
||||||
const [modResultCount, setModResultCount] = useState(2);
|
const [modResultCount, setModResultCount] = useState<number>(2);
|
||||||
const [modResultSelectedVersion, setModResultSelectedVersion] = useState(new Map());
|
const [modResultSelectedVersion, setModResultSelectedVersion] = useState<Map<string,number>>(new Map());
|
||||||
|
|
||||||
const factorioVersion = props.modPack.factorioVersion.split(".").slice(0, 2).join(".");
|
const factorioVersion = props.modPack.factorioVersion.split(".").slice(0, 2).join(".");
|
||||||
|
|
||||||
@@ -57,7 +91,7 @@ function SearchModsTable(props) {
|
|||||||
// of || 0 on modResultSelectedVersion.get() calls. Remove when updating React.
|
// of || 0 on modResultSelectedVersion.get() calls. Remove when updating React.
|
||||||
setModResults(response.results);
|
setModResults(response.results);
|
||||||
setModResultSelectedVersion(new Map(response.results.map(({ name, versions }) => [name, 0])));
|
setModResultSelectedVersion(new Map(response.results.map(({ name, versions }) => [name, 0])));
|
||||||
setModResultCount(response.result_count);
|
setModResultCount(response.resultCount);
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -65,20 +99,29 @@ function SearchModsTable(props) {
|
|||||||
};
|
};
|
||||||
}, [searchText, factorioVersion, modResultPageSize, modResultPage, modResultSort, modResultSortOrder]);
|
}, [searchText, factorioVersion, modResultPageSize, modResultPage, modResultSort, modResultSortOrder]);
|
||||||
|
|
||||||
function modResultPageChanged(page, pageSize) {
|
function modResultPageChanged(page: number, pageSize: number) {
|
||||||
setModResultPage(page);
|
setModResultPage(page);
|
||||||
setModResultPageSize(pageSize);
|
setModResultPageSize(pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
function modResultsTableChanged(pagination, filters, sorters, extra) {
|
function modResultsTableChanged(
|
||||||
|
pagination: TablePaginationConfig,
|
||||||
|
filters: Record<string, FilterValue | null>,
|
||||||
|
sorter: SorterResult<ModResult>|SorterResult<ModResult>[],
|
||||||
|
extra: TableCurrentDataSource<ModResult>,
|
||||||
|
) {
|
||||||
if (extra.action === "sort") {
|
if (extra.action === "sort") {
|
||||||
if (sorters.order) {
|
if (sorter instanceof Array) {
|
||||||
|
sorter = sorter[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sorter.order) {
|
||||||
const mapping = {
|
const mapping = {
|
||||||
ascend: "asc",
|
ascend: "asc",
|
||||||
descend: "desc",
|
descend: "desc",
|
||||||
};
|
};
|
||||||
setModResultSort(sorters.columnKey);
|
setModResultSort(String(sorter.columnKey));
|
||||||
setModResultSortOrder(mapping[sorters.order]);
|
setModResultSortOrder(mapping[sorter.order]);
|
||||||
} else {
|
} else {
|
||||||
setModResultSort(undefined);
|
setModResultSort(undefined);
|
||||||
setModResultSortOrder(undefined);
|
setModResultSortOrder(undefined);
|
||||||
@@ -86,9 +129,9 @@ function SearchModsTable(props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function actions(mod) {
|
function actions(mod: lib.ModInfo|lib.ModRecord) {
|
||||||
return <Space>
|
return <Space>
|
||||||
{(!props.modPack.mods.has(mod.name) || props.modPack.mods.get(mod.name).version !== mod.version)
|
{(!props.modPack.mods.has(mod.name) || props.modPack.mods.get(mod.name)?.version !== mod.version)
|
||||||
&& <Typography.Link
|
&& <Typography.Link
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
props.onChange({
|
props.onChange({
|
||||||
@@ -106,7 +149,7 @@ function SearchModsTable(props) {
|
|||||||
props.onChange({
|
props.onChange({
|
||||||
type: "mods.delete",
|
type: "mods.delete",
|
||||||
name: mod.name,
|
name: mod.name,
|
||||||
value: { name: mod.name, version: mod.version, sha1: mod.sha1 },
|
value: { name: mod.name, enabled: false, version: mod.version, sha1: mod.sha1 },
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
>remove</Typography.Link>
|
>remove</Typography.Link>
|
||||||
@@ -142,14 +185,14 @@ function SearchModsTable(props) {
|
|||||||
{
|
{
|
||||||
title: "Title",
|
title: "Title",
|
||||||
key: "title",
|
key: "title",
|
||||||
render: results => results.versions[0].title,
|
render: (result:ModResult) => result.versions[0].title,
|
||||||
defaultSortOrder: "ascend",
|
defaultSortOrder: "ascend",
|
||||||
sorter: true,
|
sorter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Author",
|
title: "Author",
|
||||||
key: "author",
|
key: "author",
|
||||||
render: results => results.versions[0].author,
|
render: (result:ModResult) => result.versions[0].author,
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
sorter: true,
|
sorter: true,
|
||||||
},
|
},
|
||||||
@@ -157,7 +200,7 @@ function SearchModsTable(props) {
|
|||||||
title: "Version",
|
title: "Version",
|
||||||
key: "version",
|
key: "version",
|
||||||
align: "right",
|
align: "right",
|
||||||
render: result => <Select
|
render: (result:ModResult) => <Select
|
||||||
size="small"
|
size="small"
|
||||||
bordered={false}
|
bordered={false}
|
||||||
value={modResultSelectedVersion.get(result.name) || 0}
|
value={modResultSelectedVersion.get(result.name) || 0}
|
||||||
@@ -173,7 +216,7 @@ function SearchModsTable(props) {
|
|||||||
title: "Action",
|
title: "Action",
|
||||||
key: "action",
|
key: "action",
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
render: result => actions(result.versions[modResultSelectedVersion.get(result.name) || 0]),
|
render: (result:ModResult) => actions(result.versions[modResultSelectedVersion.get(result.name) || 0]),
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
expandable={{
|
expandable={{
|
||||||
@@ -192,34 +235,44 @@ function SearchModsTable(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ModsTable(props) {
|
type ModsTableProps = {
|
||||||
|
modPack: lib.ModPack;
|
||||||
|
changes: ModChange[];
|
||||||
|
onChange: (change: ModChange) => void;
|
||||||
|
onRevert: (change: ModChange) => void;
|
||||||
|
};
|
||||||
|
function ModsTable(props: ModsTableProps) {
|
||||||
const [showAddMods, setShowAddMods] = useState(false);
|
const [showAddMods, setShowAddMods] = useState(false);
|
||||||
const [modList] = useModList();
|
const [modList] = useModList();
|
||||||
|
|
||||||
const deletedMods = new Map();
|
const deletedMods: Map<string, lib.ModRecord|lib.ModInfo> = new Map();
|
||||||
const changedMods = new Map();
|
const changedMods: Map<string, lib.ModRecord|lib.ModInfo> = new Map();
|
||||||
for (let change of props.changes) {
|
for (let change of props.changes) {
|
||||||
if (props.modPack.mods.has(change.name)) {
|
if (change.name) {
|
||||||
if (change.type === "mods.set") {
|
if (props.modPack.mods.has(change.name)) {
|
||||||
changedMods.set(change.name, change.value);
|
if (change.type === "mods.set") {
|
||||||
|
changedMods.set(change.name, change.value);
|
||||||
|
}
|
||||||
|
} else if (change.type === "mods.delete") {
|
||||||
|
deletedMods.set(change.name, change.value);
|
||||||
}
|
}
|
||||||
} else if (change.type === "mods.delete") {
|
|
||||||
deletedMods.set(change.name, change.value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const modListMap = new Map(modList.map(mod => [`${mod.name}_${mod.version}`, mod]));
|
const modListMap = new Map(modList.map(mod => [`${mod.name}_${mod.version}`, mod]));
|
||||||
const mods = [...props.modPack.mods.values(), ...deletedMods.values()].map(
|
const mods = [...props.modPack.mods.values(), ...deletedMods.values()].map(
|
||||||
mod => {
|
(mod: lib.ModRecord|lib.ModInfo): lib.ModInfo|lib.ModRecord => {
|
||||||
const candidate = modListMap.get(`${mod.name}_${mod.version}`);
|
const candidate = modListMap.get(`${mod.name}_${mod.version}`);
|
||||||
if (!candidate) {
|
if (!candidate) {
|
||||||
return {
|
return {
|
||||||
...mod,
|
...mod,
|
||||||
|
enabled: (mod as any).enabled ?? false,
|
||||||
error: "missing",
|
error: "missing",
|
||||||
};
|
};
|
||||||
} else if (mod.sha1 && candidate.sha1 !== mod.sha1) {
|
} else if (mod.sha1 && candidate.sha1 !== mod.sha1) {
|
||||||
return {
|
return {
|
||||||
...mod,
|
...mod,
|
||||||
|
enabled: (mod as any).enabled ?? false,
|
||||||
error: "bad_checksum",
|
error: "bad_checksum",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -227,7 +280,7 @@ function ModsTable(props) {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
function actions(mod) {
|
function actions(mod: lib.ModRecord|lib.ModInfo) {
|
||||||
return <Space>
|
return <Space>
|
||||||
{!deletedMods.has(mod.name) && <Typography.Link
|
{!deletedMods.has(mod.name) && <Typography.Link
|
||||||
type="danger"
|
type="danger"
|
||||||
@@ -241,7 +294,7 @@ function ModsTable(props) {
|
|||||||
>remove</Typography.Link>}
|
>remove</Typography.Link>}
|
||||||
{(deletedMods.has(mod.name) || changedMods.has(mod.name)) && <Typography.Link
|
{(deletedMods.has(mod.name) || changedMods.has(mod.name)) && <Typography.Link
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
props.onRevert({
|
props.onRevert && props.onRevert({
|
||||||
type: deletedMods.has(mod.name) ? "mods.delete" : "mods.set",
|
type: deletedMods.has(mod.name) ? "mods.delete" : "mods.set",
|
||||||
name: mod.name,
|
name: mod.name,
|
||||||
value: mod,
|
value: mod,
|
||||||
@@ -275,16 +328,16 @@ function ModsTable(props) {
|
|||||||
return { disabled: deletedMods.has(mod.name) };
|
return { disabled: deletedMods.has(mod.name) };
|
||||||
},
|
},
|
||||||
onChange(selectedRowKeys, selectedRows) {
|
onChange(selectedRowKeys, selectedRows) {
|
||||||
function setEnabled(modNames, enabled) {
|
function setEnabled(modNames: string[], enabled: boolean) {
|
||||||
for (let name of modNames) {
|
for (let name of modNames) {
|
||||||
props.onChange({
|
props.onChange({
|
||||||
type: "mods.set",
|
type: "mods.set",
|
||||||
name,
|
name,
|
||||||
value: { ...props.modPack.mods.get(name), enabled },
|
value: { ...props.modPack.mods.get(name)!, enabled },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const added = selectedRowKeys.filter(key => !props.modPack.mods.get(key).enabled);
|
const added = selectedRowKeys.filter(key => !props.modPack.mods.get(key as string)?.enabled) as string[];
|
||||||
const removed = [...props.modPack.mods.values()].filter(
|
const removed = [...props.modPack.mods.values()].filter(
|
||||||
mod => mod.enabled && selectedRowKeys.indexOf(mod.name) === -1
|
mod => mod.enabled && selectedRowKeys.indexOf(mod.name) === -1
|
||||||
).map(mod => mod.name);
|
).map(mod => mod.name);
|
||||||
@@ -341,16 +394,18 @@ function ModsTable(props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Returns true if a change record with the given fields exist
|
// Returns true if a change record with the given fields exist
|
||||||
function hasChange(changes, field) {
|
function hasChange(changes: ModChange[], field:Partial<ModChange>) {
|
||||||
return changes.some(change => Object.entries(field).every(([key, value]) => change[key] === value));
|
return changes
|
||||||
|
.some(change => Object.entries(field)
|
||||||
|
.every(([key, value]) => (change as any)[key] === value));
|
||||||
}
|
}
|
||||||
|
|
||||||
// picks out the value property from settings.
|
// picks out the value property from settings.
|
||||||
function pickValue(map) {
|
function pickValue(map: Map<string, lib.ModSetting>): [string, string|number|boolean][] {
|
||||||
return [...map].map(([name, value]) => [name, value.value]);
|
return [...map].map(([name, value]) => [name, value.value]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupToMap(array, fn) {
|
function groupToMap(array: any[], fn: (...args:any) => any) {
|
||||||
const map = new Map();
|
const map = new Map();
|
||||||
for (let index = 0; index < array.length; index++) {
|
for (let index = 0; index < array.length; index++) {
|
||||||
let key = fn(array[index], index, array);
|
let key = fn(array[index], index, array);
|
||||||
@@ -362,7 +417,15 @@ function groupToMap(array, fn) {
|
|||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SettingsTableField = memo((props) => {
|
type SettingsTableFieldProps = {
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
scope: string;
|
||||||
|
allowedValues: any;
|
||||||
|
locale: Map<string, any>;
|
||||||
|
changed: boolean;
|
||||||
|
}
|
||||||
|
const SettingsTableField = memo((props: SettingsTableFieldProps) => {
|
||||||
const name = props.name;
|
const name = props.name;
|
||||||
const isBoolean = props.type === "bool-setting";
|
const isBoolean = props.type === "bool-setting";
|
||||||
const isNumber = ["int-setting", "double-setting"].includes(props.type);
|
const isNumber = ["int-setting", "double-setting"].includes(props.type);
|
||||||
@@ -388,20 +451,29 @@ const SettingsTableField = memo((props) => {
|
|||||||
wrapperCol={{ span: 16 }}
|
wrapperCol={{ span: 16 }}
|
||||||
valuePropName={isBoolean ? "checked" : "value"}
|
valuePropName={isBoolean ? "checked" : "value"}
|
||||||
rules={[...isNumber ? [{
|
rules={[...isNumber ? [{
|
||||||
validator(rule, value) {
|
validator(rule: any, value: any) {
|
||||||
if (Number.isNaN(Number(value))) {
|
if (Number.isNaN(Number(value))) {
|
||||||
return Promise.reject(new Error("Must be a number"));
|
return Promise.reject(new Error("Must be a number"));
|
||||||
}
|
}
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
},
|
},
|
||||||
}] : []]}
|
}] : []]}
|
||||||
className={ props.changed && "changed" }
|
className={ props.changed && "changed" || "" }
|
||||||
>
|
>
|
||||||
{input}
|
{input}
|
||||||
</Form.Item>;
|
</Form.Item>;
|
||||||
});
|
});
|
||||||
|
|
||||||
function SettingsTable(props) {
|
|
||||||
|
type SettingsTableProps = {
|
||||||
|
modPack: lib.ModPack;
|
||||||
|
prototypes: any;
|
||||||
|
locale: any;
|
||||||
|
changes: ModChange[];
|
||||||
|
onChange: (change: ModChange) => void;
|
||||||
|
onRevert: (change: ModChange) => void;
|
||||||
|
};
|
||||||
|
function SettingsTable(props: SettingsTableProps) {
|
||||||
const [modList] = useModList();
|
const [modList] = useModList();
|
||||||
const modsInPack = new Set([...props.modPack.mods.values()].map(mod => `${mod.name}_${mod.version}`));
|
const modsInPack = new Set([...props.modPack.mods.values()].map(mod => `${mod.name}_${mod.version}`));
|
||||||
const modTitles = new Map(modList
|
const modTitles = new Map(modList
|
||||||
@@ -412,10 +484,13 @@ function SettingsTable(props) {
|
|||||||
const types = ["bool-setting", "int-setting", "double-setting", "string-setting"];
|
const types = ["bool-setting", "int-setting", "double-setting", "string-setting"];
|
||||||
let prototypes = Object.entries(props.prototypes)
|
let prototypes = Object.entries(props.prototypes)
|
||||||
.filter(([type, _]) => types.includes(type))
|
.filter(([type, _]) => types.includes(type))
|
||||||
.flatMap(([_, settingPrototypes]) => Object.values(settingPrototypes))
|
.flatMap<any>(([_, settingPrototypes]: [string, any]) => Object.values(settingPrototypes))
|
||||||
;
|
;
|
||||||
|
|
||||||
function controls(scope, storedFields) {
|
function controls(
|
||||||
|
scope: "startup"|"runtime-global"|"runtime-per-user",
|
||||||
|
storedFields: [string, string|number|boolean][]
|
||||||
|
) {
|
||||||
let fields = new Map(prototypes
|
let fields = new Map(prototypes
|
||||||
.filter(p => p.setting_type === scope)
|
.filter(p => p.setting_type === scope)
|
||||||
.sort((a, b) => strcmp(a.mod, b.mod) || strcmp(a.order || "", b.order || "") || strcmp(a.name, b.name))
|
.sort((a, b) => strcmp(a.mod, b.mod) || strcmp(a.order || "", b.order || "") || strcmp(a.name, b.name))
|
||||||
@@ -473,10 +548,10 @@ function SettingsTable(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function CopyButton(props) {
|
function CopyButton(props: { content: string }) {
|
||||||
let clipboard = useClipboard();
|
let clipboard = useClipboard();
|
||||||
let [copiedVisible, setCopiedVisible] = useState(false);
|
let [copiedVisible, setCopiedVisible] = useState<boolean|undefined>(false);
|
||||||
let copiedTimeout = useRef();
|
let copiedTimeout = useRef<ReturnType<typeof setTimeout>|undefined>();
|
||||||
|
|
||||||
useEffect(() => () => {
|
useEffect(() => () => {
|
||||||
clearTimeout(copiedTimeout.current);
|
clearTimeout(copiedTimeout.current);
|
||||||
@@ -493,7 +568,7 @@ function CopyButton(props) {
|
|||||||
copiedTimeout.current = setTimeout(() => {
|
copiedTimeout.current = setTimeout(() => {
|
||||||
setCopiedVisible(false);
|
setCopiedVisible(false);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
} catch (err) {
|
} catch (err: any) {
|
||||||
logger.error(`Writing to clipboard failed:\n${err.stack}`);
|
logger.error(`Writing to clipboard failed:\n${err.stack}`);
|
||||||
notify("Unable to copy to clipboard", "error", "Use ordinary select and copy instead.");
|
notify("Unable to copy to clipboard", "error", "Use ordinary select and copy instead.");
|
||||||
}
|
}
|
||||||
@@ -501,13 +576,13 @@ function CopyButton(props) {
|
|||||||
</Tooltip>;
|
</Tooltip>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ExportButton(props) {
|
function ExportButton(props: { modPack: lib.ModPack }) {
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState<boolean>(false);
|
||||||
function close() {
|
function close() {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
let exportString;
|
let exportString = "";
|
||||||
if (open) { exportString = props.modPack.toModPackString(); }
|
if (open) { exportString = props.modPack.toModPackString(); }
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
@@ -530,10 +605,10 @@ function ExportButton(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function useExportedAsset(modPack, asset) {
|
function useExportedAsset(modPack: lib.ModPack, asset: "settings"|"locale"): Map<any, any> | any {
|
||||||
let [assetData, setAssetData] = useState(asset === "locale" ? new Map() : {});
|
let [assetData, setAssetData] = useState<Map<any, any>|any>(asset === "locale" ? new Map() : {});
|
||||||
let assetFilename;
|
let assetFilename: string | undefined;
|
||||||
if (modPack instanceof lib.ModPack && modPack.exportManifest && modPack.exportManifest.assets[asset]) {
|
if (modPack instanceof lib.ModPack && modPack.exportManifest?.assets[asset]) {
|
||||||
assetFilename = modPack.exportManifest.assets[asset];
|
assetFilename = modPack.exportManifest.assets[asset];
|
||||||
}
|
}
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -542,7 +617,7 @@ function useExportedAsset(modPack, asset) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = await fetch(`${staticRoot}static/${assetFilename}`);
|
let response = await fetch(`${window.staticRoot}static/${assetFilename}`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
let data = await response.json();
|
let data = await response.json();
|
||||||
setAssetData(asset === "locale" ? new Map(data) : data);
|
setAssetData(asset === "locale" ? new Map(data) : data);
|
||||||
@@ -557,7 +632,7 @@ function useExportedAsset(modPack, asset) {
|
|||||||
return assetData;
|
return assetData;
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyModPackChanges(modPack, changes) {
|
function applyModPackChanges(modPack: lib.ModPack, changes: ModChange[]) {
|
||||||
let modifiedModPack = modPack.shallowClone();
|
let modifiedModPack = modPack.shallowClone();
|
||||||
for (let change of changes) {
|
for (let change of changes) {
|
||||||
// Only modify fields that change to reduce re-renders
|
// Only modify fields that change to reduce re-renders
|
||||||
@@ -566,6 +641,7 @@ function applyModPackChanges(modPack, changes) {
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
["settings.set", "settings.delete"].includes(change.type)
|
["settings.set", "settings.delete"].includes(change.type)
|
||||||
|
&& change.scope
|
||||||
&& modifiedModPack.settings[change.scope] === modPack.settings[change.scope]
|
&& modifiedModPack.settings[change.scope] === modPack.settings[change.scope]
|
||||||
) {
|
) {
|
||||||
if (modifiedModPack.settings === modPack.settings) {
|
if (modifiedModPack.settings === modPack.settings) {
|
||||||
@@ -581,13 +657,19 @@ function applyModPackChanges(modPack, changes) {
|
|||||||
} else if (change.type === "factorioVersion") {
|
} else if (change.type === "factorioVersion") {
|
||||||
modifiedModPack.factorioVersion = change.value;
|
modifiedModPack.factorioVersion = change.value;
|
||||||
} else if (change.type === "mods.set") {
|
} else if (change.type === "mods.set") {
|
||||||
modifiedModPack.mods.set(change.name, change.value);
|
if (change.name) {
|
||||||
|
modifiedModPack.mods.set(change.name, change.value as lib.ModRecord);
|
||||||
|
}
|
||||||
} else if (change.type === "mods.delete") {
|
} else if (change.type === "mods.delete") {
|
||||||
modifiedModPack.mods.delete(change.name);
|
modifiedModPack.mods.delete(change.name!);
|
||||||
} else if (change.type === "settings.set") {
|
} else if (change.type === "settings.set") {
|
||||||
modifiedModPack.settings[change.scope].set(change.name, change.value);
|
if (change.scope && change.name) {
|
||||||
|
modifiedModPack.settings[change.scope].set(change.name, change.value);
|
||||||
|
}
|
||||||
} else if (change.type === "settings.delete") {
|
} else if (change.type === "settings.delete") {
|
||||||
modifiedModPack.settings[change.scope].delete(change.name);
|
if (change.scope && change.name) {
|
||||||
|
modifiedModPack.settings[change.scope].delete(change.name);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`Unknown change type ${change.type}`);
|
throw new Error(`Unknown change type ${change.type}`);
|
||||||
}
|
}
|
||||||
@@ -603,13 +685,13 @@ export default function ModPackViewPage() {
|
|||||||
let modPackId = Number(params.id);
|
let modPackId = Number(params.id);
|
||||||
|
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
let [modPack] = useModPack(modPackId);
|
let [modPack] = useModPack(modPackId) as lib.ModPack[];
|
||||||
let prototypes = useExportedAsset(modPack, "settings");
|
let prototypes: any = useExportedAsset(modPack, "settings");
|
||||||
let locale = useExportedAsset(modPack, "locale");
|
let locale: Map<any, any> = useExportedAsset(modPack, "locale");
|
||||||
let [changes, setChanges] = useState([]);
|
let [changes, setChanges] = useState<ModChange[]>([]);
|
||||||
let syncTimeout = useRef();
|
let syncTimeout = useRef<ReturnType<typeof setTimeout>|undefined>();
|
||||||
|
|
||||||
let modifiedModPack;
|
let modifiedModPack: any;
|
||||||
if (!(modPack instanceof lib.ModPack)) {
|
if (!(modPack instanceof lib.ModPack)) {
|
||||||
// Loading or invalid id
|
// Loading or invalid id
|
||||||
modifiedModPack = modPack;
|
modifiedModPack = modPack;
|
||||||
@@ -620,7 +702,7 @@ export default function ModPackViewPage() {
|
|||||||
|
|
||||||
useEffect(() => () => { clearTimeout(syncTimeout.current); });
|
useEffect(() => () => { clearTimeout(syncTimeout.current); });
|
||||||
|
|
||||||
const pushChange = useCallback((change) => {
|
const pushChange = useCallback((change: ModChange) => {
|
||||||
setChanges(oldChanges => {
|
setChanges(oldChanges => {
|
||||||
const newChanges = [...oldChanges];
|
const newChanges = [...oldChanges];
|
||||||
if (
|
if (
|
||||||
@@ -637,7 +719,7 @@ export default function ModPackViewPage() {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const revertChange = useCallback((change) => {
|
const revertChange = useCallback((change: ModChange) => {
|
||||||
setChanges(oldChanges => {
|
setChanges(oldChanges => {
|
||||||
const newChanges = [...oldChanges];
|
const newChanges = [...oldChanges];
|
||||||
const index = newChanges.findLastIndex(reference => (
|
const index = newChanges.findLastIndex(reference => (
|
||||||
@@ -652,20 +734,19 @@ export default function ModPackViewPage() {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
function syncPack(fields) {
|
function syncPack(fields: FieldData[]) {
|
||||||
for (let field of fields) {
|
for (let field of fields) {
|
||||||
if (!field.touched || field.validating || field.errors.length) {
|
if (!field.touched || field.validating || (field.errors?.length??false)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (["name", "description", "factorioVersion"].includes(field.name[0])) {
|
if (["name", "description", "factorioVersion"].includes(field.name[0])) {
|
||||||
if (modifiedModPack[field.name[0]] !== field.value) {
|
if (modifiedModPack[field.name[0]] !== field.value) {
|
||||||
pushChange({ type: field.name[0], value: field.value });
|
pushChange({ type: field.name[0], value: field.value });
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (["startup", "runtime-global", "runtime-per-user"].includes(field.name[0])) {
|
} else if (["startup", "runtime-global", "runtime-per-user"].includes(field.name[0])) {
|
||||||
let [scope, settingName] = field.name;
|
let [scope, settingName]: ["startup"|"runtime-global"|"runtime-per-user", string] = field.name;
|
||||||
let value = field.value;
|
let value = field.value;
|
||||||
if (typeof modPack.settings[scope].get(settingName).value === "number") {
|
if (typeof modPack.settings[scope].get(settingName)?.value === "number") {
|
||||||
value = Number(value);
|
value = Number(value);
|
||||||
if (Number.isNaN(value)) {
|
if (Number.isNaN(value)) {
|
||||||
continue;
|
continue;
|
||||||
@@ -678,10 +759,10 @@ export default function ModPackViewPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let nav = [{ name: "Mods", path: "/mods" }, { name: "Mod Packs" }, { name: modPack.name || modPackId }];
|
let nav = [{ name: "Mods", path: "/mods" }, { name: "Mod Packs" }, { name: modPack.name || String(modPackId) }];
|
||||||
if (modifiedModPack.loading) {
|
if (modifiedModPack.loading) {
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<PageHeader title={modPackId} />
|
<PageHeader title={String(modPackId)} />
|
||||||
<Spin size="large" />
|
<Spin size="large" />
|
||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
@@ -704,11 +785,13 @@ export default function ModPackViewPage() {
|
|||||||
okText="Delete"
|
okText="Delete"
|
||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
if (modPack.id !== undefined) {
|
||||||
new lib.ModPackDeleteRequest(modPack.id)
|
control.send(
|
||||||
).then(() => {
|
new lib.ModPackDeleteRequest(modPack.id)
|
||||||
navigate("/mods");
|
).then(() => {
|
||||||
}).catch(notifyErrorHandler("Error deleting mod pack"));
|
navigate("/mods");
|
||||||
|
}).catch(notifyErrorHandler("Error deleting mod pack"));
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Button danger icon={<DeleteOutlined />}>Delete</Button>
|
<Button danger icon={<DeleteOutlined />}>Delete</Button>
|
||||||
@@ -739,7 +822,7 @@ export default function ModPackViewPage() {
|
|||||||
<Descriptions.Item span={3} label="Name">
|
<Descriptions.Item span={3} label="Name">
|
||||||
<Form.Item noStyle name="name">
|
<Form.Item noStyle name="name">
|
||||||
<Input
|
<Input
|
||||||
className={hasChange(changes, { type: "name" }) && "changed"}
|
className={hasChange(changes, { type: "name" }) && "changed" || ""}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
@@ -747,7 +830,7 @@ export default function ModPackViewPage() {
|
|||||||
<Form.Item noStyle name="description">
|
<Form.Item noStyle name="description">
|
||||||
<Input.TextArea
|
<Input.TextArea
|
||||||
autoSize={{ minRows: 2 }}
|
autoSize={{ minRows: 2 }}
|
||||||
className={hasChange(changes, { type: "description" }) && "changed"}
|
className={hasChange(changes, { type: "description" }) && "changed" || ""}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
@@ -764,7 +847,7 @@ export default function ModPackViewPage() {
|
|||||||
}]}
|
}]}
|
||||||
>
|
>
|
||||||
<Input
|
<Input
|
||||||
className={hasChange(changes, { type: "factorioVersion" }) && "changed"}
|
className={hasChange(changes, { type: "factorioVersion" }) && "changed" || ""}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
@@ -812,5 +895,4 @@ export default function ModPackViewPage() {
|
|||||||
</Row>
|
</Row>
|
||||||
</div>
|
</div>
|
||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
|
|
||||||
}
|
}
|
||||||
+11
-12
@@ -18,8 +18,7 @@ import PluginExtra from "./PluginExtra";
|
|||||||
import SectionHeader from "./SectionHeader";
|
import SectionHeader from "./SectionHeader";
|
||||||
import ModDetails from "./ModDetails";
|
import ModDetails from "./ModDetails";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
function ImportModPackButton() {
|
function ImportModPackButton() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
@@ -94,11 +93,11 @@ function CreateModPackButton() {
|
|||||||
} catch {
|
} catch {
|
||||||
return; // Validation failed
|
return; // Validation failed
|
||||||
}
|
}
|
||||||
const modPack = lib.ModPack.fromJSON({});
|
const modPack = lib.ModPack.fromJSON({} as any);
|
||||||
modPack.name = values.name;
|
modPack.name = values.name;
|
||||||
modPack.factorioVersion = values.factorioVersion;
|
modPack.factorioVersion = values.factorioVersion;
|
||||||
if (values.description) { modPack.description = values.description; }
|
if (values.description) { modPack.description = values.description; }
|
||||||
await control.send(new lib.ModPackCreateRequest(modPack.toJSON()));
|
await control.send(new lib.ModPackCreateRequest(modPack));
|
||||||
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
||||||
})().catch(notifyErrorHandler("Error creating mod pack"));
|
})().catch(notifyErrorHandler("Error creating mod pack"));
|
||||||
}}
|
}}
|
||||||
@@ -133,17 +132,17 @@ export default function ModsPage() {
|
|||||||
let [modList] = useModList();
|
let [modList] = useModList();
|
||||||
let [modPackList] = useModPackList();
|
let [modPackList] = useModPackList();
|
||||||
|
|
||||||
function actions(mod) {
|
function actions(mod: lib.ModInfo|lib.ModRecord) {
|
||||||
return <Space>
|
return <Space>
|
||||||
{account.hasPermission("core.mod.download")
|
{account.hasPermission("core.mod.download")
|
||||||
&& <Typography.Link
|
&& <Typography.Link
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new lib.ModDownloadRequest(mod.name, mod.version)
|
new lib.ModDownloadRequest(mod.name, mod.version)
|
||||||
).then(streamId => {
|
).then((streamId: string) => {
|
||||||
let url = new URL(webRoot, document.location);
|
let url = new URL(window.webRoot, document.location.origin);
|
||||||
url.pathname += `api/stream/${streamId}`;
|
url.pathname += `api/stream/${streamId}`;
|
||||||
document.location = url;
|
document.location = url.href;
|
||||||
}).catch(
|
}).catch(
|
||||||
notifyErrorHandler("Error downloading save")
|
notifyErrorHandler("Error downloading save")
|
||||||
);
|
);
|
||||||
@@ -174,9 +173,9 @@ export default function ModsPage() {
|
|||||||
accept=".zip"
|
accept=".zip"
|
||||||
multiple
|
multiple
|
||||||
headers={{
|
headers={{
|
||||||
"X-Access-Token": control.connector.token,
|
"X-Access-Token": control.connector.token||"",
|
||||||
}}
|
}}
|
||||||
action={`${webRoot}api/upload-mod`}
|
action={`${window.webRoot}api/upload-mod`}
|
||||||
>
|
>
|
||||||
<Button icon={<UploadOutlined/>}>Upload</Button>
|
<Button icon={<UploadOutlined/>}>Upload</Button>
|
||||||
</Upload>;
|
</Upload>;
|
||||||
@@ -212,7 +211,7 @@ export default function ModsPage() {
|
|||||||
]}
|
]}
|
||||||
dataSource={modPackList}
|
dataSource={modPackList}
|
||||||
pagination={false}
|
pagination={false}
|
||||||
rowKey={modPack => modPack.id}
|
rowKey={modPack => Number(modPack.id)}
|
||||||
onRow={(modPack, rowIndex) => ({
|
onRow={(modPack, rowIndex) => ({
|
||||||
onClick: event => {
|
onClick: event => {
|
||||||
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
navigate(`/mods/mod-packs/${modPack.id}/view`);
|
||||||
@@ -261,7 +260,7 @@ export default function ModsPage() {
|
|||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
expandable={{
|
expandable={{
|
||||||
expandedRowRender: mod => <ModDetails mod={mod} actions={actions} />,
|
expandedRowRender: (mod: lib.ModInfo) => <ModDetails mod={mod} actions={actions} />,
|
||||||
expandedRowClassName: () => "no-expanded-padding",
|
expandedRowClassName: () => "no-expanded-padding",
|
||||||
}}
|
}}
|
||||||
dataSource={modList}
|
dataSource={modList}
|
||||||
+6
-1
@@ -1,6 +1,11 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
export default function PageHeader(props) {
|
type PageHeaderProps = {
|
||||||
|
title: string|React.ReactElement;
|
||||||
|
extra?: React.JSX.Element;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function PageHeader(props: PageHeaderProps): React.JSX.Element {
|
||||||
return <div className="page-header">
|
return <div className="page-header">
|
||||||
<h2 className="page-header-title">{props.title}</h2>
|
<h2 className="page-header-title">{props.title}</h2>
|
||||||
{props.extra && <div className="page-header-extra">{props.extra}</div>}
|
{props.extra && <div className="page-header-extra">{props.extra}</div>}
|
||||||
+8
-1
@@ -4,7 +4,14 @@ import { Layout, Breadcrumb } from "antd";
|
|||||||
|
|
||||||
const { Content } = Layout;
|
const { Content } = Layout;
|
||||||
|
|
||||||
export default function PageLayout(props) {
|
type PageLayoutProps = {
|
||||||
|
nav: {
|
||||||
|
path?: string;
|
||||||
|
name: string;
|
||||||
|
}[];
|
||||||
|
children?: any;
|
||||||
|
};
|
||||||
|
export default function PageLayout(props: PageLayoutProps) {
|
||||||
return <>
|
return <>
|
||||||
<Breadcrumb className="site-breadcrumb">
|
<Breadcrumb className="site-breadcrumb">
|
||||||
{props.nav.map((part, index) => <Breadcrumb.Item key={index}>
|
{props.nav.map((part, index) => <Breadcrumb.Item key={index}>
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import React, { useContext } from "react";
|
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
|
||||||
|
|
||||||
|
|
||||||
export default function PluginExtra(params) {
|
|
||||||
let control = useContext(ControlContext);
|
|
||||||
|
|
||||||
let components = [];
|
|
||||||
for (let [name, plugin] of control.plugins) {
|
|
||||||
if (Object.prototype.hasOwnProperty.call(plugin.componentExtra, params.component)) {
|
|
||||||
let ComponentExtra = plugin.componentExtra[params.component];
|
|
||||||
components.push(<ComponentExtra key={name} plugin={plugin} {...params}/>);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return components;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import React, { useContext } from "react";
|
||||||
|
|
||||||
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
import ControlContext from "./ControlContext";
|
||||||
|
import { RawUserState } from "../model/user";
|
||||||
|
import { HostState } from "../model/host";
|
||||||
|
import { InstanceState } from "../model/instance";
|
||||||
|
import { RawRoleState } from "./RoleViewPage";
|
||||||
|
|
||||||
|
|
||||||
|
type PluginExtraProps = {
|
||||||
|
component: string;
|
||||||
|
instance?: InstanceState;
|
||||||
|
user?: RawUserState;
|
||||||
|
host?: HostState;
|
||||||
|
role?: RawRoleState;
|
||||||
|
};
|
||||||
|
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:lib.BaseWebPlugin}>};
|
||||||
|
let ComponentExtra = (plugin.componentExtra as ComponentExtra)[props.component];
|
||||||
|
components.push(<ComponentExtra key={name} plugin={plugin} {...props}/>);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return components;
|
||||||
|
}
|
||||||
+7
-5
@@ -2,19 +2,21 @@ import React, { useEffect, useContext, useState } from "react";
|
|||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
import { Alert, Descriptions, Spin } from "antd";
|
import { Alert, Descriptions, Spin } from "antd";
|
||||||
|
|
||||||
|
import type { PluginWebApi } from "@clusterio/controller/src/routes";
|
||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import PageLayout from "./PageLayout";
|
import PageLayout from "./PageLayout";
|
||||||
|
import notify from "../util/notify";
|
||||||
|
|
||||||
export default function PluginViewPage() {
|
export default function PluginViewPage() {
|
||||||
let params = useParams();
|
let params = useParams();
|
||||||
let plugins = useContext(ControlContext).plugins;
|
let plugins = useContext(ControlContext).plugins;
|
||||||
let [pluginList, setPluginList] = useState(null);
|
let [pluginList, setPluginList] = useState<PluginWebApi[]>([]);
|
||||||
let pluginName = params.name;
|
let pluginName = String(params.name);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
let response = await fetch(`${webRoot}api/plugins`);
|
let response = await fetch(`${window.webRoot}api/plugins`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
setPluginList(await response.json());
|
setPluginList(await response.json());
|
||||||
} else {
|
} else {
|
||||||
@@ -28,7 +30,7 @@ export default function PluginViewPage() {
|
|||||||
let nav = [{ name: "Plugins", path: "/plugins" }, { name: pluginTitle }];
|
let nav = [{ name: "Plugins", path: "/plugins" }, { name: pluginTitle }];
|
||||||
if (!pluginList) {
|
if (!pluginList) {
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<Descriptions borderd size="small" title={pluginTitle} />
|
<Descriptions bordered size="small" title={pluginTitle} />
|
||||||
<Spin size="large" />
|
<Spin size="large" />
|
||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
|
|
||||||
export default React.createContext();
|
|
||||||
+7
-5
@@ -2,21 +2,23 @@ import React, { useContext, useEffect, useState } from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { Table } from "antd";
|
import { Table } from "antd";
|
||||||
|
|
||||||
|
import type { PluginWebApi } from "@clusterio/controller/src/routes";
|
||||||
|
|
||||||
import notify from "../util/notify";
|
import notify from "../util/notify";
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import PageLayout from "./PageLayout";
|
import PageLayout from "./PageLayout";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
export default function PluginsPage() {
|
export default function PluginsPage() {
|
||||||
let plugins = useContext(ControlContext).plugins;
|
let plugins = useContext(ControlContext).plugins;
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
let [pluginList, setPluginList] = useState([]);
|
let [pluginList, setPluginList] = useState<PluginWebApi[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
let response = await fetch(`${webRoot}api/plugins`);
|
let response = await fetch(`${window.webRoot}api/plugins`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
setPluginList(await response.json());
|
setPluginList(await response.json());
|
||||||
} else {
|
} else {
|
||||||
@@ -28,7 +30,7 @@ export default function PluginsPage() {
|
|||||||
let tableContents = [];
|
let tableContents = [];
|
||||||
for (let meta of pluginList) {
|
for (let meta of pluginList) {
|
||||||
if (plugins.has(meta.name)) {
|
if (plugins.has(meta.name)) {
|
||||||
let plugin = plugins.get(meta.name);
|
let plugin = plugins.get(meta.name)!;
|
||||||
tableContents.push({
|
tableContents.push({
|
||||||
meta,
|
meta,
|
||||||
info: plugin.info,
|
info: plugin.info,
|
||||||
@@ -70,7 +72,7 @@ export default function PluginsPage() {
|
|||||||
title: "Loaded",
|
title: "Loaded",
|
||||||
dataIndex: ["meta", "loaded"],
|
dataIndex: ["meta", "loaded"],
|
||||||
render: loaded => (loaded ? "Yes" : null),
|
render: loaded => (loaded ? "Yes" : null),
|
||||||
sorter: (a, b) => a.loaded - b.loaded,
|
sorter: (a, b) => Number(a.meta.loaded) - Number(b.meta.loaded),
|
||||||
responsive: ["sm"],
|
responsive: ["sm"],
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
+11
-6
@@ -13,9 +13,14 @@ import PluginExtra from "./PluginExtra";
|
|||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
|
||||||
|
|
||||||
function useRole(id) {
|
export type RawRoleState = Partial<lib.RawRole> & {
|
||||||
|
loading?: Boolean;
|
||||||
|
missing?: Boolean;
|
||||||
|
present?: Boolean;
|
||||||
|
};
|
||||||
|
function useRole(id: number): [RawRoleState, () => void] {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [role, setRole] = useState({ loading: true });
|
let [role, setRole] = useState<RawRoleState>({ loading: true });
|
||||||
|
|
||||||
function updateRole() {
|
function updateRole() {
|
||||||
// XXX optimize by requesting only the role in question
|
// XXX optimize by requesting only the role in question
|
||||||
@@ -51,10 +56,10 @@ export default function RoleViewPage() {
|
|||||||
let [edited, setEdited] = useState(false);
|
let [edited, setEdited] = useState(false);
|
||||||
|
|
||||||
|
|
||||||
let nav = [{ name: "Roles", path: "/roles" }, { name: role["name"] || roleId }];
|
let nav = [{ name: "Roles", path: "/roles" }, { name: role.name || String(roleId) }];
|
||||||
if (role.loading) {
|
if (role.loading) {
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
<PageHeader title={roleId} />
|
<PageHeader title={String(roleId)} />
|
||||||
<Spin size="large" />
|
<Spin size="large" />
|
||||||
</PageLayout>;
|
</PageLayout>;
|
||||||
}
|
}
|
||||||
@@ -71,7 +76,7 @@ export default function RoleViewPage() {
|
|||||||
description: role["description"],
|
description: role["description"],
|
||||||
permissions: {
|
permissions: {
|
||||||
...Object.fromEntries([...lib.permissions.values()].map(perm => [
|
...Object.fromEntries([...lib.permissions.values()].map(perm => [
|
||||||
perm.name, role["permissions"].includes(perm.name),
|
perm.name, role.permissions!.includes(perm.name),
|
||||||
])),
|
])),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -96,7 +101,7 @@ export default function RoleViewPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={role["name"]}
|
title={role.name!}
|
||||||
extra={<>
|
extra={<>
|
||||||
{canUpdate && <Button type={edited ? "primary" : "default"} htmlType="submit">Apply</Button>}
|
{canUpdate && <Button type={edited ? "primary" : "default"} htmlType="submit">Apply</Button>}
|
||||||
{account.hasPermission("core.role.delete") && <Popconfirm
|
{account.hasPermission("core.role.delete") && <Popconfirm
|
||||||
+5
-6
@@ -11,8 +11,7 @@ import PageHeader from "./PageHeader";
|
|||||||
import PageLayout from "./PageLayout";
|
import PageLayout from "./PageLayout";
|
||||||
import PluginExtra from "./PluginExtra";
|
import PluginExtra from "./PluginExtra";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
function CreateRoleButton() {
|
function CreateRoleButton() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
@@ -27,11 +26,11 @@ function CreateRoleButton() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = await control.send(
|
let idRole = await control.send(
|
||||||
new lib.RoleCreateRequest(values.roleName, values.description || "", [])
|
new lib.RoleCreateRequest(values.roleName, values.description || "", [])
|
||||||
);
|
);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
navigate(`/roles/${result.id}/view`);
|
navigate(`/roles/${idRole}/view`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return <>
|
return <>
|
||||||
@@ -64,7 +63,7 @@ export default function RolesPage() {
|
|||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
|
|
||||||
let [roles, setRoles] = useState([]);
|
let [roles, setRoles] = useState<lib.RawRole[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
control.send(new lib.RoleListRequest()).then(newRoles => {
|
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||||
@@ -75,7 +74,7 @@ export default function RolesPage() {
|
|||||||
return <PageLayout nav={[{ name: "Roles" }]}>
|
return <PageLayout nav={[{ name: "Roles" }]}>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Roles"
|
title="Roles"
|
||||||
extra={account.hasPermission("core.role.create") && <CreateRoleButton />}
|
extra={account.hasPermission("core.role.create") && <CreateRoleButton /> || undefined}
|
||||||
/>
|
/>
|
||||||
<Table
|
<Table
|
||||||
columns={[
|
columns={[
|
||||||
+43
-25
@@ -12,12 +12,19 @@ import { useAccount } from "../model/account";
|
|||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import CreateSaveModal from "./CreateSaveModal";
|
import CreateSaveModal from "./CreateSaveModal";
|
||||||
import SectionHeader from "./SectionHeader";
|
import SectionHeader from "./SectionHeader";
|
||||||
import { useInstanceList } from "../model/instance";
|
import { InstanceState, useInstanceList } from "../model/instance";
|
||||||
import { useSaves } from "../model/saves";
|
import { useSaves } from "../model/saves";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
|
||||||
|
|
||||||
function RenameModal(props) {
|
|
||||||
|
type ModalProps = {
|
||||||
|
disabled: boolean;
|
||||||
|
save: lib.SaveDetails;
|
||||||
|
instanceId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RenameModal(props: ModalProps) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
@@ -56,7 +63,7 @@ function RenameModal(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function CopyModal(props) {
|
function CopyModal(props: ModalProps) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
@@ -95,7 +102,8 @@ function CopyModal(props) {
|
|||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TransferModal(props) {
|
|
||||||
|
function TransferModal(props: ModalProps) {
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [open, setOpen] = useState(false);
|
let [open, setOpen] = useState(false);
|
||||||
@@ -142,7 +150,7 @@ function TransferModal(props) {
|
|||||||
<Select
|
<Select
|
||||||
autoFocus
|
autoFocus
|
||||||
showSearch
|
showSearch
|
||||||
filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
|
filterOption={(input, option) => (option?.title.toLowerCase().indexOf(input.toLowerCase())??-1) >= 0}
|
||||||
>
|
>
|
||||||
{instanceList.filter(
|
{instanceList.filter(
|
||||||
instance => instance["id"] !== props.instanceId
|
instance => instance["id"] !== props.instanceId
|
||||||
@@ -161,32 +169,42 @@ function TransferModal(props) {
|
|||||||
<Form.Item
|
<Form.Item
|
||||||
name="transferredName"
|
name="transferredName"
|
||||||
label="Transferred name"
|
label="Transferred name"
|
||||||
disabled={!account.hasAnyPermission("core.instance.save.rename", "core.instance.save.copy")}
|
|
||||||
>
|
>
|
||||||
<Input />
|
<Input
|
||||||
|
disabled={!account.hasAnyPermission("core.instance.save.rename", "core.instance.save.copy")}
|
||||||
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="copy"
|
name="copy"
|
||||||
valuePropName="checked"
|
valuePropName="checked"
|
||||||
label="Copy"
|
label="Copy"
|
||||||
tooltip="Copy instead of moving the save to the new instance."
|
tooltip="Copy instead of moving the save to the new instance."
|
||||||
disabled={!account.hasPermission("core.instance.save.copy")}
|
|
||||||
>
|
>
|
||||||
<Checkbox />
|
<Checkbox
|
||||||
|
disabled={!account.hasPermission("core.instance.save.copy")}
|
||||||
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
</>;
|
</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function SavesList(props) {
|
|
||||||
|
type File = {
|
||||||
|
uid: string;
|
||||||
|
name: string;
|
||||||
|
percent: number;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SavesList(props: { instance: InstanceState }) {
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let saves = useSaves(props.instance.id);
|
let saves = useSaves(props.instance.id);
|
||||||
let [starting, setStarting] = useState(false);
|
let [starting, setStarting] = useState(false);
|
||||||
let [uploadingFiles, setUploadingFiles] = useState([]);
|
let [uploadingFiles, setUploadingFiles] = useState<File[]>([]);
|
||||||
|
|
||||||
let hostOffline = ["unassigned", "unknown"].includes(props.instance.status);
|
let hostOffline = ["unassigned", "unknown"].includes(props.instance.status!);
|
||||||
const saveTable = <Table
|
const saveTable = <Table
|
||||||
size="small"
|
size="small"
|
||||||
columns={[
|
columns={[
|
||||||
@@ -228,7 +246,7 @@ export default function SavesList(props) {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
setStarting(true);
|
setStarting(true);
|
||||||
control.sendTo(
|
control.sendTo(
|
||||||
{ instanceId: props.instance.id },
|
{ instanceId: props.instance.id! },
|
||||||
new lib.InstanceStartRequest(save.name),
|
new lib.InstanceStartRequest(save.name),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error loading save")
|
notifyErrorHandler("Error loading save")
|
||||||
@@ -238,27 +256,27 @@ export default function SavesList(props) {
|
|||||||
}}
|
}}
|
||||||
>Load save</Button>}
|
>Load save</Button>}
|
||||||
{account.hasPermission("core.instance.save.rename") && <RenameModal
|
{account.hasPermission("core.instance.save.rename") && <RenameModal
|
||||||
disabled={hostOffline} instanceId={props.instance.id} save={save}
|
disabled={hostOffline} instanceId={props.instance.id!} save={save}
|
||||||
/>}
|
/>}
|
||||||
{account.hasPermission("core.instance.save.copy") && <CopyModal
|
{account.hasPermission("core.instance.save.copy") && <CopyModal
|
||||||
disabled={hostOffline} instanceId={props.instance.id} save={save}
|
disabled={hostOffline} instanceId={props.instance.id!} save={save}
|
||||||
/>}
|
/>}
|
||||||
{account.hasPermission("core.instance.save.download") && <Button
|
{account.hasPermission("core.instance.save.download") && <Button
|
||||||
disabled={hostOffline}
|
disabled={hostOffline}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new lib.InstanceDownloadSaveRequest(props.instance.id, save.name)
|
new lib.InstanceDownloadSaveRequest(props.instance.id!, save.name)
|
||||||
).then(streamId => {
|
).then(streamId => {
|
||||||
let url = new URL(webRoot, document.location);
|
let url = new URL(window.webRoot, document.location.href);
|
||||||
url.pathname += `api/stream/${streamId}`;
|
url.pathname += `api/stream/${streamId}`;
|
||||||
document.location = url;
|
document.location.assign(url);
|
||||||
}).catch(
|
}).catch(
|
||||||
notifyErrorHandler("Error downloading save")
|
notifyErrorHandler("Error downloading save")
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
>Download</Button>}
|
>Download</Button>}
|
||||||
{account.hasPermission("core.instance.save.transfer") && <TransferModal
|
{account.hasPermission("core.instance.save.transfer") && <TransferModal
|
||||||
disabled={hostOffline} instanceId={props.instance.id} save={save}
|
disabled={hostOffline} instanceId={props.instance.id!} save={save}
|
||||||
/>}
|
/>}
|
||||||
{account.hasPermission("core.instance.save.delete") && <Popconfirm
|
{account.hasPermission("core.instance.save.delete") && <Popconfirm
|
||||||
title="Permanently delete save?"
|
title="Permanently delete save?"
|
||||||
@@ -267,7 +285,7 @@ export default function SavesList(props) {
|
|||||||
okButtonProps={{ danger: true }}
|
okButtonProps={{ danger: true }}
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
control.send(
|
control.send(
|
||||||
new lib.InstanceDeleteSaveRequest(props.instance.id, save.name)
|
new lib.InstanceDeleteSaveRequest(props.instance.id!, save.name)
|
||||||
).catch(notifyErrorHandler("Error deleting save"));
|
).catch(notifyErrorHandler("Error deleting save"));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -277,7 +295,7 @@ export default function SavesList(props) {
|
|||||||
}}
|
}}
|
||||||
/>;
|
/>;
|
||||||
|
|
||||||
function onChange(changeEvent) {
|
function onChange(changeEvent: any) {
|
||||||
if (["done", "error"].includes(changeEvent.file.status)) {
|
if (["done", "error"].includes(changeEvent.file.status)) {
|
||||||
if (changeEvent.file.status === "error") {
|
if (changeEvent.file.status === "error") {
|
||||||
notifyErrorHandler("Error uploading file")(changeEvent.file.error);
|
notifyErrorHandler("Error uploading file")(changeEvent.file.error);
|
||||||
@@ -292,7 +310,7 @@ export default function SavesList(props) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let file = {
|
let file: File = {
|
||||||
uid: changeEvent.file.uid,
|
uid: changeEvent.file.uid,
|
||||||
name: changeEvent.file.name,
|
name: changeEvent.file.name,
|
||||||
percent: changeEvent.file.percent,
|
percent: changeEvent.file.percent,
|
||||||
@@ -314,13 +332,13 @@ export default function SavesList(props) {
|
|||||||
name: "file",
|
name: "file",
|
||||||
accept: ".zip",
|
accept: ".zip",
|
||||||
headers: {
|
headers: {
|
||||||
"X-Access-Token": control.connector.token,
|
"X-Access-Token": control.connector.token || "",
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
instance_id: props.instance.id,
|
instance_id: props.instance.id,
|
||||||
},
|
},
|
||||||
showUploadList: false,
|
showUploadList: false,
|
||||||
action: `${webRoot}api/upload-save`,
|
action: `${window.webRoot}api/upload-save`,
|
||||||
onChange,
|
onChange,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -343,7 +361,7 @@ export default function SavesList(props) {
|
|||||||
{file.name}
|
{file.name}
|
||||||
<Progress
|
<Progress
|
||||||
percent={file.percent}
|
percent={file.percent}
|
||||||
format={percent => `${Math.floor(percent)}%`}
|
format={percent => `${Math.floor(percent||0)}%`}
|
||||||
status={file.status === "error" ? "exception" : "normal"}
|
status={file.status === "error" ? "exception" : "normal"}
|
||||||
/>
|
/>
|
||||||
</List.Item>)}
|
</List.Item>)}
|
||||||
+5
-1
@@ -1,6 +1,10 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
export default function SectionHeader(props) {
|
type SectionHeader = {
|
||||||
|
title: string;
|
||||||
|
extra?: React.JSX.Element;
|
||||||
|
};
|
||||||
|
export default function SectionHeader(props: SectionHeader): React.JSX.Element {
|
||||||
return <div className="section-header">
|
return <div className="section-header">
|
||||||
<div className="section-header-title">{props.title}</div>
|
<div className="section-header-title">{props.title}</div>
|
||||||
{props.extra && <div className="section-header-extra">{props.extra}</div>}
|
{props.extra && <div className="section-header-extra">{props.extra}</div>}
|
||||||
+9
-10
@@ -1,6 +1,6 @@
|
|||||||
import React, { useContext, useEffect, useState } from "react";
|
import React, { useContext, useEffect, useState } from "react";
|
||||||
import { Route, Routes, useNavigate } from "react-router-dom";
|
import { Route, Routes, useNavigate } from "react-router-dom";
|
||||||
import { Dropdown, Layout, Menu } from "antd";
|
import { Dropdown, Layout, Menu, MenuProps } from "antd";
|
||||||
import UserOutlined from "@ant-design/icons/UserOutlined";
|
import UserOutlined from "@ant-design/icons/UserOutlined";
|
||||||
import webUiPackage from "../../package.json";
|
import webUiPackage from "../../package.json";
|
||||||
|
|
||||||
@@ -12,22 +12,21 @@ import { pages } from "../pages";
|
|||||||
|
|
||||||
const { Header, Sider } = Layout;
|
const { Header, Sider } = Layout;
|
||||||
|
|
||||||
|
export default function SiteLayout() {
|
||||||
export default function SiteLayout(props) {
|
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
let [currentSidebarPath, setCurrentSidebarPath] = useState(null);
|
let [currentSidebarPath, setCurrentSidebarPath] = useState<string|null>(null);
|
||||||
let account = useAccount();
|
let account = useAccount();
|
||||||
let plugins = useContext(ControlContext).plugins;
|
let plugins = useContext(ControlContext).plugins;
|
||||||
|
|
||||||
function SetSidebar(setSidebarProps) {
|
function SetSidebar(props: { path: string|null }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setCurrentSidebarPath(setSidebarProps.path);
|
setCurrentSidebarPath(props.path);
|
||||||
});
|
});
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
let accountMenuProps = {
|
let accountMenuProps: MenuProps = {
|
||||||
onClick: ({ key }) => {
|
onClick: ({ key }: {key:string}) => {
|
||||||
if (key === "user") {
|
if (key === "user") {
|
||||||
navigate(`/users/${account.name}/view`);
|
navigate(`/users/${account.name}/view`);
|
||||||
} else if (key === "logOut") {
|
} else if (key === "logOut") {
|
||||||
@@ -87,7 +86,7 @@ export default function SiteLayout(props) {
|
|||||||
<Dropdown
|
<Dropdown
|
||||||
className="account-dropdown-header"
|
className="account-dropdown-header"
|
||||||
placement="bottomRight"
|
placement="bottomRight"
|
||||||
trigger="click"
|
trigger={["click"]}
|
||||||
menu={accountMenuProps}
|
menu={accountMenuProps}
|
||||||
>
|
>
|
||||||
<UserOutlined/>
|
<UserOutlined/>
|
||||||
@@ -105,7 +104,7 @@ export default function SiteLayout(props) {
|
|||||||
<Menu
|
<Menu
|
||||||
mode="inline"
|
mode="inline"
|
||||||
defaultOpenKeys={[...menuGroups.keys()]}
|
defaultOpenKeys={[...menuGroups.keys()]}
|
||||||
selectedKeys={[currentSidebarPath]}
|
selectedKeys={currentSidebarPath ? [currentSidebarPath] : []}
|
||||||
style={{ height: "100%", borderRight: 0 }}
|
style={{ height: "100%", borderRight: 0 }}
|
||||||
onClick={({ key }) => navigate(key)}
|
onClick={({ key }) => navigate(key)}
|
||||||
items={menuItems}
|
items={menuItems}
|
||||||
+16
-12
@@ -5,27 +5,33 @@ import * as lib from "@clusterio/lib";
|
|||||||
|
|
||||||
import ControlContext from "./ControlContext";
|
import ControlContext from "./ControlContext";
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
|
import type { InstanceState } from "../model/instance";
|
||||||
|
import { ButtonProps } from "antd/es/button";
|
||||||
|
|
||||||
|
type StartStopInstanceButtonProps = {
|
||||||
export default function StartStopInstanceButton(props) {
|
instance: InstanceState;
|
||||||
|
onFinish?: () => void;
|
||||||
|
buttonProps?: ButtonProps;
|
||||||
|
};
|
||||||
|
export default function StartStopInstanceButton(props: StartStopInstanceButtonProps) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [switching, setSwitching] = useState(false);
|
let [switching, setSwitching] = useState<boolean>(false);
|
||||||
|
|
||||||
function onClick(event) {
|
const onClick: React.MouseEventHandler<HTMLElement> = function(event) {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
setSwitching(true);
|
setSwitching(true);
|
||||||
let action;
|
let action;
|
||||||
if (props.instance["status"] === "stopped") {
|
if (props.instance.status === "stopped") {
|
||||||
action = control.sendTo(
|
action = control.sendTo(
|
||||||
{ instanceId: props.instance["id"] },
|
{ instanceId: props.instance.id! },
|
||||||
new lib.InstanceStartRequest(undefined),
|
new lib.InstanceStartRequest(undefined),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error starting instance")
|
notifyErrorHandler("Error starting instance")
|
||||||
);
|
);
|
||||||
|
|
||||||
} else if (["starting", "running"].includes(props.instance["status"])) {
|
} else if (["starting", "running"].includes(props.instance.status!)) {
|
||||||
action = control.sendTo(
|
action = control.sendTo(
|
||||||
{ instanceId: props.instance["id"] },
|
{ instanceId: props.instance.id! },
|
||||||
new lib.InstanceStopRequest(),
|
new lib.InstanceStopRequest(),
|
||||||
).catch(
|
).catch(
|
||||||
notifyErrorHandler("Error stopping instance")
|
notifyErrorHandler("Error stopping instance")
|
||||||
@@ -48,11 +54,9 @@ export default function StartStopInstanceButton(props) {
|
|||||||
{...(props.buttonProps || {})}
|
{...(props.buttonProps || {})}
|
||||||
loading={switching}
|
loading={switching}
|
||||||
type="primary"
|
type="primary"
|
||||||
disabled={!["starting", "running", "stopped"].includes(props.instance["status"])}
|
disabled={!["starting", "running", "stopped"].includes(props.instance.status!)}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
{props.instance["status"] === "stopped" ? "Start" : "Stop"}
|
{props.instance.status === "stopped" ? "Start" : "Stop"}
|
||||||
</Button>;
|
</Button>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
+17
-17
@@ -19,7 +19,7 @@ import notify, { notifyErrorHandler } from "../util/notify";
|
|||||||
import { formatDuration } from "../util/time_format";
|
import { formatDuration } from "../util/time_format";
|
||||||
import { formatLastSeen, sortLastSeen, useUser } from "../model/user";
|
import { formatLastSeen, sortLastSeen, useUser } from "../model/user";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
// The user page has a lot of optional elements, that does not make it
|
// The user page has a lot of optional elements, that does not make it
|
||||||
@@ -27,7 +27,7 @@ const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "ba
|
|||||||
// eslint-disable-next-line complexity
|
// eslint-disable-next-line complexity
|
||||||
export default function UserViewPage() {
|
export default function UserViewPage() {
|
||||||
let params = useParams();
|
let params = useParams();
|
||||||
let userName = params.name;
|
let userName = params.name as string;
|
||||||
|
|
||||||
let navigate = useNavigate();
|
let navigate = useNavigate();
|
||||||
|
|
||||||
@@ -35,12 +35,12 @@ export default function UserViewPage() {
|
|||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [instanceList] = useInstanceList();
|
let [instanceList] = useInstanceList();
|
||||||
let [user] = useUser(userName);
|
let [user] = useUser(userName);
|
||||||
let [roles, setRoles] = useState(null);
|
let [roles, setRoles] = useState<Map<number, lib.RawRole>>(new Map());
|
||||||
let [form] = Form.useForm();
|
let [form] = Form.useForm();
|
||||||
let [rolesDirty, setRolesDirty] = useState(false);
|
let [rolesDirty, setRolesDirty] = useState<boolean>(false);
|
||||||
let [banReasonDirty, setBanReasonDirty] = useState(false);
|
let [banReasonDirty, setBanReasonDirty] = useState<boolean>(false);
|
||||||
let [applyingRoles, setApplyingRoles] = useState(false);
|
let [applyingRoles, setApplyingRoles] = useState<boolean>(false);
|
||||||
let [rolesError, setRolesError] = useState();
|
let [rolesError, setRolesError] = useState<string|undefined>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
control.send(new lib.RoleListRequest()).then(newRoles => {
|
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||||
@@ -88,9 +88,9 @@ export default function UserViewPage() {
|
|||||||
loading={!roles}
|
loading={!roles}
|
||||||
mode="multiple"
|
mode="multiple"
|
||||||
showArrow={true}
|
showArrow={true}
|
||||||
filterOption={(inputValue, option) => {
|
filterOption={(inputValue:string, option: any): boolean => {
|
||||||
let role = roles.get(option.value);
|
let role = roles.get(option.value);
|
||||||
return role && role.name.toLowerCase().includes(inputValue.toLowerCase());
|
return role?.name.toLowerCase().includes(inputValue.toLowerCase()) ?? false;
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{roles && [...roles.values()].map(r => <Select.Option
|
{roles && [...roles.values()].map(r => <Select.Option
|
||||||
@@ -100,9 +100,9 @@ export default function UserViewPage() {
|
|||||||
</Select>
|
</Select>
|
||||||
</Form.Item>;
|
</Form.Item>;
|
||||||
|
|
||||||
function instanceName(id) {
|
function instanceName(id: number): string {
|
||||||
let instance = instanceList.find(i => i.id === id);
|
let instance = instanceList.find(i => i.id === id);
|
||||||
return instance ? instance.name : id;
|
return instance ? instance.name : String(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
return <PageLayout nav={nav}>
|
return <PageLayout nav={nav}>
|
||||||
@@ -181,7 +181,7 @@ export default function UserViewPage() {
|
|||||||
<Col flex="auto">
|
<Col flex="auto">
|
||||||
{account.hasPermission("core.user.update_roles")
|
{account.hasPermission("core.user.update_roles")
|
||||||
? roleSelector
|
? roleSelector
|
||||||
: [...user.roles].map(id => <Tag key={id}>{
|
: [...user.roles!].map(id => <Tag key={id}>{
|
||||||
roles ? (roles.get(id) || { name: id }).name : id
|
roles ? (roles.get(id) || { name: id }).name : id
|
||||||
}</Tag>)
|
}</Tag>)
|
||||||
}
|
}
|
||||||
@@ -198,7 +198,7 @@ export default function UserViewPage() {
|
|||||||
new lib.UserUpdateRolesRequest(userName, newRoles)
|
new lib.UserUpdateRolesRequest(userName, newRoles)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
setRolesDirty(false);
|
setRolesDirty(false);
|
||||||
setRolesError();
|
setRolesError(undefined);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
setRolesError(err.message);
|
setRolesError(err.message);
|
||||||
return form.validateFields();
|
return form.validateFields();
|
||||||
@@ -288,10 +288,10 @@ export default function UserViewPage() {
|
|||||||
<SectionHeader title="Player stats" />
|
<SectionHeader title="Player stats" />
|
||||||
<Descriptions size="small" bordered column={{ xs: 1, sm: 2, lg: 3 }}>
|
<Descriptions size="small" bordered column={{ xs: 1, sm: 2, lg: 3 }}>
|
||||||
<Descriptions.Item label="Total online time">
|
<Descriptions.Item label="Total online time">
|
||||||
{formatDuration(user.playerStats.onlineTimeMs || 0)}
|
{formatDuration(user.playerStats?.onlineTimeMs ?? 0)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="Total join count">
|
<Descriptions.Item label="Total join count">
|
||||||
{user.playerStats.joinCount || 0}
|
{user.playerStats?.joinCount ?? 0}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="Last seen">
|
<Descriptions.Item label="Last seen">
|
||||||
{formatLastSeen(user) || " "}
|
{formatLastSeen(user) || " "}
|
||||||
@@ -306,7 +306,7 @@ export default function UserViewPage() {
|
|||||||
key: "instance",
|
key: "instance",
|
||||||
render: ([id]) => instanceName(id),
|
render: ([id]) => instanceName(id),
|
||||||
defaultSortOrder: "ascend",
|
defaultSortOrder: "ascend",
|
||||||
sorter: (a, b) => strcmp(a[0], b[0]),
|
sorter: (a, b) => strcmp(instanceName(a[0]), instanceName(b[0])),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Online time",
|
title: "Online time",
|
||||||
@@ -328,7 +328,7 @@ export default function UserViewPage() {
|
|||||||
sorter: (a, b) => sortLastSeen(user, user, a[0], b[0]),
|
sorter: (a, b) => sortLastSeen(user, user, a[0], b[0]),
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
dataSource={[...user.instanceStats.entries()]}
|
dataSource={[...(user.instanceStats || []).entries()]}
|
||||||
pagination={false}
|
pagination={false}
|
||||||
rowKey={([id]) => id}
|
rowKey={([id]) => id}
|
||||||
onRow={([id], rowIndex) => ({
|
onRow={([id], rowIndex) => ({
|
||||||
+8
-8
@@ -13,7 +13,7 @@ import PageLayout from "./PageLayout";
|
|||||||
import PluginExtra from "./PluginExtra";
|
import PluginExtra from "./PluginExtra";
|
||||||
import { formatLastSeen, sortLastSeen, useUserList } from "../model/user";
|
import { formatLastSeen, sortLastSeen, useUserList } from "../model/user";
|
||||||
|
|
||||||
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
|
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||||
|
|
||||||
|
|
||||||
function CreateUserButton() {
|
function CreateUserButton() {
|
||||||
@@ -75,14 +75,14 @@ export default function UsersPage() {
|
|||||||
return <PageLayout nav={[{ name: "Users" }]}>
|
return <PageLayout nav={[{ name: "Users" }]}>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title="Users"
|
title="Users"
|
||||||
extra={account.hasPermission("core.user.create") && <CreateUserButton />}
|
extra={account.hasPermission("core.user.create") && <CreateUserButton /> || undefined}
|
||||||
/>
|
/>
|
||||||
<Table
|
<Table
|
||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
title: "Name",
|
title: "Name",
|
||||||
key: "name",
|
key: "name",
|
||||||
render: user => <Space>
|
render: (user: lib.RawUser) => <Space>
|
||||||
{user.name}
|
{user.name}
|
||||||
<span>
|
<span>
|
||||||
{user.isAdmin && <Tag color="gold">Admin</Tag>}
|
{user.isAdmin && <Tag color="gold">Admin</Tag>}
|
||||||
@@ -96,21 +96,21 @@ export default function UsersPage() {
|
|||||||
{
|
{
|
||||||
title: "Roles",
|
title: "Roles",
|
||||||
key: "roles",
|
key: "roles",
|
||||||
render: user => user.roles.map(id => <Tag key={id}>{(roles.get(id) || { name: id }).name}</Tag>),
|
render: (user: lib.RawUser) => user.roles.map(id => <Tag key={id}>{(roles.get(id) || { name: id }).name}</Tag>),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Online time",
|
title: "Online time",
|
||||||
key: "onlineTime",
|
key: "onlineTime",
|
||||||
render: user => (user.playerStats.onlineTimeMs
|
render: (user: lib.RawUser) => (user.playerStats?.onlineTimeMs
|
||||||
? formatDuration(user.playerStats.onlineTimeMs) : null),
|
? formatDuration(user.playerStats.onlineTimeMs) : null),
|
||||||
sorter: (a, b) => (a.playerStats.onlineTimeMs || 0) -
|
sorter: (a, b) => (a.playerStats?.onlineTimeMs ?? 0) -
|
||||||
(b.playerStats.onlineTimeMs || 0),
|
(b.playerStats?.onlineTimeMs ?? 0),
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Last seen",
|
title: "Last seen",
|
||||||
key: "lastSeen",
|
key: "lastSeen",
|
||||||
render: user => formatLastSeen(user),
|
render: (user: lib.RawUser) => formatLastSeen(user),
|
||||||
sorter: (a, b) => sortLastSeen(a, b),
|
sorter: (a, b) => sortLastSeen(a, b),
|
||||||
responsive: ["lg"],
|
responsive: ["lg"],
|
||||||
},
|
},
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
export { default as bootstrap } from "./bootstrap.jsx";
|
export { default as bootstrap } from "./bootstrap";
|
||||||
export { default as notify, notifyErrorHandler } from "./util/notify.jsx";
|
export { default as notify, notifyErrorHandler } from "./util/notify";
|
||||||
|
|
||||||
export * from "./model/instance.jsx";
|
|
||||||
export * from "./model/host.jsx";
|
|
||||||
export * from "./model/locale.jsx";
|
|
||||||
export * from "./model/item_metadata.jsx";
|
|
||||||
export * from "./model/account.jsx";
|
|
||||||
|
|
||||||
|
export * from "./model/instance";
|
||||||
|
export * from "./model/host";
|
||||||
|
export * from "./model/locale";
|
||||||
|
export * from "./model/item_metadata";
|
||||||
|
export * from "./model/account";
|
||||||
|
|
||||||
export { default as ControlContext } from "./components/ControlContext";
|
export { default as ControlContext } from "./components/ControlContext";
|
||||||
|
|
||||||
@@ -1,24 +1,17 @@
|
|||||||
import { useContext, useEffect, useState } from "react";
|
import { useContext, useEffect, useState } from "react";
|
||||||
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { notifyErrorHandler } from "../util/notify";
|
import { notifyErrorHandler } from "../util/notify";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
/**
|
|
||||||
* @typedef {Object} Account
|
|
||||||
* @property {?string} name - Name of the currently logged in account.
|
|
||||||
* @property {?Array<object>} roles - Roles of the corrently logged in account.
|
|
||||||
* @property {function(string)} hasPermission -
|
|
||||||
* Check if the currently logged in account has the given permission.
|
|
||||||
* @property {function()} logOut - Logs out of the web interface.
|
|
||||||
*/
|
|
||||||
|
|
||||||
export function useAccount() {
|
export function useAccount(): lib.UserAccount {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [name, setName] = useState(control.accountName);
|
let [name, setName] = useState<string>(control.accountName || "");
|
||||||
let [roles, setRoles] = useState(control.accountRoles);
|
let [roles, setRoles] = useState<any[]>(control.accountRoles || []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function onAccountUpdate(account) {
|
function onAccountUpdate(account: lib.AccountDetails) {
|
||||||
setName(account.name);
|
setName(account.name);
|
||||||
setRoles(account.roles);
|
setRoles(account.roles);
|
||||||
}
|
}
|
||||||
@@ -28,7 +21,7 @@ export function useAccount() {
|
|||||||
};
|
};
|
||||||
}, [control]);
|
}, [control]);
|
||||||
|
|
||||||
function hasPermission(permission) {
|
function hasPermission(permission: string): boolean {
|
||||||
for (let role of roles) {
|
for (let role of roles) {
|
||||||
if (role.permissions.includes("core.admin") || role.permissions.includes(permission)) {
|
if (role.permissions.includes("core.admin") || role.permissions.includes(permission)) {
|
||||||
return true;
|
return true;
|
||||||
@@ -40,13 +33,13 @@ export function useAccount() {
|
|||||||
return {
|
return {
|
||||||
name,
|
name,
|
||||||
roles,
|
roles,
|
||||||
hasPermission(permission) {
|
hasPermission(permission: string): boolean | null {
|
||||||
if (!roles) {
|
if (!roles) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return hasPermission(permission);
|
return hasPermission(permission);
|
||||||
},
|
},
|
||||||
hasAnyPermission(...permissions) {
|
hasAnyPermission(...permissions: string[]): boolean | null {
|
||||||
if (!roles) {
|
if (!roles) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -57,7 +50,7 @@ export function useAccount() {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
hasAllPermission(...permissions) {
|
hasAllPermission(...permissions: string[]): boolean | null {
|
||||||
if (!roles) {
|
if (!roles) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -70,7 +63,8 @@ export function useAccount() {
|
|||||||
},
|
},
|
||||||
logOut() {
|
logOut() {
|
||||||
control.loggingOut = true;
|
control.loggingOut = true;
|
||||||
control.shutdown(notifyErrorHandler("Error logging out"));
|
notifyErrorHandler("Error logging out");
|
||||||
|
control.shutdown();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+4
-5
@@ -3,12 +3,11 @@ import { useEffect, useContext, useState } from "react";
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import ControlContext from "../components/ControlContext";
|
import ControlContext from "../components/ControlContext";
|
||||||
|
|
||||||
|
let exportManifestCache: lib.ExportManifest|null = null;
|
||||||
let exportManifestCache = null;
|
let emptyCache: any = {};
|
||||||
let emptyCache = {};
|
export function useExportManifest(): lib.ExportManifest|null {
|
||||||
export function useExportManifest() {
|
|
||||||
const control = useContext(ControlContext);
|
const control = useContext(ControlContext);
|
||||||
let [exportManifest, setExportManifest] = useState(exportManifestCache || emptyCache);
|
let [exportManifest, setExportManifest] = useState<lib.ExportManifest|null>(exportManifestCache || emptyCache);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
let modPack = await control.send(new lib.ModPackGetDefaultRequest());
|
let modPack = await control.send(new lib.ModPackGetDefaultRequest());
|
||||||
@@ -4,13 +4,20 @@ import ControlContext from "../components/ControlContext";
|
|||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
|
|
||||||
export function useHost(id) {
|
export type HostState = Partial<lib.HostDetails> & {
|
||||||
|
loading?: boolean,
|
||||||
|
present?: boolean,
|
||||||
|
missing?: boolean,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useHost(id: number): [ HostState, () => void ] {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [host, setHost] = useState({ loading: true });
|
let [host, setHost] = useState<HostState>({ loading: true });
|
||||||
|
|
||||||
function updateHost() {
|
function updateHost() {
|
||||||
// XXX optimize by requesting only the host in question
|
// XXX optimize by requesting only the host in question
|
||||||
control.send(new lib.HostListRequest()).then(hosts => {
|
control.send(new lib.HostListRequest())
|
||||||
|
.then((hosts: lib.HostDetails[]) => {
|
||||||
let match = hosts.find(i => i.id === id);
|
let match = hosts.find(i => i.id === id);
|
||||||
if (!match) {
|
if (!match) {
|
||||||
setHost({ missing: true });
|
setHost({ missing: true });
|
||||||
@@ -27,8 +34,8 @@ export function useHost(id) {
|
|||||||
}
|
}
|
||||||
updateHost();
|
updateHost();
|
||||||
|
|
||||||
function updateHandler(newHost) {
|
function updateHandler(newHost: lib.HostDetails) {
|
||||||
setHost({ ...newHost, present: true });
|
setHost({ ...newHost, loading:false, missing:false, present:true });
|
||||||
}
|
}
|
||||||
|
|
||||||
control.onHostUpdate(id, updateHandler);
|
control.onHostUpdate(id, updateHandler);
|
||||||
@@ -42,10 +49,11 @@ export function useHost(id) {
|
|||||||
|
|
||||||
export function useHostList() {
|
export function useHostList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [hostList, setHostList] = useState([]);
|
let [hostList, setHostList] = useState<lib.HostDetails[]>([]);
|
||||||
|
|
||||||
function updateHostList() {
|
function updateHostList() {
|
||||||
control.send(new lib.HostListRequest()).then(hosts => {
|
control.send(new lib.HostListRequest())
|
||||||
|
.then((hosts: lib.HostDetails[]) => {
|
||||||
setHostList(hosts);
|
setHostList(hosts);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -53,7 +61,7 @@ export function useHostList() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateHostList();
|
updateHostList();
|
||||||
|
|
||||||
function updateHandler(newHost) {
|
function updateHandler(newHost: lib.HostDetails) {
|
||||||
setHostList(oldList => {
|
setHostList(oldList => {
|
||||||
let newList = oldList.concat();
|
let newList = oldList.concat();
|
||||||
let index = newList.findIndex(s => s.id === newHost.id);
|
let index = newList.findIndex(s => s.id === newHost.id);
|
||||||
@@ -5,18 +5,23 @@ import * as lib from "@clusterio/lib";
|
|||||||
|
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useInstance(id) {
|
export type InstanceState = Partial<lib.InstanceDetails> & {
|
||||||
|
loading?: boolean,
|
||||||
|
present?: boolean,
|
||||||
|
missing?: boolean,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useInstance(id: number): [InstanceState, ()=>void] {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [instance, setInstance] = useState({ loading: true });
|
let [instance, setInstance] = useState<InstanceState>({ loading: true });
|
||||||
|
|
||||||
function updateInstance() {
|
function updateInstance() {
|
||||||
control.send(new lib.InstanceDetailsGetRequest(id)).then(updatedInstance => {
|
control.send(new lib.InstanceDetailsGetRequest(id)).then(updatedInstance => {
|
||||||
setInstance({ ...updatedInstance, present: true });
|
setInstance({ ...updatedInstance, present: true });
|
||||||
}).catch(err => {
|
}).catch((err: any) => {
|
||||||
logger.error(`Failed to get instance: ${err}`);
|
logger.error(`Failed to get instance: ${err}`);
|
||||||
setInstance({ missing: true });
|
setInstance({ missing: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -26,7 +31,7 @@ export function useInstance(id) {
|
|||||||
}
|
}
|
||||||
updateInstance();
|
updateInstance();
|
||||||
|
|
||||||
function updateHandler(newInstance) {
|
function updateHandler(newInstance: lib.InstanceDetails) {
|
||||||
setInstance({ ...newInstance, present: true });
|
setInstance({ ...newInstance, present: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +46,7 @@ export function useInstance(id) {
|
|||||||
|
|
||||||
export function useInstanceList() {
|
export function useInstanceList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [instanceList, setInstanceList] = useState([]);
|
let [instanceList, setInstanceList] = useState<lib.InstanceDetails[]>([]);
|
||||||
|
|
||||||
function updateInstanceList() {
|
function updateInstanceList() {
|
||||||
control.send(new lib.InstanceDetailsListRequest()).then(instances => {
|
control.send(new lib.InstanceDetailsListRequest()).then(instances => {
|
||||||
@@ -54,7 +59,7 @@ export function useInstanceList() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateInstanceList();
|
updateInstanceList();
|
||||||
|
|
||||||
function updateHandler(newInstance) {
|
function updateHandler(newInstance: lib.InstanceDetails) {
|
||||||
setInstanceList(oldList => {
|
setInstanceList(oldList => {
|
||||||
let newList = oldList.concat();
|
let newList = oldList.concat();
|
||||||
let index = newList.findIndex(s => s.id === newInstance.id);
|
let index = newList.findIndex(s => s.id === newInstance.id);
|
||||||
+15
-12
@@ -3,10 +3,15 @@ import { useEffect, useState } from "react";
|
|||||||
import { useExportManifest } from "./export_manifest";
|
import { useExportManifest } from "./export_manifest";
|
||||||
|
|
||||||
|
|
||||||
let itemMetadataCache = null;
|
type Metadata = {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
size: number;
|
||||||
|
};
|
||||||
|
let itemMetadataCache: Map<string, Metadata> | null = null;
|
||||||
export function useItemMetadata() {
|
export function useItemMetadata() {
|
||||||
let exportManifest = useExportManifest();
|
let exportManifest = useExportManifest();
|
||||||
let [itemMetadata, setItemMetadata] = useState(itemMetadataCache || new Map());
|
let [itemMetadata, setItemMetadata] = useState<Map<string, Metadata>>(itemMetadataCache || new Map());
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
if (
|
if (
|
||||||
@@ -17,22 +22,21 @@ export function useItemMetadata() {
|
|||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let response = await fetch(`${staticRoot}static/${exportManifest.assets["item-metadata"]}`);
|
let response = await fetch(`${window.staticRoot}static/${exportManifest.assets["item-metadata"]}`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
let data = await response.json();
|
let data = await response.json();
|
||||||
itemMetadataCache = new Map(data);
|
itemMetadataCache = new Map(data);
|
||||||
let style = document.createElement("style");
|
let style = document.createElement("style");
|
||||||
style.type = "text/css";
|
|
||||||
document.head.appendChild(style);
|
document.head.appendChild(style);
|
||||||
for (let [name, meta] of itemMetadataCache) {
|
for (let [name, meta] of itemMetadataCache) {
|
||||||
style.sheet.insertRule(
|
style.sheet!.insertRule(
|
||||||
`.item-${CSS.escape(name)} {
|
`.item-${CSS.escape(name)} {
|
||||||
background-image: url("${staticRoot}static/${exportManifest.assets["item-spritesheet"]}");
|
background-image: url("${window.staticRoot}static/${exportManifest.assets["item-spritesheet"]}");
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
background-position: -${meta.x}px -${meta.y}px;
|
background-position: -${meta.x}px -${meta.y}px;
|
||||||
height: ${meta.size}px;
|
height: ${meta.size}px;
|
||||||
width: ${meta.size}px;
|
width: ${meta.size}px;
|
||||||
}`
|
}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
setItemMetadata(itemMetadataCache);
|
setItemMetadata(itemMetadataCache);
|
||||||
@@ -46,4 +50,3 @@ export function useItemMetadata() {
|
|||||||
|
|
||||||
return itemMetadata;
|
return itemMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3,16 +3,16 @@ import React, { useEffect, useState } from "react";
|
|||||||
import { useExportManifest } from "./export_manifest";
|
import { useExportManifest } from "./export_manifest";
|
||||||
|
|
||||||
|
|
||||||
let localeCache = null;
|
let localeCache: Map<string, string>|null = null;
|
||||||
export function useLocale() {
|
export function useLocale(): Map<string, string> {
|
||||||
let exportManifest = useExportManifest();
|
let exportManifest = useExportManifest();
|
||||||
let [locale, setLocale] = useState(localeCache || new Map());
|
let [locale, setLocale] = useState<Map<string, string>>(localeCache || new Map());
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
if (!exportManifest || !exportManifest.assets || !exportManifest.assets["locale"]) {
|
if (!exportManifest?.assets?.["locale"]) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let response = await fetch(`${staticRoot}static/${exportManifest.assets["locale"]}`);
|
let response = await fetch(`${window.staticRoot}static/${exportManifest.assets["locale"]}`);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
let data = await response.json();
|
let data = await response.json();
|
||||||
localeCache = new Map(data);
|
localeCache = new Map(data);
|
||||||
@@ -6,9 +6,16 @@ import ControlContext from "../components/ControlContext";
|
|||||||
|
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useModPack(id) {
|
|
||||||
|
export type StateLoadStatus = {
|
||||||
|
loading?: boolean;
|
||||||
|
present?: boolean;
|
||||||
|
missing?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useModPack(id: number) {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [modPack, setModPack] = useState({ loading: true });
|
let [modPack, setModPack] = useState<lib.ModPack|StateLoadStatus>({ loading: true });
|
||||||
|
|
||||||
function updateModPack() {
|
function updateModPack() {
|
||||||
control.send(new lib.ModPackGetRequest(id)).then(updatedModPack => {
|
control.send(new lib.ModPackGetRequest(id)).then(updatedModPack => {
|
||||||
@@ -37,7 +44,7 @@ export function useModPack(id) {
|
|||||||
|
|
||||||
export function useModPackList() {
|
export function useModPackList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [modPackList, setModPackList] = useState([]);
|
let [modPackList, setModPackList] = useState<lib.ModPack[]>([]);
|
||||||
|
|
||||||
function updateModPackList() {
|
function updateModPackList() {
|
||||||
control.send(new lib.ModPackListRequest()).then(modPacks => {
|
control.send(new lib.ModPackListRequest()).then(modPacks => {
|
||||||
@@ -50,7 +57,7 @@ export function useModPackList() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateModPackList();
|
updateModPackList();
|
||||||
|
|
||||||
function updateHandler(newModPack) {
|
function updateHandler(newModPack: lib.ModPack) {
|
||||||
setModPackList(oldList => {
|
setModPackList(oldList => {
|
||||||
let newList = oldList.concat();
|
let newList = oldList.concat();
|
||||||
let index = newList.findIndex(u => u.id === newModPack.id);
|
let index = newList.findIndex(u => u.id === newModPack.id);
|
||||||
@@ -8,7 +8,7 @@ const { logger } = lib;
|
|||||||
|
|
||||||
export function useModList() {
|
export function useModList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [modList, setModList] = useState([]);
|
let [modList, setModList] = useState<lib.ModInfo[]>([]);
|
||||||
|
|
||||||
function updateModList() {
|
function updateModList() {
|
||||||
control.send(new lib.ModListRequest()).then(mods => {
|
control.send(new lib.ModListRequest()).then(mods => {
|
||||||
@@ -21,7 +21,7 @@ export function useModList() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateModList();
|
updateModList();
|
||||||
|
|
||||||
function updateHandler(newMod) {
|
function updateHandler(newMod: lib.ModInfo) {
|
||||||
setModList(oldList => {
|
setModList(oldList => {
|
||||||
let newList = oldList.concat();
|
let newList = oldList.concat();
|
||||||
let index = newList.findIndex(mod => mod.name === newMod.name && mod.version === newMod.version);
|
let index = newList.findIndex(mod => mod.name === newMod.name && mod.version === newMod.version);
|
||||||
@@ -5,12 +5,12 @@ import * as lib from "@clusterio/lib";
|
|||||||
|
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
export function useSaves(instanceId) {
|
export function useSaves(instanceId?: number): lib.SaveDetails[] {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [saves, setSaves] = useState([]);
|
let [saves, setSaves] = useState<lib.SaveDetails[]>([]);
|
||||||
|
|
||||||
function updateSaves() {
|
function updateSaves() {
|
||||||
control.sendTo({ instanceId }, new lib.InstanceListSavesRequest()).then(updatedSaves => {
|
control.sendTo({ instanceId:instanceId! }, new lib.InstanceListSavesRequest()).then(updatedSaves => {
|
||||||
setSaves(updatedSaves);
|
setSaves(updatedSaves);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error(`Failed to list instance saves: ${err}`);
|
logger.error(`Failed to list instance saves: ${err}`);
|
||||||
@@ -25,13 +25,13 @@ export function useSaves(instanceId) {
|
|||||||
}
|
}
|
||||||
updateSaves();
|
updateSaves();
|
||||||
|
|
||||||
function updateHandler(data) {
|
function updateHandler(data: lib.InstanceSaveListUpdateEvent) {
|
||||||
setSaves(data.saves);
|
setSaves(data.saves);
|
||||||
}
|
}
|
||||||
|
|
||||||
control.onSaveListUpdate(instanceId, updateHandler);
|
control.onSaveListUpdate(instanceId!, updateHandler);
|
||||||
return () => {
|
return () => {
|
||||||
control.offSaveListUpdate(instanceId, updateHandler);
|
control.offSaveListUpdate(instanceId!, updateHandler);
|
||||||
};
|
};
|
||||||
}, [instanceId]);
|
}, [instanceId]);
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@ import * as lib from "@clusterio/lib";
|
|||||||
|
|
||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
function calculateLastSeen(user, instanceId) {
|
function calculateLastSeen(user: RawUserState, instanceId?: number) {
|
||||||
let stats;
|
let stats;
|
||||||
if (instanceId === undefined) {
|
if (instanceId === undefined) {
|
||||||
stats = user.playerStats;
|
stats = user.playerStats;
|
||||||
@@ -25,8 +25,8 @@ function calculateLastSeen(user, instanceId) {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatLastSeen(user, instanceId = undefined) {
|
export function formatLastSeen(user: RawUserState, instanceId?: number) {
|
||||||
if (user.instances.some(id => instanceId === undefined || id === instanceId)) {
|
if (user.instances && user.instances.some(id => instanceId === undefined || id === instanceId)) {
|
||||||
return <Tag color="green">Online</Tag>;
|
return <Tag color="green">Online</Tag>;
|
||||||
}
|
}
|
||||||
let lastSeen = calculateLastSeen(user, instanceId);
|
let lastSeen = calculateLastSeen(user, instanceId);
|
||||||
@@ -36,15 +36,15 @@ export function formatLastSeen(user, instanceId = undefined) {
|
|||||||
return new Date(lastSeen).toLocaleString();
|
return new Date(lastSeen).toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sortLastSeen(userA, userB, instanceIdA = undefined, instanceIdB = undefined) {
|
export function sortLastSeen(userA:RawUserState, userB:RawUserState, instanceIdA?: number, instanceIdB?: number) {
|
||||||
function epoch(user, instanceId) {
|
function epoch(user:RawUserState, instanceId?: number) {
|
||||||
return user.instances.some(id => instanceId === undefined || id === instanceId);
|
return user.instances && user.instances.some(id => instanceId === undefined || id === instanceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
let epochA = epoch(userA, instanceIdA);
|
let epochA = epoch(userA, instanceIdA);
|
||||||
let epochB = epoch(userB, instanceIdB);
|
let epochB = epoch(userB, instanceIdB);
|
||||||
if (epochA !== epochB) {
|
if (epochA !== epochB) {
|
||||||
return epochA - epochB;
|
return Number(epochA) - Number(epochB);
|
||||||
}
|
}
|
||||||
|
|
||||||
let lastSeenA = calculateLastSeen(userA, instanceIdA) || 0;
|
let lastSeenA = calculateLastSeen(userA, instanceIdA) || 0;
|
||||||
@@ -52,9 +52,15 @@ export function sortLastSeen(userA, userB, instanceIdA = undefined, instanceIdB
|
|||||||
return lastSeenA - lastSeenB;
|
return lastSeenA - lastSeenB;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUser(name) {
|
export type RawUserState = Partial<lib.RawUser> & {
|
||||||
|
loading?: Boolean;
|
||||||
|
present?: Boolean;
|
||||||
|
missing?: Boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useUser(name: string): [RawUserState, () => void] {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [user, setUser] = useState({ loading: true });
|
let [user, setUser] = useState<RawUserState>({ loading: true });
|
||||||
|
|
||||||
function updateUser() {
|
function updateUser() {
|
||||||
control.send(new lib.UserGetRequest(name)).then(updatedUser => {
|
control.send(new lib.UserGetRequest(name)).then(updatedUser => {
|
||||||
@@ -63,7 +69,6 @@ export function useUser(name) {
|
|||||||
logger.error(`Failed to get user: ${err}`);
|
logger.error(`Failed to get user: ${err}`);
|
||||||
setUser({ missing: true });
|
setUser({ missing: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -73,7 +78,7 @@ export function useUser(name) {
|
|||||||
}
|
}
|
||||||
updateUser();
|
updateUser();
|
||||||
|
|
||||||
function updateHandler(newUser) {
|
function updateHandler(newUser: lib.RawUser) {
|
||||||
setUser({ ...newUser, present: true });
|
setUser({ ...newUser, present: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +93,7 @@ export function useUser(name) {
|
|||||||
|
|
||||||
export function useUserList() {
|
export function useUserList() {
|
||||||
let control = useContext(ControlContext);
|
let control = useContext(ControlContext);
|
||||||
let [userList, setUserList] = useState([]);
|
let [userList, setUserList] = useState<lib.RawUser[]>([]);
|
||||||
|
|
||||||
function updateUserList() {
|
function updateUserList() {
|
||||||
control.send(new lib.UserListRequest()).then(users => {
|
control.send(new lib.UserListRequest()).then(users => {
|
||||||
@@ -101,7 +106,7 @@ export function useUserList() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateUserList();
|
updateUserList();
|
||||||
|
|
||||||
function updateHandler(newUser) {
|
function updateHandler(newUser: lib.RawUser) {
|
||||||
setUserList(oldList => {
|
setUserList(oldList => {
|
||||||
let newList = oldList.concat();
|
let newList = oldList.concat();
|
||||||
let index = newList.findIndex(u => u.name === newUser.name);
|
let index = newList.findIndex(u => u.name === newUser.name);
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import React from "react";
|
import React, { ReactElement } from "react";
|
||||||
|
|
||||||
|
import type * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import ControllerPage from "./components/ControllerPage";
|
import ControllerPage from "./components/ControllerPage";
|
||||||
import HostsPage from "./components/HostsPage";
|
import HostsPage from "./components/HostsPage";
|
||||||
@@ -14,8 +16,7 @@ import RoleViewPage from "./components/RoleViewPage";
|
|||||||
import PluginsPage from "./components/PluginsPage";
|
import PluginsPage from "./components/PluginsPage";
|
||||||
import PluginViewPage from "./components/PluginViewPage";
|
import PluginViewPage from "./components/PluginViewPage";
|
||||||
|
|
||||||
|
export const pages: lib.PluginPage[] = [
|
||||||
export const pages = [
|
|
||||||
{
|
{
|
||||||
path: "/controller",
|
path: "/controller",
|
||||||
sidebarName: "Controller",
|
sidebarName: "Controller",
|
||||||
@@ -46,7 +47,7 @@ export const pages = [
|
|||||||
{
|
{
|
||||||
path: "/mods",
|
path: "/mods",
|
||||||
sidebarName: "Mods",
|
sidebarName: "Mods",
|
||||||
permission: account => account.hasAnyPermission("core.mod.list", "core.mod-pack.list"),
|
permission: (account:lib.UserAccount) => account.hasAnyPermission("core.mod.list", "core.mod-pack.list"),
|
||||||
content: <ModsPage />,
|
content: <ModsPage />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2,9 +2,9 @@ import { useEffect, useState } from "react";
|
|||||||
import { EventEmitter } from "events";
|
import { EventEmitter } from "events";
|
||||||
|
|
||||||
class Permission extends EventEmitter {
|
class Permission extends EventEmitter {
|
||||||
status;
|
status!: { state: string };
|
||||||
|
|
||||||
constructor(name) {
|
constructor(name: PermissionName) {
|
||||||
super();
|
super();
|
||||||
navigator.permissions.query({ name }).then(
|
navigator.permissions.query({ name }).then(
|
||||||
status => {
|
status => {
|
||||||
@@ -30,8 +30,8 @@ class Permission extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let readPermission = new Permission("clipboard-read");
|
let readPermission = new Permission("clipboard-read" as PermissionName);
|
||||||
let writePermission = new Permission("clipboard-write");
|
let writePermission = new Permission("clipboard-write" as PermissionName);
|
||||||
|
|
||||||
// Wrapper for navigator.clipboard suitable for use in React
|
// Wrapper for navigator.clipboard suitable for use in React
|
||||||
export function useClipboard() {
|
export function useClipboard() {
|
||||||
@@ -52,8 +52,8 @@ export function useClipboard() {
|
|||||||
read: async () => await navigator.clipboard.read(),
|
read: async () => await navigator.clipboard.read(),
|
||||||
readText: async () => await navigator.clipboard.readText(),
|
readText: async () => await navigator.clipboard.readText(),
|
||||||
writePermissionState: writePermissionState,
|
writePermissionState: writePermissionState,
|
||||||
write: async (data) => await navigator.clipboard.write(data),
|
write: async (data: ClipboardItems) => await navigator.clipboard.write(data),
|
||||||
writeText: async (text) => await navigator.clipboard.writeText(text),
|
writeText: async (text: string) => await navigator.clipboard.writeText(text),
|
||||||
|
|
||||||
// Give a possible reason for why the clipboard is not available
|
// Give a possible reason for why the clipboard is not available
|
||||||
deniedReason: () => {
|
deniedReason: () => {
|
||||||
@@ -2,7 +2,11 @@ import { notification } from "antd";
|
|||||||
import { logger } from "@clusterio/lib";
|
import { logger } from "@clusterio/lib";
|
||||||
|
|
||||||
|
|
||||||
export default function notify(message, type = "info", description = undefined) {
|
export default function notify(
|
||||||
|
message: string | Error,
|
||||||
|
type: "success"|"info"|"warning"|"error" = "info",
|
||||||
|
description?: string,
|
||||||
|
) {
|
||||||
notification[type]({
|
notification[type]({
|
||||||
message: typeof message === "string" ? message : "ERROR: See console",
|
message: typeof message === "string" ? message : "ERROR: See console",
|
||||||
description,
|
description,
|
||||||
@@ -18,13 +22,13 @@ export default function notify(message, type = "info", description = undefined)
|
|||||||
*
|
*
|
||||||
* Shows the error occuring in a notification card.
|
* Shows the error occuring in a notification card.
|
||||||
*
|
*
|
||||||
* @param {string} message -
|
* @param message -
|
||||||
* User facing message to give context to the error. Should say which
|
* User facing message to give context to the error. Should say which
|
||||||
* operation failed.
|
* operation failed.
|
||||||
* @returns {function(err)} function showing the error passed to it.
|
* @returns function showing the error passed to it.
|
||||||
*/
|
*/
|
||||||
export function notifyErrorHandler(message) {
|
export function notifyErrorHandler(message: string): (err:Error) => void {
|
||||||
return function handler(err) {
|
return function handler(err: Error) {
|
||||||
logger.error(err.stack);
|
logger.error(err.stack);
|
||||||
notification.error({
|
notification.error({
|
||||||
message,
|
message,
|
||||||
@@ -5,11 +5,10 @@ const formatDay = new Intl.NumberFormat(undefined, { style: "unit", unit: "day",
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Formats a duration of time in milliseconds to something human readable.
|
* Formats a duration of time in milliseconds to something human readable.
|
||||||
* @param {number} ms - Duration to formatDuration
|
* @param ms - Duration to formatDuration
|
||||||
* @param {object=} options - Options to control the formatting.
|
* @returns human readable representation of the duration.
|
||||||
* @returns {string} human readable representation of the duration.
|
|
||||||
*/
|
*/
|
||||||
export function formatDuration(ms, options = {}) {
|
export function formatDuration(ms: number): string {
|
||||||
let result = "";
|
let result = "";
|
||||||
if (ms < 0) {
|
if (ms < 0) {
|
||||||
result += "-";
|
result += "-";
|
||||||
@@ -3,15 +3,21 @@ import packageJson from "../../package.json";
|
|||||||
|
|
||||||
const { logFilter, logger } = lib;
|
const { logFilter, logger } = lib;
|
||||||
|
|
||||||
|
type accountHandler = (account: lib.AccountDetails) => void;
|
||||||
|
type hostHandler = (hostDetails: lib.HostDetails) => void;
|
||||||
|
type instanceHandler = (instanceDetails: lib.InstanceDetails) => void;
|
||||||
|
type saveListHandler = (saveListEvent: lib.InstanceSaveListUpdateEvent) => void;
|
||||||
|
type modPackHandler = (modPack: lib.ModPack) => void;
|
||||||
|
type modInfoHandler = (modInfo: lib.ModInfo) => void;
|
||||||
|
type userHandler = (rawUser: lib.RawUser) => void;
|
||||||
|
type logHandler = (info: { level:string, message:string }) => void;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connector for control connection to controller
|
* Connector for control connection to controller
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
export class ControlConnector extends lib.WebSocketClientConnector {
|
export class ControlConnector extends lib.WebSocketClientConnector {
|
||||||
constructor(url, maxReconnectDelay) {
|
token: string | null = null;
|
||||||
super(url, maxReconnectDelay);
|
|
||||||
this.token = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
register() {
|
register() {
|
||||||
if (!this.token) {
|
if (!this.token) {
|
||||||
@@ -38,45 +44,33 @@ export class ControlConnector extends lib.WebSocketClientConnector {
|
|||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
export class Control extends lib.Link {
|
export class Control extends lib.Link {
|
||||||
constructor(connector, plugins) {
|
/** Flag indicating the connection is in the process of logging out. */
|
||||||
|
loggingOut: boolean = false;
|
||||||
|
/** Name of the account this control link is connected as. */
|
||||||
|
accountName: string | null = null;
|
||||||
|
/** Roles of the account this control link is connected as. */
|
||||||
|
accountRoles: lib.AccountRole[] | null = null;
|
||||||
|
accountUpdateHandlers: Function[] = [];
|
||||||
|
hostUpdateHandlers: Map<number|null, hostHandler[]> = new Map();
|
||||||
|
instanceUpdateHandlers: Map<number|null, instanceHandler[]> = new Map();
|
||||||
|
saveListUpdateHandlers: Map<number|null, saveListHandler[]> = new Map();
|
||||||
|
modPackUpdateHandlers: Map<number|null, modPackHandler[]> = new Map();
|
||||||
|
modUpdateHandlers: Map<string|null, modInfoHandler[]> = new Map();
|
||||||
|
userUpdateHandlers: Map<string|null, userHandler[]> = new Map();
|
||||||
|
logHandlers: Map<lib.LogFilter, logHandler[]> = new Map();
|
||||||
|
|
||||||
|
declare connector: ControlConnector;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
connector: ControlConnector,
|
||||||
|
public plugins: Map<string, lib.BaseWebPlugin>,
|
||||||
|
) {
|
||||||
super(connector);
|
super(connector);
|
||||||
|
|
||||||
/**
|
|
||||||
* Mapping of plugin names to their instance for loaded plugins.
|
|
||||||
* @type {Map<string, module:lib.BaseWebPlugin>}
|
|
||||||
*/
|
|
||||||
this.plugins = plugins;
|
|
||||||
for (let plugin of plugins.values()) {
|
for (let plugin of plugins.values()) {
|
||||||
plugin.control = this;
|
plugin.control = this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Flag indicating the connection is in the process of logging out.
|
|
||||||
* @type {boolean}
|
|
||||||
*/
|
|
||||||
this.loggingOut = false;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Name of the account this control link is connected as.
|
|
||||||
* @type {?string}
|
|
||||||
*/
|
|
||||||
this.accountName = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Roles of the account this control link is connected as.
|
|
||||||
* @type {?Array<object>}
|
|
||||||
*/
|
|
||||||
this.accountRoles = null;
|
|
||||||
|
|
||||||
this.accountUpdateHandlers = [];
|
|
||||||
this.hostUpdateHandlers = new Map();
|
|
||||||
this.instanceUpdateHandlers = new Map();
|
|
||||||
this.saveListUpdateHandlers = new Map();
|
|
||||||
this.modPackUpdateHandlers = new Map();
|
|
||||||
this.modUpdateHandlers = new Map();
|
|
||||||
this.userUpdateHandlers = new Map();
|
|
||||||
this.logHandlers = new Map();
|
|
||||||
|
|
||||||
this.connector.on("connect", data => {
|
this.connector.on("connect", data => {
|
||||||
this.accountName = data.account.name;
|
this.accountName = data.account.name;
|
||||||
this.accountRoles = data.account.roles;
|
this.accountRoles = data.account.roles;
|
||||||
@@ -110,7 +104,7 @@ export class Control extends lib.Link {
|
|||||||
this.emitAccountUpdate();
|
this.emitAccountUpdate();
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"]) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
this.connector.on(event, () => {
|
this.connector.on(event, () => {
|
||||||
for (let plugin of this.plugins.values()) {
|
for (let plugin of this.plugins.values()) {
|
||||||
plugin.onControllerConnectionEvent(event);
|
plugin.onControllerConnectionEvent(event);
|
||||||
@@ -129,8 +123,8 @@ export class Control extends lib.Link {
|
|||||||
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleAccountUpdateEvent(event) {
|
async handleAccountUpdateEvent(event: lib.AccountUpdateEvent) {
|
||||||
this.accountRoles = event.roles;
|
this.accountRoles = event.roles??null;
|
||||||
this.emitAccountUpdate();
|
this.emitAccountUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,11 +137,11 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onAccountUpdate(handler) {
|
onAccountUpdate(handler: accountHandler) {
|
||||||
this.accountUpdateHandlers.push(handler);
|
this.accountUpdateHandlers.push(handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
offAccountUpdate(handler) {
|
offAccountUpdate(handler: accountHandler) {
|
||||||
let index = this.accountUpdateHandlers.lastIndexOf(handler);
|
let index = this.accountUpdateHandlers.lastIndexOf(handler);
|
||||||
if (index === -1) {
|
if (index === -1) {
|
||||||
throw new Error("Given handler is not registered for account update");
|
throw new Error("Given handler is not registered for account update");
|
||||||
@@ -155,8 +149,8 @@ export class Control extends lib.Link {
|
|||||||
this.accountUpdateHandlers.splice(index, 1);
|
this.accountUpdateHandlers.splice(index, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleHostUpdateEvent(event) {
|
async handleHostUpdateEvent(event: lib.HostUpdateEvent) {
|
||||||
let handlers = [].concat(
|
let handlers: Function[] = ([] as Function[]).concat(
|
||||||
this.hostUpdateHandlers.get(null) || [],
|
this.hostUpdateHandlers.get(null) || [],
|
||||||
this.hostUpdateHandlers.get(event.update.id) || [],
|
this.hostUpdateHandlers.get(event.update.id) || [],
|
||||||
);
|
);
|
||||||
@@ -165,7 +159,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async onHostUpdate(id, handler) {
|
async onHostUpdate(id: number|null, handler: hostHandler) {
|
||||||
if (id !== null && !Number.isInteger(id)) {
|
if (id !== null && !Number.isInteger(id)) {
|
||||||
throw new Error("Invalid host id");
|
throw new Error("Invalid host id");
|
||||||
}
|
}
|
||||||
@@ -183,7 +177,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offHostUpdate(id, handler) {
|
async offHostUpdate(id: number|null, handler: hostHandler) {
|
||||||
let handlers = this.hostUpdateHandlers.get(id);
|
let handlers = this.hostUpdateHandlers.get(id);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error(`No handlers for host ${id} exists`);
|
throw new Error(`No handlers for host ${id} exists`);
|
||||||
@@ -208,12 +202,12 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.HostSetSubscriptionsRequest(
|
await this.send(new lib.HostSetSubscriptionsRequest(
|
||||||
this.hostUpdateHandlers.has(null),
|
this.hostUpdateHandlers.has(null),
|
||||||
[...this.hostUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.hostUpdateHandlers.keys()].filter(e => e !== null) as number[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceDetailsUpdateEvent(event) {
|
async handleInstanceDetailsUpdateEvent(event: lib.InstanceDetailsUpdateEvent) {
|
||||||
let handlers = [].concat(
|
let handlers = ([] as Function[]).concat(
|
||||||
this.instanceUpdateHandlers.get(null) || [],
|
this.instanceUpdateHandlers.get(null) || [],
|
||||||
this.instanceUpdateHandlers.get(event.details.id) || [],
|
this.instanceUpdateHandlers.get(event.details.id) || [],
|
||||||
);
|
);
|
||||||
@@ -222,7 +216,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async onInstanceUpdate(id, handler) {
|
async onInstanceUpdate(id: number|null, handler: instanceHandler) {
|
||||||
if (id !== null && !Number.isInteger(id)) {
|
if (id !== null && !Number.isInteger(id)) {
|
||||||
throw new Error("Invalid instance id");
|
throw new Error("Invalid instance id");
|
||||||
}
|
}
|
||||||
@@ -240,7 +234,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offInstanceUpdate(id, handler) {
|
async offInstanceUpdate(id: number|null, handler: instanceHandler) {
|
||||||
let handlers = this.instanceUpdateHandlers.get(id);
|
let handlers = this.instanceUpdateHandlers.get(id);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error(`No handlers for instance ${id} exist`);
|
throw new Error(`No handlers for instance ${id} exist`);
|
||||||
@@ -265,18 +259,18 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.InstanceDetailsSetSubscriptionsRequest(
|
await this.send(new lib.InstanceDetailsSetSubscriptionsRequest(
|
||||||
this.instanceUpdateHandlers.has(null),
|
this.instanceUpdateHandlers.has(null),
|
||||||
[...this.instanceUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.instanceUpdateHandlers.keys()].filter(e => e !== null) as number[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleInstanceSaveListUpdateEvent(event) {
|
async handleInstanceSaveListUpdateEvent(event: lib.InstanceSaveListUpdateEvent) {
|
||||||
let handlers = this.saveListUpdateHandlers.get(event.instanceId);
|
let handlers = this.saveListUpdateHandlers.get(event.instanceId);
|
||||||
for (let handler of handlers || []) {
|
for (let handler of handlers || []) {
|
||||||
handler(event);
|
handler(event);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async onSaveListUpdate(id, handler) {
|
async onSaveListUpdate(id: number, handler: saveListHandler) {
|
||||||
if (!Number.isInteger(id)) {
|
if (!Number.isInteger(id)) {
|
||||||
throw new Error("Invalid instance id");
|
throw new Error("Invalid instance id");
|
||||||
}
|
}
|
||||||
@@ -294,7 +288,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offSaveListUpdate(id, handler) {
|
async offSaveListUpdate(id: number, handler: saveListHandler) {
|
||||||
let handlers = this.saveListUpdateHandlers.get(id);
|
let handlers = this.saveListUpdateHandlers.get(id);
|
||||||
if (!handlers) {
|
if (!handlers) {
|
||||||
throw new Error(`No handlers for instance ${id} exists`);
|
throw new Error(`No handlers for instance ${id} exists`);
|
||||||
@@ -319,22 +313,23 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.InstanceSetSaveListSubscriptionsRequest(
|
await this.send(new lib.InstanceSetSaveListSubscriptionsRequest(
|
||||||
false,
|
false,
|
||||||
[...this.saveListUpdateHandlers.keys()],
|
[...this.saveListUpdateHandlers.keys()].filter(e => e !== null) as number[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleModPackUpdateEvent(event) {
|
async handleModPackUpdateEvent(event: lib.ModPackUpdateEvent) {
|
||||||
let modPack = event.modPack;
|
let modPack = event.modPack;
|
||||||
let handlers = [].concat(
|
|
||||||
|
let handlers = ([] as modPackHandler[]).concat(
|
||||||
this.modPackUpdateHandlers.get(null) || [],
|
this.modPackUpdateHandlers.get(null) || [],
|
||||||
this.modPackUpdateHandlers.get(modPack.id) || [],
|
this.modPackUpdateHandlers.get(modPack.id??null) || [],
|
||||||
);
|
);
|
||||||
for (let handler of handlers) {
|
for (let handler of handlers) {
|
||||||
handler(modPack);
|
handler(modPack);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async onModPackUpdate(id, handler) {
|
async onModPackUpdate(id: number|null, handler: modPackHandler) {
|
||||||
if (id !== null && typeof id !== "number") {
|
if (id !== null && typeof id !== "number") {
|
||||||
throw new Error("Invalid mod pack id");
|
throw new Error("Invalid mod pack id");
|
||||||
}
|
}
|
||||||
@@ -352,7 +347,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offModPackUpdate(id, handler) {
|
async offModPackUpdate(id: number|null, handler: modPackHandler) {
|
||||||
let handlers = this.modPackUpdateHandlers.get(id);
|
let handlers = this.modPackUpdateHandlers.get(id);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error(`No handlers for mod pack ${id} exist`);
|
throw new Error(`No handlers for mod pack ${id} exist`);
|
||||||
@@ -377,13 +372,14 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.ModPackSetSubscriptionsRequest(
|
await this.send(new lib.ModPackSetSubscriptionsRequest(
|
||||||
this.modPackUpdateHandlers.has(null),
|
this.modPackUpdateHandlers.has(null),
|
||||||
[...this.modPackUpdateHandlers.keys()].filter(k => k !== null),
|
[...this.modPackUpdateHandlers.keys()]
|
||||||
|
.filter(k => k !== null && k !== undefined) as number[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleModUpdateEvent(event) {
|
async handleModUpdateEvent(event: lib.ModUpdateEvent) {
|
||||||
let mod = event.mod;
|
let mod = event.mod;
|
||||||
let handlers = [].concat(
|
let handlers = ([] as modInfoHandler[]).concat(
|
||||||
this.modUpdateHandlers.get(null) || [],
|
this.modUpdateHandlers.get(null) || [],
|
||||||
this.modUpdateHandlers.get(mod.name) || []
|
this.modUpdateHandlers.get(mod.name) || []
|
||||||
);
|
);
|
||||||
@@ -392,7 +388,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async onModUpdate(name, handler) {
|
async onModUpdate(name: string|null, handler: modInfoHandler) {
|
||||||
if (name !== null && typeof name !== "string") {
|
if (name !== null && typeof name !== "string") {
|
||||||
throw new Error("Invalid mod name");
|
throw new Error("Invalid mod name");
|
||||||
}
|
}
|
||||||
@@ -410,7 +406,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offModUpdate(name, handler) {
|
async offModUpdate(name: string|null, handler: modInfoHandler) {
|
||||||
let handlers = this.modUpdateHandlers.get(name);
|
let handlers = this.modUpdateHandlers.get(name);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error(`No handlers for mod ${name} exist`);
|
throw new Error(`No handlers for mod ${name} exist`);
|
||||||
@@ -435,12 +431,12 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.ModSetSubscriptionsRequest(
|
await this.send(new lib.ModSetSubscriptionsRequest(
|
||||||
this.modUpdateHandlers.has(null),
|
this.modUpdateHandlers.has(null),
|
||||||
[...this.modUpdateHandlers.keys()].filter(k => k !== null),
|
[...this.modUpdateHandlers.keys()].filter(k => k !== null) as string[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleUserUpdateEvent(event) {
|
async handleUserUpdateEvent(event: lib.UserUpdateEvent) {
|
||||||
let handlers = [].concat(
|
let handlers = ([] as userHandler[]).concat(
|
||||||
this.userUpdateHandlers.get(null) || [],
|
this.userUpdateHandlers.get(null) || [],
|
||||||
this.userUpdateHandlers.get(event.user.name) || [],
|
this.userUpdateHandlers.get(event.user.name) || [],
|
||||||
);
|
);
|
||||||
@@ -449,7 +445,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async onUserUpdate(name, handler) {
|
async onUserUpdate(name: string|null, handler: userHandler) {
|
||||||
if (name !== null && typeof name !== "string") {
|
if (name !== null && typeof name !== "string") {
|
||||||
throw new Error("Invalid user name");
|
throw new Error("Invalid user name");
|
||||||
}
|
}
|
||||||
@@ -467,7 +463,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offUserUpdate(name, handler) {
|
async offUserUpdate(name: string|null, handler: userHandler) {
|
||||||
let handlers = this.userUpdateHandlers.get(name);
|
let handlers = this.userUpdateHandlers.get(name);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error(`No handlers for user ${name} exist`);
|
throw new Error(`No handlers for user ${name} exist`);
|
||||||
@@ -492,11 +488,11 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
await this.send(new lib.UserSetSubscriptionsRequest(
|
await this.send(new lib.UserSetSubscriptionsRequest(
|
||||||
this.userUpdateHandlers.has(null),
|
this.userUpdateHandlers.has(null),
|
||||||
[...this.userUpdateHandlers.keys()].filter(e => e !== null),
|
[...this.userUpdateHandlers.keys()].filter(e => e !== null) as string[],
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleLogMessageEvent(event) {
|
async handleLogMessageEvent(event: lib.LogMessageEvent) {
|
||||||
let info = event.info;
|
let info = event.info;
|
||||||
|
|
||||||
for (let [filter, handlers] of this.logHandlers) {
|
for (let [filter, handlers] of this.logHandlers) {
|
||||||
@@ -508,7 +504,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async onLog(filter, handler) {
|
async onLog(filter: lib.LogFilter, handler: logHandler) {
|
||||||
let handlers = this.logHandlers.get(filter);
|
let handlers = this.logHandlers.get(filter);
|
||||||
if (!handlers) {
|
if (!handlers) {
|
||||||
handlers = [];
|
handlers = [];
|
||||||
@@ -522,7 +518,7 @@ export class Control extends lib.Link {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async offLog(filter, handler) {
|
async offLog(filter: lib.LogFilter, handler: logHandler) {
|
||||||
let handlers = this.logHandlers.get(filter);
|
let handlers = this.logHandlers.get(filter);
|
||||||
if (!handlers || !handlers.length) {
|
if (!handlers || !handlers.length) {
|
||||||
throw new Error("No handlers for the given filter exists");
|
throw new Error("No handlers for the given filter exists");
|
||||||
@@ -547,8 +543,8 @@ export class Control extends lib.Link {
|
|||||||
|
|
||||||
let all = false;
|
let all = false;
|
||||||
let controller = false;
|
let controller = false;
|
||||||
let hostIds = [];
|
let hostIds: number[] = [];
|
||||||
let instanceIds = [];
|
let instanceIds: number[] = [];
|
||||||
|
|
||||||
for (let filter of this.logHandlers.keys()) {
|
for (let filter of this.logHandlers.keys()) {
|
||||||
if (filter.all) { all = true; }
|
if (filter.all) { all = true; }
|
||||||
@@ -568,9 +564,9 @@ export class Control extends lib.Link {
|
|||||||
await this.send(new lib.LogSetSubscriptionsRequest(all, controller, hostIds, instanceIds, undefined));
|
await this.send(new lib.LogSetSubscriptionsRequest(all, controller, hostIds, instanceIds, undefined));
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleDebugWsMessageEvent(message) {
|
async handleDebugWsMessageEvent(message: lib.DebugWsMessageEvent) {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.log("WS", message.data.direction, message.data.content);
|
console.log("WS", message.direction, message.content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async shutdown() {
|
async shutdown() {
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"include": [ "src/**/*.tsx", "src/**/*.ts", "package.json", "global.d.ts" ],
|
||||||
|
"compilerOptions": {
|
||||||
|
"jsx": "react",
|
||||||
|
"lib": ["dom", "es2023"],
|
||||||
|
"module": "commonjs",
|
||||||
|
"target": "es2022",
|
||||||
|
"rootDir": "./",
|
||||||
|
"outDir": "dist",
|
||||||
|
"composite": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"strict": true,
|
||||||
|
"alwaysStrict": true,
|
||||||
|
"noImplicitAny": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"noEmitOnError": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -73,6 +73,13 @@ module.exports = (env = {}) => ({
|
|||||||
fullySpecified: false,
|
fullySpecified: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
test: /\.tsx?$/,
|
||||||
|
exclude: /node_modules/,
|
||||||
|
use: {
|
||||||
|
loader: require.resolve("ts-loader"),
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
test: /\.jsx$/,
|
test: /\.jsx$/,
|
||||||
exclude: /node_modules/,
|
exclude: /node_modules/,
|
||||||
@@ -90,7 +97,7 @@ module.exports = (env = {}) => ({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
extensions: [".js", ".json", ".jsx"],
|
extensions: [".js", ".ts", ".json", ".jsx", ".tsx"],
|
||||||
fallback: {
|
fallback: {
|
||||||
"crypto": false,
|
"crypto": false,
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import type { PluginInfo } from "@clusterio/lib";
|
import type * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import { ChatEvent } from "./messages";
|
import { ChatEvent } from "./messages";
|
||||||
|
|
||||||
const info: PluginInfo = {
|
const info: lib.PluginDeclaration = {
|
||||||
name: "global_chat",
|
name: "global_chat",
|
||||||
title: "Global Chat",
|
title: "Global Chat",
|
||||||
description: "Forwards chat between instances.",
|
description: "Forwards chat between instances.",
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ lib.definePermission({
|
|||||||
grantByDefault: true,
|
grantByDefault: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const info: lib.PluginInfo = {
|
const info: lib.PluginDeclaration = {
|
||||||
name: "inventory_sync",
|
name: "inventory_sync",
|
||||||
title: "Inventory sync",
|
title: "Inventory sync",
|
||||||
description: "Synchronizes players inventories between instances",
|
description: "Synchronizes players inventories between instances",
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ ControllerConfigGroup.define({
|
|||||||
});
|
});
|
||||||
ControllerConfigGroup.finalize();
|
ControllerConfigGroup.finalize();
|
||||||
|
|
||||||
const info: lib.PluginInfo = {
|
const info: lib.PluginDeclaration = {
|
||||||
name: "player_auth",
|
name: "player_auth",
|
||||||
title: "Player Auth",
|
title: "Player Auth",
|
||||||
description: "Provides authentication to the cluster via logging into a Factorio server.",
|
description: "Provides authentication to the cluster via logging into a Factorio server.",
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import type { PluginInfo } from "@clusterio/lib";
|
import type * as lib from "@clusterio/lib";
|
||||||
|
|
||||||
import * as messages from "./messages";
|
import * as messages from "./messages";
|
||||||
|
|
||||||
const info: PluginInfo = {
|
const info: lib.PluginDeclaration = {
|
||||||
name: "research_sync",
|
name: "research_sync",
|
||||||
title: "Research Sync",
|
title: "Research Sync",
|
||||||
description: "Synchronises technology research progress between instances.",
|
description: "Synchronises technology research progress between instances.",
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ InstanceConfigGroup.define({
|
|||||||
});
|
});
|
||||||
InstanceConfigGroup.finalize();
|
InstanceConfigGroup.finalize();
|
||||||
|
|
||||||
const info: lib.PluginInfo = {
|
const info: lib.PluginDeclaration = {
|
||||||
name: "statistics_exporter",
|
name: "statistics_exporter",
|
||||||
title: "Statistics Exporter",
|
title: "Statistics Exporter",
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
{ "path": "./packages/controller" },
|
{ "path": "./packages/controller" },
|
||||||
{ "path": "./packages/host" },
|
{ "path": "./packages/host" },
|
||||||
{ "path": "./packages/ctl" },
|
{ "path": "./packages/ctl" },
|
||||||
|
{ "path": "./packages/web_ui" },
|
||||||
{ "path": "./plugins/global_chat" },
|
{ "path": "./plugins/global_chat" },
|
||||||
{ "path": "./plugins/inventory_sync" },
|
{ "path": "./plugins/inventory_sync" },
|
||||||
{ "path": "./plugins/player_auth" },
|
{ "path": "./plugins/player_auth" },
|
||||||
|
|||||||
Reference in new issue
Block a user