mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-18 23:03:13 +09:00
Send every value, register protected entities, fix the pattern offset
- The instance sends every value of a feature, defaults included, so update_config is one loop which sets each field and compares. The stored table is the last set of values, and _apply is gone. - values_equal compares table sizes before the contents. - Protected entities are registered with register_on_object_destroyed and forgotten in on_object_destroyed, which covers every way an entity can go. The four removal handlers and the validity checks are gone. Entities destroyed while the feature is disabled are swept when it is enabled again. Saves from before the registrations table get it through the Storage on_init callback. - Spawn area applied the water offset twice and the pattern offset never. The pattern tiles now move with the entities above them. - pruneFeatureValues reads a validation result instead of catching an error, and FeaturesPage hands its pending state and unsaved bar to helpers. - Shorter comments throughout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
f90b8fcee1
commit
2959d7476b
11 files changed
+300
-350
No files matched your search
@@ -46,13 +46,7 @@ export class ControllerPlugin {
|
||||
await this.features.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the stored records in line with the features declared in features.ts.
|
||||
*
|
||||
* New features begin with their defaults, records of removed features are
|
||||
* deleted, and values which no longer match a field are dropped so the
|
||||
* feature can still be saved from the web interface.
|
||||
*/
|
||||
/** Add new features, delete removed ones, and drop stored values which no longer fit a field */
|
||||
reconcileFeatures() {
|
||||
const declared = new Map(features.map(feature => [feature.name, feature]));
|
||||
for (const record of [...this.features.values()]) {
|
||||
|
||||
+23
-45
@@ -1,18 +1,11 @@
|
||||
/**
|
||||
* The scenario features which can be configured from the web interface.
|
||||
*
|
||||
* Defaults must match the Features.config call in the lua module,
|
||||
* test/features.test.js checks this. Only list settings which the lua side
|
||||
* reads at runtime. Settings in nested tables are named "section.key".
|
||||
* The features which can be configured from the web interface. Defaults must
|
||||
* match the lua side, test/features.test.js checks this.
|
||||
*/
|
||||
|
||||
export type FeatureValue = boolean | number | string | string[] | null;
|
||||
|
||||
/**
|
||||
* A setting of a feature, shaped like a clusterio config field definition so
|
||||
* the web interface can render it with the same inputs, including the input
|
||||
* components registered by plugins.
|
||||
*/
|
||||
/** A setting, shaped like a clusterio config field so the config inputs can render it */
|
||||
export type FeatureField = {
|
||||
name: string,
|
||||
title: string,
|
||||
@@ -211,12 +204,7 @@ export const features: Feature[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Check the values for a feature against its fields.
|
||||
*
|
||||
* @returns the values which differ from their default
|
||||
* @throws Error if the feature is unknown, or a value is unknown or the wrong type
|
||||
*/
|
||||
/** Check values against the fields of a feature, returning those which differ from their default */
|
||||
export function validateFeatureValues(name: string, values: Record<string, FeatureValue>) {
|
||||
const feature = features.find(f => f.name === name);
|
||||
if (!feature) {
|
||||
@@ -229,7 +217,10 @@ export function validateFeatureValues(name: string, values: Record<string, Featu
|
||||
if (!field) {
|
||||
throw new Error(`Feature ${name} has no setting ${key}`);
|
||||
}
|
||||
checkFieldValue(field, value, `Setting ${key} of ${name}`);
|
||||
const error = fieldValueError(field, value);
|
||||
if (error) {
|
||||
throw new Error(`Setting ${key} of ${name} ${error}`);
|
||||
}
|
||||
if (!isDefaultValue(field, value)) {
|
||||
result[key] = value;
|
||||
}
|
||||
@@ -237,39 +228,35 @@ export function validateFeatureValues(name: string, values: Record<string, Featu
|
||||
return result;
|
||||
}
|
||||
|
||||
function checkFieldValue(field: FeatureField, value: FeatureValue, label: string) {
|
||||
/** Why a value does not fit a field, undefined when it does */
|
||||
function fieldValueError(field: FeatureField, value: FeatureValue) {
|
||||
if (value === null) {
|
||||
if (field.type === "string_list" || !field.optional) {
|
||||
throw new Error(`${label} can not be null`);
|
||||
}
|
||||
return;
|
||||
return field.type === "string_list" || !field.optional ? "can not be null" : undefined;
|
||||
}
|
||||
switch (field.type) {
|
||||
case "string_list":
|
||||
if (!Array.isArray(value) || value.some(item => typeof item !== "string")) {
|
||||
throw new Error(`${label} must be a list of strings`);
|
||||
return "must be a list of strings";
|
||||
}
|
||||
return;
|
||||
return undefined;
|
||||
case "number":
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
throw new Error(`${label} must be a finite number`);
|
||||
return "must be a finite number";
|
||||
}
|
||||
if (field.min !== undefined && value < field.min) {
|
||||
throw new Error(`${label} must be at least ${field.min}`);
|
||||
return `must be at least ${field.min}`;
|
||||
}
|
||||
return;
|
||||
return undefined;
|
||||
case "string":
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`${label} must be a string`);
|
||||
return "must be a string";
|
||||
}
|
||||
if (field.enum && !field.enum.includes(value)) {
|
||||
throw new Error(`${label} must be one of ${field.enum.join(", ")}`);
|
||||
return `must be one of ${field.enum.join(", ")}`;
|
||||
}
|
||||
return;
|
||||
return undefined;
|
||||
default:
|
||||
if (typeof value !== field.type) {
|
||||
throw new Error(`${label} must be a ${field.type}`);
|
||||
}
|
||||
return typeof value === field.type ? undefined : `must be a ${field.type}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,24 +272,15 @@ export function isDefaultValue(field: FeatureField, value: FeatureValue) {
|
||||
return sameValue(value, field.default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop stored values which no longer match the fields of a feature, after a
|
||||
* setting was renamed, removed, or changed type.
|
||||
*
|
||||
* @returns the values which are still valid, and the names of those dropped
|
||||
*/
|
||||
/** Split stored values into those which still fit a field and the names of the rest */
|
||||
export function pruneFeatureValues(feature: Feature, values: Record<string, FeatureValue>) {
|
||||
const kept: Record<string, FeatureValue> = {};
|
||||
const dropped: string[] = [];
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
const field = feature.fields.find(f => f.name === key);
|
||||
try {
|
||||
if (!field) {
|
||||
throw new Error("removed");
|
||||
}
|
||||
checkFieldValue(field, value, key);
|
||||
if (field && !fieldValueError(field, value)) {
|
||||
kept[key] = value;
|
||||
} catch {
|
||||
} else {
|
||||
dropped.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { Instance, InstancePluginContext } from "@clusterio/host";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "./messages.js";
|
||||
import { features, FeatureValue } from "./features.js";
|
||||
|
||||
/** Sends the feature config from the controller to the lua side, see module/features.lua. */
|
||||
/** Sends feature config to the lua side, see module/features.lua. */
|
||||
export class InstancePlugin {
|
||||
instance: Instance;
|
||||
logger: lib.Logger;
|
||||
@@ -39,7 +40,7 @@ export class InstancePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to updates and send every feature, updates arriving while listing are covered by the list. */
|
||||
/** Subscribe, then send every feature */
|
||||
async syncFeatures() {
|
||||
await this.instance.sendTo("controller", new lib.SubscriptionRequest(
|
||||
`exp_scenario:${messages.FeatureUpdatedEvent.name}`, "subscribe", Date.now(),
|
||||
@@ -54,14 +55,21 @@ export class InstancePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
async luaSendFeatures(features: messages.FeatureRecord[]) {
|
||||
if (!features.length) {
|
||||
/** Every value of each feature is sent, so the lua side sets them all */
|
||||
async luaSendFeatures(records: messages.FeatureRecord[]) {
|
||||
if (!records.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updates = features.map(feature => ({ name: feature.id, enabled: feature.enabled, values: feature.values }));
|
||||
const updates = records.map(record => {
|
||||
const values: Record<string, FeatureValue> = { enabled: record.enabled };
|
||||
for (const field of features.find(feature => feature.name === record.id)?.fields ?? []) {
|
||||
values[field.name] = field.name in record.values ? record.values[field.name] : field.default;
|
||||
}
|
||||
return { name: record.id, values };
|
||||
});
|
||||
const json = JSON.stringify(updates);
|
||||
// A long bracket level which the json does not close, string values are user input
|
||||
// Pick a long bracket the json does not contain
|
||||
let level = "=";
|
||||
while (json.includes(`]${level}]`)) {
|
||||
level += "=";
|
||||
|
||||
@@ -16,12 +16,7 @@ export class SeedRequest {
|
||||
|
||||
const FeatureValueSchema = Type.Union([Type.Boolean(), Type.Number(), Type.String(), Type.Array(Type.String()), Type.Null()]);
|
||||
|
||||
/**
|
||||
* The config of one scenario feature, see features.ts.
|
||||
*
|
||||
* Only values which differ from the default are stored, so a changed default
|
||||
* applies to every cluster which did not set that value.
|
||||
*/
|
||||
/** The config of one feature, see features.ts. Only values which differ from the default are stored. */
|
||||
export class FeatureRecord {
|
||||
constructor(
|
||||
/** Name of the feature in features.ts */
|
||||
@@ -105,7 +100,7 @@ export class FeatureListRequest {
|
||||
static Response = lib.jsonArray(FeatureRecord);
|
||||
}
|
||||
|
||||
/** Enable or disable a feature and replace its values, values left out go back to their default. */
|
||||
/** Replace the config of a feature, values left out go back to their default. */
|
||||
export class FeatureUpdateRequest {
|
||||
declare ["constructor"]: typeof FeatureUpdateRequest;
|
||||
static plugin = "exp_scenario" as const;
|
||||
|
||||
@@ -45,18 +45,29 @@ local Protection = {
|
||||
--- @field last uint Tick of the last protected removal
|
||||
--- @field count number Protected removals since the last repeat violation
|
||||
|
||||
local protected_entities = {} --- @type table<uint, table<string, LuaEntity>> Keyed by surface index then entity key
|
||||
local protected_areas = {} --- @type table<uint, table<string, BoundingBox>> Keyed by surface index then area key
|
||||
local repeats = {} --- @type table<string, ExpScenario_Protection.Repeat> Keyed by player name
|
||||
--- @class ExpScenario_Protection.Registration
|
||||
--- @field surface_index uint
|
||||
--- @field key string
|
||||
--- @field entity LuaEntity
|
||||
|
||||
local protected_entities = {} --- @type table<uint, table<string, LuaEntity>> By surface index then entity key
|
||||
local protected_areas = {} --- @type table<uint, table<string, BoundingBox>> By surface index then area key
|
||||
local registrations = {} --- @type table<uint64, ExpScenario_Protection.Registration> By on_object_destroyed registration number
|
||||
local repeats = {} --- @type table<string, ExpScenario_Protection.Repeat> By player name
|
||||
|
||||
Storage.register({
|
||||
protected_entities = protected_entities,
|
||||
protected_areas = protected_areas,
|
||||
registrations = registrations,
|
||||
repeats = repeats,
|
||||
}, function(tbl)
|
||||
protected_entities = tbl.protected_entities
|
||||
protected_areas = tbl.protected_areas
|
||||
registrations = tbl.registrations
|
||||
repeats = tbl.repeats
|
||||
end, function(tbl)
|
||||
-- Saves from before entities were registered
|
||||
tbl.registrations = tbl.registrations or {}
|
||||
end)
|
||||
|
||||
--- Get the key an entity is stored under
|
||||
@@ -73,15 +84,18 @@ function Protection.get_area_key(area)
|
||||
return format_string("%i,%i", floor(area.left_top.x), floor(area.left_top.y))
|
||||
end
|
||||
|
||||
--- Protect an entity
|
||||
--- Protect an entity, it is forgotten when destroyed
|
||||
--- @param entity LuaEntity
|
||||
function Protection.add_entity(entity)
|
||||
local entities = protected_entities[entity.surface.index]
|
||||
local surface_index = entity.surface.index
|
||||
local entities = protected_entities[surface_index]
|
||||
if not entities then
|
||||
entities = {}
|
||||
protected_entities[entity.surface.index] = entities
|
||||
protected_entities[surface_index] = entities
|
||||
end
|
||||
entities[Protection.get_entity_key(entity)] = entity
|
||||
local key = Protection.get_entity_key(entity)
|
||||
entities[key] = entity
|
||||
registrations[script.register_on_object_destroyed(entity)] = { surface_index = surface_index, key = key, entity = entity }
|
||||
end
|
||||
|
||||
--- Remove the protection from an entity
|
||||
@@ -89,21 +103,18 @@ end
|
||||
function Protection.remove_entity(entity)
|
||||
local entities = protected_entities[entity.surface.index]
|
||||
if not entities then return end
|
||||
entities[Protection.get_entity_key(entity)] = nil
|
||||
local key = Protection.get_entity_key(entity)
|
||||
if entities[key] == entity then
|
||||
entities[key] = nil
|
||||
registrations[script.register_on_object_destroyed(entity)] = nil
|
||||
end
|
||||
end
|
||||
|
||||
--- Get the protected entities on a surface, always protected entities are not included
|
||||
-- Entities removed while the feature was disabled, or without an event, are forgotten here
|
||||
--- @param surface LuaSurface
|
||||
--- @return table<string, LuaEntity>
|
||||
function Protection.get_entities(surface)
|
||||
local entities = protected_entities[surface.index] or {}
|
||||
for key, entity in pairs(entities) do
|
||||
if not entity.valid then
|
||||
entities[key] = nil
|
||||
end
|
||||
end
|
||||
return entities
|
||||
return protected_entities[surface.index] or {}
|
||||
end
|
||||
|
||||
--- Check if an entity is protected, either directly or by its name or type
|
||||
@@ -113,13 +124,7 @@ function Protection.is_entity_protected(entity)
|
||||
if config.always_protected_names[entity.name] or config.always_protected_types[entity.type] then return true end
|
||||
local entities = protected_entities[entity.surface.index]
|
||||
if not entities then return false end
|
||||
local key = Protection.get_entity_key(entity)
|
||||
local protected = entities[key]
|
||||
if protected and not protected.valid then
|
||||
entities[key] = nil
|
||||
return false
|
||||
end
|
||||
return protected == entity
|
||||
return entities[Protection.get_entity_key(entity)] == entity
|
||||
end
|
||||
|
||||
--- Protect every position within an area
|
||||
@@ -200,7 +205,7 @@ local function raise_violation(event, player)
|
||||
end
|
||||
end
|
||||
|
||||
--- Raise the protection events when a protected entity is mined, then forget the entity
|
||||
--- Raise the protection events when a protected entity is mined
|
||||
--- @param event EventData.on_pre_player_mined_item
|
||||
local function on_pre_player_mined_item(event)
|
||||
local entity = event.entity
|
||||
@@ -211,14 +216,36 @@ local function on_pre_player_mined_item(event)
|
||||
then
|
||||
raise_violation(event, player)
|
||||
end
|
||||
|
||||
Protection.remove_entity(entity)
|
||||
end
|
||||
|
||||
--- Forget an entity once it no longer exists
|
||||
--- @param event { entity: LuaEntity }
|
||||
local function on_entity_removed(event)
|
||||
Protection.remove_entity(event.entity)
|
||||
--- Forget a protected entity once it is destroyed, unless another one took its place
|
||||
--- @param registration_number uint64
|
||||
--- @param registration ExpScenario_Protection.Registration
|
||||
local function forget_entity(registration_number, registration)
|
||||
registrations[registration_number] = nil
|
||||
local entities = protected_entities[registration.surface_index]
|
||||
if entities and entities[registration.key] == registration.entity then
|
||||
entities[registration.key] = nil
|
||||
end
|
||||
end
|
||||
|
||||
--- @param event EventData.on_object_destroyed
|
||||
local function on_object_destroyed(event)
|
||||
local registration = registrations[event.registration_number]
|
||||
if registration then
|
||||
forget_entity(event.registration_number, registration)
|
||||
end
|
||||
end
|
||||
|
||||
--- Entities destroyed while the feature was disabled were not forgotten
|
||||
--- @param event EventData.ExpScenario.on_config_updated
|
||||
local function on_config_updated(event)
|
||||
if event.feature_name ~= feature.name or event.path ~= "enabled" then return end
|
||||
for registration_number, registration in pairs(registrations) do
|
||||
if not registration.entity.valid then
|
||||
forget_entity(registration_number, registration)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Forget protected removals older than the repeat lifetime
|
||||
@@ -234,10 +261,8 @@ end
|
||||
local e = defines.events
|
||||
|
||||
Protection.events[e.on_pre_player_mined_item] = on_pre_player_mined_item
|
||||
Protection.events[e.on_space_platform_pre_mined] = on_entity_removed
|
||||
Protection.events[e.on_robot_pre_mined] = on_entity_removed
|
||||
Protection.events[e.on_entity_died] = on_entity_removed
|
||||
Protection.events[e.script_raised_destroy] = on_entity_removed
|
||||
Protection.events[e.on_object_destroyed] = on_object_destroyed
|
||||
Protection.events[Feature.events.on_config_updated] = on_config_updated
|
||||
Protection.on_nth_tick[3600 * 5] = clear_old_repeats
|
||||
|
||||
return feature:guard(Protection)
|
||||
@@ -35,7 +35,7 @@ end
|
||||
apply_offset_to_array(config.turrets.locations, config.turrets.offset, 1, 2)
|
||||
apply_offset_to_array(config.afk_belts.locations, config.afk_belts.offset, 1, 2)
|
||||
apply_offset_to_array(config.water.locations, config.water.offset, 1, 2)
|
||||
apply_offset_to_array(config.water.locations, config.water.offset, 1, 2)
|
||||
apply_offset_to_array(config.pattern.locations, config.pattern.offset, 1, 2)
|
||||
apply_offset_to_array(config.entities.locations, config.entities.offset, 2, 3)
|
||||
|
||||
--- Get or create the force used for entities in spawn
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
--[[-- ExpScenario - Features
|
||||
Features which the controller can enable, disable, and configure while the game is running
|
||||
|
||||
A feature's config table is changed in place when the controller sends overrides,
|
||||
so read values when they are used rather than copying them into locals when the
|
||||
file loads. Booleans, numbers, and strings can be overridden, as can lists and
|
||||
sets of strings made with Feature.list and Feature.set, and values with no default
|
||||
made with Feature.optional. Tables with string keys are nested sections whose
|
||||
values are addressed as "section.key", other tables can not be overridden. Values used while the file
|
||||
loads, such as on_nth_tick periods, stay as plain values and are not listed in
|
||||
features.ts.
|
||||
The config table is changed in place when the controller sends values, so read
|
||||
them where they are used rather than caching them when the file loads. Values
|
||||
read while the file loads, such as on_nth_tick periods, are not listed in features.ts.
|
||||
|
||||
--- Registering a feature, small configs live at the top of the file which uses them:
|
||||
local Feature = require("modules/exp_scenario/features")
|
||||
local feature, config = Feature.register("my_feature", {
|
||||
show_message = true,
|
||||
role_id = Feature.optional("number"),
|
||||
item_names = Feature.set{ "iron-plate" },
|
||||
show_message = true, -- booleans, numbers, and strings
|
||||
role_id = Feature.optional("number"), -- no default
|
||||
item_names = Feature.set{ "iron-plate" }, -- indexed by name
|
||||
surface_names = Feature.list{ "nauvis" },
|
||||
section = { count = 1 }, -- addressed as "section.count"
|
||||
})
|
||||
|
||||
--- Handlers do nothing while the feature is disabled:
|
||||
@@ -24,17 +20,10 @@ return feature:guard{
|
||||
events = { [defines.events.on_player_joined_game] = on_player_joined_game },
|
||||
}
|
||||
|
||||
--- Toolbar buttons are hidden while disabled, which also hides their left element:
|
||||
Gui.toolbar.create_button{
|
||||
visible = function(player, element) return feature:is_enabled() end,
|
||||
}
|
||||
|
||||
--- Commands are denied and left out of help while disabled:
|
||||
--- Toolbar buttons and commands:
|
||||
Gui.toolbar.create_button{ visible = function(player) return feature:is_enabled() end }
|
||||
Commands.new("my_command", { "..." }):add_flags{ feature = feature }
|
||||
|
||||
--- Sets are kept as sets, the controller sends a list which is converted when it is applied:
|
||||
if config.item_names[item.name] then end
|
||||
|
||||
--- Changes are raised per value:
|
||||
[Feature.events.on_config_updated] = function(event) end, -- { feature_name, path, old_value, new_value }
|
||||
]]
|
||||
@@ -42,32 +31,31 @@ if config.item_names[item.name] then end
|
||||
local Storage = require("modules/exp_util/storage")
|
||||
|
||||
--- @class ExpScenario.FeatureField
|
||||
--- @field parent table The table holding the value within the config
|
||||
--- @field key string The key of the value within its parent
|
||||
--- @field path string
|
||||
--- @field parent table
|
||||
--- @field key string
|
||||
--- @field default any
|
||||
--- @field type string "boolean", "number", "string", "list" or "set" of strings, or a type which can not be overridden
|
||||
--- @field type string "boolean", "number", "string", "list", "set", or a type which can not be set
|
||||
|
||||
--- @class ExpScenario.Features
|
||||
local Feature = {
|
||||
_registered = {}, --- @type table<string, ExpScenario.Feature>
|
||||
events = {
|
||||
--- Raised for each value which changes when the controller updates a feature
|
||||
--- @type EventData.ExpScenario.on_config_updated
|
||||
on_config_updated = script.generate_event_name(),
|
||||
},
|
||||
}
|
||||
|
||||
--- The methods of every feature, kept apart from the lib so they are not called on it by mistake
|
||||
--- @class ExpScenario.Feature
|
||||
--- @field name string
|
||||
--- @field config table Changed in place when the config is updated
|
||||
--- @field fields table<string, ExpScenario.FeatureField> The values in the config by path
|
||||
--- @field overrides table<string, any> The overrides from the controller by path, restored from storage on load
|
||||
--- @field config table
|
||||
--- @field fields table<string, ExpScenario.FeatureField> By path
|
||||
--- @field values table<string, any> Last received from the controller, restored from storage on load
|
||||
Feature._prototype = {}
|
||||
|
||||
--- @class EventData.ExpScenario.on_config_updated : EventData
|
||||
--- @field feature_name string
|
||||
--- @field path string The path of the value within the config, "enabled" when the feature is enabled or disabled
|
||||
--- @field path string "enabled" when the feature is enabled or disabled
|
||||
--- @field old_value any
|
||||
--- @field new_value any
|
||||
|
||||
@@ -75,17 +63,18 @@ local Feature_mt = {
|
||||
__index = Feature._prototype,
|
||||
}
|
||||
|
||||
--- The overrides of each feature by name, only these are stored because the rest is rebuilt when the file loads
|
||||
local stored_overrides = {} --- @type table<string, table<string, any>>
|
||||
Storage.register(stored_overrides, function(tbl)
|
||||
stored_overrides = tbl
|
||||
--- Only the values are stored, the rest is rebuilt when the file loads
|
||||
local stored_values = {} --- @type table<string, table<string, any>>
|
||||
Storage.register(stored_values, function(tbl)
|
||||
stored_values = tbl
|
||||
for name, feature in pairs(Feature._registered) do
|
||||
feature.overrides = tbl[name] or {}
|
||||
feature:_apply()
|
||||
feature.values = tbl[name] or {}
|
||||
for path, field in pairs(feature.fields) do
|
||||
feature:_set_field(field, feature.values[path])
|
||||
end
|
||||
end
|
||||
end)
|
||||
|
||||
--- Check if a value is a list of strings, as sent by the controller for lists and sets
|
||||
--- @param value any
|
||||
--- @return boolean
|
||||
local function is_string_list(value)
|
||||
@@ -97,25 +86,22 @@ local function is_string_list(value)
|
||||
return true
|
||||
end
|
||||
|
||||
--- Check if two values are equal, lists and sets are compared by their contents
|
||||
--- Lists and sets are compared by their contents
|
||||
--- @param a any
|
||||
--- @param b any
|
||||
--- @return boolean
|
||||
local function values_equal(a, b)
|
||||
if type(a) ~= "table" or type(b) ~= "table" then return a == b end
|
||||
if table_size(a) ~= table_size(b) then return false end
|
||||
for key, value in pairs(a) do
|
||||
if b[key] ~= value then return false end
|
||||
end
|
||||
for key in pairs(b) do
|
||||
if a[key] == nil then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- Marks a default made by Feature.list, Feature.set, or Feature.optional with the type of the field
|
||||
--- Marks a default made by Feature.list, Feature.set, or Feature.optional
|
||||
local typed_mt = {}
|
||||
|
||||
--- Convert a list of strings into a set
|
||||
--- @param list string[]
|
||||
--- @return table<string, true>
|
||||
local function list_to_set(list)
|
||||
@@ -126,58 +112,58 @@ local function list_to_set(list)
|
||||
return set
|
||||
end
|
||||
|
||||
--- Collect the values of a config table, recursing into nested sections
|
||||
--- Nested tables with string keys are sections
|
||||
--- @param fields table<string, ExpScenario.FeatureField>
|
||||
--- @param tbl table
|
||||
--- @param prefix string
|
||||
local function collect_fields(fields, tbl, prefix)
|
||||
for key, value in pairs(tbl) do
|
||||
if type(key) == "string" then
|
||||
local field = { parent = tbl, key = key, default = value, type = type(value) }
|
||||
local path = prefix .. key
|
||||
local field = { path = path, parent = tbl, key = key, default = value, type = type(value) }
|
||||
if type(value) == "table" then
|
||||
local typed = getmetatable(value) == typed_mt and value
|
||||
if typed then
|
||||
field.type = typed.type
|
||||
field.default = typed.default
|
||||
tbl[key] = typed.default
|
||||
if getmetatable(value) == typed_mt then
|
||||
field.type = value.type
|
||||
field.default = value.default
|
||||
tbl[key] = value.default
|
||||
elseif type(next(value)) == "string" then
|
||||
collect_fields(fields, value, prefix .. key .. ".")
|
||||
collect_fields(fields, value, path .. ".")
|
||||
field = nil
|
||||
end
|
||||
end
|
||||
if field then
|
||||
fields[prefix .. key] = field
|
||||
fields[path] = field
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Declare a value with no default, the argument is the type it can be overridden with
|
||||
--- A value with no default, the argument is the type it accepts
|
||||
--- @param value_type "boolean" | "number" | "string"
|
||||
--- @return any
|
||||
function Feature.optional(value_type)
|
||||
return setmetatable({ type = value_type }, typed_mt)
|
||||
end
|
||||
|
||||
--- Declare a list of strings which can be overridden
|
||||
--- A list of strings
|
||||
--- @param items string[]
|
||||
--- @return string[]
|
||||
function Feature.list(items)
|
||||
return setmetatable({ type = "list", default = items }, typed_mt)
|
||||
end
|
||||
|
||||
--- Declare a set of strings which can be overridden, the controller sends a list which is converted when applied
|
||||
--- A set of strings, the controller sends a list
|
||||
--- @param items string[]
|
||||
--- @return table<string, true>
|
||||
function Feature.set(items)
|
||||
return setmetatable({ type = "set", default = list_to_set(items) }, typed_mt)
|
||||
end
|
||||
|
||||
--- Register a feature and its config, features are enabled unless the config says otherwise
|
||||
--- Features are enabled unless the config says otherwise
|
||||
--- @param name string
|
||||
--- @param config table?
|
||||
--- @return ExpScenario.Feature feature
|
||||
--- @return table config The same table as feature.config
|
||||
--- @return table config
|
||||
function Feature.register(name, config)
|
||||
assert(Feature._registered[name] == nil, "Feature already registered: " .. name)
|
||||
config = config or {}
|
||||
@@ -192,21 +178,19 @@ function Feature.register(name, config)
|
||||
name = name,
|
||||
config = config,
|
||||
fields = fields,
|
||||
overrides = {},
|
||||
values = {},
|
||||
}, Feature_mt) --[[@as ExpScenario.Feature]]
|
||||
|
||||
Feature._registered[name] = feature
|
||||
return feature, config
|
||||
end
|
||||
|
||||
--- Get a registered feature by name
|
||||
--- @param name string
|
||||
--- @return ExpScenario.Feature
|
||||
function Feature.get(name)
|
||||
return Feature._registered[name] or error("Unknown feature: " .. tostring(name), 2)
|
||||
end
|
||||
|
||||
--- Check if a field can take a value
|
||||
--- @param field ExpScenario.FeatureField
|
||||
--- @param value any
|
||||
--- @return boolean
|
||||
@@ -217,18 +201,18 @@ local function is_valid(field, value)
|
||||
return type(value) == field.type and (field.type == "boolean" or field.type == "number" or field.type == "string")
|
||||
end
|
||||
|
||||
--- Set a value to its override, or its default when there is no valid override
|
||||
--- Set a value, nil or an invalid value means the default
|
||||
--- @package
|
||||
--- @param path string
|
||||
--- @param field ExpScenario.FeatureField
|
||||
--- @param value any
|
||||
--- @return any # The value which was set
|
||||
function Feature._prototype:_apply_field(path, field)
|
||||
local value = self.overrides[path]
|
||||
function Feature._prototype:_set_field(field, value)
|
||||
if value ~= nil and not is_valid(field, value) then
|
||||
log("[WARNING] Invalid value for " .. self.name .. "." .. field.path .. ", using the default")
|
||||
value = nil
|
||||
end
|
||||
if value == nil then
|
||||
value = field.default
|
||||
elseif not is_valid(field, value) then
|
||||
log("[WARNING] Invalid override for " .. self.name .. "." .. path .. ", using the default")
|
||||
value = field.default
|
||||
elseif field.type == "set" then
|
||||
value = list_to_set(value)
|
||||
end
|
||||
@@ -236,21 +220,12 @@ function Feature._prototype:_apply_field(path, field)
|
||||
return value
|
||||
end
|
||||
|
||||
--- Set every value to its override, or its default when there is no valid override
|
||||
--- @package
|
||||
function Feature._prototype:_apply()
|
||||
for path, field in pairs(self.fields) do
|
||||
self:_apply_field(path, field)
|
||||
end
|
||||
end
|
||||
|
||||
--- Check if the feature is enabled
|
||||
--- @return boolean
|
||||
function Feature._prototype:is_enabled()
|
||||
return self.config.enabled
|
||||
end
|
||||
|
||||
--- Make the event and on_nth_tick handlers of an event handler lib do nothing while the feature is disabled
|
||||
--- Make the event and on_nth_tick handlers of a lib do nothing while the feature is disabled
|
||||
--- @generic T : table
|
||||
--- @param lib T
|
||||
--- @return T
|
||||
@@ -269,39 +244,16 @@ function Feature._prototype:guard(lib)
|
||||
return lib
|
||||
end
|
||||
|
||||
--- Replace the overrides of the feature, then raise on_config_updated for each value which changed
|
||||
--- @param enabled boolean
|
||||
--- @param values table<string, boolean | number | string | string[]>
|
||||
function Feature._prototype:update_config(enabled, values)
|
||||
local old_overrides = self.overrides
|
||||
local overrides = { enabled = enabled }
|
||||
for path, value in pairs(values) do
|
||||
if self.fields[path] == nil then
|
||||
log("[WARNING] Unknown override for " .. self.name .. "." .. path)
|
||||
else
|
||||
overrides[path] = value
|
||||
end
|
||||
end
|
||||
self.overrides = overrides
|
||||
stored_overrides[self.name] = overrides
|
||||
|
||||
-- Only a value whose override was added, removed, or replaced can change
|
||||
local paths = {}
|
||||
for path in pairs(overrides) do
|
||||
paths[path] = true
|
||||
end
|
||||
for path in pairs(old_overrides) do
|
||||
-- A save can hold overrides for settings which no longer exist
|
||||
if self.fields[path] then
|
||||
paths[path] = true
|
||||
end
|
||||
end
|
||||
--- Replace every value, then raise on_config_updated for each one which changed
|
||||
--- @param values table<string, any> By path, "enabled" included
|
||||
function Feature._prototype:update_config(values)
|
||||
self.values = values
|
||||
stored_values[self.name] = values
|
||||
|
||||
local updates = {}
|
||||
for path in pairs(paths) do
|
||||
local field = self.fields[path]
|
||||
for path, field in pairs(self.fields) do
|
||||
local old_value = field.parent[field.key]
|
||||
local new_value = self:_apply_field(path, field)
|
||||
local new_value = self:_set_field(field, values[path])
|
||||
if not values_equal(old_value, new_value) then
|
||||
updates[#updates + 1] = { feature_name = self.name, path = path, old_value = old_value, new_value = new_value }
|
||||
end
|
||||
@@ -314,16 +266,15 @@ end
|
||||
|
||||
--- @class ExpScenario.FeatureUpdate
|
||||
--- @field name string
|
||||
--- @field enabled boolean
|
||||
--- @field values table<string, boolean | number | string | string[]>
|
||||
--- @field values table<string, any>
|
||||
|
||||
--- Called over rcon by the instance plugin with the features which changed, unknown features are ignored
|
||||
--- Called over rcon by the instance plugin, unknown features are ignored
|
||||
--- @param updates ExpScenario.FeatureUpdate[]
|
||||
function Feature.receive_update(updates)
|
||||
for _, update in ipairs(updates) do
|
||||
local feature = Feature._registered[update.name]
|
||||
if feature then
|
||||
feature:update_config(update.enabled, update.values)
|
||||
feature:update_config(update.values)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Instance } from "@clusterio/host";
|
||||
import { InstancePlugin } from "../dist/node/instance.js";
|
||||
import { plugin as pluginDeclaration } from "../dist/node/index.js";
|
||||
import * as messages from "../dist/node/messages.js";
|
||||
import { features } from "../dist/node/features.js";
|
||||
|
||||
// The instance validates message classes against the link registry
|
||||
for (const Message of pluginDeclaration.messages) {
|
||||
@@ -64,10 +65,12 @@ t.test("class InstancePlugin", t2 => {
|
||||
|
||||
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes to updates first");
|
||||
t3.ok(state.sent[1] instanceof messages.FeatureListRequest, "then lists the features");
|
||||
t3.strictSame(
|
||||
decodeRcon(state.rcons[0]),
|
||||
[{ name: "death_markers", enabled: false, values: { show_map_markers: false } }],
|
||||
);
|
||||
const [update] = decodeRcon(state.rcons[0]);
|
||||
const deathMarkers = features.find(feature => feature.name === "death_markers");
|
||||
t3.equal(update.name, "death_markers");
|
||||
t3.strictSame([update.values.enabled, update.values.show_map_markers], [false, false], "stored values are sent");
|
||||
t3.equal(update.values.collect_corpses, true, "the rest are filled with their defaults");
|
||||
t3.equal(Object.keys(update.values).length, deathMarkers.fields.length + 1, "every field and enabled");
|
||||
});
|
||||
|
||||
t2.test(".handleFeatureUpdatedEvent() only sends while the game is up", async t3 => {
|
||||
@@ -83,8 +86,9 @@ t.test("class InstancePlugin", t2 => {
|
||||
await plugin.onStart();
|
||||
state.rcons.length = 0;
|
||||
await plugin.handleFeatureUpdatedEvent(event);
|
||||
t3.strictSame(decodeRcon(state.rcons[0]), [{ name: "afk_kick", enabled: true, values: { afk_minutes: 5 } }],
|
||||
"deleted features are left out");
|
||||
const updates = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(updates.map(update => update.name), ["afk_kick"], "deleted features are left out");
|
||||
t3.strictSame([updates[0].values.enabled, updates[0].values.afk_minutes], [true, 5]);
|
||||
|
||||
await plugin.onExit();
|
||||
state.rcons.length = 0;
|
||||
|
||||
@@ -18,12 +18,18 @@ local Framework = assert(loadfile(shared_root .. "/framework.lua"))() --- @type
|
||||
--- @field on_load fun(tbl: table) Act out on_load with the given storage table
|
||||
--- @field load_config fun(name: string): ExpScenario.Feature Load module/config/<name>.lua
|
||||
--- @field logged string[] Messages passed to log
|
||||
--- @field events table[] Raised events, name and tick filled in
|
||||
|
||||
return Framework.suite(function(env)
|
||||
--- @cast env ExpScenario.TestEnv
|
||||
local callback --- @type fun(tbl: table)
|
||||
env.logged = {}
|
||||
log = function(message) env.logged[#env.logged + 1] = message end
|
||||
table_size = function(tbl)
|
||||
local size = 0
|
||||
for _ in pairs(tbl) do size = size + 1 end
|
||||
return size
|
||||
end
|
||||
env.extend_requires{
|
||||
["modules/exp_util/storage"] = {
|
||||
register = function(tbl, fn)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
local Suite = ... --- @type Suite<ExpScenario.TestEnv>
|
||||
|
||||
--- The values of on_config_updated events, ignoring the event name and tick
|
||||
--- The raised on_config_updated events as { path, old value, new value }, sorted by path
|
||||
local function updates(env)
|
||||
local rtn = {}
|
||||
for _, event in ipairs(env.events) do
|
||||
rtn[#rtn + 1] = { event.feature_name, event.path, event.old_value, event.new_value }
|
||||
rtn[#rtn + 1] = { event.path, event.old_value, event.new_value }
|
||||
end
|
||||
table.sort(rtn, function(a, b) return a[1] < b[1] end)
|
||||
return rtn
|
||||
end
|
||||
|
||||
@@ -16,64 +17,71 @@ Suite.test("register() enables features unless the config says otherwise", funct
|
||||
Suite.throws(function() env.Feature.register("on", {}) end, "Feature already registered: on", "names are unique")
|
||||
end)
|
||||
|
||||
Suite.test("register() returns the config as well", function(env)
|
||||
local feature, config = env.Feature.register("test", { flag = true })
|
||||
Suite.eq(config == feature.config, true, "the same table")
|
||||
end)
|
||||
|
||||
Suite.test("get() finds registered features", function(env)
|
||||
local feature = env.Feature.register("test")
|
||||
Suite.eq(env.Feature.get("test") == feature, true, "by name")
|
||||
Suite.throws(function() env.Feature.get("unknown") end, "Unknown feature: unknown", "unknown names error")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() changes the config in place", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true, count = 5, text = "a" })
|
||||
local config = feature.config
|
||||
feature:update_config(false, { flag = false, count = 7 })
|
||||
Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values replace the defaults")
|
||||
Suite.test("update_config() sets every value, missing ones to their default", function(env)
|
||||
local feature, config = env.Feature.register("test", { flag = true, count = 5, text = "a" })
|
||||
feature:update_config{ enabled = false, flag = false, count = 7 }
|
||||
Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values are set")
|
||||
|
||||
feature:update_config(true, { text = "b" })
|
||||
feature:update_config{ enabled = true, text = "b" }
|
||||
Suite.eq(config, { enabled = true, flag = true, count = 5, text = "b" }, "values left out go back to their default")
|
||||
Suite.eq(env.storage, { test = { enabled = true, text = "b" } }, "the overrides are kept in storage")
|
||||
Suite.eq(env.storage, { test = { enabled = true, text = "b" } }, "the values are kept in storage")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() raises on_config_updated for each changed value", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true, names = env.Feature.set{ "a" }, section = { count = 1 } })
|
||||
feature:update_config(false, { names = { "a" }, ["section.count"] = 2 })
|
||||
Suite.eq(#env.events, 2, "unchanged values raise nothing")
|
||||
feature:update_config{ enabled = false, flag = true, names = { "a" }, ["section.count"] = 2 }
|
||||
Suite.eq(env.Feature.events.on_config_updated, assert(env.events[1]).name, "the event is on_config_updated")
|
||||
|
||||
local seen = updates(env)
|
||||
table.sort(seen, function(a, b) return a[2] < b[2] end)
|
||||
Suite.eq(seen, {
|
||||
{ "test", "enabled", true, false },
|
||||
{ "test", "section.count", 1, 2 },
|
||||
}, "with the path, old value, and new value")
|
||||
Suite.eq(updates(env), {
|
||||
{ "enabled", true, false },
|
||||
{ "section.count", 1, 2 },
|
||||
}, "with the path, old value, and new value, unchanged values raise nothing")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() ignores and logs values which can not be overridden", function(env)
|
||||
Suite.test("update_config() raises when a value goes back to its default", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true })
|
||||
feature:update_config{ enabled = true, flag = false }
|
||||
env.events = {}
|
||||
feature:update_config{ enabled = true }
|
||||
Suite.eq(updates(env), { { "flag", false, true } }, "the value reverts")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() ignores and logs values of the wrong type", function(env)
|
||||
local function check() return true end
|
||||
local feature = env.Feature.register("test", { flag = true, check = check, icon = nil })
|
||||
feature:update_config(true, { flag = "yes", check = false, icon = "x" })
|
||||
Suite.eq(feature.config, { enabled = true, flag = true, check = check }, "wrong types, functions, and unknown keys are skipped")
|
||||
Suite.eq(#env.logged, 3, "each one is logged")
|
||||
Suite.eq(env.storage.test, { enabled = true, flag = "yes", check = false }, "unknown keys are not stored")
|
||||
local feature, config = env.Feature.register("test", { flag = true, check = check })
|
||||
feature:update_config{ enabled = true, flag = "yes", check = false }
|
||||
Suite.eq(config, { enabled = true, flag = true, check = check }, "wrong types and functions keep their default")
|
||||
Suite.eq(#env.logged, 2, "each one is logged")
|
||||
end)
|
||||
|
||||
Suite.test("receive_update() updates known features", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true })
|
||||
env.Feature.receive_update{
|
||||
{ name = "test", enabled = true, values = { flag = false } },
|
||||
{ name = "unknown", enabled = false, values = {} },
|
||||
{ name = "test", values = { enabled = true, flag = false } },
|
||||
{ name = "unknown", values = { enabled = false } },
|
||||
}
|
||||
Suite.eq(feature.config.flag, false, "the known feature changed")
|
||||
Suite.eq(env.storage.unknown, nil, "unknown features are not stored")
|
||||
end)
|
||||
|
||||
Suite.test("on_load applies the overrides from storage without raising events", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true })
|
||||
env.on_load{ test = { enabled = false, flag = false } }
|
||||
Suite.eq(feature.config, { enabled = false, flag = false }, "the saved overrides apply")
|
||||
Suite.test("on_load applies the stored values without raising events", function(env)
|
||||
local feature, config = env.Feature.register("test", { flag = true })
|
||||
env.on_load{ test = { enabled = false, flag = false, gone = 1 } }
|
||||
Suite.eq(config, { enabled = false, flag = false }, "the saved values apply, unknown ones are skipped")
|
||||
Suite.empty(env.events, "nothing is raised")
|
||||
|
||||
feature:update_config(true, {})
|
||||
Suite.eq(env.storage, { test = { enabled = true } }, "later updates go to the loaded storage table")
|
||||
feature:update_config{ enabled = true }
|
||||
Suite.eq(env.storage, { test = { enabled = true } }, "later updates replace the stored values")
|
||||
end)
|
||||
|
||||
Suite.test("guard() skips handlers while the feature is disabled", function(env)
|
||||
@@ -87,7 +95,7 @@ Suite.test("guard() skips handlers while the feature is disabled", function(env)
|
||||
|
||||
lib.events.on_event("a")
|
||||
lib.on_nth_tick[60]("b")
|
||||
feature:update_config(false, {})
|
||||
feature:update_config{ enabled = false }
|
||||
lib.events.on_event("c")
|
||||
lib.on_nth_tick[60]("d")
|
||||
Suite.eq(calls, { "a", "b" }, "only called while enabled")
|
||||
@@ -95,70 +103,48 @@ end)
|
||||
|
||||
Suite.test("register() addresses nested values by path", function(env)
|
||||
local offset = { 1, 2 }
|
||||
local feature = env.Feature.register("test", { section = { flag = true, count = 1 }, offset = offset })
|
||||
feature:update_config(true, { ["section.flag"] = false, offset = { "x" } })
|
||||
Suite.eq(feature.config.section, { flag = false, count = 1 }, "the nested value changes in place")
|
||||
Suite.eq(feature.config.offset, offset, "tables which are not sections can not be overridden")
|
||||
local feature, config = env.Feature.register("test", { section = { flag = true, count = 1 }, offset = offset })
|
||||
feature:update_config{ enabled = true, ["section.flag"] = false, offset = { "x" } }
|
||||
Suite.eq(config.section, { flag = false, count = 1 }, "the nested value changes in place")
|
||||
Suite.eq(config.offset, offset, "tables which are not sections can not be set")
|
||||
|
||||
feature:update_config(true, {})
|
||||
Suite.eq(feature.config.section.flag, true, "and goes back to its default")
|
||||
feature:update_config{ enabled = true }
|
||||
Suite.eq(config.section.flag, true, "and goes back to its default")
|
||||
end)
|
||||
|
||||
Suite.test("list() declares a list of strings which can be overridden", function(env)
|
||||
local feature = env.Feature.register("test", { names = env.Feature.list{ "a", "b" }, empty = env.Feature.list{}, plain = { "x" } })
|
||||
Suite.eq(feature.config.names, { "a", "b" }, "the default is the list")
|
||||
feature:update_config(true, { names = { "c" }, empty = { "d" }, plain = { "y" } })
|
||||
Suite.eq(feature.config.names, { "c" }, "a list is replaced")
|
||||
Suite.eq(feature.config.empty, { "d" }, "an empty list can be overridden")
|
||||
Suite.eq(feature.config.plain, { "x" }, "a plain table can not be overridden")
|
||||
feature:update_config(true, { names = { 1 } })
|
||||
Suite.eq(feature.config.names, { "a", "b" }, "a list with other types is invalid")
|
||||
Suite.test("list() declares a list of strings", function(env)
|
||||
local feature, config = env.Feature.register("test", { names = env.Feature.list{ "a", "b" }, empty = env.Feature.list{}, plain = { "x" } })
|
||||
Suite.eq(config.names, { "a", "b" }, "the default is the list")
|
||||
feature:update_config{ enabled = true, names = { "c" }, empty = { "d" }, plain = { "y" } }
|
||||
Suite.eq(config.names, { "c" }, "a list is replaced")
|
||||
Suite.eq(config.empty, { "d" }, "an empty list can be set")
|
||||
Suite.eq(config.plain, { "x" }, "a plain table can not be set")
|
||||
feature:update_config{ enabled = true, names = { 1 } }
|
||||
Suite.eq(config.names, { "a", "b" }, "a list with other types is invalid")
|
||||
end)
|
||||
|
||||
Suite.test("set() declares a set of strings which is overridden with a list", function(env)
|
||||
local feature = env.Feature.register("test", { names = env.Feature.set{ "a" }, empty = env.Feature.set{} })
|
||||
Suite.eq(feature.config.names, { a = true }, "the default is a set")
|
||||
Suite.eq(feature.config.empty, {}, "and can be empty")
|
||||
feature:update_config(true, { names = { "b", "c" } })
|
||||
Suite.eq(feature.config.names, { b = true, c = true }, "the list is converted to a set")
|
||||
Suite.test("set() declares a set of strings which is sent as a list", function(env)
|
||||
local feature, config = env.Feature.register("test", { names = env.Feature.set{ "a" }, empty = env.Feature.set{} })
|
||||
Suite.eq(config.names, { a = true }, "the default is a set")
|
||||
Suite.eq(config.empty, {}, "and can be empty")
|
||||
feature:update_config{ enabled = true, names = { "b", "c" } }
|
||||
Suite.eq(config.names, { b = true, c = true }, "the list is converted to a set")
|
||||
env.on_load{ test = { enabled = true, names = { "d" } } }
|
||||
Suite.eq(feature.config.names, { d = true }, "also when the overrides are loaded")
|
||||
Suite.eq(config.names, { d = true }, "also when the values are loaded")
|
||||
end)
|
||||
|
||||
Suite.test("optional() declares a value without a default", function(env)
|
||||
local feature = env.Feature.register("test", { role_id = env.Feature.optional("number") })
|
||||
Suite.eq(feature.config.role_id, nil, "nil until overridden")
|
||||
feature:update_config(true, { role_id = 3 })
|
||||
Suite.eq(feature.config.role_id, 3, "overridden with the given type")
|
||||
feature:update_config(true, {})
|
||||
Suite.eq(feature.config.role_id, nil, "and back to nil")
|
||||
end)
|
||||
|
||||
|
||||
Suite.test("register() returns the config as well", function(env)
|
||||
local feature, config = env.Feature.register("test", { flag = true })
|
||||
Suite.eq(config == feature.config, true, "the same table")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() raises when an override is removed", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true, count = 1 })
|
||||
feature:update_config(true, { flag = false })
|
||||
env.events = {}
|
||||
feature:update_config(true, {})
|
||||
Suite.eq(updates(env), { { "test", "flag", false, true } }, "the value goes back to its default")
|
||||
end)
|
||||
|
||||
Suite.test("update_config() skips stored overrides for settings which no longer exist", function(env)
|
||||
local feature = env.Feature.register("test", { flag = true })
|
||||
env.on_load{ test = { enabled = true, gone = 1 } }
|
||||
feature:update_config(true, { flag = false })
|
||||
Suite.eq(updates(env), { { "test", "flag", true, false } }, "only the known value is compared")
|
||||
Suite.eq(env.storage.test, { enabled = true, flag = false }, "and the stale key is not kept")
|
||||
local feature, config = env.Feature.register("test", { role_id = env.Feature.optional("number") })
|
||||
Suite.eq(config.role_id, nil, "nil until set")
|
||||
feature:update_config{ enabled = true, role_id = 3 }
|
||||
Suite.eq(config.role_id, 3, "set with the given type")
|
||||
feature:update_config{ enabled = true }
|
||||
Suite.eq(config.role_id, nil, "and back to nil")
|
||||
end)
|
||||
|
||||
Suite.test("config files register their feature", function(env)
|
||||
local feature = env.load_config("spawn_area")
|
||||
feature:update_config(true, { ["turrets.enabled"] = false })
|
||||
feature:update_config{ enabled = true, ["turrets.enabled"] = false }
|
||||
Suite.eq(feature.config.turrets.enabled, false, "spawn_area can be changed")
|
||||
Suite.eq(feature.config.turrets.ammo_type, "uranium-rounds-magazine", "other values keep their default")
|
||||
end)
|
||||
|
||||
@@ -39,7 +39,7 @@ function groupFields(fields: FeatureField[]) {
|
||||
return [...groups.entries()];
|
||||
}
|
||||
|
||||
/** Converts a section name into Title Case, same as the group titles on the role page */
|
||||
/** "afk_belts" to "Afk Belts", like the group titles on the role page */
|
||||
function formatSectionTitle(name: string) {
|
||||
return name
|
||||
.replace(/\./g, " / ")
|
||||
@@ -54,7 +54,7 @@ function matches(text: string, query: string) {
|
||||
return text.toLowerCase().includes(query);
|
||||
}
|
||||
|
||||
/** The fields of a feature which match the search, every field if the feature itself matches. */
|
||||
/** Fields matching the search, every field when the feature itself matches */
|
||||
function searchFields(feature: Feature, query: string) {
|
||||
if (!query || matches(feature.title, query) || matches(feature.description, query) || matches(feature.name, query)) {
|
||||
return feature.fields;
|
||||
@@ -64,10 +64,7 @@ function searchFields(feature: Feature, query: string) {
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the input for a setting the same way the config pages do, input components registered
|
||||
* with the web interface take priority so plugins can provide inputs for other types
|
||||
*/
|
||||
/** Renders a setting like the config pages do, registered input components take priority */
|
||||
function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void }) {
|
||||
const { field, value, disabled, onChange } = props;
|
||||
const control = useContext(ControlContext);
|
||||
@@ -126,7 +123,7 @@ function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled:
|
||||
}
|
||||
}
|
||||
|
||||
/** A single setting, laid out like a permission on the role page. */
|
||||
/** A setting, laid out like a permission on the role page */
|
||||
function FieldItem(props: {
|
||||
field: FeatureField, value: FeatureValue, stored: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void,
|
||||
}) {
|
||||
@@ -217,7 +214,51 @@ function FeatureNav(props: { feature: Feature, enabled: boolean }) {
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** Enable, disable, and configure the scenario features listed in features.ts. */
|
||||
/** The pending changes with one more, dropped again when it matches what is stored */
|
||||
function withChange(pending: PendingChanges, stored: FeatureState, name: string, update: (entry: PendingChanges[string]) => void) {
|
||||
const entry = { enabled: pending[name]?.enabled, values: { ...pending[name]?.values } };
|
||||
update(entry);
|
||||
if (entry.enabled === stored.enabled) {
|
||||
delete entry.enabled;
|
||||
}
|
||||
for (const [key, value] of Object.entries(entry.values)) {
|
||||
if (sameValue(value, stored.values[key])) {
|
||||
delete entry.values[key];
|
||||
}
|
||||
}
|
||||
const next = { ...pending };
|
||||
if (entry.enabled === undefined && !Object.keys(entry.values).length) {
|
||||
delete next[name];
|
||||
} else {
|
||||
next[name] = entry;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function UnsavedChangesBar(props: { onRevert: () => void, onApply: () => void }) {
|
||||
return <div style={{
|
||||
position: "fixed",
|
||||
bottom: 24,
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
background: modifiedColor,
|
||||
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" onClick={props.onApply}>Apply</Button>
|
||||
</Space>
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** Enable, disable, and configure the features listed in features.ts */
|
||||
export default function FeaturesPage() {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
@@ -226,7 +267,7 @@ export default function FeaturesPage() {
|
||||
const [search, setSearch] = useState("");
|
||||
const canEdit = Boolean(account.hasPermission("exp_scenario.config.edit"));
|
||||
|
||||
// Until the subscription delivers the records every feature would look enabled with its defaults
|
||||
// Before the first update every feature would look enabled with its defaults
|
||||
if (!synced) {
|
||||
return <PageLayout nav={[{ name: "Scenario Features" }]}>
|
||||
<PageHeader title="Scenario Features" />
|
||||
@@ -240,27 +281,8 @@ export default function FeaturesPage() {
|
||||
values: { ...stored[name].values, ...pending[name]?.values },
|
||||
});
|
||||
|
||||
/** Record a change, dropping it again if it matches what is stored */
|
||||
function change(name: string, update: (entry: PendingChanges[string]) => void) {
|
||||
setPending(prev => {
|
||||
const entry = { enabled: prev[name]?.enabled, values: { ...prev[name]?.values } };
|
||||
update(entry);
|
||||
if (entry.enabled === stored[name].enabled) {
|
||||
delete entry.enabled;
|
||||
}
|
||||
for (const [key, value] of Object.entries(entry.values)) {
|
||||
if (sameValue(value, stored[name].values[key])) {
|
||||
delete entry.values[key];
|
||||
}
|
||||
}
|
||||
const next = { ...prev };
|
||||
if (entry.enabled === undefined && !Object.keys(entry.values).length) {
|
||||
delete next[name];
|
||||
} else {
|
||||
next[name] = entry;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setPending(prev => withChange(prev, stored[name], name, update));
|
||||
}
|
||||
|
||||
function applyChanges() {
|
||||
@@ -284,26 +306,7 @@ export default function FeaturesPage() {
|
||||
return <PageLayout nav={[{ name: "Scenario Features" }]}>
|
||||
<PageHeader title="Scenario Features" />
|
||||
|
||||
{Object.keys(pending).length > 0 && <div style={{
|
||||
position: "fixed",
|
||||
bottom: 24,
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
background: modifiedColor,
|
||||
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={() => setPending({})}>Revert</Button>
|
||||
<Button type="primary" onClick={applyChanges}>Apply</Button>
|
||||
</Space>
|
||||
</div>}
|
||||
{Object.keys(pending).length > 0 && <UnsavedChangesBar onRevert={() => setPending({})} onApply={applyChanges} />}
|
||||
|
||||
<Input.Search placeholder="Search features and settings" allowClear
|
||||
onChange={e => setSearch(e.target.value)} style={{ marginBottom: 16 }} />
|
||||
@@ -320,7 +323,7 @@ export default function FeaturesPage() {
|
||||
</div>
|
||||
</Col>
|
||||
<Col flex="auto" style={{ minWidth: 0 }}>
|
||||
{/* Small inputs match the line height of the text, same as the config pages */}
|
||||
{/* Same input size as the config pages */}
|
||||
<ConfigProvider componentSize="small">
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
{shown.map(({ feature, fields }) => <FeatureSection
|
||||
|
||||
Reference in new issue
Block a user