Module:Grouped columns

From Final Fantasy XIV Online Wiki
Jump to navigation Jump to search
Documentation for Module:Grouped columns [view] [edit] [history] [purge] (How does this work?)

Implements {{Grouped columns}}.

local getArgs = require("Module:Arguments").getArgs

local p = {}

function p.main(frame)
  local args = getArgs(frame, {parentOnly = true})
  local columnMinWidth = tonumber(args["min width"]) or 24
  local maxColumns = tonumber(args.columns)

  local wrapper = mw.html.create("div"):css({
    ["column-width"] = ("%dem"):format(columnMinWidth),
    ["column-count"] = maxColumns and tostring(maxColumns) or nil,
  })

  local group_start = [[<div style="break-inside:avoid-column;border-top:1px solid transparent;margin-top:-1px">]]
  local group_end = [[</div>]]

  local lines = (args[1] .. "\n"):gmatch("(.-)\n")

  local grouped_lines = group_start
  for line in lines do
    -- when we encounter a heading, close current group and open a new one
    -- however, if the initial group has no content yet (i.e. first line of
    -- input is a heading), do not close the empty initial group
    if line:match("^=") and grouped_lines ~= group_start then
      -- also trim any trailing whitespace from the end of the old group
      grouped_lines = grouped_lines:gsub('%s-$', '')
      -- close the group and open the next one
      grouped_lines = grouped_lines .. "\n" .. group_end .. "\n" .. group_start
    end
    -- add line to current group
    grouped_lines = grouped_lines .. "\n" .. line
  end

  -- trim trailing whitespace and close group
  grouped_lines = grouped_lines:gsub('%s-$', '')
  grouped_lines = grouped_lines .. "\n" .. group_end

  wrapper:wikitext(grouped_lines)
  return tostring(wrapper)
end

return p