Module:Listing

From Zelda Dungeon Wiki
Revision as of 03:28, July 24, 2020 by Locke (talk | contribs) (proof-of-concept parser for listing pages. may or may not decide to use this to generate navboxes)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
Want an adless experience? Log in or Create an account.

Documentation for this module may be created at Module:Listing/doc

local p = {}

function p.getSections( pageContent )
  local currentSection = {
    level = 1,
    name = "", -- TODO page name (change args to take pagename and get the content in this function)
    content = "",
    summary = "",
    sections = {}
  }

  -- can't think of a regex to split sections so go line by line
  for line in mw.text.gsplit( pageContent, '\n' ) do
    local headingLevel, headingText = string.match( line, '%s*(=+)%s*(.-)%s*=+' )
    if headingLevel then -- line is a heading
      local newSection = {
        level = #headingLevel,
        name = headingText,
        content = "",
        summary = "",
        sections = {}
      }

      -- find the right parent and insert
      while currentSection.level >= #headingLevel do
        currentSection = currentSection.parent
      end
      newSection.parent = currentSection
      currentSection.sections[#currentSection.sections + 1] = newSection
      currentSection = newSection
    elseif #currentSection.sections == 0 then -- no child headings yet so this is part of the summary of the current section
      currentSection.summary = currentSection.summary .. line .. '\n'
    end

    -- add to content of all parent sections, plus current section if line isn't a heading
    local contentBackfillSection = headingLevel and currentSection.parent or currentSection
    repeat
      contentBackfillSection.content = contentBackfillSection.content .. line .. '\n'
      contentBackfillSection = contentBackfillSection.parent
    until not contentBackfillSection
  end

  -- navigate back to the root to return
  while currentSection.parent do
    currentSection = currentSection.parent
  end
  return currentSection
end

p.debugContent = [[
Summary {{Infobox|thing=value}}

== First Section ==
Section 1 summary {{Template|prop=val}}

=== Subsection of First Section ===
Subsection 1 content {{Template|prop=val}}

== Second Section ==
Section 2 summary {{Template|prop=val}}

=== Subsection of Second Section ===
Subsection 2 content {{Template|prop=val}}

{{Cat}}
]]

return p