// Extend the application with search functionality
// To make this new extension go away, you either need to reload the page or use extensionsUninstall.

const searchResults = []
let searchText = ""

function search() {
    searchResults.splice(0)
    const notebook = Twirlip7.getCurrentNotebook()
    if (!searchText) return
    for (let i = 0; i < notebook.itemCount(); i++) {
        const item = notebook.getItemForLocation(i)
        if (item && item.indexOf(searchText) !== -1) {
            const key = notebook.keyForLocation(i)
            searchResults.push({i, key, item})
        }
    }
}

Twirlip7.workspaceView.extensionsInstall({
    id: "search-plain",
    // For tags, try header, middle, and footer
    tags: "header",
    code: () => {
        return m("div",
            searchResults.map((result) => {
                return m("div", {
                    title: result.item, 
                    onclick: Twirlip7.workspaceView.goToKey.bind(null, result.key)
                }, "" + (result.i + 1) + ") " + result.item.substring(0, 120) + "...")
            }),
            "Find items matching:",
            m("input.ma1", { value: searchText, onchange: (event) => searchText = event.target.value }),
            m("button.ma1", {onclick: search}, "Search"),
            m("button.ma1", {onclick: () => searchResults.splice(0)}, "Clear results"),
            m("hr")
        )
    }
})

// Twirlip7.workspaceView.extensionsUninstall({id: "search-plain"})

@@ -210,24 +210,29 @@
  search() %7B%0A
+    %0A
     searchRe
@@ -334,108 +334,44 @@
     
-for (let i = 0; i %3C notebook.itemCount(); i++) %7B%0A        const item = notebook.getItemForLocation(i)
+%0A    function processItem(i, item) %7B
 %0A   
@@ -438,19 +438,14 @@
     
-const key =
+return
  not
@@ -467,17 +467,37 @@
 ation(i)
-%0A
+.then((key) =%3E %7B%0A    
         
@@ -547,15 +547,367 @@
     
-%7D%0A    %7D
+        return Promise.resolve(null)%0A            %7D)%0A        %7D%0A        return Promise.resolve(null)%0A    %7D%0A    %0A    const promises = %5B%5D%0A    for (let i = 0; i %3C notebook.itemCount(); i++) %7B%0A        const promise = notebook.getItemForLocation(i).then(processItem.bind(null, i))%0A        promises.push(promise)%0A    %7D%0A    Promise.all(promises).then(() =%3E m.redraw())
 %0A%7D%0A%0A

Update extension search plain example for Promises