Модуль:Hatnote: различия между версиями

Материал из Викимультии — энциклопедии мультипликации
Перейти к навигации Перейти к поиску
[непроверенная версия][отпатрулированная версия]
Нет описания правки
Метка: отменено
отмена правки 97160 участника Alexandr Efremov (обс)
Метка: отмена
 
Строка 1: Строка 1:
--------------------------------------------------------------------------------
local get_args = require('Module:Arguments').getArgs
--                              Module:Hatnote                                --
local mError
--                                                                            --
local yesno = function (v) return require('Module:Yesno')(v, true) end
-- This module produces hatnote links and links to related articles. It      --
-- implements the {{hatnote}} and {{format link}} meta-templates and includes --
-- helper functions for other Lua hatnote modules.                            --
--------------------------------------------------------------------------------


local libraryUtil = require('libraryUtil')
local p, tr = {}, {}
local checkType = libraryUtil.checkType
local current_title = mw.title.getCurrentTitle()
local checkTypeForNamedArg = libraryUtil.checkTypeForNamedArg
local tracking_categories = {
local mArguments -- lazily initialise [[Module:Arguments]]
no_prefix = 'Викимультия:Страницы с модулем Hatnote без указания префикса',
local yesno -- lazily initialise [[Module:Yesno]]
no_links = 'Викимультия:Страницы с модулем Hatnote без ссылок',
local formatLink -- lazily initialise [[Module:Format link]] ._formatLink
red_link = 'Викимультия:Страницы с модулем Hatnote с красной ссылкой',
bad_format = 'Викимультия:Страницы с модулем Hatnote с некорректно заполненными параметрами',
unparsable_link = 'Викимультия:Страницы с модулем Hatnote с нечитаемой ссылкой',
formatted = 'Викимультия:Страницы с модулем Hatnote с готовым форматированием',
}


local p = {}
local function index(t1, t2)
return setmetatable(t1, {__index = t2})
end


--------------------------------------------------------------------------------
local function concat(e1, e2)
-- Helper functions
return tostring(e1) .. tostring(e2)
--------------------------------------------------------------------------------
end


local curNs = mw.title.getCurrentTitle().namespace
function tr.define_categories(tracked_cases)
p.missingTargetCat =
local categories = setmetatable({}, {
--Default missing target category, exported for use in related modules
__tostring = function (self) return table.concat(self) end,
((curNs ==  0) or (curNs == 14)) and
__concat = concat
'Articles with hatnote templates targeting a nonexistent page' or nil
})


local function getArgs(frame)
function categories:add(element, nocat)
-- Fetches the arguments from the parent frame. Whitespace is trimmed and
if not nocat then
-- blanks are removed.
local cat_name
mArguments = require('Module:Arguments')
if tracked_cases and tracked_cases[element] then
return mArguments.getArgs(frame, {parentOnly = true})
cat_name = tracked_cases[element]
else
cat_name = element
end
table.insert(self, string.format('[[Категория:%s]]', cat_name))
end
end
return categories
end
end


local function removeInitialColon(s)
function tr.error(msg, categories, preview_only)
-- Removes the initial colon from a string, if present.
local current_frame = mw.getCurrentFrame()
return s:match('^:?(.*)')
local parent_frame = current_frame:getParent()
local res_frame_title = parent_frame and parent_frame:getTitle() ~= current_title.prefixedText and
parent_frame:getTitle() or
current_frame:getTitle()
if not preview_only or current_frame:preprocess('{{REVISIONID}}') == '' then
mError = require('Module:Error')
return mError.error{
tag = 'div',
string.format('Ошибка в [[%s]]: %s.'
.. (preview_only and '<br><small>Это сообщение показывается только во время предпросмотра.</small>' or ''), res_frame_title, msg)
} .. categories
else
return categories
end
end
end


