模块:RichTab

来自科学ADV中文wiki
风落翎讨论 | 贡献2020年5月9日 (六) 21:24的版本
跳到导航 跳到搜索

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

local p = {}

function p.render_template(html, params)
	local div = html:tag('div')
	local p1 = div:tag('div'):addClass('nav'):addClass(params.tabClass):attr('role', 'tablist')
	for i = 1, #params.tabBar do
		local li = p1:tag('li'):attr('role', 'presentation'):addClass(params.tabBar[i].tabState):wikitext('')
		local a = li:tag('a'):attr('href', '#'..tostring(params.tabBar[i].tabId))
				:attr('aria-controls', tostring(params.tabBar[i].tabId))
				:attr('role', 'tab'):attr('data-toggle', 'tab'):wikitext(params.tabBar[i].tabName)
	end
	p1:done()
	local p2 = div:tag('div'):addClass('tab-content')
	for i = 1, #params.tabContent do
		p2:tag('div'):attr('role','tabpanel'):addClass('tab-pane'):addClass(params.tabContent[i].tabState)
			:attr('id', tostring(params.tabContent[i].tabId)):wikitext(params.tabContent[i].tabText)
		:done()
	end
	p2:done()
	div:done()
	return html
end
	

function p.render(frame)
	local params = {}
	if frame:getParent() ~= nil then
		frame = frame:getParent()
	end
	local tabParams = parseTabParams(frame)
	if #tabParams == 0 then
		return ''
	end
	if frame.args['class'] then
		params.tabClass = frame.args['class']
	else
		params.tabClass = 'nav-tabs'
	end
	params.tabBar = {}
	params.tabContent = {}
	local index = 1
	while index < #tabParams do
		local id = genId()
		local tabIndex = math.ceil(index / 2)
		params.tabBar[tabIndex] = {}
		params.tabContent[tabIndex] = {}
		params.tabBar[tabIndex].tabId = id
		params.tabBar[tabIndex].tabName = tabParams[index]
		params.tabContent[tabIndex].tabId = id
		params.tabContent[tabIndex].tabText = tabParams[index + 1]
		index = index + 2
	end
	params.tabBar[1].tabState = 'active'
	params.tabContent[1].tabState = 'active'
	local result = mw.html.create()
	p.render_template(result, params)
	mw.logObject(result)
	return tostring(result)
end

function parseTabParams(frame)
	local index = 1
	local parsedParams = {}
	while frame.args[index] ~= nil do
		local continue = false
		repeat
			if frame.args[index] == '' then
				if index % 2 == 0 then
					parsedParams[#parsedParams] = nil
				else
					index = index + 1
				end
				index = index + 1
				continue = true
				break;
			end
			parsedParams[#parsedParams + 1] = frame.args[index]
			index = index + 1
			continue = true
		until true
		if not continue then
			break
		end
	end
	return parsedParams	
end

function genId()
	return 'tab-' .. os.clock() * 1e9
end

return p