import React, {SyntheticEvent, useEffect, useState} from "react"; import ColorThief from "colorthief"; import {getBrowser} from "../main.tsx"; function BMIcon(props: {imgSrc?: string, bmUrl?:string}) { let [iconMode, setIconMode] = React.useState<"large" | "small" | "letter">("large"); let [bgColor, setBgColor] = React.useState<[number, number, number] | null>(null) function handleImageLoad(e: SyntheticEvent) { if (e.currentTarget.naturalWidth < 75 && !props.imgSrc!.startsWith("data:image/svg+xml")) { setBgColor(new ColorThief().getColor(e.currentTarget)); setIconMode("small"); } } function handleImageError() { if (props.bmUrl) { let url = new URL(props.bmUrl); setBgColor(hashStringToColor(url.hostname)) } setIconMode("letter"); } if (!props.imgSrc) { if (props.bmUrl) { let url = new URL(props.bmUrl); bgColor = hashStringToColor(url.hostname) } iconMode = "letter" } return (
{(() => { switch (iconMode) { case "letter": { return ({ props.bmUrl ? new URL(props.bmUrl).hostname.charAt(0) : '?' }) } case "small": { return (Bookmark icon) } case "large": { return (Bookmark icon) } }})()}
) } function hashStringToColor(str: string): [number, number, number] { let hash = 5381; for (var i = 0; i < str.length; i++) { hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */ } let r = (hash & 0xFF0000) >> 16; let g = (hash & 0x00FF00) >> 8; let b = hash & 0x0000FF; return [r, g, b]; } export default BMIcon;