|
require('strict')
local p = {}
local cfg = mw.loadData('Module:Navbox/configuration')
local inArray = require("Module:TableTools").inArray
local getArgs -- lazily initialized
local hiding_templatestyles = {}
local navbar = require "Module:Navbar"._navbar
-- global passthrough variables
local passthroughtrim = {mw.text.trim
local tools = require 'Module:TableTools'
[cfg.arg.above]=true,[cfg.arg.aboveclass]=true,[cfg.arg.abovestyle]=true,
local boolean = require 'Module:Yesno'
[cfg.arg.basestyle]=true,
[cfg.arg.below]=true,[cfg.arg.belowclass]=true,[cfg.arg.belowstyle]=true,
[cfg.arg.bodyclass]=true,
[cfg.arg.groupclass]=true,
[cfg.arg.image]=true,[cfg.arg.imageclass]=true,[cfg.arg.imagestyle]=true,
[cfg.arg.imageleft]=true,[cfg.arg.imageleftstyle]=true,
[cfg.arg.listclass]=true,
[cfg.arg.name]=true,
[cfg.arg.navbar]=true,
[cfg.arg.state]=true,
[cfg.arg.title]=true,[cfg.arg.titleclass]=true,[cfg.arg.titlestyle]=true,
argHash=true
}
--[[
-- helper functions
用于多次访问表的字段。例如,
local andnum = function(s, n) return string.format(cfg.arg[s .. '_and_num'], n) end
index(t, 'a', 'b', 'c')
local isblank = function(v) return (v or '') == '' end
类似于
t.a.b.c 但如果a或b字段不存在,直接返回nil,而不是抛出错误。
local function concatstrings(s)
就相当于
local r = table.concat(s, '')
((t.a or {}).b).c
if r:match('^%s*$') then return nil end
]]
return r
local function index(t, ...)
end
local result = t
for i = 1, select("#", ...) do
local function concatstyles(s)
local rk = ''select(i, ...)
if type(result) == "table" then
for _, v in ipairs(s) do
result = result[k]
v = mw.text.trim(v, "%s;")
else
if not isblank(v) then r = r .. v .. ';' end
return nil
end
if isblank(r) then return nil end
return r
end
local function getSubgroup(args, listnum, listText, prefix)
local subArgs = {
[cfg.arg.border] = cfg.keyword.border_subgroup,
[cfg.arg.navbar] = cfg.keyword.navbar_plain,
argHash = 0
}
local hasSubArgs = false
local subgroups_and_num = prefix and {prefix} or cfg.arg.subgroups_and_num
for k, v in pairs(args) do
k = tostring(k)
for _, w in ipairs(subgroups_and_num) do
w = string.format(w, listnum) .. "_"
if (#k > #w) and (k:sub(1, #w) == w) then
subArgs[k:sub(#w + 1)] = v
hasSubArgs = true
subArgs.argHash = subArgs.argHash + (v and #v or 0)
end
end
end
return result
return hasSubArgs and p._navbox(subArgs) or listText
end
--[[
-- Main functions
为表创建指定位置的字段。例如,
function p._navbox(args)
newindex(t, value, 'a', 'b', 'c')
if args.type == cfg.keyword.with_collapsible_groups then
就类似于
return p._withCollapsibleGroups(args)
t.a.b.c = value
elseif args.type == cfg.keyword.with_columns then
但是当a、b字段不存在时,以空表创建字段,再写入这个空表。大致相当于:
return p._withColumns(args)
t.a = t.a or {}
t.a.b = t.a.b or {}
t.a.b.c = value
]]
local function newindex(t, value, ...)
local current = t
local k
if type(current) ~= 'table' then
return current
end
for i = 1, select("#", ...) - 1 do
local function striped(wikitext, border)
-- 此时的current必然是个表
-- Return wikitext with markers replaced for odd/even striping.
k = select(i, ...)
-- Child (subgroup) navboxes are flagged with a category that is removed
if not current[k] then
-- by parent navboxes. The result is that the category shows all pages
current[k] = {}
-- where a child navbox is not contained in a parent navbox.
elseif type(current[k]) ~= 'table' then
local orphanCat = cfg.category.orphan
local warn = '警告:尝试将字段值' .. tostring(value)
if border == cfg.keyword.border_subgroup and args[cfg.arg.orphan] ~= cfg.keyword.orphan_yes then
.. '写入非空非表的值:' .. tostring(current[k])
-- No change; striping occurs in outermost navbox.
mw.addWarning(warn)
return wikitext .. orphanCat
mw.log(warn)
mw.log('\tt=', t)
mw.log('\t...=', ...)
mw.log(debug.traceback())
return
end
current = current[k]
local first, second = cfg.class.navbox_odd_part, cfg.class.navbox_even_part
if args[cfg.arg.evenodd] then
if args[cfg.arg.evenodd] == cfg.keyword.evenodd_swap then
first, second = second, first
else
first = args[cfg.arg.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(cfg.marker.regex, changer)) -- () omits gsub count
end
if type(current[k]) ~= "table" then
k = select(-1, ...)
local function processItem(item, nowrapitems)
current[k] = value
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 == cfg.keyword.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(cfg.pattern.nowrap) then
line = string.format(cfg.nowrap_item, prefix, content)
end
table.insert(lines, line)
end
item = table.concat(lines, '\n')
end
if item:match('^[*:;#]') then
return '\n' .. item .. '\n'
end
return item
end
return type(value) == "table" and current[k] or t
end
local function has_navbaraddNewline(s)
if s:match("^[*:;#]") or s:match("^{|") then
return args[cfg.arg.navbar] ~= cfg.keyword.navbar_off
return "\n" .. s .. "\n"
and args[cfg.arg.navbar] ~= cfg.keyword.navbar_plain
else
and (
return s
args[cfg.arg.name]
or mw.getCurrentFrame():getParent():getTitle():gsub(cfg.pattern.sandbox, '')
~= cfg.pattern.navbox
)
end
end
--[[
-- extract text color from css, which is the only permitted inline CSS for the navbar
识别单个数字或拆分逗号隔开的多个数字(@param key)并转化为多个数字。例如:
local function extract_color(css_str)
getKeys '1' → {1}
-- return nil because navbar takes its argument into mw.html which handles
getKeys '1-4' → {1, 'list', 'content', 4}
-- nil gracefully, removing the associated style attribute
getKeys '1-4-5' → {1, 'list', 'content', 4, 'list', 'content', 5}
return mw.ustring.match(';' .. css_str .. ';', '.*;%s*([Cc][Oo][Ll][Oo][Rr]%s*:%s*.-)%s*;') or nil
不符合格式的键会返回nil。
end
可选参数(@param ...)会被加在表的最后。例如:
getKeys '1-4style' → {1, 'list', 'content', 4, 'style'}
local function renderNavBar(titleCell)
]]
if has_navbar() then
local function getkeys(key, ...)
local navbar = require('Module:Navbar')._navbar
local keys = {}
titleCell:wikitext(navbar{
for eachnum in key:gmatch "[^%- ]+" do
[cfg.navbar.name] = args[cfg.arg.name],
-- 以横杠(减号)为分隔拆分数字
[cfg.navbar.mini] = 1,
eachnum = tonumber(eachnum)
[cfg.navbar.fontstyle] = extract_color(
if not eachnum then
(args[cfg.arg.basestyle] or '') .. ';' .. (args[cfg.arg.titlestyle] or '')
)return nil
})
end
-- 循环体里面使用原始写法,以增加效率。
keys[#keys + 1] = eachnum
keys[#keys + 1] = "list"
keys[#keys + 1] = "content"
end
keys[#keys], keys[#keys - 1] = nil, nil
-- 最后的两个list和content不一定需要
local function renderTitleRow(tbl)
-- 需要时会作为可选参数传入
if not args[cfg.arg.title] then return end
if #keys == 0 then
return nil
local titleRow = tbl:tag('tr')
local titleCell = titleRow:tag('th'):attr('scope', 'col')
local titleColspan = 2
if args[cfg.arg.imageleft] then titleColspan = titleColspan + 1 end
if args[cfg.arg.image] then titleColspan = titleColspan + 1 end
titleCell
:cssText(args[cfg.arg.basestyle])
:cssText(args[cfg.arg.titlestyle])
:addClass(cfg.class.navbox_title)
:attr('colspan', titleColspan)
renderNavBar(titleCell)
titleCell
:tag('div')
-- id for aria-labelledby attribute
:attr('id', mw.uri.anchorEncode(args[cfg.arg.title]) .. args.argHash)
:addClass(args[cfg.arg.titleclass])
:css('font-size', '114%')
:css('margin', '0 4em')
:wikitext(processItem(args[cfg.arg.title]))
end
for i = 1, select("#", ...) do
local function getAboveBelowColspan()
keys[#keys + 1] = select(i, ...)
local ret = 2
if args[cfg.arg.imageleft] then ret = ret + 1 end
if args[cfg.arg.image] then ret = ret + 1 end
return ret
end
return keys
end
-- 将上述函数导出为public以便于外部访问
local function renderAboveRow(tbl)
p.getkeys = getkeys
if not args[cfg.arg.above] then return end
-- 为便于维护,采用面向对象。
tbl:tag('tr')
:tag('td')
:addClass(cfg.class.navbox_abovebelow)
:addClass(args[cfg.arg.aboveclass])
:cssText(args[cfg.arg.basestyle])
:cssText(args[cfg.arg.abovestyle])
:attr('colspan', getAboveBelowColspan())
:tag('div')
-- id for aria-labelledby attribute, if no title
:attr('id', (not args[cfg.arg.title]) and
(mw.uri.anchorEncode(args[cfg.arg.above]) .. args.argHash)
or nil)
:wikitext(processItem(args[cfg.arg.above], args[cfg.arg.nowrapitems]))
end
--[[
local function renderBelowRow(tbl)
创建一个新的navbox对象。
if not args[cfg.arg.below] then return end
创建时,其对应的html对象会被自动创建,也可以在参数中手动创建。
创建一个子框表时,会给它设置好根框表。
@param paras 可选的命名参数,包括:
rootself 如果正在创建一个子框表,则该参数为根框表对象
frame 框架对象,可能为null
args 该对象的参数
level 该对象的等级,根框表为0,子框表为1
root 该对象的根元素对象,如果为nil则会在渲染时准备
]]
function p.new(paras)
local obj = {}
tbl:tag('tr')
local paras = paras or {}
:tag('td')
obj.rootself = paras.rootself or obj
:addClass(cfg.class.navbox_abovebelow)
obj.data = paras.data or {}
:addClass(args[cfg.arg.belowclass])
local frame = paras.frame
:cssText(args[cfg.arg.basestyle])
obj.frame = paras.frame -- or nil
:cssText(args[cfg.arg.belowstyle])
obj.args = paras.args or {}
:attr('colspan', getAboveBelowColspan())
obj.level = paras.level or 0
:tag('div')
obj.root = paras.root
:wikitext(processItem(args[cfg.arg.below], args[cfg.arg.nowrapitems]))
return setmetatable(
obj,
{
__index = p
}
)
end
function p:renderRow(groupArgs, listArgs, k)
-- 给定一个列的标题和文本,渲染这个列。
local listContent = listArgs.content
if not listContent then
return
end
local listStyle = listArgs.style
local listClass = listArgs.class
local groupContent = groupArgs.content
local groupStyle = groupArgs.style
local groupClass = groupArgs.class
local data = self.data
local isGroups = data.isGroups
-- 根框表的数据。
local rootdata = self.rootself.data
-- 对于子框表,其list的奇偶性存储在根框表中,而非子框表本身。
local function renderListRow(tbl, index, listnum, listnums_size)
local rowisEven = tbl:tag('tr')self.rootself.isEven
local root = self.root
if index == 1 and args[cfg.arg.imageleft] then
row
local row = root
:tag('td')
if isGroups then
:addClass(cfg.class.noviewer)
row = root:tag "div"
:addClass(cfg.class.navbox_image)
:addClass(args[cfg.arg.imageclass]) "navbox-list navbox-sole-row navbox"
:addClass "collapsible"
:css('width', '1px') -- Minimize width
local selected = data.selected
:css('padding', '0 2px 0 0')
local isSelected
:cssText(args[cfg.arg.imageleftstyle])
if not selected or next(selected)==nil or selected.all or selected['*'] then
:attr('rowspan', listnums_size)
isSelected = true
:tag('div')
elseif selected.none then
:wikitext(processItem(args[cfg.arg.imageleft]))
isSelected = false
elseif selected[listArgs.id] or selected[k] then
isSelected = true
end
if not isSelected then
row:addClass 'collapsed'
local group_and_num = andnum('group', listnum)
local groupstyle_and_num = andnum('groupstyle', listnum)
if args[group_and_num] 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[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group2]) then
groupCell
:attr('id', mw.uri.anchorEncode(args[cfg.arg.group1]) .. args.argHash)
end
groupCell
:attr('scope', 'row')
:addClass(cfg.class.navbox_group)
:addClass(args[cfg.arg.groupclass])
:cssText(args[cfg.arg.basestyle])
-- If groupwidth not specified, minimize width
:css('width', args[cfg.arg.groupwidth] or '1%')
groupCell
:cssText(args[cfg.arg.groupstyle])
:cssText(args[groupstyle_and_num])
:wikitext(args[group_and_num])
end
end
if groupContent then
local group =
row:tag "div" -- groupclass、groupstyle等不影响其子框表的group。
:addClass "navbox-cell"
:addClass(isGroups and "navbox-title navbox-sole-row" or "navbox-group")
:addClass(index(data, "group", "class")) -- 单独类,比如group1class
:addClass(groupClass) -- 共同类,即args中的groupclass
:cssText(index(data, "group", "style")) -- 单独样式,比如group1style
:cssText(groupStyle) -- 共同样式,比如groupstyle
:tag "span"
:wikitext(addNewline(groupContent))
:addClass(isGroups and "navbox-title-content" or nil)
:done()
end
local listCelllist = row:tag('td') "div"
:addClass "navbox-list navbox-cell"
:addClass(listClass) -- 共同类,即args中的listclass
if args[group_and_num] then
:cssText(listStyle) -- 共同样式,即args中的liststyle
listCell
:addClass(cfg.class.navbox_list_with_group)
-- 该列表所在直接框表中定义的样式
else
:addClass(index(data, "list", "class"))
listCell:attr('colspan', 2)
:cssText(index(data, "list", "style"))
if rootdata ~= data then list
:addClass(index(rootdata, "list", "class"))
:cssText(index(rootdata, "list", "style"))
end
if isGroups or not args[cfg.arg.groupwidth]groupContent then
list:addClass "navbox-sole-row"
listCell:css('width', '100%')
end
if type(listContent) == "string" then
local rowstyle -- usually nil so cssText(rowstyle) usually adds nothing
-- addNewline函数在前文中已定义
if index % 2 == 1 then
-- 一层span是为了适应grid,二层span是为了应付维基百科遗留下来的先</span>再<span>的烂代码
rowstyle = args[cfg.arg.oddstyle]
-- 未来肯定是不会有两层span了
list
:tag 'span':tag 'span'
:wikitext(addNewline(listContent))
-- 则这个list不受listclass、liststyle的影响。
self.rootself.isEven = not isEven -- 交换奇偶性
if isEven then
list
:addClass "navbox-even"
:addClass(index(rootdata, "even", "class"))
:cssText(index(rootdata, "even", "style"))
else
list
rowstyle = args[cfg.arg.evenstyle]
:addClass "navbox-odd"
:addClass(index(rootdata, "odd", "class"))
:cssText(index(rootdata, "odd", "style"))
end
elseif type(listContent) == "table" then
local list_and_numsubElement = andnum('list',:addClass listnum)"navbox"
-- listngroupwidth
local listText = inArray(cfg.keyword.subgroups, args[list_and_num])
local groupwidth = listArgs.groupwidth
and getSubgroup(args, listnum, args[list_and_num]) or args[list_and_num]
if groupwidth then
list:css('grid-template-columns', tostring(groupwidth) .. ' auto')
local oddEven = cfg.marker.oddeven
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(cfg.pattern.navbox_title) and cfg.marker.restart or cfg.class.navbox_odd_part
end
local liststyle_and_num = andnum('liststyle', listnum)
local listclass_and_num = andnum('listclass', listnum)
listCell
:css('padding', '0')
:cssText(args[cfg.arg.liststyle])
:cssText(rowstyle)
:cssText(args[liststyle_and_num])
:addClass(cfg.class.navbox_list)
:addClass(cfg.class.navbox_part .. oddEven)
:addClass(args[cfg.arg.listclass])
:addClass(args[listclass_and_num])
:tag('div')
:css('padding',
(index == 1 and args[cfg.arg.list1padding]) or args[cfg.arg.listpadding] or '0 0.25em'
)
:wikitext(processItem(listText, args[cfg.arg.nowrapitems]))
if index == 1 and args[cfg.arg.image] then
row
:tag('td')
:addClass(cfg.class.noviewer)
:addClass(cfg.class.navbox_image)
:addClass(args[cfg.arg.imageclass])
:css('width', '1px') -- Minimize width
:css('padding', '0 0 0 2px')
:cssText(args[cfg.arg.imagestyle])
:attr('rowspan', listnums_size)
:tag('div')
:wikitext(processItem(args[cfg.arg.image]))
end
local subObj = self.new {
rootself = self,
root = subElement,
data = listContent,
level = (self.level or 0) + 1
}
subObj:render()
end
root:newline()
return row
end
local function has_list_classp:renderSingleRow(htmlclassrowArgs)
-- 渲染标题、上方栏或下方栏
local patterns = {
-- type可以是'title' 'above' 'below'
'^' .. htmlclass .. '$',
local content = rowArgs.content
'%s' .. htmlclass .. '$',
if content then
'^' .. htmlclass .. '%s',
content = addNewline(content)
'%s' .. htmlclass .. '%s'
else
}
return
for arg, _ in pairs(args) do
if type(arg) == 'string' and mw.ustring.find(arg, cfg.pattern.class) then
for _, pattern in ipairs(patterns) do
if mw.ustring.find(args[arg] or '', pattern) then
return true
end
end
end
end
return false
end
local class = rowArgs.class
-- there are a lot of list classes in the wild, so we add their TemplateStyles
local functionstyle add_list_styles()= rowArgs.style
local rowtype = rowArgs.rowtype or "unknown-rowtype"
local frame = mw.getCurrentFrame()
local root = self.root
local function add_list_templatestyles(htmlclass, templatestyles)
local level = rowArgs.level
if has_list_class(htmlclass) then
return frame:extensionTag{
name = 'templatestyles', args = { src = templatestyles }
}
else
return ''
end
end
local row =
local hlist_styles = add_list_templatestyles('hlist', cfg.hlist_templatestyles)
root
local plainlist_styles = add_list_templatestyles('plainlist', cfg.plainlist_templatestyles)
:tag "div"
:addClass "navbox-cell navbox-sole-row"
:addClass("navbox-" .. rowtype):addClass(
class
):cssText(style):attr("colspan", "2")
if rowtype == "title" then
-- a second workaround for [[phab:T303378]]
if level == 0 then
-- when that issue is fixed, we can actually use has_navbar not to emit the
local navbarObj = rowArgs.navbarObj -- or nil
-- tag here if we want
row:node(navbarObj):addClass(navbarObj and "navbox-title-with-navbar" or nil)
if has_navbar() and hlist_styles == '' then
hlist_styles = frame:extensionTag{
name = 'templatestyles', args = { src = cfg.hlist_templatestyles }
}
end
row:tag "span":addClass "navbox-title-content":wikitext(content)
else
-- hlist -> plainlist is best-effort to preserve old Common.css ordering.
row:wikitext(content)
-- this ordering is not a guarantee because most navboxes will emit only
-- one of these classes [hlist_note]
return hlist_styles .. plainlist_styles
end
row:newline()
return row
end
local function needsHorizontalLists(border)
if border == cfg.keyword.border_subgroup or args[cfg.arg.tracking] == cfg.keyword.tracking_no then
return false
end
return not has_list_class(cfg.pattern.hlist) and not has_list_class(cfg.pattern.plainlist)
end
local function p:hasBackgroundColors()
local data = self.data or '无法运行hasBackgroundColors函数,因为data字段不存在。'
for _, key in ipairs({cfg.arg.titlestyle, cfg.arg.groupstyle,
return mw.ustring.match(data.title and data.title.style or '', 'background')
cfg.arg.basestyle, cfg.arg.abovestyle, cfg.arg.belowstyle}) do
or mw.ustring.match(data.group and data.group.style or '', 'background')
if tostring(args[key]):find('background', 1, true) then
end
return true
end
end
return false
end
local function hasBordersp:argNameAndRealTitleAreDifferent()
local args = self.args
for _, key in ipairs({cfg.arg.groupstyle, cfg.arg.basestyle,
return args.name and args.name ~= mw.title.getCurrentTitle().text
cfg.arg.abovestyle, cfg.arg.belowstyle}) do
end
if tostring(args[key]):find('border', 1, true) then
return true
end
end
return false
end
local function isIllegible()
local styleratio = require('Module:Color contrast')._styleratio
for key, style in pairs(args) do
if tostring(key):match(cfg.pattern.style) then
if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
return true
end
end
end
return false
end
local function getTrackingCategories(border)
local cats = {}
if needsHorizontalLists(border) then table.insert(cats, cfg.category.horizontal_lists) end
if hasBackgroundColors() then table.insert(cats, cfg.category.background_colors) end
if isIllegible() then table.insert(cats, cfg.category.illegible) end
if hasBorders() then table.insert(cats, cfg.category.borders) end
return cats
end
local prefixes = {
local function renderTrackingCategories(builder, border)
group = true,
local title = mw.title.getCurrentTitle()
list = true,
if title.namespace ~= 10 then return end -- not in template space
title = true,
local subpage = title.subpageText
above = true,
if subpage == cfg.keyword.subpage_doc or subpage == cfg.keyword.subpage_sandbox
below = true,
or subpage == cfg.keyword.subpage_testcases then return end
body = true,
even = true,
odd = true,
id = true, abbr = true
}
local suffixes = {
for _, cat in ipairs(getTrackingCategories(border)) do
content = true,
builder:wikitext('[[Category:' .. cat .. ']]')
style = true,
end
class = true,
end
groupwidth = true,
[""] = true
}
--[[
local function renderMainTable(border, listnums)
检查这个键值对,并进行处理。
local tbl = mw.html.create('table')
符合特定条件的键,将被“转录”到data参数(或self.data中)。
:addClass(cfg.class.nowraplinks)
]]
:addClass(args[cfg.arg.bodyclass])
function p:processArg(k, v, data)
data = data or self.data
-- 以下均只检查字符串键。
local state = args[cfg.arg.state]
if type(k) ~= "string" then
if args[cfg.arg.title] and state ~= cfg.keyword.state_plain and state ~= cfg.keyword.state_off then
return
if state == cfg.keyword.state_collapsed then
end
state = cfg.class.collapsed
end
tbl
:addClass(cfg.class.collapsible)
:addClass(state or cfg.class.autocollapse)
end
-- 优先处理list开头的。这部分似乎不起作用,因为没有必要。
tbl:css('border-spacing', 0)
--[[local suffix = k:match "^list(%l+[%l%d%.%-]*)$"
if border == cfg.keyword.border_subgroup or border == cfg.keyword.border_none then
if suffix and not suffixes[suffix] then
tbl
data.list = data.list or {}
:addClass(cfg.class.navbox_subgroup)
self:processArg(suffix, v, data.list)
:cssText(args[cfg.arg.bodystyle])
return
:cssText(args[cfg.arg.style])
end]]--
else -- regular navbox - bodystyle and style will be applied to the wrapper table
tbl
:addClass(cfg.class.navbox_inner)
:css('background', 'transparent')
:css('color', 'inherit')
end
tbl:cssText(args[cfg.arg.innerstyle])
local suffix, prefix
renderTitleRow(tbl)
renderAboveRow(tbl)
--[[
local listnums_size = #listnums
检查固定的前缀是否存在直接搭配了固定的后缀的情况。例如:
for i, listnum in ipairs(listnums) do
bodyclass(prefix = body, suffix = class)
renderListRow(tbl, i, listnum, listnums_size)
titlestyle(prefix = title, suffix = title)
odd(prefix = odd, suffix = '')
若为:oddnothing(prefix = odd, suffix = nil),将在后面略过
]]
for localprefix, _ in pairs(prefixes) do
-- 检查通用属性
suffix = k:match("^" .. localprefix .. "(%l*)$")
-- 其他的值也有效,但是不起作用。
if suffix then
prefix = localprefix
break
end
-- 如果没有suffix进入下一轮循环
renderBelowRow(tbl)
return tbl
end
if prefix == 'body' then
local function add_navbox_styles(hiding_templatestyles)
-- 此时 suffix 不应该是空字符串或者'content',但是这里忽略了。
local frame = mw.getCurrentFrame()
data[suffix] = v
-- This is a lambda so that it doesn't need the frame as a parameter
elseif suffix == "" then
local function add_user_styles(templatestyles)
newindex(data, v, prefix, "content")
if not isblank(templatestyles) then
return frame:extensionTag{
elseif suffix and suffixes[suffix] then
name = 'templatestyles', args = { src = templatestyles }
-- 这里的suffix通常是style、class之类
}
newindex(data, v, prefix, suffix)
end
return ''
end
-- get templatestyles. load base from config so that Lua only needs to do
-- the work once of parser tag expansion
local base_templatestyles = cfg.templatestyles
local templatestyles = add_user_styles(args[cfg.arg.templatestyles])
local child_templatestyles = add_user_styles(args[cfg.arg.child_templatestyles])
-- The 'navbox-styles' div exists to wrap the styles to work around T200206
-- more elegantly. Instead of combinatorial rules, this ends up being linear
-- number of CSS rules.
return mw.html.create('div')
:addClass(cfg.class.navbox_styles)
:wikitext(
add_list_styles() .. -- see [hlist_note] applied to 'before base_templatestyles'
base_templatestyles ..
templatestyles ..
child_templatestyles ..
table.concat(hiding_templatestyles)
)
:done()
end
--[[
-- work around [[phab:T303378]]
检查带有数字的变量。在这个过程中,任何prefix和suffix都有可能被匹配到。
-- for each arg: find all the templatestyles strip markers, insert them into a
]]
-- table. then remove all templatestyles markers from the arg
local prefix, key, suffix = k:match "^(%l+)([0-9%.%-]+)(%l*)$"
local strip_marker_pattern = '(\127[^\127]*UNIQ%-%-templatestyles%-%x+%-QINU[^\127]*\127)'
local argHash = 0
if not prefixes[prefix] then
for k, arg in pairs(args) do
return -- 忽略不被识别的前缀
if type(arg) == 'string' then
for marker in string.gfind(arg, strip_marker_pattern) do
table.insert(hiding_templatestyles, marker)
end
argHash = argHash + #arg
args[k] = string.gsub(arg, strip_marker_pattern, '')
end
end
-- 对于group和list,以及其他的类型,采取不同的数据加工方式
if not args.argHash then args.argHash = argHash end
local isCell = (prefix == "group" or prefix == "list")
local listnums = {}
-- 这里的prefix可以是group,list
-- 这里的suffix可以是空白、class或style
for k, _ in pairs(args) do
-- 这里的key可以是1、2、3或1-2、1-4这样的数字或多重数字。
if type(k) == 'string' then
if not suffix or not suffixes[suffix] then
local listnum = k:match(cfg.pattern.listnum)
key, suffix = k:match "^list([%d%.%-]+)(%l+[%l%d%-%.]*)$"
if listnum and args[andnum('list', tonumber(listnum))] then
table.insert(listnums, tonumber(listnum))
end
end
end
table.sort(listnums)
if not key then return end
if suffix == "" then suffix = "content" end
local border = mw.text.trim(args[cfg.arg.border] or args[1] or '')
if border == cfg.keyword.border_child then
local keys = getkeys(key)
border = cfg.keyword.border_subgroup
if not keys then return end
end
if not prefix then
-- render the main body of the navbox
self:processArg(suffix, v, newindex(data, {}, unpack(getkeys(key, "list", "content"))))
local tbl = renderMainTable(border, listnums)
elseif (prefix == 'id' or prefix == 'abbr') and suffix == 'content' then
newindex(data, v, unpack(getkeys(key, 'list', 'id')))
local res = mw.html.create()
elseif isCell then
-- render the appropriate wrapper for the navbox, based on the border param
newindex(data, v, unpack(getkeys(key, prefix, suffix)))
if border == cfg.keyword.border_none then
res:node(add_navbox_styles(hiding_templatestyles))
local nav = res:tag('div')
:attr('role', 'navigation')
:node(tbl)
-- aria-labelledby title, otherwise above, otherwise lone group
if args[cfg.arg.title] or args[cfg.arg.above] or (args[cfg.arg.group1]
and not args[cfg.arg.group2]) then
nav:attr(
'aria-labelledby',
mw.uri.anchorEncode(
args[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group1]
) .. args.argHash
)
else
nav:attr('aria-label', cfg.aria_label .. args.argHash)
end
elseif border == cfg.keyword.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
newindex(data, v, unpack(getkeys(key, "list", "content", prefix, suffix)))
res:node(add_navbox_styles(hiding_templatestyles))
local nav = res:tag('div')
:attr('role', 'navigation')
:addClass(cfg.class.navbox)
:addClass(args[cfg.arg.navboxclass])
:cssText(args[cfg.arg.bodystyle])
:cssText(args[cfg.arg.style])
:css('padding', '3px')
:node(tbl)
-- aria-labelledby title, otherwise above, otherwise lone group
if args[cfg.arg.title] or args[cfg.arg.above]
or (args[cfg.arg.group1] and not args[cfg.arg.group2]) then
nav:attr(
'aria-labelledby',
mw.uri.anchorEncode(
args[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group1]
) .. args.argHash
)
else
nav:attr('aria-label', cfg.aria_label .. args.argHash)
end
end
end
function p:processArgs()
if (args[cfg.arg.nocat] or cfg.keyword.nocat_false):lower() == cfg.keyword.nocat_false then
-- 这里的args是frame中未经重写处理的args。
renderTrackingCategories(res, border)
-- 转录参数时,参数遍历两遍。
end
-- 这是为了防止普通参数占了data参数的位置导致不能newindex。
return striped(tostring(res), border)
end --p._navbox
-- 先处理一些已知名称的参数,这些参数键的哈希值会提前编译,这样可以更快地
function p._withCollapsibleGroups(pargs)
-- 被访问,无需走p:processArg的流程。
-- table for args passed to navbox
local targs = {}
local args = self.args
local data = self.data
-- process args
local passthroughLocal = {
data.name = args.name or data.name
[cfg.arg.bodystyle] = true,
data.state = args.state or data.state
[cfg.arg.border] = true,
data.isChild = data.isChild
[cfg.arg.style] = true,
or (args[1] or args.border) == 'subgroup'
}
or (args[1] or args.border) == 'child'
for k,v in pairs(pargs) do
if k and type(k) == 'string' then
data.nocat = boolean(args.nocat) or data.nocat
if passthrough[k] or passthroughLocal[k] then
data.isGroups = boolean(args.isGroups) or data.isGroups
targs[k] = v
elseif (k:match(cfg.pattern.num)) then
data.selected = data.selected or {}
local n = k:match(cfg.pattern.num)
local list_and_numselected = andnum('list', n)data.selected
if type(args.selected) == 'string' then
if ((k:match(cfg.pattern.listnum) or k:match(cfg.pattern.contentnum))
for a_selected in mw.text.gsplit(args.selected, '[,;]%s*') do
and targs[list_and_num] == nil
selected[tonumber(a_selected) or a_selected] = true
and pargs[andnum('group', n)] == nil
and pargs[andnum('sect', n)] == nil
and pargs[andnum('section', n)] == nil) then
targs[list_and_num] = concatstrings({
pargs[list_and_num] or '',
pargs[andnum('content', n)] or ''
})
if (targs[list_and_num] and inArray(cfg.keyword.subgroups, targs[list_and_num])) then
targs[list_and_num] = getSubgroup(pargs, n, targs[list_and_num])
end
elseif ((k:match(cfg.pattern.groupnum) or k:match(cfg.pattern.sectnum) or k:match(cfg.pattern.sectionnum))
and targs[list_and_num] == nil) then
local titlestyle = concatstyles({
pargs[cfg.arg.groupstyle] or '',
pargs[cfg.arg.secttitlestyle] or '',
pargs[andnum('groupstyle', n)] or '',
pargs[andnum('sectiontitlestyle', n)] or ''
})
local liststyle = concatstyles({
pargs[cfg.arg.liststyle] or '',
pargs[cfg.arg.contentstyle] or '',
pargs[andnum('liststyle', n)] or '',
pargs[andnum('contentstyle', n)] or ''
})
local title = concatstrings({
pargs[andnum('group', n)] or '',
pargs[andnum('sect', n)] or '',
pargs[andnum('section', n)] or ''
})
local list = concatstrings({
pargs[list_and_num] or '',
pargs[andnum('content', n)] or ''
})
if list and inArray(cfg.keyword.subgroups, list) then
list = getSubgroup(pargs, n, list)
end
local abbr_and_num = andnum('abbr', n)
local state = (pargs[abbr_and_num] and pargs[abbr_and_num] == pargs[cfg.arg.selected])
and cfg.keyword.state_uncollapsed
or (pargs[andnum('state', n)] or cfg.keyword.state_collapsed)
targs[list_and_num] =p._navbox({
cfg.keyword.border_child,
[cfg.arg.navbar] = cfg.keyword.navbar_plain,
[cfg.arg.state] = state,
[cfg.arg.basestyle] = pargs[cfg.arg.basestyle],
[cfg.arg.title] = title,
[cfg.arg.titlestyle] = titlestyle,
[andnum('list', 1)] = list,
[cfg.arg.liststyle] = liststyle,
[cfg.arg.listclass] = pargs[andnum('listclass', n)],
[cfg.arg.image] = pargs[andnum('image', n)],
[cfg.arg.imageleft] = pargs[andnum('imageleft', n)],
[cfg.arg.listpadding] = pargs[cfg.arg.listpadding],
argHash = pargs.argHash
})
end
end
end
end
-- ordering of style and bodystyle
targs[cfg.arg.style] = concatstyles({targs[cfg.arg.style] or '', targs[cfg.arg.bodystyle] or ''})
targs[cfg.arg.bodystyle] = nil
data.style = args.style or data.style
-- child or subgroup
data.class = args.class or data.class
if targs[cfg.arg.border] == nil then targs[cfg.arg.border] = pargs[1] end
data.groupwidth = args.groupwidth or data.groupwidth
return p._navbox(targs)
for k, v in pairs(args) do
end --p._withCollapsibleGroups
v = trim(v)
if v and v ~= "" then
function p._withColumns(pargs)
self:processArg(k, v, data)
-- table for args passed to navbox
local targs = {}
-- tables of column numbers
local colheadernums = {}
local colnums = {}
local colfooternums = {}
-- process args
local passthroughLocal = {
[cfg.arg.evenstyle]=true,
[cfg.arg.groupstyle]=true,
[cfg.arg.liststyle]=true,
[cfg.arg.oddstyle]=true,
[cfg.arg.state]=true,
}
for k,v in pairs(pargs) do
if passthrough[k] or passthroughLocal[k] then
targs[k] = v
elseif type(k) == 'string' then
if k:match(cfg.pattern.listnum) then
local n = k:match(cfg.pattern.listnum)
targs[andnum('liststyle', n + 2)] = pargs[andnum('liststyle', n)]
targs[andnum('group', n + 2)] = pargs[andnum('group', n)]
targs[andnum('groupstyle', n + 2)] = pargs[andnum('groupstyle', n)]
if v and inArray(cfg.keyword.subgroups, v) then
targs[andnum('list', n + 2)] = getSubgroup(pargs, n, v)
else
targs[andnum('list', n + 2)] = v
end
elseif (k:match(cfg.pattern.colheadernum) and v ~= '') then
table.insert(colheadernums, tonumber(k:match(cfg.pattern.colheadernum)))
elseif (k:match(cfg.pattern.colnum) and v ~= '') then
table.insert(colnums, tonumber(k:match(cfg.pattern.colnum)))
elseif (k:match(cfg.pattern.colfooternum) and v ~= '') then
table.insert(colfooternums, tonumber(k:match(cfg.pattern.colfooternum)))
end
end
end
return self
table.sort(colheadernums)
end
table.sort(colnums)
table.sort(colfooternums)
--[[
-- HTML table for list1
用于在控制台测试参数的转换过程。
local coltable = mw.html.create( 'table' ):addClass('navbox-columns-table')
注意这是个静态方法。
local row, col
]]
function p.test(args, params)
params = params or {}
assert(type(args)=='table', 'args should be table')
assert(type(params)=='table', 'params should be nil or table')
params.args = args
local obj = p.new(params)
obj:processArgs()
mw.logObject(obj.data, 'data')
return obj:render()
end
--[[
local tablestyle = ( (#colheadernums > 0) or (not isblank(pargs[cfg.arg.fullwidth])) )
类似于p.test的一种更快的测试方式。
and 'width:100%'
例如,
or 'width:auto; margin-left:auto; margin-right:auto'
p.test2('list1-2', 'list1-3')
等价于
coltable:cssText(concatstyles({
p.test{['list1-2'] = 'list1-2', ['list1-3'] = 'list1-3'}
'border-spacing: 0px; text-align:left',
]]
tablestyle,
function p.test2(...)
pargs[cfg.arg.coltablestyle] or ''
local args = {}
}))
local list = {...}
for _, v in ipairs(list) do
--- Header row ---
args[v] = v
if (#colheadernums > 0) then
row = coltable:tag('tr')
for k, n in ipairs(colheadernums) do
col = row:tag('th'):addClass('navbox-abovebelow')
col:cssText(concatstyles({
(k > 1) and 'border-left:2px solid #fdfdfd' or '',
'font-weight:bold',
pargs[cfg.arg.colheaderstyle] or '',
pargs[andnum('colheaderstyle', n)] or ''
}))
col:attr('colspan', tonumber(pargs[andnum('colheadercolspan', n)]))
col:wikitext(pargs[andnum('colheader', n)])
end
end
return p.test(args)
end
function p:render()
--- Main columns ---
local data = self.data or {}
row = coltable:tag('tr'):css('vertical-align', 'top')
-- 如果是通过args而非data创建的对象,
for k, n in ipairs(colnums) do
-- 渲染之前务必记得processArgs,以将args“转录”到data中。
if k == 1 and isblank(pargs[andnum('colheader', 1)])
-- 因为渲染过程只认data不认args。
and isblank(pargs[andnum('colfooter', 1)])
self.root = self.root
and isblank(pargs[cfg.arg.fullwidth]) then
or mw.html.create "div":addClass "navbox"
local nopad = inArray(
local root = self.root
{'off', '0', '0em', '0px'},
mw.ustring.gsub(pargs[cfg.arg.padding] or '', '[;%%]', ''))
local navbarObj
if not nopad then
row:tag('td'):wikitext(' ')
local level = self.level or 0
:css('width', (pargs[cfg.arg.padding] or '5em'))
local state = data.state
end
root
:addClass("navbox-level")
:addClass("navbox-level-" .. (level or "unknown"))
-- navbox主体的类,可能是args.bodyclass或args.class
:addClass(data.class)
-- navbox主体的样式,可能是args.bodystyle或args.style
:cssText(data.style)
do
local groupwidth = data.groupwidth
if groupwidth then
root:css('grid-template-columns', tostring(groupwidth)..' auto')
end
col = row:tag('td'):addClass('navbox-list')
col:cssText(concatstyles({
(k > 1) and 'border-left:2px solid #fdfdfd' or '',
'padding:0px',
pargs[cfg.arg.colstyle] or '',
((n%2 == 0) and pargs[cfg.arg.evencolstyle] or pargs[cfg.arg.oddcolstyle]) or '',
pargs[andnum('colstyle', n)] or '',
'width:' .. (pargs[andnum('colwidth', n)] or pargs[cfg.arg.colwidth] or '10em')
}))
local wt = pargs[andnum('col', n)]
if wt and inArray(cfg.keyword.subgroups, wt) then
wt = getSubgroup(pargs, n, wt, cfg.arg.col_and_num)
end
col:tag('div'):newline():wikitext(wt):newline()
end
root:addClass(
--- Footer row ---
state == "collapsed" and "collapsible collapsed"
if (#colfooternums > 0) then
or state == "plain" and ""
row = coltable:tag('tr')
or state == "collapsible" and "collapsible"
for k, n in ipairs(colfooternums) do
col = row:tag('td'):addClass('navbox-abovebelow')
-- 若state未指定或为其他值,且该表不是子框表,则默认为collapsible
col:cssText(concatstyles({
or (level == 0 and not data.isChild) and "collapsible"
(k > 1) and 'border-left:2px solid #fdfdfd' or '',
or nil
'font-weight:bold',
)
pargs[cfg.arg.colfooterstyle] or '',
pargs[andnum('colfooterstyle', n)] or ''
-- 为表格添加模板样式。如果frame不存在,则不添加表格样式。
}))
if level == 0 and self.frame and self.frame.getParent then
col:attr('colspan', tonumber(pargs[andnum('colfootercolspan', n)]))
root:addClass "hlist"
col:wikitext(pargs[andnum('colfooter', n)])
local name = data.name
if name then
navbarObj =
navbar {
mini = 1,
name
}
end
end
-- 渲染标题。
-- assign table to list1
self:renderSingleRow {
targs[andnum('list', 1)] = tostring(coltable)
navbarObj = navbarObj,
if isblank(pargs[andnum('colheader', 1)])
content = index(data, "title", "content"),
and isblank(pargs[andnum('col', 1)])
class = index(data, "title", "class"),
and isblank(pargs[andnum('colfooter', 1)]) then
style = index(data, "title", "style"),
targs[andnum('list', 1)] = targs[andnum('list', 1)] ..
rowtype = "title",
cfg.category.without_first_col
level = level
end
}
-- 渲染上方框。
-- Other parameters
self:renderSingleRow {
targs[cfg.arg.border] = pargs[cfg.arg.border] or pargs[1]
content = index(data, "above", "content"),
targs[cfg.arg.evenodd] = (not isblank(pargs[cfg.arg.evenodd])) and pargs[cfg.arg.evenodd] or nil
class = index(data, "above", "class"),
targs[cfg.arg.list1padding] = '0px'
style = index(data, "above", "style"),
targs[andnum('liststyle', 1)] = 'background:transparent;color:inherit;'
rowtype = "above",
targs[cfg.arg.style] = concatstyles({pargs[cfg.arg.style], pargs[cfg.arg.bodystyle]})
level = level
targs[cfg.arg.tracking] = 'no'
}
return p._navbox(targs)
-- 渲染列表。这是重头戏。
end --p._withColumns
local isGroups = self.data.groups
for k, v in tools.extendedSparseIpairs(data) do
local groupContent = index(v, "group", "content")
local listContent = index(v, "list", "content")
local groupClass = index(v, "group", "class")
local groupStyle = index(v, "group", "style")
local listClass = index(v, "list", "class")
local listStyle = index(v, "list", "style")
local listGroupWidth = index(v, 'list', 'groupwidth')
self:renderRow(
-- Template entry points
index(v, 'group') or {},
function p.navbox (frame, boxtype)
index(v, 'list') or {}, k
local function readArgs(args, prefix)
)
local function readSubgroups(element, i)
if inArray(cfg.keyword.subgroups, args[prefix .. andnum(element, i)]) then
for _, v in ipairs(cfg.arg.subgroups_and_num) do
readArgs(args, prefix .. string.format(v, i) .. "_")
end
readArgs(args, prefix .. andnum('col', i) .. "_")
end
end
-- Read the arguments in the order they'll be output in, to make references
-- number in the right order.
local _
_ = args[prefix .. cfg.arg.title]
_ = args[prefix .. cfg.arg.above]
-- Limit this to 20 as covering 'most' cases (that's a SWAG) and because
-- iterator approach won't work here
local boxtype = args.type or cfg.keyword[boxtype]
if boxtype == cfg.keyword.with_columns then
for i = 1, 20 do
_ = args[prefix .. andnum('colheader', i)]
end
for i = 1, 20 do
readSubgroups('col', i)
end
for i = 1, 20 do
_ = args[prefix .. andnum('colfooter', i)]
end
end
for i = 1, 20 do
_ = args[prefix .. andnum('group', i)]
readSubgroups('list', i)
end
_ = args[prefix .. cfg.arg.below]
end
-- 渲染下方框。
if not getArgs then
self:renderSingleRow {
getArgs = require('Module:Arguments').getArgs
content = index(data, "below", "content"),
class = index(data, "below", "class"),
style = index(data, "below", "style"),
rowtype = "below"
}
if self.data.nocat then
if self:hasBackgroundColors() then root:wikitext('[[Category:使用背景颜色的导航框]]') end
if self:argNameAndRealTitleAreDifferent() then root:wikitext('[[Category:name參數和實際不同的導航框]]') end
end
return root:allDone()
local args = getArgs(frame, {wrappers = {cfg.pattern[boxtype or 'navbox']}})
readArgs(args, "")
args.argHash = nil -- we shouldn't accept argHash passed from a template
args.type = args.type or cfg.keyword[boxtype]
return p['_navbox'](args)
end
function p._navbox(args, frame)
p[cfg.keyword.with_collapsible_groups] = function (frame)
-- 通常第三方模块可以不必这样使用
return p.navbox(frame, 'with_collapsible_groups')
-- 可以设置data然后再render
local obj =
p.new {
args = args,
frame = frame
}
obj:processArgs()
return obj:render()
end
function p.navbox(frame)
p[cfg.keyword.with_columns] = function (frame)
-- 通过#invoke直接使用
return p.navbox(frame, 'with_columns')
local getArgs = require 'Module:Arguments'.getArgs
return p._navbox(getArgs(frame), frame)
end
function p.subgroup(frame)
local getArgs = require 'Module:Arguments'.getArgs
local args = getArgs(frame)
local obj = p.new {
args = args,
frame = frame,
data = {isChild = true}
}
return obj:processArgs():render()
end
function p.groups(frame)
local getArgs = require 'Module:Arguments'.getArgs
local args = getArgs(frame)
local obj = p.new {
args = args,
frame = frame,
data = {isGroups = true, state = 'plain'}
}
return obj:processArgs():render()
end
p.main = p.navbox
return p
|