Module:Sandbox/Hike395/Graphical timeline explained

local getArgs = require('Module:Arguments').getArgslocal compressSparseArray = require('Module:TableTools').compressSparseArraylocal p =

--

-- UTILITY FUNCTIONS--

-- Default colors for first 28 bars/periodslocal defaultColor = -- The default width of annotations (in em) local defaultAW = 8-- Previous version default width (in em)local oldDefaultAW = 7

-- Function to turn blank arguments back into nil-- Parameters:-- s = a string argument-- Returns-- if s is empty, turn back into nil (considered false by Lua)local function ignoreBlank(s) if s

"" then return nil end return send

-- Function to suppress incorrect CSS values-- Parameters:-- val = dimensional value -- unit = unit of value-- nonneg = [bool] value needs to be non-negative-- formatstr = optional format string-- Returns:-- correct string for html, or nil if val is negativelocal function checkDim(val, unit, nonneg, formatstr) if not val then return nil end val = tonumber(val) if not val or (nonneg and val < 0) then return nil end if formatstr then return mw.ustring.format(formatstr,val)..unit end return val..unitend

-- function to scan argument list for pattern-- Parameters:-- args = an argument dict that will be scanned for one or more patterns-- patterns = a list of Lua string patters to scan for-- other = a list of other argument specification lists-- each element o corresponds to a new argument to produce in the results-- o[1] = key in new argument list-- o[2] = prefix of old argument-- o[3] = suffix of old argument-- Returns:-- new argument list that matches patterns specified, with new key names---- This function makes the Lua module scalable, by specifying a list of string patterns that-- contain relevant arguments for a single graphical element, e.g., "period(%d+)". These-- patterns should have exactly one capture that returns a number.---- When such a pattern is detected, the number is extracted and then other arguments-- with the same number is searched for. Thus, if "period57" is detected, other relevant-- arguments like "period57-text" are searched for and, if non-empty, are copied to the-- output list with a new argument key. Thus, there is, and-- "period(%d+)" detects period57, the code will look for "period57-text" in the input-- and copy it's value to "text" on the output.---- This function thus pulls all relevant arguments for a single graphical item out, and-- makes an argument list to call a function to produce a single element (such as a bar or note)function p._scanArgs(args,patterns,other) local result = for _, p in pairs(patterns) do for k, v in pairs(args) do local m = tonumber(mw.ustring.match(k,p)) -- if there is a matching argument, and it's not blank -- and we haven't handled that match yet, then find other -- arguments and copy them into output arg list. -- We have to handle blank arguments for backward compatibility with the template -- we check for an existing output with item m to save time if m and v ~= "" and not result[m] then local singleResult = for _, o in ipairs(other) do local foundVal = args[(o[2] or "")..m..(o[3] or "")] if foundVal then singleResult[o[1]] = foundVal end end -- A hack: for any argument number m, there is a magic list of default -- colors. We copy that default color for m into the new argument list, in -- case it's useful. After this, m is discarded singleResult.defaultColor = defaultColor[m] result[m] = singleResult end end end -- Squeeze out all skipped values. Thus, continguous argument numbers are not -- required: the module can get called with bar3, bar17, bar59 and it will only produce -- three bars, in numerical order that they were called (3, 17, 59) return compressSparseArray(result)end

-- Function to compute the numeric step in the timescale-- Parameters:-- p1, p2 = lower and upper bounds of timescale-- Returns:-- round step size that produces ~10 steps between p1 and p2---- Implements, except with a slight tweak:-- The round value (0.1, 0.2, 0.5, 1.0) is selected based on minimum log-- distance, so the thresholds are slightly tweakedfunction p._calculateIncrement(p1, p2) local d = math.abs(p1-p2) if d < 1e-10 then return 1e-10 end local logd = math.log10(d) local n = math.floor(logd) local frac = logd-n local prevPower = math.pow(10,n-1) if frac < 0.5*math.log10(2) then return prevPower elseif frac < 0.5 then return 2*prevPower elseif frac < 0.5*math.log10(50) then return 5*prevPower else return 10*prevPower endend

