Module:RecursiveSelectiveList

From Ikwipedia
Revision as of 08:53, 22 December 2024 by EnWikiAdmin (talk | contribs)

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

local p = {}

-- Helper function to format numbers with commas
local function formatNumber(num)
    if not num then return "0" end
    local formatted = tostring(num)
    local k
    while true do  
        formatted, k = formatted:gsub("^(-?%d+)(%d%d%d)", '%1,%2')
        if k == 0 then break end
    end
    return formatted
end

function p.main(frame)
    return p.getCategoryStats(frame)
end

function p.getCategoryStats(frame)
    local categoryName = frame.args.categoryName -- Pass the category name as an argument

    if not categoryName or categoryName == "" then
        return "'''Error:''' No category name provided."
    end

    local stats = mw.site.stats.pagesInCategory(categoryName, "*")
    if not stats then
        return "'''Error:''' Unable to retrieve statistics for the category."
    end

    -- Calculate percentages
    local total = stats.all
    local pagesPercent = total > 0 and string.format("%.2f%%", (stats.pages / total) * 100) or "0%"
    local subcatsPercent = total > 0 and string.format("%.2f%%", (stats.subcats / total) * 100) or "0%"
    local filesPercent = total > 0 and string.format("%.2f%%", (stats.files / total) * 100) or "0%"

    -- Create a link to the category
    local categoryLink = "[[Category:" .. mw.text.encode(categoryName) .. "|" .. mw.text.encode(categoryName) .. "]]"

    -- Build the wikitext table
    local result = {}
    table.insert(result, '{| class="wikitable sortable" style="width:50%; margin:auto;"')
    table.insert(result, '! colspan="2" style="text-align:center; font-size:150%;" ' .. categoryLink)
    table.insert(result, '|-')
    table.insert(result, '! Statistic !! Count !! Percentage')
    table.insert(result, '|-')
    table.insert(result, '| Total items || ' .. formatNumber(stats.all) .. ' || 100%')
    table.insert(result, '|-')
    table.insert(result, '| Pages || ' .. formatNumber(stats.pages) .. ' || ' .. pagesPercent)
    table.insert(result, '|-')
    table.insert(result, '| Subcategories || ' .. formatNumber(stats.subcats) .. ' || ' .. subcatsPercent)
    table.insert(result, '|-')
    table.insert(result, '| Files || ' .. formatNumber(stats.files) .. ' || ' .. filesPercent)
    table.insert(result, '|}')
    
    -- Optionally, add a timestamp of when the data was retrieved
    local timestamp = os.date("Retrieved on %Y-%m-%d at %H:%M:%S UTC")
    table.insert(result, '<div style="text-align:center; font-size:small; color:gray;">' .. timestamp .. '</div>')

    return table.concat(result, "\n")
end

return p