Open main menu

Changes

Module:Age

5,345 bytes added, 03:32, 3 May 2019
update from sandbox: use data-sort-value for sort keys per Module talk:Age#Sorting will use data-sort-value
-- Implement various "age of" and other date-related templates.
 
local mtext = {
-- Message and other text that should be localized.
['mt-bad-param1'] = 'Invalid parameter $1',
['mt-bad-param2'] = 'Parameter $1=$2 is invalid',
['mt-bad-show'] = 'Parameter show=$1 is not supported here',
['mt-cannot-add'] = 'Cannot add "$1"',
['mt-conflicting-show'] = 'Parameter show=$1 conflicts with round=$2',
['mt-date-wrong-order'] = 'The second date must be later in time than the first date',
['mt-dd-future'] = 'Death date (first date) must not be in the future',
['mt-dd-wrong-order'] = 'Death date (first date) must be later in time than the birth date (second date)',
['mt-invalid-bd-age'] = 'Invalid birth date for calculating age',
['mt-invalid-dates-age'] = 'Invalid dates for calculating age',
['mt-invalid-end'] = 'Invalid end date in second parameter',
['mt-invalid-start'] = 'Invalid start date in first parameter',
['mt-need-jdn'] = 'Need valid Julian date number',
['mt-need-valid-bd'] = 'Need valid birth date: year, month, day',
['mt-need-valid-bd2'] = 'Need valid birth date (second date): year, month, day',
['mt-need-valid-date'] = 'Need valid date',
['mt-need-valid-dd'] = 'Need valid death date (first date): year, month, day',
['mt-need-valid-ymd'] = 'Need valid year, month, day',
['mt-need-valid-ymd-current'] = 'Need valid year|month|day or "currentdate"',
['mt-need-valid-ymd2'] = 'Second date should be year, month, day',
['mt-template-bad-name'] = 'The specified template name is not valid',
['mt-template-x'] = 'The template invoking this must have "|template=x" where x is the wanted operation',
['txt-age'] = '(age ',
['txt-aged'] = ' (aged ',
['txt-and'] = ' and ',
['txt-comma-and'] = ', and ',
['txt-error'] = 'Error: ',
['txt-or'] = ' or ',
}
 
local translate, from_en, to_en, isZero
if translate then
-- Functions to translate from en to local language and reverse go here.
-- See example at [[:bn:Module:বয়স]].
else
from_en = function (text)
return text
end
isZero = function (text)
return tonumber(text) == 0
end
end
local _Date, _currentDate
local sandbox = frame:getTitle():find('sandbox', 1, true) and '/sandbox' or ''
local datemod = require('Module:Date' .. sandbox)
_Date local realDate = datemod._Date
_currentDate = datemod._current
if to_en then
_Date = function (...)
local args = {}
for i, v in ipairs({...}) do
args[i] = to_en(v)
end
return realDate(unpack(args))
end
else
_Date = realDate
end
end
return _Date, _currentDate
local function message(msg, id)
-- Return formatted message text for an error or warning.
local function getText(msg)
return mtext[msg] or error('Bug: message "' .. tostring(msg) .. '" not defined')
end
local text
if type(msg) == 'table' then
text = getText(msg[1])
local rep = {}
for i, v in ipairs(msg) do
if i > 1 then
rep['$' .. (i - 1)] = v
end
end
text = text:gsub('$%d+', rep)
else
text = getText(msg)
end
local categories = {
error = '[[Category:Age error]]',
b = '</i>]</sup>'
else
a = '<strong class="error">Error: '.. getText('txt-error')
b = '</strong>'
end
return
a ..
mw.text.nowiki(msgtext) ..
b ..
(category or '')
options.ordinal -- true: 'first' instead of 'one'
) or number
end
 
