Відмінності між версіями «Модуль:Navbox»

Матеріал з Вікіпедія ЄСІТС
Перейти до навігації Перейти до пошуку
(Створена сторінка: -------------------------------------------------------------------- --<pre> Navbox Module -- -- * Fully CSS styled (inline styles possible but not default) --...)
 
м
Рядок 1: Рядок 1:
--------------------------------------------------------------------
--<pre> Navbox Module
--
--
-- * Fully CSS styled (inline styles possible but not default)
-- Реализует {{Навигационная таблица}} и {{Подгруппы навигационной таблицы}}.
-- * Supports unlimited rows
-- Основной объём кода заимствован из английского Module:Navbox.
--
--
-- By User:Tjcool007 from layton.fandom.com
 
--------------------------------------------------------------------
local p = {}
local p = {}
 
local args = {} -- Arguments passed to template
local getArgs -- lazily initialized
local navbox -- Actual navbox
local yesno -- lazily initialized
 
--local working = {}
local args
local rownums, skiprows = {}, {}
local border
local hasrows, alt, hasData, isChild = false, false, false, false
local listnums = {}
local activeSection, sections, cimage, cimageleft
local ODD_EVEN_MARKER = '\127_ODDEVEN_\127'
local colspan, rowspan
local RESTART_MARKER = '\127_ODDEVEN0_\127'
local REGEX_MARKER = '\127_ODDEVEN(%d?)_\127'
local showText, hideText = 'Show', 'Hide'
 
local maintitle
local langCode = mw.getContentLanguage():getCode()
local name
local localization = {} --localized strings table
local navigation
localization['en'] = {show = 'Show', hide = 'Hide'}
local navbar
localization['ru'] = {show = 'показать', hide = 'скрыть'}
local above
localization['zh'] = {show = '显示', hide = '隐藏'}
local image
if localization[langCode] then
local below
    showText = localization[langCode]['show']
 
    hideText = localization[langCode]['hide']
local titlestyle
end
local groupstyle
local bodystyle
------------------------------------------------
local basestyle
-- Title
local liststyle
------------------------------------------------
local evenodd_VARIABLE
local abovestyle
--- Processes the VDE links in the title
local belowstyle
--
local imageleft
-- @param titlecell The table cell of the title
local imageleftstyle
local function processVde( titlecell )
local style
if not args.template then return end
 
local groupwidth
titlecell:wikitext('<span class="navbox-vde">'
local listpadding
.. mw.getCurrentFrame():expandTemplate({
 
title = 'vdelinks',
local bodyclass
args = { args.template, ['type'] = 'navbox' }
local titleclass
}) .. '</span>')
local aboveclass
end
local belowclass
local groupclass
--- Processes the main title row
local listclass
local function processTitle()
local imageclass
local titlerow = mw.html.create('tr'):addClass('navbox-title')
 
local titlecell = mw.html.create('th'):attr('colspan',colspan):attr('scope','col')
local function striped(wikitext)
-- Return wikitext with markers replaced for odd/even striping.
if not pcall( processVde, titlecell ) then
-- Child (subgroup) navboxes are flagged with a category that is removed
titlecell:wikitext( '<b class="navbox-vde error" title="Missing Template:Vdelinks">!!!</b>' )
-- 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 = '[[Категория:Навигационные шаблоны без родителя]]'
if border == 'subgroup' and args.orphan ~= 'yes' then
-- No change; striping occurs in outermost navbox.
return wikitext .. orphanCat
end
end
local first, second = 'odd', 'even'
titlecell:wikitext( args.title or '{{{title}}}' )
if evenodd_VARIABLE then
if evenodd_VARIABLE == 'swap' then
-- Padding
first, second = second, first
local hasTemplate = args.template ~= nil
local hasState = not args.state or args.state ~= 'plain'
if hasTemplate ~= hasState then
if hasTemplate then
titlecell:addClass('navbox-title-padright')
else
else
titlecell:addClass('navbox-title-padleft')
first = evenodd_VARIABLE
second = first
end
end
end
end
local changer
if args.titleclass then titlerow:addClass( args.titleclass ) end
if first == second then
if args.titlestyle then titlecell:cssText( args.titlestyle ) end
changer = first
else
titlerow:node(titlecell)
local index = 0
navbox:node(titlerow)
changer = function (code)
end
if code == '0' then
-- Current occurrence is for a group before a nested table.
local function _addGutter( parent, incRowspan )
-- Set it to first as a valid although pointless class.
parent:tag('tr'):addClass('navbox-gutter'):tag('td'):attr('colspan',2)
-- The next occurrence will be the first row after a title
-- in a subgroup and will also be first.
if incRowspan then
index = 0
rowspan = rowspan + 1
return first
end
index = index + 1
return index % 2 == 1 and first or second
end
end
end
local regex = orphanCat:gsub('([%[%]])', '%%%1')
return (wikitext:gsub(regex, ''):gsub(REGEX_MARKER, changer))  -- () omits gsub count
end
end
 
