Module:Subpage 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 utilsArg = require("Module:UtilsArg")
local utilsPage = require("Module:UtilsPage")

function p.Main(frame)
	local args = utilsArg.parse(frame:getParent().args, p.Templates["Subpage List"])
	local pageTree = p.main(args.page, args)
	return p.displayTree(pageTree)
end

function p.main(pageName, options)
	local title
	if pageName then
		title = mw.title.new(pageName)
	else
		title = mw.title.getCurrentTitle()
	end
	local subpages = utilsPage.getSubpages(title.prefixedText)
	return p.buildTree(title, subpages, options)
end

function p.buildTree(title, subpages, options, root)
	local options = options or {}
	local recurse = options.recurse
	if root == nil then
		root = root or {}
		root.value = title.text
		p.buildTree(title, subpages, options, root)
		return root;
	end
	
	local children
	for _, subpage in pairs(subpages) do
		local subpageTitle = mw.title.new(subpage)
		if subpageTitle.baseText == title.text then
			children = children or {}
			local pageName = subpageTitle.fullText
			local pageDisplay = options.fullPageNames and subpageTitle.fullText or subpageTitle.subpageText
			local node = {
				pageName = pageName,
				pageDisplay = pageDisplay,
			}
			table.insert(children, node)
			if recurse == nil or recurse > 0 then
				options.recurse = recurse and recurse - 1
				p.buildTree(subpageTitle, subpages, options, node)
			end
		end
	end
	root.children = children
	return root
end

function p.displayTree(root, list)
	local list = list or '<ul>'
	if not root.children then
		return ''
	end
	for i, node in pairs(root.children) do
		list = list .. string.format('<li>[[%s|%s]]</li>', node.pageName, node.pageDisplay)
		list = list .. p.displayTree(node)
	end
	return list .. '</ul>'
end

p.Templates = {
	["Subpage List"] = {
		params = {
			[1] = {
				name = "page",
				type = "wiki-page-name",
			},
			recurse = {
				type = "number",
			},
			fullPageNames = {
				type = "boolean",
				nilIfEmpty = true,
				default = false,
			},
		},
	},
}

return p