Модуль:Languages: Розніца паміж версіямі
[дагледжаная версія] | [дагледжаная версія] |
Змесціва выдалена Змесціва дададзена
...як і іх камбінацыя Тэг: Адменена |
Няма тлумачэння праўкі Тэг: Ручны адкат |
||
Радок 244: | Радок 244: | ||
-- Паказвае спасылку на іншамоўны артыкул ці прапанова прыбраць шаблон |
-- Паказвае спасылку на іншамоўны артыкул ці прапанова прыбраць шаблон |
||
if ifExists and not ifRedirect then |
if ifExists and not ifRedirect then |
||
s = s .. '<sup class="iw__notice noprint">' |
s = s .. '<sup class="iw__notice noprint">[[Шаблон:Не перакладзена 5#Калі старонка існуе|' |
||
.. '<span style="color: |
.. '<span style="color:red; font-style:normal; font-weight:bold;" title="Прыбярыце шаблон «Не перакладзена 5» з артыкула ' |
||
.. 'і заменіце яго простай вікі-спасылкай"> |
.. 'і заменіце яго простай вікі-спасылкай">?!</span>]]</sup>' |
||
if this.namespace == 0 and isEmpty(nocat) then |
if this.namespace == 0 and isEmpty(nocat) then |
||
s = s .. categoryExists |
s = s .. categoryExists |
Версія ад 10:35, 22 лютага 2023
Дакументацыю да гэтага модуля можна стварыць у Модуль:Languages/Дакументацыя
-- Модуль для працы з мовамі ISO 639
-- загрузка модуля даных з табліцай моў
local languages = mw.loadData('Module:Languages/data')
local p = {}
-- Правярае, ці пусты дан параметр
local function isEmpty(s)
return s == nil or s == ''
end
-- дапаможная функцыя, выдаляе прабелы
local function trimstr(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-- атрымлівае код мовы, вяртае спасылку і нармалізаваны код мовы (ці пустыя радкі)
local function get_lang_data(code)
local l = languages[code];
if l ~= nil then
return "[[" .. l[2] .. "|" .. l[1] .. "]]", code
elseif code ~= "" then
return code, ""
else
return "", ""
end
end
function p.getRefHtmlFrame( frame )
return p.getRefHtml( trimstr( frame.args[1] ) )
end
function p.getRefHtml( wikidataItemId )
local codeByItemId = mw.loadData( "Module:Wikidata/Language-codes" )
local code = codeByItemId[ wikidataItemId ];
if code == nil then
mw.log( 'Language code not found for ' .. wikidataItemId )
return ""
else
local l = languages[code];
if l == nil then
mw.log( 'Language description for code ' .. code .. ' not found' )
return ""
else
return '<span class="ref-info" title="' .. l[ 2 ] .. '" style="font-size:85%; cursor:help; color:#888;">(' .. l[ 1 ] .. ')</span>'
end
end
end
-- прымае zh|我|tt|мін, вяртае спіс праз коску
function p.list(frame)
local curr_lang = nil
local result = nil
for n, v in frame:argumentPairs() do
local trimmed = trimstr(v)
if curr_lang == nil then
if trimmed ~= '' then
-- калі мова прапушчаны, пакінем мінулы
curr_lang = trimstr(v)
end
else
if trimmed ~= '' then
local link, lang_code = get_lang_data(curr_lang)
local list_item
if lang_code ~= '' then
list_item = link .. " <span dir='auto' lang='" .. lang_code .. "'>" .. trimmed .. "</span>"
else
list_item = link .. " <span class='unknown-foreign-lang'>" .. trimmed .. "</span>".."[[Category:Вікіпедыя:Артыкулы з нераспазнанай мовай]]"
end
if result == nil then
result = list_item
else
result = result .. ", " .. list_item
end
else
-- Пусты тэкст — значыць, бягучая мова супадае з наступным
local link, lang_code = get_lang_data(curr_lang)
if result == nil then
result = link
else
result = result .. ", " .. link
end
end
curr_lang = nil
end
end
-- проста #invoke:Languages|list|yue павінна вяртаць усё ж спасылку без тэксту
if curr_lang ~= nil then
local link, lang_code = get_lang_data(curr_lang)
if result ~= nil then
result = result .. ", " .. link
else
result = link
end
end
return result
end
-- прымае zh|tt, вяртае ref-zh, ref-tt
function p.list_ref(frame)
local result = ''
local v = frame.args['в'] or nil
local ref = nil
if v then
ref = ' <span class="ref-info" style="cursor:help;" title="на %2%">[%1%]</span>'
else
ref = ' <span class="ref-info" style="cursor:help;" title="на %2%">(%1%)</span>'
end
for x, lg in pairs( frame.args ) do
local code = trimstr(lg)
if code ~= '' and code ~= 'в' then
local l = languages[code]
if l and l ~= nil then
result = result .. mw.ustring.gsub(mw.ustring.gsub(ref, '%%2%%', p._transform_lang(code)), '%%1%%', l[1])
else
result = result .. frame:expandTemplate{ title = 'ref-' .. code } .. '[[Катэгорыя:Вікіпедыя:Артыкулы з нераспазнанай мовай (ref)]]'
end
end
end
return result
end
-- Выводзіць назва мовы ў месным склоне
function p._transform_lang(code)
if isEmpty(languages[code]) then return '<невядомы код ' .. code .. '>' end
if languages[code][3] then return languages[code][3] end
local ln = mw.ustring.lower(
languages[code] and languages[code][2]
or mw.language.fetchLanguageName(code,'be')
):gsub('%s+мова%s+', ' '):gsub('%s*%(?мова%)?%s*', '')
if not ln then return 'мове з ISO-кодам '..code..' (?)' end
if ln:match('.*лінгва$') then return ln:gsub('а$','е') end
if mw.ustring.match(ln,'[сц]кая$') or ln:match('ная$') or mw.ustring.match(ln,'[сц]кая%s%b()$') or ln:match('ная%s%b()$')
then
ln = mw.ustring.gsub(
mw.ustring.gsub(ln, 'н([ая])я(%A)', function(y,s) return (y=='а' and 'най' or 'няй')..s end)
:gsub('ная$', 'най'),
'([сц]к)ая(%A)', '%1ай%2'
):gsub('скі$', 'скай'):gsub('цкая$', 'цкай');
if ln:match('%)$') and not (ln:match('ай%)$') or ln:match('няй%)$')) -- «мове» перад удакладненнем, калі яно не скланяецца
then
local r,s=ln:gsub('(%s)(%b())$','%1мове%1%2');
if s==1 then return r end
end
return ln..' мове'
else
return 'мове '..ln
end
end
function p.transform_lang(frame)
return p._transform_lang(trimstr(frame.args[1]))
end
-- Правярае існаванне старонкі і ці з’яўляецца яна перанакіраваннем
local function getTitle(page)
local success, result = pcall(function()
local title = mw.title.new(page)
return { title.exists, title.isRedirect }
end)
return success and result or nil
end
-- Выводзіць {{Не перакладзена 5}}
function p.getIW(frame)
local mwlang = mw.getContentLanguage()
local f = frame.args
local title = f.title
local text = f.text
local lang = mwlang:lc(f.lang)
local page = f.page
local state = f.state
local nocat = f.nocat
-- Выявы для старой функцыі паказу статусу
local states = {
['ВА'] = {'Вікіпедыя:Выдатныя артыкулы','Выдатны артыкул','Green star unboxed.svg'},
['ДА'] = {'Вікіпедыя:Добрыя артыкулы','Добры артыкул','Blue star unboxed.svg'},
['ВС'] = {'Вікіпедыя:Выбраныя спісы','Выбраныя спіс','Purple star unboxed.svg'}
}
-- Катэгорыі для шаблона
local categoryErrors = '[[Катэгорыя:Вікіпедыя:Артыкулы з некарэктна запоўненым шаблонам Не перакладзена]]'
local categoryExists = '[[Катэгорыя:Вікіпедыя:Артыкулы з неактуальным шаблонам Не перакладзена]]'
local categoryRedirect = '[[Катэгорыя:Вікіпедыя:Запыты на замену перанакіраванняў перакладамі]]'
-- Правярае існаванне параметраў і замяняе іх на альтэрнатыўныя
if isEmpty(text) then
text = title
end
if isEmpty(lang) then
lang = "en"
end
if isEmpty(page) then
page = title
end
-- Стварае шаблон
if title ~= '{{{1}}}' then
local this = mw.title.getCurrentTitle()
local titleObj = getTitle(title)
local ifExists, ifRedirect
local type = ''
local s = ''
local langName = ''
if lang ~= 'd' then
if isEmpty(languages[lang]) then
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryErrors
end
else
langName = ' data-lang-name="' .. (languages[lang][1] and languages[lang][1] or '???') .. '"'
end
end
-- Правярае, ці не абмежаваны ліміт выклікаў функцыі
if titleObj ~= nil then
ifExists = titleObj[1]
ifRedirect = titleObj[2]
end
-- Паказвае спасылку на рэдырэкт ці чырвоную спасылку
local class = (ifExists and (ifRedirect and ' iw--redirect' or ' iw--exists') or ' iw-nonexists')
s = s .. string.format('<span class="iw%s plainlinks" data-title="%s" data-lang="%s"' .. langName .. '>', class, mwlang:ucfirst(title), lang)
if ifRedirect then
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryRedirect
end
s = s .. string.format('[%s %s]', tostring(mw.uri.fullUrl(title,'redirect=no')), text)
else
s = s .. string.format('[[%s|<span class="' .. class .. '">%s</span>]]', title, text)
end
-- Паказвае спасылку на іншамоўны артыкул ці прапанова прыбраць шаблон
if ifExists and not ifRedirect then
s = s .. '<sup class="iw__notice noprint">[[Шаблон:Не перакладзена 5#Калі старонка існуе|'
.. '<span style="color:red; font-style:normal; font-weight:bold;" title="Прыбярыце шаблон «Не перакладзена 5» з артыкула '
.. 'і заменіце яго простай вікі-спасылкай">?!</span>]]</sup>'
if this.namespace == 0 and isEmpty(nocat) then
s = s .. categoryExists
end
else
-- Стварае ўсплывальную падказку
local t = ''
if lang == 'd' then
t = string.format('Старонка артыкула «%s» на Вікіданых', mwlang:ucfirst(title))
page = page .. '#sitelinks-wikipedia'
else
if not isEmpty(f.page) then
t = string.format('%s — версія артыкула', page)
else
t = 'Версія артыкула'
end
t = t .. string.format(' «%s» на %s', mwlang:ucfirst(title), p._transform_lang(lang))
end
-- Стварае заўвагу пра перанакіраванне
local aster = ''
if ifRedirect then
aster = '<sup class="iw__notice noprint" style="font-style:normal; font-weight:normal; margin:0 0 0 1px;">'
.. '[[Шаблон:Не перакладзена 5#Калі існуе перанакіраванне|'
.. '<span title="Замяніце перанакіраванне артыкулам або прыбярыце шаблон «Не перакладзена 5»">*</span>]]'
.. '</sup>'
end
-- Выводзіць спасылку на іншамоўную старонку
s = s .. '<sup class="iw__note noprint" style="font-style:normal; font-weight:normal;">' ..
string.format('[[:%s:%s|<span class="iw__tooltip" title="%s">[%s]</span>]]</sup>', lang, page, t, lang) ..
aster
-- Выводзіць статус іншамоўнай старонкі
if not isEmpty(state) and not isEmpty(states[state]) then
s = s .. string.format('<sup class="iw__status noprint" style="margin:0 0 0 1px;">[[Файл:%s|8px|link=%s|%s]]</sup>',
states[state][3], states[state][1], states[state][2])
end
end
return s .. '</span>'
else
-- Калі няма абавязковага параметру, выводзіць чырвоны тэкст
local htmlerror = require('Module:Error').error
return htmlerror{'Пазначце назву старонкі.'}
end
end
-- Раскрывае {{Не перакладзена 5}}
function p.unwrapIW(frame)
local f = frame.args
local title = f.title
local text = f.text
local s = '[[' .. title
if not isEmpty(text) and title ~= text then
s = s .. '|' .. text
end
return s .. ']]'
end
return p