Ҳуҷҷатгузорӣ
--
-- Реализует {{ҷадвали новбарӣ}}, {{зергурӯҳи ҷадвали новбарӣ}} ва {{ҷадвали новбарӣ бо блокҳо}}.
-- Основной объём кода заимствован из английского Module:Navbox.
--

local p = {}

local getArgs -- lazily initialized
local yesno -- lazily initialized
local styleratio

local ODD_EVEN_MARKER = '\127_ODDEVEN_\127'
local RESTART_MARKER = '\127_ODDEVEN0_\127'
local REGEX_MARKER = '\127_ODDEVEN(%d?)_\127'

-- общие параметры для всех шаблонов
local commonAliases = {
	name = {'name', 'ном'},
	navigation = {'navigation', 'новбарӣ'},
	navbar = {'navbar', 'пайванд_барои_дидан'},
	state = {'state'},
	orphan = {'orphan'},
	tracking = {'tracking'},
	border = {'border', 1},
	title = {'title', 'сарлавҳа'},
	titlegroup = {'titlegroup'},
	above = {'above', 'болоӣ'},
	image = {'image', 'тасвир'},
	imageleft = {'imageleft', 'тасвир2', 'тасвир_аз_чап'},
	below = {'below', 'поёнӣ'},
		
	bodyclass = {'bodyclass', 'синфи_бадан'},
	titleclass = {'titleclass', 'синфи_сарлавҳа'},
	titlegroupclass = {'titlegroupclass'},
	aboveclass = {'aboveclass', 'синфи_болоӣ'},
	belowclass = {'belowclass', 'синфи_поёнӣ'},
	groupclass = {'groupclass', 'синфи_гурӯҳ'},
	listclass = {'listclass', 'синфи_феҳристҳо'},
	imageclass = {'imageclass', 'синфи_тасвир'},
	
	basestyle = {'basestyle', 'сабк', 'сабки_асосӣ'},
	bodystyle = {'style', 'bodystyle', 'сабки_бадан'},
	titlestyle = {'titlestyle', 'сабки_сарлавҳаи_асосӣ', 'сабки_сарлавҳа'},
	titlegroupstyle = {'titlegroupstyle'},
	innerstyle = {'innerstyle'},
	abovestyle = {'abovestyle', 'сабки_болоӣ'},
	belowstyle = {'belowstyle', 'сабки_поёнӣ'},
	imagestyle = {'imagestyle', 'сабки_тасвир'},
	imageleftstyle = {'imageleftstyle', 'imagestyle2', 'сабки_тасвир_аз_чап'},
}

-- параметрҳои {{ҷадвали новбарӣ}} ва {{зергурӯҳи ҷадвали новбарӣ}}
local standardAliases = {
	groupstyle = {'groupstyle', 'сабки_сарлавҳаҳо', 'сабки_гурӯҳ'},
	liststyle = {'liststyle', 'сабки_феҳристҳо'},
	evenodd = {'evenodd', 'ҷуфт_тоқ', 'ҷуфт_тоқ'},
	groupwidth = {'groupwidth', 'бари_гурӯҳ'},
	listpadding = {'listpadding', 'фосилаи_феҳристҳо'},
}

-- параметры {{ҷадвали новбарӣ}} ва {{зергурӯҳи ҷадвали новбарӣ}} с нумерацией
local standardElementAliases = {
	group = {'group%s', 'сарлавҳа%s', 'гурӯҳ%s'},
	list = {'list%s', 'феҳрист%s'},
	groupstyle = {'group%sstyle', 'сабки_сарлавҳа%s', 'сабки_гурӯҳҳо%s'},
	listclass = {'list%sclass', 'синфи%sфеҳрист', 'синфи_феҳрист%s'},
	liststyle = {'list%sstyle', 'сабки_феҳрист%s'},
	listpadding = {'list%spadding'}
}

-- параметры {{ҷадвали новбарӣ бо блокҳо}}
-- с нижнего подчеркивания начинаются параметры, конфликтующие с standardAliases 
local groupsParentAliases = {
	selected = {'selected', 'блоки_боз', 'васеъ кардан'},
	secttitlestyle = {'secttitlestyle', 'сабки_сарлавҳаҳо'},
	_groupstyle = {'groupstyle', 'сабки_блоков'},
	_liststyle = {'liststyle', 'сабки_феҳристҳо', 'contentstyle'},
	_listpadding = {'listpadding', 'фосилаи_феҳрист', 'фосилаи_феҳристҳо'}
}

