From 33c9e8bca54d753c7ea976dd178db0cd5408c218 Mon Sep 17 00:00:00 2001
From: MohamedBassem <me@mbassem.com>
Date: Tue, 13 Feb 2024 00:29:25 +0000
Subject: feature: A usable, yet ugly browser extension

---
 packages/browser-extension/src/SavePage.tsx | 61 +++++++++++++++++++----------
 1 file changed, 41 insertions(+), 20 deletions(-)

(limited to 'packages/browser-extension/src/SavePage.tsx')

diff --git a/packages/browser-extension/src/SavePage.tsx b/packages/browser-extension/src/SavePage.tsx
index c66cc0ad..e202aea5 100644
--- a/packages/browser-extension/src/SavePage.tsx
+++ b/packages/browser-extension/src/SavePage.tsx
@@ -5,23 +5,49 @@ export default function SavePage({ settings }: { settings: Settings }) {
   const [loading, setLoading] = useState(true);
   const [error, setError] = useState<string | undefined>(undefined);
 
-  async function runFetch() {
-    const resp = await fetch(
-      `${settings.address}/api/trpc/bookmarks.bookmarkLink`,
-      {
-        method: "POST",
-      },
-    );
+  useEffect(() => {
+    async function runFetch() {
+      let currentUrl;
+      const [currentTab] = await chrome.tabs.query({
+        active: true,
+        lastFocusedWindow: true,
+      });
+      if (currentTab?.url) {
+        currentUrl = currentTab.url;
+      } else {
+        setError("Couldn't find the URL of the current tab");
+        setLoading(false);
+        return;
+      }
 
-    if (!resp.ok) {
-      setError("Something went wrong: " + (await resp.json()));
-    }
-    setLoading(false);
-  }
+      try {
+        const resp = await fetch(
+          `${settings.address}/api/trpc/bookmarks.bookmarkLink`,
+          {
+            method: "POST",
+            headers: {
+              Authorization: `Bearer ${settings.apiKey}`,
+              "Content-Type": "application/json",
+            },
+            body: JSON.stringify({
+              type: "link",
+              url: currentUrl,
+            }),
+          },
+        );
+        if (!resp.ok) {
+          setError(
+            "Something went wrong: " + JSON.stringify(await resp.json()),
+          );
+        }
+      } catch (e) {
+        setError("Message: " + (e as Error).message);
+      }
 
-  useEffect(() => {
+      setLoading(false);
+    }
     runFetch();
-  }, []);
+  }, [settings]);
 
   if (loading) {
     return <div>Loading ...</div>;
@@ -31,10 +57,5 @@ export default function SavePage({ settings }: { settings: Settings }) {
     return <div className="text-red-500">{error} ...</div>;
   }
 
-  return (
-    <div>
-      SAVED!
-      <button onClick={runFetch}> Reload </button>
-    </div>
-  );
+  return <div>SAVED!</div>;
 }
-- 
cgit v1.2.3-70-g09d2

