Module:Navbox: Difference between revisions

From Deadlock Wiki
Jump to navigation Jump to search
No edit summary
Tag: Reverted
Undo revision 516 by Cronos (talk)
Tag: Undo
 
Line 1: Line 1:
-- <nowiki>
--
--
-- Implements {{Navbox}}
-- This module implements {{Navbox}}
--
--


local p = {}
local p = {}
local tnavbar = require( 'Module:Tnavbar' )
local yesno = require( 'Module:Yesno' )
local onmain = require('Module:Mainonly').on_main()
local page_title = mw.title.getCurrentTitle().fullText
--
-- Helper for inserting a new row into the navbox
--
-- @param tbl {mw.html table}
-- @return tbl {mw.html table}
--
local function insertRow( tbl )
return tbl:tag( 'tr' )
end


--
local navbar = require('Module:Navbar')._navbar
-- Creates the navbox table
local getArgs -- lazily initialized
--
-- @param args {table}
-- @return tbl {mw.html table}
--
local function createTbl( args )


local tbl = mw.html.create( 'table' )
local args
local border
local listnums
local ODD_EVEN_MARKER = '\127_ODDEVEN_\127'
local RESTART_MARKER = '\127_ODDEVEN0_\127'
local REGEX_MARKER = '\127_ODDEVEN(%d?)_\127'


tbl
local function striped(wikitext)
:addClass( yesno( args.subgroup ) and 'navbox-subgroup' or 'navbox' )
-- Return wikitext with markers replaced for odd/even striping.
:addClass( 'nowraplinks' )
-- Child (subgroup) navboxes are flagged with a category that is removed
 
-- by parent navboxes. The result is that the category shows all pages
if not yesno( args.subgroup ) and
-- where a child navbox is not contained in a parent navbox.
( args.state == 'collapsed' or
local orphanCat = '[[Category:Navbox orphans]]'
  args.state == 'uncollapsed' or
if border == 'subgroup' and args.orphan ~= 'yes' then
  args.state == 'autocollapse' or
-- No change; striping occurs in outermost navbox.
  -- defaults to autocollapse
return wikitext .. orphanCat
  args.state == nil )
end
then
local first, second = 'odd', 'even'
tbl:addClass( 'mw-collapsible' )
if args.evenodd then
 
if args.evenodd == 'swap' then
if args.state == 'collapsed' then
first, second = second, first
tbl:addClass( 'mw-collapsed' )
elseif args.state == 'uncollapsed' then
tbl:addClass('navbox-uncollapsed')
else
else
tbl:addClass( 'mw-collapsed' )
first = args.evenodd
tbl:addClass( 'navbox-autocollapse' )
second = first
end
end
local changer
if first == second then
changer = first
else
local index = 0
changer = function (code)
if code == '0' then
-- Current occurrence is for a group before a nested table.
-- Set it to first as a valid although pointless class.
-- The next occurrence will be the first row after a title
-- in a subgroup and will also be first.
index = 0
return first
end
index = index + 1
return index % 2 == 1 and first or second
end
end
end
end
local regex = orphanCat:gsub('([%[%]])', '%%%1')
return (wikitext:gsub(regex, ''):gsub(REGEX_MARKER, changer))  -- () omits gsub count
end


if yesno( args.collapsible ) then
local function processItem(item, nowrapitems)
tbl:addClass( 'navbox-collapsible' )
if item:sub(1, 2) == '{|' then
-- Applying nowrap to lines in a table does not make sense.
-- Add newlines to compensate for trim of x in |parm=x in a template.
return '\n' .. item ..'\n'
end
end
if nowrapitems == 'yes' then
local lines = {}
for line in (item .. '\n'):gmatch('([^\n]*)\n') do
local prefix, content = line:match('^([*:;#]+)%s*(.*)')
if prefix and not content:match('^<span class="nowrap">') then
line = prefix .. '<span class="nowrap">' .. content .. '</span>'
end
table.insert(lines, line)
end
item = table.concat(lines, '\n')
end
if item:match('^[*:;#]') then
return '\n' .. item ..'\n'
end
return item
end


