require( 'strict' )
local p = {}
local docPage = 'Module:Надстрочное предупреждение'
local templateStylesPage = 'Module:Надстрочное предупреждение/styles.css'
local defaultClass = 'ts-fix'
local defaultErrorCat = '[[Категория:Википедия:Надстрочные предупреждения с некорректно заданной датой]]'
local mwLang = mw.getContentLanguage()
local getArgs = require( 'Module:Arguments' ).getArgs
local function isEmpty( val )
return val == nil or val == ''
end
-- Комбинация стандартного класса и кастомного
local function getHtmlClass( class, val )
if isEmpty( class ) then
return string.format( '%s-%s', defaultClass, val )
end
return string.format( '%s-%s %s-%s', defaultClass, val, class, 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, class )
local tag = mw.html.create( 'span' )
:addClass( getHtmlClass( class, 'text' ) )
-- TODO: WMF pls fix [[phab:T162379]] / https://phabricator.wikimedia.org/T162379
:attr( 'style', '-webkit-box-decoration-break: clone' )
: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 )
local html = mw.html.create( 'i' )
if not isEmpty( comment ) then
local span = mw.html.create( 'span' )
:attr( 'title', comment )
:wikitext( text )
if hasCustomComment then
if isEmpty( link ) then
html:addClass( defaultClass .. '-comment' )
else
html:addClass( defaultClass .. '-commented' )
end
end
text = tostring( span )
end
if isEmpty( link ) then
html:wikitext( text )
else
html:wikitext( string.format( '[[%s|%s]]', link, text ) )
end
return tostring( html )
end
-- Форматирование ссылки на обсуждение как в шаблоне
local function getTalkLink( page, noprint )
if not page then return '' end
-- Страница обсуждения для текущей статьи в случае отсутствия якоря
local anchorSymbol = mw.ustring.find( page, '#' )
if isEmpty( anchorSymbol ) or anchorSymbol == 1 then
page = mw.title.getCurrentTitle().talkPageTitle.fullText .. '#' .. mw.text.trim( page, '#' )
end
local result = string.format( ' [[%s|(обс.)]]', page )
if isEmpty( noprint ) or not noprint then
local html = mw.html.create( 'span' )
:addClass( 'noprint' )
:wikitext( result )
result = tostring( html )
end
return result
end
-- Простановка категорий
local function getCategory( category, config, date )
if isEmpty( category ) then
return ''
end
if config == false then
return category
end
if isEmpty( date ) 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( defaultClass .. '-error 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 pairs( 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
local hasDate = false
local isMainNamespace = mw.title.getCurrentTitle().namespace == 0
local result = ''
-- Проверка наличия параметра date
if not isEmpty( args.date ) then
-- Проверка формата YYYY-MM-DD
if mw.ustring.match( args.date, '^%d%d%d%d%-%d%d%-%d%d$' ) then
local year, month, day = mw.ustring.match( args.date, '^(%d%d%d%d)%-(%d%d)%-(%d%d)$' )
date = getValidDate( year, month, day )
hasDate = true
else
date = nil
hasDate = true -- Параметр date указан, но имеет некорректный формат
end
else
-- Использование параметров year, month, day
date = getValidDate( args.year, args.month, args.day )
hasDate = not isEmpty( args.day ) or not isEmpty( args.month ) or not isEmpty( args.year )
end
-- Поддержка TemplateStyles
local class = nil
if not isEmpty( args.name ) then
class = 'ts-' .. args.name
end
result = result .. frame:extensionTag{
name = 'templatestyles', args = { src = templateStylesPage }
}
if not isEmpty( args.name ) and not isEmpty( args.templatestyles ) then
result = result .. frame:extensionTag{
name = 'templatestyles', args = { src = args.templatestyles }
}
end
-- Поддержка подстановки
if mw.isSubsting() then
return p.subst( frame )
end
-- Вывод надстрочного предупреждения
local tag = mw.html.create( 'sup' )
:addClass( getHtmlClass( class, 'template' ) )
if not isEmpty( args.noprint ) then
tag:addClass( 'noprint' )
end
-- Вывод ошибки о параметре text
if isEmpty( args.text ) then
result = result .. getError( 'не задан параметр <code>text</code>', 'Использование' )
tag:wikitext( result )
return tostring( tag )
end
-- Поддержка параметра {{{span-text|}}}
if not isEmpty( args[ 'span-text' ] ) then
result = result .. getSpanText( args[ 'span-text' ], class )
end
-- Вывод надстрочного предупреждения
local comment = getComment( args.comment or args[ 'comment-default' ], args.link, date )
tag
:wikitext( '[' ) -- [
:wikitext( getLink( args.link, args.text, comment, not isEmpty( args.comment ) ) )
:wikitext( getTalkLink( args.talk, args.noprint ) )
:wikitext( ']' ) -- ]
-- Проверка для категории страниц с некорректным указанием даты
local errorcat = args.errorcat or defaultErrorCat
if hasDate and isEmpty( date ) then
result = result .. getError( 'некорректно задана дата установки (исправьте через подстановку шаблона)', 'Дата установки' )
if isMainNamespace then
result = result .. errorcat
end
else
result = result .. tostring( tag )
end
-- Поддержка параметра {{{anchor|}}}
if not isEmpty( args.anchor ) then
local anchor = require( 'Module:Якорь' ).main;
result = anchor{ visible = true, text = result, args.anchor }
end
-- Установка категорий
if isEmpty( args.nocat ) and isMainNamespace then
result = result .. getCategory( args.cat, false )
if hasDate then
result = result .. getCategory( args[ 'cat1' ], args[ 'cat-date1' ], date )
result = result .. getCategory( args[ 'cat2' ], args[ 'cat-date2' ], date )
result = result .. getCategory( args[ 'cat3' ], args[ 'cat-date3' ], date )
end
end
return result
end
return p