Tidy up web interface buttons and labels

Rename save Copy to Duplicate, shorten the save buttons, move Load
scenario into the instance control button and Create template into
More, square off the online players table, show the bind address and
public URL on the controller page, restyle the user settings like the
role page, add a favicon with a controller.favicon_url override, and
put the page name in the tab title.

Closes #1260

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-21 22:03:02 +00:00
1 parent 8865038af5
commit a6b44e78d6
19 files changed
+455 -391

No files matched your search

+8
View File
@@ -126,6 +126,14 @@ This should be a full URL ending with a /.
Defaults to null meaning assume localhost.
### controller.favicon_url
URL of the icon shown in the browser tab.
A relative URL is relative to the web interface root, so `static/icon.png` loads `icon.png` from the `static` folder in the controller's working directory.
Defaults to null meaning use the Clusterio logo.
### controller.static_url
Used to override where static assets such as the web bundle is loaded from.
+14 -1
View File
@@ -48,6 +48,11 @@ const logSizeGauge = new Gauge(
type InstanceId = { instanceId: number };
const htmlEscapes: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" };
function escapeHtml(text: string) {
return text.replace(/[&<>"']/g, char => htmlEscapes[char]);
}
type ControllerDebugEvents = {
"message": [ { direction: "in" | "out", content: string } ],
};
@@ -1720,8 +1725,16 @@ export default class Controller {
path.join(import.meta.dirname, "..", "..", "..", "web", "index.html"),
"utf8",
).then(async (content) => {
const config: lib.ControllerConfig = res.app.locals.controller.config;
let faviconUrl = config.get("controller.favicon_url");
// Relative to the web root rather than the page
if (faviconUrl && !/^([a-z][a-z0-9+.-]*:|\/)/i.test(faviconUrl)) {
faviconUrl = webRoot + faviconUrl;
}
const favicon = faviconUrl ? `<link rel="icon" href="${escapeHtml(faviconUrl)}" />` : "";
content = content
.replace(/__CLUSTER_NAME__/g, res.app.locals.controller.config.get("controller.name"))
.replace(/__CLUSTER_NAME__/g, () => escapeHtml(config.get("controller.name")))
.replace(/__FAVICON__/g, () => favicon)
.replace(/__WEB_ROOT__/g, webRoot)
.replace(/__STATIC_ROOT__/g, staticRoot)
.replace(/__IMPORT_MAP__/g, () => importMap)
+2
View File
@@ -4,7 +4,9 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#2a2a2a" />
<meta name="application-name" content="__CLUSTER_NAME__" />
<title>__CLUSTER_NAME__</title>
__FAVICON__
<script type="importmap">__IMPORT_MAP__</script>
<style>
html {
+7
View File
@@ -19,6 +19,7 @@ export interface ControllerConfigFields {
"controller.bind_address": string | null;
"controller.trusted_proxies": string | null;
"controller.public_url": string | null;
"controller.favicon_url": string | null;
"controller.static_url": string | null;
"controller.grafana_url": string | null;
"controller.tls_certificate": string | null;
@@ -177,6 +178,12 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
optional: true,
// TODO extendedValidation, valid url including the protocol
},
"controller.favicon_url": {
title: "Favicon URL",
description: "URL of the icon shown in the browser tab, defaults to the Clusterio logo.",
type: "string",
optional: true,
},
"controller.static_url": {
title: "Static URL",
description: "Override the URL to where static assets are hosted (must have a path consisting of /static/)",
+8
View File
@@ -15,6 +15,7 @@ import { loadedPluginSetKey } from "./util/pluginSet";
import { pageActionsFromHooks } from "./util/plugin_actions";
import * as WebPlugin from "./BaseWebPlugin";
import { pages } from "./pages";
import logo from "./images/logo.png";
const { ConsoleTransport, WebConsoleFormat, logger } = lib;
@@ -190,6 +191,13 @@ async function pagesFromHooks(control: Control) {
}
export default async function bootstrap() {
// The controller adds a link when controller.favicon_url is set
if (!document.querySelector("link[rel=icon]")) {
const icon = document.createElement("link");
icon.rel = "icon";
icon.href = logo;
document.head.appendChild(icon);
}
logger.add(new ConsoleTransport({
level: "verbose",
format: new WebConsoleFormat(),
@@ -1,4 +1,4 @@
import React, {useContext, useState} from "react";
import React, { useContext, useEffect, useState } from "react";
import { Descriptions, Flex, Modal, Popconfirm, Space, Tooltip, Typography } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
@@ -108,12 +108,49 @@ function ControllerControlButton({ canRestart, restartRequired }: ControllerCont
}
function formatListen(config: lib.ControllerConfig) {
let address = config.get("controller.bind_address") || "*";
if (address.includes(":")) {
address = `[${address}]`;
}
const listen = [];
for (const protocol of ["http", "https"] as const) {
const port = config.get(`controller.${protocol}_port`);
if (port) {
listen.push(`${protocol}://${address}:${port}`);
}
}
return listen.join(", ");
}
function useControllerConfig() {
const account = useAccount();
const control = useContext(ControlContext);
const [config, setConfig] = useState<lib.ControllerConfig>();
const canConfig = account.hasPermission("core.controller.get_config");
useEffect(() => {
if (!canConfig) {
return undefined;
}
let canceled = false;
control.send(new lib.ControllerConfigGetRequest()).then(serialized => {
if (!canceled) {
setConfig(lib.ControllerConfig.fromJSON(serialized, "control"));
}
}).catch(notifyErrorHandler("Error loading controller config"));
return () => { canceled = true; };
}, [control, canConfig]);
return config;
}
export default function ControllerPage() {
const account = useAccount();
const [systems] = useSystems();
const system = systems.get("controller");
const [maxLevel, setMaxLevel] = useState<keyof typeof lib.levels>("info");
const canShowNpm = hasNpmButtonPermission(true);
const config = useControllerConfig();
return <PageLayout nav={[{ name: "Controller" }]}>
<PageHeader
@@ -138,7 +175,8 @@ export default function ControllerPage() {
<Descriptions.Item label="Process Uptime">
<MetricRelativeDate timeMs={system?.processStartedAtMs}/>
</Descriptions.Item>
<Descriptions.Item label="Hostname" span={2}>{system?.hostname}</Descriptions.Item>
<Descriptions.Item label="Hostname" span={config ? 1 : 2}>{system?.hostname}</Descriptions.Item>
{config && <Descriptions.Item label="Bind Address">{formatListen(config)}</Descriptions.Item>}
<Descriptions.Item label="CPU Model" span={2}>{system?.cpuModel}</Descriptions.Item>
<Descriptions.Item label="CPU Usage"><MetricCpuRatio system={system} /></Descriptions.Item>
<Descriptions.Item label="Cores"><MetricCpuUsed system={system} /></Descriptions.Item>
@@ -146,6 +184,9 @@ export default function ControllerPage() {
<Descriptions.Item label="Memory"><MetricMemoryUsed system={system} /></Descriptions.Item>
<Descriptions.Item label="Disk Usage"><MetricDiskRatio system={system} /></Descriptions.Item>
<Descriptions.Item label="Disk"><MetricDiskUsed system={system} /></Descriptions.Item>
{config && <Descriptions.Item label="Public URL">
{config.get("controller.public_url") || <em>Not set</em>}
</Descriptions.Item>}
</Descriptions>
{account.hasPermission("core.log.follow") && <>
<Flex justify="space-between" align="baseline">
@@ -96,7 +96,7 @@ export default function CreateSaveModal(props: CreateSaveModalProps) {
setOpen(true);
}}
>
Create save
Create
</Button>
<Modal
title="Create Save"
@@ -0,0 +1,9 @@
import React from "react";
/** Label and control laid out on one line */
export default function FieldRow(props: { label: React.ReactNode, children: React.ReactNode }) {
return <div style={{ marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
<label style={{ width: 110, flexShrink: 0 }}>{props.label}</label>
{props.children}
</div>;
}
@@ -11,6 +11,8 @@ import VariableDropdownButton, { VariableDropdownButtonProps } from "./VariableD
type InstanceControlButtonProps = Omit<VariableDropdownButtonProps, "actions"> & {
instance: lib.InstanceDetails;
onFinish?: () => void;
/** Added to the dropdown before Kill */
extraActions?: VariableDropdownButtonProps["actions"];
};
export const InstanceControlButtonPermissions = [
@@ -23,8 +25,9 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
const [switching, setSwitching] = useState<boolean>(false);
const [popconfirm, setPopconfirm] = useState<string | null>(null);
const instanceId = props.instance.id;
const instanceStatus = props.instance.status;
const { instance, onFinish, extraActions, ...buttonProps } = props;
const instanceId = instance.id;
const instanceStatus = instance.status;
// While starting or stopping the button shows the action in progress as loading.
const showStart = ["stopped", "starting"].includes(instanceStatus);
const showStop = ["running", "stopping"].includes(instanceStatus);
@@ -32,8 +35,8 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
function actionFinish() {
setSwitching(false);
if (props.onFinish) {
props.onFinish();
if (onFinish) {
onFinish();
}
}
@@ -88,6 +91,8 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
});
}
actions.push(...extraActions ?? []);
if (account.hasPermission("core.instance.kill")) {
actions.push({
key: "kill",
@@ -100,7 +105,7 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
return <div style={{ position: "relative", display: "inline-block" }}>
<VariableDropdownButton
{...props}
{...buttonProps}
type="primary"
actions={actions}
loading={switching || transitioning}
@@ -27,7 +27,7 @@ import SavesList from "./SavesList";
import OnlinePlayersList from "./OnlinePlayersList";
import { notifyErrorHandler } from "../util/notify";
import { useInstance, useInstances } from "../model/instance";
import { CreateInstanceButton } from "./InstancesPage";
import { CreateInstanceButton, CreateInstanceModal } from "./InstancesPage";
import { useHost } from "../model/host";
import InstanceStatusTag from "./InstanceStatusTag";
import Link from "./Link";
@@ -146,6 +146,7 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
let control = useContext(ControlContext);
let navigate = useNavigate();
let [exportingData, setExportingData] = useState(false);
const [modal, setModal] = useState<"scenario" | "template">();
let instance = props.instance;
let instanceId = instance.id!;
let [host] = useHost(instance.assignedHost);
@@ -154,6 +155,9 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
const pluginActions = usePluginActions("InstanceViewPage", { instance });
let instanceButtonMenuItems: MenuItem[] = [];
if (canCreate) {
instanceButtonMenuItems.push({ key: "template", label: "Create template" });
}
if (account.hasPermission("core.instance.export_data")) {
instanceButtonMenuItems.push({
disabled: exportingData || instance.status !== "stopped",
@@ -199,7 +203,9 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
let instanceButtonsMenuProps: MenuProps = {
items: instanceButtonMenuItems,
onClick: ({ key }: { key: string }) => {
if (key === "export") {
if (key === "template") {
setModal("template");
} else if (key === "export") {
setExportingData(true);
control.sendTo(
{ instanceId },
@@ -240,10 +246,19 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
</Space>;
}
const canLoadScenario = account.hasPermission("core.instance.load_scenario");
return <Space wrap>
{
account.hasAnyPermission(...InstanceControlButtonPermissions)
&& <InstanceControlButton instance={instance} />
account.hasAnyPermission(...InstanceControlButtonPermissions, "core.instance.load_scenario")
&& <InstanceControlButton
instance={instance}
extraActions={canLoadScenario ? [{
key: "scenario",
label: "Load scenario",
disabled: instance.status !== "stopped",
onClick: () => setModal("scenario"),
}] : []}
/>
}
<Button
onClick={() => {
@@ -256,17 +271,21 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
>
Connect via Steam
</Button>
{account.hasPermission("core.instance.load_scenario") && <LoadScenarioModal instance={instance} />}
{canCreate && <CreateInstanceButton
instances={instances}
initial={{ instanceClone: instanceId, asTemplate: true, linkSource: true }}
buttonText="Create template"
buttonType="default"
/>}
{instanceButtonMenuItems.length > 0
&& <Dropdown placement="bottomRight" trigger={["click"]} menu={instanceButtonsMenuProps}>
<Button>More <DownOutlined /></Button>
</Dropdown>}
{canLoadScenario && <LoadScenarioModal
instance={instance}
open={modal === "scenario"}
onClose={() => setModal(undefined)}
/>}
{canCreate && <CreateInstanceModal
instances={instances}
initial={{ instanceClone: instanceId, asTemplate: true, linkSource: true }}
open={modal === "template"}
onClose={() => setModal(undefined)}
/>}
</Space>;
}
@@ -97,10 +97,28 @@ export function CreateInstanceButton({ buttonText = "Create", buttonType = "prim
buttonType?: "primary" | "default";
buttonSize?: "small";
}) {
const [open, setOpen] = useState(false);
return <>
<Button type={buttonType} size={props.buttonSize} onClick={() => setOpen(true)}>{buttonText}</Button>
<CreateInstanceModal
instances={props.instances}
initial={props.initial}
open={open}
onClose={() => setOpen(false)}
/>
</>;
}
export function CreateInstanceModal(props: {
instances: ReturnType<typeof useInstances>[0];
initial?: CreateInstanceInitial;
open: boolean;
onClose: () => void;
}) {
const { open } = props;
let control = useContext(ControlContext);
let account = useAccount();
let navigate = useNavigate();
let [open, setOpen] = useState(false);
let [creating, setCreating] = useState(false);
let [form] = Form.useForm();
let [hosts] = useHosts();
@@ -190,100 +208,91 @@ export function CreateInstanceButton({ buttonText = "Create", buttonType = "prim
} finally {
setCreating(false);
if (created) {
setOpen(false);
props.onClose();
navigate(`/instances/${instanceId}/view`);
}
}
}
return <>
<Button
type={buttonType}
size={props.buttonSize}
onClick={() => {
setOpen(true);
return <Modal
title={asTemplate ? "Create Template" : "Create Instance"}
okText="Create"
open={open}
confirmLoading={creating}
onOk={() => { createInstance().catch(notifyErrorHandler("Error creating instance")); }}
onCancel={props.onClose}
destroyOnHidden
>
<Form
form={form}
initialValues={{
host: "null", instanceClone: -1, saveMode: "none", startAfter: false,
template: null, asTemplate: false, linkSource: true, ...props.initial,
}}
>{buttonText}</Button>
<Modal
title={asTemplate ? "Create Template" : "Create Instance"}
okText="Create"
open={open}
confirmLoading={creating}
onOk={() => { createInstance().catch(notifyErrorHandler("Error creating instance")); }}
onCancel={() => { setOpen(false); }}
destroyOnHidden
>
<Form
form={form}
initialValues={{
host: "null", instanceClone: -1, saveMode: "none", startAfter: false,
template: null, asTemplate: false, linkSource: true, ...props.initial,
}}
<Form.Item name="instanceName" label="Name">
<Input />
</Form.Item>
<Tooltip title="Templates hold shared config for other instances and cannot be started">
<Form.Item name="asTemplate" valuePropName="checked">
<Checkbox>Create as template</Checkbox>
</Form.Item>
</Tooltip>
{canAssign && !asTemplate && <Form.Item name="host" label="Host">
<Select showSearch optionFilterProp="name">
<Select.Option value={"null"}>
<Typography.Text italic>Unassigned</Typography.Text>
</Select.Option>
{[...hosts.values()].sort((a, b) => strcmp(a.name, b.name)).map(h => <Select.Option
key={h.id}
value={h.id}
name={h.name}
disabled={!h.connected}
>
{h.name}
{!h.connected && " (offline)"}
</Select.Option>)}
</Select>
</Form.Item>}
<ConfigSourceFields
instances={props.instances}
templateId={templateId}
source={source}
asTemplate={asTemplate}
/>
{copySettings && <Tooltip
title="Name of the server as shown in the in-game server browser"
>
<Form.Item name="instanceName" label="Name">
<Form.Item name="serverName" label="Server Name">
<Input />
</Form.Item>
<Tooltip title="Templates hold shared config for other instances and cannot be started">
<Form.Item name="asTemplate" valuePropName="checked">
<Checkbox>Create as template</Checkbox>
</Form.Item>
</Tooltip>
{canAssign && !asTemplate && <Form.Item name="host" label="Host">
<Select showSearch optionFilterProp="name">
<Select.Option value={"null"}>
<Typography.Text italic>Unassigned</Typography.Text>
</Select.Option>
{[...hosts.values()].sort((a, b) => strcmp(a.name, b.name)).map(h => <Select.Option
key={h.id}
value={h.id}
name={h.name}
disabled={!h.connected}
>
{h.name}
{!h.connected && " (offline)"}
</Select.Option>)}
</Select>
</Form.Item>}
<ConfigSourceFields
instances={props.instances}
templateId={templateId}
source={source}
asTemplate={asTemplate}
</Tooltip>}
{source && hostId !== undefined && <Form.Item name="saveMode" label="Copy Save">
<Select
options={[
{ value: "none", label: "None" },
{
value: "copy",
label: activeSave ? `Copy ${activeSave.name}` : "Copy active save",
disabled: !activeSave,
},
{
value: "save_and_copy",
label: "Save the running game and copy it",
disabled: !sourceRunning || !activeSave,
},
]}
/>
{copySettings && <Tooltip
title="Name of the server as shown in the in-game server browser"
>
<Form.Item name="serverName" label="Server Name">
<Input />
</Form.Item>
</Tooltip>}
{source && hostId !== undefined && <Form.Item name="saveMode" label="Copy Save">
<Select
options={[
{ value: "none", label: "None" },
{
value: "copy",
label: activeSave ? `Copy ${activeSave.name}` : "Copy active save",
disabled: !activeSave,
},
{
value: "save_and_copy",
label: "Save the running game and copy it",
disabled: !sourceRunning || !activeSave,
},
]}
/>
</Form.Item>}
{hostId !== undefined && <Form.Item
name="startAfter"
valuePropName="checked"
extra={saveMode === "none" ? "A new save is created if none is copied" : undefined}
>
<Checkbox>Start after creation</Checkbox>
</Form.Item>}
</Form>
</Modal>
</>;
</Form.Item>}
{hostId !== undefined && <Form.Item
name="startAfter"
valuePropName="checked"
extra={saveMode === "none" ? "A new save is created if none is copied" : undefined}
>
<Checkbox>Start after creation</Checkbox>
</Form.Item>}
</Form>
</Modal>;
}
function TemplateList(props: { instances: ReturnType<typeof useInstances>[0] }) {
@@ -8,9 +8,10 @@ import { notifyErrorHandler } from "../util/notify";
type LoadScenarioModalProps = {
instance: lib.InstanceDetails;
open: boolean;
onClose: () => void;
};
export default function LoadScenarioModal(props: LoadScenarioModalProps) {
let [open, setOpen] = useState(false);
let [loadingScenario, setLoadingScenario] = useState(false);
let [form] = Form.useForm();
let control = useContext(ControlContext);
@@ -57,7 +58,7 @@ export default function LoadScenarioModal(props: LoadScenarioModalProps) {
{ instanceId: props.instance.id },
new lib.InstanceLoadScenarioRequest(scenario, seed, mapGenSettings, mapSettings),
).then(() => {
setOpen(false);
props.onClose();
}).catch(
notifyErrorHandler("Error loading scenario")
).finally(() => {
@@ -81,58 +82,43 @@ export default function LoadScenarioModal(props: LoadScenarioModalProps) {
});
}
function handleCancel() {
setOpen(false);
}
return <>
<Button
loading={loadingScenario}
disabled={props.instance.status !== "stopped"}
onClick={() => {
setOpen(true);
}}
>
Load scenario
</Button>
<Modal
title="Load Scenario"
width={560}
okText="Load"
open={open}
confirmLoading={loadingScenario}
onOk={loadScenario}
onCancel={handleCancel}
destroyOnHidden
>
<Form form={form} layout="vertical">
<Form.Item name="scenario" label="Scenario">
<Input placeholder="base/freeplay" />
</Form.Item>
<Form.Item name="seed" label="Seed">
<Input type="number" />
</Form.Item>
<Form.Item name="exchangeString" label="Map Exchange String">
<Input.TextArea allowClear={true} autoSize={{ minRows: 3 }} />
</Form.Item>
<div style={{ textAlign: "right", marginTop: -8 }}>
<Button onClick={() => convertExchangeString()}>Convert to settings</Button>
</div>
<Form.Item
name="mapGenSettings"
label="Map Gen Settings"
tooltip="JSON data to pass to Factorio with --map-gen-settings, overrides Map Exchange String"
>
<Input.TextArea allowClear={true} autoSize={{ minRows: 1 }} />
</Form.Item>
<Form.Item
name="mapSettings"
label="Map Settings"
tooltip="JSON data to pass to Factorio with --map-settings, overrides Map Exchange String"
>
<Input.TextArea allowClear={true} autoSize={{ minRows: 1 }} />
</Form.Item>
</Form>
</Modal>
</>;
return <Modal
title="Load Scenario"
width={560}
okText="Load"
open={props.open}
confirmLoading={loadingScenario}
onOk={loadScenario}
onCancel={props.onClose}
destroyOnHidden
>
<Form form={form} layout="vertical">
<Form.Item name="scenario" label="Scenario">
<Input placeholder="base/freeplay" />
</Form.Item>
<Form.Item name="seed" label="Seed">
<Input type="number" />
</Form.Item>
<Form.Item name="exchangeString" label="Map Exchange String">
<Input.TextArea allowClear={true} autoSize={{ minRows: 3 }} />
</Form.Item>
<div style={{ textAlign: "right", marginTop: -8 }}>
<Button onClick={() => convertExchangeString()}>Convert to settings</Button>
</div>
<Form.Item
name="mapGenSettings"
label="Map Gen Settings"
tooltip="JSON data to pass to Factorio with --map-gen-settings, overrides Map Exchange String"
>
<Input.TextArea allowClear={true} autoSize={{ minRows: 1 }} />
</Form.Item>
<Form.Item
name="mapSettings"
label="Map Settings"
tooltip="JSON data to pass to Factorio with --map-settings, overrides Map Exchange String"
>
<Input.TextArea allowClear={true} autoSize={{ minRows: 1 }} />
</Form.Item>
</Form>
</Modal>;
}
@@ -1,5 +1,5 @@
import React, { useState } from "react";
import { Collapse } from "antd";
import { Collapse, ConfigProvider } from "antd";
import { useUsers } from "../model/user";
import UsersTable from "./UsersTable";
@@ -24,12 +24,15 @@ export default function OnlinePlayersList({ instanceId }: OnlinePlayersListProps
items={[{
key: "players",
label: `Online Players (${onlineCount})`,
children: <UsersTable instanceId={instanceId} onlyOnline size="small" pagination={{
defaultPageSize: 10,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100", "200"],
showTotal: (total: number) => `${total} Users`,
}} />,
styles: { body: { padding: 0 } },
children: <ConfigProvider theme={{ components: { Table: { headerBorderRadius: 0 } } }}>
<UsersTable instanceId={instanceId} onlyOnline size="small" pagination={{
defaultPageSize: 10,
showSizeChanger: true,
pageSizeOptions: ["10", "20", "50", "100", "200"],
showTotal: (total: number) => `${total} Users`,
}} />
</ConfigProvider>,
}]}
/>;
}
+13 -1
View File
@@ -1,4 +1,4 @@
import React from "react";
import React, { useEffect } from "react";
import { Layout, Breadcrumb } from "antd";
import Link from "./Link";
@@ -11,7 +11,19 @@ type PageLayoutProps = {
}[];
children?: any;
};
function clusterName() {
const meta = document.querySelector<HTMLMetaElement>("meta[name=application-name]");
return meta?.content || "Clusterio";
}
export default function PageLayout(props: PageLayoutProps) {
const page = props.nav.at(-1)?.name;
useEffect(() => {
const name = clusterName();
document.title = page ? `${page} - ${name}` : name;
return () => { document.title = name; };
}, [page]);
return <>
<Breadcrumb
className="site-breadcrumb"
@@ -9,6 +9,8 @@ import { useRole } from "../model/roles";
import { useAccount } from "../model/account";
import ControlContext from "./ControlContext";
import PageHeader from "./PageHeader";
import UnsavedChangesBar from "./UnsavedChangesBar";
import FieldRow from "./FieldRow";
import PageLayout from "./PageLayout";
import PluginExtra from "./PluginExtra";
import ResourceNotes from "./ResourceNotes";
@@ -292,46 +294,15 @@ export default function RoleViewPage() {
</Space>}
/>
{edited && (
<div style={{
position: "fixed",
bottom: 24,
left: "50%",
transform: "translateX(-50%)",
background: "#2a1912",
borderRadius: 8,
boxShadow: "0 8px 24px rgba(0,0,0,0.12)",
padding: "10px 14px",
display: "flex",
alignItems: "center",
gap: 12,
zIndex: 1000,
}}>
<span style={{ color: "#FFF" }}>
You have unsaved changes
</span>
{edited && <UnsavedChangesBar onRevert={revertChanges} onApply={applyChanges} />}
<Space>
<Button onClick={revertChanges}>
Revert
</Button>
<Button type="primary" onClick={applyChanges}>
Apply
</Button>
</Space>
</div>
)}
<div style={{ marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
<label style={{ width: 110, flexShrink: 0 }}>Name</label>
<FieldRow label="Name">
<Input value={name} disabled={!canUpdate} onChange={e => setNameEdit(e.target.value)} />
</div>
</FieldRow>
<div style={{ marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
<label style={{ width: 110, flexShrink: 0 }}>Description</label>
<FieldRow label="Description">
<Input value={description} disabled={!canUpdate} onChange={e => setDescriptionEdit(e.target.value)} />
</div>
</FieldRow>
<ResourceNotes resourceType="role" resourceId={roleId} />
+8 -10
View File
@@ -69,16 +69,16 @@ function RenameModal(props: ModalProps) {
</>;
}
function CopyModal(props: ModalProps) {
function DuplicateModal(props: ModalProps) {
let control = useContext(ControlContext);
let [open, setOpen] = useState(false);
let [form] = Form.useForm();
return <>
<Button disabled={props.disabled} onClick={() => setOpen(true)}>Copy</Button>
<Button disabled={props.disabled} onClick={() => setOpen(true)}>Duplicate</Button>
<Modal
title="Copy save"
okText="Copy"
title="Duplicate save"
okText="Duplicate"
open={open}
onOk={() => form.submit()}
onCancel={() => setOpen(false)}
@@ -93,7 +93,7 @@ function CopyModal(props: ModalProps) {
).then(() => {
setOpen(false);
form.resetFields();
}).catch(notifyErrorHandler("Error copying save"));
}).catch(notifyErrorHandler("Error duplicating save"));
}}
>
<Form.Item
@@ -383,11 +383,11 @@ export default function SavesList(props: { instance: lib.InstanceDetails }) {
() => { setStarting(false); }
);
}}
>Load save</Button>}
>Load</Button>}
{account.hasPermission("core.instance.save.rename") && <RenameModal
disabled={hostOffline} instanceId={props.instance.id!} save={save}
/>}
{account.hasPermission("core.instance.save.copy") && <CopyModal
{account.hasPermission("core.instance.save.copy") && <DuplicateModal
disabled={hostOffline} instanceId={props.instance.id!} save={save}
/>}
{account.hasPermission("core.instance.save.download") && <Button
@@ -444,9 +444,7 @@ export default function SavesList(props: { instance: lib.InstanceDetails }) {
onDone={setSelectedNames}
/>}
{account.hasPermission("core.instance.save.upload") && <Upload {...uploadProps} >
<UploadButton disabled={hostOffline}>
Upload save
</UploadButton>
<UploadButton disabled={hostOffline} icon={null} />
</Upload>}
{account.hasPermission("core.instance.save.create") && <CreateSaveModal instance={props.instance} />}
</Space>} />
@@ -0,0 +1,40 @@
import React from "react";
import { Button, Space } from "antd";
type UnsavedChangesBarProps = {
onRevert: () => void;
onApply: () => void;
applying?: boolean;
};
/** Floating bar shown while a page has edits that are not applied yet */
export default function UnsavedChangesBar(props: UnsavedChangesBarProps) {
return <div style={{
position: "fixed",
bottom: 24,
left: "50%",
transform: "translateX(-50%)",
background: "#2a1912",
borderRadius: 8,
boxShadow: "0 8px 24px rgba(0,0,0,0.12)",
padding: "10px 14px",
display: "flex",
alignItems: "center",
gap: 12,
zIndex: 1000,
}}>
<span style={{ color: "#FFF" }}>
You have unsaved changes
</span>
<Space>
<Button onClick={props.onRevert}>
Revert
</Button>
<Button type="primary" loading={props.applying} onClick={props.onApply}>
Apply
</Button>
</Space>
</div>;
}
@@ -7,6 +7,8 @@ import { DraggingContext } from "../model/is_dragging";
export default function UploadButton(props: React.ComponentProps<typeof Button>) {
const isDroppingFile = useContext(DraggingContext);
const borderColor = props.disabled ? "gray" : "rgb(22, 119, 255)";
// Pass icon={null} for no icon
const icon = props.icon === undefined ? <UploadOutlined /> : props.icon;
return <Button
className={`dropzone ${props.disabled ? "disabled" : "enabled"}`}
{...props}
@@ -15,7 +17,7 @@ export default function UploadButton(props: React.ComponentProps<typeof Button>)
// Distinct border when dropping file
border: isDroppingFile ? `dashed 2px ${borderColor}` : undefined,
}}
icon={isDroppingFile ? <InboxOutlined /> : props.icon || <UploadOutlined />}
icon={isDroppingFile ? <InboxOutlined /> : icon}
>
{props.children || "Upload"}
</Button>;
+107 -176
View File
@@ -1,8 +1,7 @@
import React, { useEffect, useContext, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
Button, Col, Descriptions, Dropdown, Form, Input, Popconfirm,
Row, Table, Tag, Select, Space, Switch,
Button, Descriptions, Dropdown, Input, Popconfirm, Table, Tag, Select, Space, Switch,
} from "antd";
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
import DownOutlined from "@ant-design/icons/DownOutlined";
@@ -14,12 +13,14 @@ import useTableQueryState from "../util/useTableQueryState";
import { useAccount } from "../model/account";
import { useInstances } from "../model/instance";
import ControlContext from "./ControlContext";
import FieldRow from "./FieldRow";
import PageHeader from "./PageHeader";
import PageLayout from "./PageLayout";
import PluginExtra from "./PluginExtra";
import SectionHeader from "./SectionHeader";
import ResourceNotes from "./ResourceNotes";
import ResourceState from "./ResourceState";
import UnsavedChangesBar from "./UnsavedChangesBar";
import useRowNavigation from "../util/useRowNavigation";
import useResourceState from "../util/useResourceState";
import usePluginActions from "../util/usePluginActions";
@@ -30,6 +31,10 @@ import { formatFirstSeen, formatLastSeen, sortFirstSeen, sortLastSeen, useUser }
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
function sameIds(ids: number[], set: Set<number>) {
return ids.length === set.size && ids.every(id => set.has(id));
}
function UserPluginActions(props: { user: lib.UserDetails }) {
const pluginActions = usePluginActions("UserViewPage", { user: props.user });
@@ -57,66 +62,59 @@ export default function UserViewPage() {
const [user, synced, error] = useUser(userName);
const state = useResourceState(user, synced, error, userName);
let [roles, rolesSynced] = useRoles();
let [form] = Form.useForm();
const statsTable = useTableQueryState<[number, lib.PlayerStats]>({
namespace: "stats", defaultSortKey: "instance",
});
let [rolesDirty, setRolesDirty] = useState<boolean>(false);
let [banReasonDirty, setBanReasonDirty] = useState<boolean>(false);
let [applyingRoles, setApplyingRoles] = useState<boolean>(false);
let [rolesError, setRolesError] = useState<string|undefined>();
// Local edits on top of the live user
const [rolesEdit, setRolesEdit] = useState<number[]>();
const [banReasonEdit, setBanReasonEdit] = useState<string>();
const [applying, setApplying] = useState(false);
const canUpdateRoles = account.hasPermission("core.user.update_roles");
const canBan = account.hasPermission("core.user.set_banned");
// Drop edits that now match the user, and roles deleted since
useEffect(() => {
if (
account.hasPermission("core.user.set_banned")
&& !banReasonDirty
&& user
&& user.banReason !== form.getFieldValue("banReason")
) {
form.setFieldsValue({ "banReason": user.banReason });
}
}, [account, form, user, banReasonDirty]);
useEffect(() => {
if (!user || !account.hasPermission("core.user.update_roles")) {
if (!user) {
return;
}
const current: number[] = form.getFieldValue("roles") ?? [];
// Keep local edits, but drop roles deleted since
const next = rolesDirty
? current.filter(id => !rolesSynced || roles.has(id))
: [...user.roleIds];
if (next.length !== current.length || next.some((id, i) => id !== current[i])) {
form.setFieldsValue({ "roles": next });
}
}, [account, form, user, roles, rolesSynced, rolesDirty]);
setRolesEdit(prev => {
const next = prev?.filter(id => !rolesSynced || roles.has(id));
return next && sameIds(next, user.roleIds) ? undefined : next;
});
setBanReasonEdit(prev => (prev === user.banReason ? undefined : prev));
}, [user, roles, rolesSynced]);
useEffect(() => {
setRolesEdit(undefined);
setBanReasonEdit(undefined);
}, [userName]);
let nav = [{ name: "Users", path: "/users" }, { name: userName }];
if (!user) {
return <ResourceState state={state} type="User" id={userName} nav={nav} listPath="/users" error={error} />;
}
let roleSelector = <Form.Item
noStyle
name="roles"
initialValue={[...user.roleIds]}
rules={[
{ validator: () => (rolesError ? Promise.reject(rolesError) : Promise.resolve()) },
]}
>
<Select
onChange={() => setRolesDirty(true)}
loading={!roles}
mode="multiple"
optionFilterProp="name"
>
{[...roles.values()].map(r => <Select.Option
key={r.id}
value={r.id}
name={r.name}
>{r.name}</Select.Option>)}
</Select>
</Form.Item>;
const roleIds = rolesEdit ?? [...user.roleIds];
const banReason = banReasonEdit ?? user.banReason;
const rolesChanged = rolesEdit !== undefined && !sameIds(rolesEdit, user.roleIds);
// Only a banned user has a ban reason to update, otherwise it is used by the Banned switch
const banReasonChanged = user.isBanned && banReason !== user.banReason;
function revertChanges() {
setRolesEdit(undefined);
setBanReasonEdit(undefined);
}
async function applyChanges() {
if (rolesChanged) {
await control.send(new lib.UserUpdateRolesRequest(userName, roleIds));
setRolesEdit(undefined);
}
if (banReasonChanged) {
await control.send(new lib.UserSetBannedRequest(userName, false, true, banReason));
setBanReasonEdit(undefined);
}
}
function instanceName(id: number) {
return instances.get(id)?.name ?? String(id);
@@ -182,134 +180,67 @@ export default function UserViewPage() {
<UserPluginActions user={user} />
</Space>}
/>
<Form
form={form}
labelCol={{
sm: { span: 6 },
md: { span: 6 },
lg: { span: 4 },
xl: { span: 3 },
xxl: { span: 2 },
{(rolesChanged || banReasonChanged) && <UnsavedChangesBar
applying={applying}
onRevert={revertChanges}
onApply={() => {
setApplying(true);
applyChanges()
.catch(notifyErrorHandler("Error applying changes"))
.finally(() => setApplying(false));
}}
wrapperCol={{
sm: { span: 18 },
md: { span: 18 },
lg: { span: 20 },
xl: { span: 21 },
xxl: { span: 22 },
}}
>
<Form.Item
label="Roles"
>
<Row gutter={[8, 8]}>
<Col flex="auto">
{account.hasPermission("core.user.update_roles")
? roleSelector
: [...user.roleIds!].map(id => <Tag key={id}>{
roles?.get(id)?.name ?? id
}</Tag>)
}
</Col>
{account.hasPermission("core.user.update_roles") && <Col flex="0 0 auto">
<Button
type={"primary"}
disabled={!rolesDirty}
loading={applyingRoles}
onClick={() => {
let newRoles = form.getFieldValue("roles");
setApplyingRoles(true);
control.send(
new lib.UserUpdateRolesRequest(userName, newRoles)
).then(() => {
setRolesDirty(false);
setRolesError(undefined);
}).catch(err => {
setRolesError(err.message);
return form.validateFields();
}).finally(() => {
setApplyingRoles(false);
});
}}
>Apply</Button>
</Col>}
</Row>
</Form.Item>
{account.hasPermission("core.user.set_admin") && <Form.Item label="In-game Admin">
<Switch
checked={user.isAdmin}
onClick={() => {
control.send(
new lib.UserSetAdminRequest(userName, false, !user.isAdmin)
).catch(notifyErrorHandler("Error toggling user admin status"));
}}
/>
</Form.Item>}
{account.hasPermission("core.user.set_whitelisted") && <Form.Item label="Whitelisted">
<Switch
checked={user.isWhitelisted}
onClick={() => {
control.send(
new lib.UserSetWhitelistedRequest(userName, false, !user.isWhitelisted)
).catch(notifyErrorHandler("Error toggling user whitelisted status"));
}}
/>
</Form.Item>}
{account.hasPermission("core.user.set_banned")
? <Form.Item label="Ban reason">
<Row gutter={[8, 8]} justify={"end"}>
<Col flex="auto" style={{ minWidth: "20em" }}>
<Form.Item noStyle name="banReason" initialValue={user.banReason}>
<Input
onChange={e => {
setBanReasonDirty(e.target.value !== user.banReason);
}}
/>
</Form.Item>
</Col>
<Col flex="0 0 auto">
{user.isBanned
? <Space>
<Button
type={banReasonDirty ? "primary" : "default"}
onClick={() => {
control.send(
new lib.UserSetBannedRequest(
userName, false, true, form.getFieldValue("banReason")
)
).then(() => {
setBanReasonDirty(false);
}).catch(notifyErrorHandler("Error updating ban"));
}}
>Update</Button>
<Button
onClick={() => {
control.send(
new lib.UserSetBannedRequest(userName, false, false, "")
).catch(notifyErrorHandler("Error unbanning user"));
}}
>Unban</Button>
</Space>
: <Button
type={banReasonDirty ? "primary" : "default"}
onClick={() => {
control.send(
new lib.UserSetBannedRequest(
userName, false, true, form.getFieldValue("banReason")
)
).then(() => {
setBanReasonDirty(false);
}).catch(notifyErrorHandler("Error banning user"));
}}
>Ban</Button>
}
</Col>
</Row>
</Form.Item>
: user.isBanned
&& <Form.Item label="Ban reason">{user.banReason}</Form.Item>
}
</Form>
/>}
<FieldRow label="Roles">
<Select
style={{ width: "100%" }}
mode="multiple"
disabled={!canUpdateRoles}
value={roleIds}
onChange={setRolesEdit}
optionFilterProp="label"
options={[...roles.values()].map(r => ({ value: r.id, label: r.name }))}
/>
</FieldRow>
{account.hasPermission("core.user.set_admin") && <FieldRow label="In-game Admin">
<Switch
checked={user.isAdmin}
onClick={() => {
control.send(
new lib.UserSetAdminRequest(userName, false, !user.isAdmin)
).catch(notifyErrorHandler("Error toggling user admin status"));
}}
/>
</FieldRow>}
{account.hasPermission("core.user.set_whitelisted") && <FieldRow label="Whitelisted">
<Switch
checked={user.isWhitelisted}
onClick={() => {
control.send(
new lib.UserSetWhitelistedRequest(userName, false, !user.isWhitelisted)
).catch(notifyErrorHandler("Error toggling user whitelisted status"));
}}
/>
</FieldRow>}
{canBan && <FieldRow label="Banned">
<Switch
checked={user.isBanned}
onClick={() => {
control.send(new lib.UserSetBannedRequest(
userName, false, !user.isBanned, user.isBanned ? "" : banReason
)).then(() => {
setBanReasonEdit(undefined);
}).catch(notifyErrorHandler(user.isBanned ? "Error unbanning user" : "Error banning user"));
}}
/>
</FieldRow>}
{(canBan || user.isBanned) && <FieldRow label="Ban reason">
<Input
value={banReason}
disabled={!canBan}
placeholder={user.isBanned ? undefined : "Reason given when the user is banned"}
onChange={e => setBanReasonEdit(e.target.value)}
/>
</FieldRow>}
<ResourceNotes resourceType="user" resourceId={user.id} />
<SectionHeader title="Player stats" />
<Descriptions size="small" bordered column={{ xs: 1, sm: 2, md: 2, lg: 2, xl: 2, xxl: 2 }}>