Module:TableTools and Module:Navbox: Difference between pages

From Frontierpedia, the Microsoft Agent encyclopedia
(Difference between pages)
en>Alex 21
(Implementing talk page edit requested)
 
w>MusikAnimal
m (Protected "Module:Navbox": High-risk Lua module ([Edit=Allow only autoconfirmed users] (indefinite) [Move=Allow only autoconfirmed users] (indefinite)))
 
Line 1: Line 1:
--[[
--
------------------------------------------------------------------------------------
-- This module implements {{Navbox}}
--                              TableTools                                      --
--
--                                                                                --
-- This module includes a number of functions for dealing with Lua tables.        --
-- It is a meta-module, meant to be called from other Lua modules, and should    --
-- not be called directly from #invoke.                                          --
------------------------------------------------------------------------------------
--]]


local libraryUtil = require('libraryUtil')
local p = {}


local p = {}
local navbar = require('Module:Navbar')._navbar
local getArgs -- lazily initialized


-- Define often-used variables and functions.
local args
local floor = math.floor
local tableRowAdded = false
local infinity = math.huge
local border
local checkType = libraryUtil.checkType
local listnums = {}
local checkTypeMulti = libraryUtil.checkTypeMulti


--[[
local function trim(s)
------------------------------------------------------------------------------------
    return (mw.ustring.gsub(s, "^%s*(.-)%s*$", "%1"))
-- isPositiveInteger
--
-- This function returns true if the given value is a positive integer, and false
-- if not. Although it doesn't operate on tables, it is included here as it is
-- useful for determining whether a given table key is in the array part or the
-- hash part of a table.
------------------------------------------------------------------------------------
--]]
function p.isPositiveInteger(v)
if type(v) == 'number' and v >= 1 and floor(v) == v and v < infinity then
return true
else
return false
end
end
end


--[[
local function addNewline(s)
------------------------------------------------------------------------------------
    if s:match('^[*:;#]') or s:match('^{|') then
-- isNan
        return '\n' .. s ..'\n'
--
    else
-- This function returns true if the given number is a NaN value, and false
        return s
-- if not. Although it doesn't operate on tables, it is included here as it is
    end
-- useful for determining whether a value can be a valid table key. Lua will
-- generate an error if a NaN is used as a table key.
------------------------------------------------------------------------------------
--]]
function p.isNan(v)
if type(v) == 'number' and tostring(v) == '-nan' then
return true
else
return false
end
end
end


--[[
local function addTableRow(tbl)
------------------------------------------------------------------------------------
    -- If any other rows have already been added, then we add a 2px gutter row.
-- shallowClone
    if tableRowAdded then
--
        tbl
-- This returns a clone of a table. The value returned is a new table, but all
            :tag('tr')
-- subtables and functions are shared. Metamethods are respected, but the returned
                :css('height', '2px')
-- table will have no metatable of its own.
                :tag('td')
------------------------------------------------------------------------------------
                    :attr('colspan',2)
--]]
    end
function p.shallowClone(t)
 
local ret = {}
    tableRowAdded = true
for k, v in pairs(t) do
 
ret[k] = v
    return tbl:tag('tr')
end
return ret
end
end


--[[
local function renderNavBar(titleCell)
------------------------------------------------------------------------------------
    -- Depending on the presence of the navbar and/or show/hide link, we may need to add a spacer div on the left
-- removeDuplicates
    -- or right to keep the title centered.
--
    local spacerSide = nil
-- This removes duplicate values from an array. Non-positive-integer keys are
 
-- ignored. The earliest value is kept, and all subsequent duplicate values are
    if args.navbar == 'off' then
-- removed, but otherwise the array order is unchanged.
        -- No navbar, and client wants no spacer, i.e. wants the title to be shifted to the left. If there's
------------------------------------------------------------------------------------
        -- also no show/hide link, then we need a spacer on the right to achieve the left shift.
--]]
        if args.state == 'plain' then spacerSide = 'right' end
function p.removeDuplicates(t)
    elseif args.navbar == 'plain' or (not args.name and mw.getCurrentFrame():getParent():getTitle():gsub('/sandbox$', '') == 'Template:Navbox') then
checkType('removeDuplicates', 1, t, 'table')
        -- No navbar. Need a spacer on the left to balance out the width of the show/hide link.
local isNan = p.isNan
        if args.state ~= 'plain' then spacerSide = 'left' end
