Jump to content

Module:ExtendedSwitcher

From Wikipedia, the free encyclopedia
local p = {}

function p.main(frame)
    local root = mw.html.create('div'):addClass('switcher-container')
    local default = tonumber(frame.args.default) or 1  -- Default option (1-based index)

    local buttonContainer = root:tag('div'):addClass('switcher-buttons')  -- Div for switcher buttons
    local contentContainer = root:tag('div'):addClass('switcher-contents') -- Div for switcher contents
    
    for i = 1, 50, 2 do  -- Loop through arguments (pairs)
        local label = frame.args[tostring(i)]
        local content = frame.args[tostring(i + 1)] or ""

        if label then
            -- Create switcher buttons
            buttonContainer:tag('button')
                :attr('onclick', 'switchContent(' .. i .. ')')
                :wikitext(label)

            -- Create switcher content areas
            local contentDiv = contentContainer:tag('div')
                :addClass('switcher-content')
                :attr('id', 'switcher-' .. i)
                :wikitext(content)

            if i == (default - 1) * 2 + 1 then
                contentDiv:css('display', 'block')  -- Show default
            else
                contentDiv:css('display', 'none')   -- Hide others
            end
        end
    end

    -- JavaScript for switching behavior
    root:tag('script'):wikitext([[
        function switchContent(n) {
            var elements = document.getElementsByClassName('switcher-content');
            for (var i = 0; i < elements.length; i++) {
                elements[i].style.display = 'none';
            }
            document.getElementById('switcher-' + n).style.display = 'block';
        }
    ]])

    return root
end

return p