------------------------------------------------
local function addNewline(s)
-- Above/Below
if s:match('^[*:;#]') or s:match('^{|') then
------------------------------------------------
return '\n' .. s ..'\n'
--- Processes the above and below rows
--
-- @param rowtype Either 'above' or 'below'
local function processAboveBelow( rowtype )
if not args[rowtype] then return end
local abrow = mw.html.create('tr'):addClass('navbox-'..rowtype)
local abcell = mw.html.create('td'):attr('colspan',colspan):wikitext( args[rowtype] )
if args[rowtype .. 'class'] then abrow:addClass( args[rowtype .. 'class'] ) end
if args[rowtype .. 'style'] then abcell:cssText( args[rowtype .. 'style'] ) end
abrow:node( abcell )
_addGutter( navbox )
navbox:node( abrow )
end
------------------------------------------------
-- Main Rows
------------------------------------------------
--- Processes the images
local function _processImage(row, imgtype)
if not args[imgtype] then return end
local iclass = imgtype == 'image' and 'navbox-image-right' or 'navbox-image-left'
local imagecell = mw.html.create('td'):addClass('navbox-image'):addClass(iclass)
local image = args[imgtype]
if image:sub(1,1) ~= '[' then
local width = args[imgtype .. 'width'] or '100px'
imagecell:css('width',width):wikitext('['..'[' .. image  .. '|' .. width .. '|link=' .. (args[imgtype .. 'link'] or '') .. ']]')
else
else
imagecell:css('width','0%'):wikitext(image)
return s
end
end
end
if args[imgtype .. 'class'] then imagecell:addClass( args[imgtype .. 'class'] ) end
 
if args[imgtype .. 'style'] then imagecell:cssText( args[imgtype .. 'style'] ) end
local function renderNavBar(titleCell)
 
row:node( imagecell )
if navbar ~= 'off' and navbar ~= 'plain' and not (not name and mw.getCurrentFrame():getParent():getTitle():gsub('/песочница$', '') == 'Шаблон:Навигационная таблица') then
if imgtype == 'image' then
cimage = imagecell
-- Check color contrast of the gear icon
else
local styleratio = require('Module:Color contrast')._styleratio
cimageleft = imagecell
local gearColor = ''
local contrastStyle = titlestyle or basestyle
local gearStyleBlack = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#666;' or '')
local gearStyleWhite = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#fff;' or '')
if styleratio{gearStyleBlack} < styleratio{gearStyleWhite} then
gearColor = ' white'
end
--- Gear creation
titleCell
:tag('span')
:addClass('navbox-gear')
:css('float', 'left')
:css('text-align', 'left')
:css('width', '5em')
:css('margin-right', '0.5em')
:wikitext('[[Файл:Wikipedia interwiki section gear icon' .. gearColor .. '.svg|14px|Просмотр этого шаблона|link=Шаблон:' .. name .. '|alt=⛭]]')
end
end
end
end
 
--- Closes the currently active section (if any)
--
local function _closeCurrentSection()
--  Title row
if not activeSection then return end
--
local function renderTitleRow(tbl)
local row = mw.html.create('tr'):addClass('navbox-section-row')
if not maintitle then return end
local cell = mw.html.create('td'):attr('colspan',2)
 
local titleRow = tbl:tag('tr')
if not hasrows then
 
_processImage(row,'imageleft')
if args.titlegroup then
titleRow
:tag('th')
:attr('scope', 'row')
:addClass('navbox-group')
:addClass(args.titlegroupclass)
:cssText(basestyle)
:cssText(groupstyle)
:cssText(args.titlegroupstyle)
:wikitext(args.titlegroup)
end
end
 
cell:node(sections[activeSection])
local titleCell = titleRow:tag('th'):attr('scope', 'col')
row:node(cell)
 
if args.titlegroup then
local firstRow = false
titleCell
if not hasrows then
:css('border-left', '2px solid #fdfdfd')
firstRow = true
:css('width', '100%')
hasrows = true
_processImage(row,'image')
end
end
 
