Module:List

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
This is the main module for the following templates:
local p = {}
local h = {}

local utilsArg = require("Module:UtilsArg")
local utilsString = require("Module:UtilsString")
local utilsTable = require("Module:UtilsTable")

local CATEGORY_INVALID_ARGS = "[[Category:"..require("Module:Constants/category/invalidArgs").."]]"
local CATEGORY_EXP_GAME = "[[Category:Infoboxes using exp game]]"

function h.warn(msg)
	local utilsError = require("Module:UtilsError")
	utilsError.warn(msg)
end

function p.Main(frame)
	local args, err = utilsArg.parse(frame:getParent().args, p.Templates.List)
	local categories = err and err.categoryText or ""
	local listItems = h.parseListItems(args.entries)
	categories = categories..h.validate(listItems)
	return h.printList(listItems)
end

function h.parseListItems(items)
	if #items == 1 then -- assume list items are delimited by commas instead of pipes
		local input = items[1]
		input = string.gsub(input, ",%s*$", "") -- strip dangling comma if present
		items = utilsString.split(input, '%s*,%f[^,%d]%s*') -- %f[^,%d] is so we don't split numbers on their thousands separator (e.g., 1,500)
	end
	return items
end

function h.validate(items)
	local categories = ""
	local itemsUsingExpGame = utilsTable.filter(items, function(item)
		return string.find(item, "exp%-game")
	end)
	if #itemsUsingExpGame > 1 and #itemsUsingExpGame == #items then
		h.warn("List is using {{Template|Exp Game}} for every list entry. In such cases {{Template|Infobox Game Blocks}} should be used instead. See [[:Category:Infoboxes using exp game]] for more information")
		categories = categories..CATEGORY_EXP_GAME
	end
	return categories
end

function h.printList(items)
	if items == nil or #items == 0 then
		return ""
	end
	local html = mw.html.create("ul"):addClass("plainlist")
	for i, item in ipairs(items) do
		html:tag("li"):wikitext(item)
	end
	return tostring(html)
end

p.Templates = {
	List = {
		desc = "Renders each list entry on a separate line without any list markers such as bullets or numbers",
		format = "inline",
		params = {
			["..."] = {
				name = "entries",
				placeholder = "entry",
				type = "content",
				desc = "List items. Can be any wikitext.",
				trim = true,
				nilIfEmpty = true,
			},
		},
	},
}

return p