Module:ConceptFooter

From No Subject
Jump to navigation Jump to search

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

-- Module:ConceptFooter
-- Adds categories automatically based on axis navboxes passed to Template:ConceptFooter.
-- Default: only categorizes mainspace (ns=0). Disable with |nocat=yes.

local p = {}

local data = mw.loadData('Module:ConceptFooter/data')

local function truthy(v)
	if v == nil then return false end
	v = tostring(v)
	v = mw.text.trim(v)
	if v == '' then return false end
	v = mw.ustring.lower(v)
	return not (v == '0' or v == 'no' or v == 'false' or v == 'n')
end

local function normalizeTemplateName(s)
	if not s then return nil end
	s = tostring(s)
	s = mw.text.trim(s)
	if s == '' then return nil end
	-- strip Template: prefix if user passed it
	s = s:gsub('^[Tt]emplate:%s*', '')
	return mw.text.trim(s)
end

function p.categories(frame)
	-- IMPORTANT: we want args from the template call, not from #invoke
	local args = (frame:getParent() and frame:getParent().args) or frame.args

	-- allow opt-out
	if truthy(args.nocat) then
		return ''
	end

	-- default: mainspace only
	local title = mw.title.getCurrentTitle()
	if title.namespace ~= 0 then
		return ''
	end

	local out = {}
	local seen = {}

	local function addCat(catName)
		if not catName or catName == '' then return end
		catName = mw.text.trim(tostring(catName))
		if catName == '' then return end
		if seen[catName] then return end
		seen[catName] = true
		table.insert(out, string.format('[[Category:%s]]', catName))
	end

	local function addCatsForNavbox(navboxName)
		navboxName = normalizeTemplateName(navboxName)
		if not navboxName then return end

		local mapped = data.navbox_to_categories[navboxName]
		if not mapped then return end

		if type(mapped) == 'string' then
			addCat(mapped)
		elseif type(mapped) == 'table' then
			for _, c in ipairs(mapped) do
				addCat(c)
			end
		end
	end

	-- axis inputs: axis1/axis2 or positional 1/2
	addCatsForNavbox(args.axis1 or args[1])
	addCatsForNavbox(args.axis2 or args[2])

	return table.concat(out, '')
end

return p