Module:Pinout

From Amateur Radio Equipment Database
Jump to: navigation, search

This Module implements the {{Pinout}} template. Please see the template page for usage instructions.


local p = {}

local args = {}
local root

local function union(t1, t2)
    -- Returns the union of the values of two tables, as a sequence.
    local vals = {}
    for k, v in pairs(t1) do
        vals[v] = true
    end
    for k, v in pairs(t2) do
        vals[v] = true
    end
    local ret = {}
    for k, v in pairs(vals) do
        table.insert(ret, k)
    end
    return ret
end

local function getArgNums(prefix)
    -- Returns a table containing the numbers of the arguments that exist
    -- for the specified prefix. For example, if the prefix was 'data', and
    -- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
    local nums = {}
    for k, v in pairs(args) do
        local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
        if num then table.insert(nums, tonumber(num)) end
    end
    table.sort(nums)
    return nums
end

local function renderPin(pinArgs)
    -- builds a single pin definition
    local row = root:tag('tr')
    if pinArgs.id then
        row:tag('td'):wikitext(pinArgs.id)
    else
        row:tag('td'):wikitext(pinArgs.number)
    end
    row:tag('td'):wikitext(pinArgs.name)
    row:tag('td'):wikitext(pinArgs.desc)
end

local function renderRows()
    -- builds the pin detail rows
    local rownums = union(getArgNums('id'), getArgNums('name'))
    table.sort(rownums)
    for k, num in ipairs(rownums) do
        renderPin({
            number = tostring(num),
            id = args['id' .. tostring (num)],
            name = args['name' .. tostring (num)],
            desc = args['desc' .. tostring (num)],
        })
    end
end
    

function p.pinout( frame )
    -- If called via #invoke, use the args passed into the invoking template.
    -- Otherwise, for testing purposes, assume args are being passed directly in.
    if frame == mw.getCurrentFrame() then
        args = frame:getParent().args
    else
        args = frame
    end

    root = mw.html.create('table')
    root:addClass('wikitable')

    local header = root:tag('tr')
    header:tag('th'):wikitext('Diagram')
    header:tag('th'):attr('colspan', '3'):wikitext('Details')

    local header2 = root:tag('tr')
    header2:tag('td'):attr('rowspan','99'):wikitext(args.diagram_image)
    header2:tag('th'):wikitext('ID')
    header2:tag('th'):wikitext('name')
    header2:tag('th'):wikitext('description')

    renderRows()

    return tostring(root)
end

return p