Page/Document directory example in Lua (v2)

Just an example of a display of pages/documents and “directories”

njb = njb or {}


function njb.splitPath(path)
  local parts = {}
  for part in string.gmatch(path, "([^/]+)") do
    table.insert(parts, part)
  end
  return parts
end

local function newNode()
  return { children = {}, item = nil }
end

function njb.renderTree(node, indentLevel)
  indentLevel = indentLevel or 0
  local markup = ""
  for name, child in pairs(node.children) do
    print(name)
    local linked = "[[" .. child.item.path .. "|" .. name .. "]] " .. (child.item.lastModified or "") 
    -- local linked = "[" .. name .. "](" .. child.item.path .. ")"
    local symbol
    if child.item.type=="folder" then
      symbol = "📁"
    else 
      symbol = "📄"
    end
    local line = "\n| └─" .. string.rep("──", indentLevel) .. symbol .. linked .. " |"
    markup = markup .. line .. njb.renderTree(child, indentLevel + 1)
  end
  return markup
end


function njb.listAllThings()
  local allThings = {}

  local pages = space.listPages()
  for _, page in ipairs(pages) do
    table.insert(allThings, {
      type = "page",
      path = page.name,
      contentType = page.contentType,
      perm = page.perm,
      tag = page.tag,
      lastModified = page.lastModified
    })
  end
  print("Found " .. #pages .. " pages")

  local docs = space.listDocuments()
  for _, doc in ipairs(docs) do
    table.insert(allThings, {
      type = "document",
      path = doc.name,
      contentType = doc.contentType,
      perm = doc.perm,
      tag = doc.tag,
      lastModified = doc.lastModified
    })
    -- print(doc)
  end
  print("Found " .. #docs .. " docs")

  -- Build the tree using the allThings data.
  local tree = newNode()
  for _, item in ipairs(allThings) do
    local parts = njb.splitPath(item.path)
    local node = tree
    for i, part in ipairs(parts) do
      if not node.children[part] then
        node.children[part] = newNode()
      end
      node = node.children[part]
      if i == #parts then
        node.item = item
      else
        -- if not a real item, still need a path for the user to click on?
        node.item = {
          type = "folder",
          path =  table.concat(parts,"/",1,i),
          contentType = nil,
          perm = nil,
          tag = nil,
          lastModified = nil
        }
      end
    end
  end
print(tree)
  local markup = njb.renderTree(tree, 0)
  markup = "| Page |\n|---|" .. markup
  return widget.new { markdown = markup }
end

Generate the table with

${njb.listAllThings()}

Looks like:

3 Likes

I did this to get something like Tree View on v2, but Migrate from v1 showed me how to get Tree View back on v2:

config.set("plugs", {
  "github:joekrill/silverbullet-treeview/treeview.plug.js"
})