-- Utility function to create HTML container for entire graphical timeline-- Parameters:-- container = HTML container for title-- args = arguments passed to main-- args["instance-id"] = unique string per Graphical timeline per page-- args.embedded = is timeline embedded in another infobox?-- args.align = float of timeline (default=right)-- args.margin = uniform margin around timeline-- Returns;-- html div object that is root of DOM for graphical timeline---- CSS taken from previous version of local function createContainer(args) local container = mw.html.create('div') container:attr("id","Container"..(args["instance-id"] or "")) container:addClass("toccolours") container:addClass("searchaux") container:css("text-align","left") container:css("padding","0 0.5em") container:css("border-style",args.embedded and "none" or "solid") if args.embedded then container:css("margin","auto") else container:css("float",args.align or "right") container:css("clear",args.align or "right") local margins = margins[1] = args.margin or "0.3em" margins[2] = (args.align

"right" and 0) or args.margin or "1.4em" margins[3] = args.margin or "0.8em" margins[4] = (args.align

"right" and (args.margin or "1.4em")) or 0 container:css("margin",table.concat(margins," ")) end container:css("overflow","hidden") return containerend

-- Utility function to create title for graphical timeline-- Parameters:-- args = arguments passed to main-- args["instance-id"] = unique string per Graphical timeline per page-- args["title-color"] = background color for title-- args.title = title of timeline-- Returns;-- html div object that is the title---- CSS taken from previous version of local function createTitle(container,args) local title = container:tag("div") title:attr("id","Title"..(args["instance-id"] or "")) title:css("background-color",ignoreBlank(args["title-colour"] or args["title-color"] or "#77bb77")) title:css("font-weight","bold") title:css("padding","0.2em") title:css("text-align","center") title:css("margin","0.6em 0 1.2em 0") title:wikitext(args.title)end

-- Utility function to create optional navbox header for timeline-- Parameters:-- container = container for navbox header-- args = arguments passed to main-- args.title = title of timeline-- args["link-to"] = name of parent template (without namespace)-- Returns;-- html div object that is the navbox header---- CSS taken from previous version of local function navboxHeader(container,args) local frame = mw.getCurrentFrame local link_to = container:tag("div") link_to:css("text-align","right") link_to:css("position","relative") if args.title then link_to:css("top","-1em") else link_to:css("top","0em") link_to:css("right","0em") end link_to:wikitext(frame:expandTemplate)end

--

-- TIME AXIS AND BARS--

--Function to create HTML time axis on left side of timeline--Arguments:-- container = HTML parent object-- args = arguments passed to main-- args.from = beginning (earliest) time of timeline-- args.to = ending (latest) time of timeline-- args.height = height of timeline-- args["height-unit"] = unit of height (default args.unit)-- args.unit = unit of measurement (default em)-- args["instance-id"] = unique string per Graphical timeline per page-- args["scale-increment"] = gap between time ticks (default=automatically computed)-- Returns;-- html div object for the time axis---- CSS taken from previous version of function p._scalemarkers(container,args) local height = tonumber(args.height) or 36 local unit = args["height-unit"] or args.unit or "em" local scaleDiv = container:tag("div") scaleDiv:attr("id","Scale"..(args["instance-id"] or "")) scaleDiv:css("width","3.1em") scaleDiv:css("position","relative") scaleDiv:css("top","-0.82em") scaleDiv:css("float","left") scaleDiv:css("height",checkDim(height,unit,true)) scaleDiv:css("padding","0px") local incr = args["scale-increment"] or p._calculateIncrement(args.from,args.to) -- step through by half the desired increment, alternating labels and ticks local halfIncr = incr/2 local tIndex = math.ceil(args.from/incr)*2 -- always start on a label local toIndex = math.floor(args.to/halfIncr) local showNum = true while tIndex <= toIndex do local t = tIndex*halfIncr local div = scaleDiv:tag("div") div:css("float","right") div:css("position","absolute") div:css("right","-1px") div:css("top",checkDim(height*(args.to-t)/(args.to-args.from),unit,nil,"%.2f")) local span = div:tag("span") span:attr("name",showNum and "Number" or "Tick") span:css("font-size","90%") span:css("white-space:nowrap") if showNum then span:wikitext(string.format("%d  - ",t)) else span:wikitext(" - ") end tIndex = tIndex + 1 showNum = not showNum end local scaleBar = container:tag("div") scaleBar:attr("id","ScaleBar"..(args["instance-id"] or "")) scaleBar:css("width","1px") scaleBar:css("float","left") scaleBar:css("height",checkDim(height,unit,true)) scaleBar:css("padding","0") scaleBar:css("background-color","#242020")end

