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

Lua модуль из Wikimeat
(Новая страница: «local get_args = require('Module:Arguments').getArgs local mError = require('Module:Error') local yesno = function (v) return require('Module:Yesno')(v, true) end...»)
 
мНет описания правки
 
Строка 1: Строка 1:
local get_args = require('Module:Arguments').getArgs
--------------------------------------------------------------------------------
local mError = require('Module:Error')
--                              Module:Hatnote                                --
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 p, tr = {}, {}
local libraryUtil = require('libraryUtil')
local current_title = mw.title.getCurrentTitle()
local checkType = libraryUtil.checkType
local tracking_categories = {
local mArguments -- lazily initialise [[Module:Arguments]]
no_prefix = 'Википедия:Страницы с модулем Hatnote без указания префикса',
local yesno -- lazily initialise [[Module:Yesno]]
no_links = 'Википедия:Страницы с модулем Hatnote без ссылок',
red_link = 'Википедия:Страницы с модулем Hatnote с красной ссылкой',
bad_format = 'Википедия:Страницы с модулем Hatnote с некорректно заполненными параметрами',
formatted = 'Википедия:Страницы с модулем Hatnote с готовым форматированиеми',
}


local function index(t1, t2)
local p = {}
return setmetatable(t1, {__index = t2})
 
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
 
local function getArgs(frame)
-- Fetches the arguments from the parent frame. Whitespace is trimmed and
-- blanks are removed.
mArguments = require('Module:Arguments')
return mArguments.getArgs(frame, {parentOnly = true})
end
end


local function concat(e1, e2)
local function removeInitialColon(s)
return tostring(e1) .. tostring(e2)
-- Removes the initial colon from a string, if present.
return s:match('^:?(.*)')
end
end


function tr.make_categories(tracking_categories)
function p.findNamespaceId(link, removeColon)
local categories = setmetatable({}, {
-- Finds the namespace id (namespace number) of a link or a pagename. This
__tostring = function (self) return table.concat(self) end,
-- function will not work if the link is enclosed in double brackets. Colons
__concat = concat
-- are trimmed from the start of the link by default. To skip colon
})
-- trimming, set the removeColon parameter to false.
checkType('findNamespaceId', 1, link, 'string')
function categories:add(type, nocat)
checkType('findNamespaceId', 2, removeColon, 'boolean', true)
if not nocat then
if removeColon ~= false then
table.insert(self, string.format('[[Категория:%s]]', tracking_categories[type]))
link = removeInitialColon(link)
end
local namespace = link:match('^(.-):')
if namespace then
local nsTable = mw.site.namespaces[namespace]
if nsTable then
return nsTable.id
end
end
end
end
return 0
return categories
end
end


function tr.error(msg, categories, preview_only)
function p.formatPages(...)
local current_frame = mw.getCurrentFrame()
-- Formats a list of pages using formatLink and returns it as an array. Nil
local parent_frame = current_frame:getParent()
-- values are not allowed.
local res_frame_title = parent_frame and parent_frame:getTitle() ~= current_title.prefixedText and
local pages = {...}
parent_frame:getTitle() or
local ret = {}
current_frame:getTitle()
for i, page in ipairs(pages) do
if not preview_only or current_frame:preprocess('{{REVISIONID}}') == '' then
ret[i] = p._formatLink(page)
return mError.error{string.format('Ошибка в [[%s]]: %s', res_frame_title, msg)} .. categories
else
return categories
end
end
return ret
end
end


local function parse_link(link, label)
function p.formatPageTables(...)
link = link:gsub('\n', '')
-- Takes a list of page/display tables and returns it as a list of
link = link:match('%[%[:?([^%]]+)%]%]') or link:match(':?(.+)')
-- formatted links. Nil values are not allowed.
if link:match('|') then
local pages = {...}
link, label = link:match('^([^%|]+)%|(.+)$')
local links = {}
for i, t in ipairs(pages) do
checkType('formatPageTables', i, t, 'table')
local link = t[1]
local display = t[2]
links[i] = p._formatLink(link, display)
end
end
return links
return link, label
end
end


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