function p.findNamespaceId(link, removeColon)
function p.parse_link(frame)
-- Finds the namespace id (namespace number) of a link or a pagename. This
local args = get_args(frame)
-- function will not work if the link is enclosed in double brackets. Colons
local link = args[1]:gsub('\n', '')
-- are trimmed from the start of the link by default. To skip colon
local label
-- trimming, set the removeColon parameter to false.
checkType('findNamespaceId', 1, link, 'string')
link = mw.text.trim(link:match('^%[%[([^%]]+)%]%]$') or link)
checkType('findNamespaceId', 2, removeColon, 'boolean', true)
if link:sub(1, 1) == '/' then
if removeColon ~= false then
label = link
link = removeInitialColon(link)
link = current_title.prefixedText .. link
end
end
local namespace = link:match('^(.-):')
link = link:match(':?(.+)')
if namespace then
if link:match('|') then
local nsTable = mw.site.namespaces[namespace]
link, label = link:match('^([^%|]+)%|(.+)$')
if nsTable then
end
return nsTable.id
end
if not mw.title.new(link) then
return nil, nil
end
end
return 0
return link, label
end
end


function p.makeWikitextError(msg, helpLink, addTrackingCategory, title)
function p.format_link(frame)
-- Formats an error message to be returned to wikitext. If
-- {{ссылка на раздел}}
-- addTrackingCategory is not false after being returned from
local args = get_args(frame)
-- [[Module:Yesno]], and if we are not on a talk page, a tracking category
local link, section, label = args[1], args[2], args[3]
-- is added.
checkType('makeWikitextError', 1, msg, 'string')
if not link then
checkType('makeWikitextError', 2, helpLink, 'string', true)
link = current_title.prefixedText
yesno = require('Module:Yesno')
if section then
title = title or mw.title.getCurrentTitle()
link = '#' .. section
-- Make the help link text.
label = label or '§&nbsp;' .. section
local helpText
end
if helpLink then
helpText = ' ([[' .. helpLink .. '|help]])'
else
else
helpText = ''
local parsed_link, parsed_label = p.parse_link{link}
if parsed_link then
link = parsed_link
else
return link
end
if section and not link:match('#') then
link = link .. '#' .. section
if parsed_label then
parsed_label = parsed_label .. '#' .. section
end
end
label = (label or parsed_label or link):gsub('^([^#]-)#(.+)$', '%1 §&nbsp;%2')
end
end
-- Make the category text.
local category
if label and label ~= link then
if not title.isTalkPage -- Don't categorise talk pages
return string.format('[[:%s|%s]]', link, label)
and title.namespace ~= 2 -- Don't categorise userspace
and yesno(addTrackingCategory) ~= false -- Allow opting out
then
category = 'Hatnote templates with errors'
category = mw.ustring.format(
'[[%s:%s]]',
mw.site.namespaces[14].name,
category
)
else
else
category = ''
return string.format('[[:%s]]', link)
end
end
return mw.ustring.format(
'<strong class="error">Error: %s%s.</strong>%s',
msg,
helpText,
category
)
end
end


function p.disambiguate(page, disambiguator)
function p.remove_precision(frame)
-- Formats a page title with a disambiguation parenthetical,
-- {{без уточнения}}
-- i.e. "Example" → "Example (disambiguation)".
local args = get_args(frame)
checkType('disambiguate', 1, page, 'string')
local title = args[1]
checkType('disambiguate', 2, disambiguator, 'string', true)
disambiguator = disambiguator or 'disambiguation'
return title:match('^(.+)%s+%b()$') or title
return mw.ustring.format('%s (%s)', page, disambiguator)
end
 
function p.is_disambig(frame)
local args = get_args(frame)
local title = args[1]
local page = mw.title.new(title)
if not page or not page.exists or mw.title.equals(page, current_title) then
return false
end
local page_content = page:getContent()
local mw_list_content = mw.title.new('MediaWiki:Disambiguationspage'):getContent()
local lang = mw.language.getContentLanguage()
for template in mw.ustring.gmatch(mw_list_content, '%*%s?%[%[Шаблон:([^%]]+)') do
if page_content:match('{{' .. template) or page_content:match('{{' .. lang:lcfirst(template)) then
return true
end
end
return false
end
end


