Module:Variants

Revision as of 19:50, 23 November 2024 by Artoire (talk | contribs) (Add logic for main variants table (so they are sorted the same))

Creates a section containing all items with the same Variant property, ordered by the sum of the profession level requirements in ascending order.

If a variant does not have a profession level, 0 is used as a fallback, meaning items with unknown level requirements will always appear first in the list.

Usage:

{{Variants|Eel}}

Result:


local p = {}

function sort_entries(entry1, entry2)
	-- Sort the variants based on the sum of the profession levels
	local entry1_value = (entry1['Profession Level A'] or 0) + (entry1['Profession Level B'] or 0)
	local entry2_value = (entry2['Profession Level A'] or 0) + (entry2['Profession Level B'] or 0)
	return entry1_value < entry2_value
end

function get_table_info(args, get_images)
	local variant_name = args.variant or mw.title.getCurrentTitle().fullText
	local query = {
        '[[Variant of::'..variant_name..']]',
        '?Profession Level A',
        '?Profession Level B',
        get_images and '?Image#64px;x64px = Image' or nil,
        limit = args.limit or 500,
    }
	local smw_data = mw.smw.ask(query)
	if not smw_data then
		return nil
	end
	table.sort(smw_data, sort_entries)
	return smw_data
end

function p.variants_header(args)
	local smw_data = get_table_info(args)
	local contents
	if smw_data then
    	local formatted = {}
    	for _, entry in ipairs(smw_data) do
    		table.insert(formatted, entry[1])
    	end
		contents = table.concat(formatted, '&nbsp;•&nbsp;')
	else
		contents = '[[Category:Empty variant list]]'
	end
	return mw.html.create('div')
		:addClass('variants-header')
		:wikitext(contents)
	:done()
end

function p.main(frame)
	local args = frame:getParent().args
	args.variant = args[1] or args.variant
	return p.variants_header(args)
end

function p.variants_table(args)
	local smw_data = get_table_info(args, true)
	if not smw_data then
		return ':No variants found.'
	end
	local table = mw.html.create('table')
		:addClass('sortable wikitable')
		:tag('tr')
			:tag('th')
				:attr{ colspan = '2' }
				:wikitext('Item')
			:done()
			:tag('th')
				:wikitext('Level')
			:done()
		:done()

	for _, entry in ipairs(smw_data) do
		table
			:tag('tr')
				:tag('td')
					:css{ ['border-right'] = 'none' }
					:wikitext(entry.Image)
				:done()
				:tag('td')
					:css{ ['border-left'] = 'none' }
					:wikitext(entry[1])
				:done()
				:tag('td')
					:wikitext(entry['Profession Level A'])
				:done()
			:done()
	end

	return table
end

function p.main_table(frame)
	local args = frame:getParent().args
	args.variant = args[1] or args.variant
	return p.variants_table(args)
end

return p