function p.remove_precision(frame)
function p.disambiguate(page, disambiguator)
-- {{без уточнения}}
-- Formats a page title with a disambiguation parenthetical,
local args = get_args(frame)
-- i.e. "Example" → "Example (disambiguation)".
local title = args[1]
checkType('disambiguate', 1, page, 'string')
checkType('disambiguate', 2, disambiguator, 'string', true)
return title:match('^(.+)%s+%b()$') or title
disambiguator = disambiguator or 'disambiguation'
return string.format('%s (%s)', page, disambiguator)
end
end


function p.is_disambig(frame)
--------------------------------------------------------------------------------
local args = get_args(frame)
-- Format link
local title = args[1]
--
local page = mw.title.new(title)
-- Makes a wikilink from the given link and display values. Links are escaped
-- with colons if necessary, and links to sections are detected and displayed
if not page.exists or mw.title.equals(page, current_title) then
-- with " § " as a separator rather than the standard MediaWiki "#". Used in
return false
-- the {{format hatnote link}} template.
end
--------------------------------------------------------------------------------
 
local page_content = page:getContent()
function p.formatLink(frame)
local mw_list_content = mw.title.new('MediaWiki:Disambiguationspage'):getContent()
local args = getArgs(frame)
local lang = mw.language.getContentLanguage()
local link = args[1]
for template in mw.ustring.gmatch(mw_list_content, '%*%s?%[%[Шаблон:([^%]]+)') do
local display = args[2]
if page_content:match('{{' .. template) or page_content:match('{{' .. lang:lcfirst(template)) then
if not link then
return true
return p.makeWikitextError(
end
'no link specified',
'Template:Format hatnote link#Errors',
args.category
)
end
end
return false
return p._formatLink(link, display)
end
end


function p.list(frame)
function p._formatLink(link, display)
local args = get_args(frame, {trim = false})
checkType('_formatLink', 1, link, 'string')
local list_sep = args.list_sep or args['разделитель списка'] or ', '
checkType('_formatLink', 2, display, 'string', true)
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 = {}
-- Remove the initial colon for links where it was specified manually.
local tracked = {
link = removeInitialColon(link)
red_link = false,
 
bad_format = false,
-- Find whether a faux display value has been added with the {{!}} magic
formatted = false,
-- word.
}
if not display then
local prePipe, postPipe = link:match('^(.-)|(.*)$')
local i = 1
link = prePipe or link
while args[i] do
display = postPipe
local link = args[i]
end
local label = args['l' .. i]
 
-- Find the display value.
local element = ''
if not display then
if link:match('<span') then -- TODO: переписать
local page, section = link:match('^(.-)#(.*)$')
tracked.formatted = true
if page then
element = link -- for {{не переведено}}
display = page .. ' §&nbsp;' .. section
else
tracked.bad_format = tracked.bad_format or link:match('|') or link:match('[%[%]]')
link, label = parse_link(link, label)
if links_ns then
label = label or link
link = mw.site.namespaces[links_ns].name .. ':' .. link
end
tracked.red_link = tracked.red_link or not mw.title.new(link).exists
element = p.format_link{link, nil, label}
end
end
if bold_links then
element = string.format('<b>%s</b>', element)
end
table.insert(res_list, element)
i = i + 1
end
end
 
local res = mw.text.listToText(res_list, list_sep, last_list_sep)
-- Assemble the link.
if display then
return setmetatable({res}, {
return string.format(
__index = tracked,
'[[:%s|%s]]',
__tostring = function (self) return self[1] end,
string.gsub(link, '|(.*)$', ''), --display overwrites manual piping
__concat = concat
display
})
)
else
return string.format('[[:%s]]', link)
end
end
end
--------------------------------------------------------------------------------
-- Hatnote
--
-- Produces standard hatnote text. Implements the {{hatnote}} template.
--------------------------------------------------------------------------------


function p.hatnote(frame)
function p.hatnote(frame)
local args = get_args(frame)
local args = getArgs(frame)
local text = args[1]
local s = args[1]
local extraclasses = args.extraclasses
local options = {}
local hide_disambig = yesno(args.hide_disambig)
if not s then
return p.makeWikitextError(
local res = mw.html.create('div')
'no text specified',
:addClass('hatnote')
'Template:Hatnote#Errors',
:addClass(extraclasses)
args.category
:wikitext(text)
)
if hide_disambig then
res:addClass('dabhide')
end
end
options.extraclasses = args.extraclasses
return res
options.selfref = args.selfref
return p._hatnote(s, options)
end
end


