Module:Labelled list hatnote

Documentation for this module may be created at Module:Labelled list hatnote/doc

--------------------------------------------------------------------------------
--                               Labelled list                                --
-- This module generates a hatnote with a colon-terminated label, e.g.,       --
-- "LABEL: [andList of pages]", for {{see also}} and similar templates.       --
--------------------------------------------------------------------------------

local mHatnote = require('Module:Hatnote')
local mHatlist = require('Module:Hatnote list')
local mArguments
local p = {}

-- Defaults for this module
local defaults = {
    label = 'See also', -- Fallback for the label argument
    labelForm = '%s: %s', -- Format for the label
    prefixes = {'label', 'label ', 'l'}, -- Prefixes for display parameters
    template = 'Module:Labelled list hatnote'
}

-- Preprocess display parameters and combine them with page arguments.
local function preprocessDisplays(args, prefixes)
    prefixes = prefixes or defaults.prefixes
    local pages = {}
    for k, v in pairs(args) do
        if type(k) == 'number' then
            local display
            for _, prefix in ipairs(prefixes) do
                display = args[prefix .. k]
                if display then break end
            end
            local page = display and string.format('%s|%s', v:gsub('|.*$', ''), display) or v
            table.insert(pages, page)
        end
    end
    return pages
end

-- Main entry point for the module.
function p.labelledList(frame)
    mArguments = mArguments or require('Module:Arguments')
    local args = mArguments.getArgs(frame, {parentOnly = true})
    local labels = {frame.args[1] or defaults.label, frame.args[2] or frame.args[1] or defaults.label}
    local pages = preprocessDisplays(args)
    local options = {
        extraclasses = frame.args.extraclasses,
        category = args.category,
        selfref = frame.args.selfref or args.selfref,
        template = frame:getParent():getTitle()
    }
    return p._labelledList(pages, labels, options)
end

-- Generates the hatnote text and wraps it.
function p._labelledList(pages, labels, options)
    if #pages == 0 then
        return mHatnote.makeWikitextError(
            'Page name not specified',
            (options.template or defaults.template) .. '#error',
            options.category
        )
    end

    local label = (#pages == 1 and labels[1] or labels[2]) or defaults.label
    local text = string.format(
        options.labelForm or defaults.labelForm,
        label,
        mHatlist.andList(pages, true)
    )
    return mHatnote._hatnote(text, {extraclasses = options.extraclasses, selfref = options.selfref})
end

return p