local function makeExtra(args, flagCurrent)
-- Return extra text that will be inserted before the visible result
-- but after any sort key.
local extra = args.prefix or ''
if mw.ustring.len(extra) > 1 then
-- Parameter "~" gives "~3" whereas "over" gives "over 3".
if extra:sub(-6, -1) ~= '&nbsp;' then
extra = extra .. ' '
end
end
if flagCurrent then
extra = '<span class="currentage"></span>' .. extra
end
return extra
end
-- Assume value is a valid number which has not overflowed.
if sortable == 'sortable_table' or sortable == 'sortable_on' or sortable == 'sortable_debug' then
local sortkeysortKey
if value == 0 then
sortkey sortKey = '5000000000000000000'
else
local mag = math.floor(math.log10(math.abs(value)) + 1e-14)
local prefix
if value > 0 then
prefix sortKey = 7000 + mag
else
prefix sortKey = 2999 - mag
value = value + 10^(mag+1)
end
sortkey sortKey = string.format('%d', prefixsortKey) .. string.format('%015.0f', math.floor(value * 10^(14-mag)))
end
local lhs, rhsresult
if sortable == 'sortable_table' then
lhs result = 'data-sort-value="_SORTKEY_"|' elseif sortable == 'sortable_debug' then rhs result = '<span data-sort-value="|_SORTKEY_♠"><span style="border:1px solid">_SORTKEY_♠</span></span>'
else
lhs result = sortable == 'sortable_debug' and '<span styledata-sort-value="border:1px solid;display:inline;" class="sortkey_SORTKEY_♠">' or '<span style="display:none" class="sortkey">' rhs = '♠</span>'
end
return lhs .. sortkey .. rhsresult:gsub('_SORTKEY_', sortKey)
end
end
return 'error'
end
return message('Need mt-need-valid -date')
end
local add = stripToNil(args.add)
date = date + item
if not date then
return message({ 'Cannot mt-cannot-add "' .. , item .. '"'})
end
end
end
local prefixsortKey, result
local sortable = translateParameters.sortable[args.sortable]
if sortable then
local value = (date.partial and date.partial.first or date).jdz
prefix sortKey = makeSort(value, sortable)
end
if show ~= 'hide' then
result = date[show]
if result == nil then
result = from_en(date:text(show))
elseif type(result) == 'boolean' then
result = result and '1' or '0'
else
result = from_en(tostring(result))
end
end
return (prefix sortKey or '') .. makeExtra(args) .. (result or '')
end
local function rangeJoin(range)
-- Return text to be used between a range of ages.
return range == 'dash' and '–' or mtext['&nbsp;txt-or ']
end
elseif options.join == 'sep_serialcomma' and text.n > 2 then
first = ', '
last = mtext[', txt-comma-and ']
else
first = ', '
last = mtext[' txt-and ']
end
for i, v in ipairs(text) do
end
return
(options.prefix sortKey or '') ..
(options.extra or '') ..
sign ..
range = parms.range and true or nil,
}
local prefixsortKey
if parms.sortable then
local value = diff.age_days + (parms.wantDuration and 1 or 0) -- days and fraction of a day
value = -value
end
prefix sortKey = makeSort(value, parms.sortable)
end
local textOptions = {
prefix = prefix,
suffix = parms.suffix, -- not currently used
extra = parms.extra,
format = parms.format,
isnegative = diff.isnegative,
range = parms.range,
sortKey = sortKey,
spell = parms.spell,
suffix = parms.suffix, -- not currently used
}
if show.id == 'hide' then
return prefix sortKey or ''
end
local values = { diff:age(show.id, diffOptions) }
}
return
(textOptions.prefix sortKey or '') ..
makeText({ diff.partial.mindiff:age(show.id, diffOptions) }, show, names[abbr], opt) ..
rangeJoin(textOptions.range) ..
(textOptions.suffix or '')
end
return message({ 'Parameter mt-bad-show=' .. , show.id .. ' is not supported here'})
end
-- Don't bother detecting if wantMixture is used because not needed and it is a poor option.
if not text then
if getopt.noMissing then
return nil -- this gives a nil date which gives an error
end
text = 'currentdate'
if getopt.flag == 'usesCurrent' then
end
if getopt.omitZero and i % 3 ~= 1 then -- omit zero months and days as unknown values but keep year 0 which is 1 BCE
if tonumberisZero(fields[i]) == 0 then
fields[i] = nil
getopt.partial = true
end
local fix = getopt.fix and 'fix' or ''
local noDefault = imax == 0 and getopt.noMissing
local partialText = getopt.partial and 'partial' or ''
local dates = {}
if (getopt.partial and y and (m or not d)) or (y and m and d) then
dates[i] = Date(fix, partialText, y, m, d)
elseif not y and not m and not d and not noDefault then
dates[i] = Date(flagCurrent())
end
end
end
elseif not noDefault thenelse
getopt.textdates = true -- have parsed each date from a single text field
dates[1] = Date(fix, partialText, flagCurrent(fields[1]))
end
if not dates[1] then
return message(getopt.missing1 or 'Need mt-need-valid year, month, day-ymd')
end
if getopt.single then
end
if not dates[2] then
return message(getopt.missing2 or 'Second date should be year, month, daymt-need-valid-ymd2')
end
return dates[1], dates[2]
local name = frame.args.template
if not name then
return message('The mt-template invoking this must have "|template=x" where -x is the wanted operation')
end
local args = frame:getParent().args
local spec = specs[name]
if not spec then
return message('The specified mt-template -bad-name is not valid')
end
if name == 'age_days' then
abbr = spec.abbr,
disp = spec.disp,
extra = makeExtra(args, getopt.usesCurrent and format ~= 'format_raw') and '<span class="currentage"></span>' or nil,
format = format or spec.format,
round = yes(args.round),
}
if (spec.negative or frame.args.negative) == 'error' and parms.diff.isnegative then
return message('The second date should not be before the first mt-date-wrong-order')
end
return from_en(dateDifference(parms))
end
-- Implement [[Template:Birth date and age]].
local args = frame:getParent().args
local options = { missing1 = 'mt-need-valid-bd', noMissing=true, single=true , }
local date = getDates(frame, options)
if type(date) == 'string' then
local diff = Date('currentdate') - date
if diff.isnegative or diff.years > 150 then
return message('Invalid birth date for calculating mt-invalid-bd-age')
end
local disp, show = 'disp_raw', 'y'
end
local df = stripToNil(args.df) -- day first (dmy); default is month first (mdy)
local result = df and '%-d %B %-Y' or '%B %-d, %-Y' result = '(<span class="bday">%-Y-%m-%d</span>) </span>' .. result (df and '%-d %B %-Y' or '%B %-d, %-Y') result = from_en('<span style="display:none"> ' ..
date:text(result) ..
'<span class="noprint ForceAgeToShow"> ' ..
mtext['(txt-age&nbsp;' ] ..
dateDifference({
diff = diff,
sep = 'sep_space',
}) ..
')</span>')
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
end
if invalid then
result = result .. message({ 'mt-bad-param1', invalid }, 'warning') end end return resultend local function dda(frame) -- Implement [[Template:Death date and age]]. local args = frame:getParent().args local options = { missing1 = 'mt-need-valid-dd', missing2 = 'mt-need-valid-bd2', noMissing = true, partial = true, } local date1, date2 = getDates(frame, options) if type(date1) == 'string' then return date1 end local diff = date1 - date2 if diff.isnegative then return message('mt-dd-wrong-order') end local Date = getExports(frame) local today = Date('currentdate') + 1 -- one day in future allows for timezones if date1 > today then return message('mt-dd-future') end local years if diff.partial then years = diff.partial.years years = type(years) == 'table' and years[2] or years else years = diff.years end if years > 150 then return message('mt-invalid-dates-age') end local df = stripToNil(args.df) -- day first (dmy); default is month first (mdy) local result if date1.day then -- y, m, d known result = (df and '%-d %B %-Y' or '%B %-d, %-Y') .. '<span style="display:none">(%-Y-%m-%d)</span>' elseif date1.month then -- y, m known; d unknown result = '%B %-Y' .. '<span style="display:none">(%-Y-%m-00)</span>' else -- y known; m, d unknown result = '%-Y' .. '<span style="display:none">(%-Y-00-00)</span>' end result = from_en(date1:text(result) .. mtext['txt-aged'] .. dateDifference({ diff = diff, show = 'y', abbr = 'abbr_off', disp = 'disp_raw', range = 'dash', sep = 'sep_space', }) .. ')') local warnings = tonumber(frame.args.warnings) if warnings and warnings > 0 then local good = { df = true, mf = true, } local invalid parameter local imax = options.textdates and 2 or 6 for k, _ in pairs(args) do if type(k) == 'number' then if k > imax then invalid = tostring(k) break end else if not good[k] then invalid = k break end end end if invalid then result = result .. message({ 'mt-bad-param1', invalid}, 'warning')
end
end
local date = Date('juliandate', args[1], args[2])
if date then
return from_en(date:text())
end
return message('Need valid Julian date numbermt-need-jdn')
end
return tostring(date.jd)
end
return message('Need mt-need-valid year/month/day or "currentdate"-ymd-current')
end
local args = frame:getParent().args
local parms = {
extra = makeExtra(args),
wantDuration = yes(args.duration),
range = yes(args.range) or (args.range == 'dash' and 'dash' or nil),
local date1 = Date(fix, 'partial', stripToNil(args[1]) or 'currentdatetime')
if not date1 then
return message('Invalid mt-invalid-start date in first parameter')
end
local date2 = Date(fix, 'partial', stripToNil(args[2]) or 'currentdatetime')
if not date2 then
return message('Invalid mt-invalid-end date in second parameter')
end
parms.diff = date2 - date1
parm = translate[parm]
if parm == nil then -- test for nil because false is a valid setting
return message({ 'Parameter mt-bad-param2' .. , argname .. '=' .. , args[argname] .. ' is invalid'})
end
parms[argname] = parm
if show then
if show.id ~= round then
return message({ 'Parameter mt-conflicting-show=' .. , args.show .. ' conflicts with round=' .. , args.round})
end
else
parms.round = true
end
return from_en(dateDifference(parms))
end
age_generic = ageGeneric, -- can emulate several age templates
birth_date_and_age = bda, -- Template:Birth_date_and_age
death_date_and_age = dda, -- Template:Death_date_and_age
gsd = dateToGsd, -- Template:Gregorian_serial_date
extract = dateExtract, -- Template:Extract
Anonymous user