Template duplication and event.listener hijinks

I’m going to confess up front that I spun up v2 and then got distracted with life, so I’m probably doing something hilariously overwrought and unnecessary.

Desired functionality: My need is to have (a) visits to the index intercepted and redirected to my journal and (b) create a journal page from a template if it doesn’t exist.

Behavior: My setup largely works, except that the template is sometimes inserted multiple times if I reload the page. This could be related to an issue where a template doesn’t apply if I create a link and immediately click it and the link should be triggering application of a template.

A brief aside…

You’re about to see some code. I got v2 set up shortly after it was released and was exploring how to use it. Please be gentle.

Question: Is there an easier way to do all … waves hands this template stuff now?

Current solution: everything is handled in a CONFIG file in my document root. That file contains a space-lua block that does a bunch of configuration things.

Redirect index

local function redirectToCustomIndex()

  if editor.getCurrentPage() == "index" then
    editor.navigate({kind = "page", page = "Journal/Day/" .. os.date('%Y') .. "/" .. os.date('%m') .. "/" .. date.today()})
  end

end

Event listeners

-- Listener: When initiating editor or loading page, redirectToCustomIndex()
event.listen {

  name = "editor:init",
  run = redirectToCustomIndex

}

event.listen {

  name = "editor:pageLoaded",
  run = redirectToCustomIndex

}

-- Listener: When creating a page, use a template based on the name in the path (top-level, e.g., "Meeting"), or "Daily Note" for Journal, or a blank bullet for anything else

event.listen {

  name = "editor:pageCreating",
  run = function(e)

    local templateFlag = e.data.name:match("([^/]*)")
    local templateName = ""

    if templateFlag == "Journal" then
      templateName = "Library/Templates/New Daily Note"
    else
      templateName = "Library/Templates/New " .. templateFlag
    end

    if not space.pageExists(templateName) then
      templateName = "Library/Templates/Default"
    end

    createPageFromTemplate(templateName, e.data.name)
    
  end

}

Also, at some point I overrode createPageFromTemplate while trying to troubleshoot the duplication issue. I’m including this for completeness, but I almost didn’t because the duplication issue was happening with the standard function.

-- Function: Create a page from a template (override Library/Std to test what may be a race condition
local creatingPages = {}

local function createPageFromTemplate(templatePage, pageName)

  if creatingPages[pageName] then
    return
  end

  creatingPages[pageName] = true

  if space.pageExists(pageName) then
    editor.flashNotification("Page " .. pageName .. " already exists", "error")
    creatingPages[pageName] = nil
    return
  end

  local tpl, fm = template.fromPage(templatePage)
  local initialText = ""

  if fm.frontmatter then
    initialText = "---\n" .. string.trim(template.new(fm.frontmatter)()) .. "\n---\n"
  end

  space.writePage(pageName, initialText)
  editor.navigate({kind = "page", page = pageName})

  event.listen {
    name = "editor:pageLoaded",
    once = true,

    run = function(e)
      if e.data[1] == pageName then
        local tries = 0
        local function tryInsert()
          local doc = editor.getText()
          if doc and #doc >= #initialText then
            editor.insertAtPos(tpl(), #initialText, true)
            creatingPages[pageName] = nil
          elseif tries < 10 then
            tries = tries + 1
            setTimeout(tryInsert, 100)
          else
            editor.flashNotification("Failed to insert template content", "error")
            creatingPages[pageName] = nil
          end
        end
        tryInsert()
      else
        creatingPages[pageName] = nil
      end
    end
  }
end

You should return the page content from the pageCreating listener. So render page using template api and then return the finished string. Unsure what you are trying to do with the pageLoaded listener.