Jump to content

Module:PadUtils

From PAD Wiki
Revision as of 04:45, 22 August 2025 by GlifterPad (talk | contribs)

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

local p = {}

local function split(text, delim)
    local out = {}
    if not text or text == "" then return out end
    for part in mw.text.gsplit(text, delim, true) do
        part = mw.text.trim(part)
        if part ~= "" then table.insert(out, part) end
    end
    return out
end

local function parseItem(item)
    local inner = item:match("^%[%[(.*)%]%]$")
    if inner then item = inner end
    local t, l = item:match("^(.-)|(.*)$")
    local target = mw.text.trim(t or item)
    local label  = mw.text.trim(l or item)
    return target, label
end

local function normalizeTarget(base, target)
    target = mw.text.trim(target)
    local withSlash = base .. "/"
    if target:sub(1, #withSlash) == withSlash then
        target = target:sub(#withSlash + 1)
    end
    return base .. "/" .. target
end

function p.dungeonFloors(frame)
    local args    = frame.args
    local base    = args.base and mw.text.trim(args.base) or mw.title.getCurrentTitle().fullText
    local floors  = split(args.floors or "", ";")
    local listTag = (args.ol == "1" or args.ol == "true") and "ol" or "ul"
    local before  = args.before or ""
    local after   = args.after or ""

    if #floors == 0 then return "" end

    -- Use mw.html so MediaWiki treats the output as safe HTML
    local list = mw.html.create(listTag)

    for _, raw in ipairs(floors) do
        local target, label = parseItem(raw)
        local titleText = normalizeTarget(base, target)
        local titleObj  = mw.title.new(titleText)
        local url = titleObj and titleObj:fullUrl() or ("/wiki/" .. mw.uri.encode(titleText))

        list:tag("li")
            :tag("a")
                :attr("href", url)
                :wikitext(before .. label .. after)
            :done()
        :done()
    end

    return tostring(list)  -- ensures proper HTML rendering
end

return p