-- параметры {{ҷадвали новбарӣ бо блокҳо}} с нумерацией
local groupsChildAliases = {
	groupname = {'abbr%s', 'номи_блок%s', 'аббр%s'},
	state = {'state%s'},
	title = {'group%s', 'блок%s', 'сарлавҳа%s', 'гурӯҳ%s', 'sect%s', 'section%s', 'бахш%s'},
	list1 = {'list%s', 'феҳрист%s', 'content%s'},
	image = {'image%s', 'тасвир%s'},
	imageleft = {'imageleft%s', 'тасвир_аз_чап%s'},

	secttitlestyle = {'sect%stitlestyle', 'сабки%sсарлавҳа', 'сабки_секции%s'},
	groupstyle = {'group%sstyle', 'сабки%sблок', 'сабки_гурӯҳҳо%s', 'сабки_блок%s'},
	listclass = {'list%sclass', 'синфи%sфеҳрист', 'синфи_феҳрист%s'},
	liststyle = {'list%sstyle', 'сабки%sфеҳрист', 'сабки_феҳрист%s', 'content%sstyle'},
	color = {'цвет%s'}
}

local function checkAliases(args, aliases, index)
	for _, alias in ipairs(aliases) do
		local arg
		if index then
			arg = args[string.format(alias, index)]
		else
			arg = args[alias]
		end
		
		if arg then
			return arg
		end
	end
	
	return nil
end

local function checkElAliases(args, name, index)
	return checkAliases(args, standardElementAliases[name], index)
end

local function concatStyles(t)
	local res
	for k, v in pairs(t) do
		if v then
			res = res and res .. ';' .. v or v
		end
	end
	return res
end

local function striped(wikitext, args)
	-- 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 args.border == 'subgroup' and args.orphan ~= 'yes' then
		-- No change; striping occurs in outermost navbox.
		return wikitext .. orphanCat
	end
	local first, second = 'odd', 'even'
	if args.evenodd then
		if args.evenodd == 'swap' then
			first, second = second, first
		else
			first = args.evenodd
			second = first
		end
	end
	local changer
	if first == second then
		changer = first
	else
		local index = 0
		changer = function (code)
			if code == '0' then
				-- Current occurrence is for a group before a nested table.
				-- Set it to first as a valid although pointless class.
				-- The next occurrence will be the first row after a title
				-- in a subgroup and will also be first.
				index = 0
				return first
			end
			index = index + 1
			return index % 2 == 1 and first or second
		end
	end
	local regex = orphanCat:gsub('([%[%]])', '%%%1')
	return (wikitext:gsub(regex, ''):gsub(REGEX_MARKER, changer))  -- () omits gsub count
end

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

local function renderNavBar(titleCell, args)
	local currentFrame = mw.getCurrentFrame()
	if args.navbar ~= 'off' and args.navbar ~= 'plain' 
		and (args.name or not currentFrame:getParent():getTitle():gsub('/регдон$', '') == 'Шаблон:Ҷадвали новбарӣ') then
		
		-- Check color contrast of the gear icon
		if not styleratio then
			styleratio = require('Module:Color contrast')._styleratio
		end
		local contrastStyle = args.titlestyle or args.basestyle
		local gearStyleBlack = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#666;' or '')
		local gearStyleWhite = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#fff;' or '')
		local gear = currentFrame:expandTemplate{
			title = 'Tnavbar-view',
			args = {
				args.name,
				fontcolor = (styleratio{gearStyleBlack} < styleratio{gearStyleWhite}) and 'white',
			}
		}
		
		--- Gear creation
		titleCell
			:tag('span')
				:addClass('navbox-gear')
				:css('float', 'left')
				:css('text-align', 'left')
				:css('width', '5em')
				:css('margin-right', '0.5em')
				:wikitext(gear)
	end

end

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

	local titleRow = tbl:tag('tr')

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

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

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

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

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

	renderNavBar(titleCell, args)

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

--
--   Above/Below rows
--

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

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

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

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

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

--
--   List rows
--

local function haveSubgroups(args)
	for i = 1, 23 do
		if checkElAliases(args, 'group', i) and checkElAliases(args, 'list', i) then
			return true
		end
	end
	return false
end

local function renderListRow(tbl, args, index, rowspan, rowArgs)
	local row = tbl:tag('tr')

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

	if rowArgs.group then
		local groupCell = row:tag('th')

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

		groupCell
			:cssText(args.groupstyle)
			:cssText(rowArgs.groupstyle)
			:wikitext(rowArgs.group)
	end

	local listCell = row:tag('td')

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

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

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

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

--
--   Tracking categories
--
local function needsChangetoSubgroups(args)
	for i = 1, 23 do
		if (checkElAliases(args, 'group', i)) and not (checkElAliases(args, 'list', i)) then
			return true
		end
	end
	return false
end

local function needsHorizontalLists(args)
	if args.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[args.listclass] or listClasses[args.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(args)
	if not styleratio then
		styleratio = require('Module:Color contrast')._styleratio
	end

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

local function renderTrackingCategories(builder, args)
	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(args)) do
		builder:wikitext('[[Гурӯҳ:' .. cat .. ']]')
	end
