模块:InfoBox

来自「荏苒之境」

此模块的文档可以在模块:InfoBox/doc创建

local html = mw.html

local csv = require("Module:Csv")

local infobox = {}

local function trim(str)
	return string.gsub(str, "^%s*(.-)%s*$", "%1")
end

local function append_full_row(table_elem)
	return table_elem:tag("tr"):tag("th")
		:attr("colspan", "2")
end

local function append_header(frame, parent, text)
	local title = append_full_row(parent):wikitext(text)
		
	local args = frame.args
	local title_color = args.title_color
	local title_background = args.title_background
	
	if title_color then
		title:css("color", title_color)
	end
	if title_background then
		title:css("background", title_background)
	end
	
	return title
end

local row_appenders = {
	title = function(...)
		append_header(...):addClass("infobox-title")
	end,
	section = function(...)
		append_header(...):addClass("infobox-header")
	end,
	image = function(frame, parent, file)
		local actual_file = frame:preprocess(file)
		if actual_file ~= "" then
			append_full_row(parent)
				:addClass("infobox-image")
				:wikitext("[[File:"..actual_file.."|300px]]")
		end
	end,
	caption = function(frame, parent, text)
		local actual_text = frame:preprocess(text)
		if actual_text ~= "" then
			append_full_row(parent)
				:addClass("infobox-caption")
				:wikitext(actual_text)
		end
	end,
	text = function(frame, parent, header, data)
		local actual_data = frame:preprocess(data)
		if actual_data ~= "" then
			parent:tag("tr")
				:tag("th"):wikitext(header):done()
				:tag("td"):wikitext(actual_data):done()
		end
	end
}

local function append_row(frame, parent, row_type, ...)
	local appender = row_appenders[row_type]
	if appender == nil then
		return
	end
	return appender(frame, parent, ...)
end

infobox.show = function(frame)
	local parent_frame = frame:getParent()
	local args = parent_frame.args
	local view = html.create("div"):addClass("infobox")
	local table_elem = view:tag("table")
	
	for k, v in ipairs(args) do
		local parts = csv.parse_row(v)
		for i = 1, #parts do
			parts[i] = trim(parts[i])
		end
		append_row(parent_frame, table_elem, unpack(parts))
	end
	
	table_elem:done()
	return view
end

return infobox