-- Function to create timeline container div-- Arguments:-- container = HTML parent object-- args = arguments passed to main-- args["plot-colour"] = background color for timeline-- args["instance-id"] = unique string per graphical timeline per page-- args.height = height of timeline (36 by default)-- args.width = width of timeline (10 by default)-- args["height-unit"] = unit of height measurement (args.unit by default)-- args["width-unit"] = unit of width measurement (args.unit by default)-- args.unit = unit of measurement (em by default)-- Returns:-- timeline HTML object createdlocal function createTimeline(container,args) local color = ignoreBlank(args["plot-colour"] or args["plot-color"]) local timeline = container:tag("div") timeline:attr("id","Timeline"..(args["instance-id"] or "")) timeline:addClass("toccolours") timeline:css("font-size","100%") timeline:css("width","100%") timeline:css("height",checkDim(args.height or 36,args["height-unit"] or args.unit or "em",true)) timeline:css("padding","0px") timeline:css("float","left") timeline:css("width",checkDim(args.width or 10,args["width-unit"] or args.unit or "em",true)) timeline:css("border","none") timeline:css("background-color",color) return timelineend

-- Function to draw single bar (or box)-- Arguments:-- container = parent HTML object for bar-- args = arguments for this box-- args.text = text to display-- args.nudgedown = distance to nudge text down (in em)-- args.nudgeup = distance to nudge text up (in em)-- args.nudgeright = distance to nudge text right (in em)-- args.nudgeleft = distance to nudge text left (in em)-- args.colour = color of bar (default to color assigned to bar number)-- args.left = fraction of timeline width for left edge of bar (default 0)-- args.right = fraction of timeline width for right edge of bar (default 1)-- args.to = beginning (bottom) of bar, in time units (default timeline begin)-- args.from = end (top) of bar, in time units (default timeline end)-- args.height = timeline height-- args.width = timeline width-- args["height-unit"] = units of timeline height (default args.unit)-- args["width-unit"] = units of timeline width (default args.unit)-- args.unit = units for timeline dimensions (default em)-- args.border-style = CSS style for top/bottom of border (default "solid" if args.border)function p._singleBar(container,args) args.text = args.text or " " args.nudgedown = (tonumber(args.nudgedown) or 0) - (tonumber(args.nudgeup) or 0) args.nudgeright = (tonumber(args.nudgeright) or 0) - (tonumber(args.nudgeleft) or 0) args.colour = args.colour or args.defaultColor args.left = tonumber(args.left) or 0 args.right = tonumber(args.right) or 1 args.to = tonumber(args.to) or args["tl-to"] args.from = tonumber(args.from) or args["tl-from"] args.height = tonumber(args.height) or 36 args.width = tonumber(args.width) or 10 args["height-unit"] = args["height-unit"] or args.unit or "em" args["width-unit"] = args["width-unit"] or args.unit or "em" args.border = tonumber(args.border) args["border-style"] = args["border-style"] or ((args.border or args["border-colour"]) and "solid") or "none" -- the HTML element for the box/bar itself local bar = container:tag('div') bar:css("font-size","100%") bar:css("background-color",ignoreBlank(args.colour or "#aaccff")) bar:css("border-width",checkDim(args.border,args["height-unit"],true)) bar:css("border-color",ignoreBlank(args["border-colour"])) bar:css("border-style",args["border-style"].." none") bar:css("position","absolute") bar:css("text-align","center") local bar_top = args.height*(args["tl-to"]-args.to)/(args["tl-to"]-args["tl-from"]) bar:css("margin-top",checkDim(bar_top,args["height-unit"],nil,"%.3f")) local bar_height = args.height*(args.to-args.from)/(args["tl-to"]-args["tl-from"]) if args["border-style"] ~= "none" and args.border then bar_height = bar_height-2*args.border end bar:css("height",checkDim(bar_height,args["height-unit"],true,"%.3f")) bar:css("margin-left",checkDim(args.left*args.width,args["width-unit"],nil,"%.3f")) bar:css("width",checkDim((args.right-args.left)*args.width,args["width-unit"],true,"%.3f")) -- within the bar, use a div to nudge text away from center local nudge = bar:tag('div') nudge:css("font-size","100%") nudge:css("position","relative") nudge:css("top",checkDim(args.nudgedown-0.86,"em",nil)) nudge:css("left",checkDim(args.nudgeright,"em",nil)) -- put text div as child of nudge div local text = nudge:tag('div') text:css("position","relative") text:css("text-align","center") text:css("font-size",ignoreBlank(args.textsize)) text:css("vertical-align","middle") local text_bottom = -0.5*args.height*(args.to-args.from)/(args["tl-to"]-args["tl-from"]) text:css("display","block") text:css("bottom",checkDim(text_bottom,args["height-unit"],nil,"%.3f")) text:wikitext(ignoreBlank(args.text))end