if args.style then
local function renderNavBar(titleCell)
tbl:cssText( args.style )
 
if args.navbar ~= 'off' and args.navbar ~= 'plain' and not (not args.name and mw.getCurrentFrame():getParent():getTitle():gsub('/sandbox$', '') == 'Template:Navbox') then
titleCell:wikitext(navbar{
args.name,
mini = 1,
fontstyle = (args.basestyle or '') .. ';' .. (args.titlestyle or '') .. ';background:none transparent;border:none;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none; padding:0;'
})
end
end


-- manually set collapse/expand messages
-- bug causing the default database messages to be used
tbl
:attr( {
['cellspacing'] = '0',
['data-expandtext'] = 'show',
['data-collapsetext'] = 'hide',
['data-navbox-name'] = args.name
} )
return tbl
end
end


--
--
-- Wrapper for [[Module:Tnavbar]]
--   Title row
--
--
-- @param args {table}
local function renderTitleRow(tbl)
-- @return {string}
if not args.title then return end
--
 
local function navbar( args )
local titleRow = tbl:tag('tr')
return tnavbar._collapsible( { [1] = '<span style="display:none;">RS3 </span>'..args.title, [2] = args.name } )
 
end
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')
-- Creates the header (what you see when the navbox is collapsed)
--
-- @param tbl {mw.html table}
-- @param args {table}
-- @return {mw.html table}
--
local function header( tbl, args )
local div = insertRow( tbl )
:tag( 'th' )
:attr( 'colspan', '2' )
:addClass( 'navbox-title' )
:attr( 'id' , 'navbox-title' )
:tag( 'div' )


-- @todo move this to site css so we can simplify this (hook off a class)
if args.titlegroup then
-- to something like div:wikitext( args.name and navbar( args ) or args.title )
titleCell
-- which can be appended to the above and returned straight away
:css('border-left', '2px solid #fdfdfd')
if args.name then
:css('width', '100%')
div
:css( 'padding-right', args.state == 'plain' and '6em' or '0' )
:wikitext( navbar( args ) )
else
div
:css( 'padding-left', args.state == 'plain' and '0' or '6em' )
:wikitext( '<span style="display:none;">RS3 </span>'..args.title )
end
end


return div:allDone()
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')
-- id for aria-labelledby attribute
:attr('id', mw.uri.anchorEncode(args.title))
:addClass(args.titleclass)
:css('font-size', '114%')
:css('margin', '0 4em')
:wikitext(processItem(args.title))
end
end


--
--
-- Inserts a row into the navbox
--   Above/Below rows
--
--
-- @param tbl {mw.html table}
-- @param gtitle {string}
-- @param group {string}
-- @param gtype {string}
-- @param gcats {table}
-- @param style {string}
-- @return {mw.html table}
--
local function row( tbl, gtitle, group, gtype, gcats, style, _name, subgroup )
local tr = insertRow( tbl )
local td
if gtitle then
td = tr
:addClass( 'navbox-group' )
:tag( 'th' )
:addClass( 'navbox-group-title' )
:wikitext( gtitle )
:done()
:tag( 'td' )
else
td = tr
:addClass( 'navbox-group' )
:addClass( 'navbox-group-split' )
:tag( 'td' )
:addClass( 'navbox-group-title-hidden' )
:attr( 'colspan', '0' )
:css( 'display', 'none' )
:done()
:tag( 'td' )
:attr( 'colspan', '2' )
end


--[[
local function getAboveBelowColspan()
  List styling
local ret = 2
  This is unlikely to be implemented in the near future due to it requiring extra css to work
if args.imageleft then ret = ret + 1 end
  and mobile currently not supporting that css.
if args.image then ret = ret + 1 end
  As an example, it lets you do the following instead if using {{*}} all the time
return ret
  | group3 =
end
  * {{plink|foo}}
 
  * {{plink|bar}}
local function renderAboveRow(tbl)
  * {{plink|baz}}
if not args.above then return end
]]
 