_addGutter(navbox,not firstRow)
local titleColspan = 2
navbox:node(row)
if imageleft then titleColspan = titleColspan + 1 end
rowspan = rowspan + 1
if image then titleColspan = titleColspan + 1 end
if args.titlegroup then titleColspan = titleColspan - 1 end
activeSection = false
 
hasData = false
titleCell
:cssText(basestyle)
:cssText(titlestyle)
:addClass('navbox-title')
:attr('colspan', titleColspan)
 
renderNavBar(titleCell)
 
titleCell
:tag('div')
:attr('id', mw.uri.anchorEncode(maintitle))
:addClass(titleclass)
:css('font-size', '114%')
:css('margin', '0 5em')
:wikitext(addNewline(maintitle))
end
end
 
--- Handles alternating rows
--
--   Above/Below rows
--
--
-- @return Alternatingly returns true or false. Always returns false if alternating rows
 
--        are disabled with "alternaterows = no"
local function getAboveBelowColspan()
local function _alternateRow()
local ret = 2
if args.alternaterows == 'no' then return false end
if imageleft then ret = ret + 1 end
if alt then
if image then ret = ret + 1 end
alt = false
return ret
return true
end
else
 
alt = true
local function renderAboveRow(tbl)
return false
if not above then return end
end
 
