Jump to content

Module:Countdown

From Meta, a Wikimedia project coordination wiki
This is an archived version of this page, as edited by w>Theopolisme at 17:28, 8 December 2013 (Create module). It may differ significantly from the current version.
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Module documentation
-- This module powers {{countdown}}.

local p = {}

-- Constant
local lang = mw.language.getContentLanguage()

function formatMessage(secondsLeft, event, color)
    local timeLeft = lang:formatDuration(secondsLeft)
    -- Find whether we are plural or not.
    local isOrAre
    if mw.ustring.match(timeLeft, '^%d+') == '1' then
        isOrAre = 'is'
    else
        isOrAre = 'are'
    end
    -- Color and bold the numbers, because it makes them look important.
    local timeLeft = mw.ustring.gsub(timeLeft, '(%d+)', '<span style="color: ' .. (color or '#F00') .. '; font-weight: bold;">%1</span>')
    -- Make the refresh link and join it all together.
    local refreshLink = mw.title.getCurrentTitle():fullUrl{action = 'purge'}
    refreshLink = mw.ustring.format('<small><span class="plainlinks">([%s refresh])</span></small>', refreshLink)
    return mw.ustring.format('There %s %s until %s. %s', isOrAre, timeLeft, event, refreshLink)
end

function p.main(frame)
    local args = frame:getParent().args

    if not (args.year and args.month and args.day) then
        error('year, month, and day must be specified')
    end

    local eventTime = os.time{year=args.year, month=args.month, day=args.day, hour=args.hour, min=args.minute, sec=args.second}
    local timeToStart = os.difftime(eventTime, os.time()) -- (future time - current time)

    if timeToStart > 0 then
        -- Event has not begun yet
        return formatMessage(timeToStart, args.event or 'the event begins', args.color)
    elseif args.duration then
        if args['duration unit'] then
            -- Duration is in unit other than seconds, use parser function to add
            timeToEnd = tonumber(frame:callParserFunction('#time:U', tostring(timeToStart) .. ' +' .. tostring(args.duration) .. ' ' .. args['duration unit'])) or 0
        else
            timeToEnd = timeToStart + tonumber(args.duration)
        end
        if timeToEnd > 0 then
            -- Event is in progress
            return args.eventstart or formatMessage(timeToEnd, (args.event or 'the event') .. ' ends', args.color)
        else
            -- Event had a duration and has now ended
            return args.eventend or ((lang:ucfirst(args.event) or 'The event') .. ' has ended.')
        end
    else
        -- Event had no duration and has begun
        return args.eventstart or ((lang:ucfirst(args.event) or 'The event') .. ' has started.')
    end
end

return p