Module:Connections

From Amateur Radio Equipment Database
Jump to: navigation, search

This Module implements the {{Connections}} 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 renderConnection(connectionArgs)
    -- builds a single pin definition
    local item = root:tag('li')
    item:wikitext(connectionArgs.name):wikitext(' - '):wikitext(connectionArgs.connector)
    if connectionArgs.note then
        item:wikitext(' '):wikitext(connectionArgs.note)
    end
    if connectionArgs.pinout then
        item:wikitext(' <span class="mw-customtoggle-con'.. tostring(connectionArgs.number) ..' mw-customtoggle" tabindex="0">(Show Pinout)</span>')
        item:wikitext('<div class="mw-collapsible mw-collapsed" id="mw-customcollapsible-con'.. tostring(connectionArgs.number) ..'" style="display: none;">')
        item:wikitext(connectionArgs.pinout)
        item:wikitext('</div>')
    end
end

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

function p.connections( 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('ul')

    renderRows()

    return tostring(root)
end

return p