--------------------------------------------------------------------------------
function p.list(frame)
-- Hatnote
local args = get_args(frame, {trim = false})
--
local list_sep = args.list_sep or args['разделитель списка'] or ', '
-- Produces standard hatnote text. Implements the {{hatnote}} template.
local last_list_sep = yesno(args.natural_join) ~= false and ' и ' or list_sep
--------------------------------------------------------------------------------
local links_ns = args.links_ns or args['ПИ ссылок']
local bold_links = yesno(args.bold_links or args['ссылки болдом'])


function p.hatnote(frame)
local res_list = {}
local args = getArgs(frame)
local tracked = {
local s = args[1]
red_link = false,
if not s then
bad_format = false,
return p.makeWikitextError(
formatted = false,
'no text specified',
unparsable_link = false
'Template:Hatnote#Errors',
}
args.category
)
local i = 1
while args[i] do
local link = args[i]
local label = args['l' .. i]
local element = ''
if link:match('<span') then -- TODO: переписать
tracked.formatted = true
element = link -- for {{не переведено}}
else
local bad_format = (link:match('|') or link:match('[%[%]]')) ~= nil
local parsed_link, parsed_label = p.parse_link{link}
if parsed_link then
tracked.bad_format = tracked.bad_format or bad_format
if links_ns then
parsed_label = parsed_label or parsed_link
parsed_link = mw.site.namespaces[links_ns].name .. ':' .. parsed_link
end
local title = mw.title.new(parsed_link)
tracked.red_link = tracked.red_link or not (title.isExternal or title.exists)
element = p.format_link{parsed_link, nil, label or parsed_label}
else
tracked.unparsable_link = true
element = link
end
end
if bold_links then
element = string.format('<b>%s</b>', element)
end
table.insert(res_list, element)
i = i + 1
end
end
return p._hatnote(s, {
extraclasses = args.extraclasses,
return setmetatable(res_list, {
selfref = args.selfref
__index = tracked,
__tostring = function (self) return mw.text.listToText(self, list_sep, last_list_sep) end,
__concat = concat,
__pairs = function (self) return pairs(tracked) end
})
})
end
end


function p._hatnote(s, options)
function p.hatnote(frame)
checkType('_hatnote', 1, s, 'string')
local args = get_args(frame)
checkType('_hatnote', 2, options, 'table', true)
local text = args[1]
options = options or {}
local id = args.id
local inline = options.inline
local extraclasses = args.extraclasses
local hatnote = mw.html.create(inline == 1 and 'span' or 'div')
local hide_disambig = yesno(args.hide_disambig)
local extraclasses
if type(options.extraclasses) == 'string' then
local res = mw.html.create('div')
extraclasses = options.extraclasses
:attr('id', id)
:addClass('hatnote')
:addClass('navigation-not-searchable')
:addClass(extraclasses)
:wikitext(text)
if hide_disambig then
res:addClass('dabhide')
end
end
return res
end


hatnote
function p.main(frame, _tracking_categories)
:attr('role', 'note')
local args = get_args(frame, {trim = false})
:addClass(inline == 1 and 'hatnote-inline' or 'hatnote')
:addClass('navigation-not-searchable')
local prefix = args.prefix or args['префикс']
:addClass(extraclasses)
local prefix_plural = args.prefix_plural or args['префикс мн. ч.']
:addClass(options.selfref and 'selfref')
local sep = args.sep or args['разделитель'] or ' '
:wikitext(s)
local dot = yesno(args.dot or args['точка']) and '.' or ''
local nocat = yesno(args.nocat)
local preview_error = yesno(args.preview_error)
local empty_list_message = args.empty_list_message or 'Не указано ни одной страницы'
categories = tr.define_categories(index(_tracking_categories or {}, tracking_categories))
 
if not prefix then
categories:add('no_prefix', nocat)
return tr.error('Не указан префикс', categories)
end
if not args[1] then
categories:add('no_links', nocat)
return tr.error(empty_list_message, categories, preview_error)
end
if args[2] and prefix_plural then
prefix = prefix_plural
end
local list = p.list(args)
for k, v in pairs(list) do
if type(v) == 'boolean' and v then
categories:add(k, nocat)
end
end
return mw.getCurrentFrame():extensionTag{
return p.hatnote(index({prefix .. sep .. list .. dot}, args)) .. categories
name = 'templatestyles', args = { src = 'Module:Hatnote/styles.css' }
} .. tostring(hatnote)
end
end


