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:
bbassieandClaude Fable 5.1 committed 2026-10-04 12:55:08 +00:00
1 parent f90b8fcee1
commit 2959d7476b
11 files changed
+300 -350

No files matched your search

+1 -7
View File
@@ -46,13 +46,7 @@ export class ControllerPlugin {
await this.features.save(); await this.features.save();
} }
/** /** Add new features, delete removed ones, and drop stored values which no longer fit a field */
* 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.
*/
reconcileFeatures() { reconcileFeatures() {
const declared = new Map(features.map(feature => [feature.name, feature])); const declared = new Map(features.map(feature => [feature.name, feature]));
for (const record of [...this.features.values()]) { for (const record of [...this.features.values()]) {
+23 -45
View File
@@ -1,18 +1,11 @@
/** /**
* The scenario features which can be configured from the web interface. * The features which can be configured from the web interface. Defaults must
* * match the lua side, test/features.test.js checks this.
* 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".
*/ */
export type FeatureValue = boolean | number | string | string[] | null; export type FeatureValue = boolean | number | string | string[] | null;
/** /** A setting, shaped like a clusterio config field so the config inputs can render it */
* 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.
*/
export type FeatureField = { export type FeatureField = {
name: string, name: string,
title: string, title: string,
@@ -211,12 +204,7 @@ export const features: Feature[] = [
}, },
]; ];
/** /** Check values against the fields of a feature, returning those which differ from their default */
* 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
*/
export function validateFeatureValues(name: string, values: Record<string, FeatureValue>) { export function validateFeatureValues(name: string, values: Record<string, FeatureValue>) {
const feature = features.find(f => f.name === name); const feature = features.find(f => f.name === name);
if (!feature) { if (!feature) {
@@ -229,7 +217,10 @@ export function validateFeatureValues(name: string, values: Record<string, Featu
if (!field) { if (!field) {
throw new Error(`Feature ${name} has no setting ${key}`); 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)) { if (!isDefaultValue(field, value)) {
result[key] = value; result[key] = value;
} }
@@ -237,39 +228,35 @@ export function validateFeatureValues(name: string, values: Record<string, Featu
return result; 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 (value === null) {
if (field.type === "string_list" || !field.optional) { return field.type === "string_list" || !field.optional ? "can not be null" : undefined;
throw new Error(`${label} can not be null`);
}
return;
} }
switch (field.type) { switch (field.type) {
case "string_list": case "string_list":
if (!Array.isArray(value) || value.some(item => typeof item !== "string")) { 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": case "number":
if (typeof value !== "number" || !Number.isFinite(value)) { 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) { 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": case "string":
if (typeof value !== "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)) { 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: default:
if (typeof value !== field.type) { return typeof value === field.type ? undefined : `must be a ${field.type}`;
throw new Error(`${label} must be a ${field.type}`);
}
} }
} }
@@ -285,24 +272,15 @@ export function isDefaultValue(field: FeatureField, value: FeatureValue) {
return sameValue(value, field.default); return sameValue(value, field.default);
} }
/** /** Split stored values into those which still fit a field and the names of the rest */
* 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
*/
export function pruneFeatureValues(feature: Feature, values: Record<string, FeatureValue>) { export function pruneFeatureValues(feature: Feature, values: Record<string, FeatureValue>) {
const kept: Record<string, FeatureValue> = {}; const kept: Record<string, FeatureValue> = {};
const dropped: string[] = []; const dropped: string[] = [];
for (const [key, value] of Object.entries(values)) { for (const [key, value] of Object.entries(values)) {
const field = feature.fields.find(f => f.name === key); const field = feature.fields.find(f => f.name === key);
try { if (field && !fieldValueError(field, value)) {
if (!field) {
throw new Error("removed");
}
checkFieldValue(field, value, key);
kept[key] = value; kept[key] = value;
} catch { } else {
dropped.push(key); dropped.push(key);
} }
} }
+14 -6
View File
@@ -1,8 +1,9 @@
import type { Instance, InstancePluginContext } from "@clusterio/host"; import type { Instance, InstancePluginContext } from "@clusterio/host";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import * as messages from "./messages.js"; 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 { export class InstancePlugin {
instance: Instance; instance: Instance;
logger: lib.Logger; 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() { async syncFeatures() {
await this.instance.sendTo("controller", new lib.SubscriptionRequest( await this.instance.sendTo("controller", new lib.SubscriptionRequest(
`exp_scenario:${messages.FeatureUpdatedEvent.name}`, "subscribe", Date.now(), `exp_scenario:${messages.FeatureUpdatedEvent.name}`, "subscribe", Date.now(),
@@ -54,14 +55,21 @@ export class InstancePlugin {
} }
} }
async luaSendFeatures(features: messages.FeatureRecord[]) { /** Every value of each feature is sent, so the lua side sets them all */
if (!features.length) { async luaSendFeatures(records: messages.FeatureRecord[]) {
if (!records.length) {
return; 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); 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 = "="; let level = "=";
while (json.includes(`]${level}]`)) { while (json.includes(`]${level}]`)) {
level += "="; level += "=";
+2 -7
View File
@@ -16,12 +16,7 @@ export class SeedRequest {
const FeatureValueSchema = Type.Union([Type.Boolean(), Type.Number(), Type.String(), Type.Array(Type.String()), Type.Null()]); const FeatureValueSchema = Type.Union([Type.Boolean(), Type.Number(), Type.String(), Type.Array(Type.String()), Type.Null()]);
/** /** The config of one feature, see features.ts. Only values which differ from the default are stored. */
* 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.
*/
export class FeatureRecord { export class FeatureRecord {
constructor( constructor(
/** Name of the feature in features.ts */ /** Name of the feature in features.ts */
@@ -105,7 +100,7 @@ export class FeatureListRequest {
static Response = lib.jsonArray(FeatureRecord); 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 { export class FeatureUpdateRequest {
declare ["constructor"]: typeof FeatureUpdateRequest; declare ["constructor"]: typeof FeatureUpdateRequest;
static plugin = "exp_scenario" as const; static plugin = "exp_scenario" as const;
+59 -34
View File
@@ -45,18 +45,29 @@ local Protection = {
--- @field last uint Tick of the last protected removal --- @field last uint Tick of the last protected removal
--- @field count number Protected removals since the last repeat violation --- @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 --- @class ExpScenario_Protection.Registration
local protected_areas = {} --- @type table<uint, table<string, BoundingBox>> Keyed by surface index then area key --- @field surface_index uint
local repeats = {} --- @type table<string, ExpScenario_Protection.Repeat> Keyed by player name --- @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({ Storage.register({
protected_entities = protected_entities, protected_entities = protected_entities,
protected_areas = protected_areas, protected_areas = protected_areas,
registrations = registrations,
repeats = repeats, repeats = repeats,
}, function(tbl) }, function(tbl)
protected_entities = tbl.protected_entities protected_entities = tbl.protected_entities
protected_areas = tbl.protected_areas protected_areas = tbl.protected_areas
registrations = tbl.registrations
repeats = tbl.repeats repeats = tbl.repeats
end, function(tbl)
-- Saves from before entities were registered
tbl.registrations = tbl.registrations or {}
end) end)
--- Get the key an entity is stored under --- 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)) return format_string("%i,%i", floor(area.left_top.x), floor(area.left_top.y))
end end
--- Protect an entity --- Protect an entity, it is forgotten when destroyed
--- @param entity LuaEntity --- @param entity LuaEntity
function Protection.add_entity(entity) 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 if not entities then
entities = {} entities = {}
protected_entities[entity.surface.index] = entities protected_entities[surface_index] = entities
end 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 end
--- Remove the protection from an entity --- Remove the protection from an entity
@@ -89,21 +103,18 @@ end
function Protection.remove_entity(entity) function Protection.remove_entity(entity)
local entities = protected_entities[entity.surface.index] local entities = protected_entities[entity.surface.index]
if not entities then return end 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 end
--- Get the protected entities on a surface, always protected entities are not included --- 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 --- @param surface LuaSurface
--- @return table<string, LuaEntity> --- @return table<string, LuaEntity>
function Protection.get_entities(surface) function Protection.get_entities(surface)
local entities = protected_entities[surface.index] or {} return protected_entities[surface.index] or {}
for key, entity in pairs(entities) do
if not entity.valid then
entities[key] = nil
end
end
return entities
end end
--- Check if an entity is protected, either directly or by its name or type --- 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 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] local entities = protected_entities[entity.surface.index]
if not entities then return false end if not entities then return false end
local key = Protection.get_entity_key(entity) return entities[Protection.get_entity_key(entity)] == entity
local protected = entities[key]
if protected and not protected.valid then
entities[key] = nil
return false
end
return protected == entity
end end
--- Protect every position within an area --- Protect every position within an area
@@ -200,7 +205,7 @@ local function raise_violation(event, player)
end end
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 --- @param event EventData.on_pre_player_mined_item
local function on_pre_player_mined_item(event) local function on_pre_player_mined_item(event)
local entity = event.entity local entity = event.entity
@@ -211,14 +216,36 @@ local function on_pre_player_mined_item(event)
then then
raise_violation(event, player) raise_violation(event, player)
end end
Protection.remove_entity(entity)
end end
--- Forget an entity once it no longer exists --- Forget a protected entity once it is destroyed, unless another one took its place
--- @param event { entity: LuaEntity } --- @param registration_number uint64
local function on_entity_removed(event) --- @param registration ExpScenario_Protection.Registration
Protection.remove_entity(event.entity) 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 end
--- Forget protected removals older than the repeat lifetime --- Forget protected removals older than the repeat lifetime
@@ -234,10 +261,8 @@ end
local e = defines.events local e = defines.events
Protection.events[e.on_pre_player_mined_item] = on_pre_player_mined_item 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_object_destroyed] = on_object_destroyed
Protection.events[e.on_robot_pre_mined] = on_entity_removed Protection.events[Feature.events.on_config_updated] = on_config_updated
Protection.events[e.on_entity_died] = on_entity_removed
Protection.events[e.script_raised_destroy] = on_entity_removed
Protection.on_nth_tick[3600 * 5] = clear_old_repeats Protection.on_nth_tick[3600 * 5] = clear_old_repeats
return feature:guard(Protection) return feature:guard(Protection)
+1 -1
View File
@@ -35,7 +35,7 @@ end
apply_offset_to_array(config.turrets.locations, config.turrets.offset, 1, 2) 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.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.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) apply_offset_to_array(config.entities.locations, config.entities.offset, 2, 3)
--- Get or create the force used for entities in spawn --- Get or create the force used for entities in spawn
+61 -110
View File
@@ -1,22 +1,18 @@
--[[-- ExpScenario - Features --[[-- ExpScenario - Features
Features which the controller can enable, disable, and configure while the game is running 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, The config table is changed in place when the controller sends values, so read
so read values when they are used rather than copying them into locals when the them where they are used rather than caching them when the file loads. Values
file loads. Booleans, numbers, and strings can be overridden, as can lists and read while the file loads, such as on_nth_tick periods, are not listed in features.ts.
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.
--- Registering a feature, small configs live at the top of the file which uses them: --- Registering a feature, small configs live at the top of the file which uses them:
local Feature = require("modules/exp_scenario/features") local Feature = require("modules/exp_scenario/features")
local feature, config = Feature.register("my_feature", { local feature, config = Feature.register("my_feature", {
show_message = true, show_message = true, -- booleans, numbers, and strings
role_id = Feature.optional("number"), role_id = Feature.optional("number"), -- no default
item_names = Feature.set{ "iron-plate" }, item_names = Feature.set{ "iron-plate" }, -- indexed by name
surface_names = Feature.list{ "nauvis" }, surface_names = Feature.list{ "nauvis" },
section = { count = 1 }, -- addressed as "section.count"
}) })
--- Handlers do nothing while the feature is disabled: --- 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 }, events = { [defines.events.on_player_joined_game] = on_player_joined_game },
} }
--- Toolbar buttons are hidden while disabled, which also hides their left element: --- Toolbar buttons and commands:
Gui.toolbar.create_button{ Gui.toolbar.create_button{ visible = function(player) return feature:is_enabled() end }
visible = function(player, element) return feature:is_enabled() end,
}
--- Commands are denied and left out of help while disabled:
Commands.new("my_command", { "..." }):add_flags{ feature = feature } 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: --- Changes are raised per value:
[Feature.events.on_config_updated] = function(event) end, -- { feature_name, path, old_value, new_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") local Storage = require("modules/exp_util/storage")
--- @class ExpScenario.FeatureField --- @class ExpScenario.FeatureField
--- @field parent table The table holding the value within the config --- @field path string
--- @field key string The key of the value within its parent --- @field parent table
--- @field key string
--- @field default any --- @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 --- @class ExpScenario.Features
local Feature = { local Feature = {
_registered = {}, --- @type table<string, ExpScenario.Feature> _registered = {}, --- @type table<string, ExpScenario.Feature>
events = { events = {
--- Raised for each value which changes when the controller updates a feature
--- @type EventData.ExpScenario.on_config_updated --- @type EventData.ExpScenario.on_config_updated
on_config_updated = script.generate_event_name(), 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 --- @class ExpScenario.Feature
--- @field name string --- @field name string
--- @field config table Changed in place when the config is updated --- @field config table
--- @field fields table<string, ExpScenario.FeatureField> The values in the config by path --- @field fields table<string, ExpScenario.FeatureField> By path
--- @field overrides table<string, any> The overrides from the controller by path, restored from storage on load --- @field values table<string, any> Last received from the controller, restored from storage on load
Feature._prototype = {} Feature._prototype = {}
--- @class EventData.ExpScenario.on_config_updated : EventData --- @class EventData.ExpScenario.on_config_updated : EventData
--- @field feature_name string --- @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 old_value any
--- @field new_value any --- @field new_value any
@@ -75,17 +63,18 @@ local Feature_mt = {
__index = Feature._prototype, __index = Feature._prototype,
} }
--- The overrides of each feature by name, only these are stored because the rest is rebuilt when the file loads --- Only the values are stored, the rest is rebuilt when the file loads
local stored_overrides = {} --- @type table<string, table<string, any>> local stored_values = {} --- @type table<string, table<string, any>>
Storage.register(stored_overrides, function(tbl) Storage.register(stored_values, function(tbl)
stored_overrides = tbl stored_values = tbl
for name, feature in pairs(Feature._registered) do for name, feature in pairs(Feature._registered) do
feature.overrides = tbl[name] or {} feature.values = tbl[name] or {}
feature:_apply() for path, field in pairs(feature.fields) do
feature:_set_field(field, feature.values[path])
end
end end
end) end)
--- Check if a value is a list of strings, as sent by the controller for lists and sets
--- @param value any --- @param value any
--- @return boolean --- @return boolean
local function is_string_list(value) local function is_string_list(value)
@@ -97,25 +86,22 @@ local function is_string_list(value)
return true return true
end 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 a any
--- @param b any --- @param b any
--- @return boolean --- @return boolean
local function values_equal(a, b) local function values_equal(a, b)
if type(a) ~= "table" or type(b) ~= "table" then return a == b end 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 for key, value in pairs(a) do
if b[key] ~= value then return false end if b[key] ~= value then return false end
end end
for key in pairs(b) do
if a[key] == nil then return false end
end
return true return true
end 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 = {} local typed_mt = {}
--- Convert a list of strings into a set
--- @param list string[] --- @param list string[]
--- @return table<string, true> --- @return table<string, true>
local function list_to_set(list) local function list_to_set(list)
@@ -126,58 +112,58 @@ local function list_to_set(list)
return set return set
end 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 fields table<string, ExpScenario.FeatureField>
--- @param tbl table --- @param tbl table
--- @param prefix string --- @param prefix string
local function collect_fields(fields, tbl, prefix) local function collect_fields(fields, tbl, prefix)
for key, value in pairs(tbl) do for key, value in pairs(tbl) do
if type(key) == "string" then 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 if type(value) == "table" then
local typed = getmetatable(value) == typed_mt and value if getmetatable(value) == typed_mt then
if typed then field.type = value.type
field.type = typed.type field.default = value.default
field.default = typed.default tbl[key] = value.default
tbl[key] = typed.default
elseif type(next(value)) == "string" then elseif type(next(value)) == "string" then
collect_fields(fields, value, prefix .. key .. ".") collect_fields(fields, value, path .. ".")
field = nil field = nil
end end
end end
if field then if field then
fields[prefix .. key] = field fields[path] = field
end end
end end
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" --- @param value_type "boolean" | "number" | "string"
--- @return any --- @return any
function Feature.optional(value_type) function Feature.optional(value_type)
return setmetatable({ type = value_type }, typed_mt) return setmetatable({ type = value_type }, typed_mt)
end end
--- Declare a list of strings which can be overridden --- A list of strings
--- @param items string[] --- @param items string[]
--- @return string[] --- @return string[]
function Feature.list(items) function Feature.list(items)
return setmetatable({ type = "list", default = items }, typed_mt) return setmetatable({ type = "list", default = items }, typed_mt)
end 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[] --- @param items string[]
--- @return table<string, true> --- @return table<string, true>
function Feature.set(items) function Feature.set(items)
return setmetatable({ type = "set", default = list_to_set(items) }, typed_mt) return setmetatable({ type = "set", default = list_to_set(items) }, typed_mt)
end 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 name string
--- @param config table? --- @param config table?
--- @return ExpScenario.Feature feature --- @return ExpScenario.Feature feature
--- @return table config The same table as feature.config --- @return table config
function Feature.register(name, config) function Feature.register(name, config)
assert(Feature._registered[name] == nil, "Feature already registered: " .. name) assert(Feature._registered[name] == nil, "Feature already registered: " .. name)
config = config or {} config = config or {}
@@ -192,21 +178,19 @@ function Feature.register(name, config)
name = name, name = name,
config = config, config = config,
fields = fields, fields = fields,
overrides = {}, values = {},
}, Feature_mt) --[[@as ExpScenario.Feature]] }, Feature_mt) --[[@as ExpScenario.Feature]]
Feature._registered[name] = feature Feature._registered[name] = feature
return feature, config return feature, config
end end
--- Get a registered feature by name
--- @param name string --- @param name string
--- @return ExpScenario.Feature --- @return ExpScenario.Feature
function Feature.get(name) function Feature.get(name)
return Feature._registered[name] or error("Unknown feature: " .. tostring(name), 2) return Feature._registered[name] or error("Unknown feature: " .. tostring(name), 2)
end end
--- Check if a field can take a value
--- @param field ExpScenario.FeatureField --- @param field ExpScenario.FeatureField
--- @param value any --- @param value any
--- @return boolean --- @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") return type(value) == field.type and (field.type == "boolean" or field.type == "number" or field.type == "string")
end 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 --- @package
--- @param path string
--- @param field ExpScenario.FeatureField --- @param field ExpScenario.FeatureField
--- @param value any
--- @return any # The value which was set --- @return any # The value which was set
function Feature._prototype:_apply_field(path, field) function Feature._prototype:_set_field(field, value)
local value = self.overrides[path] 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 if value == nil then
value = field.default 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 elseif field.type == "set" then
value = list_to_set(value) value = list_to_set(value)
end end
@@ -236,21 +220,12 @@ function Feature._prototype:_apply_field(path, field)
return value return value
end 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 --- @return boolean
function Feature._prototype:is_enabled() function Feature._prototype:is_enabled()
return self.config.enabled return self.config.enabled
end 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 --- @generic T : table
--- @param lib T --- @param lib T
--- @return T --- @return T
@@ -269,39 +244,16 @@ function Feature._prototype:guard(lib)
return lib return lib
end end
--- Replace the overrides of the feature, then raise on_config_updated for each value which changed --- Replace every value, then raise on_config_updated for each one which changed
--- @param enabled boolean --- @param values table<string, any> By path, "enabled" included
--- @param values table<string, boolean | number | string | string[]> function Feature._prototype:update_config(values)
function Feature._prototype:update_config(enabled, values) self.values = values
local old_overrides = self.overrides stored_values[self.name] = values
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
local updates = {} local updates = {}
for path in pairs(paths) do for path, field in pairs(self.fields) do
local field = self.fields[path]
local old_value = field.parent[field.key] 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 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 } updates[#updates + 1] = { feature_name = self.name, path = path, old_value = old_value, new_value = new_value }
end end
@@ -314,16 +266,15 @@ end
--- @class ExpScenario.FeatureUpdate --- @class ExpScenario.FeatureUpdate
--- @field name string --- @field name string
--- @field enabled boolean --- @field values table<string, any>
--- @field values table<string, boolean | number | string | string[]>
--- 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[] --- @param updates ExpScenario.FeatureUpdate[]
function Feature.receive_update(updates) function Feature.receive_update(updates)
for _, update in ipairs(updates) do for _, update in ipairs(updates) do
local feature = Feature._registered[update.name] local feature = Feature._registered[update.name]
if feature then if feature then
feature:update_config(update.enabled, update.values) feature:update_config(update.values)
end end
end end
end end
+10 -6
View File
@@ -4,6 +4,7 @@ import { Instance } from "@clusterio/host";
import { InstancePlugin } from "../dist/node/instance.js"; import { InstancePlugin } from "../dist/node/instance.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js"; import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.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 // The instance validates message classes against the link registry
for (const Message of pluginDeclaration.messages) { 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[0] instanceof lib.SubscriptionRequest, "subscribes to updates first");
t3.ok(state.sent[1] instanceof messages.FeatureListRequest, "then lists the features"); t3.ok(state.sent[1] instanceof messages.FeatureListRequest, "then lists the features");
t3.strictSame( const [update] = decodeRcon(state.rcons[0]);
decodeRcon(state.rcons[0]), const deathMarkers = features.find(feature => feature.name === "death_markers");
[{ name: "death_markers", enabled: false, values: { show_map_markers: false } }], 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 => { t2.test(".handleFeatureUpdatedEvent() only sends while the game is up", async t3 => {
@@ -83,8 +86,9 @@ t.test("class InstancePlugin", t2 => {
await plugin.onStart(); await plugin.onStart();
state.rcons.length = 0; state.rcons.length = 0;
await plugin.handleFeatureUpdatedEvent(event); await plugin.handleFeatureUpdatedEvent(event);
t3.strictSame(decodeRcon(state.rcons[0]), [{ name: "afk_kick", enabled: true, values: { afk_minutes: 5 } }], const updates = decodeRcon(state.rcons[0]);
"deleted features are left out"); 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(); await plugin.onExit();
state.rcons.length = 0; state.rcons.length = 0;
+6
View File
@@ -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 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 load_config fun(name: string): ExpScenario.Feature Load module/config/<name>.lua
--- @field logged string[] Messages passed to log --- @field logged string[] Messages passed to log
--- @field events table[] Raised events, name and tick filled in
return Framework.suite(function(env) return Framework.suite(function(env)
--- @cast env ExpScenario.TestEnv --- @cast env ExpScenario.TestEnv
local callback --- @type fun(tbl: table) local callback --- @type fun(tbl: table)
env.logged = {} env.logged = {}
log = function(message) env.logged[#env.logged + 1] = message end 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{ env.extend_requires{
["modules/exp_util/storage"] = { ["modules/exp_util/storage"] = {
register = function(tbl, fn) register = function(tbl, fn)
+70 -84
View File
@@ -1,11 +1,12 @@
local Suite = ... --- @type Suite<ExpScenario.TestEnv> 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 function updates(env)
local rtn = {} local rtn = {}
for _, event in ipairs(env.events) do 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 end
table.sort(rtn, function(a, b) return a[1] < b[1] end)
return rtn return rtn
end 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") Suite.throws(function() env.Feature.register("on", {}) end, "Feature already registered: on", "names are unique")
end) 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) Suite.test("get() finds registered features", function(env)
local feature = env.Feature.register("test") local feature = env.Feature.register("test")
Suite.eq(env.Feature.get("test") == feature, true, "by name") Suite.eq(env.Feature.get("test") == feature, true, "by name")
Suite.throws(function() env.Feature.get("unknown") end, "Unknown feature: unknown", "unknown names error") Suite.throws(function() env.Feature.get("unknown") end, "Unknown feature: unknown", "unknown names error")
end) end)
Suite.test("update_config() changes the config in place", function(env) Suite.test("update_config() sets every value, missing ones to their default", function(env)
local feature = env.Feature.register("test", { flag = true, count = 5, text = "a" }) local feature, config = env.Feature.register("test", { flag = true, count = 5, text = "a" })
local config = feature.config feature:update_config{ enabled = false, flag = false, count = 7 }
feature:update_config(false, { flag = false, count = 7 }) Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values are set")
Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values replace the defaults")
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(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) end)
Suite.test("update_config() raises on_config_updated for each changed value", function(env) 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 } }) 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 }) feature:update_config{ enabled = false, flag = true, names = { "a" }, ["section.count"] = 2 }
Suite.eq(#env.events, 2, "unchanged values raise nothing")
Suite.eq(env.Feature.events.on_config_updated, assert(env.events[1]).name, "the event is on_config_updated") Suite.eq(env.Feature.events.on_config_updated, assert(env.events[1]).name, "the event is on_config_updated")
Suite.eq(updates(env), {
local seen = updates(env) { "enabled", true, false },
table.sort(seen, function(a, b) return a[2] < b[2] end) { "section.count", 1, 2 },
Suite.eq(seen, { }, "with the path, old value, and new value, unchanged values raise nothing")
{ "test", "enabled", true, false },
{ "test", "section.count", 1, 2 },
}, "with the path, old value, and new value")
end) 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 function check() return true end
local feature = env.Feature.register("test", { flag = true, check = check, icon = nil }) local feature, config = env.Feature.register("test", { flag = true, check = check })
feature:update_config(true, { flag = "yes", check = false, icon = "x" }) feature:update_config{ enabled = true, flag = "yes", check = false }
Suite.eq(feature.config, { enabled = true, flag = true, check = check }, "wrong types, functions, and unknown keys are skipped") Suite.eq(config, { enabled = true, flag = true, check = check }, "wrong types and functions keep their default")
Suite.eq(#env.logged, 3, "each one is logged") Suite.eq(#env.logged, 2, "each one is logged")
Suite.eq(env.storage.test, { enabled = true, flag = "yes", check = false }, "unknown keys are not stored")
end) end)
Suite.test("receive_update() updates known features", function(env) Suite.test("receive_update() updates known features", function(env)
local feature = env.Feature.register("test", { flag = true }) local feature = env.Feature.register("test", { flag = true })
env.Feature.receive_update{ env.Feature.receive_update{
{ name = "test", enabled = true, values = { flag = false } }, { name = "test", values = { enabled = true, flag = false } },
{ name = "unknown", enabled = false, values = {} }, { name = "unknown", values = { enabled = false } },
} }
Suite.eq(feature.config.flag, false, "the known feature changed") Suite.eq(feature.config.flag, false, "the known feature changed")
Suite.eq(env.storage.unknown, nil, "unknown features are not stored") Suite.eq(env.storage.unknown, nil, "unknown features are not stored")
end) end)
Suite.test("on_load applies the overrides from storage without raising events", function(env) Suite.test("on_load applies the stored values without raising events", function(env)
local feature = env.Feature.register("test", { flag = true }) local feature, config = env.Feature.register("test", { flag = true })
env.on_load{ test = { enabled = false, flag = false } } env.on_load{ test = { enabled = false, flag = false, gone = 1 } }
Suite.eq(feature.config, { enabled = false, flag = false }, "the saved overrides apply") Suite.eq(config, { enabled = false, flag = false }, "the saved values apply, unknown ones are skipped")
Suite.empty(env.events, "nothing is raised") Suite.empty(env.events, "nothing is raised")
feature:update_config(true, {}) feature:update_config{ enabled = true }
Suite.eq(env.storage, { test = { enabled = true } }, "later updates go to the loaded storage table") Suite.eq(env.storage, { test = { enabled = true } }, "later updates replace the stored values")
end) end)
Suite.test("guard() skips handlers while the feature is disabled", function(env) 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.events.on_event("a")
lib.on_nth_tick[60]("b") lib.on_nth_tick[60]("b")
feature:update_config(false, {}) feature:update_config{ enabled = false }
lib.events.on_event("c") lib.events.on_event("c")
lib.on_nth_tick[60]("d") lib.on_nth_tick[60]("d")
Suite.eq(calls, { "a", "b" }, "only called while enabled") Suite.eq(calls, { "a", "b" }, "only called while enabled")
@@ -95,70 +103,48 @@ end)
Suite.test("register() addresses nested values by path", function(env) Suite.test("register() addresses nested values by path", function(env)
local offset = { 1, 2 } local offset = { 1, 2 }
local feature = env.Feature.register("test", { section = { flag = true, count = 1 }, offset = offset }) local feature, config = env.Feature.register("test", { section = { flag = true, count = 1 }, offset = offset })
feature:update_config(true, { ["section.flag"] = false, offset = { "x" } }) feature:update_config{ enabled = true, ["section.flag"] = false, offset = { "x" } }
Suite.eq(feature.config.section, { flag = false, count = 1 }, "the nested value changes in place") Suite.eq(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") Suite.eq(config.offset, offset, "tables which are not sections can not be set")
feature:update_config(true, {}) feature:update_config{ enabled = true }
Suite.eq(feature.config.section.flag, true, "and goes back to its default") Suite.eq(config.section.flag, true, "and goes back to its default")
end) end)
Suite.test("list() declares a list of strings which can be overridden", function(env) Suite.test("list() declares a list of strings", function(env)
local feature = env.Feature.register("test", { names = env.Feature.list{ "a", "b" }, empty = env.Feature.list{}, plain = { "x" } }) local feature, config = 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") Suite.eq(config.names, { "a", "b" }, "the default is the list")
feature:update_config(true, { names = { "c" }, empty = { "d" }, plain = { "y" } }) feature:update_config{ enabled = true, names = { "c" }, empty = { "d" }, plain = { "y" } }
Suite.eq(feature.config.names, { "c" }, "a list is replaced") Suite.eq(config.names, { "c" }, "a list is replaced")
Suite.eq(feature.config.empty, { "d" }, "an empty list can be overridden") Suite.eq(config.empty, { "d" }, "an empty list can be set")
Suite.eq(feature.config.plain, { "x" }, "a plain table can not be overridden") Suite.eq(config.plain, { "x" }, "a plain table can not be set")
feature:update_config(true, { names = { 1 } }) feature:update_config{ enabled = true, names = { 1 } }
Suite.eq(feature.config.names, { "a", "b" }, "a list with other types is invalid") Suite.eq(config.names, { "a", "b" }, "a list with other types is invalid")
end) end)
Suite.test("set() declares a set of strings which is overridden with a list", function(env) Suite.test("set() declares a set of strings which is sent as a list", function(env)
local feature = env.Feature.register("test", { names = env.Feature.set{ "a" }, empty = env.Feature.set{} }) local feature, config = 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(config.names, { a = true }, "the default is a set")
Suite.eq(feature.config.empty, {}, "and can be empty") Suite.eq(config.empty, {}, "and can be empty")
feature:update_config(true, { names = { "b", "c" } }) feature:update_config{ enabled = true, names = { "b", "c" } }
Suite.eq(feature.config.names, { b = true, c = true }, "the list is converted to a set") Suite.eq(config.names, { b = true, c = true }, "the list is converted to a set")
env.on_load{ test = { enabled = true, names = { "d" } } } 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) end)
Suite.test("optional() declares a value without a default", function(env) Suite.test("optional() declares a value without a default", function(env)
local feature = env.Feature.register("test", { role_id = env.Feature.optional("number") }) local feature, config = env.Feature.register("test", { role_id = env.Feature.optional("number") })
Suite.eq(feature.config.role_id, nil, "nil until overridden") Suite.eq(config.role_id, nil, "nil until set")
feature:update_config(true, { role_id = 3 }) feature:update_config{ enabled = true, role_id = 3 }
Suite.eq(feature.config.role_id, 3, "overridden with the given type") Suite.eq(config.role_id, 3, "set with the given type")
feature:update_config(true, {}) feature:update_config{ enabled = true }
Suite.eq(feature.config.role_id, nil, "and back to nil") Suite.eq(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")
end) end)
Suite.test("config files register their feature", function(env) Suite.test("config files register their feature", function(env)
local feature = env.load_config("spawn_area") 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.enabled, false, "spawn_area can be changed")
Suite.eq(feature.config.turrets.ammo_type, "uranium-rounds-magazine", "other values keep their default") Suite.eq(feature.config.turrets.ammo_type, "uranium-rounds-magazine", "other values keep their default")
end) end)
+53 -50
View File
@@ -39,7 +39,7 @@ function groupFields(fields: FeatureField[]) {
return [...groups.entries()]; 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) { function formatSectionTitle(name: string) {
return name return name
.replace(/\./g, " / ") .replace(/\./g, " / ")
@@ -54,7 +54,7 @@ function matches(text: string, query: string) {
return text.toLowerCase().includes(query); 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) { function searchFields(feature: Feature, query: string) {
if (!query || matches(feature.title, query) || matches(feature.description, query) || matches(feature.name, query)) { if (!query || matches(feature.title, query) || matches(feature.description, query) || matches(feature.name, query)) {
return feature.fields; return feature.fields;
@@ -64,10 +64,7 @@ function searchFields(feature: Feature, query: string) {
)); ));
} }
/** /** Renders a setting like the config pages do, registered input components take priority */
* 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
*/
function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void }) { function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void }) {
const { field, value, disabled, onChange } = props; const { field, value, disabled, onChange } = props;
const control = useContext(ControlContext); 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: { function FieldItem(props: {
field: FeatureField, value: FeatureValue, stored: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void, field: FeatureField, value: FeatureValue, stored: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void,
}) { }) {
@@ -217,7 +214,51 @@ function FeatureNav(props: { feature: Feature, enabled: boolean }) {
</div>; </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() { export default function FeaturesPage() {
const control = useContext(ControlContext); const control = useContext(ControlContext);
const account = useAccount(); const account = useAccount();
@@ -226,7 +267,7 @@ export default function FeaturesPage() {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const canEdit = Boolean(account.hasPermission("exp_scenario.config.edit")); 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) { if (!synced) {
return <PageLayout nav={[{ name: "Scenario Features" }]}> return <PageLayout nav={[{ name: "Scenario Features" }]}>
<PageHeader title="Scenario Features" /> <PageHeader title="Scenario Features" />
@@ -240,27 +281,8 @@ export default function FeaturesPage() {
values: { ...stored[name].values, ...pending[name]?.values }, 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) { function change(name: string, update: (entry: PendingChanges[string]) => void) {
setPending(prev => { setPending(prev => withChange(prev, stored[name], name, update));
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;
});
} }
function applyChanges() { function applyChanges() {
@@ -284,26 +306,7 @@ export default function FeaturesPage() {
return <PageLayout nav={[{ name: "Scenario Features" }]}> return <PageLayout nav={[{ name: "Scenario Features" }]}>
<PageHeader title="Scenario Features" /> <PageHeader title="Scenario Features" />
{Object.keys(pending).length > 0 && <div style={{ {Object.keys(pending).length > 0 && <UnsavedChangesBar onRevert={() => setPending({})} onApply={applyChanges} />}
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>}
<Input.Search placeholder="Search features and settings" allowClear <Input.Search placeholder="Search features and settings" allowClear
onChange={e => setSearch(e.target.value)} style={{ marginBottom: 16 }} /> onChange={e => setSearch(e.target.value)} style={{ marginBottom: 16 }} />
@@ -320,7 +323,7 @@ export default function FeaturesPage() {
</div> </div>
</Col> </Col>
<Col flex="auto" style={{ minWidth: 0 }}> <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"> <ConfigProvider componentSize="small">
<Space direction="vertical" style={{ width: "100%" }}> <Space direction="vertical" style={{ width: "100%" }}>
{shown.map(({ feature, fields }) => <FeatureSection {shown.map(({ feature, fields }) => <FeatureSection