Модуль:Надстрочное предупреждение: различия между версиями

Материал из in.wiki
Перейти к навигации Перейти к поиску
(обратная логика)
(упрощение обработки комментариев)
Строка 39: Строка 39:
 
end
 
end
  
-- Форматирование даты как в шаблоне
+
-- Форматирование комментария как в шаблоне
local function getDate( date )
+
local function getComment( comment, link, date )
if isEmpty( date ) then
+
if isEmpty( comment ) and isEmpty( date ) then
return ''
+
return nil
 +
end
 +
 +
-- «Википедия:Нейтральная точка зрения (2 мая 2015)»
 +
if isEmpty( comment ) and not isEmpty( date ) then
 +
comment = link
 +
end
 +
 +
if isEmpty( comment ) then
 +
return nil
 +
end
 +
 +
local delink = require( 'Module:Delink' )._delink
 +
comment = delink( { comment } )
 +
 +
if not isEmpty( date ) then
 +
comment = comment .. mwLang:formatDate( ' (j xg Y)', date )
 
end
 
end
 
 
return mwLang:formatDate( ' (j xg Y)', date )
+
return comment
 
end
 
end
  
-- Форматирование ссылок как в шаблоне
+
-- Форматирование ссылки как в шаблоне
local function getLink( link, text, comment, hasComment )
+
local function getLink( link, text, comment, hasCustomComment )
 
if isEmpty( link ) then
 
if isEmpty( link ) then
 
return text
 
return text
Строка 55: Строка 71:
 
 
 
if not isEmpty( comment ) then
 
if not isEmpty( comment ) then
local delink = require( 'Module:Delink' )._delink
+
local html = mw.html.create( 'span' )
comment = delink( { comment } )
+
:attr( 'title', comment )
if comment then
+
:wikitext( text )
local html = mw.html.create( 'span' )
 
:attr( 'title', comment )
 
:wikitext( text )
 
 
 
if hasComment then
+
if hasCustomComment then
html:attr( 'style', 'border-bottom:1px dotted;' )
+
html:attr( 'style', 'border-bottom:1px dotted;' )
end
 
 
text = tostring( html )
 
 
end
 
end
 +
 +
text = tostring( html )
 
end
 
end
 
 
Строка 182: Строка 194:
 
 
 
-- Поддержка параметра {{{comment|}}}
 
-- Поддержка параметра {{{comment|}}}
local comment = args.comment or args[ 'comment-default' ] or args.link
+
local comment = getComment( args.comment or args[ 'comment-default' ], args.link, date )
if not isEmpty( comment ) then
 
comment = comment .. getDate( date )
 
end
 
 
 
 
tag
 
tag

Версия от 18:33, 16 мая 2023

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

require( 'strict' )
local p = {}

local docPage = 'Шаблон:Надстрочное предупреждение'

local mwLang = mw.getContentLanguage()
local getArgs = require( 'Module:Arguments' ).getArgs

local function isEmpty( val )
	return val == nil or val == ''
end

-- Игнорирование некорректно указанных дат с помощью стандартных методов
local function getValidDate( year, month, day )
	if isEmpty( year ) or isEmpty( month ) or isEmpty( day ) then
		return nil
	end
	local dateString = year .. '-' .. month .. '-' .. day
	
	local success, result = pcall( mwLang.formatDate, mwLang, 'U', dateString )
	if success then
		if tonumber( result ) then
			return '@' .. result
		end
	end
	
	return nil
end

-- Форматирование выделяемого шаблоном текста
local function getSpanText( text, style )
	style = style or 'background:#ffeaea; color:#444444;'
	
	local tag = mw.html.create( 'span' )
		:attr( 'style', style )
		:wikitext( text )
	
	return tostring( tag )
end

-- Форматирование комментария как в шаблоне
local function getComment( comment, link, date )
	if isEmpty( comment ) and isEmpty( date ) then
		return nil
	end
	
	-- «Википедия:Нейтральная точка зрения (2 мая 2015)»
	if isEmpty( comment ) and not isEmpty( date ) then
		comment = link
	end
	
	if isEmpty( comment ) then
		return nil
	end
	
	local delink = require( 'Module:Delink' )._delink
	comment = delink( { comment } )
	
	if not isEmpty( date ) then
		comment = comment .. mwLang:formatDate( ' (j xg Y)', date )
	end
	
	return comment
end

-- Форматирование ссылки как в шаблоне
local function getLink( link, text, comment, hasCustomComment )
	if isEmpty( link ) then
		return text
	end
	
	if not isEmpty( comment ) then
		local html = mw.html.create( 'span' )
			:attr( 'title', comment )
			:wikitext( text )
				
		if hasCustomComment then
			html:attr( 'style', 'border-bottom:1px dotted;' )
		end
	
		text = tostring( html )
	end
	
	return string.format( '<i>[[%s|%s]]</i>', link, text )
end

