From c19262a4ce956d046b35274b11eef5db25833fd9 Mon Sep 17 00:00:00 2001
From: dragonwocky <thedragonring.bod@gmail.com>
Date: Fri, 20 Jan 2023 00:33:05 +1100
Subject: [PATCH] perf(load): import all deps at once + wait for load.mjs
 completion, fix(electron): use ipc for reloadApp

---
 src/api/electron.cjs   |  10 ++--
 src/core/menu/menu.mjs |   6 +--
 src/init.js            |   2 +
 src/load.mjs           |  16 ++++---
 src/worker.js          | 102 +++++++++++++++++++++++++----------------
 5 files changed, 82 insertions(+), 54 deletions(-)

diff --git a/src/api/electron.cjs b/src/api/electron.cjs
index a2a12ba..1be69ca 100644
--- a/src/api/electron.cjs
+++ b/src/api/electron.cjs
@@ -31,10 +31,12 @@ const readFile = (file) => {
     return require(path.resolve(`${__dirname}/../${file}`));
   },
   reloadApp = () => {
-    const { app } = require("electron"),
-      args = process.argv.slice(1).filter((arg) => arg !== "--startup");
-    app.relaunch({ args });
-    app.exit();
+    const { app, ipcRenderer } = require("electron");
+    if (app) {
+      const args = process.argv.slice(1).filter((arg) => arg !== "--startup");
+      app.relaunch({ args });
+      app.exit();
+    } else ipcRenderer.send("notion-enhancer", "reload-app");
   };
 
 const sendMessage = (channel, message) => {
diff --git a/src/core/menu/menu.mjs b/src/core/menu/menu.mjs
index c2cc8c3..8123cd3 100644
--- a/src/core/menu/menu.mjs
+++ b/src/core/menu/menu.mjs
@@ -411,8 +411,6 @@ useState(["rerender"], async () => {
     // the notion:// protocol csp bypass allows scripts to
     // set iframe globals via $iframe.contentWindow
   }
-  // load stylesheets from enabled themes
-  await import("../../load.mjs");
-  // wait for api globals to be available
-  requestIdleCallback(() => render());
+  // load stylesheets and api globals
+  (await import("../../load.mjs")).default.then(render);
 });
