Module:Pedigree tree

From Miraheze Developers Wiki
local p = {}
function p.main( f )
	local args = f
	if f == mw.getCurrentFrame() then 
		args = {}
		local origArgs = f.args
		local parentArgs = f:getParent().args
		
		for k, v in pairs( origArgs ) do
			v = mw.text.trim( tostring( v ) )
			if v ~= '' then
				args[k] = v
			end
		end
		
		for k, v in pairs( parentArgs ) do
			v = mw.text.trim( v )
			if v ~= '' then
				args[k] = v
			end
		end
	else
		f = mw.getCurrentFrame()
	end

	---- get wikitext
	
	local wikitext = args[1]

	if not wikitext or wikitext:match("^%s*(.-)%s*$"):len() == 0 then
		return ''
	end

	---- Split lines

	local lines = {}

	for s in wikitext:gmatch("[^\r\n]+") do
		table.insert(lines, s)
	end

	---- Generate object tree

	local treedata = { children = {}, level = 0 }
	local curtree = treedata
	local last_lvl = 1

	for i=1, #lines do
		local astarisk, text = lines[i]:match("^(%*+)%s*(.*)$")
		local level = astarisk:len()

		local tree = {
			level = level,
			text = text
		}

		if level < last_lvl then
			repeat
				curtree = curtree.parent
			until curtree.level < level
		end

		if level > last_lvl then
			curtree = curtree.children[ # curtree.children ];
		end
		
		tree.parent = curtree

		if not curtree.children then
			curtree.children = {}
		end
		table.insert(curtree.children, tree)

		last_lvl = level

	end

	---- Generate html from the object tree

	local root = mw.html.create( "div" )
	root:addClass( "pedigree-tree" )
	
	local curdiv = root:tag( "div" )
	curdiv:addClass( "child-wrapper" )
	
	p.genchild( treedata.children, curdiv, true )

    return tostring( root )
end

function p.genchild ( children, div, isRoot )
	for i, tree in ipairs( children ) do
		local child = div:tag( "div" )
		child:addClass( "child" )

		if not isRoot then
			local con = child:tag( "div" )
			con:addClass( "con" )
			local lrow = con:tag( "div" )
			lrow:addClass( "lrow" )
			local ru = lrow:tag( "div" )
			ru:addClass( "ru" )
			local rl = lrow:tag( "div" )
			rl:addClass( "rl" )
		end

		local item = child:tag( "div" )
		item:addClass( "item" )
		local span = item:tag( "span" )
		span:wikitext( tree.text )

		if tree.children then
			local lcol = child:tag( "div" )
			lcol:addClass( "lcol" )
			local bar = lcol:tag( "div" )
			bar:addClass( "bar" )
			local wrapper = child:tag( "div" )
			wrapper:addClass( "child-wrapper" )

			p.genchild(tree.children, wrapper)
		end
	end

	return div
end

return p