Module:CharInserts

From Leaguepedia | League of Legends Esports Wiki
Jump to: navigation, search
local util_sentence = require("Module:SentenceUtil")
local util_table = require('Module:TableUtil')
local util_vars = require("Module:VarsUtil")
local i18n = require('Module:i18nUtil')

local h = {}

local p = {}
function p.main(frame)
	local title = mw.title.getCurrentTitle()
	i18n.init('CharInserts')
	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
	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(i18n.print('loading', label or ''))
	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 = mw.title.getCurrentTitle().text,
	}
	return util_sentence.makeReplacements(str, 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