local ret, exists = {}, {}
    else
for i, v in ipairs(t) do
        -- Will render navbar (or error message). If there's no show/hide link, need a spacer on the right
if isNan(v) then
        -- to balance out the width of the navbar.
-- NaNs can't be table keys, and they are also unique, so we don't need to check existence.
        if args.state == 'plain' then spacerSide = 'right' end
ret[#ret + 1] = v
 
else
        titleCell:wikitext(navbar{
if not exists[v] then
            args.name,
ret[#ret + 1] = v
            mini = 1,
exists[v] = true
            fontstyle = (args.basestyle or '') .. ';' .. (args.titlestyle or '') ..  ';background:none transparent;border:none;'
end
        })
end
    end
end
return ret
end


--[[
    -- Render the spacer div.
------------------------------------------------------------------------------------
    if spacerSide then
-- numKeys
        titleCell
--
            :tag('span')
-- This takes a table and returns an array containing the numbers of any numerical
                :css('float', spacerSide)
-- keys that have non-nil values, sorted in numerical order.
                :css('width', '6em')
------------------------------------------------------------------------------------
                :wikitext('&nbsp;')
--]]
    end
function p.numKeys(t)
checkType('numKeys', 1, t, 'table')
local isPositiveInteger = p.isPositiveInteger
local nums = {}
for k, v in pairs(t) do
if isPositiveInteger(k) then
nums[#nums + 1] = k
end
end
table.sort(nums)
return nums
end
end


--[[
------------------------------------------------------------------------------------
-- affixNums
--
--
-- This takes a table and returns an array containing the numbers of keys with the
--   Title row
-- specified prefix and suffix. For example, for the table
--
-- {a1 = 'foo', a3 = 'bar', a6 = 'baz'} and the prefix "a", affixNums will
local function renderTitleRow(tbl)
-- return {1, 3, 6}.
    if not args.title then return end
------------------------------------------------------------------------------------
--]]
function p.affixNums(t, prefix, suffix)
checkType('affixNums', 1, t, 'table')
checkType('affixNums', 2, prefix, 'string', true)
checkType('affixNums', 3, suffix, 'string', true)


local function cleanPattern(s)
    local titleRow = addTableRow(tbl)
-- Cleans a pattern so that the magic characters ()%.[]*+-?^$ are interpreted literally.
s = s:gsub('([%(%)%%%.%[%]%*%+%-%?%^%$])', '%%%1')
return s
end


prefix = prefix or ''
    if args.titlegroup then
suffix = suffix or ''
        titleRow
prefix = cleanPattern(prefix)
            :tag('th')
suffix = cleanPattern(suffix)
                :attr('scope', 'row')
local pattern = '^' .. prefix .. '([1-9]%d*)' .. suffix .. '$'
                :addClass('navbox-group')
                :addClass(args.titlegroupclass)
                :cssText(args.basestyle)
                :cssText(args.groupstyle)
                :cssText(args.titlegroupstyle)
                :wikitext(args.titlegroup)
    end


local nums = {}
    local titleCell = titleRow:tag('th'):attr('scope', 'col')
for k, v in pairs(t) do
 
if type(k) == 'string' then
    if args.titlegroup then
local num = mw.ustring.match(k, pattern)
        titleCell
if num then
            :css('border-left', '2px solid #fdfdfd')
nums[#nums + 1] = tonumber(num)
            :css('width', '100%')
end
    end
end
 
end
    local titleColspan = 2
table.sort(nums)
    if args.imageleft then titleColspan = titleColspan + 1 end
return nums
    if args.image then titleColspan = titleColspan + 1 end
    if args.titlegroup then titleColspan = titleColspan - 1 end
 
    titleCell
        :cssText(args.basestyle)
        :cssText(args.titlestyle)
        :addClass('navbox-title')
        :attr('colspan', titleColspan)
 
    renderNavBar(titleCell)
 
    titleCell
        :tag('div')
            :addClass(args.titleclass)
            :css('font-size', '110%')
            :wikitext(addNewline(args.title))
end
end


--[[
------------------------------------------------------------------------------------
-- numData
--
--
-- Given a table with keys like ("foo1", "bar1", "foo2", "baz2"), returns a table
--   Above/Below rows
-- of subtables in the format
--
-- { [1] = {foo = 'text', bar = 'text'}, [2] = {foo = 'text', baz = 'text'} }
 
-- Keys that don't end with an integer are stored in a subtable named "other".
local function getAboveBelowColspan()
-- The compress option compresses the table so that it can be iterated over with
    local ret = 2
-- ipairs.
    if args.imageleft then ret = ret + 1 end
------------------------------------------------------------------------------------
    if args.image then ret = ret + 1 end
--]]
    return ret
function p.numData(t, compress)
end
checkType('numData', 1, t, 'table')
 
checkType('numData', 2, compress, 'boolean', true)
local function renderAboveRow(tbl)
local ret = {}
    if not args.above then return end
for k, v in pairs(t) do
 
local prefix, num = mw.ustring.match(tostring(k), '^([^0-9]*)([1-9][0-9]*)$')
    addTableRow(tbl)
if num then
        :tag('td')
num = tonumber(num)
            :addClass('navbox-abovebelow')
local subtable = ret[num] or {}
            :addClass(args.aboveclass)
if prefix == '' then
            :cssText(args.basestyle)
-- Positional parameters match the blank string; put them at the start of the subtable instead.
            :cssText(args.abovestyle)
prefix = 1
            :attr('colspan', getAboveBelowColspan())
end
            :tag('div')
subtable[prefix] = v
                :wikitext(addNewline(args.above))
ret[num] = subtable
else
local subtable = ret.other or {}
subtable[k] = v
ret.other = subtable
end
end
if compress then
local other = ret.other
ret = p.compressSparseArray(ret)
ret.other = other
end
return ret
end
end


--[[
local function renderBelowRow(tbl)
------------------------------------------------------------------------------------
    if not args.below then return end
-- compressSparseArray
 
--
    addTableRow(tbl)
-- This takes an array with one or more nil values, and removes the nil values
        :tag('td')
-- while preserving the order, so that the array can be safely traversed with
            :addClass('navbox-abovebelow')
-- ipairs.
            :addClass(args.belowclass)
------------------------------------------------------------------------------------
            :cssText(args.basestyle)
--]]
            :cssText(args.belowstyle)
function p.compressSparseArray(t)
            :attr('colspan', getAboveBelowColspan())
checkType('compressSparseArray', 1, t, 'table')
            :tag('div')
local ret = {}
                :wikitext(addNewline(args.below))
local nums = p.numKeys(t)
for _, num in ipairs(nums) do
ret[#ret + 1] = t[num]
end
return ret
end
end


--[[
------------------------------------------------------------------------------------
-- sparseIpairs
--
--
-- This is an iterator for sparse arrays. It can be used like ipairs, but can
--   List rows
-- handle nil values.
--
------------------------------------------------------------------------------------
local function renderListRow(tbl, listnum)
--]]
    local row = addTableRow(tbl)
function p.sparseIpairs(t)
 
checkType('sparseIpairs', 1, t, 'table')
    if listnum == 1 and args.imageleft then
local nums = p.numKeys(t)
        row
local i = 0
            :tag('td')
local lim = #nums
                :addClass('navbox-image')
return function ()
                :addClass(args.imageclass)
i = i + 1
                :css('width', '0%')
if i <= lim then
                :css('padding', '0px 2px 0px 0px')
local key = nums[i]
                :cssText(args.imageleftstyle)
return key, t[key]
                :attr('rowspan', 2 * #listnums - 1)
else
                :tag('div')
return nil, nil
                    :wikitext(addNewline(args.imageleft))
end
    end
end
 
    if args['group' .. listnum] then
        local groupCell = row:tag('th')
 
        groupCell
            :attr('scope', 'row')
            :addClass('navbox-group')
            :addClass(args.groupclass)
            :cssText(args.basestyle)
 
        if args.groupwidth then
            groupCell:css('width', args.groupwidth)
        end
 
        groupCell
            :cssText(args.groupstyle)
            :cssText(args['group' .. listnum .. 'style'])
            :wikitext(args['group' .. listnum])
    end
 
    local listCell = row:tag('td')
 
    if args['group' .. listnum] then
        listCell
            :css('text-align', 'left')
            :css('border-left-width', '2px')
            :css('border-left-style', 'solid')
    else
        listCell:attr('colspan', 2)
    end
 
    if not args.groupwidth then
        listCell:css('width', '100%')
    end
 
    local isOdd = (listnum % 2) == 1
    local rowstyle = args.evenstyle
    if isOdd then rowstyle = args.oddstyle end
 
    local evenOdd
    if args.evenodd == 'swap' then
        if isOdd then evenOdd = 'even' else evenOdd = 'odd' end
    else
        if isOdd then evenOdd = args.evenodd or 'odd' else evenOdd = args.evenodd or 'even' end
    end
 
    listCell
        :css('padding', '0px')
        :cssText(args.liststyle)
        :cssText(rowstyle)
        :cssText(args['list' .. listnum .. 'style'])
        :addClass('navbox-list')
        :addClass('navbox-' .. evenOdd)
        :addClass(args.listclass)
        :tag('div')
            :css('padding', (listnum == 1 and args.list1padding) or args.listpadding or '0em 0.25em')
            :wikitext(addNewline(args['list' .. listnum]))
 
    if listnum == 1 and args.image then
        row
            :tag('td')
                :addClass('navbox-image')
                :addClass(args.imageclass)
                :css('width', '0%')
                :css('padding', '0px 0px 0px 2px')
                :cssText(args.imagestyle)
                :attr('rowspan', 2 * #listnums - 1)
                :tag('div')
                    :wikitext(addNewline(args.image))
    end
end
end


--[[
 
------------------------------------------------------------------------------------
--
-- size
--   Tracking categories
--
--
-- This returns the size of a key/value pair table. It will also work on arrays,
-- but for arrays it is more efficient to use the # operator.
------------------------------------------------------------------------------------
--]]


function p.size(t)
local function needsHorizontalLists()
checkType('size', 1, t, 'table')
    if border == 'child' or border == 'subgroup' or args.tracking == 'no' then return false end
local i = 0
for k in pairs(t) do
i = i + 1
end
return i
end


    local listClasses = {'plainlist', 'hlist', 'hlist hnum', 'hlist hwrap', 'hlist vcard', 'vcard hlist', 'hlist vevent'}
    for i, cls in ipairs(listClasses) do
        if args.listclass == cls or args.bodyclass == cls then
            return false
        end
    end


local function defaultKeySort(item1, item2)
    return true
-- "number" < "string", so numbers will be sorted before strings.
local type1, type2 = type(item1), type(item2)
if type1 ~= type2 then
return type1 < type2
else -- This will fail with table, boolean, function.
return item1 < item2
end
end
end


--[[
local function hasBackgroundColors()
Returns a list of the keys in a table, sorted using either a default
    return mw.ustring.match(args.titlestyle or '','background') or mw.ustring.match(args.groupstyle or '','background') or mw.ustring.match(args.basestyle or '','background')
comparison function or a custom keySort function.
]]
function p.keysToList(t, keySort, checked)
if not checked then
checkType('keysToList', 1, t, 'table')
checkTypeMulti('keysToList', 2, keySort, { 'function', 'boolean', 'nil' })
end
local list = {}
local index = 1
for key, value in pairs(t) do
list[index] = key
index = index + 1
end
if keySort ~= false then
keySort = type(keySort) == 'function' and keySort or defaultKeySort
table.sort(list, keySort)
end
return list
end
end


--[[
local function getTrackingCategories()
Iterates through a table, with the keys sorted using the keysToList function.
    local cats = {}
If there are only numerical keys, sparseIpairs is probably more efficient.
    if needsHorizontalLists() then table.insert(cats, 'Navigational boxes without horizontal lists') end
]]
    if hasBackgroundColors() then table.insert(cats, 'Navboxes using background colours') end
function p.sortedPairs(t, keySort)
    return cats
checkType('sortedPairs', 1, t, 'table')
checkType('sortedPairs', 2, keySort, 'function', true)
local list = p.keysToList(t, keySort, true)
local i = 0
return function()
i = i + 1
local key = list[i]
if key ~= nil then
return key, t[key]
else
return nil, nil
end
end
end
end


--[[
local function renderTrackingCategories(builder)
Returns true if all keys in the table are consecutive integers starting at 1.
    local title = mw.title.getCurrentTitle()
--]]
    if title.namespace ~= 10 then return end -- not in template space
function p.isArray(t)
    local subpage = title.subpageText
checkType("isArray", 1, t, "table")
    if subpage == 'doc' or subpage == 'sandbox' or subpage == 'testcases' then return end
 
local i = 0
    for i, cat in ipairs(getTrackingCategories()) do
for k, v in pairs(t) do
        builder:wikitext('[[Category:' .. cat .. ']]')
i = i + 1
    end
if t[i] == nil then
return false
end
end
return true
end
end


-- { "a", "b", "c" } -> { a = 1, b = 2, c = 3 }
--
function p.invert(array)
--  Main navbox tables
checkType("invert", 1, array, "table")
--
local function renderMainTable()
local map = {}
    local tbl = mw.html.create('table')
for i, v in ipairs(array) do
        :addClass('nowraplinks')
map[v] = i
        :addClass(args.bodyclass)
end
 
    if args.title and (args.state ~= 'plain' and args.state ~= 'off') then
return map
    local state = args.state;
    if state and state == 'collapsed' then
    state = 'mw-collapsed'
    end
        tbl
            :addClass('mw-collapsible')
            :addClass(state or 'autocollapse')
    end
 
    tbl:css('border-spacing', 0)
    if border == 'subgroup' or border == 'child' or border == 'none' then
        tbl
            :addClass('navbox-subgroup')
            :cssText(args.bodystyle)
            :cssText(args.style)
    else -- regular navobx - bodystyle and style will be applied to the wrapper table
        tbl
            :addClass('navbox-inner')
            :css('background', 'transparent')
            :css('color', 'inherit')
    end
    tbl:cssText(args.innerstyle)
 
    renderTitleRow(tbl)
    renderAboveRow(tbl)
    for i, listnum in ipairs(listnums) do
        renderListRow(tbl, listnum)
    end
    renderBelowRow(tbl)
 
    return tbl
end
end


--[[
function p._navbox(navboxArgs)
{ "a", "b", "c" } -> { ["a"] = true, ["b"] = true, ["c"] = true }
    args = navboxArgs
--]]
 
function p.listToSet(t)
    for k, v in pairs(args) do
checkType("listToSet", 1, t, "table")
        local listnum = ('' .. k):match('^list(%d+)$')
        if listnum then table.insert(listnums, tonumber(listnum)) end
local set = {}
    end
for _, item in ipairs(t) do
    table.sort(listnums)
set[item] = true
 
end
    border = trim(args.border or args[1] or '')
 
return set
    -- render the main body of the navbox
end
    local tbl = renderMainTable()
 
    -- render the appropriate wrapper around the navbox, depending on the border param
    local res = mw.html.create()
    if border == 'none' then
        res:node(tbl)
    elseif border == 'subgroup' or border == 'child' then
        -- We assume that this navbox is being rendered in a list cell of a parent navbox, and is
        -- therefore inside a div with padding:0em 0.25em. We start with a </div> to avoid the
        -- padding being applied, and at the end add a <div> to balance out the parent's </div>
        res
            :wikitext('</div>') -- XXX: hack due to lack of unclosed support in mw.html.
            :node(tbl)
            :wikitext('<div>') -- XXX: hack due to lack of unclosed support in mw.html.
    else
        res
            :tag('table')
                :addClass('navbox')
                :css('border-spacing', 0)
                :cssText(args.bodystyle)
                :cssText(args.style)
                :tag('tr')
                    :tag('td')
                        :css('padding', '2px')
                        :node(tbl)
    end


--[[
    renderTrackingCategories(res)
Recursive deep copy function.
Preserves identities of subtables.
]]
local function _deepCopy(orig, includeMetatable, already_seen)
-- Stores copies of tables indexed by the original table.
already_seen = already_seen or {}
local copy = already_seen[orig]
if copy ~= nil then
return copy
end
if type(orig) == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[deepcopy(orig_key, includeMetatable, already_seen)] = deepcopy(orig_value, includeMetatable, already_seen)
end
already_seen[orig] = copy
if includeMetatable then
local mt = getmetatable(orig)
if mt ~= nil then
local mt_copy = deepcopy(mt, includeMetatable, already_seen)
setmetatable(copy, mt_copy)
already_seen[mt] = mt_copy
end
end
else -- number, string, boolean, etc
copy = orig
end
return copy
end


function p.deepCopy(orig, noMetatable, already_seen)
    return tostring(res)
checkType("deepCopy", 3, already_seen, "table", true)
return _deepCopy(orig, not noMetatable, already_seen)
end
end


--[[
function p.navbox(frame)
Concatenates all values in the table that are indexed by a number, in order.
    if not getArgs then
sparseConcat{ a, nil, c, d }  =>  "acd"
        getArgs = require('Module:Arguments').getArgs
sparseConcat{ nil, b, c, d }  =>  "bcd"
    end
]]
    args = getArgs(frame, {wrappers = 'Template:Navbox'})
function p.sparseConcat(t, sep, i, j)
local list = {}
local list_i = 0
for _, v in p.sparseIpairs(t) do
list_i = list_i + 1
list[list_i] = v
end
return table.concat(list, sep, i, j)
end


--[[
    -- Read the arguments in the order they'll be output in, to make references number in the right order.
-- This returns the length of a table, or the first integer key n counting from
    local _
-- 1 such that t[n + 1] is nil. It is similar to the operator #, but may return
    _ = args.title
-- a different value when there are gaps in the array portion of the table.
    _ = args.above
-- Intended to be used on data loaded with mw.loadData. For other tables, use #.
    for i = 1, 20 do
-- Note: #frame.args in frame object always be set to 0, regardless of
        _ = args["group" .. tostring(i)]
-- the number of unnamed template parameters, so use this function for
        _ = args["list" .. tostring(i)]
-- frame.args.
    end
--]]
    _ = args.below
function p.length(t)
local i = 1
while t[i] ~= nil do
i = i + 1
end
return i - 1
end


function p.inArray(arr, valueToFind)
    return p._navbox(args)
checkType("inArray", 1, arr, "table")
-- if valueToFind is nil, error?
for _, v in ipairs(arr) do
if v == valueToFind then
return true
end
end
return false
end
end


return p
return p

Revision as of 01:08, 7 November 2019

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

--
-- This module implements {{Navbox}}
--

local p = {}

local navbar = require('Module:Navbar')._navbar
local getArgs -- lazily initialized

local args
local tableRowAdded = false
local border
local listnums = {}

local function trim(s)
    return (mw.ustring.gsub(s, "^%s*(.-)%s*$", "%1"))
end

local function addNewline(s)
    if s:match('^[*:;#]') or s:match('^{|') then
        return '\n' .. s ..'\n'
    else
        return s
    end
end

local function addTableRow(tbl)
    -- If any other rows have already been added, then we add a 2px gutter row.
    if tableRowAdded then
        tbl
            :tag('tr')
                :css('height', '2px')
                :tag('td')
                    :attr('colspan',2)
    end

    tableRowAdded = true

    return tbl:tag('tr')
end

local function renderNavBar(titleCell)
    -- Depending on the presence of the navbar and/or show/hide link, we may need to add a spacer div on the left
    -- or right to keep the title centered.
    local spacerSide = nil

    if args.navbar == 'off' then
        -- No navbar, and client wants no spacer, i.e. wants the title to be shifted to the left. If there's
        -- also no show/hide link, then we need a spacer on the right to achieve the left shift.
        if args.state == 'plain' then spacerSide = 'right' end
    elseif args.navbar == 'plain' or (not args.name and mw.getCurrentFrame():getParent():getTitle():gsub('/sandbox$', '') == 'Template:Navbox') then
        -- No navbar. Need a spacer on the left to balance out the width of the show/hide link.
        if args.state ~= 'plain' then spacerSide = 'left' end
    else
        -- Will render navbar (or error message). If there's no show/hide link, need a spacer on the right
        -- to balance out the width of the navbar.
        if args.state == 'plain' then spacerSide = 'right' end

        titleCell:wikitext(navbar{
            args.name,
            mini = 1,
            fontstyle = (args.basestyle or '') .. ';' .. (args.titlestyle or '') ..  ';background:none transparent;border:none;'
        })
    end

    -- Render the spacer div.
    if spacerSide then
        titleCell
            :tag('span')
                :css('float', spacerSide)
                :css('width', '6em')
                :wikitext('&nbsp;')
    end
end

--
--   Title row
--
local function renderTitleRow(tbl)
    if not args.title then return end

    local titleRow = addTableRow(tbl)

    if args.titlegroup then
        titleRow
            :tag('th')
                :attr('scope', 'row')
                :addClass('navbox-group')
                :addClass(args.titlegroupclass)
                :cssText(args.basestyle)
                :cssText(args.groupstyle)
                :cssText(args.titlegroupstyle)
                :wikitext(args.titlegroup)
    end

    local titleCell = titleRow:tag('th'):attr('scope', 'col')

    if args.titlegroup then
        titleCell
            :css('border-left', '2px solid #fdfdfd')
            :css('width', '100%')
    end

    local titleColspan = 2
    if args.imageleft then titleColspan = titleColspan + 1 end
    if args.image then titleColspan = titleColspan + 1 end
    if args.titlegroup then titleColspan = titleColspan - 1 end

    titleCell
        :cssText(args.basestyle)
        :cssText(args.titlestyle)
        :addClass('navbox-title')
        :attr('colspan', titleColspan)

    renderNavBar(titleCell)

    titleCell
         :tag('div')
             :addClass(args.titleclass)
             :css('font-size', '110%')
             :wikitext(addNewline(args.title))
end

--
--   Above/Below rows
--

local function getAboveBelowColspan()
    local ret = 2
    if args.imageleft then ret = ret + 1 end
    if args.image then ret = ret + 1 end
    return ret
end

local function renderAboveRow(tbl)
    if not args.above then return end

    addTableRow(tbl)
        :tag('td')
            :addClass('navbox-abovebelow')
            :addClass(args.aboveclass)
            :cssText(args.basestyle)
            :cssText(args.abovestyle)
            :attr('colspan', getAboveBelowColspan())
            :tag('div')
                :wikitext(addNewline(args.above))
end

local function renderBelowRow(tbl)
    if not args.below then return end

    addTableRow(tbl)
        :tag('td')
            :addClass('navbox-abovebelow')
            :addClass(args.belowclass)
            :cssText(args.basestyle)
            :cssText(args.belowstyle)
            :attr('colspan', getAboveBelowColspan())
            :tag('div')
                :wikitext(addNewline(args.below))
end

--
--   List rows
--
local function renderListRow(tbl, listnum)
    local row = addTableRow(tbl)

    if listnum == 1 and args.imageleft then
        row
            :tag('td')
                :addClass('navbox-image')
                :addClass(args.imageclass)
                :css('width', '0%')
                :css('padding', '0px 2px 0px 0px')
                :cssText(args.imageleftstyle)
                :attr('rowspan', 2 * #listnums - 1)
                :tag('div')
                    :wikitext(addNewline(args.imageleft))
    end

    if args['group' .. listnum] then
        local groupCell = row:tag('th')

        groupCell
            :attr('scope', 'row')
            :addClass('navbox-group')
            :addClass(args.groupclass)
            :cssText(args.basestyle)

        if args.groupwidth then
            groupCell:css('width', args.groupwidth)
        end

        groupCell
            :cssText(args.groupstyle)
            :cssText(args['group' .. listnum .. 'style'])
            :wikitext(args['group' .. listnum])
    end

    local listCell = row:tag('td')

    if args['group' .. listnum] then
        listCell
            :css('text-align', 'left')
            :css('border-left-width', '2px')
            :css('border-left-style', 'solid')
    else
        listCell:attr('colspan', 2)
    end

    if not args.groupwidth then
        listCell:css('width', '100%')
    end

    local isOdd = (listnum % 2) == 1
    local rowstyle = args.evenstyle
    if isOdd then rowstyle = args.oddstyle end

    local evenOdd
    if args.evenodd == 'swap' then
        if isOdd then evenOdd = 'even' else evenOdd = 'odd' end
    else
        if isOdd then evenOdd = args.evenodd or 'odd' else evenOdd = args.evenodd or 'even' end
    end

    listCell
        :css('padding', '0px')
        :cssText(args.liststyle)
        :cssText(rowstyle)
        :cssText(args['list' .. listnum .. 'style'])
        :addClass('navbox-list')
        :addClass('navbox-' .. evenOdd)
        :addClass(args.listclass)
        :tag('div')
            :css('padding', (listnum == 1 and args.list1padding) or args.listpadding or '0em 0.25em')
            :wikitext(addNewline(args['list' .. listnum]))

    if listnum == 1 and args.image then
        row
            :tag('td')
                :addClass('navbox-image')
                :addClass(args.imageclass)
                :css('width', '0%')
                :css('padding', '0px 0px 0px 2px')
                :cssText(args.imagestyle)
                :attr('rowspan', 2 * #listnums - 1)
                :tag('div')
                    :wikitext(addNewline(args.image))
    end
end


--
--   Tracking categories
--

local function needsHorizontalLists()
    if border == 'child' or border == 'subgroup'  or args.tracking == 'no' then return false end

    local listClasses = {'plainlist', 'hlist', 'hlist hnum', 'hlist hwrap', 'hlist vcard', 'vcard hlist', 'hlist vevent'}
    for i, cls in ipairs(listClasses) do
        if args.listclass == cls or args.bodyclass == cls then
            return false
        end
    end

    return true
end

local function hasBackgroundColors()
    return mw.ustring.match(args.titlestyle or '','background') or mw.ustring.match(args.groupstyle or '','background') or mw.ustring.match(args.basestyle or '','background')
end

local function getTrackingCategories()
    local cats = {}
    if needsHorizontalLists() then table.insert(cats, 'Navigational boxes without horizontal lists') end
    if hasBackgroundColors() then table.insert(cats, 'Navboxes using background colours') end
    return cats
end

local function renderTrackingCategories(builder)
    local title = mw.title.getCurrentTitle()
    if title.namespace ~= 10 then return end -- not in template space
    local subpage = title.subpageText
    if subpage == 'doc' or subpage == 'sandbox' or subpage == 'testcases' then return end

    for i, cat in ipairs(getTrackingCategories()) do
        builder:wikitext('[[Category:' .. cat .. ']]')
    end
end

--
--   Main navbox tables
--
local function renderMainTable()
    local tbl = mw.html.create('table')
        :addClass('nowraplinks')
        :addClass(args.bodyclass)

    if args.title and (args.state ~= 'plain' and args.state ~= 'off') then
    	local state = args.state;
    	if state and state == 'collapsed' then
    		state = 'mw-collapsed'
    	end
        tbl
            :addClass('mw-collapsible')
            :addClass(state or 'autocollapse')
    end

    tbl:css('border-spacing', 0)
    if border == 'subgroup' or border == 'child' or border == 'none' then
        tbl
            :addClass('navbox-subgroup')
            :cssText(args.bodystyle)
            :cssText(args.style)
    else -- regular navobx - bodystyle and style will be applied to the wrapper table
        tbl
            :addClass('navbox-inner')
            :css('background', 'transparent')
            :css('color', 'inherit')
    end
    tbl:cssText(args.innerstyle)

    renderTitleRow(tbl)
    renderAboveRow(tbl)
    for i, listnum in ipairs(listnums) do
        renderListRow(tbl, listnum)
    end
    renderBelowRow(tbl)

    return tbl
end

function p._navbox(navboxArgs)
    args = navboxArgs

    for k, v in pairs(args) do
        local listnum = ('' .. k):match('^list(%d+)$')
        if listnum then table.insert(listnums, tonumber(listnum)) end
    end
    table.sort(listnums)

    border = trim(args.border or args[1] or '')

    -- render the main body of the navbox
    local tbl = renderMainTable()

    -- render the appropriate wrapper around the navbox, depending on the border param
    local res = mw.html.create()
    if border == 'none' then
        res:node(tbl)
    elseif border == 'subgroup' or border == 'child' then
        -- We assume that this navbox is being rendered in a list cell of a parent navbox, and is
        -- therefore inside a div with padding:0em 0.25em. We start with a </div> to avoid the
        -- padding being applied, and at the end add a <div> to balance out the parent's </div>
        res
            :wikitext('</div>') -- XXX: hack due to lack of unclosed support in mw.html.
            :node(tbl)
            :wikitext('<div>') -- XXX: hack due to lack of unclosed support in mw.html.
    else
        res
            :tag('table')
                :addClass('navbox')
                :css('border-spacing', 0)
                :cssText(args.bodystyle)
                :cssText(args.style)
                :tag('tr')
                    :tag('td')
                        :css('padding', '2px')
                        :node(tbl)
    end

    renderTrackingCategories(res)

    return tostring(res)
end

function p.navbox(frame)
    if not getArgs then
        getArgs = require('Module:Arguments').getArgs
    end
    args = getArgs(frame, {wrappers = 'Template:Navbox'})

    -- Read the arguments in the order they'll be output in, to make references number in the right order.
    local _
    _ = args.title
    _ = args.above
    for i = 1, 20 do
        _ = args["group" .. tostring(i)]
        _ = args["list" .. tostring(i)]
    end
    _ = args.below

    return p._navbox(args)
end

return p