Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Module:BookTOC

From ProleWiki, the proletarian encyclopedia
Revision as of 18:35, 12 August 2025 by CriticalResist (talk | contribs)
local p = {}

function p.main(frame)
    local args = frame:getParent().args
    local items = {}
    local levels = {}
    
    -- Collect all TOC items and their levels
    local i = 1
    while args['item' .. i] do
        items[i] = args['item' .. i]
        levels[i] = tonumber(args['level' .. i]) or 2  -- Default to level 2 (==) if not provided
        i = i + 1
    end
    
    -- Return empty if no items
    if #items == 0 then
        return ''
    end
    
    local list = {}
    local list_stack = {}
    
    for idx = 1, #items do
        local level = levels[idx]
        local item = items[idx]
        
        -- Adjust for MediaWiki heading levels (== is level 2, but we want it as top-level)
        local depth = level - 1
        
        -- Close deeper levels
        while #list_stack > 0 and list_stack[#list_stack] > depth do
            table.remove(list_stack)
        end
        
        -- Open new levels
        while #list_stack < depth do
            table.insert(list_stack, #list_stack + 1)
        end
        
        -- Add the item with the correct number of # markers
        table.insert(list, string.rep('#', depth) .. ' ' .. item .. '\n')
    end
    
    return '<div class="book-toc">\n' .. table.concat(list) .. '</div>'
end

return p