return p
return index(p, tr)

Текущая версия от 01:50, 4 мая 2022


Документация
local get_args = require('Module:Arguments').getArgs
local mError
local yesno = function (v) return require('Module:Yesno')(v, true) end

local p, tr = {}, {}
local current_title = mw.title.getCurrentTitle()
local tracking_categories = {
	no_prefix = 'Викимультия:Страницы с модулем Hatnote без указания префикса',
	no_links = 'Викимультия:Страницы с модулем Hatnote без ссылок',
	red_link = 'Викимультия:Страницы с модулем Hatnote с красной ссылкой',
	bad_format = 'Викимультия:Страницы с модулем Hatnote с некорректно заполненными параметрами',
	unparsable_link = 'Викимультия:Страницы с модулем Hatnote с нечитаемой ссылкой',
	formatted = 'Викимультия:Страницы с модулем Hatnote с готовым форматированием',
}

local function index(t1, t2)
	return setmetatable(t1, {__index = t2})
end

local function concat(e1, e2) 
	return tostring(e1) .. tostring(e2)
end

function tr.define_categories(tracked_cases)
	local categories = setmetatable({}, {
		__tostring = function (self) return table.concat(self) end, 
		__concat = concat
	})

	function categories:add(element, nocat)
		if not nocat then
			local cat_name
			if tracked_cases and tracked_cases[element] then
				cat_name = tracked_cases[element]
			else
				cat_name = element
			end
			table.insert(self, string.format('[[Категория:%s]]', cat_name))
		end
	end
	
	return categories
end

function tr.error(msg, categories, preview_only)
	local current_frame = mw.getCurrentFrame()
	local parent_frame = current_frame:getParent()
	local res_frame_title = parent_frame and parent_frame:getTitle() ~= current_title.prefixedText and
		parent_frame:getTitle() or
		current_frame:getTitle()
	if not preview_only or current_frame:preprocess('{{REVISIONID}}') == '' then
		mError = require('Module:Error')
		return mError.error{
			tag = 'div',
			string.format('Ошибка в [[%s]]: %s.' 
				.. (preview_only and '<br><small>Это сообщение показывается только во время предпросмотра.</small>' or ''), res_frame_title, msg)
		} .. categories
	else 
		return categories
	end
end

function p.parse_link(frame)
	local args = get_args(frame)
	local link = args[1]:gsub('\n', '')
	local label
	
	link = mw.text.trim(link:match('^%[%[([^%]]+)%]%]$') or link)
	if link:sub(1, 1) == '/' then
		label = link
		link = current_title.prefixedText .. link
	end
	link = link:match(':?(.+)')
	if link:match('|') then
		link, label = link:match('^([^%|]+)%|(.+)$')
	end
	
	if not mw.title.new(link) then
		return nil, nil
	end
	
	return link, label
end

function p.format_link(frame)
	-- {{ссылка на раздел}}
	local args = get_args(frame)
	local link, section, label = args[1], args[2], args[3]
	
	if not link then
		link = current_title.prefixedText
		if section then
			link = '#' .. section
			label = label or '§ ' .. section
		end
	else
		local parsed_link, parsed_label = p.parse_link{link}
		if parsed_link then
			link = parsed_link
		else
			return link
		end
		if section and not link:match('#') then
			link = link .. '#' .. section
			if parsed_label then
				parsed_label = parsed_label .. '#' .. section
			end
		end
		
		label = (label or parsed_label or link):gsub('^([^#]-)#(.+)$', '%1 § %2')
	end
	
	if label and label ~= link then
		return string.format('[[:%s|%s]]', link, label)
	else
		return string.format('[[:%s]]', link)
	end
end

function p.remove_precision(frame)
	-- {{без уточнения}}
	local args = get_args(frame)
	local title = args[1]
	
	return title:match('^(.+)%s+%b()$') or title
end

