Jump to content

Module:Location/Components/Table

From Creopedia

This documentation is transcluded from Module:Location/Components/Table/doc.

Implements Template:Locations.


require( 'strict' )

local tableLua = require( 'Module:TableLua' )

local p = {
	MAX_WIKITEXT_LOCATIONS = 50
}

--- Process the wikitext args
---
--- @param args table
--- @return table
local function processArgs( args )
	local data = {}

	for i = 1, p.MAX_WIKITEXT_LOCATIONS do
		local name = args[ 'name' .. i ]
		local link = args[ 'link' .. i ]
		local rate = args[ 'rate' .. i ]
		local note = args[ 'note' .. i ]

		if name then
			table.insert( data, {
				name = name,
				link = link,
				rate = rate,
				note = note
			} )
		end
	end

	return data
end

--- Whether any location carries an encounter rate. The Rate column is only
--- rendered when at least one does, so tables without rate data are unchanged.
---
--- @param data table
--- @return boolean
local function hasRate( data )
	for _, location in ipairs( data ) do
		if location.rate then
			return true
		end
	end

	return false
end

--- @param showRate boolean
--- @return TableColumn[]
local function getColumns( showRate )
	local columns = {
		{ id = 'location', label = 'Location' }
	}

	if showRate then
		table.insert( columns, { id = 'rate', label = 'Rate', textAlign = 'number' } )
	end

	table.insert( columns, { id = 'note', label = 'Note' } )

	return columns
end

--- @param data table
--- @param showRate boolean
--- @return TableRow[]
local function getRows( data, showRate )
	local rows = {}

	for _, location in ipairs( data ) do
		local row = {
			string.format( '[[%s|%s]]', location.link or location.name, location.name )
		}

		if showRate then
			table.insert( row, location.rate or '' )
		end

		table.insert( row, location.note or '' )

		table.insert( rows, row )
	end

	return rows
end

--- @param data table
--- @return TableProps
local function getTableProps( data )
	local showRate = hasRate( data )

	return {
		caption = 'Locations',
		hideCaption = true,
		columns = getColumns( showRate ),
		data = getRows( data, showRate ),
		class = table.concat( {
			't-location-table',
			'wikitable--fluid' -- Citizen built-in class for broad tables
		}, ' ' )
	}
end

--- Wikitext entry point for the module
---
--- @param frame mw.frame
--- @return string
function p.main( frame )
	local getArgs = require( 'Module:Arguments' ).getArgs
	return p._main( processArgs( getArgs( frame ) ) )
end

--- Lua entry point for the module
---
--- @param data table
--- @return string
function p._main( data )
	return tableLua.render( getTableProps( data ) )
end

return p