if mw.ustring.match( group, '^%s*%*' ) then
tbl:tag('tr')
td:newline()
:tag('td')
:addClass('navbox-abovebelow')
:addClass(args.aboveclass)
:cssText(args.basestyle)
:cssText(args.abovestyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
-- id for aria-labelledby attribute, if no title
:attr('id', args.title and nil or mw.uri.anchorEncode(args.above))
:wikitext(processItem(args.above, args.nowrapitems))
end
 
local function renderBelowRow(tbl)
if not args.below then return end


-- trim whitespace on bullets
tbl:tag('tr')
local spl = mw.text.split( group, '\n' )
:tag('td')
:addClass('navbox-abovebelow')
:addClass(args.belowclass)
:cssText(args.basestyle)
:cssText(args.belowstyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
:wikitext(processItem(args.below, args.nowrapitems))
end


for i = 1, #spl do
--
spl[i] = mw.text.trim( spl[i] )
--  List rows
end
--
local function renderListRow(tbl, index, listnum)
local row = tbl:tag('tr')


group = '\n' .. table.concat( spl, '\n' )
if index == 1 and args.imageleft then
row
:tag('td')
:addClass('navbox-image')
:addClass(args.imageclass)
:css('width', '1px')              -- Minimize width
:css('padding', '0px 2px 0px 0px')
:cssText(args.imageleftstyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(processItem(args.imageleft))
end
end


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


--if _name then
-- id for aria-labelledby attribute, if lone group with no title or above
-- local name = mw.ustring.gsub(_name,' ','_')
if listnum == 1 and not (args.title or args.above or args.group2) then
-- for v in mw.ustring.gmatch(group,'%[%[[^%]]+%]%]') do
groupCell
-- if mw.ustring.match(v,'%[%[File:.+|link=') then
:attr('id', mw.uri.anchorEncode(args.group1))
-- local link = mw.ustring.match(v,'|link=([^%]|]+)')
end
-- if link then
-- local linkrep = mw.ustring.gsub(link,'([%%%]%[%-^$*()+?])','%%%1')
-- local _link = mw.ustring.gsub(link,' ','_')
-- local newfile = mw.ustring.gsub(v,'|link='..linkrep,string.format('|link=https://runescape.wiki/w/%s?f=%s',_link,name))
-- local w = mw.ustring.gsub(v,'([%%%]%[%-^$*()+?])','%%%1')
-- group2 = mw.ustring.gsub(group2,w,newfile)
-- end
-- elseif mw.ustring.match(v,'%[%[Category:') then
-- nothing
-- else
-- local link = mw.ustring.match(v,'%[%[([^%]|]+)')
-- local txt = mw.ustring.match(v,'%|([^%]|]+)') or link


-- local newlink = ''
groupCell
:attr('scope', 'row')
:addClass('navbox-group')
:addClass(args.groupclass)
:cssText(args.basestyle)
:css('width', args.groupwidth or '1%') -- If groupwidth not specified, minimize width


-- black links if current page
groupCell
-- if link == page_title then
:cssText(args.groupstyle)
-- newlink = string.format('<b>%s</b>',txt)
:cssText(args['group' .. listnum .. 'style'])
-- else
:wikitext(args['group' .. listnum])
-- local _link = mw.ustring.gsub(link or '',' ','_')
end
-- newlink = string.format('[https://runescape.wiki.com/w/%s?n=%s %s]',_link,name,txt)
-- end
-- local w = mw.ustring.gsub(v,'([%%%]%[%-^$*()+?])','%%%1')
-- group2 = mw.ustring.gsub(group2,w,newlink)
-- end
-- end


--[==[
local listCell = row:tag('td')
fix [[these kind]]s of [[link]]s post analytics parse
]==]
-- group3 = group2


-- for v in mw.ustring.gmatch(group2,'%[https://runescape.wiki.com/w[^%]]-%]%a') do
if args['group' .. listnum] then
-- local rep = mw.ustring.gsub(v,'%]','')
listCell
-- rep = rep..']'
:css('text-align', 'left')
-- local w = mw.ustring.gsub(v,'([%%%]%[%-^$*()+?])','%%%1')
:css('border-left-width', '2px')
:css('border-left-style', 'solid')
else
listCell:attr('colspan', 2)
end


-- group3 = mw.ustring.gsub(group2,w,rep)
if not args.groupwidth then
-- end
listCell:css('width', '100%')
--end
end


td
local rowstyle  -- usually nil so cssText(rowstyle) usually adds nothing
:addClass( 'navbox-list' )
if index % 2 == 1 then
:wikitext( group ) --group3
rowstyle = args.oddstyle
else
rowstyle = args.evenstyle
end


if gtype and mw.ustring.lower( gtype ) == 'subgroup' then
local listText = args['list' .. listnum]
td
local oddEven = ODD_EVEN_MARKER
:addClass( 'navbox-parent' )
if listText:sub(1, 12) == '</div><table' then
:css( {
-- Assume list text is for a subgroup navbox so no automatic striping for this row.
padding = '0',
oddEven = listText:find('<th[^>]*"navbox%-title"') and RESTART_MARKER or 'odd'
['border-bottom'] = '0'
} )
end
end
listCell
:css('padding', '0px')
:cssText(args.liststyle)
:cssText(rowstyle)
:cssText(args['list' .. listnum .. 'style'])
:addClass('navbox-list')
:addClass('navbox-' .. oddEven)
:addClass(args.listclass)
:addClass(args['list' .. listnum .. 'class'])
:tag('div')
:css('padding', (index == 1 and args.list1padding) or args.listpadding or '0em 0.25em')
:wikitext(processItem(listText, args.nowrapitems))


if style then
if index == 1 and args.image then
td:cssText( style )
row
:tag('td')
:addClass('navbox-image')
:addClass(args.imageclass)
:css('width', '1px')              -- Minimize width
:css('padding', '0px 0px 0px 2px')
:cssText(args.imagestyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(processItem(args.image))
end
end
-- add subgroup categories
if next(gcats) and onmain then
first_char = page_title:sub(1,1)
title_pattern = "[" .. first_char:upper() .. first_char:lower() .. "]" .. page_title:sub(2)
title_pattern = title_pattern :gsub("%(","%%(")
:gsub("%)","%%)")
:gsub("_"," ")
:gsub(" ","[_ ]")
:gsub("%-","%%-")
local link_patterns = {
"%[%["..title_pattern.."%]%]", "%[%["..title_pattern.."%|", "{{[Pp]link%|"..title_pattern.."}}",
"{{[Pp]link%|"..title_pattern.."%|", "{{[Pp]linkp%|"..title_pattern.."}}",
"{{[Pp]linkp%|"..title_pattern.."%|", "{{[Ii]linkp%|"..title_pattern.."}}",
"{{[Ii]linkp%|"..title_pattern.."%|", "{{[Cc]hatl%|"..title_pattern.."}}",
"{{[Cc]hatl%|"..title_pattern.."%|"
}
for _,v in ipairs(link_patterns) do
if group:match(v) then
for _,cat in ipairs(gcats) do
td:wikitext('[[Category:'..cat..']]')
end
break
end
end
end
return td:allDone()
end
end


--
--
-- Inserts a footer into the navbox
--   Tracking categories
--
--
-- @param tbl {mw.html table}
-- @param args {table}
-- @return {mw.html table}
--
local function footer( tbl, args )
local th = insertRow( tbl )
:tag( 'th' )
:attr( 'colspan', '2' )
:addClass( 'navbox-footer' )


if args.fstyle then
local function needsHorizontalLists()
th:cssText( args.fstyle )
if border == 'subgroup' or args.tracking == 'no' then
return false
end
end
local listClasses = {
['plainlist'] = true, ['hlist'] = true, ['hlist hnum'] = true,
['hlist hwrap'] = true, ['hlist vcard'] = true, ['vcard hlist'] = true,
['hlist vevent'] = true,
}
return not (listClasses[args.listclass] or listClasses[args.bodyclass])
end


if mw.ustring.match( args.footer, '^%s*%*' ) then
local function hasBackgroundColors()
th:newline()
for _, key in ipairs({'titlestyle', 'groupstyle', 'basestyle', 'abovestyle', 'belowstyle'}) do
 
if tostring(args[key]):find('background', 1, true) then
-- trim whitespace on bullets
return true
local spl = mw.text.split( args.footer, '\n' )
end
end
end


for i = 1, #spl do
local function hasBorders()
spl[i] = mw.text.trim( spl[i] )
for _, key in ipairs({'groupstyle', 'basestyle', 'abovestyle', 'belowstyle'}) do
if tostring(args[key]):find('border', 1, true) then
return true
end
end
end
end


args.footer = table.concat( spl, '\n' )
local function isIllegible()
local styleratio = require('Module:Color contrast')._styleratio


th:addClass( 'navbox-list' )
for key, style in pairs(args) do
if tostring(key):match("style$") then
if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
return true
end
end
end
end
return false
end


th:wikitext( args.footer )
local function getTrackingCategories()
 
local cats = {}
return th:allDone()
if needsHorizontalLists() then table.insert(cats, 'Navigational boxes without horizontal lists') end
if hasBackgroundColors() then table.insert(cats, 'Navboxes using background colours') end
if isIllegible() then table.insert(cats, 'Potentially illegible navboxes') end
if hasBorders() then table.insert(cats, 'Navboxes using borders') end
return cats
end
end


--
local function renderTrackingCategories(builder)
-- Adds [[Category:Navigational templates]] to navbox template pages
--
-- @return {string}
--
local function categories()
local title = mw.title.getCurrentTitle()
local title = mw.title.getCurrentTitle()
local page = title.text
if title.namespace ~= 10 then return end -- not in template space
local ns = title.nsText
local subpage = title.subpageText
if subpage == 'doc' or subpage == 'sandbox' or subpage == 'testcases' then return end


if ns == 'Template' then
for _, cat in ipairs(getTrackingCategories()) do
-- sort in category by pagename
builder:wikitext('[[Category:' .. cat .. ']]')
return '[[Category:Navigational templates|' .. page .. ']]'
else
return ''
end
end
end
end


--
--
-- Adds [[Template:Navbox/doc]] to navbox template pages
--   Main navbox tables
--
--
-- @param args {table}
local function renderMainTable()
-- @return {string}
local tbl = mw.html.create('table')
--
:addClass('nowraplinks')
local function docs( args )
:addClass(args.bodyclass)
local frame = mw.getCurrentFrame()
 
local title = mw.title.getCurrentTitle()
if args.title and (args.state ~= 'plain' and args.state ~= 'off') then
local base = title.baseText
if args.state == 'collapsed' then args.state = 'mw-collapsed' end
local ns = title.nsText
tbl
:addClass('mw-collapsible')
:addClass(args.state or 'autocollapse')
end
 
tbl:css('border-spacing', 0)
if border == 'subgroup' or border == 'none' then
tbl
:addClass('navbox-subgroup')
:cssText(args.bodystyle)
:cssText(args.style)
else  -- regular navbox - 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)


-- not if a subpage of [[Template:Navbox]]
renderTitleRow(tbl)
if base ~= 'Navbox' and
renderAboveRow(tbl)
-- in template ns
for i, listnum in ipairs(listnums) do
ns == 'Template' and
renderListRow(tbl, i, listnum)
-- not a navbox group within a navbox
not yesno( args.subgroup ) and
-- not a collapsible navbox within a navbox
not yesno( args.collapsible ) and
-- not if the doc argument is not set to "yes"
yesno( args.doc, false )
then
return frame:expandTemplate{ title = 'Navbox/doc' }
else
return ''
end
end
renderBelowRow(tbl)


return tbl
end
end


--
function p._navbox(navboxArgs)
-- Navbox method to allow it to be called by other modules
args = navboxArgs
--
listnums = {}
-- @param _args {table}
 
-- @return {string}
for k, _ in pairs(args) do
--
if type(k) == 'string' then
function p._navbox( _args )
local listnum = k:match('^list(%d+)$')
local args = {}
if listnum then table.insert(listnums, tonumber(listnum)) end
local wkCss = ''
local wkDiv = ''
local j
-- preserves parser function behaviour where an empty string is considered undefined
-- or nil in lua's case
for k, v in pairs( _args ) do
if v ~= '' then
args[k] = v
end
end
end
end
table.sort(listnums)


local tbl = createTbl( args )
border = mw.text.trim(args.border or args[1] or '')
 
if border == 'child' then
if not yesno( args.subgroup ) then
border = 'subgroup'
tbl = header( tbl, args )
end
end


-- insert up to 20 rows
-- render the main body of the navbox
--
local tbl = renderMainTable()
-- 20 is a limit inherited from wikipedia when we copied this over
-- and we've never had a reason to extend it
for i = 1, 20 do
j = tostring( i )


if args['group' .. j] then
-- render the appropriate wrapper around the navbox, depending on the border param
local gcats = {}
local res = mw.html.create()
for p = 1, 20 do
if border == 'none' then
local q = tostring ( p )
local nav = res:tag('div')
:attr('role', 'navigation')
if args['g' .. j .. 'cat' .. q] then
:node(tbl)
table.insert(gcats, args['g' .. j .. 'cat' .. q])
-- aria-labelledby title, otherwise above, otherwise lone group
else
if args.title or args.above or (args.group1 and not args.group2) then
break
nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title or args.above or args.group1))
end
else
end
nav:attr('aria-label', 'Navbox')
end
tbl = row( tbl, args['gtitle' .. j], args['group' .. j], args['gtype' .. j], gcats, args['style' .. j], args.name, args.subgroup )
elseif border == 'subgroup' 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>')
:node(tbl)
:wikitext('<div>')
else
local nav = res:tag('div')
:attr('role', 'navigation')
:addClass('navbox')
:addClass(args.navboxclass)
:cssText(args.bodystyle)
:cssText(args.style)
:css('padding', '3px')
:node(tbl)
-- aria-labelledby title, otherwise above, otherwise lone group
if args.title or args.above or (args.group1 and not args.group2) then
nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title or args.above or args.group1))
else
else
break
nav:attr('aria-label', 'Navbox')
end
end
end
end