diff --git a/src/init.js b/src/init.js
index a29501a..4562f44 100644
--- a/src/init.js
+++ b/src/init.js
@@ -26,6 +26,8 @@ if (isElectron()) {
   } = globalThis.__enhancerApi;
 
   module.exports = async (target, __exports, __eval) => {
+    if (target === "main/main") require("./worker.js");
+
     // clientStyles
     // clientScripts
     if (target === "renderer/preload") {
diff --git a/src/load.mjs b/src/load.mjs
index 0cc8bca..e131fb5 100644
--- a/src/load.mjs
+++ b/src/load.mjs
@@ -6,7 +6,7 @@
 
 "use strict";
 
-(async () => {
+export default (async () => {
   // prettier-ignore
   const { enhancerUrl } = globalThis.__enhancerApi,
   isMenu = location.href.startsWith(enhancerUrl("/core/menu/index.html")),
@@ -17,13 +17,15 @@
   // avoid repeat logging
   if (!isMenu) console.log("notion-enhancer: loading...");
 
-  await import("./assets/icons.svg.js");
-  await import("./vendor/twind.min.js");
-  await import("./vendor/lucide.min.js");
-  await import("./vendor/htm.min.js");
+  await Promise.all([
+    import("./assets/icons.svg.js"),
+    import("./vendor/twind.min.js"),
+    import("./vendor/lucide.min.js"),
+    import("./vendor/htm.min.js"),
+    import("./api/events.js"),
+    import("./api/mods.js"),
+  ]);
   await import("./api/interface.js");
-  await import("./api/events.js");
-  await import("./api/mods.js");
   const { getMods, getProfile } = globalThis.__enhancerApi,
     { isEnabled, optionDefaults, initDatabase } = globalThis.__enhancerApi;
 
diff --git a/src/worker.js b/src/worker.js
index 3deb537..296f2a5 100644
--- a/src/worker.js
+++ b/src/worker.js
@@ -6,46 +6,70 @@
 
 "use strict";
 
-const notionUrl = "https://www.notion.so/",
-  isNotionTab = (tab) => tab?.url?.startsWith(notionUrl);
+const isElectron = () => {
+  try {
+    return typeof module !== "undefined";
+  } catch {}
+  return false;
+};
 
-const tabQueue = new Set(),
-  openEnhancerMenu = async (tab) => {
-    if (!isNotionTab(tab)) {
+if (isElectron()) {
+  const { app, ipcMain } = require("electron"),
+    reloadApp = () => {
+      const args = process.argv.slice(1).filter((arg) => arg !== "--startup");
+      app.relaunch({ args });
+      app.exit();
+    };
+
+  ipcMain.on("notion-enhancer", (event, message) => {
+    if (message === "open-menu") {
+      //
+    } else if (message === "reload-app") {
+      reloadApp();
+    }
+  });
+} else {
+  const notionUrl = "https://www.notion.so/",
+    isNotionTab = (tab) => tab?.url?.startsWith(notionUrl);
+
+  const tabQueue = new Set(),
+    openEnhancerMenu = async (tab) => {
+      if (!isNotionTab(tab)) {
+        const openTabs = await chrome.tabs.query({
+          windowId: chrome.windows.WINDOW_ID_CURRENT,
+        });
+        tab = openTabs.find(isNotionTab);
+        tab ??= await chrome.tabs.create({ url: notionUrl });
+      }
+      chrome.tabs.highlight({ tabs: [tab.index] });
+      if (tab.status === "complete") {
+        chrome.tabs.sendMessage(tab.id, {
+          channel: "notion-enhancer",
+          message: "open-menu",
+        });
+      } else tabQueue.add(tab.id);
+    },
+    reloadNotionTabs = async () => {
       const openTabs = await chrome.tabs.query({
-        windowId: chrome.windows.WINDOW_ID_CURRENT,
-      });
-      tab = openTabs.find(isNotionTab);
-      tab ??= await chrome.tabs.create({ url: notionUrl });
-    }
-    chrome.tabs.highlight({ tabs: [tab.index] });
-    if (tab.status === "complete") {
-      chrome.tabs.sendMessage(tab.id, {
-        channel: "notion-enhancer",
-        message: "open-menu",
-      });
-    } else tabQueue.add(tab.id);
-  },
-  reloadNotionTabs = async () => {
-    const openTabs = await chrome.tabs.query({
-        windowId: chrome.windows.WINDOW_ID_CURRENT,
-      }),
-      notionTabs = openTabs.filter(isNotionTab);
-    notionTabs.forEach((tab) => chrome.tabs.reload(tab.id));
-  };
+          windowId: chrome.windows.WINDOW_ID_CURRENT,
+        }),
+        notionTabs = openTabs.filter(isNotionTab);
+      notionTabs.forEach((tab) => chrome.tabs.reload(tab.id));
+    };
 
-chrome.action.onClicked.addListener(openEnhancerMenu);
-chrome.runtime.onMessage.addListener((msg, sender) => {
-  if (msg?.channel !== "notion-enhancer") return;
-  if (sender.tab && msg.message === "load-complete") {
-    if (tabQueue.has(sender.tab.id)) {
-      chrome.tabs.sendMessage(sender.tab.id, {
-        channel: "notion-enhancer",
-        message: "open-menu",
-      });
-      tabQueue.delete(sender.tab.id);
+  chrome.action.onClicked.addListener(openEnhancerMenu);
+  chrome.runtime.onMessage.addListener((msg, sender) => {
+    if (msg?.channel !== "notion-enhancer") return;
+    if (sender.tab && msg.message === "load-complete") {
+      if (tabQueue.has(sender.tab.id)) {
+        chrome.tabs.sendMessage(sender.tab.id, {
+          channel: "notion-enhancer",
+          message: "open-menu",
+        });
+        tabQueue.delete(sender.tab.id);
+      }
+    } else if (msg.message === "reload-app") {
+      reloadNotionTabs();
     }
-  } else if (msg.message === "reload-app") {
-    reloadNotionTabs();
-  }
-});
+  });
+}