Permanently protected module

Module:Card/models/Limitation history

From Yugipedia
Jump to: navigation, search
require('Module:No globals')

-- @field card           string    Page name of the card whose history this is for
-- @field caption        string    A short description of the table, to be displayed as a table caption
-- @field format         string    The format the history is for (e.g. "Advanced Format", "OCG", "Korean")
-- @field debutDate      string    ISO date of when the card was first released in the format
-- @field history        table     List with details on each limitation list that the card was on and the status it had on each list
-- @field groupedHistory table     Shorter version of `history` where consecutive lists in which the card had the same status are grouped together
-- @field currentStatus  string    The card's status on the list that's in effect
local LimitationHistory = {
	card = nil,
	caption = nil,
	format = nil,
	debutDate = nil,
	history = {},
	groupedHistory = {},
	currentStatus = nil,
}

-- ------------------------------------
-- Local functions
--    Functions only used within this class
-- ------------------------------------

-- Function to be used with table.sort to order items by start date
-- @param item1 table
-- @param item2 table
-- @return boolean
local function orderHistory(item1, item2)
	-- If one of the dates is missing, default it to a letter, so it gets
	-- sorted after any date value.
	return (item1.startDate or 'a') < (item2.startDate or 'a')
end


-- Convert a status name to the name of the CSS class used to add its styling
-- e.g. "Limited 1" → "status-limited-1"
local function statusToClass(status)
	return 'status-' .. (status:gsub(' ', '-')):lower()
end

-- Add a number of days to a  date
-- @param date string    Date in the format YYYY-MM-DD
-- @param days number    Number of days to add. Use a negative number to subtract
-- @return string        New date in the format YYYY-MM-DD
local function addDaysToDate(date, days)
	local dateParts = mw.text.split(date, '%-')
	
	return os.date('%Y-%m-%d', os.time{
		year  = dateParts[1],
		month = dateParts[2],
		day   = dateParts[3] + days
	})
end



-- ------------------------------------
-- LimitationHistory methods
--    Functions that can be invoked from an instance of a LimitationHistory table
-- ------------------------------------


-- Create a new instance of a LimitationHistory object
-- @param card   string   Page name of the card
-- @param format string   Page name of the format
-- @param caption string  Short description for table caption
-- @return LimitationHistory
function LimitationHistory:new(card, format, debutDate, caption)
	local lh = mw.clone(LimitationHistory)
	lh.card = card
	lh.caption = caption
	lh.format = format
	lh.debutDate = debutDate
	lh.history = lh:lookupHistory()
	lh.groupedHistory = lh:getGroupedHistory()
	lh.currentStatus = lh:getCurrentStatus()

	return lh
end

-- Look up all limitation status lists that include the card for the format
-- @return table
function LimitationHistory:lookupHistory()
	local results = mw.smw.ask{
		'[[List contains::' .. self.card .. ']]' ..
		'[[-Has subobject.Page type::Status list]]' ..
		'[[-Has subobject.Format::' .. self.format .. ']]',
		'?Status#                    = status',
		'?-Has subobject#            = list',
		'?-Has subobject.Start date# = startDate',
		'?-Has subobject.Start date  = startDateFormatted',
		'?-Has subobject.End date#   = endDate',
		'?-Has subobject.End date    = endDateFormatted',
		'mainlabel = -',
		'limit = 500'
	} or {}

	-- SMW sorting doesn't work with inverse properties. Doing it in Lua instead.
	table.sort(results and results, orderHistory)

	return results
end

-- Merge consecutive history items with the same status together
-- @return table
function LimitationHistory:getGroupedHistory()
	local i = 0
	local groupedHistory = {}

	-- Can't use `for item in pairs(self.history) do`
	-- because the order will get messed up.
	for h = 1, #self.history do
		local item = self.history[h]

		-- Check if this item has a different status than the incumbent item
		-- Always true for the first item.
		local hasNewStatus = (i == 0 or item.status ~= groupedHistory[i].status)

		if (hasNewStatus) then
			-- Create a new object at the next space in the table
			i = i + 1
			groupedHistory[i] = mw.clone(item)
			groupedHistory[i].firstList = item.list
			groupedHistory[i].list = nil
		else
			-- Update the end date on the existing object
			groupedHistory[i].endDate = item.endDate
			groupedHistory[i].endDateFormatted = item.endDateFormatted
			groupedHistory[i].lastList = item.list
		end
	end

	return groupedHistory
end