if args.footer then
if (args.nocat or 'false'):lower() == 'false' then
tbl = footer( tbl, args )
renderTrackingCategories(res)
end
end
return striped(tostring(res))
end


tbl = tostring( tbl )
function p.navbox(frame)
if not getArgs then
getArgs = require('Module:Arguments').getArgs
end
args = getArgs(frame, {wrappers = {'Template:Navbox', 'Template:Navbox subgroup'}})
if frame.args.border then
-- This allows Template:Navbox_subgroup to use {{#invoke:Navbox|navbox|border=...}}.
args.border = frame.args.border
end


local cats = ''
-- Read the arguments in the order they'll be output in, to make references number in the right order.
if not yesno(args.subgroup) and not yesno(args.hidecat) then
local _
cats = categories()
_ = args.title
_ = args.above
for i = 1, 20 do
_ = args["group" .. tostring(i)]
_ = args["list" .. tostring(i)]
end
end
local docs = docs( args )
_ = args.below
 
return tbl .. cats .. docs
end


--
return p._navbox(args)
-- Main navbox method accessed through #invoke
--
-- @param frame {table}
-- @return {string}
--
function p.navbox( frame )
local args = frame:getParent().args
return p._navbox( args )
end
end


return p
return p
-- </nowiki>

Latest revision as of 00:06, 26 August 2024

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 border
local listnums
local ODD_EVEN_MARKER = '\127_ODDEVEN_\127'
local RESTART_MARKER = '\127_ODDEVEN0_\127'
local REGEX_MARKER = '\127_ODDEVEN(%d?)_\127'

local function striped(wikitext)
	-- Return wikitext with markers replaced for odd/even striping.
	-- Child (subgroup) navboxes are flagged with a category that is removed
	-- by parent navboxes. The result is that the category shows all pages
	-- where a child navbox is not contained in a parent navbox.
	local orphanCat = '[[Category:Navbox orphans]]'
	if border == 'subgroup' and args.orphan ~= 'yes' then
		-- No change; striping occurs in outermost navbox.
		return wikitext .. orphanCat
	end
	local first, second = 'odd', 'even'
	if args.evenodd then
		if args.evenodd == 'swap' then
			first, second = second, first
		else
			first = args.evenodd
			second = first
		end
	end
	local changer
	if first == second then
		changer = first
	else
		local index = 0
		changer = function (code)
			if code == '0' then
				-- Current occurrence is for a group before a nested table.
				-- Set it to first as a valid although pointless class.
				-- The next occurrence will be the first row after a title
				-- in a subgroup and will also be first.
				index = 0
				return first
			end
			index = index + 1
			return index % 2 == 1 and first or second
		end
	end
	local regex = orphanCat:gsub('([%[%]])', '%%%1')
	return (wikitext:gsub(regex, ''):gsub(REGEX_MARKER, changer))  -- () omits gsub count
end

local function processItem(item, nowrapitems)
	if item:sub(1, 2) == '{|' then
		-- Applying nowrap to lines in a table does not make sense.
		-- Add newlines to compensate for trim of x in |parm=x in a template.
		return '\n' .. item ..'\n'
	end
	if nowrapitems == 'yes' then
		local lines = {}
		for line in (item .. '\n'):gmatch('([^\n]*)\n') do
			local prefix, content = line:match('^([*:;#]+)%s*(.*)')
			if prefix and not content:match('^<span class="nowrap">') then
				line = prefix .. '<span class="nowrap">' .. content .. '</span>'
			end
			table.insert(lines, line)
		end
		item = table.concat(lines, '\n')
	end
	if item:match('^[*:;#]') then
		return '\n' .. item ..'\n'
	end
	return item
end

local function renderNavBar(titleCell)

	if args.navbar ~= 'off' and args.navbar ~= 'plain' and not (not args.name and mw.getCurrentFrame():getParent():getTitle():gsub('/sandbox$', '') == 'Template:Navbox') then
		titleCell:wikitext(navbar{
			args.name,
			mini = 1,
			fontstyle = (args.basestyle or '') .. ';' .. (args.titlestyle or '') .. ';background:none transparent;border:none;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none; padding:0;'
		})
	end

end

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

	local titleRow = tbl:tag('tr')

	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')
			-- id for aria-labelledby attribute
			:attr('id', mw.uri.anchorEncode(args.title))
			:addClass(args.titleclass)
			:css('font-size', '114%')
			:css('margin', '0 4em')
			:wikitext(processItem(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

	tbl:tag('tr')
		:tag('td')
			:addClass('navbox-abovebelow')
			:addClass(args.aboveclass)
			:cssText(args.basestyle)
			:cssText(args.abovestyle)
			:attr('colspan', getAboveBelowColspan())
			:tag('div')
				-- id for aria-labelledby attribute, if no title
				:attr('id', args.title and nil or mw.uri.anchorEncode(args.above))
				:wikitext(processItem(args.above, args.nowrapitems))
end

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

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

--
--   List rows
--
local function renderListRow(tbl, index, listnum)
	local row = tbl:tag('tr')

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

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

		-- id for aria-labelledby attribute, if lone group with no title or above
		if listnum == 1 and not (args.title or args.above or args.group2) then
			groupCell
				:attr('id', mw.uri.anchorEncode(args.group1))
		end

		groupCell
			:attr('scope', 'row')
			:addClass('navbox-group')
			:addClass(args.groupclass)
			:cssText(args.basestyle)
			:css('width', args.groupwidth or '1%') -- If groupwidth not specified, minimize width

		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 rowstyle  -- usually nil so cssText(rowstyle) usually adds nothing
	if index % 2 == 1 then
		rowstyle = args.oddstyle
	else
		rowstyle = args.evenstyle
	end

	local listText = args['list' .. listnum]
	local oddEven = ODD_EVEN_MARKER
	if listText:sub(1, 12) == '</div><table' then
		-- Assume list text is for a subgroup navbox so no automatic striping for this row.
		oddEven = listText:find('<th[^>]*"navbox%-title"') and RESTART_MARKER or 'odd'
	end
	listCell
		:css('padding', '0px')
		:cssText(args.liststyle)
		:cssText(rowstyle)
		:cssText(args['list' .. listnum .. 'style'])
		:addClass('navbox-list')
		:addClass('navbox-' .. oddEven)
		:addClass(args.listclass)
		:addClass(args['list' .. listnum .. 'class'])
		:tag('div')
			:css('padding', (index == 1 and args.list1padding) or args.listpadding or '0em 0.25em')
			:wikitext(processItem(listText, args.nowrapitems))

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


--
--   Tracking categories
--

local function needsHorizontalLists()
	if border == 'subgroup' or args.tracking == 'no' then
		return false
	end
	local listClasses = {
		['plainlist'] = true, ['hlist'] = true, ['hlist hnum'] = true,
		['hlist hwrap'] = true, ['hlist vcard'] = true, ['vcard hlist'] = true,
		['hlist vevent'] = true,
	}
	return not (listClasses[args.listclass] or listClasses[args.bodyclass])
end

local function hasBackgroundColors()
	for _, key in ipairs({'titlestyle', 'groupstyle', 'basestyle', 'abovestyle', 'belowstyle'}) do
		if tostring(args[key]):find('background', 1, true) then
			return true
		end
	end
end

local function hasBorders()
	for _, key in ipairs({'groupstyle', 'basestyle', 'abovestyle', 'belowstyle'}) do
		if tostring(args[key]):find('border', 1, true) then
			return true
		end
	end
end

local function isIllegible()
	local styleratio = require('Module:Color contrast')._styleratio

	for key, style in pairs(args) do
		if tostring(key):match("style$") then
			if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
				return true
			end
		end
	end
	return false
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
	if isIllegible() then table.insert(cats, 'Potentially illegible navboxes') end
	if hasBorders() then table.insert(cats, 'Navboxes using borders') 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 _, 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
		if args.state == 'collapsed' then args.state = 'mw-collapsed' end
		tbl
			:addClass('mw-collapsible')
			:addClass(args.state or 'autocollapse')
	end

	tbl:css('border-spacing', 0)
	if border == 'subgroup' or border == 'none' then
		tbl
			:addClass('navbox-subgroup')
			:cssText(args.bodystyle)
			:cssText(args.style)
	else  -- regular navbox - 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, i, listnum)
	end
	renderBelowRow(tbl)

	return tbl
end

function p._navbox(navboxArgs)
	args = navboxArgs
	listnums = {}

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

	border = mw.text.trim(args.border or args[1] or '')
	if border == 'child' then
		border = 'subgroup'
	end

	-- 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
		local nav = res:tag('div')
			:attr('role', 'navigation')
			:node(tbl)
		-- aria-labelledby title, otherwise above, otherwise lone group
		if args.title or args.above or (args.group1 and not args.group2) then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title or args.above or args.group1))
		else
			nav:attr('aria-label', 'Navbox')
		end
	elseif border == 'subgroup' 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>')
			:node(tbl)
			:wikitext('<div>')
	else
		local nav = res:tag('div')
			:attr('role', 'navigation')
			:addClass('navbox')
			:addClass(args.navboxclass)
			:cssText(args.bodystyle)
			:cssText(args.style)
			:css('padding', '3px')
			:node(tbl)
		-- aria-labelledby title, otherwise above, otherwise lone group
		if args.title or args.above or (args.group1 and not args.group2) then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title or args.above or args.group1))
		else
			nav:attr('aria-label', 'Navbox')
		end
	end

	if (args.nocat or 'false'):lower() == 'false' then
		renderTrackingCategories(res)
	end
	return striped(tostring(res))
end

function p.navbox(frame)
	if not getArgs then
		getArgs = require('Module:Arguments').getArgs
	end
	args = getArgs(frame, {wrappers = {'Template:Navbox', 'Template:Navbox subgroup'}})
	if frame.args.border then
		-- This allows Template:Navbox_subgroup to use {{#invoke:Navbox|navbox|border=...}}.
		args.border = frame.args.border
	end

	-- 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