Jump to content

Module:Global permissions table

From Meta, a Wikimedia project coordination wiki
Module documentation


Usage

[edit]
{|
|-
! Column 1 || Column 2 || Column 3 || Column 4
{{#invoke:Global permissions table|main
|section1-note = <!-- Typically some parameter -->
|section1-bgcolor  = <!-- Hexadecimal color code -->
|section1-permissions = <!-- Space-separated permission names. Automatically sorted. -->
    foo, <!-- Comments are tolerated -->
    bar <!-- But not trailing commas! -->
}}
|}
Column 1 Column 2 Column 3 Column 4
1 bar ⧼Right-bar⧽ Some note
2 foo ⧼Right-foo⧽

See Global sysops/Permissions and Global rollback/Permissions for more realistic examples.

require('strict')

local p = {}

local MAX_SECTIONS = 10

local get_args = require('Module:Arguments').getArgs

---@class SectionInfo
---@field note string
---@field background_color string
---@field permissions string[]

---@param sections SectionInfo[]
---@return string
function p._render_rows(sections)
	local rows = {}
	local row_index = 1

	for _, section in ipairs(sections) do
		for index, permission in ipairs(section.permissions) do
			local row = {
				('|- style="background: #%s;"'):format(section.background_color),
				('| {{formatnum:%s}}'):format(row_index),
				('| <bdi lang="zxx" dir="ltr" style="font-family: monospace, monospace;">%s</bdi>'):format(permission),
				-- [[Module:Int]] doesn't provide a Lua interface
				('| {{int|Right-%s}}'):format(permission)
			}

			if index == 1 then
				table.insert(row, ('| rowspan="%s" | %s'):format(#section.permissions, section.note))
			end

			row_index = row_index + 1
			table.insert(rows, table.concat(row, '\n'))
		end
	end

	return table.concat(rows, '\n')
end

function p.main(frame)
	local args = get_args(frame, {
		trim = true,
		removeBlanks = true
	})

	---@type SectionInfo[]
	local sections = {}

	for section_index = 1, MAX_SECTIONS do
		local note = args[('section%s-note'):format(section_index)]
		local background_color = args[('section%s-bgcolor'):format(section_index)]
		local permissions = args[('section%s-permissions'):format(section_index)]
		
		if not note or not background_color or not permissions then
			break
		end

		permissions = mw.ustring.gsub(permissions, '<!--.--->', '')
		permissions = mw.text.split(permissions, '%s*,%s*')

		table.sort(permissions, function(a, b)
			return a < b
		end)

		---@type SectionInfo
		local section = {
			note = note,
			background_color = background_color,
			permissions = permissions
		}

		table.insert(sections, section)
	end

	local rows = p._render_rows(sections)

	return frame:preprocess(rows)
end

return p