function p.is_disambig(frame)
	local args = get_args(frame)
	local title = args[1]
	local page = mw.title.new(title)
	
	if not page or not page.exists or mw.title.equals(page, current_title) then
		return false
	end
	
	local page_content = page:getContent()
	local mw_list_content = mw.title.new('MediaWiki:Disambiguationspage'):getContent()
	local lang = mw.language.getContentLanguage()
	for template in mw.ustring.gmatch(mw_list_content, '%*%s?%[%[Шаблон:([^%]]+)') do
		if page_content:match('{{' .. template) or page_content:match('{{' .. lang:lcfirst(template)) then 
			return true
		end
	end
	return false
end

function p.list(frame)
	local args = get_args(frame, {trim = false})
	local list_sep = args.list_sep or args['разделитель списка'] or ', '
	local last_list_sep = yesno(args.natural_join) ~= false and ' и ' or list_sep
	local links_ns = args.links_ns or args['ПИ ссылок']
	local bold_links = yesno(args.bold_links or args['ссылки болдом'])

	local res_list = {}
	local tracked = {
		red_link = false,
		bad_format = false,
		formatted = false,
		unparsable_link = false
	}
	
	local i = 1
	while args[i] do
		local link = args[i]
		local label = args['l' .. i]
		
		local element = ''
		if link:match('<span') then -- TODO: переписать
			tracked.formatted = true
			element = link -- for {{не переведено}}
		else
			local bad_format = (link:match('|') or link:match('[%[%]]')) ~= nil
			local parsed_link, parsed_label = p.parse_link{link}
			
			if parsed_link then
				tracked.bad_format = tracked.bad_format or bad_format
				if links_ns then
					parsed_label = parsed_label or parsed_link
					parsed_link = mw.site.namespaces[links_ns].name .. ':' .. parsed_link
				end
			
				local title = mw.title.new(parsed_link)
				tracked.red_link = tracked.red_link or not (title.isExternal or title.exists)
				element = p.format_link{parsed_link, nil, label or parsed_label}
			else
				tracked.unparsable_link = true
				element = link
			end
		end
		
		if bold_links then
			element = string.format('<b>%s</b>', element)
		end
		
		table.insert(res_list, element)
		i = i + 1
	end
	
	return setmetatable(res_list, {
		__index = tracked,
		__tostring = function (self) return mw.text.listToText(self, list_sep, last_list_sep) end,
		__concat = concat,
		__pairs = function (self) return pairs(tracked) end
	})
end

function p.hatnote(frame)
	local args = get_args(frame)
	local text = args[1]
	local id = args.id
	local extraclasses = args.extraclasses
	local hide_disambig = yesno(args.hide_disambig)
	
	local res = mw.html.create('div')
		:attr('id', id)
		:addClass('hatnote')
		:addClass('navigation-not-searchable')
		:addClass(extraclasses)
		:wikitext(text)
	
	if hide_disambig then
		res:addClass('dabhide')
	end
	
	return res
end

function p.main(frame, _tracking_categories)
	local args = get_args(frame, {trim = false})
	
	local prefix = args.prefix or args['префикс']
	local prefix_plural = args.prefix_plural or args['префикс мн. ч.']
	local sep = args.sep or args['разделитель'] or ' '
	local dot = yesno(args.dot or args['точка']) and '.' or ''
	local nocat = yesno(args.nocat)
	local preview_error = yesno(args.preview_error)
	local empty_list_message = args.empty_list_message or 'Не указано ни одной страницы'
	
	categories = tr.define_categories(index(_tracking_categories or {}, tracking_categories))

	if not prefix then
		categories:add('no_prefix', nocat)
		return tr.error('Не указан префикс', categories)
	end
	if not args[1] then
		categories:add('no_links', nocat)
		return tr.error(empty_list_message, categories, preview_error)
	end
	
	if args[2] and prefix_plural then
		prefix = prefix_plural
	end
	
	local list = p.list(args)
	
	for k, v in pairs(list) do
		if type(v) == 'boolean' and v then
			categories:add(k, nocat)
		end
	end
	
	return p.hatnote(index({prefix .. sep .. list .. dot}, args)) .. categories
end

return index(p, tr)