-- Function to render all bars/boxes in timeline-- Arguments:-- container = parent HTML object-- args = arguments to main function---- Global (main) arguments are parsed, individual box arguments are picked out-- and passed to p._singleBar above---- The function looks for bar*-left, bar*-right, bar*-from, or bar*-to,-- where * is a string of digits. That string of digits is then used to-- find corresponding parameters of the individual bar.-- For example, if bar23-left is found, then bar23-colour turns into local colour,-- bar23-left turns into local left, bar23-from turns into local from, etc.function p._bars(container,args) local barArgs = p._scanArgs(args,, ) -- The individual bar arguments are placed into the barArgs table -- Iterating through barArgs picks out the for _, barg in ipairs(barArgs) do -- barg is a table with the local arguments for one bar. -- barg needs to have some global arguments copied into it: barg["tl-from"] = args.from barg["tl-to"] = args.to barg.height = args.height barg.width = args.width barg["height-unit"] = args["height-unit"] barg["width-unit"] = args["width-unit"] barg.unit = args.unit -- call _singleBar with the local arguments for one bar p._singleBar(container,barg) endend

-- Function to draw a bar corresponding to a geological period-- Arguments:-- container = parent HTML object-- args = global arguments passed to main---- This function is just like _bars, above, except with defaults for periods:-- a period bar is triggered by period* (* = string of digits)-- all other parameters start with "period", not "bar"-- colour, from, and to parameters default to data from named period-- text is a wikilink to period articlefunction p._periods(container,args) local frame = mw.getCurrentFrame local periodArgs = p._scanArgs(args,, ) -- Iterate through period* arguments, translating much like bar* arguments -- Supply period defaults to local arguments, also for _, parg in ipairs(periodArgs) do parg.text = parg.text or (""..parg.period.."") parg.textsize = "90%" parg.colour = parg.colour or frame:expandTemplate parg.from = parg.from or tonumber("-"..frame:expandTemplate) parg.to = parg.to or tonumber("-"..frame:expandTemplate) parg["tl-from"] = args.from parg["tl-to"] = args.to parg.height = args.height parg.width = args.width parg["height-unit"] = args["height-unit"] parg["width-unit"] = args["width-unit"] parg.unit = args.unit p._singleBar(container,parg) endend

--

=-- ANNOTATIONS--

=

-- Function to render a single note (annotation)-- Arguments:-- container = parent HTML object-- args = arguments for this single note-- args.text = text to display in note-- args.noarr = bool, true if no arrow should be used-- args.height = height of timeline-- args.unit = height units-- args.at = position of annotation (in time units)-- args.colour = color of text in note-- args.textsize = size of text (default 90%)-- Following parameters are only applicable to "no arrow" case-- args.nudgeright = nudge text to right (in em)-- args.nudgeleft = nudge text to left (in em)-- args.nudgedown = nudge text down (in em)-- args.nudgeup = nudge text up (in em)-- args.aw = annotation width (in em)