-- Форматирование ссылки на обсуждение как в шаблоне
local function getTalkLink( page, noprint )
	if not page then return '' end
	
	-- Страница обсуждения для текущей статьи в случае отсутствия якоря
	if not mw.ustring.find( page, '#' ) then
		page = mw.title.getCurrentTitle().talkPageTitle.fullText .. '#' .. page
	end
	
	local result = ' [[%s|(обс.)]]'
	if isEmpty( noprint ) or not noprint then
		local html = mw.html.create( 'span' )
			:addClass( 'noprint' )
			:wikitext( result )
		
		result = tostring( html )
	end
	return string.format( result, page )
end

-- Простановка категорий
local function getCategory( category, config, date )
	if isEmpty( date ) then
		return ''
	end
	
	if isEmpty( category ) then
		return ''
	end
	
	config = ' ' .. ( config or '>= 0' )
	local mDate = require( 'Module:Date' )._Date
	local today = mwLang:formatDate( 'Y-m-d H:i:s' )
	local input = mwLang:formatDate( 'Y-m-d H:i:s', date )
	local diff = ( mDate( today ) - mDate( input ) )
	
	local success, result = pcall( mw.ext.ParserFunctions.expr, diff .. config )
	if success and result == '1' then
		return category
	end
	
	return ''
end

local function getError( comment, anchor )
	local html = mw.html.create( 'strong' )
		:addClass( 'error noprint' )
		:wikitext( string.format( '[[%s#%s|Ошибка:]] %s', docPage, anchor, comment ) )
	
	return tostring( html )
end

-- Поддержка подстановки без Unsubst
function p.subst( frame )
	local args = getArgs( frame, {
		parentOnly = true,
	} )
	local mArgs = getArgs( frame, {
		removeBlanks = true,
	} )
	local mTemplateInvocation = require( 'Module:Template invocation' )
	local name = mTemplateInvocation.name( frame:getParent():getTitle() )
	
	-- Передать все нумерованные параметры из вызова модуля
	for key, val in ipairs( mArgs ) do
		if key == tonumber( key ) then
			args[ key ] = val
		end
	end
	
	return mTemplateInvocation.invocation( name, args )
end

--
-- Модуль на замену шаблону «Надстрочное предупреждение»
--
function p.main( frame )
	local args = getArgs( frame )
	local date = getValidDate( args.year, args.month, args.day )
	local isMainNamespace = mw.title.getCurrentTitle().namespace == 0
	local result = ''
	
	-- Поддержка подстановки
	if mw.isSubsting() then
		return p.subst( frame )
	end
	
	-- Вывод надстрочного предупреждения
	local tag = mw.html.create( 'sup' )
		:attr( 'style', 'white-space:nowrap' )
	
	if not isEmpty( args.noprint ) then
		tag:addClass( 'noprint' )
	end
	
	-- Вывод ошибки о параметре text
	if isEmpty( args.text ) then
		result = getError( 'не задан параметр <code>text</code>', 'Использование' )
		tag:wikitext( result )
		
		return tostring( tag )
	end
	
	-- Поддержка параметра {{{span-text|}}}
	if args[ 'span-text' ] then
		result = result .. getSpanText( args[ 'span-text' ], args[ 'span-style' ] )
	end
	
	-- Поддержка параметра {{{comment|}}}
	local comment = getComment( args.comment or args[ 'comment-default' ], args.link, date )
	
	tag
		:wikitext( '&#91;' ) -- [
		:wikitext( getLink( args.link, args.text, comment, not isEmpty( args.comment ) ) )
		:wikitext( getTalkLink( args.talk, args.noprint ) )
		:wikitext( '&#93;' ) -- ]
	
	result = result .. tostring( tag )
		
	-- Проверка для [[Категория:Википедия:Надстрочные предупреждения с некорректно заданной датой]]
	local errorcat = args.errorcat or '[[Категория:Википедия:Надстрочные предупреждения с некорректно заданной датой]]'
	if not isEmpty( args.day ) or not isEmpty( args.month ) or not isEmpty( args.year ) then
		if isEmpty( date ) then
			result = getError( 'некорректно задана дата установки', 'Дата установки' )
			
			if isMainNamespace then
				result = result .. errorcat
			end
		end
	end
	
	-- Поддержка параметра {{{anchor|}}}
	if args.anchor then
		local anchor = require( 'Module:Якорь' ).main;
		result = anchor{ visible = true, text = result, args.anchor }
	end
	
	-- Установка категорий
	if isEmpty( args.nocat ) and isMainNamespace then
		if not isEmpty( args.cat ) then
			result = result .. args.cat
		end
		result = result .. getCategory( args[ 'cat1' ], args[ 'cat1-date' ], date )
		result = result .. getCategory( args[ 'cat2' ], args[ 'cat2-date' ], date )
		result = result .. getCategory( args[ 'cat3' ], args[ 'cat3-date' ], date )
	end
	
	return result
end

return p