Module:TemplatePreview

From IdleOn MMO Wiki

Documentation for this module may be created at Module:TemplatePreview/doc

require('strict')

local p = {}

--- Appends braces to the root element.
--- @param root table The root element.
--- @param braces string The braces text.
local function addBraces(root, braces)
	root:tag('span'):wikitext(braces)
end

--- Appends the name of the template to the preview.
--- @param root table The root element.
--- @param text string The name of the template.
local function addTemplateName(root, text)
	root:wikitext(string.format('[[Template:%s|%s]]', text, text))
end

--- Appends a template argument to the preview.
--- @param root table The root element.
--- @param text string The template argument text.
local function addTemplateArgument(root, text)
	root:wikitext('|')
		:tag('span'):addClass('argument'):wikitext(text)
end

--- Main entry point for use by templates.
--- @param frame table The frame object
--- @return string
function p.main(frame)
	return p._main(frame:getParent().args)
end

--- Main entry point for use by other modules.
--- @param args string[]
--- @return string
function p._main(args)
	--- Assert.exists(args[1], 'Caller must specify a template name.')

	local preview = mw.html.create('code'):addClass('template-preview')

	addBraces(preview, '{{')

	-- Add positional arguments first.
	for i, v in ipairs(args) do
		if i == 1 then
			addTemplateName(preview, v)
		else
			addTemplateArgument(preview, v)
		end
	end

	-- Add named arguments last.
	for k, v in pairs(args) do
		if type(k) == "string" then
			addTemplateArgument(preview, k .. '=' .. v)
		end
	end

	addBraces(preview, '}}')

	return tostring(preview)
end

return p