mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-18 07:33:12 +09:00
Rename bases to templates and add per property inheritance
Review changes for #1142: - base becomes template everywhere (is_template, template_id, --template, --is-template, --templates, InstanceDetails.isTemplate). - Object fields inherit per property. inherited_fields lists the overridden properties for object fields and the template object is merged with them. - Linking a template also inherits fields that hold the default value. The server name stays per instance. - Ports are never inherited. - InstanceDetails carries templateId. Web UI: inherited values are locked until unlocked, overridden values can be inherited again, templates are listed separately, the create modal can create templates and instances from templates, and the instance page has "Create template" which can link the source. Part of #200 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
01cf789f5d
commit
b5c372f109
21 files changed
+865
-312
No files matched your search
@@ -8,6 +8,7 @@ import * as lib from "@clusterio/lib";
|
||||
import App from "./components/App";
|
||||
import InputRole from "./components/InputRole";
|
||||
import InputModPack from "./components/InputModPack";
|
||||
import { InputInstanceTemplate } from "./components/InputInstance";
|
||||
import { InputTargetVersion, InputPartialVersion, InputFullVersion } from "./components/InputVersion";
|
||||
import { Control, ControlConnector } from "./util/websocket";
|
||||
import { loadedPluginSetKey } from "./util/pluginSet";
|
||||
@@ -148,6 +149,7 @@ async function inputComponentsFromHooks(control: Control) {
|
||||
"target_version": InputTargetVersion,
|
||||
"mod_pack": InputModPack,
|
||||
"role": InputRole,
|
||||
"instance_template": InputInstanceTemplate,
|
||||
}]);
|
||||
|
||||
const iterable = result.map(
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import {
|
||||
Button, Card, Checkbox, Form, FormInstance, Input, InputNumber, Select, Space, Spin, Tooltip, Tree, Typography,
|
||||
Button, Card, Checkbox, Form, FormInstance, Input, InputNumber, Popconfirm, Select, Space, Spin, Tooltip, Tree,
|
||||
Typography,
|
||||
} from "antd";
|
||||
import LockOutlined from "@ant-design/icons/LockOutlined";
|
||||
import ReloadOutlined from "@ant-design/icons/ReloadOutlined";
|
||||
import UnlockOutlined from "@ant-design/icons/UnlockOutlined";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
@@ -65,8 +68,24 @@ function renderInput(inputComponents: Map<string, InputComponent>, def: lib.Fiel
|
||||
return `Unknown type ${def.type}`;
|
||||
}
|
||||
|
||||
/** Lets fields follow the value of another config, inherited values are locked until unlocked */
|
||||
export type ConfigInheritance = {
|
||||
canInherit: (config: lib.Config<any>, field: string) => boolean;
|
||||
isInherited: (config: lib.Config<any>, field: string, prop?: string) => boolean;
|
||||
inherit: (field: string, prop?: string) => Promise<void>;
|
||||
notice?: (config: lib.Config<any>) => React.ReactNode;
|
||||
};
|
||||
|
||||
type LockState = {
|
||||
inheritance?: ConfigInheritance;
|
||||
unlocked: Set<string>;
|
||||
setUnlocked: (unlocked: Set<string>) => void;
|
||||
inherit: (field: string, prop?: string) => void;
|
||||
};
|
||||
|
||||
type BaseConfigTreeProps = {
|
||||
ConfigClass: typeof lib.ControllerConfig | typeof lib.HostConfig | typeof lib.InstanceConfig;
|
||||
inheritance?: ConfigInheritance;
|
||||
retrieveConfig: () => Promise<lib.ConfigSchema>;
|
||||
setConfig: (fields: Record<string, string | Record<string, string>>) => Promise<void>;
|
||||
id?: number;
|
||||
@@ -79,6 +98,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
let [changedFields, setChangedFields] = useState<Set<string>>(new Set());
|
||||
let [errorFields, setErrorFields] = useState(new Map<string, string>());
|
||||
let [applying, setApplying] = useState(false);
|
||||
let [unlocked, setUnlocked] = useState<Set<string>>(new Set());
|
||||
const available = props.available ?? true;
|
||||
const control = useContext(ControlContext);
|
||||
|
||||
@@ -136,6 +156,17 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
}
|
||||
}
|
||||
|
||||
function inherit(field: string, prop?: string) {
|
||||
props.inheritance!.inherit(field, prop).then(async () => {
|
||||
const newConfig = await updateConfig();
|
||||
const values = getInitialValues(newConfig, props);
|
||||
const keys = Object.keys(values).filter(key => key === field || key.startsWith(`${field}.`));
|
||||
form.resetFields(keys);
|
||||
form.setFieldsValue(Object.fromEntries(keys.map(key => [key, values[key]])));
|
||||
setChangedFields(fields => new Set([...fields].filter(key => !keys.includes(key))));
|
||||
}).catch(err => notify(err.message, "error"));
|
||||
}
|
||||
|
||||
const [propsMap, treeData] = computeTreeData(
|
||||
control,
|
||||
form,
|
||||
@@ -145,6 +176,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
setConfig,
|
||||
props.ConfigClass,
|
||||
onValuesChange,
|
||||
{ inheritance: props.inheritance, unlocked, setUnlocked, inherit },
|
||||
);
|
||||
|
||||
return <>
|
||||
@@ -179,14 +211,21 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
}
|
||||
}
|
||||
|
||||
let applied = false;
|
||||
try {
|
||||
await props.setConfig(fields);
|
||||
setChangedFields(new Set());
|
||||
setUnlocked(new Set());
|
||||
applied = true;
|
||||
} catch (err: any) {
|
||||
notify(err.message, "error");
|
||||
}
|
||||
|
||||
await updateConfig();
|
||||
const newConfig = await updateConfig();
|
||||
if (applied) {
|
||||
// Linking a template can change other values
|
||||
form.setFieldsValue(getInitialValues(newConfig, props));
|
||||
}
|
||||
setApplying(false);
|
||||
|
||||
if (props.onApply) {
|
||||
@@ -202,6 +241,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
onClick={() => {
|
||||
form.resetFields();
|
||||
setChangedFields(new Set());
|
||||
setUnlocked(new Set());
|
||||
setErrorFields(new Map());
|
||||
}}
|
||||
>
|
||||
@@ -210,6 +250,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) {
|
||||
</Space>
|
||||
</Title>
|
||||
<Card size="small" className="config-container">
|
||||
{props.inheritance?.notice?.(config)}
|
||||
<Form
|
||||
size="small"
|
||||
form={form}
|
||||
@@ -237,6 +278,7 @@ function computeTreeData(
|
||||
setConfig: (newConfig: lib.Config<any>) => void,
|
||||
ConfigClass: BaseConfigTreeProps["ConfigClass"],
|
||||
onValuesChange: (changedValues: object) => void,
|
||||
lock: LockState,
|
||||
) {
|
||||
let restartTip = <Tooltip
|
||||
className="ant-form-item-tooltip"
|
||||
@@ -254,6 +296,47 @@ function computeTreeData(
|
||||
children: ChildNode[];
|
||||
};
|
||||
|
||||
function lockButton(key: string, fieldName: string, prop?: string) {
|
||||
const { inheritance, unlocked, setUnlocked } = lock;
|
||||
if (!inheritance?.canInherit(config, fieldName) || !config.canAccess(fieldName, lib.ConfigAccess.write)) {
|
||||
return null;
|
||||
}
|
||||
if (inheritance.isInherited(config, fieldName, prop)) {
|
||||
if (!unlocked.has(key)) {
|
||||
return <Tooltip title="Inherited from the template. Click to unlock and override it.">
|
||||
<Button
|
||||
type="text" size="small" icon={<LockOutlined />} aria-label={`Unlock ${key}`}
|
||||
onClick={() => setUnlocked(new Set([...unlocked, key]))}
|
||||
/>
|
||||
</Tooltip>;
|
||||
}
|
||||
return <Tooltip title="Unlocked, applying a change overrides the template. Click to lock it again.">
|
||||
<Button
|
||||
type="text" size="small" icon={<UnlockOutlined />} aria-label={`Lock ${key}`}
|
||||
onClick={() => {
|
||||
setUnlocked(new Set([...unlocked].filter(k => k !== key)));
|
||||
form.setFieldValue(key, initialValues[key]);
|
||||
onValuesChange({ [key]: initialValues[key] });
|
||||
}}
|
||||
/>
|
||||
</Tooltip>;
|
||||
}
|
||||
return <Popconfirm
|
||||
title="Discard this value and inherit it from the template?"
|
||||
okText="Inherit"
|
||||
onConfirm={() => lock.inherit(fieldName, prop)}
|
||||
>
|
||||
<Tooltip title="Overrides the template. Click to inherit it again.">
|
||||
<Button type="text" size="small" icon={<UnlockOutlined />} aria-label={`Inherit ${key}`} danger />
|
||||
</Tooltip>
|
||||
</Popconfirm>;
|
||||
}
|
||||
function isReadonly(canWrite: boolean, key: string, fieldName: string, prop?: string) {
|
||||
return !canWrite || Boolean(lock.inheritance?.canInherit(config, fieldName))
|
||||
&& lock.inheritance!.isInherited(config, fieldName, prop)
|
||||
&& !lock.unlocked.has(key);
|
||||
}
|
||||
|
||||
let treeData = [];
|
||||
const propsMap = new Map<string, [fieldName: string, prop: string]>();
|
||||
const groups = new Map<string, { [name: string]: lib.FieldDefinition }>();
|
||||
@@ -312,6 +395,7 @@ function computeTreeData(
|
||||
label={<>
|
||||
{`"${prop}"`}
|
||||
{restart && restartTip}
|
||||
{lockButton(propPath, fieldName, prop)}
|
||||
</>}
|
||||
dependencies={def.dependsOn}
|
||||
rules={[({getFieldValue}) => ({ validator: async (_, fieldValue) => {
|
||||
@@ -345,7 +429,7 @@ function computeTreeData(
|
||||
def.validator(fieldValue, config.staging);
|
||||
}})]}
|
||||
>
|
||||
<Input className="json-input" disabled={!canWrite} />
|
||||
<Input className="json-input" disabled={isReadonly(canWrite, propPath, fieldName, prop)} />
|
||||
</Form.Item>,
|
||||
});
|
||||
|
||||
@@ -382,6 +466,7 @@ function computeTreeData(
|
||||
}
|
||||
|
||||
let propPath = `${groupName}.${field}.${propName}`;
|
||||
lock.setUnlocked(new Set([...lock.unlocked, propPath]));
|
||||
form.setFieldsValue({
|
||||
[`${newPropPath}.name`]: "",
|
||||
[`${newPropPath}.value`]: "",
|
||||
@@ -407,6 +492,7 @@ function computeTreeData(
|
||||
label={<>
|
||||
{def.title || field}
|
||||
{def.restartRequired && restartTip}
|
||||
{lockButton(fieldName, fieldName)}
|
||||
</>}
|
||||
validateStatus={errorFields.has(fieldName) ? "error" : undefined}
|
||||
help={errorFields.get(fieldName)}
|
||||
@@ -436,7 +522,7 @@ function computeTreeData(
|
||||
},
|
||||
})]}
|
||||
>
|
||||
{renderInput(control.inputComponents, def, !canWrite)}
|
||||
{renderInput(control.inputComponents, def, isReadonly(canWrite, fieldName, fieldName))}
|
||||
</Form.Item>;
|
||||
initialValues[fieldName] = value;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useInstances } from "../model/instance";
|
||||
|
||||
interface BaseInputInstanceProps extends InputComponentProps {
|
||||
includeAll?: boolean;
|
||||
templates?: boolean;
|
||||
}
|
||||
|
||||
function BaseInputInstance(props: BaseInputInstanceProps) {
|
||||
@@ -12,7 +13,9 @@ function BaseInputInstance(props: BaseInputInstanceProps) {
|
||||
|
||||
const options = [
|
||||
...(props.includeAll ? [{ label: "All instances", value: null }] : []),
|
||||
...[...instances.values()].map(instance => ({
|
||||
...[...instances.values()].filter(
|
||||
instance => Boolean(instance.isTemplate) === Boolean(props.templates)
|
||||
).map(instance => ({
|
||||
label: instance.name ?? `Instance ${instance.id}`,
|
||||
value: instance.id,
|
||||
})),
|
||||
@@ -40,3 +43,7 @@ export function InputInstanceWithAll(props: InputComponentProps) {
|
||||
export function InputInstance(props: InputComponentProps) {
|
||||
return <BaseInputInstance {...props} />;
|
||||
}
|
||||
|
||||
export function InputInstanceTemplate(props: InputComponentProps) {
|
||||
return <BaseInputInstance {...props} templates />;
|
||||
}
|
||||
@@ -1,15 +1,32 @@
|
||||
import React, { useContext } from "react";
|
||||
import { Alert } from "antd";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import BaseConfigTree from "./BaseConfigTree";
|
||||
import BaseConfigTree, { ConfigInheritance } from "./BaseConfigTree";
|
||||
import ControlContext from "./ControlContext";
|
||||
import Link from "./Link";
|
||||
import { useInstance } from "../model/instance";
|
||||
|
||||
|
||||
type InstanceConfigTreeProps = {
|
||||
id: number;
|
||||
};
|
||||
|
||||
function TemplateNotice(props: { templateId: number }) {
|
||||
const [template] = useInstance(props.templateId);
|
||||
return <Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 8 }}
|
||||
message={<>
|
||||
Locked values are inherited from the template{" "}
|
||||
<Link to={`/instances/${props.templateId}/view`}>{template?.name ?? props.templateId}</Link>.
|
||||
Unlock a value to override it on this instance.
|
||||
</>}
|
||||
/>;
|
||||
}
|
||||
|
||||
export default function InstanceConfigTree(props: InstanceConfigTreeProps) {
|
||||
let control = useContext(ControlContext);
|
||||
|
||||
@@ -21,10 +38,26 @@ export default function InstanceConfigTree(props: InstanceConfigTreeProps) {
|
||||
await control.send(new lib.InstanceConfigSetRequest(props.id, fields));
|
||||
}
|
||||
|
||||
const inheritance: ConfigInheritance = {
|
||||
canInherit: (config, field) => (
|
||||
(config as lib.InstanceConfig).get("instance.template_id") !== null
|
||||
&& lib.InstanceConfig.isInheritable(field)
|
||||
),
|
||||
isInherited: (config, field, prop) => (config as lib.InstanceConfig).isInherited(field, prop),
|
||||
inherit: async (field, prop) => {
|
||||
await control.send(new lib.InstanceConfigInheritFieldRequest(props.id, field, prop));
|
||||
},
|
||||
notice: (config) => {
|
||||
const templateId = (config as lib.InstanceConfig).get("instance.template_id");
|
||||
return templateId !== null ? <TemplateNotice templateId={templateId} /> : null;
|
||||
},
|
||||
};
|
||||
|
||||
return <BaseConfigTree
|
||||
ConfigClass={lib.InstanceConfig}
|
||||
retrieveConfig={retrieveConfig}
|
||||
setConfig={setConfig}
|
||||
inheritance={inheritance}
|
||||
id={props.id}
|
||||
/>;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ type InstanceListProps = {
|
||||
instances: ReadonlyMap<number, Readonly<lib.InstanceDetails>>;
|
||||
size?: SizeType;
|
||||
hideAssignedHost?: boolean;
|
||||
tableNamespace?: string;
|
||||
};
|
||||
|
||||
export default function InstanceList(props: InstanceListProps) {
|
||||
@@ -30,7 +31,7 @@ export default function InstanceList(props: InstanceListProps) {
|
||||
let [hosts] = useHosts();
|
||||
const [systems] = useSystems();
|
||||
const tableState = useTableQueryState<lib.InstanceDetails>({
|
||||
namespace: "instance", defaultSortKey: "name",
|
||||
namespace: props.tableNamespace ?? "instance", defaultSortKey: "name",
|
||||
});
|
||||
const nameSearch = useColumnSearch<lib.InstanceDetails>(
|
||||
tableState, "name", instance => instance.name, "Search instances"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import {
|
||||
Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Tooltip, Typography,
|
||||
Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Tag, Tooltip, Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import CopyOutlined from "@ant-design/icons/CopyOutlined";
|
||||
@@ -26,7 +26,8 @@ import LoadScenarioModal from "./LoadScenarioModal";
|
||||
import SavesList from "./SavesList";
|
||||
import OnlinePlayersList from "./OnlinePlayersList";
|
||||
import { notifyErrorHandler } from "../util/notify";
|
||||
import { useInstance } from "../model/instance";
|
||||
import { useInstance, useInstances } from "../model/instance";
|
||||
import { CreateInstanceButton } from "./InstancesPage";
|
||||
import { useHost } from "../model/host";
|
||||
import InstanceStatusTag from "./InstanceStatusTag";
|
||||
import Link from "./Link";
|
||||
@@ -45,6 +46,28 @@ type InstanceDescriptionProps = {
|
||||
host?: Readonly<lib.HostDetails>;
|
||||
instance: Readonly<lib.InstanceDetails>;
|
||||
};
|
||||
function TemplateDescription(props: { instance: Readonly<lib.InstanceDetails> }) {
|
||||
const [instances] = useInstances();
|
||||
const inheritors = [...instances.values()].filter(i => i.templateId === props.instance.id);
|
||||
return <Descriptions bordered size="small" column={1}>
|
||||
<Descriptions.Item label="Inherited by">
|
||||
{inheritors.length
|
||||
? <Space wrap>
|
||||
{inheritors.map(i => <Link key={i.id} to={`/instances/${i.id}/view`}>{i.name}</Link>)}
|
||||
</Space>
|
||||
: <em>No instances</em>}
|
||||
</Descriptions.Item>
|
||||
{props.instance.templateId !== undefined && <Descriptions.Item label="Template">
|
||||
<TemplateLink id={props.instance.templateId} />
|
||||
</Descriptions.Item>}
|
||||
</Descriptions>;
|
||||
}
|
||||
|
||||
function TemplateLink(props: { id: number }) {
|
||||
const [template] = useInstance(props.id);
|
||||
return <Link to={`/instances/${props.id}/view`}>{template?.name ?? props.id}</Link>;
|
||||
}
|
||||
|
||||
function InstanceDescription(props: InstanceDescriptionProps) {
|
||||
let account = useAccount();
|
||||
|
||||
@@ -97,6 +120,9 @@ function InstanceDescription(props: InstanceDescriptionProps) {
|
||||
<Descriptions.Item label="Last Start Time">
|
||||
<MetricRelativeDate timeMs={instance.startedAtMs}/>
|
||||
</Descriptions.Item>
|
||||
{instance.templateId !== undefined && <Descriptions.Item label="Template">
|
||||
<TemplateLink id={instance.templateId} />
|
||||
</Descriptions.Item>}
|
||||
</Descriptions>;
|
||||
}
|
||||
|
||||
@@ -108,6 +134,8 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
|
||||
let instance = props.instance;
|
||||
let instanceId = instance.id!;
|
||||
let [host] = useHost(instance.assignedHost);
|
||||
const [instances] = useInstances();
|
||||
const canCreate = account.hasPermission("core.instance.create");
|
||||
|
||||
let instanceButtonMenuItems: MenuItem[] = [];
|
||||
if (account.hasPermission("core.instance.export_data")) {
|
||||
@@ -136,6 +164,21 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
|
||||
label: "Delete",
|
||||
});
|
||||
}
|
||||
function confirmDelete() {
|
||||
Modal.confirm({
|
||||
autoFocusButton: "cancel",
|
||||
content: "Permamently delete instance and server saves?",
|
||||
okText: "Delete",
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => {
|
||||
control.send(
|
||||
new lib.InstanceDeleteRequest(instanceId)
|
||||
).then(() => {
|
||||
navigate("/instances");
|
||||
}).catch(notifyErrorHandler("Error deleting instance"));
|
||||
},
|
||||
});
|
||||
}
|
||||
let instanceButtonsMenuProps: MenuProps = {
|
||||
items: instanceButtonMenuItems,
|
||||
onClick: ({ key }: { key: string }) => {
|
||||
@@ -157,22 +200,25 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) {
|
||||
).catch(notifyErrorHandler("Error extracting player data"));
|
||||
|
||||
} else if (key === "delete") {
|
||||
Modal.confirm({
|
||||
autoFocusButton: "cancel",
|
||||
content: "Permamently delete instance and server saves?",
|
||||
okText: "Delete",
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => {
|
||||
control.send(
|
||||
new lib.InstanceDeleteRequest(instanceId)
|
||||
).then(() => {
|
||||
navigate("/instances");
|
||||
}).catch(notifyErrorHandler("Error deleting instance"));
|
||||
},
|
||||
});
|
||||
confirmDelete();
|
||||
}
|
||||
},
|
||||
};
|
||||
if (instance.isTemplate) {
|
||||
return <Space wrap>
|
||||
{canCreate && <CreateInstanceButton
|
||||
instances={instances}
|
||||
initial={{ template: instanceId }}
|
||||
buttonText="Create instance from template"
|
||||
/>}
|
||||
{account.hasPermission("core.instance.delete") && <Button
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={confirmDelete}
|
||||
>Delete</Button>}
|
||||
</Space>;
|
||||
}
|
||||
|
||||
return <Space wrap>
|
||||
{
|
||||
account.hasAnyPermission(...InstanceControlButtonPermissions)
|
||||
@@ -190,6 +236,12 @@ 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"
|
||||
/>}
|
||||
{account.hasAnyPermission(
|
||||
"core.instance.export_data",
|
||||
"core.instance.extract_players",
|
||||
@@ -224,11 +276,16 @@ export default function InstanceViewPage() {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader
|
||||
title={instance.name ?? ""}
|
||||
status={<InstanceStatusTag status={instance.status} />}
|
||||
status={instance.isTemplate
|
||||
? <Tag color="purple">Template</Tag>
|
||||
: <InstanceStatusTag status={instance.status} />}
|
||||
extra={<InstanceButtons instance={instance} />}
|
||||
/>
|
||||
<InstanceDescription host={host} instance={instance} />
|
||||
{instance.isTemplate
|
||||
? <TemplateDescription instance={instance} />
|
||||
: <InstanceDescription host={host} instance={instance} />}
|
||||
<ResourceNotes resourceType="instance" resourceId={instanceId} />
|
||||
{!instance.isTemplate && <>
|
||||
|
||||
{account.hasPermission("core.user.list") && <OnlinePlayersList instanceId={instanceId} />}
|
||||
|
||||
@@ -275,6 +332,7 @@ export default function InstanceViewPage() {
|
||||
account.hasPermission("core.instance.send_rcon")
|
||||
&& <InstanceRcon id={instanceId} disabled={instance.status !== "running"} />
|
||||
}
|
||||
</>}
|
||||
|
||||
{account.hasPermission("core.instance.get_config") && <InstanceConfigTree id={instanceId} />}
|
||||
|
||||
|
||||
@@ -14,12 +14,85 @@ import { useInstanceConfig, useInstances } from "../model/instance";
|
||||
import { useSaves } from "../model/saves";
|
||||
import InstanceList from "./InstanceList";
|
||||
import { notifyErrorHandler } from "../util/notify";
|
||||
import type { Control } from "../util/websocket";
|
||||
|
||||
type SaveMode = "none" | "copy" | "save_and_copy";
|
||||
|
||||
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||
|
||||
function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances>[0] }) {
|
||||
function ConfigSourceFields(props: {
|
||||
instances: ReturnType<typeof useInstances>[0];
|
||||
templateId?: number | null;
|
||||
source?: Readonly<lib.InstanceDetails>;
|
||||
asTemplate: boolean;
|
||||
}) {
|
||||
const templates = [...props.instances.values()].filter(i => i.isTemplate);
|
||||
const hasTemplate = typeof props.templateId === "number";
|
||||
return <>
|
||||
{(templates.length > 0 || hasTemplate) && <Tooltip
|
||||
title="Inherit config from a template, later changes to the template apply to this instance too"
|
||||
>
|
||||
<Form.Item name="template" label="Template">
|
||||
<Select
|
||||
disabled={props.source !== undefined}
|
||||
options={[{ value: null, label: "None" }, ...templates.map(i => ({ value: i.id, label: i.name }))]}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Tooltip>}
|
||||
<Tooltip title="Perform a one time copy of the config of an existing instance">
|
||||
<Form.Item name="instanceClone" label="Copy Config">
|
||||
<Select
|
||||
disabled={hasTemplate}
|
||||
options={[
|
||||
{ id: -1, name: "Default Config" },
|
||||
...[...props.instances.values()].filter(i => !i.isTemplate),
|
||||
].map(i => ({ value: i.id, label: i.name }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Tooltip>
|
||||
{props.asTemplate && props.source && <Form.Item name="linkSource" valuePropName="checked">
|
||||
<Checkbox>Make {props.source.name} inherit from the new template</Checkbox>
|
||||
</Form.Item>}
|
||||
</>;
|
||||
}
|
||||
|
||||
async function linkToTemplate(control: Control, source: lib.InstanceDetails | undefined, templateId: number) {
|
||||
if (source) {
|
||||
await control.send(new lib.InstanceConfigSetFieldRequest(
|
||||
source.id, "instance.template_id", String(templateId),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
function setTemplateFields(
|
||||
config: lib.InstanceConfig,
|
||||
fields: (keyof lib.InstanceConfigFields)[],
|
||||
templateId: unknown,
|
||||
asTemplate: boolean,
|
||||
) {
|
||||
if (typeof templateId === "number") {
|
||||
config.set("instance.template_id", templateId);
|
||||
fields.push("instance.template_id");
|
||||
}
|
||||
if (asTemplate) {
|
||||
config.set("instance.is_template", true);
|
||||
fields.push("instance.is_template");
|
||||
}
|
||||
}
|
||||
|
||||
type CreateInstanceInitial = {
|
||||
instanceClone?: number;
|
||||
template?: number;
|
||||
asTemplate?: boolean;
|
||||
linkSource?: boolean;
|
||||
};
|
||||
|
||||
export function CreateInstanceButton({ buttonText = "Create", buttonType = "primary", ...props }: {
|
||||
instances: ReturnType<typeof useInstances>[0];
|
||||
initial?: CreateInstanceInitial;
|
||||
buttonText?: string;
|
||||
buttonType?: "primary" | "default";
|
||||
}) {
|
||||
let control = useContext(ControlContext);
|
||||
let account = useAccount();
|
||||
let navigate = useNavigate();
|
||||
@@ -31,9 +104,11 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
|
||||
const canAssign = account.hasPermission("core.instance.assign");
|
||||
const cloneId: number | undefined = Form.useWatch("instanceClone", form);
|
||||
const templateId: number | null | undefined = Form.useWatch("template", form);
|
||||
const asTemplate = Boolean(Form.useWatch("asTemplate", form));
|
||||
const host: number | string | undefined = Form.useWatch("host", form);
|
||||
const saveMode: SaveMode = Form.useWatch("saveMode", form) ?? "none";
|
||||
const hostId = typeof host === "number" ? host : undefined;
|
||||
const hostId = typeof host === "number" && !asTemplate ? host : undefined;
|
||||
const source = cloneId !== undefined && cloneId >= 0 ? props.instances.get(cloneId) : undefined;
|
||||
const sourceRunning = source?.status === "running";
|
||||
const activeSave = source ? [...saves.values()].find(
|
||||
@@ -42,6 +117,7 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
const sourceConfig = useInstanceConfig(source?.id);
|
||||
const sourceSettings = sourceConfig?.["factorio.settings"] as Record<string, unknown> | undefined;
|
||||
const sourceServerName = typeof sourceSettings?.name === "string" ? sourceSettings.name : undefined;
|
||||
const copySettings = sourceSettings !== undefined && !asTemplate;
|
||||
|
||||
useEffect(() => {
|
||||
if (open && sourceServerName !== undefined) {
|
||||
@@ -68,7 +144,8 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
let instanceConfig = new lib.InstanceConfig("control");
|
||||
instanceConfig.set("instance.name", values.instanceName);
|
||||
const fields: (keyof lib.InstanceConfigFields)[] = ["instance.id", "instance.name"];
|
||||
if (source && sourceSettings) {
|
||||
setTemplateFields(instanceConfig, fields, values.template, asTemplate);
|
||||
if (copySettings) {
|
||||
if (!values.serverName) {
|
||||
form.setFields([{ name: "serverName", errors: ["Server name is required"] }]);
|
||||
return;
|
||||
@@ -87,6 +164,9 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
));
|
||||
created = true;
|
||||
|
||||
if (asTemplate && values.linkSource) {
|
||||
await linkToTemplate(control, source, instanceId);
|
||||
}
|
||||
if (hostId !== undefined) {
|
||||
await control.send(new lib.InstanceAssignRequest(instanceId, hostId));
|
||||
}
|
||||
@@ -114,13 +194,13 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
|
||||
return <>
|
||||
<Button
|
||||
type="primary"
|
||||
type={buttonType}
|
||||
onClick={() => {
|
||||
setOpen(true);
|
||||
}}
|
||||
>Create</Button>
|
||||
>{buttonText}</Button>
|
||||
<Modal
|
||||
title="Create Instance"
|
||||
title={asTemplate ? "Create Template" : "Create Instance"}
|
||||
okText="Create"
|
||||
open={open}
|
||||
confirmLoading={creating}
|
||||
@@ -130,12 +210,20 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
initialValues={{ host: "null", instanceClone: -1, saveMode: "none", startAfter: false }}
|
||||
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>
|
||||
{canAssign && <Form.Item name="host" label="Host">
|
||||
<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>
|
||||
@@ -151,16 +239,15 @@ function CreateInstanceButton(props: { instances: ReturnType<typeof useInstances
|
||||
</Select.Option>)}
|
||||
</Select>
|
||||
</Form.Item>}
|
||||
<Tooltip title="Perform a one time copy of the config of an existing instance">
|
||||
<Form.Item name="instanceClone" label="Copy Config">
|
||||
<Select
|
||||
options={[{ id: -1, name: "Default Config" }, ...props.instances.values()]
|
||||
.map(i => ({ value: i.id, label: i.name }))
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Tooltip>
|
||||
{source && sourceSettings && <Tooltip title="Name of the server as shown in the in-game server browser">
|
||||
<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="serverName" label="Server Name">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
@@ -198,6 +285,8 @@ export default function InstancesPage() {
|
||||
let control = useContext(ControlContext);
|
||||
let account = useAccount();
|
||||
let [instances] = useInstances();
|
||||
const plainInstances = new Map([...instances].filter(([, instance]) => !instance.isTemplate));
|
||||
const templates = new Map([...instances].filter(([, instance]) => instance.isTemplate));
|
||||
|
||||
return <PageLayout nav={[{ name: "Instances" }]}>
|
||||
<PageHeader
|
||||
@@ -231,7 +320,11 @@ export default function InstancesPage() {
|
||||
</Space>}
|
||||
/>
|
||||
|
||||
<InstanceList instances={instances} />
|
||||
<InstanceList instances={plainInstances} />
|
||||
{templates.size > 0 && <>
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>Templates</Typography.Title>
|
||||
<InstanceList instances={templates} hideAssignedHost tableNamespace="template" />
|
||||
</>}
|
||||
<PluginExtra component="InstancesPage" />
|
||||
</PageLayout>;
|
||||
}
|
||||
Reference in new issue
Block a user