From 41814aa14040aa038c17ee0728532b0e341c5953 Mon Sep 17 00:00:00 2001
From: sowgro <tpoke.ferrari@gmail.com>
Date: Tue, 31 Dec 2024 00:49:03 -0500
Subject: Refactor BMIcon

---
 extension/src/components/Bookmark.tsx | 54 +++++++++++++++++++++++++++++++++--
 1 file changed, 52 insertions(+), 2 deletions(-)

(limited to 'extension/src/components/Bookmark.tsx')

diff --git a/extension/src/components/Bookmark.tsx b/extension/src/components/Bookmark.tsx
index 0e36b56..a57f7f7 100644
--- a/extension/src/components/Bookmark.tsx
+++ b/extension/src/components/Bookmark.tsx
@@ -84,7 +84,7 @@ function Bookmark(props: {id: string}) {
     return(
         <div className={"bookmark"}>
             <a href={bmData.url} draggable={settings.editMode} onDrag={handleDrag} onDragEnd={handleDragEnd}>
-                <BMIcon url={bmData.url!} id={bmData.title}/>
+                <IconPre id={bmData.id} bmUrl={bmData.url!}/>
                 <span>{bmData.title}</span>
             </a>
             {settings.editMode && <ContextMenu onEdit={handleEdit} onDelete={handleDelete}/>}
@@ -94,4 +94,54 @@ function Bookmark(props: {id: string}) {
     );
 }
 
-export default Bookmark;
\ No newline at end of file
+export default Bookmark;
+
+function IconPre(props: {bmUrl: string, id:string}) {
+    const [data, setData] = useState()
+
+    useEffect(() => {
+        findIcon(props.bmUrl, props.id).then(r => {
+            setData(r);
+        })
+    }, []);
+
+    if (!data) return;
+    return <BMIcon bmUrl={props.bmUrl} imgSrc={data}/>
+}
+
+/**
+ * 1. check for icon cache
+ * 2. check if the user selected an icon
+ * 3. use the best icon from the available icons
+ * 4. search googles icon database
+ */
+async function findIcon(bmUrl: string, id:string) {
+    let cachedIcon = (await getBrowser().storage.local.get("icon-cache-"+id))["icon-cache-"+id];
+    if (cachedIcon) return cachedIcon
+
+    // let selectedUrl: string[] = (await getBrowser().storage.local.get("icon-aval-"+data.id))["icon-aval-"+data.id]
+    // if (selectedUrl.length > 0) {
+    //     await getBrowser().storage.local.set({["icon-cache-"+data.id]: selectedUrl[0]});
+    //     return selectedUrl[0];
+    // }
+
+    const url = new URL('https://www.google.com/s2/favicons');
+    url.searchParams.set("sz", "256");
+    url.searchParams.set("domain_url", bmUrl);
+    let resp = await fetch(url)
+    let imgData = resp.ok ? await toDataURL(url.toString()) : null;
+    getBrowser().storage.local.set({["icon-cache-"+bmUrl]: imgData});
+    return imgData;
+}
+
+function toDataURL(url: string): string {
+    // @ts-ignore
+    return fetch(url)
+        .then(response => response.blob())
+        .then(blob => new Promise((resolve, reject) => {
+            const reader = new FileReader()
+            reader.onloadend = () => resolve(reader.result)
+            reader.onerror = reject
+            reader.readAsDataURL(blob)
+        }))
+}
\ No newline at end of file
-- 
cgit v1.2.3