function p.main(frame, _tracking_categories)
function p._hatnote(s, options)
local args = get_args(frame, {trim = false})
checkType('_hatnote', 1, s, 'string')
checkType('_hatnote', 2, options, 'table', true)
local prefix = args.prefix or args['префикс']
options = options or {}
local prefix_plural = args.prefix_plural or args['префикс мн. ч.']
local classes = {'hatnote-container', 'navigation-not-searchable'}
local sep = args.sep or args['разделитель'] or ' '
local extraclasses = options.extraclasses
local dot = yesno(args.dot or args['точка']) and '.' or ''
local selfref = options.selfref
local nocat = yesno(args.nocat)
if type(extraclasses) == 'string' then
local preview_error = yesno(args.preview_error)
classes[#classes + 1] = extraclasses
categories = tr.make_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('Не указано ни одной страницы', categories, preview_error)
end
if args[2] and prefix_plural then
prefix = prefix_plural
end
local list = p.list(args)
if list.red_link then
categories:add('red_link', nocat)
end
if list.bad_format then
categories:add('bad_format', nocat)
end
end
if list.formatted then
if selfref then
categories:add('formatted', nocat)
classes[#classes + 1] = 'selfref'
end
end
return string.format(
return p.hatnote(index({prefix .. sep .. list .. dot}, args)) .. categories
'<div class="%s">%s</div>',
table.concat(classes, ' '),
s
)
end
end


return index(p, tr)
return p

Текущая версия от 02:04, 26 ноября 2021

Эта документация включена из Модуль:Hatnote/doc. Изменения можно предлагать на странице обсуждения.

Module:Hatnote — это метамодуль, предоставляющий различные функции для создания шапок. Он реализует шаблон {{hatnote}} для использования в хэтноут-заметках в верхней части страниц и шаблон {{format link}}, который используется для форматирования вики-ссылки для использования в хэтноут-заметках. Он также содержит ряд вспомогательных функций для использования в других модулях заметок Lua.


--------------------------------------------------------------------------------
--                              Module:Hatnote                                --
--                                                                            --
-- 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 checkType = libraryUtil.checkType
local mArguments -- lazily initialise [[Module:Arguments]]
local yesno -- lazily initialise [[Module:Yesno]]

local p = {}

--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------

local function getArgs(frame)
	-- Fetches the arguments from the parent frame. Whitespace is trimmed and
	-- blanks are removed.
	mArguments = require('Module:Arguments')
	return mArguments.getArgs(frame, {parentOnly = true})
end

local function removeInitialColon(s)
	-- Removes the initial colon from a string, if present.
	return s:match('^:?(.*)')
end

function p.findNamespaceId(link, removeColon)
	-- Finds the namespace id (namespace number) of a link or a pagename. This
	-- function will not work if the link is enclosed in double brackets. Colons
	-- are trimmed from the start of the link by default. To skip colon
	-- trimming, set the removeColon parameter to false.
	checkType('findNamespaceId', 1, link, 'string')
	checkType('findNamespaceId', 2, removeColon, 'boolean', true)
	if removeColon ~= false then
		link = removeInitialColon(link)
	end
	local namespace = link:match('^(.-):')
	if namespace then
		local nsTable = mw.site.namespaces[namespace]
		if nsTable then
			return nsTable.id
		end
	end
	return 0
end

function p.formatPages(...)
	-- Formats a list of pages using formatLink and returns it as an array. Nil
	-- values are not allowed.
	local pages = {...}
	local ret = {}
	for i, page in ipairs(pages) do
		ret[i] = p._formatLink(page)
	end
	return ret
end

function p.formatPageTables(...)
	-- Takes a list of page/display tables and returns it as a list of
	-- formatted links. Nil values are not allowed.
	local pages = {...}
	local links = {}
	for i, t in ipairs(pages) do
		checkType('formatPageTables', i, t, 'table')
		local link = t[1]
		local display = t[2]
		links[i] = p._formatLink(link, display)
	end
	return links
end

function p.makeWikitextError(msg, helpLink, addTrackingCategory, title)
	-- Formats an error message to be returned to wikitext. If
	-- addTrackingCategory is not false after being returned from
	-- [[Module:Yesno]], and if we are not on a talk page, a tracking category
	-- is added.
	checkType('makeWikitextError', 1, msg, 'string')
	checkType('makeWikitextError', 2, helpLink, 'string', true)
	yesno = require('Module:Yesno')
	title = title or mw.title.getCurrentTitle()
	-- Make the help link text.
	local helpText
	if helpLink then
		helpText = ' ([[' .. helpLink .. '|help]])'
	else
		helpText = ''
	end
	-- Make the category text.
	local category
	if not title.isTalkPage and yesno(addTrackingCategory) ~= false then
		category = 'Hatnote templates with errors'
		category = string.format(
			'[[%s:%s]]',
			mw.site.namespaces[14].name,
			category
		)
	else
		category = ''
	end
	return string.format(
		'<strong class="error">Error: %s%s.</strong>%s',
		msg,
		helpText,
		category
	)
end

function p.disambiguate(page, disambiguator)
	-- Formats a page title with a disambiguation parenthetical,
	-- i.e. "Example" → "Example (disambiguation)".
	checkType('disambiguate', 1, page, 'string')
	checkType('disambiguate', 2, disambiguator, 'string', true)
	disambiguator = disambiguator or 'disambiguation'
	return string.format('%s (%s)', page, disambiguator)
end

--------------------------------------------------------------------------------
-- Format link
--
-- Makes a wikilink from the given link and display values. Links are escaped
-- with colons if necessary, and links to sections are detected and displayed
-- with " § " as a separator rather than the standard MediaWiki "#". Used in
-- the {{format hatnote link}} template.
--------------------------------------------------------------------------------

function p.formatLink(frame)
	local args = getArgs(frame)
	local link = args[1]
	local display = args[2]
	if not link then
		return p.makeWikitextError(
			'no link specified',
			'Template:Format hatnote link#Errors',
			args.category
		)
	end
	return p._formatLink(link, display)
end

function p._formatLink(link, display)
	checkType('_formatLink', 1, link, 'string')
	checkType('_formatLink', 2, display, 'string', true)

	-- Remove the initial colon for links where it was specified manually.
	link = removeInitialColon(link)

	-- Find whether a faux display value has been added with the {{!}} magic
	-- word.
	if not display then
		local prePipe, postPipe = link:match('^(.-)|(.*)$')
		link = prePipe or link
		display = postPipe
	end

	-- Find the display value.
	if not display then
		local page, section = link:match('^(.-)#(.*)$')
		if page then
			display = page .. ' §&nbsp;' .. section
		end
	end

	-- Assemble the link.
	if display then
		return string.format(
			'[[:%s|%s]]',
			string.gsub(link, '|(.*)$', ''), --display overwrites manual piping
			display
		)
	else
		return string.format('[[:%s]]', link)
	end
end

--------------------------------------------------------------------------------
-- Hatnote
--
-- Produces standard hatnote text. Implements the {{hatnote}} template.
--------------------------------------------------------------------------------

function p.hatnote(frame)
	local args = getArgs(frame)
	local s = args[1]
	local options = {}
	if not s then
		return p.makeWikitextError(
			'no text specified',
			'Template:Hatnote#Errors',
			args.category
		)
	end
	options.extraclasses = args.extraclasses
	options.selfref = args.selfref
	return p._hatnote(s, options)
end

function p._hatnote(s, options)
	checkType('_hatnote', 1, s, 'string')
	checkType('_hatnote', 2, options, 'table', true)
	options = options or {}
	local classes = {'hatnote-container', 'navigation-not-searchable'}
	local extraclasses = options.extraclasses
	local selfref = options.selfref
	if type(extraclasses) == 'string' then
		classes[#classes + 1] = extraclasses
	end
	if selfref then
		classes[#classes + 1] = 'selfref'
	end
	return string.format(
		'<div class="%s">%s</div>',
		table.concat(classes, ' '),
		s
	)
end

return p
🍪 Наш веб-сайт использует файлы cookie для того, чтобы сделать ваш опыт использования сайта лучше и анализа использования сайта