Module:Track list

From Sekaipedia

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

local getArgs   = require('Module:Arguments').getArgs

local p = {}

local function extract(str)
	local col = nil
	local title_col = string.find(str, "^title%d+$")
	local singer_col = string.find(str, "^singer%d+$")
	local length_col = string.find(str, "^length%d+$")
	local idx = string.match(str, "(%d+)")
	
	if title_col then
		col = 'title'
	elseif singer_col then
		col = 'singer'
	elseif length_col then
		col = 'length'
	end
	
	if col and idx then
		return {
			['column'] = col,
			['index'] = idx
		}
	end
	
	return nil
end

function p.main(frame)
	local args = getArgs(frame, { wrappers = 'Template:Track list' })
	local rows = {}
	local total_length = 0
	local root = mw.html.create()
	
	for k,v in pairs(args) do
		local col_idx = extract(k)
		
		if col_idx then
			local col = col_idx['column']
			local idx = col_idx['index']
			
			if rows[idx] then
				rows[idx][col] = v
			else
				rows[idx] = {
					['number'] = tonumber(idx),
					[col] = v
				}
			end
			
			if col == 'length' then
				local mins, secs = string.match(v, "(%d+):(%d+)")
				total_length = total_length + tonumber(mins) * 60 + tonumber(secs)
			end
		end
	end
	
	local root_table = root:tag('table')
		:addClass('tracklist')
		:css({
			['margin-bottom'] = 0
		})
		:tag('tr')
			:addClass('tlist-head')
			:tag('th')
				:css({
					['text-align'] = 'right'
				})
				:wikitext('No.')
				:done()
			:tag('th')
				:css({
					['text-align'] = 'left'
				})
				:wikitext('Title')
				:done()
			:tag('th')
				:css({
					['text-align'] = 'left'
				})
				:wikitext('Singer(s)')
				:done()
			:tag('th')
				:css({
					['text-align'] = 'left'
				})
				:wikitext('Length')
				:done()
			:done()
	
	local sorted_rows = {}
	for k,v in pairs(rows) do table.insert(sorted_rows, v) end
	table.sort(sorted_rows, function (t1, t2)
			return t1.number < t2.number
		end)
	for i,v in ipairs(sorted_rows) do
		local no = v['number']
		local title = v['title']
		local singer = v['singer']
		local length = v['length']
		
		root_table:tag('tr')
			:addClass('tlist-song')
			:tag('td')
				:css({
					['text-align'] = 'right'
				})
				:wikitext(no)
				:done()
			:tag('td')
				:wikitext(title)
				:done()
			:tag('td')
				:wikitext(singer)
				:done()
			:tag('td')
				:css({
					['text-align'] = 'right'
				})
				:wikitext(length)
				:done()
	end
	
	local minutes = math.floor(total_length / 60)
	local seconds = total_length % 60
	
	root_table:tag('tr')
		:tag('td')
			:attr('colspan', 3)
			:css({
				['text-align'] = 'right'
			})
			:wikitext('Total length:')
			:done()
		:tag('th')
			:css({
				['text-align'] = 'right'
			})
			:wikitext(string.format(
				"%d:%02d",
				minutes,
				seconds)
			)
			:done()
	
	return tostring(root)
end

return p
Cookies help us deliver our services. By using our services, you agree to our use of cookies.