Module:Meta category

From Wikisource
Jump to navigation Jump to search

require('strict')

local p = {}

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')
local messageBox = require('Module:Message box').main
local makeList = require('Module:List').makeList
local plain_sister = require('Module:Plain sister')._plain_sister

local function category_link(args)
	if not args[1] then
		return nil
	end
	
	local cat_text = mw.text.trim(args[1])
	local tracking_cat = ''
	
	local current_title = mw.title.getCurrentTitle()
	if current_title:inNamespace(14) and not args.allowedredlink then
		local target = mw.title.makeTitle('Category', cat)
		-- expensive function!
		if not target or not target.exists then
			tracking_cat = '[[Category:' .. 'Wikisource category-disambiguation box parameter needs fixing|∃' .. current_title.text .. ']]'
		end
	end
	
	return '\'\'\'[[:Category:' .. cat_text .. ']]\'\'\''
end

function p._meta_category(args)
	local allowedredlink = yesno(args.allowedredlink) or false
	
	-- get number of categories (largest-numbered parameter)
	-- can't use #args because that doesn't work consistently on tables that aren't sequences
	-- table.maxn also seems not to work
	local cat_count = 0
	for k, v in pairs(args) do
		local i = tonumber(k)
		if i and i > cat_count then
			cat_count = i
		end
	end
	
	local cat_links = {}
	for i = 1, cat_count do
		local link = category_link({[1] = args[i], ['allowedredlink'] = allowedredlink})
		if link then
			table.insert(cat_links, link)
		end
	end
	
	local cmbox = messageBox(
		'cmbox',
		{
			['type'] = 'content',
			image = '[[File:Sub-arrows.svg|50px]]',
			table.concat(
				{
					"'''This category is not in use because it is a meta category.'''",
					"'''Note:''' This category page should be empty of pages, and only contain subcategories.",
					makeList('horizontal', cat_links),
					'All entries should be recategorized under one of the above listed categories or an appropriate subcategory.'
				},
				'\n'
			)
		}
	)
	
	local single_namespace = ''
	local tracking_cat = ''
	if not yesno(args.nocat) then
		-- single_namespace = something
		
		local page_count = mw.site.stats.pagesInCategory(mw.title.getCurrentTitle().text, 'pages') -- expensive function!
		if page_count > 0 then
			tracking_cat = '[[Category:' .. 'Non-empty meta categories' .. ']]'
		end
	end
	
	local clear = tostring(mw.html.create('div'):css({clear = 'both'}))
	
	return cmbox .. single_namespace .. tracking_cat .. tracking_cat .. clear .. plain_sister({})
end

function p.meta_category(frame)
	return p._meta_category(getArgs(frame))
end

return p