All files / src/utils pageIcons.ts

100% Statements 61/61
100% Branches 36/36
100% Functions 15/15
100% Lines 51/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124                    21x     21x 21x   21x 4441x               21x 21x             11x 9x 8x 8x   1x         6x 3x 3x 1x   2x                 4176x 4174x         11x 11x 10x 9x 9x 7x 6x     1x 1x 1x     7x   9x         5x   3x   6x 3x     1x 1x 1x     5x               11x 11x 10x 10x 10x 10x 31x 26x 22x   10x         18x 18x    
/**
 * Loads the space menu icons on demand (UC-SPACE-015.1). A page can use any
 * Font Awesome free solid icon; the most common ones are registered in
 * main.ts, every other one is fetched once from its own small file (see
 * vite-plugins/pageIcons.ts) and kept in memory for the tab.
 */
import { findIconDefinition, type IconDefinition } from '@fortawesome/fontawesome-svg-core'
import { version } from '@fortawesome/free-solid-svg-icons/package.json'
 
/** Same path as PAGE_ICONS_DIR in vite-plugins/pageIcons.ts */
const PAGE_ICONS_PATH = `${import.meta.env.BASE_URL}page-icons/${version}/`
 
/** Same rule as the API's isPageIcon (utils/spacePages.js) */
const PAGE_ICON_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
const PAGE_ICON_MAX_LENGTH = 50
 
export const isPageIcon = (name: unknown): name is string =>
  typeof name === 'string' && name.length <= PAGE_ICON_MAX_LENGTH && PAGE_ICON_REGEX.test(name)
 
/** An icon of the search index: its name and the other names it is known by */
export interface PageIconEntry {
  name: string
  aliases: string[]
}
 
const icons = new Map<string, Promise<IconDefinition | null>>()
let index: Promise<PageIconEntry[]> | null = null
 
/**
 * Fetches a JSON file. CloudFront answers a missing file with index.html and a
 * 200, so a body that is not JSON counts as missing too.
 */
async function fetchJson(url: string): Promise<unknown> {
  const response = await fetch(url)
  if (!response.ok) return null
  try {
    return await response.json()
  } catch {
    return null
  }
}
 
function toDefinition(name: string, data: unknown): IconDefinition | null {
  if (!Array.isArray(data) || data.length !== 3) return null
  const [width, height, path] = data
  if (typeof width !== 'number' || typeof height !== 'number' || typeof path !== 'string') {
    return null
  }
  return {
    prefix: 'fas',
    iconName: name as IconDefinition['iconName'],
    icon: [width, height, [], '', path]
  }
}
 
/** An icon already registered in the library (main.ts), without any request */
export function registeredPageIcon(name: string): IconDefinition | null {
  if (!isPageIcon(name)) return null
  return findIconDefinition({ prefix: 'fas', iconName: name as IconDefinition['iconName'] }) ?? null
}
 
/** An icon's definition, null for a name Font Awesome does not have */
export function loadPageIcon(name: string): Promise<IconDefinition | null> {
  const registered = registeredPageIcon(name)
  if (registered) return Promise.resolve(registered)
  if (!isPageIcon(name)) return Promise.resolve(null)
  let pending = icons.get(name)
  if (!pending) {
    pending = fetchJson(`${PAGE_ICONS_PATH}${name}.json`).then(
      (data) => toDefinition(name, data),
      (error) => {
        // A network error: forget it so that the next display tries again
        console.error(`Failed to load the page icon "${name}":`, error)
        icons.delete(name)
        return null
      }
    )
    icons.set(name, pending)
  }
  return pending
}
 
/** Every icon, for the editor's search (loaded once, ~10 KB gzipped) */
export function loadPageIconIndex(): Promise<PageIconEntry[]> {
  index ??= fetchJson(`${PAGE_ICONS_PATH}index.json`).then(
    (data) =>
      Array.isArray(data)
        ? data
            .filter((row): row is string[] => Array.isArray(row) && isPageIcon(row[0]))
            .map(([name, ...aliases]) => ({ name, aliases }))
        : [],
    (error) => {
      console.error('Failed to load the page icon index:', error)
      index = null
      return []
    }
  )
  return index
}
 
/**
 * The icons matching a search, those whose name starts with it first, then
 * those containing it, then those with a matching alias (`home` finds `house`).
 */
export function searchPageIcons(entries: PageIconEntry[], query: string, limit: number): string[] {
  const q = query.trim().toLowerCase().replace(/\s+/g, '-')
  if (!q) return []
  const starts: string[] = []
  const contains: string[] = []
  const byAlias: string[] = []
  for (const { name, aliases } of entries) {
    if (name.startsWith(q)) starts.push(name)
    else if (name.includes(q)) contains.push(name)
    else if (aliases.some((alias) => alias.includes(q))) byAlias.push(name)
  }
  return [...starts, ...contains, ...byAlias].slice(0, limit)
}
 
/** For the tests: forgets every loaded icon and the index */
export function resetPageIconCache() {
  icons.clear()
  index = null
}