可在模組:Navbox/doc建立此模組的說明文件

require('strict')local p = {}local navbar = require('Module:Navbar')._navbarlocal cfg = mw.loadData('Module:Navbox/configuration')local getArgs -- lazily initializedlocal argslocal format = string.formatlocal function striped(wikitext, border)-- 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 = cfg.category.orphanif border == cfg.keyword.border_subgroup and args[cfg.arg.orphan] ~= cfg.keyword.orphan_yes then-- No change; striping occurs in outermost navbox.return wikitext .. orphanCatendlocal first, second = cfg.class.navbox_odd_part, cfg.class.navbox_even_partif args[cfg.arg.evenodd] thenif args[cfg.arg.evenodd] == cfg.keyword.evenodd_swap thenfirst, second = second, firstelsefirst = args[cfg.arg.evenodd]second = firstendendlocal changerif first == second thenchanger = firstelselocal index = 0changer = 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 = 0return firstendindex = index + 1return index % 2 == 1 and first or secondendendlocal regex = orphanCat:gsub('([%[%]])', '%%%1')return (wikitext:gsub(regex, ''):gsub(cfg.marker.regex, changer)) -- () omits gsub countendlocal 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'endif nowrapitems == cfg.keyword.nowrapitems_yes thenlocal lines = {}for line in (item .. '\n'):gmatch('([^\n]*)\n') dolocal prefix, content = line:match('^([*:;#]+)%s*(.*)')if prefix and not content:match(cfg.pattern.nowrap) thenline = format(cfg.nowrap_item, prefix, content)endtable.insert(lines, line)enditem = table.concat(lines, '\n')endif item:match('^[*:;#]') thenreturn '\n' .. item ..'\n'endreturn itemendlocal function has_navbar()return args[cfg.arg.navbar] ~= cfg.keyword.navbar_offand args[cfg.arg.navbar] ~= cfg.keyword.navbar_plainand (args[cfg.arg.name]or mw.getCurrentFrame():getParent():getTitle():gsub(cfg.pattern.sandbox, '')~= cfg.pattern.navbox)end-- extract text color from css, which is the only permitted inline CSS for the navbarlocal function extract_color(css_str)-- return nil because navbar takes its argument into mw.html which handles-- nil gracefully, removing the associated style attributereturn mw.ustring.match(';' .. css_str .. ';', '.*;%s*([Cc][Oo][Ll][Oo][Rr]%s*:%s*.-)%s*;') or nilendlocal function renderNavBar(titleCell)if has_navbar() thentitleCell:wikitext(navbar{[cfg.navbar.name] = args[cfg.arg.name],[cfg.navbar.mini] = 1,[cfg.navbar.fontstyle] = extract_color((args[cfg.arg.basestyle] or '') .. ';' .. (args[cfg.arg.titlestyle] or ''))})endendlocal function renderTitleRow(tbl)if not args[cfg.arg.title] then return endlocal titleRow = tbl:tag('tr')local titleCell = titleRow:tag('th'):attr('scope', 'col')local titleColspan = 2if args[cfg.arg.imageleft] then titleColspan = titleColspan + 1 endif args[cfg.arg.image] then titleColspan = titleColspan + 1 endtitleCell: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])):addClass(args[cfg.arg.titleclass]):css('font-size', '114%'):css('margin', '0 4em'):wikitext(processItem(args[cfg.arg.title]))endlocal function getAboveBelowColspan()local ret = 2if args[cfg.arg.imageleft] then ret = ret + 1 endif args[cfg.arg.image] then ret = ret + 1 endreturn retendlocal function renderAboveRow(tbl)if not args[cfg.arg.above] then return endtbl: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]) or nil):wikitext(processItem(args[cfg.arg.above], args[cfg.arg.nowrapitems]))endlocal function renderBelowRow(tbl)if not args[cfg.arg.below] then return endtbl:tag('tr'):tag('td'):addClass(cfg.class.navbox_abovebelow):addClass(args[cfg.arg.belowclass]):cssText(args[cfg.arg.basestyle]):cssText(args[cfg.arg.belowstyle]):attr('colspan', getAboveBelowColspan()):tag('div'):wikitext(processItem(args[cfg.arg.below], args[cfg.arg.nowrapitems]))endlocal function renderListRow(tbl, index, listnum, listnums_size)local row = tbl:tag('tr')if index == 1 and args[cfg.arg.imageleft] thenrow:tag('td'):addClass(cfg.class.noviewer):addClass(cfg.class.navbox_image):addClass(args[cfg.arg.imageclass]):css('width', '1px')               -- Minimize width:css('padding', '0 2px 0 0'):cssText(args[cfg.arg.imageleftstyle]):attr('rowspan', listnums_size):tag('div'):wikitext(processItem(args[cfg.arg.imageleft]))endlocal group_and_num = format(cfg.arg.group_and_num, listnum)local groupstyle_and_num = format(cfg.arg.groupstyle_and_num, listnum)if args[group_and_num] thenlocal groupCell = row:tag('th')-- id for aria-labelledby attribute, if lone group with no title or aboveif listnum == 1 and not (args[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group2]) thengroupCell:attr('id', mw.uri.anchorEncode(args[cfg.arg.group1]))endgroupCell: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])endlocal listCell = row:tag('td')if args[group_and_num] thenlistCell:addClass(cfg.class.navbox_list_with_group)elselistCell:attr('colspan', 2)endif not args[cfg.arg.groupwidth] thenlistCell:css('width', '100%')endlocal rowstyle  -- usually nil so cssText(rowstyle) usually adds nothingif index % 2 == 1 thenrowstyle = args[cfg.arg.oddstyle]elserowstyle = args[cfg.arg.evenstyle]endlocal list_and_num = format(cfg.arg.list_and_num, listnum)local listText = args[list_and_num]local oddEven = cfg.marker.oddevenif 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_partendlocal liststyle_and_num = format(cfg.arg.liststyle_and_num, listnum)local listclass_and_num = format(cfg.arg.listclass_and_num, 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] thenrow: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]))endendlocal function has_list_class(htmlclass)local patterns = {'^' .. htmlclass .. '$','%s' .. htmlclass .. '$','^' .. htmlclass .. '%s','%s' .. htmlclass .. '%s'}for arg, _ in pairs(args) doif type(arg) == 'string' and mw.ustring.find(arg, cfg.pattern.class) thenfor _, pattern in ipairs(patterns) doif mw.ustring.find(args[arg] or '', pattern) thenreturn trueendendendendreturn falseend-- there are a lot of list classes in the wild, so we add their TemplateStyleslocal function add_list_styles()local frame = mw.getCurrentFrame()local function add_list_templatestyles(htmlclass, templatestyles)if has_list_class(htmlclass) thenreturn frame:extensionTag{name = 'templatestyles', args = { src = templatestyles }}elsereturn ''endendlocal hlist_styles = add_list_templatestyles('hlist', cfg.hlist_templatestyles)local plainlist_styles = add_list_templatestyles('plainlist', cfg.plainlist_templatestyles)-- a second workaround for [[phab:T303378]]-- when that issue is fixed, we can actually use has_navbar not to emit the-- tag here if we wantif has_navbar() and hlist_styles == '' thenhlist_styles = frame:extensionTag{name = 'templatestyles', args = { src = cfg.hlist_templatestyles }}end-- hlist -> plainlist is best-effort to preserve old Common.css ordering.-- this ordering is not a guarantee because most navboxes will emit only-- one of these classes [hlist_note]return hlist_styles .. plainlist_stylesendlocal function needsHorizontalLists(border)if border == cfg.keyword.border_subgroup or args[cfg.arg.tracking] == cfg.keyword.tracking_no thenreturn falseendreturn not has_list_class(cfg.pattern.hlist) and not has_list_class(cfg.pattern.plainlist)endlocal function hasBackgroundColors()for _, key in ipairs({cfg.arg.titlestyle, cfg.arg.groupstyle,cfg.arg.basestyle, cfg.arg.abovestyle, cfg.arg.belowstyle}) doif tostring(args[key]):find('background', 1, true) thenreturn trueendendreturn falseendlocal function hasBorders()for _, key in ipairs({cfg.arg.groupstyle, cfg.arg.basestyle,cfg.arg.abovestyle, cfg.arg.belowstyle}) doif tostring(args[key]):find('border', 1, true) thenreturn trueendendreturn falseendlocal function isIllegible()local styleratio = require('Module:Color contrast')._styleratiofor key, style in pairs(args) doif tostring(key):match(cfg.pattern.style) thenif styleratio{mw.text.unstripNoWiki(style)} < 4.5 thenreturn trueendendendreturn falseendlocal function getTrackingCategories(border)local cats = {}if needsHorizontalLists(border) then table.insert(cats, cfg.category.horizontal_lists) endif hasBackgroundColors() then table.insert(cats, cfg.category.background_colors) endif isIllegible() then table.insert(cats, cfg.category.illegible) endif hasBorders() then table.insert(cats, cfg.category.borders) endreturn catsendlocal function renderTrackingCategories(builder, border)local title = mw.title.getCurrentTitle()if title.namespace ~= 10 then return end -- not in template spacelocal subpage = title.subpageTextif subpage == cfg.keyword.subpage_doc or subpage == cfg.keyword.subpage_sandboxor subpage == cfg.keyword.subpage_testcases then return endfor _, cat in ipairs(getTrackingCategories(border)) dobuilder:wikitext('[[Category:' .. cat .. ']]')endendlocal function renderMainTable(border, listnums)local tbl = mw.html.create('table'):addClass(cfg.class.nowraplinks):addClass(args[cfg.arg.bodyclass])local state = args[cfg.arg.state]if args[cfg.arg.title] and state ~= cfg.keyword.state_plain and state ~= cfg.keyword.state_off thenif state == cfg.keyword.state_collapsed thenstate = cfg.class.collapsedendtbl:addClass(cfg.class.collapsible):addClass(state or cfg.class.autocollapse)endtbl:css('border-spacing', 0)if border == cfg.keyword.border_subgroup or border == cfg.keyword.border_none thentbl:addClass(cfg.class.navbox_subgroup):cssText(args[cfg.arg.bodystyle]):cssText(args[cfg.arg.style])else  -- regular navbox - bodystyle and style will be applied to the wrapper tabletbl:addClass(cfg.class.navbox_inner):css('background', 'transparent'):css('color', 'inherit')endtbl:cssText(args[cfg.arg.innerstyle])renderTitleRow(tbl)renderAboveRow(tbl)local listnums_size = #listnumsfor i, listnum in ipairs(listnums) dorenderListRow(tbl, i, listnum, listnums_size)endrenderBelowRow(tbl)return tblendlocal function add_navbox_styles(hiding_templatestyles)local frame = mw.getCurrentFrame()-- This is a lambda so that it doesn't need the frame as a parameterlocal function add_user_styles(templatestyles)if templatestyles and templatestyles ~= '' thenreturn frame:extensionTag{name = 'templatestyles', args = { src = templatestyles }}endreturn ''end-- get templatestyles. load base from config so that Lua only needs to do-- the work once of parser tag expansionlocal base_templatestyles = cfg.templatestyleslocal 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]]-- for each arg: find all the templatestyles strip markers, insert them into a-- table. then remove all templatestyles markers from the arglocal function move_hiding_templatestyles(args)local gfind = string.gfindlocal gsub = string.gsublocal templatestyles_markers = {}local strip_marker_pattern = '(\127[^\127]*UNIQ%-%-templatestyles%-%x+%-QINU[^\127]*\127)'for k, arg in pairs(args) dofor marker in gfind(arg, strip_marker_pattern) dotable.insert(templatestyles_markers, marker)endargs[k] = gsub(arg, strip_marker_pattern, '')endreturn templatestyles_markersendfunction p._navbox(navboxArgs)args = navboxArgslocal hiding_templatestyles = move_hiding_templatestyles(args)local listnums = {}for k, _ in pairs(args) doif type(k) == 'string' thenlocal listnum = k:match(cfg.pattern.listnum)if listnum then table.insert(listnums, tonumber(listnum)) endendendtable.sort(listnums)local border = mw.text.trim(args[cfg.arg.border] or args[1] or '')if border == cfg.keyword.border_child thenborder = cfg.keyword.border_subgroupend-- render the main body of the navboxlocal tbl = renderMainTable(border, listnums)local res = mw.html.create()-- render the appropriate wrapper for the navbox, based on the border paramif border == cfg.keyword.border_none thenres:node(add_navbox_styles(hiding_templatestyles))local nav = res:tag('div'):attr('role', 'navigation'):node(tbl)-- aria-labelledby title, otherwise above, otherwise lone groupif args[cfg.arg.title] or args[cfg.arg.above] or (args[cfg.arg.group1]and not args[cfg.arg.group2]) thennav:attr('aria-labelledby',mw.uri.anchorEncode(args[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group1]))elsenav:attr('aria-label', cfg.aria_label)endelseif 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>')elseres: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 groupif args[cfg.arg.title] or args[cfg.arg.above]or (args[cfg.arg.group1] and not args[cfg.arg.group2]) thennav:attr('aria-labelledby',mw.uri.anchorEncode(args[cfg.arg.title] or args[cfg.arg.above] or args[cfg.arg.group1]))elsenav:attr('aria-label', cfg.aria_label)endendif (args[cfg.arg.nocat] or cfg.keyword.nocat_false):lower() == cfg.keyword.nocat_false thenrenderTrackingCategories(res, border)endreturn striped(tostring(res), border)endfunction p.navbox(frame)if not getArgs thengetArgs = require('Module:Arguments').getArgsendargs = getArgs(frame, {wrappers = {cfg.pattern.navbox}})-- Read the arguments in the order they'll be output in, to make references-- number in the right order.local __ = args[cfg.arg.title]_ = args[cfg.arg.above]-- Limit this to 20 as covering 'most' cases (that's a SWAG) and because-- iterator approach won't work herefor i = 1, 20 do_ = args[format(cfg.arg.group_and_num, i)]_ = args[format(cfg.arg.list_and_num, i)]end_ = args[cfg.arg.below]return p._navbox(args)endreturn p