function p._singleNote(container,args) -- Ensure some parameters default to sensible values args.height = tonumber(args.height) or 36 args.at = tonumber(args.at) or 0.5*(args.to+args.from) args.colour = args.colour or "black" args.aw = tonumber(args.aw) -- if string is centering, use old width to not break it or mw.ustring.find(args.text,"

",1,true) and oldDefaultAW or defaultAW args.textsize = args.textsize or "90%" -- Convert 4 nudge arguments to 2 numeric signed nudge dimensions (right, down) args.nudgeright = (tonumber(args.nudgeright) or 0)-(tonumber(args.nudgeleft) or 0) args.nudgedown = (tonumber(args.nudgedown) or 0)-(tonumber(args.nudgeup) or 0) -- Two cases: no arrow, and arrow -- For no arrow case, use previous CSS which works well to position text if args.noarr then -- First, place a bar that pushes annotation down to right spot local bar = container:tag('div') bar:addClass("annot-bar") bar:css("width","auto") bar:css("font-size","100%") bar:css("position","absolute") bar:css("text-align","center") bar:css("margin-top",checkDim(args.height*(args.to-args.at)/(args.to-args.from),args.unit,nil,"%.3f")) -- Now, nudge the text per nudge dimensions local nudge = bar:tag('div') nudge:addClass("annot-nudge") nudge:css("float","left") nudge:css("position","relative") nudge:css("text-align","left") nudge:css("top",checkDim(args.nudgedown-0.75,"em",nil)) nudge:css("left",checkDim(args.nudgeright,"em",nil)) nudge:css("width",checkDim(args.aw,"em",true)) -- Finally, place a dev for the text local text = nudge:tag('div') text:css("position","relative") text:css("width","auto") text:css("z-index","10") text:css("font-size",ignoreBlank(args.textsize)) text:css("color",ignoreBlank(args.colour)) text:css("vertical-align","middle") text:css("line-height","105%") text:css("bottom","0") text:wikitext(ignoreBlank(args.text)) else -- In the arrow case, previous code didn't correctly line up the text -- Now that we're in Lua, it's easy to use a table to hold the arrow against the text -- One row: first td is arrow, second td is text -- Table gets placed directly using top CSS and absolute position local tbl = container:tag('table') tbl:attr("role","presentation") -- warn screen readers this table is for layout only -- choose a reasonable height for table, then position middle of that height in the timeline local delta = (args.unit

"em" and 4) or (args.unit

"px" and 40) or 0 tbl:css("height",checkDim(delta,args.unit,true)) tbl:css("position","absolute") tbl:css("top",checkDim(args.height*(args.to-args.at)/(args.to-args.from)-0.5*delta,args.unit,nil,"%.3f")) tbl:css("padding","0") local row = tbl:tag('tr') row:css("text-align","left") row:css("vertical-align","middle") local arrowCell = row:tag('td') arrowCell:css("padding","0") local arrowSpan = arrowCell:tag('span') arrowSpan:css("color",args.colour) arrowSpan:wikitext("←") --- HTML for left-pointing arrow local textCell = row:tag('td') textCell:css("padding","0") local text = textCell:tag('span') text:css("z-index","10") text:css("font-size",ignoreBlank(args.textsize)) text:css("color",ignoreBlank(args.colour)) text:css("display","block") text:css("line-height","105%") --- don't crunch multiple lines of text text:css("bottom","0") text:wikitext(ignoreBlank(args.text)) endend

-- Function to render all annotations in timeline-- Arguments:-- container = parent HTML object-- args = arguments to main function---- Global (main) arguments are parsed, individual box arguments are picked out-- and passed to p._singleNote above---- The function looks for note*, where * is a string of digits-- That string of digits is then used to find corresponding parameters of the individual note.-- For example, if note23 is found, then note23-colour turns into local colour,-- note-at turns into local at, note-texdt turns into local text, etc.---- args["annotation-width"] overrides automatically determined width of annotation divfunction p._annotations(container,args) local noteArgs = p._scanArgs(args,, ) if #noteArgs

