Модуль:Template call code

Материал из ChronoWiki
Версия от 03:36, 28 июля 2020; wikipedia>Serhio Magpie (- динамическая навигация)
Перейти к навигацииПерейти к поиску

Для документации этого модуля может быть создана страница Модуль:Template call code/doc

local getArgs = require('Module:Arguments').getArgs
local ru = mw.language.new('ru')

local p = {}

-- Используется для того, чтобы можно было удалять элементы из таблицы
local function copy(other)
	local res = {}
	for k, v in pairs(other) do
		res[k] = v
	end
	return res
end

local function makeInvokeFunc(funcName)
	return function (frame)
		local args = copy(getArgs(frame, {
			trim = false,
			removeBlanks = false
		}))
		return p[funcName](args)
	end
end

p.withoutParams = makeInvokeFunc('_withoutParams')

function p._withoutParams(args)
	local name = args[1]
	table.remove(args, 1)
	
	-- Вещи типа «=» в первом параметре
	if not name then
		for k, v in pairs(args) do
			if not k:find('^_') then
				name = k .. '=' .. v
				args[k] = nil
				break
			end
		end
	end
	
	local flags = {}
	for i, v in ipairs(args) do
		if v == 'nl' or v == 'nolink' then
			flags.noLink = true
		elseif v == 's' then
			flags.subst = true
		elseif v == 'п' then
			flags.podst = true
		elseif v == 'g' then
			flags.global = true
		elseif v == 'nav' then
			flags.nav = true
		elseif v == 'noredir' then
			flags.noRedirect = true
		elseif v == 'u' then
			flags.ucFirst = true
		elseif v == 'b' then
			flags.black = true
		end
	end
	
	if name then
		local trimmedName = mw.text.trim(name)
		if ru:lc(mw.ustring.sub(trimmedName, 1, 6)) == 'subst:' then
			flags.subst = true
			name = mw.ustring.sub(trimmedName, 7)
		end
		if ru:lc(mw.ustring.sub(trimmedName, 1, 6)) == 'подст:' then
			flags.podst = true
			name = mw.ustring.sub(trimmedName, 7)
		end
	end
	
	if args.text == '' then
		args.text = nil
	end
	if args.comment == '' then
		args.comment = nil
	end
	if args.lang == '' then
		args.lang = nil
	end
	if args.sister == '' then
		args.sister = nil
	end
	
	local currentTitle = mw.title.getCurrentTitle()
	-- При опущенном первом параметре берём имя шаблона из названия страницы
	if name == '' or not name then
		local currentTitleRoot = currentTitle.rootText
		if not flags.ucFirst and
			((ru:uc(currentTitleRoot) ~= currentTitleRoot and
				-- Книга:Литературное наследство, TranslateDate
				not mw.ustring.match(currentTitleRoot, '^[А-Яа-яA-Za-z]+:?[А-ЯA-Z]')
			) or
				#currentTitleRoot == 1
			)
		then
			name = ru:lcfirst(currentTitleRoot)
		else
			name = currentTitleRoot
		end
	end
	
	local global = flags.global or mw.ustring.sub(name, 1, 1) == ':'
	
	-- Начинаем собирать код
	local linkBody, titleObject, linkBegin, linkDivider, linkEnd
	
	local prefixes = {}
	if args.lang then
		table.insert(prefixes, args.lang)
	end
	if args.sister then
		table.insert(prefixes, args.sister)
	end
	linkBody = table.concat(prefixes, ':')
	
	if #linkBody ~= 0 then
		linkBody = ':' .. linkBody
	end
	if mw.ustring.sub(name, 1, 1) ~= ':' then
		linkBody = linkBody .. ':'
	end
	if not global then
		linkBody = linkBody .. 'Template:'
	end
	linkBody = linkBody .. name
	titleObject = mw.title.new(linkBody)
	
	local noLink = flags.noLink or currentTitle == titleObject
	local takeBracketsInLink = not noLink and
		mw.ustring.len(name) == 1 and
		not flags.black and
		not flags.subst and
		not flags.podst
	
	if not noLink then
		if not flags.noRedirect or (
			flags.noRedirect and
			not args.lang and
			not args.sister and
			not titleObject.exists
		) then
			linkBegin = '[['
			linkEnd = ']]'
			linkDivider = '|'
		else
			linkBegin = '['
			linkEnd = ']'
			linkDivider = ' '
			linkBody = titleObject:fullUrl('redirect=no')
		end
	end
	
	local text = ''
	if flags.nav and currentTitle == titleObject then
		text = text .. '\'\'\''
	end
	if not flags.black then
		text = text .. '<span class="wp-templatelink">'
	end
	text = text .. '{'
	if not takeBracketsInLink then
		text = text .. '{'
	end
	if flags.subst then
		text = text .. 'subst:'
	elseif flags.podst then
		text = text .. 'подст:'
	end
	if not flags.black then
		text = text .. '</span>'
	end
	
	text = text .. '<span data-navboxnavigation-link="0">'
	
	local commentedLabel
	if args.comment then
		-- https://phabricator.wikimedia.org/T200704
		-- commentedLabel = mw.getCurrentFrame():expandTemplate({title = 'comment', args = {(args.text or name), args.comment}})
		commentedLabel = '<span class="commentedText" title="' .. args.comment .. '" style="border-bottom: 1px dotted; cursor: help;">' ..
			(args.text or name) ..
			'</span>'
	end
	local label = (commentedLabel or args.text or name)
	if not noLink then
		if flags.noRedirect then
			text = text .. '<span class="plainlinks">'
		end
		text = text .. linkBegin .. linkBody .. linkDivider
		if not noLink and takeBracketsInLink then
			text = text .. '<span class="wp-templatelink">{</span>'
		end
		text = text .. label
		if not noLink and takeBracketsInLink then
			text = text .. '<span class="wp-templatelink">}</span>'
		end
		text = text .. linkEnd
		if flags.noRedirect then
			text = text .. '</span>'
		end
	else
		text = text .. label
	end
	
	text = text .. '</span>'
	
	if not flags.black then
		text = text .. '<span class="wp-templatelink">'
	end
	text = text .. '}'
	if not takeBracketsInLink then
		text = text .. '}'
	end
	if not flags.black then
		text = text .. '</span>'
	end
	if flags.nav and currentTitle == titleObject then
		text = text .. '\'\'\''
	end
	
	return text
