Module:CharInserts
Jump to navigation
Jump to search
local util_table = require('Module:TableUtil')
local h = {}
local p = {}
function p.main(frame)
local title = mw.title.getCurrentTitle()
return h.makeOutput(h.getData(title.nsText), title.text)
end
function h.getData(nsText)
local moduleTitle = mw.title.new(h.getModuleName(nsText), 'Module')
if not moduleTitle.exists then return nil end
return mw.loadData(moduleTitle.prefixedText)
end
function h.getModuleName(nsText)
if nsText == '' then nsText = 'Main' end
return ('CharInserts/%s'):format(nsText)
end
function h.makeOutput(data, title)
if not data then return end
local ret = {}
for _, group in ipairs(data) do
ret[#ret+1] = h.getGroupOutput(group, title)
end
if #ret == 0 then
ret[#ret+1] = '<!-- -->'
end
return unpack(ret)
end
function h.getGroupOutput(group, title)
-- group.pattern is required to be in title
if not h.containsOneOf(title, group.pattern) then return nil end
-- group.notpattern is required NOT to be in title, and supercedes group.pattern being there
if h.containsOneOf(title, group.notpattern or '@@@@@@@@@@') then return nil end
-- newtext=true can be set to force the insert to show only in new pages
if group.newtext and mw.title.getCurrentTitle().exists then return nil end
local div = h.makeDiv(group.label)
h.printContent(div, group)
return div
end
function h.containsOneOf(title, patterns)
patterns = util_table.guaranteeTable(patterns)
for _, v in ipairs(patterns) do
if title:find(v) then
return true
end
end
end
function h.makeDiv(label)
return mw.html.create('div'):attr('data-ci-label', label)
end
function h.printContent(div, group)
div:wikitext(h.loadingText(group.label), h.makeContent(group.insert))
end
function h.loadingText(label)
local output = mw.html.create('span')
:addClass('ci-loading-text')
:wikitext('loading...')
return tostring(output)
end
function h.makeContent(insert)
return mw.getCurrentFrame():extensionTag{
name = 'charinsert',
content = h.makeReplacements(h.escape(insert)),
args = {}
}
end
function h.makeReplacements(str)
local replacements = {
PAGENAME = h.escape(mw.title.getCurrentTitle().text),
}
return h._doMakeReplacements(str, replacements)
end
function h._doMakeReplacements(sentence, replacements)
if not sentence then return nil end
if not replacements then replacements = {} end
local old = sentence
for k, v in pairs(replacements) do
sentence = sentence:gsub('%$' .. k .. '%$', v or 'unknown')
end
if sentence == old then
return sentence
end
return h._doMakeReplacements(sentence, replacements)
end
function h.escape(insert)
local replace = {
['\n'] = ' ',
['( +)'] = '<nowiki>%1</nowiki>',
['\\%['] = '[',
['\\%]'] = ']',
}
for k, v in pairs(replace) do
insert = insert:gsub(k, v)
end
return insert
end
return p