Module:Toolbar

From Zoophilia Wiki
Revision as of 09:51, 10 September 2013 by meta>Mr. Stradivarius (use a more efficient string-building algorithm)
Jump to navigationJump to search

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

local p = {}

-- Get the keys of the numerical arguments that are present.
local function getArgNums(args)
    local nums = {}
    local tinsert = table.insert
    for k, v in pairs(args) do
        if type(k) == 'number' then
            tinsert(nums, k)
        end
    end
    table.sort(nums)
    return nums
end

local function makeToolbarItems(args)
    -- Get numerical argument keys.
    local nums = getArgNums(args)
    -- Get the separator text.
    local sep = (args.separator or 'pipe') .. '-separator'
    sep = mw.message.new(sep):plain()
    
    -- Generate the toolbar items.
    local ret = {}
    local tinsert = table.insert
    for i, v in ipairs(nums) do
    	tinsert(ret, args[v])
    end
    return table.concat(ret, sep)
end

local function makeToolbar(args)
    return mw.ustring.format(
    	'<span class="plainlinks%s"%s>(%s)</span>',
    	type(args.class) == 'string' and ' ' .. args.class or '',
    	type(args.style) == 'string' and mw.ustring.format(' style="%s"', args.style) or '',
    	makeToolbarItems(args)
    )
end

function p.main(frame)
    -- If called via #invoke, use the args passed into the invoking template.
    -- Otherwise, for testing purposes, assume args are being passed directly in.
    local origArgs
    if frame == mw.getCurrentFrame() then
        origArgs = frame:getParent().args
        for k, v in pairs(frame.args) do
        	origArgs = frame.args
        	break
    	end
    else
        origArgs = frame
    end
    
    -- Strip whitespace and remove nil values
    local args = {}
    for k, v in pairs(origArgs) do
    	if type(v) == 'string' then
    		v = mw.text.trim(v)
    	end
        if v ~= '' then
            args[k] = v
        end
    end
    
    return makeToolbar(args)
end
 
return p