Cover guis, commands, and intervals in the features framework

Review feedback from Cooldude on the first version.

Features.register is renamed to Features.config, and guard also takes a
feature name so a feature without settings needs no config call.
Autofill uses this. Small configs now live at the top of the file that
uses them: death markers, mine depletion, station auto name, and
lawnmower. AFK kick and chat auto reply keep separate files because
they contain functions.

Periods no longer need a restart. A lib can list intervals, which map a
config key to a handler that runs every config[key] seconds. They are
checked once a second with a stateless tick check. AFK kick and death
markers use this and expose their periods on the page.

Guis: receive_update raises on_feature_changed, and control/features.lua
refreshes every player's gui when it fires. Autofill's toolbar button
checks Features.is_enabled, and hiding the button also hides its left
element. Quick actions refresh on the event too.

Commands: add_flags{ feature = ... } ties a command to a feature, and a
new authority denies it while the feature is disabled. The custom help
and quick actions already leave out denied commands. Lawnmower uses this
and is now added as a lib, so its destroy_decoratives handlers are
actually registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-09-28 18:43:31 +00:00
1 parent 88358b23b9
commit 69e9f172a3
21 files changed
+304 -116

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
--- Settings for lawnmower
-- @config lawnmower
return {
destroy_decoratives = false,
}
+41 -2
View File
@@ -1,8 +1,9 @@
/**
* The scenario features which can be configured from the web interface.
*
* Defaults must match module/config/<name>.lua, test/features.test.js checks
* this. Only list settings which the lua side reads at runtime.
* 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.
*/
export type FeatureValue = boolean | number | string;
@@ -71,8 +72,23 @@ export const features: Feature[] = [
min: 0,
unit: "minutes",
},
{
name: "update_seconds",
title: "Check every",
description: "How often to check for active players",
type: "number",
default: 1800,
min: 1,
unit: "seconds",
},
],
},
{
name: "autofill",
title: "Autofill",
description: "Fill ammo and fuel into entities when they are built, configured by each player from the toolbar",
fields: [],
},
{
name: "chat_auto_reply",
title: "Chat Auto Reply",
@@ -141,6 +157,29 @@ export const features: Feature[] = [
type: "boolean",
default: true,
},
{
name: "check_map_tags_seconds",
title: "Check map markers every",
description: "How often to replace map markers which were removed",
type: "number",
default: 300,
min: 1,
unit: "seconds",
},
],
},
{
name: "lawnmower",
title: "Lawnmower",
description: "The /lawnmower command which clears corpses and nuclear ground",
fields: [
{
name: "destroy_decoratives",
title: "Clear decoratives when building",
description: "Remove decoratives under entities when they are built",
type: "boolean",
default: false,
},
],
},
{
@@ -5,6 +5,7 @@ Adds a permission authority which checks the clusterio permission for a command
local Commands = require("modules/exp_commands")
local add, allow, deny = Commands.add_permission_authority, Commands.status.success, Commands.status.unauthorised
local Features = require("modules/exp_scenario/features")
local Roles = require("modules/exp_roles")
local player_has_permission = Roles.player_has_permission
@@ -22,6 +23,17 @@ authorities.exp_permission =
end
end)
--- Commands flagged with a feature are denied while it is disabled, see features.lua
authorities.feature_enabled =
add(function(player, command)
local feature = command.flags.feature
if feature and not Features.is_enabled(feature) then
return deny{ "exp-commands-authorities_feature.deny" }
else
return allow()
end
end)
Roles.define_permission_trigger("core.admin", function(player, state)
if state then
Commands.unlock_system_commands(player.name)
+15 -12
View File
@@ -4,9 +4,13 @@ Adds a command that clean up biter corpse and nuclear hole
local AABB = require("modules/exp_util/aabb")
local Commands = require("modules/exp_commands")
local Features = require("modules/exp_scenario/features")
local Selection = require("modules/exp_util/selection")
local SelectArea = Selection.connect("ExpCommand_Lawnmower")
local config = require("modules.exp_legacy.config.lawnmower")
local config = Features.config("lawnmower", {
destroy_decoratives = false, --- @setting destroy_decoratives remove decoratives under entities when they are built
})
--- @class ExpCommand_Lawnmower.commands
local commands = {}
@@ -15,6 +19,7 @@ local commands = {}
--- @class ExpCommands_Lawnmower.commands.lawnmower: ExpCommand
--- @overload fun(player: LuaPlayer)
commands.lawnmower = Commands.new("lawnmower", { "exp-commands_lawnmower.description" })
:add_flags{ feature = config }
:register(function(player)
if SelectArea:stop(player) then
return Commands.status.success{ "exp_util.selection_exit", { "exp-commands_lawnmower.selection-name" } }
@@ -51,6 +56,7 @@ end)
--- @param event EventData.on_built_entity | EventData.on_robot_built_entity | EventData.script_raised_built | EventData.script_raised_revive
local function destroy_decoratives(event)
if not config.destroy_decoratives then return end
local entity = event.entity
if entity.type ~= "entity-ghost" and entity.type ~= "tile-ghost" and entity.prototype.selectable_in_game then
entity.surface.destroy_decoratives{ area = entity.selection_box }
@@ -58,16 +64,13 @@ local function destroy_decoratives(event)
end
local e = defines.events
local events = {}
if config.destroy_decoratives then
events[e.on_built_entity] = destroy_decoratives
events[e.on_robot_built_entity] = destroy_decoratives
events[e.script_raised_built] = destroy_decoratives
events[e.script_raised_revive] = destroy_decoratives
end
return {
events = events,
return Features.guard(config, {
events = {
[e.on_built_entity] = destroy_decoratives,
[e.on_robot_built_entity] = destroy_decoratives,
[e.script_raised_built] = destroy_decoratives,
[e.script_raised_revive] = destroy_decoratives,
},
commands = commands,
}
})
+2 -2
View File
@@ -4,13 +4,13 @@
local Features = require("modules/exp_scenario/features")
local Roles = require("modules/exp_roles")
return Features.register("afk_kick", {
return Features.config("afk_kick", {
admin_as_active = true, --- @setting admin_as_active When true admins will be treated as active regardless of afk time
trust_as_active = true, --- @setting trust_as_active When true trusted players (by playtime) will be treated as active regardless of afk time
afk_minutes = 10, --- @setting afk_minutes The time in minutes that must pass for a player to be considered afk
kick_minutes = 30, --- @setting kick_minutes The time in minutes that must pass without any active players for all players to be kicked
trust_minutes = 600, --- @setting trust_minutes The time in minutes that a player must be online for to count as trusted
update_time = 3600 * 30, --- @setting update_time How often in ticks the script checks for active players, needs a restart to change
update_seconds = 1800, --- @setting update_seconds How often in seconds the script checks for active players
custom_active_check = function(player)
local veteran = Roles.get_role_by_name("Veteran")
return veteran ~= nil and not Roles.get_player_highest_role(player):is_lower_than(veteran)
@@ -25,7 +25,7 @@ local afk_time_units = {
seconds = true,
}
return Features.register("chat_auto_reply", {
return Features.config("chat_auto_reply", {
--- @type table<string, LocalisedString | fun(player: LuaPlayer, is_command: boolean): LocalisedString>
messages = { --- @setting messages will trigger when ever the word is said
["discord"] = { "info.discord", config_server_detail["discord"] },
@@ -1,15 +0,0 @@
--- This config controls what happens when a player dies mostly about map markers and item collection
-- @config Death-Markers
local Features = require("modules/exp_scenario/features")
return Features.register("death_markers", {
collect_corpses = true, --- @setting collect_corpses enables items being returned to the spawn point in chests upon corpse expiring
show_map_markers = true, --- @setting show_map_markers shows markers on the map where bodies are
clean_map_markers = false, --- @setting clean_map_markers removes the map marker once the body is gone
include_time_of_death = true, --- @setting include_time_of_death weather to include the time of death on the map marker
map_icon = nil, --- @setting map_icon the icon that the map marker shows; nil means no icon; format as a SingleID
show_light_at_corpse = true, --- @setting show_light_at_corpse if a light should be rendered at the corpse
show_line_to_corpse = true, --- @setting show_line_to_corpse if a line should be rendered from you to your corpse
period_check_map_tags = 60 * 60 * 5, --- @setting period_check_map_tags ticks between checks for missing map markers, needs a restart to change
})
@@ -1,10 +0,0 @@
--- Settings for mine depletion
-- @config Mine-Depletion
local Features = require("modules/exp_scenario/features")
return Features.register("mine_depletion", {
fluid = true, --- @setting fluid When true, checks for for fluid pipes when removing miners
chest = true, --- @setting chest When true, checks for for chest when removing miners
beacon = true, --- @setting beacon When true, checks for for beacon when removing miners
})
@@ -1,16 +0,0 @@
--- Settings for naming train stations when they are built
-- @config Station-Auto-Name
local Features = require("modules/exp_scenario/features")
return Features.register("station_auto_name", {
--[[
__icon__
__item_name__
__backer_name__
__direction__
__x__
__y__
]]
station_name = "[L] __icon__", --- @setting station_name the name given to new stations, uses the placeholders above
})
+2 -1
View File
@@ -11,6 +11,7 @@ require("modules/exp_scenario/commands/_types")
--- Commands with events
add(require("modules/exp_scenario/commands/protected_entities"))
add(require("modules/exp_scenario/commands/protected_tags"))
add(require("modules/exp_scenario/commands/lawnmower"))
--- Commands
require("modules/exp_scenario/commands/admin_chat")
@@ -24,7 +25,6 @@ require("modules/exp_scenario/commands/enemy")
require("modules/exp_scenario/commands/home")
require("modules/exp_scenario/commands/jail")
require("modules/exp_scenario/commands/kill")
require("modules/exp_scenario/commands/lawnmower")
require("modules/exp_scenario/commands/locate")
require("modules/exp_scenario/commands/me")
require("modules/exp_scenario/commands/rainbow")
@@ -50,6 +50,7 @@ add(require("modules/exp_scenario/control/death_markers"))
add(require("modules/exp_scenario/control/deconstruction_log"))
add(require("modules/exp_scenario/control/degrading_tiles"))
add(require("modules/exp_scenario/control/discord_alerts"))
add(require("modules/exp_scenario/control/features"))
add(require("modules/exp_scenario/control/extra_logging"))
add(require("modules/exp_scenario/control/fast_deconstruction"))
add(require("modules/exp_scenario/control/help_bubbles"))
+2 -2
View File
@@ -80,8 +80,8 @@ return Features.guard(config, {
events = {
[e.on_player_joined_game] = on_player_joined_game,
},
on_nth_tick = {
[config.update_time] = check_afk_players,
intervals = {
update_seconds = check_afk_players,
},
has_active_player = has_active_player,
})
+13 -3
View File
@@ -5,7 +5,17 @@ Makes markers on the map where places have died and reclaims items if not recove
local ExpUtil = require("modules/exp_util")
local Features = require("modules/exp_scenario/features")
local Storage = require("modules/exp_util/storage")
local config = require("modules/exp_scenario/config/death_markers")
local config = Features.config("death_markers", {
collect_corpses = true, --- @setting collect_corpses enables items being returned to the spawn point in chests upon corpse expiring
show_map_markers = true, --- @setting show_map_markers shows markers on the map where bodies are
clean_map_markers = false, --- @setting clean_map_markers removes the map marker once the body is gone
include_time_of_death = true, --- @setting include_time_of_death weather to include the time of death on the map marker
map_icon = nil, --- @setting map_icon the icon that the map marker shows; nil means no icon; format as a SingleID
show_light_at_corpse = true, --- @setting show_light_at_corpse if a light should be rendered at the corpse
show_line_to_corpse = true, --- @setting show_line_to_corpse if a line should be rendered from you to your corpse
check_map_tags_seconds = 300, --- @setting check_map_tags_seconds seconds between checks for missing map markers
})
local map_tag_time_format = ExpUtil.format_time_factory{ format = "short", hours = true, minutes = true }
@@ -139,8 +149,8 @@ end
local e = defines.events
return Features.guard(config, {
on_nth_tick = {
[config.period_check_map_tags] = check_map_tags,
intervals = {
check_map_tags_seconds = check_map_tags,
},
events = {
[e.on_player_died] = on_player_died,
+19
View File
@@ -0,0 +1,19 @@
--[[-- Control - Features
Refreshes the gui of every player when a feature is enabled or disabled, see features.lua
]]
local Features = require("modules/exp_scenario/features")
local Gui = require("modules/exp_gui")
--- Toolbar buttons of disabled features are hidden, which also hides their left elements
local function on_feature_changed()
for _, player in pairs(game.connected_players) do
Gui._ensure_consistency{ player_index = player.index }
end
end
return {
events = {
[Features.events.on_feature_changed] = on_feature_changed,
},
}
@@ -4,7 +4,12 @@ Marks mining drills for deconstruction when resources deplete
local Async = require("modules/exp_util/async")
local Features = require("modules/exp_scenario/features")
local config = require("modules/exp_scenario/config/mine_depletion")
local config = Features.config("mine_depletion", {
fluid = true, --- @setting fluid When true, checks for for fluid pipes when removing miners
chest = true, --- @setting chest When true, checks for for chest when removing miners
beacon = true, --- @setting beacon When true, checks for for beacon when removing miners
})
local floor = math.floor
@@ -3,7 +3,12 @@ Automatically name stations when they are placed based on closest resource and d
]]
local Features = require("modules/exp_scenario/features")
local config = require("modules/exp_scenario/config/station_auto_name")
local config = Features.config("station_auto_name", {
--- @setting station_name the name given to new stations, placeholders:
-- __icon__ __item_name__ __backer_name__ __direction__ __x__ __y__
station_name = "[L] __icon__",
})
local get_direction do
local directions = {
+81 -20
View File
@@ -1,32 +1,46 @@
--[[-- ExpScenario - Features
Feature config which the controller can change while the game is running
Features which the controller can enable, disable, and configure while the game is running
Each feature declares its defaults in config/<name>.lua by returning the table
from Features.register. The controller sends overrides over rcon, these are kept
in storage and copied onto that same table, so read values when they are used
rather than copying them into locals when the file loads.
A feature's config is the table returned by Features.config. The controller sends
overrides over rcon, these are kept in storage and copied onto that same table,
so read values when they are used rather than copying them into locals when the
file loads. Only boolean, number, and string defaults can be overridden.
Only boolean, number, and string defaults can be overridden. Values used while
the file loads, such as on_nth_tick periods, can not change without a restart
and should not be listed in features.ts.
Values used while the file loads can not change without a restart. Periods can
use intervals instead of on_nth_tick, everything else such as toolbar sprites
stays as a plain value and is not listed in features.ts.
--- Declaring a feature:
--- Declaring a feature with config, small configs live at the top of the file which uses them:
local Features = require("modules/exp_scenario/features")
return Features.register("my_feature", {
local config = Features.config("my_feature", {
show_message = true,
check_seconds = 60,
})
--- Using it from a control file, handlers do nothing while it is disabled:
local config = require("modules/exp_scenario/config/my_feature")
--- Handlers do nothing while the feature is disabled, a feature without config can be guarded by name:
return Features.guard(config, {
events = { [defines.events.on_player_joined_game] = on_player_joined_game },
intervals = { check_seconds = check_players }, -- Runs every config.check_seconds seconds
})
--- Toolbar buttons are hidden while disabled, which also hides their left element:
Gui.toolbar.create_button{
visible = function(player, element) return Features.is_enabled("my_feature") end,
}
--- Commands are denied and left out of help while disabled:
Commands.new("my_command", { "..." }):add_flags{ feature = "my_feature" }
]]
local Storage = require("modules/exp_util/storage")
--- @class ExpScenario.Features
local Features = {}
local Features = {
events = {
--- Raised when the controller changes a feature, gui and commands are refreshed by control/features.lua
on_feature_changed = script.generate_event_name(),
},
}
local overridable = {
boolean = true,
@@ -37,6 +51,8 @@ local overridable = {
--- @class ExpScenario.FeatureConfig
--- @field enabled boolean
--- @alias ExpScenario.Feature string | ExpScenario.FeatureConfig
--- The live config tables by feature name
local features = {} --- @type table<string, ExpScenario.FeatureConfig>
@@ -70,13 +86,14 @@ Storage.register(overrides, function(tbl)
end
end)
--- Register a feature and its defaults, features are enabled unless the defaults say otherwise
--- Declare a feature and its config, features are enabled unless the config says otherwise
--- @generic T : table
--- @param name string
--- @param config T
--- @param config T?
--- @return T
function Features.register(name, config)
assert(features[name] == nil, "Feature already registered: " .. name)
function Features.config(name, config)
assert(features[name] == nil, "Feature already declared: " .. name)
config = config or {} --[[@as T]]
if config.enabled == nil then
config.enabled = true
end
@@ -91,12 +108,55 @@ function Features.register(name, config)
return config
end
--- Wrap the event and on_nth_tick handlers of an event handler lib so they do nothing while the feature is disabled
--- Get the config of a feature from its name, or return the config given
--- @param feature ExpScenario.Feature
--- @return ExpScenario.FeatureConfig
local function resolve(feature)
if type(feature) == "table" then
return feature
end
return features[feature] or error("Unknown feature: " .. tostring(feature), 3)
end
--- Check if a feature is enabled
--- @param feature ExpScenario.Feature
--- @return boolean
function Features.is_enabled(feature)
return resolve(feature).enabled
end
--- Make the handlers of an event handler lib do nothing while the feature is disabled
-- A name which has not been declared is declared without config. The intervals field
-- maps config keys to handlers, each runs every config[key] seconds, checked once a second
--- @generic T : table
--- @param config ExpScenario.FeatureConfig
--- @param feature ExpScenario.Feature
--- @param lib T
--- @return T
function Features.guard(config, lib)
function Features.guard(feature, lib)
if type(feature) == "string" and features[feature] == nil then
Features.config(feature)
end
local config = resolve(feature)
local intervals = lib.intervals
if intervals then
lib.intervals = nil
lib.on_nth_tick = lib.on_nth_tick or {}
local every_second = lib.on_nth_tick[60]
lib.on_nth_tick[60] = function(event)
if every_second then
every_second(event)
end
-- Exactly one check each period lands within its first second
local tick = event.tick
for key, handler in pairs(intervals) do
if tick % (config[key] * 60) < 60 then
handler(event)
end
end
end
end
for _, handlers in pairs{ lib.events or {}, lib.on_nth_tick or {} } do
for key, handler in pairs(handlers) do
handlers[key] = function(event)
@@ -128,6 +188,7 @@ function Features.receive_update(updates)
overrides[name] = override
apply(name)
script.raise_event(Features.events.on_feature_changed, { feature_name = name })
end
end
end
+5 -4
View File
@@ -2,6 +2,7 @@
Adds a config menu for setting autofill of placed entities
]]
local Features = require("modules/exp_scenario/features")
local Gui = require("modules/exp_gui")
local Roles = require("modules/exp_roles")
local config = require("modules.exp_legacy.config.gui.autofill")
@@ -330,7 +331,7 @@ Gui.toolbar.create_button{
sprite = config.icon,
tooltip = { "exp-gui_autofill.tooltip-main" },
visible = function(player, element)
return Roles.player_has_permission(player, "exp_scenario.gui.autofill")
return Features.is_enabled("autofill") and Roles.player_has_permission(player, "exp_scenario.gui.autofill")
end
}
@@ -396,9 +397,9 @@ end
local e = defines.events
return {
return Features.guard("autofill", {
elements = Elements,
events = {
[e.on_built_entity] = on_built_entity,
}
}
},
})
@@ -4,6 +4,7 @@ Adds a few buttons for common actions
local Gui = require("modules/exp_gui")
local Commands = require("modules/exp_commands")
local Features = require("modules/exp_scenario/features")
local Roles = require("modules/exp_roles")
local addon_artillery = require("modules/exp_scenario/commands/artillery")
@@ -126,9 +127,17 @@ local function on_role_changed(event)
Elements.container.refresh_player(player)
end
--- Actions for commands of a disabled feature are hidden
local function on_feature_changed()
for _, player in pairs(game.connected_players) do
Elements.container.refresh_player(player)
end
end
return {
elements = Elements,
events = {
[Roles.events.on_player_roles_changed] = on_role_changed,
[Features.events.on_feature_changed] = on_feature_changed,
}
}
+3
View File
@@ -1,6 +1,9 @@
[exp-commands-authorities_role]
deny=Unauthorized, Access is denied due to missing permissions.
[exp-commands-authorities_feature]
deny=This command is disabled on this server.
[exp-commands-parse_role]
lower-role=Role is higher than your highest.
lower-role-player=Player has a higher role.
+21 -6
View File
@@ -3,7 +3,20 @@ import path from "node:path";
import t from "tap";
import { features, validateFeatureValues } from "../dist/node/features.js";
/** Read a literal default from a module/config file, only covers single line booleans, numbers, and strings. */
/** Every lua file in the module, by path relative to it. */
function luaFiles(dir, prefix = "") {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
const relative = path.posix.join(prefix, entry.name);
if (entry.isDirectory()) {
return luaFiles(path.join(dir, entry.name), relative);
}
return entry.name.endsWith(".lua") ? [[relative, fs.readFileSync(path.join(dir, entry.name), "utf8")]] : [];
});
}
const moduleFiles = luaFiles(path.join(import.meta.dirname, "..", "module"));
/** Read a literal default from a Features.config call, only covers single line booleans, numbers, and strings. */
function luaDefault(source, key) {
const match = new RegExp(`^\\s*${key} = (true|false|-?[\\d.]+|"[^"]*"),`, "m").exec(source);
return match ? JSON.parse(match[1]) : undefined;
@@ -12,9 +25,11 @@ function luaDefault(source, key) {
t.test("features", t2 => {
for (const feature of features) {
t2.test(feature.name, t3 => {
const file = path.join(import.meta.dirname, "..", "module", "config", `${feature.name}.lua`);
const source = fs.readFileSync(file, "utf8");
t3.match(source, `Features.register("${feature.name}"`, "the config file registers the feature");
const declarations = moduleFiles.filter(([, source]) => (
source.includes(`Features.config("${feature.name}"`) || source.includes(`Features.guard("${feature.name}"`)
));
t3.equal(declarations.length, 1, "one lua file declares the feature");
const source = declarations[0]?.[1] ?? "";
for (const field of feature.fields) {
t3.equal(luaDefault(source, field.name), field.default, `${field.name} default matches the lua side`);
}
@@ -32,8 +47,8 @@ t.test("validateFeatureValues()", t2 => {
);
t2.throws(() => validateFeatureValues("unknown", {}), { message: "Unknown feature unknown" });
t2.throws(
() => validateFeatureValues("death_markers", { period_check_map_tags: 60 }),
{ message: "Feature death_markers has no setting period_check_map_tags" },
() => validateFeatureValues("death_markers", { map_icon: "x" }),
{ message: "Feature death_markers has no setting map_icon" },
);
t2.throws(
() => validateFeatureValues("death_markers", { show_map_markers: "no" }),
+66 -14
View File
@@ -1,13 +1,21 @@
local Suite = ... --- @type Suite<ExpScenario.TestEnv>
Suite.test("register() enables features unless the defaults say otherwise", function(env)
Suite.eq(env.Features.register("on", { value = 1 }).enabled, true, "enabled by default")
Suite.eq(env.Features.register("off", { enabled = false }).enabled, false, "the defaults can disable it")
Suite.throws(function() env.Features.register("on", {}) end, "Feature already registered: on", "names are unique")
Suite.test("config() enables features unless the defaults say otherwise", function(env)
Suite.eq(env.Features.config("on", { value = 1 }).enabled, true, "enabled by default")
Suite.eq(env.Features.config("off", { enabled = false }).enabled, false, "the defaults can disable it")
Suite.eq(env.Features.config("empty"), { enabled = true }, "config is optional")
Suite.throws(function() env.Features.config("on", {}) end, "Feature already declared: on", "names are unique")
end)
Suite.test("receive_update() changes the registered table in place", function(env)
local config = env.Features.register("test", { flag = true, count = 5, text = "a" })
Suite.test("is_enabled() takes a name or a config", function(env)
local config = env.Features.config("test", { enabled = false })
Suite.eq(env.Features.is_enabled("test"), false, "by name")
Suite.eq(env.Features.is_enabled(config), false, "by config")
Suite.throws(function() env.Features.is_enabled("unknown") end, "Unknown feature: unknown", "unknown names error")
end)
Suite.test("receive_update() changes the config in place", function(env)
local config = env.Features.config("test", { flag = true, count = 5, text = "a" })
env.Features.receive_update{ { name = "test", enabled = false, values = { flag = false, count = 7 } } }
Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values replace the defaults")
@@ -16,9 +24,20 @@ Suite.test("receive_update() changes the registered table in place", function(en
Suite.eq(env.storage, { test = { enabled = true, text = "b" } }, "the overrides are kept in storage")
end)
Suite.test("receive_update() raises on_feature_changed for each known feature", function(env)
env.Features.config("test")
env.Features.receive_update{
{ name = "test", enabled = false, values = {} },
{ name = "unknown", enabled = false, values = {} },
}
Suite.eq(env.events, {
{ name = env.Features.events.on_feature_changed, tick = game.tick, feature_name = "test" },
}, "raised once")
end)
Suite.test("receive_update() ignores values which can not be overridden", function(env)
local function check() return true end
local config = env.Features.register("test", { flag = true, check = check, icon = nil })
local config = env.Features.config("test", { flag = true, check = check, icon = nil })
env.Features.receive_update{
{ name = "unknown", enabled = false, values = {} },
{ name = "test", enabled = true, values = { flag = "yes", check = false, icon = "x", extra = 1 } },
@@ -28,7 +47,7 @@ Suite.test("receive_update() ignores values which can not be overridden", functi
end)
Suite.test("on_load applies the overrides from storage", function(env)
local config = env.Features.register("test", { flag = true })
local config = env.Features.config("test", { flag = true })
env.on_load{ test = { enabled = false, flag = false } }
Suite.eq(config, { enabled = false, flag = false }, "the saved overrides apply")
@@ -37,7 +56,7 @@ Suite.test("on_load applies the overrides from storage", function(env)
end)
Suite.test("guard() skips handlers while the feature is disabled", function(env)
local config = env.Features.register("test", {})
local config = env.Features.config("test")
local calls = {}
local lib = env.Features.guard(config, {
events = { on_event = function(event) calls[#calls + 1] = event end },
@@ -53,11 +72,44 @@ Suite.test("guard() skips handlers while the feature is disabled", function(env)
Suite.eq(calls, { "a", "b" }, "only called while enabled")
end)
Suite.test("config files register their feature", function(env)
local config = env.load_config("death_markers")
env.Features.receive_update{ { name = "death_markers", enabled = true, values = { show_map_markers = false } } }
Suite.eq(config.show_map_markers, false, "death_markers can be changed")
Suite.eq(config.period_check_map_tags, 60 * 60 * 5, "other values keep their default")
Suite.test("guard() declares features by name", function(env)
local calls = 0
local lib = env.Features.guard("test", { events = { on_event = function() calls = calls + 1 end } })
env.Features.receive_update{ { name = "test", enabled = false, values = {} } }
lib.events.on_event()
Suite.eq(calls, 0, "the name is declared without config")
Suite.eq(env.Features.is_enabled("test"), false, "and can be looked up")
end)
Suite.test("guard() runs intervals once per period of the config value in seconds", function(env)
local config = env.Features.config("test", { every = 5 })
local ticks, seconds = {}, {}
local lib = env.Features.guard(config, {
on_nth_tick = { [60] = function(event) seconds[#seconds + 1] = event.tick end },
intervals = { every = function(event) ticks[#ticks + 1] = event.tick end },
})
Suite.eq(lib.intervals, nil, "intervals are replaced by on_nth_tick")
local function run_until(last)
for tick = 60, last, 60 do lib.on_nth_tick[60]{ tick = tick } end
end
run_until(1200)
Suite.eq(ticks, { 300, 600, 900, 1200 }, "every 5 seconds")
Suite.eq(#seconds, 20, "an existing handler every second still runs")
ticks = {}
env.Features.receive_update{ { name = "test", enabled = true, values = { every = 7 } } }
run_until(1260)
Suite.eq(ticks, { 420, 840, 1260 }, "the period can change at runtime")
end)
Suite.test("config files declare their feature", function(env)
env.extend_requires{ ["modules/exp_roles"] = {} }
local config = env.load_config("afk_kick")
env.Features.receive_update{ { name = "afk_kick", enabled = true, values = { afk_minutes = 3 } } }
Suite.eq(config.afk_minutes, 3, "afk_kick can be changed")
Suite.eq(config.kick_minutes, 30, "other values keep their default")
end)
return Suite.run()