Перейти до вмісту

Модуль:Hatnote

Матеріал з Вікіпедії — вільної енциклопедії.
{{i}} Документація модуля[перегляд] [редагувати] [історія] [очистити кеш]

Це метамодуль, що надає різні функції для створення верхніх приміток. Він впроваджує шаблон {{hatnote}}, який використовується у верхніх примітках вгорі сторінок. Він також містить кілька допоміжних функцій для використання в інших модулях Lua верхніх приміток.

Використання у вікітексті

Функції в цьому модулі не можна викликати напряму з #invoke та натомість повинні використовуватися через шаблони. Щодо документації, див. Шаблон:Hatnote.

Використання в інших модулях Lua

Щоб завантажити цей модуль в іншому модулі Lua, використайте наступний код.

local mHatnote = require('Module:Hatnote')

Тоді ви можете використати функції як документовано нижче.

Hatnote

mHatnote._hatnote(s, options)

Оформлює рядок s як верхню примітку. Це огортає s в теги <div class="hatnote">...</div>. Опції вказуються в таблиці options. Опції включають:

  • options.extraclasses — рядок з вказаними додатковими класами
  • options.selfref — якщо значення не є nil або false, то додає клас «selfref», що вказує на самопосилання на Вікіпедію (див. Шаблон:Selfref))
  • options.show_icon — якщо значення не є nil або false, то додає клас «dablink», що верхня примітка є посилання на сторінку значень, а тому додається іконка

CSS класу hatnote визначено в Модуль:Hatnote/styles.css.

Приклад 1
mHatnote._hatnote('This is a hatnote.')

Створює: <div class="hatnote">Це верхня примітка.</div>

Відображається як:

Приклад 2
mHatnote._hatnote('This is a hatnote.', {extraclasses = 'boilerplate seealso', show_icon=yes, selfref = true})

Створює: <div class="hatnote boilerplate seealso selfref">Це верхня примітка.</div>

Відображається як:

Приклад 3
mHatnote._hatnote('This is a hatnote.', {extraclasses = 'boilerplate seealso', selfref = true})

Створює: <div class="hatnote dablink boilerplate seealso selfref">Це верхня примітка.</div>

Відображається як:

Find namespace id

mHatnote.findNamespaceId(link, removeColon)

Шукає ідентифікатор простору назв рядка link, який повинен мати дійсну назву сторінки з або без назви розділу. Ця функція не працюватиме, якщо назва сторінки огорнуто у квадратні дужки. Коли вона намагається парсувати назву простору назв, то по стандарту двокрапка видаляється з початку посилання. Це корисно, коли користувачі вказали двокрапки, чиє використання не є обов'язковим. Якщо вам не потрібна перевірка на двокрапки на початку, то встановіть значення false параметру removeColon.

Приклади
mHatnote.findNamespaceId('Лев') → 0
mHatnote.findNamespaceId('Категорія:Леви') → 14
mHatnote.findNamespaceId(':Категорія:Леви') → 14
mHatnote.findNamespaceId(':Категорія:Леви', false) → 0 (простір назв визначено як «:Категорія», а не «Категорія»)

Make wikitext error

mHatnote.makeWikitextError(msg, helpLink, addTrackingCategory)

Оформлює рядок msg як червоне повідомлення про помилку, з допоміжним посиланням на сторінку довідки helpLink. Зазвичай, ця функція також додає К:Hatnote templates with errors (0). Щоб вимкнути категоризацію, передайте false як третій параметр функції (addTrackingCategory).

Приклади:

mHatnote.makeWikitextError('виникла помилка')Помилка: виникла помилка.
mHatnote.makeWikitextError('виникла помилка', 'Шаблон:Example#Помилки')Помилка: виникла помилка (довідка).

Приклади

Щодо прикладів як цей модуль може використовуватися в інших модулях Lua, див. Module:Labelled list hatnote.

local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType
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 removeInitialColon(s)
	-- Removes the initial colon from a string, if present.
	return s:match('^:?(.*)')
end
	
function p.defaultClasses(inline)
	-- Provides the default hatnote classes as a space-separated string; useful
	-- for hatnote-manipulation modules like [[Module:Hatnote group]].
	return
		(inline == 1 and 'hatnote-inline' or 'hatnote') .. ' ' ..
		'navigation-not-searchable'
end	

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

--------------------------------------------------------------------------------
-- Функція для Hatnote list за кодом з англвікі
--------------------------------------------------------------------------------

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 'значення'
	return mw.ustring.format('%s (%s)', page, disambiguator)
end

--------------------------------------------------------------------------------
-- Функція для Labelled list hatnote за кодом з англвікі
--------------------------------------------------------------------------------

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.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 .. '|довідка]])'
	else
		helpText = ''
	end
	-- Make the category text.
	local category
	if not title.isTalkPage -- Don't categorise talk pages
		and title.namespace ~= 2 -- Don't categorise userspace
		and yesno(addTrackingCategory) ~= false -- Allow opting out
	then
		category = 'Шаблони верхніх приміток із помилками'
		category = mw.ustring.format(
			'[[%s:%s]]',
			mw.site.namespaces[14].name,
			category
		)
	else
		category = ''
	end
	return mw.ustring.format(
		'<strong class="error">Помилка: %s%s.</strong>%s',
		msg,
		helpText,
		category
	)
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 '§&nbsp;' .. 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 §&nbsp;%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(s, options)
	checkType('_hatnote', 1, s, 'string')
	checkType('_hatnote', 2, options, 'table', true)
	options = options or {}
	local id = options.id
	local inline = options.inline
	local extraclasses = options.extraclasses
	local show_icon = yesno(options.show_icon)
	local hide_disambig = yesno(options.hide_disambig)
	
	local res = mw.html.create(inline == 1 and 'span' or 'div')
		:attr('id', id)
		:addClass(p.defaultClasses(inline))
		:addClass(show_icon and 'dablink' or nil)
		:addClass(extraclasses)
		:addClass(options.selfref and 'selfref' or nil)
		:wikitext(s)
	
	if hide_disambig then
		res:addClass('dabhide')
	end
	
	return mw.getCurrentFrame():extensionTag{
		name = 'templatestyles', args = { src = 'Module:Hatnote/styles.css' }
	} .. tostring(res)
end

--------------------------------------------------------------------------------
-- Функція для виклику коду з англвікі та місце виклику українського шаблону Hatnote
--------------------------------------------------------------------------------

function p.hatnote(frame)
	local args = get_args(frame)
	local s = args[1]
	if not s then
		return p.makeWikitextError(
			'текст не зазначено',
			'Шаблон:Hatnote#Помилки',
			args.category
		)
	end
	return p._hatnote(s, {
		extraclasses = args.extraclasses,
		selfref = args.selfref,
		show_icon = args.show_icon or args['показати_іконку']
	})
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(prefix .. sep .. list .. dot, args) .. categories
end

return index(p, tr)