A link without an icon of its own gets the library's light version when there is one (github-light), instead of a dark logo on a dark card. The server keeps the library's list of names for a day.
66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
// Where a link's icon comes from. Pure, so it can be tested without a browser.
|
|
|
|
const LIBRARY = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons"
|
|
|
|
/** JSON with the file names of every icon in the library: `{ png: ["plex.png", …] }`. */
|
|
export const LIBRARY_INDEX = `${LIBRARY}/tree.json`
|
|
|
|
/** How a link stores an icon that the user uploaded: this plus the icon's id. */
|
|
export const UPLOADED_ICON = "/api/icon?id="
|
|
|
|
const slug = (name: string) =>
|
|
name
|
|
.trim()
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, "-")
|
|
.replace(/^-|-$/g, "")
|
|
|
|
export const libraryIcon = (name: string) => `${LIBRARY}/png/${slug(name)}.png`
|
|
|
|
/**
|
|
* The library has a light version of some icons (`github-light`), made for dark
|
|
* backgrounds like the cards. Its name for a link that is called `name`, or null.
|
|
*/
|
|
export function lightVariant(libraryNames: Set<string>, name: string) {
|
|
const light = `${slug(name)}-light`
|
|
return libraryNames.has(light) ? light : null
|
|
}
|
|
|
|
/** An image address or an upload, not a name in the library. */
|
|
export const isImageAddress = (icon: string) =>
|
|
/^https?:\/\//.test(icon) || icon.startsWith(UPLOADED_ICON)
|
|
|
|
/** Icon sources to try in order; the letter tile is the last resort. */
|
|
export function iconSources({
|
|
name,
|
|
url,
|
|
icon,
|
|
lightIcon,
|
|
}: {
|
|
name: string
|
|
url: string
|
|
icon: string | null
|
|
/** see lightVariant; only used when the link has no icon of its own */
|
|
lightIcon?: string | null
|
|
}) {
|
|
return [
|
|
icon && isImageAddress(icon)
|
|
? icon
|
|
: libraryIcon(icon || lightIcon || name),
|
|
`${new URL(url).origin}/favicon.ico`,
|
|
]
|
|
}
|
|
|
|
/**
|
|
* Library icons for what the user typed: names that start with it, then names that
|
|
* contain it. In both groups the shortest first, so "plex" is before "plex-alt".
|
|
*/
|
|
export function searchIcons(names: string[], query: string, limit = 42) {
|
|
const q = slug(query)
|
|
const rank = (n: string) => (n.startsWith(q) ? 0 : 1000) + n.length
|
|
return names
|
|
.filter((n) => n.includes(q))
|
|
.sort((a, b) => rank(a) - rank(b))
|
|
.slice(0, limit)
|
|
}
|