aboutsummaryrefslogtreecommitdiff
path: root/extension/src/components/BMIcon.tsx
blob: e7c2a26d3762dfd20c64242213d886e14690d413 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import React, {SyntheticEvent, useEffect} from "react";
import ColorThief from "colorthief";
import {getBrowser} from "../main.tsx";

function BMIcon (props: {url: string, id: string}) {

    let [favicon, setFavicon] = React.useState<string | null>(null);
    let [iconMode, setIconMode] = React.useState<"large" | "small" | "letter">("letter");
    let [bgColor, setBgColor] = React.useState<[number, number, number] | null>(null)
    let [bgColorPriority, setBgColorPriority] = React.useState(0);

    useEffect(() => {
        faviconURL(props).then(r => {
            if (r) {
                setFavicon(r)
                setIconMode("small");
            }
        })
    }, []);

    function handleImageLoad(e: SyntheticEvent<HTMLImageElement, Event>) {
        if (e.currentTarget.naturalWidth >= 75 || favicon!.startsWith("data:image/svg+xml")) {
            setIconMode("large")
        } else if(bgColorPriority < 2) {
            setBgColor(new ColorThief().getColor(e.currentTarget))
            setBgColorPriority(2);
        }
    }

    return (
        <div className={"icon-box " + (iconMode)}
             style={bgColor ? {"--icon-bg": `rgba(${bgColor[0]}, ${bgColor[1]}, ${bgColor[2]}, 0.2)`} as React.CSSProperties : undefined}>
            {(() => {
                switch (iconMode) {
                    case "letter": {
                        let url = new URL(props.url);
                        if (bgColorPriority < 1) {
                            setBgColor(hashStringToColor(url.hostname));
                            setBgColorPriority(1);
                        }
                        return (<span className={"letter"}>{url.hostname.charAt(0)}</span>)
                    }
                    case "small": {
                        return (<img alt="Bookmark icon" src={favicon!} onLoad={handleImageLoad}/>)
                    }
                    case "large": {
                        return (<img alt="Bookmark icon" src={favicon!}/>)
                    }
                }
            })()}
        </div>
    )
}

/**
 * Gets the icon for a bookmark
 *
 * @param data The URL of the link
 * @return The URL of the icon
 */
async function faviconURL(data: {url: string, id:string}) {
    let i = (await getBrowser().storage.local.get("icon-cache-"+data.id))["icon-cache-"+data.id];
    if (i) return i
    // if (i == null) return i;

    const url = new URL('https://www.google.com/s2/favicons');
    url.searchParams.set("sz", "256");
    url.searchParams.set("domain_url", data.url!);
    let resp = await fetch(url)
    let imgData = resp.ok ? await toDataURL(url.toString()) : null;
    getBrowser().storage.local.set({["icon-cache-"+data.id]: 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)
        }))
}

function djb2(str: string){
    let hash = 5381;
    for (var i = 0; i < str.length; i++) {
        hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
    }
    return hash;
}

function hashStringToColor(str: string): [number, number, number] {
    let hash = djb2(str);
    let r = (hash & 0xFF0000) >> 16;
    let g = (hash & 0x00FF00) >> 8;
    let b = hash & 0x0000FF;
    return [r, g, b];
}

export default BMIcon;