-- Get the current limitation status
-- @return string
-- @todo: Avoid potential issue with non-active lists that don't specify an end date
function LimitationHistory:getCurrentStatus()
	local today = os.date('%Y-%m-%d')

	-- Loop through the history items
	-- If today falls within the start and end dates, that's the current status
	for _, item in pairs(self.groupedHistory) do
		local todayAfterStartDate = not item.startDate or item.startDate <= today
		local todayBeforeEndDate = not item.endDate or item.endDate >= today
	
		if (todayAfterStartDate and todayBeforeEndDate) then
			-- Return the status or `nil` if it's "Unlimited"
			return item.status == 'Unlimited'
				and nil
				or item.status
		end
	end

	return nil
end

-- Render the history as a table
-- Table has a row for each change in status,
-- including the start and end date of the time with that status
-- 
-- @return string
-- @todo All the fancy stuff with "Unlimited" handling to be moved to `getGroupedHistory`
function LimitationHistory:renderHistoryTable()
	-- Return empty string if there is no history
	if not self.groupedHistory or #self.groupedHistory == 0 then return '' end

	-- Create HTML table
	local historyTable = mw.html.create('table'):addClass('wikitable')
	
	-- Add caption if one has been passed in
	if self.caption then
		historyTable:tag('caption'):wikitext(self.caption)
	else
		historyTable:attr('aria-labelledby', 'Limitation_history')
	end

	-- Add heading row
	local thead = historyTable:tag('tr')
	thead:tag('th'):attr('scope', 'col'):wikitext('Status')
	thead:tag('th'):attr('scope', 'col'):wikitext('Start date')
	thead:tag('th'):attr('scope', 'col'):wikitext('End date')
	thead:tag('th'):attr('scope', 'col'):wikitext('List')

	local firstListDate = self.groupedHistory[1].startDate

	-- If the card was released before the first limitation status,
	-- Add a row saying it was 'Unlimited' in that period
	if (self.debutDate and self.debutDate < firstListDate) then
		local tr = historyTable:tag('tr')
		tr:tag('td'):addClass('status-unlimited'):wikitext('[[Unlimited]]')
		-- Start when the card was released
		tr:tag('td'):wikitext(self.debutDate)
		-- End the day before its first limitation
		tr:tag('td'):wikitext(addDaysToDate(firstListDate, -1))
	end

	-- Loop through each change in status
	for i = 1, #self.groupedHistory do
		local item = self.groupedHistory[i]

		-- If the debut date is after the start date,
		-- i.e. the card wasn't released until after the list came into effect
		-- use the debut date as the start date. e.g. "Temple of the Kings"
		local startDate = self.debutDate and self.debutDate > item.startDate
			and self.debutDate
			or item.startDate

		-- Add a row for the status.
		local tr = historyTable:tag('tr')

		-- Add a cell for the status and add a class to style it per its status.
		tr:tag('td'):addClass(statusToClass(item.status)):wikitext('[[' .. item.status .. ']]')

		-- Add cell for the start date
		tr:tag('td'):wikitext(startDate)

		-- Add cell for the end date

		-- Cards tend to only be flagged as "Unlimited" on lists where they are removed.
		-- They won't be marked as Unlimited on subsequent lists.
		-- So we have to get the end date by subtracting one from the next start date, if there is one.
		if (item.status == 'Unlimited') then
			local nextItem = self.groupedHistory[i + 1]
			tr:tag('td'):wikitext(nextItem and addDaysToDate(nextItem.startDate, -1))
		else
			tr:tag('td'):wikitext(item.endDate)
		end

		tr:tag('td'):wikitext('[[' .. item.firstList .. '|' .. (mw.text.split(item.firstList, ' %(')[1]) .. ']]')
	end

	return tostring(historyTable)
end

-- Render a given status as a badge
-- @param status  string
-- @param context string    Text to display in parentheses after the status 
function LimitationHistory.renderStatusBadge(status, context)
	local badge = mw.html.create('div')

	local statusText = '[[' .. status .. ']]'

	if (context and context ~= '') then
		statusText = statusText .. ' (' .. context .. ')'
	end

	badge
		:addClass(statusToClass(status))
		:css('border', '2px solid #666')
		:css('border-radius', '3px')
		:css('display', 'inline-block')
		:css('padding', '.1em .5em')
		:wikitext(statusText)

	return tostring(badge)
end

-- Function for calling via #invoke
-- e.g. {{ #invoke: Card/models/Limitation history | Last Will | Advanced Format | 2002-03-29 }}`
-- should produce a table of the status history for "Last Will" starting March 29, 2002
--
-- @param frame
-- @return string
function LimitationHistory.renderInline(frame)
	local args = frame:getParent().args or frame

	local lh = LimitationHistory:new(args[1], args[2], args[3], args[4])

	return lh:renderHistoryTable()
end


return LimitationHistory