end

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

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

	tbl:css('border-spacing', 0)
	if args.border == 'subgroup' or args.border == 'none' then
		tbl
			:addClass('navbox-subgroup')
			:cssText(args.bodystyle)
	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, args)
	renderAboveRow(tbl, args)
	for i, listnum in ipairs(listnums) do
		local rowArgs = {
			group = checkElAliases(args, 'group', listnum),
			list = checkElAliases(args, 'list', listnum),
			groupstyle = checkElAliases(args, 'groupstyle', listnum),
			listclass = checkElAliases(args, 'listclass', listnum),
			liststyle = checkElAliases(args, 'liststyle', listnum),
			listpadding = checkElAliases(args, 'listpadding', listnum)
		}
		renderListRow(tbl, args, i, #listnums, rowArgs)
	end
	renderBelowRow(tbl, args)

	return tbl
end

-- Read the arguments in the order they'll be output in, to make references number in the right order.
local function readInTheRightOrder(args, groupAliases, listAliases)
	local _
	_ = checkAliases(args, commonAliases.title)
	_ = checkAliases(args, commonAliases.above)
	for i = 1, 23 do
		_ = checkAliases(args, groupAliases, i)
		_ = checkAliases(args, listAliases, i)
	end
	_ = checkAliases(args, commonAliases.below)
end

function p._navbox(args)
	if not yesno then
		yesno = require('Module:Yesno')
	end

	local listnums = {}
	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)

	args.border = mw.text.trim(args.border or args[1] or '')
	if args.border == 'child' then
		args.border = 'subgroup'
	end
	
	for argname, aliasesList in pairs(commonAliases) do
		args[argname] = checkAliases(args, aliasesList)	
	end
	for argname, aliasesList in pairs(standardAliases) do
		args[argname] = checkAliases(args, aliasesList)	
	end

	args.navigation = yesno(args.navigation, '')
	
	-- render the main body of the navbox
	local tbl = renderMainTable(args, listnums)

	-- render the appropriate wrapper around the navbox, depending on the border param
	local res = mw.html.create()
	if args.border == 'none' then
		local nav = res:tag('div')
			:attr('role', 'navigation')
			:node(tbl)
		if args.title then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title))
		else
			nav:attr('aria-label', 'Навигационный шаблон')
		end
		if args.name and args.name ~= '-' then
			nav:attr('data-name', args.name)
		end
		if args.navigation == true then
			nav:attr('data-navboxnavigation', '1')
		elseif args.navigation == false then
			nav:attr('data-navboxnavigation', '0')
		end
	elseif args.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(args.bodystyle)
			:node(tbl)
		if args.title then
			nav:attr('aria-labelledby', mw.uri.anchorEncode(args.title))
		else
			nav:attr('aria-label', 'Навигационный шаблон')
		end
		if args.name and args.name ~= '-' then
			nav:attr('data-name', args.name)
		end
		if args.navigation == true then
			nav:attr('data-navboxnavigation', '1')
		elseif args.navigation == false then
			nav:attr('data-navboxnavigation', '0')
		end
		
	end

	renderTrackingCategories(res, args)

	return striped(tostring(res), args)
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
	
	readInTheRightOrder(args, standardElementAliases.group, standardElementAliases.list)

	return p._navbox(args)
end

function p.navboxWithCollapsibleGroups(frame)
	if not getArgs then
		getArgs = require('Module:Arguments').getArgs
	end
	local args = getArgs(frame, {wrappers = {'Шаблон:Ҷадвали новбарӣ бо блокҳо'}})
	
	readInTheRightOrder(args, groupsChildAliases.title, groupsChildAliases.list1)
	
	local parent = {}
	for argname, aliasesList in pairs(commonAliases) do
		parent[argname] = checkAliases(args, aliasesList)	
	end
	for argname, aliasesList in pairs(groupsParentAliases) do
		parent[argname] = checkAliases(args, aliasesList)	
	end
				
	for i = 1, 20 do
		local child = {}
		for argname, aliasesList in pairs(groupsChildAliases) do
			child[argname] = checkAliases(args, aliasesList, i)	
		end
		
		child.color = child.color and string.format('background:%s;', child.color) or ''
		child.border = 'child'
		child.navbar = 'plain'
	
		if parent.selected and parent.selected == child.groupname then
			child.state = 'uncollapsed'
		end
		
		child.state = child.state or 'collapsed'
		
		child.basestyle = concatStyles{parent.basestyle, parent.secttitlestyle, child.secttitlestyle}
    	child.titlestyle = concatStyles{parent._groupstyle, child.groupstyle, child.color}
    	child.liststyle  = concatStyles{parent._liststyle, child.liststyle}
    	child.lispadding = parent._listpadding
		
		if child.title then
			parent['list' .. i] = p._navbox(child)
		else
			parent['list' .. i] = child.list1
		end
	end
	
	return p._navbox(parent)
	
end

return p