Module:ControllerUtilities

From Against the Storm Official Wiki
Revision as of 15:14, 10 May 2024 by Aeredor (talk | contribs) (Added method to remove extra quotes from around the description.)

Documentation for this module may be created at Module:ControllerUtilities/doc

---
--- Centralizes some common functionality across controllers
---
---@module ControllerUtilities
ControllerUtilities = {}

--region Public Constants

--endregion



--region Private Constants

local TEMPLATE_SPRITE_FINDER = "Sprite"

local PATTERN_EVERYTHING_BETWEEN_COMMAS_AND_SPACES = "[^%s,][^,]+[^%s,]"
local PATTERN_SPRITE_NAME_CAPTURE_VALUE = '<sprite name="?([^>^"]+)"?>'
local PATTERN_EVERYTHING_IN_BETWEEN_DOUBLE_QUOTES = '^"?(.-)"?$'

--endregion



--region Public methods

--- Converts a string that represents a list of items into an array of those items. This is useful when a template parameter is used as a list and not a single value.
---
---@param commaSeparatedStringOfIDs string the list of IDs, separated by commas
---@param needsKeyValueFlags boolean true if the list should be made of keys (IDs) and values of `true`, false if the list should be an array of IDs
---@return table the IDs now separated into elements in a table
function ControllerUtilities.expandCommaSeparatedStringsIntoTable(commaSeparatedStringOfIDs, needsKeyValueFlags)

    if not commaSeparatedStringOfIDs or "" == commaSeparatedStringOfIDs then
        return {}
    end

    local list = {}
    for eachID in string.gmatch(commaSeparatedStringOfIDs, PATTERN_EVERYTHING_BETWEEN_COMMAS_AND_SPACES) do
        if needsKeyValueFlags then
            list[eachID] = true
        else
            table.insert(list, eachID)
        end
    end

    return list
end

--- Replaces any <sprite> XML tags in the description with Mediawiki markup using a separate template.
---
---@param description string anb otherwise unprocessed description from the data
---@param currentFrame table the Mediawiki frame that can expand templates
---@return string a modified description
function ControllerUtilities.findAndReplaceSpriteTagsWithFiles(description, currentFrame)

    description = description:gsub(PATTERN_SPRITE_NAME_CAPTURE_VALUE, function(name)
        return currentFrame:expandTemplate{
            title = TEMPLATE_SPRITE_FINDER,
            args = { ["id"] = name }
         }
    end)

    return description
end


--- Removes any enclosing double quotes from a description-like string.
---
---@param description string a description-type string, which may or may not be enclosed in double quotes
---@return string the same string, but with any enclosing double quotes removed
function ControllerUtilities.removeEnclosingDoubleQuotes(description)

    -- Need to store in a local variable because gsub returns two values
    local strippedString = description:gsub(PATTERN_EVERYTHING_IN_BETWEEN_DOUBLE_QUOTES, "%1")
    return strippedString
end

--endregion

return ControllerUtilities