end

function addParams(args, params)
	local text, equals_pos, param, value = '', 0, '', ''
	
	function addPipe()
		if params.spaced then
			text = text .. ' '
		end
		text = text .. '<span'
		if not params.black then
			text = text .. ' class="wp-templatelink"'
		end
		if not params.spaced then
			text = text .. ' style="margin:0 2px;"'
		end
		text = text .. '>&#124;</span>'
	end
	
	for k, v in pairs(args) do
		if type(k) == 'number' then  -- Неименованные параметры
			equals_pos = v:find('=')
			if equals_pos and v:find('{{=}}') == equals_pos - 2 then
				equals_pos = nil
			end
			if equals_pos then  -- Содержащие «=» преобразуем в именованные
				param = v:sub(1, equals_pos - 1)
				value = v:sub(equals_pos + 1)
				addPipe()
				text = text .. param .. '=' .. value
			else  -- Истинно неименованные
				addPipe()
				text = text .. v
			end
		elseif not k:find('^_') then  -- Именованные параметры, исключая модификаторы внешнего вида
			addPipe()
			text = text .. k .. '=' .. v
		end
	end
	
	return text
end

p.withParams = makeInvokeFunc('_withParams')

function p._withParams(args)
	local name = args[1]
	table.remove(args, 1)
	
	-- Вещи типа «=» в первом параметре
	if not name then
		for k, v in pairs(args) do
			if not k:find('^_') then
				name = k .. '=' .. v
				args[k] = nil
				break
			end
		end
	end
	
	local optpText
	if name then
		local spanOffset = mw.ustring.find(name, '<span')  -- След использования шаблона optp
		if spanOffset then
			optpText = mw.ustring.sub(name, spanOffset)
			name = mw.ustring.sub(name, 1, spanOffset - 1)
		end
	end
	
	local yesno = require('Module:Yesno')
	
	local nobr = yesno(args._nobr, false)
	local tag = args._tag or 'span'
	local style = args._style
	local spaced = yesno(args._spaced, false)
	local subst = yesno(args._s, false)
	local podst = yesno(args['_п'], false)
	local global = yesno(args._g, false) or name and mw.ustring.sub(name, 1, 1) == ':'
	local lang = args._lang
	local sister = args._sister
	local nav = yesno(args._nav, false)
	local ucFirst = yesno(args._u, false)
	local black = yesno(args._b, false) or tag ~= 'span'
	local noLink = yesno(args._nolink or args._nl, false) or not yesno(args._link, false)
	local textInPlaceOfName = args._text
	local comment = args._comment
	local noRedirect = yesno(args._noredir, false)
	local prefix = args._prefix
	local postfix = args._postfix
	
	if textInPlaceOfName == '' then
		textInPlaceOfName = nil
	end
	if comment == '' then
		comment = nil
	end
	if lang == '' then
		lang = nil
	end
	if sister == '' then
		sister = nil
	end
	
	if name then
		local trimmedName = mw.text.trim(name)
		if ru:lc(mw.ustring.sub(trimmedName, 1, 6)) == 'subst:' then
			subst = true
			name = mw.ustring.sub(trimmedName, 7)
		end
		if ru:lc(mw.ustring.sub(trimmedName, 1, 6)) == 'подст:' then
			podst = true
			name = mw.ustring.sub(trimmedName, 7)
		end
	end
	
	local currentTitle = mw.title.getCurrentTitle()
	-- При опущенном первом параметре берём имя шаблона из названия страницы
	if name == '' or not name then
		local currentTitleRoot = currentTitle.rootText
		if not ucFirst and
			((ru:uc(currentTitleRoot) ~= currentTitleRoot and
				-- Книга:Литературное наследство, TranslateDate
				not mw.ustring.match(currentTitleRoot, '^[А-Яа-яA-Za-z]+:?[А-ЯA-Z]')
			) or
				#currentTitleRoot == 1
			)
		then
			name = ru:lcfirst(currentTitleRoot)
		else
			name = currentTitleRoot
		end
	end
	
	-- Начинаем собирать код
	local linkBody, titleObject, linkBegin, linkDivider, linkEnd
	
	local prefixes = {}
	if lang then
		table.insert(prefixes, lang)
	end
	if sister then
		table.insert(prefixes, sister)
	end
	linkBody = table.concat(prefixes, ':')
	
	if #linkBody ~= 0 then
		linkBody = ':' .. linkBody
	end
	if mw.ustring.sub(name, 1, 1) ~= ':' then
		linkBody = linkBody .. ':'
	end
	if not global then
		linkBody = linkBody .. 'Template:'
	end
	linkBody = linkBody .. name
	titleObject = mw.title.new(linkBody)
	
	local noLink = noLink or currentTitle == titleObject
	local takeBracketsInLink = not noLink and
		mw.ustring.len(name) == 1 and
		not black and
		not subst and
		not podst
	
	if not noLink then
		if not noRedirect or (
			noRedirect and
			not lang and
			not sister and
			not titleObject.exists
		) then
			linkBegin = '[['
			linkEnd = ']]'
			linkDivider = '|'
		else
			linkBegin = '['
			linkEnd = ']'
			linkDivider = ' '
			linkBody = titleObject:fullUrl('redirect=no')
		end
	end
	
	local text = ''
	if tag then
		text = text .. '<' .. tag .. ' class="templateCallCode'
		if nobr then
			text = text .. ' nowrap'
		end
		text = text .. '"'
		if style then
			text = text .. ' style="' .. style .. '"'
		end
		text = text .. '>'
	end
	if prefix then
		text = text .. prefix
	end
	
	if not black then
		text = text .. '<span class="wp-templatelink">'
	end
	text = text .. '{{'
	if subst then
		text = text .. 'subst:'
	elseif podst then
		text = text .. 'подст:'
	end
	if not black then
		text = text .. '</span>'
	end
	
	if nav and currentTitle == titleObject then
		text = text .. '\'\'\''
	end
	
	local commentedLabel
	if comment then
		-- https://phabricator.wikimedia.org/T200704
		-- commentedLabel = mw.getCurrentFrame():expandTemplate({title = 'comment', args = {(text or name), comment}})
		commentedLabel = '<span class="commentedText" title="' .. comment .. '" style="border-bottom: 1px dotted; cursor: help;">' ..
			(textInPlaceOfName or name) ..
			'</span>'
	end
	local label = (commentedLabel or textInPlaceOfName or name)
	if not noLink then
		if noRedirect then
			text = text .. '<span class="plainlinks">'
		end
		text = text .. linkBegin .. linkBody .. linkDivider .. label .. linkEnd
		if noRedirect then
			text = text .. '</span>'
		end
	else
		text = text .. label
	end
	
	if nav and currentTitle == titleObject then
		text = text .. '\'\'\''
	end
	
	if optpText then
		text = text .. optpText
	end
	
	text = text .. addParams(args, {
		spaced = spaced,
		black = black,
	})
	
	if spaced then
		text = text .. ' '
	end
	
	if not black then
		text = text .. '<span class="wp-templatelink">'
	end
	text = text .. '}}'
	if not black then
		text = text .. '</span>'
	end
	
	if postfix then
		text = text .. postfix
	end
	if tag then
		text = text .. '</' .. tag .. '>'
	end
	
	return text
end

p.onlyParams = makeInvokeFunc('_onlyParams')

function p._onlyParams(args)
	local span = mw.html.create('span')
	span:css( 'color', mw.getCurrentFrame():expandTemplate({ title = 'optp/color' }) )
	
	local yesno = require('Module:Yesno')
	
	span:wikitext(addParams(args, {
		spaced = yesno(args._spaced, false),
		black = true,
	}))

	return tostring(span)
end

return p