Jump to content

Module:InfoboxLua/Components/Section

From Creopedia

This documentation is transcluded from Module:InfoboxLua/Components/Section/doc.

Used by Module:InfoboxLua.


require( 'strict' )

local tabber = mw.ext.tabber
local util = require( 'Module:InfoboxLua/Util' )
local types = require( 'Module:InfoboxLua/Types' )
local itemComponent = require( 'Module:InfoboxLua/Components/Item' )

local p = {}


--- @param section SectionComponentData
--- @return mw.html
local function getItemsHtml( section )
	local root = mw.html.create( 'div' )
	root:addClass( 't-infobox-section-items' )

	if section.columns and section.columns > 1 then
		root:css( '--infobox-section-columns', tostring( section.columns ) )
	end
	for _, itemData in ipairs( section.items ) do
		local itemHtml = itemComponent.getHtml( itemData )
		if itemHtml then
			root:node( itemHtml )
		end
	end

	return root
end

--- @param section SectionComponentData
--- @return mw.html|nil
local function getSubSectionsHtml( section )
	local tabberData = {}

	for i, subSectionData in ipairs( section.sections ) do
		local label = subSectionData.label
		local contentHtml = p.getHtml( subSectionData, true )

		if label and contentHtml then
			table.insert( tabberData, {
				label = label,
				content = tostring( contentHtml )
			} )
		end
	end

	if tabberData == {} then
		return nil
	end

	local root = mw.html.create( 'div' )
	root:addClass( 't-infobox-section-subsections' )
	root:node( tabber.render( tabberData ) )

	return root
end

--- Renders an infobox section.
---
--- @param data table
--- @param isSubSection boolean|nil
--- @return mw.html|nil
function p.getHtml( data, isSubSection )
	--- @type SectionComponentData|nil
	local section = util.validateAndConstruct( data, types.SectionComponentDataSchema )

	if not section then
		return nil
	end

	local isEmpty = true

	local root = mw.html.create( 'div' )
	root:addClass( 't-infobox-section' )

	if util.isNonEmptyString( section.class ) then
		root:addClass( section.class )
	end

	if util.isNonEmptyString( section.label ) and isSubSection ~= true then
		root:tag( 'div' )
			:addClass( 't-infobox-section-label' )
			:wikitext( section.label )
			:done()
	end

	if util.isNonEmptyString( section.content ) then
		isEmpty = false
		root:wikitext( section.content )
	end

	if util.isNonEmptyTable( section.items ) then
		local itemsHtml = getItemsHtml( section )
		if itemsHtml then
			isEmpty = false
			root:node( itemsHtml )
		end
	end

	if util.isNonEmptyTable( section.sections ) then
		local subSectionsHtml = getSubSectionsHtml( section )
		if subSectionsHtml then
			isEmpty = false
			root:node( subSectionsHtml )
		end
	end

	return isEmpty and nil or root
end

return p