tbl:tag('tr')
:tag('td')
:addClass('navbox-abovebelow')
:addClass(aboveclass)
:cssText(basestyle)
:cssText(abovestyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
:wikitext(addNewline(above))
end
 
local function renderBelowRow(tbl)
if not below then return end
 
tbl:tag('tr')
:tag('td')
:addClass('navbox-abovebelow')
:addClass(belowclass)
:cssText(basestyle)
:cssText(belowstyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
:wikitext(addNewline(below))
end
end
 
--- Process a single Header "row"
--
--   List rows
--
--
-- @param num Number of the row to be processed
 
local function processHeader(num)
local function haveSubgroups()
if not args['header'..num] then return end
for i = 1, 23 do
if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and (args['list' .. i] or args['список' .. i]) then
_closeCurrentSection()
return true
local subtable = mw.html.create('table'):addClass('navbox-section')
local headerrow = mw.html.create('tr')
local header = mw.html.create('th'):addClass('navbox-header'):attr('colspan',2):attr('scope','col'):wikitext( args['header'..num] )
local collapseme = args['state'..num] or false
local state = false
if collapseme then
-- Look at this one
if collapseme ~= 'plain' then
state = collapseme == 'expanded' and 'expanded' or 'collapsed'
end
else
-- Look at default
local collapseall = args.defaultstate or false
if collapseall then
state = collapseall == 'expanded' and 'expanded' or 'collapsed'
end
end
end
end
return false
if state then
end
subtable:addClass('mw-collapsible'):attr('data-expandtext',args['expandtext'..num] or args['defaultexpandtext'] or showText):attr('data-collapsetext',args['collapsetext'..num] or args['defaultcollapsetext'] or hideText)
 
if state == 'collapsed' then
local function renderListRow(tbl, index, listnum)
subtable:addClass('mw-collapsed')
local row = tbl:tag('tr')
end
 
header:addClass('navbox-header-collapsible')
if index == 1 and imageleft then
row
:tag('td')
:addClass('navbox-image')
:addClass(imageclass)
:css('width', '1px')
:css('padding', '0px 7px 0px 0px')
:cssText(imageleftstyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(addNewline(imageleft))
end
end
 
if args.headerclass then headerrow:addClass( args.headerclass ) end
if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
if args.headerstyle then header:cssText( args.headerstyle ) end
local groupCell = row:tag('th')
 
headerrow:node(header)
groupCell
subtable:node(headerrow)
:attr('scope', 'row')
:addClass('navbox-group')
sections[num] = subtable
:addClass(groupclass)
activeSection = num
:cssText(basestyle)
end
:css('width', groupwidth or '1px') -- If groupwidth not specified, minimize width
 
--- Processes a single list row
groupCell
--
:cssText(groupstyle)
-- @param num Number of the row to be processed
:cssText(args['group' .. listnum .. 'style'] or args['стиль_группы' .. listnum] or args['стиль_заголовка' .. listnum])
local function processList(num)
:wikitext(args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum])
if not args['list'..num] then return end
local row = mw.html.create('tr'):addClass('navbox-row')
if not hasrows and not activeSection then
_processImage(row, 'imageleft')
end
end
 
local listcell = mw.html.create('td'):addClass('navbox-list')
local listCell = row:tag('td')
local hlistcell = listcell:tag('div'):addClass('hlist')
 
if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
local data = args['list'..num]
listCell
:css('text-align', 'left')
if data:sub(1,1) == '*' then
:css('border-left-width', '2px')
-- Add newlines to support lists properly
:css('border-left-style', 'solid')
hlistcell
:newline()
:wikitext( data )
:newline()
else
else
hlistcell:wikitext( data )
if haveSubgroups() then
listCell
:attr('colspan', 2)
end
end
end
 
local altRow = _alternateRow()
if not groupwidth then
if altRow then
listCell:css('width', '100%')
row:addClass( args.altrowclass or 'alt' )
local listclass = args.altlistclass or args.listclass or false
if listclass then listcell:addClass( listclass ) end
local liststyle = args.altliststyle or args.liststyle or false
if liststyle then listcell:cssText( liststyle ) end
else
if args.rowclass then row:addClass( args.rowclass ) end
if args.listclass then listcell:addClass( args.listclass ) end
if args.liststyle then listcell:cssText( args.liststyle ) end
end
end
 
if args['group'..num] then
local listText = args['list' .. listnum] or args['список' .. listnum]
local groupcell = mw.html.create('th'):addClass('navbox-group'):attr('scope','row'):wikitext( args['group'..num] )
local oddEven = ODD_EVEN_MARKER
if listText:sub(1, 12) == '</div><table' then
if altRow then
-- Assume list text is for a subgroup navbox so no automatic striping for this row.
local groupclass = args.altgroupclass or args.groupclass or false
oddEven = listText:find('<th[^>]*"navbox%-title"') and RESTART_MARKER or 'odd'
if groupclass then groupcell:addClass( groupclass ) end
local groupstyle = args.altgroupstyle or args.groupstyle or false
if groupstyle then groupcell:cssText( groupstyle ) end
else
if args.groupclass then groupcell:addClass( args.groupclass ) end
if args.groupstyle then groupcell:cssText( args.groupstyle ) end
end
row:node( groupcell )
else
listcell:attr('colspan',2):addClass('no-group')
end
end
listCell
row:node( listcell )
:css('padding', '0px')
:cssText(liststyle)
local firstRow = false
:cssText(args['list' .. listnum .. 'style'] or args['стиль_списка' .. listnum])
if not hasrows and not activeSection then
:addClass('navbox-list')
firstRow = true
:addClass('navbox-' .. oddEven)
hasrows = true
:addClass(listclass)
_processImage(row, 'image')
:tag('div')
:css('padding', args['list' .. listnum .. 'padding'] or listpadding or '0em 0.25em')
:wikitext(addNewline(listText))
 
if index == 1 and image then
row
:tag('td')
:addClass('navbox-image')
:addClass(imageclass)
:css('width', '1px')
:css('padding', '0px 0px 0px 7px')
:cssText(imagestyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(addNewline(image))
end
end
end
if activeSection then
 
local parent = sections[activeSection]
--
if not isChild or not firstRow then
--  Tracking categories
_addGutter(parent)
--
local function needsChangetoSubgroups()
for i = 1, 23 do
if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and not (args['list' .. i] or args['список' .. i]) then
return true
end
end
parent:node(row)
hasData = true
else
if not isChild or not firstRow then
_addGutter(navbox,not firstRow)
end
navbox:node( row )
rowspan = rowspan + 1
end
end
return false
end
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, ['hlist hlist-items-nowrap'] = true, ['hlist-items-nowrap'] = true,
}
return not (listClasses[listclass] or listClasses[bodyclass])
end
end
 
--- Processes all rows
-- local function hasBackgroundColors()
local function processRows()
-- return mw.ustring.match(titlestyle or '','background') or mw.ustring.match(groupstyle or '','background') or mw.ustring.match(basestyle or '','background')
sections = {}
-- end
for i=1,#rownums do
 
local num = rownums[i]
local function isIllegible()
if not skiprows[num] then
local styleratio = require('Module:Color contrast')._styleratio
processHeader(num)
 
processList(num)
for key, style in pairs(args) do
if tostring(key):match("style$") or tostring(key):match("^стиль") then
if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
return true
end
end
end
end
end
_closeCurrentSection()
return false
end
if cimageleft then
 
cimageleft:attr('rowspan',rowspan)
local function getTrackingCategories()
end
local cats = {}
if cimage then
if needsChangetoSubgroups() then table.insert(cats, 'Навигационные шаблоны с ошибочным использованием заголовков') end
cimage:attr('rowspan',rowspan)
if needsHorizontalLists() then table.insert(cats, 'Навигационные шаблоны без горизонтальных списков') end
if isIllegible() then table.insert(cats, 'Потенциально нечитаемые навигационные шаблоны') 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 == 'песочница' or subpage == 'тесты' then return end
 
for i, cat in ipairs(getTrackingCategories()) do
builder:wikitext('[[Категория:' .. cat .. ']]')
end
end
end
end
 
------------------------------------------------
--
-- ARGUMENTS PREPROCESSOR
--   Main navbox tables
-- * Extracts arguments from frame and stores them in args table
-- * At the same time, checks for valid row numbers
------------------------------------------------
--- Preprocessor for the arguments.
-- Will fill up the args table with the parameters from the frame grouped by their type.
--
--
-- @param frame The frame passed to the Module.
local function renderMainTable()
local function preProcessArgs(frame)
local tbl = mw.html.create('table')
local tmp = {}
:addClass('nowraplinks')
:addClass(bodyclass)
if frame == mw.getCurrentFrame() then
 
tmp = frame:getParent().args
if maintitle and (args.state ~= 'plain' and args.state ~= 'off') then
else
tbl
tmp = frame
:addClass('collapsible')
:addClass(args.state or 'autocollapse')
end
 
tbl:css('border-spacing', 0)
if border == 'subgroup' or border == 'none' then
tbl
:addClass('navbox-subgroup')
:cssText(bodystyle)
:cssText(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
end
renderBelowRow(tbl)
-- Storage tables
 
local nums = {}
return tbl
end
-- Loop over all the args
 
for k,v in pairs(tmp) do
function p._navbox(navboxArgs)
-- Skip empty args, which are useless
args = navboxArgs
if v ~= '' then
if not yesno then
local cat,num = tostring(k):match('^(%a+)([1-9]%d*)$')
yesno = require('Module:Yesno');
if cat == 'header' or cat == 'list' then
nums[num] = true
end
args[k] = v -- Simple copy
end
end
end
 
colspan = args.image and 3 or 2
for k, v in pairs(args) do
if args.imageleft then colspan = colspan + 1 end
local listnum = ('' .. k):match('^list(%d+)$') or ('' .. k):match('^список(%d+)$')
rowspan = 0
if listnum then table.insert(listnums, tonumber(listnum)) end
if args.alternaterows == 'swap' then
alt = true
end
end
for k, v in pairs(nums) do
table.sort(listnums)
rownums[#rownums+1] = tonumber(k)
 
border = mw.text.trim(args.border or args[1] or '')
if border == 'child' then
border = 'subgroup'
end
end
table.sort(rownums)
maintitle = args.title or args['заголовок']
navbar = args.navbar or args['ссылка_на_просмотр']
-- Calculate skip rows
name = args.name or args['имя']
local cSection, cSkip
navigation = yesno(args.navigation or args['навигация'], '')
local showall = args.showall
above = args.above or args['вверху']
for i=1,#rownums do
image = args.image or args['изображение']
local num = rownums[i]
imagestyle = args.imagestyle or args['стиль_изображения']
if args['header'..num] then
imageleft = args.imageleft or args['изображение2'] or args['изображение_слева']
cSection = true
imageleftstyle = args.imageleftstyle or args.imagestyle2 or args['стиль_изображения_слева']
cSkip = false
below = args.below or args['внизу']
local showme = args['show'..num]
titlestyle = args.titlestyle or args['стиль_основного_заголовка'] or args['стиль_заголовка']
if showme == 'no' then
groupstyle = args.groupstyle or args['стиль_заголовков'] or args['стиль_групп']
cSkip = true
bodystyle = args.bodystyle or args['стиль_тела']
elseif showme == 'auto' or (showme ~= 'yes' and showall ~= 'yes') then
basestyle = args.basestyle or args['стиль_базовый'] or args['стиль']
if not args['list'..num] then
style = args.style
local nextNum = rownums[i+1]
liststyle = args.liststyle or args['стиль_списков']
cSkip = not nextNum or args['header'..nextNum] -- If next has a header -> skip
abovestyle = args.abovestyle or args['стиль_вверху']
end
belowstyle = args.belowstyle or args['стиль_внизу']
end
evenodd_VARIABLE = args.evenodd or args['чётные_нечётные'] or args['четные_нечетные']
groupwidth = args.groupwidth or args['ширина_групп']
listpadding = args.listpadding or args['отступ_списков']
bodyclass = args.bodyclass or args['класс_тела']
titleclass = args.titleclass or args['класс_заголовка']
aboveclass = args.aboveclass or args['класс_вверху']
belowclass = args.belowclass or args['класс_внизу']
groupclass = args.groupclass or args['класс_групп']
listclass = args.listclass or args['класс_списков']
imageclass = args.imageclass or args['класс_изображения']
-- 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)
if maintitle then
nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
else
nav:attr('aria-label', 'Навигационный шаблон')
end
if name and name ~= '-' then
nav:attr('data-name', name)
end
if navigation == true then
nav:attr('data-navboxnavigation', '1')
elseif navigation == false then
nav:attr('data-navboxnavigation', '0')
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>') -- 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
local nav = res:tag('div')
:attr('role', 'navigation')
:addClass('navbox')
:cssText(bodystyle)
:cssText(style)
:css('padding', '3px')
:node(tbl)
if maintitle then
nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
else
nav:attr('aria-label', 'Навигационный шаблон')
end
if name and name ~= '-' then
nav:attr('data-name', name)
end
end
if cSection and cSkip then
if navigation == true then
skiprows[num] = true
nav:attr('data-navboxnavigation', '1')
elseif navigation == false then
nav:attr('data-navboxnavigation', '0')
end
end
end
end
renderTrackingCategories(res)
return striped(tostring(res))
end
end
 
------------------------------------------------
function p.navbox(frame)
-- MAIN FUNCTIONS
if not getArgs then
------------------------------------------------
getArgs = require('Module:Arguments').getArgs
end
--- Processes the arguments to create the navbox.
if not yesno then
--
yesno = require('Module:Yesno');
-- @return A string with HTML that is the navbox.
local function _navbox()
-- Create the root HTML element
local trim = function(s)
return s and mw.ustring.gsub(s, "^%s*(.-)%s*$", "%1") or ''
end
end
local border = args.border or trim(args[1])  or ''
args = getArgs(frame, {wrappers = {'Шаблон:Навигационная таблица', 'Шаблон:Подгруппы навигационной таблицы'}})
isChild = (border == 'child' or border == 'subgroup')
if frame.args.border then
-- This allows Template:Navbox_subgroup to use {{#invoke:Navbox|navbox|border=...}}.
if isChild then
args.border = frame.args.border
navbox = mw.html.create('table'):addClass('navbox-subgroup')
else
navbox = mw.html.create('table'):addClass('navbox')
if args.state ~= 'plain' then
navbox:addClass('mw-collapsible'):attr('data-expandtext',args['expandtext'] or args['defaultexpandtext'] or showText):attr('data-collapsetext',args['collapsetext'] or args['defaultcollapsetext'] or hideText)
if args.state == 'collapsed' then
navbox:addClass('mw-collapsed')
end
end
end
end
if args.bodyclass then navbox:addClass(args.bodyclass) end
-- Read the arguments in the order they'll be output in, to make references number in the right order.
if args.bodystyle then navbox:cssText(args.bodystyle) end
local _
_ = maintitle
-- Process...
_ = above
if not isChild then
for i = 1, 23 do
processTitle()
_ = args["group" .. tostring(i)] and args["заголовок" .. tostring(i)] and args["группа" .. tostring(i)]
processAboveBelow('above')
_ = args["list" .. tostring(i)] and args["список" .. tostring(i)]
processRows()
processAboveBelow('below')
return tostring(navbox)
else
processRows()
local wrapper = mw.html.create('')
wrapper:wikitext('</div>')
wrapper:node(navbox)
wrapper:wikitext('<div class="hlist">')
return tostring(wrapper)
end
end
_ = below
return p._navbox(args)
end
end
 
--- Main module entry point.
-- To be called with {{#invoke:navbox|main}} or directly from another module.
--
-- @param frame The frame passed to the module via the #invoke. If called from another
--              module directly, this should be a table with the parameter definition.
function p.main(frame)
-- Save the arguments in a local variable so other functions can use them.
preProcessArgs(frame)
return _navbox()
end
return p
return p

Версія за 19:23, 14 жовтня 2020

Документацію для цього модуля можна створити у Модуль:Navbox/документація

--
-- Реализует {{Навигационная таблица}} и {{Подгруппы навигационной таблицы}}.
-- Основной объём кода заимствован из английского Module:Navbox.
--

local p = {}

local getArgs -- lazily initialized
local yesno -- 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 maintitle
local name
local navigation
local navbar
local above
local image
local below

local titlestyle
local groupstyle
local bodystyle
local basestyle
local liststyle
local evenodd_VARIABLE
local abovestyle
local belowstyle
local imageleft
local imageleftstyle
local style

local groupwidth
local listpadding

local bodyclass
local titleclass
local aboveclass
local belowclass
local groupclass
local listclass
local imageclass

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 = '[[Категория:Навигационные шаблоны без родителя]]'
	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 evenodd_VARIABLE then
		if evenodd_VARIABLE == 'swap' then
			first, second = second, first
		else
			first = evenodd_VARIABLE
			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 addNewline(s)
	if s:match('^[*:;#]') or s:match('^{|') then
		return '\n' .. s ..'\n'
	else
		return s
	end
end

local function renderNavBar(titleCell)

	if navbar ~= 'off' and navbar ~= 'plain' and not (not name and mw.getCurrentFrame():getParent():getTitle():gsub('/песочница$', '') == 'Шаблон:Навигационная таблица') then
		
		-- Check color contrast of the gear icon
		local styleratio = require('Module:Color contrast')._styleratio
		local gearColor = ''
		local contrastStyle = titlestyle or basestyle
		local gearStyleBlack = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#666;' or '')
		local gearStyleWhite = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#fff;' or '')
		if styleratio{gearStyleBlack} < styleratio{gearStyleWhite} then
			gearColor = ' white'
		end
		
		--- Gear creation
		titleCell
			:tag('span')
				:addClass('navbox-gear')
				:css('float', 'left')
				:css('text-align', 'left')
				:css('width', '5em')
				:css('margin-right', '0.5em')
				:wikitext('[[Файл:Wikipedia interwiki section gear icon' .. gearColor .. '.svg|14px|Просмотр этого шаблона|link=Шаблон:' .. name .. '|alt=⛭]]')
	end

end

--
--   Title row
--
local function renderTitleRow(tbl)
	if not maintitle 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(basestyle)
				:cssText(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 imageleft then titleColspan = titleColspan + 1 end
	if image then titleColspan = titleColspan + 1 end
	if args.titlegroup then titleColspan = titleColspan - 1 end

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

	renderNavBar(titleCell)

	titleCell
		:tag('div')
			:attr('id', mw.uri.anchorEncode(maintitle))
			:addClass(titleclass)
			:css('font-size', '114%')
			:css('margin', '0 5em')
			:wikitext(addNewline(maintitle))
end

--
--   Above/Below rows
--

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

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

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

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

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

--
--   List rows
--

local function haveSubgroups()
	for i = 1, 23 do
		if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and (args['list' .. i] or args['список' .. i]) then
			return true
		end
	end
	return false
end

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

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

	if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
		local groupCell = row:tag('th')

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

		groupCell
			:cssText(groupstyle)
			:cssText(args['group' .. listnum .. 'style'] or args['стиль_группы' .. listnum] or args['стиль_заголовка' .. listnum])
			:wikitext(args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum])
	end

	local listCell = row:tag('td')

	if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
		listCell
			:css('text-align', 'left')
			:css('border-left-width', '2px')
			:css('border-left-style', 'solid')
	else
		if haveSubgroups() then
			listCell
				:attr('colspan', 2)
		end
	end

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

	local listText = args['list' .. listnum] or args['список' .. 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(liststyle)
		:cssText(args['list' .. listnum .. 'style'] or args['стиль_списка' .. listnum])
		:addClass('navbox-list')
		:addClass('navbox-' .. oddEven)
		:addClass(listclass)
		:tag('div')
			:css('padding', args['list' .. listnum .. 'padding'] or listpadding or '0em 0.25em')
			:wikitext(addNewline(listText))

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

--
--   Tracking categories
--
local function needsChangetoSubgroups()
	for i = 1, 23 do
		if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and not (args['list' .. i] or args['список' .. i]) then
			return true
		end
	end
	return false
end

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, ['hlist hlist-items-nowrap'] = true, ['hlist-items-nowrap'] = true,
	}
	return not (listClasses[listclass] or listClasses[bodyclass])
end

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

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

	for key, style in pairs(args) do
		if tostring(key):match("style$") or tostring(key):match("^стиль") then
			if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
				return true 
			end
		end
	end
	return false
end

local function getTrackingCategories()
	local cats = {}
	if needsChangetoSubgroups() then table.insert(cats, 'Навигационные шаблоны с ошибочным использованием заголовков') end
	if needsHorizontalLists() then table.insert(cats, 'Навигационные шаблоны без горизонтальных списков') end
	if isIllegible() then table.insert(cats, 'Потенциально нечитаемые навигационные шаблоны') 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 == 'песочница' or subpage == 'тесты' then return end

	for i, cat in ipairs(getTrackingCategories()) do
		builder:wikitext('[[Категория:' .. cat .. ']]')
	end
end

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

	if maintitle and (args.state ~= 'plain' and args.state ~= 'off') then
		tbl
			:addClass('collapsible')
			:addClass(args.state or 'autocollapse')
	end

	tbl:css('border-spacing', 0)
	if border == 'subgroup' or border == 'none' then
		tbl
			:addClass('navbox-subgroup')
			:cssText(bodystyle)
			:cssText(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
	if not yesno then
		yesno = require('Module:Yesno');
	end

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

	border = mw.text.trim(args.border or args[1] or '')
	if border == 'child' then
		border = 'subgroup'
	end
	
	maintitle = args.title or args['заголовок']
	navbar = args.navbar or args['ссылка_на_просмотр']
	name = args.name or args['имя']
	navigation = yesno(args.navigation or args['навигация'], '')
	above = args.above or args['вверху']
	image = args.image or args['изображение']
	imagestyle = args.imagestyle or args['стиль_изображения']
	imageleft = args.imageleft or args['изображение2'] or args['изображение_слева']
	imageleftstyle = args.imageleftstyle or args.imagestyle2 or args['стиль_изображения_слева']
	below = args.below or args['внизу']
	titlestyle = args.titlestyle or args['стиль_основного_заголовка'] or args['стиль_заголовка']
	groupstyle = args.groupstyle or args['стиль_заголовков'] or args['стиль_групп']
	bodystyle = args.bodystyle or args['стиль_тела']
	basestyle = args.basestyle or args['стиль_базовый'] or args['стиль']
	style = args.style
	liststyle = args.liststyle or args['стиль_списков']
	abovestyle = args.abovestyle or args['стиль_вверху']
	belowstyle = args.belowstyle or args['стиль_внизу']
	evenodd_VARIABLE = args.evenodd or args['чётные_нечётные'] or args['четные_нечетные']
	
	groupwidth = args.groupwidth or args['ширина_групп']
	listpadding = args.listpadding or args['отступ_списков']
	
	bodyclass = args.bodyclass or args['класс_тела']
	titleclass = args.titleclass or args['класс_заголовка']
	aboveclass = args.aboveclass or args['класс_вверху']
	belowclass = args.belowclass or args['класс_внизу']
	groupclass = args.groupclass or args['класс_групп']
	listclass = args.listclass or args['класс_списков']
	imageclass = args.imageclass or args['класс_изображения']
	
	-- 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)
		if maintitle then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
		else
			nav:attr('aria-label', 'Навигационный шаблон')
		end
		if name and name ~= '-' then
			nav:attr('data-name', name)
		end
		if navigation == true then
			nav:attr('data-navboxnavigation', '1')
		elseif navigation == false then
			nav:attr('data-navboxnavigation', '0')
		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>') -- 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
		local nav = res:tag('div')
			:attr('role', 'navigation')
			:addClass('navbox')
			:cssText(bodystyle)
			:cssText(style)
			:css('padding', '3px')
			:node(tbl)
		if maintitle then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
		else
			nav:attr('aria-label', 'Навигационный шаблон')
		end
		if name and name ~= '-' then
			nav:attr('data-name', name)
		end
		if navigation == true then
			nav:attr('data-navboxnavigation', '1')
		elseif navigation == false then
			nav:attr('data-navboxnavigation', '0')
		end
		
	end

	renderTrackingCategories(res)

	return striped(tostring(res))
end

function p.navbox(frame)
	if not getArgs then
		getArgs = require('Module:Arguments').getArgs
	end
	if not yesno then
		yesno = require('Module:Yesno');
	end
	args = getArgs(frame, {wrappers = {'Шаблон:Навигационная таблица', 'Шаблон:Подгруппы навигационной таблицы'}})
	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 _
	_ = maintitle
	_ = above
	for i = 1, 23 do
		_ = args["group" .. tostring(i)] and args["заголовок" .. tostring(i)] and args["группа" .. tostring(i)]
		_ = args["list" .. tostring(i)] and args["список" .. tostring(i)]
	end
	_ = below

	return p._navbox(args)
end

return p