Module:BCIChapterList

Revision as of 00:06, 24 April 2025 by SuitCase (talk | contribs) (adding headers!)

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

-- Module:BCIChapterList
local p = {}

-- helper: format ISO date YYYY-MM-DD → M/D/YY
local function formatDate(iso)
    local y,m,d = iso:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)$")
    if not y then return iso end
    m = tonumber(m); d = tonumber(d)
    return m .. "/" .. d .. "/" .. y:sub(3,4)
end

-- helper: determine period for a given year
local function periodForYear(year)
    year = tonumber(year)
    if not year then return nil end
    if year >= 2010 and year <= 2014 then
        return "2010–2014"
    elseif year >= 2015 and year <= 2019 then
        return "2015–2019"
    elseif year >= 2020 and year <= 2025 then
        return "2020–2025"
    end
    return nil
end

function p.renderTable(frame)
    -- grab raw wikitext of Template:BCIChaptersList
    local tpl = mw.title.new("Template:BCIChaptersList")
    local raw = tpl and tpl:getContent() or ""

    -- parse each {{BCIChapter|…}} invocation
    local rows = {}
    for line in raw:gmatch("[^\\r\\n]+") do
        local trimmed = mw.text.trim(line)
        if trimmed:find("^{{BCIChapter") then
            local inner = trimmed:match("^{{BCIChapter%s*(.+)}}$")
            if inner then
                if inner:sub(1,1) == "|" then inner = inner:sub(2) end
                local params = {}
                for part in inner:gmatch("[^|]+") do
                    local k,v = part:match("^(%w+)%s*=%s*(.+)$")
                    if k and v then params[k] = v end
                end
                if params.title and params.date and params.seq then
                    table.insert(rows, {
                        title = params.title,
                        date  = params.date,
                        seq   = tonumber(params.seq) or 0
                    })
                end
            end
        end
    end

    -- sort by seq ascending
    table.sort(rows, function(a,b) return a.seq < b.seq end)

    -- build the wikitable with period headers
    local out = {
        '{| class="wikitable sortable"',
        '! Title',
        '! Published'
    }

    local currentPeriod = nil
    for _, r in ipairs(rows) do
        local yr = r.date:match("^(%d%d%d%d)%-.+")
        local period = periodForYear(yr)
        if period and period ~= currentPeriod then
            table.insert(out, "|-")
            table.insert(out, "! colspan=\"2\" | " .. period)
            currentPeriod = period
        end
        table.insert(out, "|-")
        table.insert(out,
          "| [[" .. r.title .. "]] || " .. formatDate(r.date)
        )
    end

    table.insert(out, "|}")
    return table.concat(out, "\n")
end

return p