Модуль:Надстрочное предупреждение: различия между версиями
Перейти к навигации
Перейти к поиску
(упрощение обработки комментариев) |
Marlezon (комментарии | вклад) |
||
(не показано 19 промежуточных версий 3 участников) | |||
Строка 2: | Строка 2: | ||
local p = {} | local p = {} | ||
− | local docPage = ' | + | local docPage = 'Module:Надстрочное предупреждение' |
+ | local templateStylesPage = 'Module:Надстрочное предупреждение/styles.css' | ||
+ | local defaultClass = 'ts-fix' | ||
+ | local defaultErrorCat = '[[Категория:Проект:Надстрочные предупреждения с некорректно заданной датой]]' | ||
local mwLang = mw.getContentLanguage() | local mwLang = mw.getContentLanguage() | ||
Строка 9: | Строка 12: | ||
local function isEmpty( val ) | local function isEmpty( val ) | ||
return val == nil or 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 | end | ||
Строка 29: | Строка 40: | ||
-- Форматирование выделяемого шаблоном текста | -- Форматирование выделяемого шаблоном текста | ||
− | local function getSpanText( text, | + | local function getSpanText( text, class ) |
− | |||
− | |||
local tag = mw.html.create( 'span' ) | local tag = mw.html.create( 'span' ) | ||
− | :attr( 'style', | + | :addClass( getHtmlClass( class, 'text' ) ) |
+ | -- TODO: WMF pls fix [[phab:T162379]] / https://phabricator.wikimedia.org/T162379 | ||
+ | :attr( 'style', '-webkit-box-decoration-break: clone' ) | ||
:wikitext( text ) | :wikitext( text ) | ||
Строка 45: | Строка 56: | ||
end | end | ||
− | -- | + | -- «Проект:Нейтральная точка зрения (2 мая 2015)» |
if isEmpty( comment ) and not isEmpty( date ) then | if isEmpty( comment ) and not isEmpty( date ) then | ||
comment = link | comment = link | ||
Строка 66: | Строка 77: | ||
-- Форматирование ссылки как в шаблоне | -- Форматирование ссылки как в шаблоне | ||
local function getLink( link, text, comment, hasCustomComment ) | local function getLink( link, text, comment, hasCustomComment ) | ||
− | + | local html = mw.html.create( 'i' ) | |
− | |||
− | |||
− | |||
if not isEmpty( comment ) then | if not isEmpty( comment ) then | ||
− | local | + | local span = mw.html.create( 'span' ) |
:attr( 'title', comment ) | :attr( 'title', comment ) | ||
:wikitext( text ) | :wikitext( text ) | ||
− | + | ||
if hasCustomComment then | if hasCustomComment then | ||
− | html: | + | if isEmpty( link ) then |
+ | html:addClass( defaultClass .. '-comment' ) | ||
+ | else | ||
+ | html:addClass( defaultClass .. '-commented' ) | ||
+ | end | ||
end | end | ||
− | text = tostring( | + | text = tostring( span ) |
end | end | ||
− | + | if isEmpty( link ) then | |
+ | html:wikitext( text ) | ||
+ | else | ||
+ | html:wikitext( string.format( '[[%s|%s]]', link, text ) ) | ||
+ | end | ||
+ | return tostring( html ) | ||
end | end | ||
Строка 90: | Строка 107: | ||
-- Страница обсуждения для текущей статьи в случае отсутствия якоря | -- Страница обсуждения для текущей статьи в случае отсутствия якоря | ||
− | + | local anchorSymbol = mw.ustring.find( page, '#' ) | |
− | page = mw.title.getCurrentTitle().talkPageTitle.fullText .. '#' .. page | + | if isEmpty( anchorSymbol ) or anchorSymbol == 1 then |
+ | page = mw.title.getCurrentTitle().talkPageTitle.fullText .. '#' .. mw.text.trim( page, '#' ) | ||
end | end | ||
− | local result = ' [[%s|(обс.)]]' | + | local result = string.format( ' [[%s|(обс.)]]', page ) |
if isEmpty( noprint ) or not noprint then | if isEmpty( noprint ) or not noprint then | ||
local html = mw.html.create( 'span' ) | local html = mw.html.create( 'span' ) | ||
Строка 102: | Строка 120: | ||
result = tostring( html ) | result = tostring( html ) | ||
end | end | ||
− | return | + | |
+ | return result | ||
end | end | ||
-- Простановка категорий | -- Простановка категорий | ||
local function getCategory( category, config, date ) | local function getCategory( category, config, date ) | ||
− | if isEmpty( | + | if isEmpty( category ) then |
return '' | return '' | ||
end | end | ||
− | if isEmpty( | + | if config == false then |
+ | return category | ||
+ | end | ||
+ | |||
+ | if isEmpty( date ) then | ||
return '' | return '' | ||
end | end | ||
Строка 131: | Строка 154: | ||
local function getError( comment, anchor ) | local function getError( comment, anchor ) | ||
local html = mw.html.create( 'strong' ) | local html = mw.html.create( 'strong' ) | ||
− | :addClass( 'error noprint' ) | + | :addClass( defaultClass .. '-error error noprint' ) |
:wikitext( string.format( '[[%s#%s|Ошибка:]] %s', docPage, anchor, comment ) ) | :wikitext( string.format( '[[%s#%s|Ошибка:]] %s', docPage, anchor, comment ) ) | ||
Строка 149: | Строка 172: | ||
-- Передать все нумерованные параметры из вызова модуля | -- Передать все нумерованные параметры из вызова модуля | ||
− | for key, val in | + | for key, val in pairs( mArgs ) do |
if key == tonumber( key ) then | if key == tonumber( key ) then | ||
args[ key ] = val | args[ key ] = val | ||
end | end | ||
end | end | ||
+ | |||
+ | -- Чаще всего перенос из других разделов, в случае проблем напишите на СО | ||
+ | args['date'] = nil | ||
return mTemplateInvocation.invocation( name, args ) | return mTemplateInvocation.invocation( name, args ) | ||
Строка 164: | Строка 190: | ||
local args = getArgs( frame ) | local args = getArgs( frame ) | ||
local date = getValidDate( args.year, args.month, args.day ) | local date = getValidDate( args.year, args.month, args.day ) | ||
+ | local hasDate = not isEmpty( args.day ) or not isEmpty( args.month ) or not isEmpty( args.year ) | ||
local isMainNamespace = mw.title.getCurrentTitle().namespace == 0 | local isMainNamespace = mw.title.getCurrentTitle().namespace == 0 | ||
local result = '' | local result = '' | ||
+ | |||
+ | -- Поддержка 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 | ||
-- Поддержка подстановки | -- Поддержка подстановки | ||
Строка 174: | Строка 216: | ||
-- Вывод надстрочного предупреждения | -- Вывод надстрочного предупреждения | ||
local tag = mw.html.create( 'sup' ) | local tag = mw.html.create( 'sup' ) | ||
− | : | + | :addClass( getHtmlClass( class, 'template' ) ) |
if not isEmpty( args.noprint ) then | if not isEmpty( args.noprint ) then | ||
Строка 182: | Строка 224: | ||
-- Вывод ошибки о параметре text | -- Вывод ошибки о параметре text | ||
if isEmpty( args.text ) then | if isEmpty( args.text ) then | ||
− | result = getError( 'не задан параметр <code>text</code>', 'Использование' ) | + | result = result .. getError( 'не задан параметр <code>text</code>', 'Использование' ) |
tag:wikitext( result ) | tag:wikitext( result ) | ||
Строка 189: | Строка 231: | ||
-- Поддержка параметра {{{span-text|}}} | -- Поддержка параметра {{{span-text|}}} | ||
− | if args[ 'span-text' ] then | + | if not isEmpty( args[ 'span-text' ] ) then |
− | result = result .. getSpanText( args[ 'span-text' ], | + | result = result .. getSpanText( args[ 'span-text' ], class ) |
end | end | ||
− | -- | + | -- Вывод надстрочного предупреждения |
local comment = getComment( args.comment or args[ 'comment-default' ], args.link, date ) | local comment = getComment( args.comment or args[ 'comment-default' ], args.link, date ) | ||
− | |||
tag | tag | ||
:wikitext( '[' ) -- [ | :wikitext( '[' ) -- [ | ||
Строка 201: | Строка 242: | ||
:wikitext( getTalkLink( args.talk, args.noprint ) ) | :wikitext( getTalkLink( args.talk, args.noprint ) ) | ||
:wikitext( ']' ) -- ] | :wikitext( ']' ) -- ] | ||
− | |||
− | |||
− | -- Проверка для | + | -- Проверка для категории страниц с некорректным указанием даты |
− | local errorcat = args.errorcat or | + | local errorcat = args.errorcat or defaultErrorCat |
− | if | + | if hasDate and isEmpty( date ) then |
− | + | result = result .. getError( 'некорректно задана дата установки (исправьте через подстановку шаблона)', 'Дата установки' ) | |
− | + | ||
− | + | if isMainNamespace then | |
− | + | result = result .. errorcat | |
− | |||
− | |||
end | end | ||
+ | else | ||
+ | result = result .. tostring( tag ) | ||
end | end | ||
-- Поддержка параметра {{{anchor|}}} | -- Поддержка параметра {{{anchor|}}} | ||
− | if args.anchor then | + | if not isEmpty( args.anchor ) then |
local anchor = require( 'Module:Якорь' ).main; | local anchor = require( 'Module:Якорь' ).main; | ||
result = anchor{ visible = true, text = result, args.anchor } | result = anchor{ visible = true, text = result, args.anchor } | ||
Строка 224: | Строка 263: | ||
-- Установка категорий | -- Установка категорий | ||
if isEmpty( args.nocat ) and isMainNamespace then | if isEmpty( args.nocat ) and isMainNamespace then | ||
− | + | result = result .. getCategory( args.cat, false ) | |
− | result = result .. args.cat | + | |
+ | 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 | ||
− | |||
− | |||
− | |||
end | end | ||
Текущая версия от 23:08, 12 апреля 2025
Для документации этого модуля может быть создана страница Модуль:Надстрочное предупреждение/doc
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
-- Чаще всего перенос из других разделов, в случае проблем напишите на СО
args['date'] = nil
return mTemplateInvocation.invocation( name, args )
end
--
-- Модуль на замену шаблону «Надстрочное предупреждение»
--
function p.main( frame )
local args = getArgs( frame )
local date = getValidDate( args.year, args.month, args.day )
local hasDate = not isEmpty( args.day ) or not isEmpty( args.month ) or not isEmpty( args.year )
local isMainNamespace = mw.title.getCurrentTitle().namespace == 0
local result = ''
-- Поддержка 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