Module:BBCode

From BFDI: Branches Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:BBCode/doc

--[[

This module converts BBCode into similarly styled HTML.

It does not yet include all BBCode features, so if you need any feature
implemented that isn't already in here, just ask User:Coppersalts and she'll
probably add it.

]]

local p = {}

local tags = {
	["color"] = "span style=color:",
	["font_size"] = "span style=font-size:",
	["bgcolor"] = "span style=background-color:",
	-- Skipping over BFB Font for now.
	["monospace"] = "span style=font-family:monospace",
	["center"] = "span style=display:block;text-align:center",
	["i"] = "i",
	["b"] = "b",
	["u"] = "u",
	["s"] = "s"
}

function p.parse( frame )
	local str = frame.args[1]
	local out = ''
	local i = 1
	while i <= #str do
		local c = str:sub(i,i)
		if c == '[' then
			i = i + 1
			if str:sub(i,i) == '[' then
				out = out .. '[['
			else
				local is_closing = false
				if str:sub(i,i) == '/' then
					out = out .. '</span>'
					is_closing = true
					i = i + 1
				end
				local tag_name_start_index = i
				while i <= #str and str:sub(i,i) ~= ']'  and str:sub(i,i) ~= '=' do i = i + 1 end
				local tag_name_end_index = i - 1
				local param_end_index = -1
				if str:sub(i,i) == '=' then
					while i <= #str and str:sub(i,i) ~= ']' do i = i + 1 end
					param_end_index = i - 1
				end
				local tag_name = str:sub(tag_name_start_index,tag_name_end_index)
				if is_closing then
					local closing_tag_type = 'span'
					if tag_name == 'b' or tag_name == 'i' or tag_name == 'u' or tag_name == 's' then closing_tag_type = tags[tag_name] end
					out = out .. '</' .. closing_tag_type .. '>'
				else
					if tags[tag_name] ~= nil then
						param_string = ''
						if param_end_index ~= -1 then
							param_string = str:sub(tag_name_end_index+2,param_end_index)
							if tag_name == 'font_size' then
								param_string = (tonumber(param_string)/100) .. 'rem'
							end
						end
						out = out .. '<' .. tags[tag_name] .. param_string .. '>'
					elseif tag_name == 'lb' then out = out .. '['
					elseif tag_name == 'rb' then out = out .. ']'
					end
				end
			end
		else out = out .. c end
		i = i + 1
	end
	return out
end

return p