0 then return end -- a div to hold all of the notes local notes = container:tag('div') notes:attr("id","Annotations"..(args["instance-id"] or "")) notes:css("float","left") notes:css("position","relative") -- Is there a "real" note? If so, leave room for it -- real is: is non-empty and (has arrow or isn't nudged left) local realNote = false for _, narg in ipairs(noteArgs) do local left = (tonumber(narg.nudgeleft) or 0)-(tonumber(narg.nudgeright) or 0) if narg.text ~= "" and (not narg.noarr or left <= 0) then realNote = true args.hasRealNote = true -- record realNote boolean in args for further use break end end -- width of notes holder depends on whethere there are any "real" notes -- width can be overriden local aw = tonumber(args["annotations-width"]) or (realNote and defaultAW) or 0 notes:css("width",checkDim(aw+2.25,"em",true)) for _, narg in ipairs(noteArgs) do --- copy required global parameters to local note args narg.from = args.from narg.to = args.to narg.height = args.height narg.unit = args["height-unit"] or args["width-unit"] or "em" narg.aw = args["annotations-width"] p._singleNote(notes,narg) endend

--

-- LEGENDS AND CAPTIONS--

-- Function to render a single legend (below the timeline)-- Arguments:-- container = parent HTML object-- args = argument table for this legend-- args.colour = color to show in square-- args.text = text that describes colorfunction p._singleLegend(container,args) if not args.text then -- if no text, not a sensible legend return end args.colour = args.colour or args.defaultColor or "transparent" local legend = container:tag('div') local square = legend:tag('span') square:css("background",ignoreBlank(args.colour)) square:css("padding","0em .1em") square:css("border","solid 1px #242020") square:css("height","1.5em") square:css("margin",".25em .9em .25em .25em") square:wikitext(" ") local text = legend:tag('span') text:wikitext(args.text) local clear = legend:tag('div') clear:css("clear","both")end

function p._legends(container,args) local legendArgs = p._scanArgs(args,, ) if #legendArgs

0 then return end local legend = container:tag('div') legend:attr("id","Legend"..(args["instance-id"] or "")) legend:addClass("toccolours") legend:css("margin-left","3.1em") legend:css("border-style","none") legend:css("float","left") legend:css("clear","both") for _,larg in ipairs(legendArgs) do p._singleLegend(legend,larg) endend

local helpString = [=[ ---- '''Usage instructions''' ---- Copy the text below, adding multiple bars, legends and notes as required. <br>Comments, enclosed in <code><!-</code><code>- -</code><code>-></code>, should be removed. Remember: * You must use <code>{</code><code>{!}</code><code>}</code> wherever you want a {{!}} to be : rendered in the timeline * Large borders will displace bars in many browsers * Text should not be wider than its containing bar, : as this may cause compatibility issues * Units default to [[em (typography){{!}}em]], the height and width of an 'M'.

See for full documentation.

}}]=]

local function createCaption(container,args) local caption = container:tag("div") caption:attr("id","Caption"..(args["instance-id"] or "")) caption:addClass("toccolours") if args.embedded then caption:css("margin","0 auto") caption:css("float","left") else caption:css("margin","0 0.5em") end caption:css("border-style","none") caption:css("clear","both") caption:css("text-align","center") local widthUnit = args["width-unit"] or args.unit or "em" local aw = tonumber(args["annotations-width"]) or (args.hasRealNote and defaultAW) or -0.25 aw = aw+5+((widthUnit

"em" and tonumber(args.width)) or 10) caption:css("width",checkDim(aw,"em",true)) caption:wikitext((args.caption or "")..((args.help and args.help ~= "off" and helpString) or ""))end

function p._main(args) -- For backward compatibility with template, all empty arguments are accepted. -- But, for some parameters, empty will cause a Lua error, so for those, we convert -- empty to nil. for _, attr in pairs do args[attr] = ignoreBlank(args[attr]) end -- Check that to > from, and that they're both defined local from = tonumber(args.from) or 0 local to = tonumber(args.to) or 0 if from > to then args.from = to args.to = from else args.from = from args.to = to end -- Create container div local container = createContainer(args) -- TITLE if args.title then createTitle(container,args) end container = container:tag("div") container:attr("id","Contains-Timeline-Scale-Note"..(args["instance-id"] or "")) -- NAVBOX HEADER if args["link-to"] then navboxHeader(container,args) end -- SCALEBAR p._scalemarkers(container,args) -- TIMELINE local timeline = createTimeline(container,args) -- PERIODS p._periods(timeline,args) -- BARS p._bars(timeline,args) -- ANNOTATIONS p._annotations(container,args) -- Pop to outer container for legend and captions container = container:allDone -- LEGEND p._legends(container,args) -- CAPTION createCaption(container,args) return containerend

function p.main(frame) local args = getArgs(frame,) return tostring(p._main(args):allDone)end

return p