# Icons

`@hamur/icon` gives every library one component, `Icon`, that draws an icon of an icon collection by name: `<Icon name="mdi:home" />`. The data comes from collections your app installed (`@iconify-json/<prefix>`) or keeps as SVG files. The module imports no Iconify package; it reads the Iconify JSON format with code of its own.

```sh
bun add @hamur/icon @iconify-json/mdi
```

````ts [icon/config.ts]
import { defineConfig } from "hamur"
import icon from "@hamur/icon"

export default defineConfig({
  framework: "react",
  modules: [icon],
  icon: {
    provider: "server",
    serverBundle: "local",
    clientBundle: { icons: ["mdi:home", "mdi:menu"], scan: true, sizeLimitKb: 256 },
    customCollections: [{ prefix: "brand", dir: "app/assets/icons", recursive: true }],
    cssLayer: "icons",
    cssClasses: true,
  },
})
````

Add the module to `modules`; its options live under the `icon` key. Your app imports `Icon` from `@hamur/icon/<library>`; in html, `Icon` from `@hamur/icon/html` returns a string you put in the page. Every option is in the [reference](/api-reference/icon#iconoptions).

## Drawing an icon

````tsx [icon/react/icons.tsx]
import { Icon } from "@hamur/icon/react"

export default function Nav() {
  return (
    <nav>
      <Icon name="mdi:home" />
      <Icon name="i-mdi-menu" mode="css" size={24} />
      <Icon name="logo" title="Hamur" className="logo" />
      <span className="i-mdi-account" />
    </nav>
  )
}
````

`name` is `prefix:name` (`mdi:home`), the class form `i-mdi-home` or `i-mdi:home`, or a key of the `aliases` option. The dash form is read against the collections the build knows, taking the longest prefix that leaves a name, so `i-material-symbols-home` is `material-symbols:home`. A prefix and a name match `/^[a-z0-9]+(-[a-z0-9]+)*$/`.

Without a `title` the icon is decorative (`aria-hidden="true"`); with one it gets `role="img"` and a `<title>` child. `size` is `1em` unless you set it, and a number is CSS pixels. The other libraries take the same props:

````vue [icon/vue/icons.vue]
<script setup lang="ts">
import { Icon } from "@hamur/icon/vue"
</script>

<template>
  <nav>
    <Icon name="mdi:home" />
    <Icon name="i-mdi-menu" mode="css" :size="24" />
    <Icon name="logo" title="Hamur" />
  </nav>
</template>
````

In Angular `Icon` is the component `hamur-icon`, with `name` and the other props as inputs:

````ts [angular/icons.ts]
import { Component } from "@angular/core"
import { Icon } from "@hamur/icon/angular"

@Component({
  imports: [Icon],
  template: `<nav>
    <hamur-icon name="mdi:home" />
    <hamur-icon name="i-mdi-menu" mode="css" [size]="24" />
    <hamur-icon name="logo" title="Hamur" />
  </nav>`,
})
export default class Nav {}
````

````ts [icon/html/nav.ts]
import { Icon } from "@hamur/icon/html"

export default function Nav(): string {
  return `<nav>${Icon({ name: "mdi:home" })}${Icon({ name: "i-mdi-menu", mode: "css", size: 24 })}</nav>`
}
````

## Modes

- **`svg`** (the default) draws an inline `<svg>` whose body is read through a sanitiser into elements, so nothing sets `innerHTML`. Ids inside an icon are prefixed per instance. A streamed page gets the whole icon where it stands.
- **`css`** draws `<span class="i-mdi:home">` and one rule per icon, written once per page in a `<style>` pushed through `useHead`. A body that uses `currentColor` is a mask painted in the text colour; a coloured one (a logo, a flag) is a plain background, so it keeps its colours. A CSS-mode icon that first renders inside a streamed boundary after the head was sent has no rule; use `svg` there.

`mode`, `size` and `class` can be set for the whole app as options of the module, and a prop wins over them:

````ts [icon/render-options.ts]
import { defineConfig } from "hamur"
import icon from "@hamur/icon"

export default defineConfig({
  framework: "react",
  modules: [icon],
  icon: { size: "1.25em", mode: "svg", aliases: { logo: "brand:logo", home: "mdi:home" } },
})
````

`aliases` maps a short name to any name form, so `<Icon name="logo" />` is `brand:logo`. The four reach the browser as `runtimeConfig.public.icon`, which is data, so a function does not fit: `customize(content, name, prefix)` is a prop of `Icon` only, and `icon.customize` fails as an unknown option. Its result goes through the same sanitiser as every body.

## Collections and the server bundle

For each `@iconify-json/<prefix>` your `package.json` lists in `dependencies` or `devDependencies`, the build reads `icons.json` (found from the app root upward, so a hoisted workspace install works) and writes it into the **icon server bundle**: data in the server output on every preset, never a public file. The server reads each collection once, at start, so a render needs no request. `serverBundle` sets which collections:

| Value                                | Collections                                            |
| ------------------------------------ | ------------------------------------------------------ |
| `"local"` (default)                  | every `@iconify-json/<prefix>` the app lists           |
| `{ collections: ["mdi", "lucide"] }` | exactly those, and the only way to use `@iconify/json` |
| `false`                              | none                                                   |

The build logs the size once, `[icon] server bundle: lucide 0.9 MB, mdi 4.1 MB`, so a heavy collection is easy to spot.

The server render puts each icon it drew into the page's payload, so hydration draws the same markup with no request.

## The client bundle

Icons whose name appears in your source reach the browser inside the app, so a client navigation draws them with no request. `clientBundle.icons` lists names yourself (`"mdi:home"`). With `scan: true` (the default) the build reads string literals of your `.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`, `.vue`, `.svelte`, `.css`, `.html`, `.md` and `.mdx` files below `srcDir`, `shared` and each layer's, and adds every one that is an icon name of a known prefix. `scan: { include, exclude }` narrows it with globs.

A name made from a variable is not found:

```tsx
<Icon name={`mdi:${kind}`} />
```

The server render still finds it in the server bundle and puts it in the payload; for the browser, list it in `clientBundle.icons`, or let the endpoint below serve it. A name its collection lacks logs `[icon] "mdi:nope" (app/pages/index.tsx) is not in the mdi collection` and is left out. A bundle above `sizeLimitKb` (256) fails the build with `icon client bundle is 300 KB, over icon.clientBundle.sizeLimitKb 256`.

## The endpoint and `provider`

An icon in neither the payload nor the client bundle is asked for when its `Icon` renders in the browser. `provider` says where:

| `provider`           | The browser asks                                                                                                                                         |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"server"` (default) | your own `/_hamur/icons/<prefix>.json?icons=a,b`, answered from the server bundle                                                                        |
| `"iconify"`          | the Iconify API at `iconifyApiEndpoint` (`https://api.iconify.design` by default)                                                                        |
| `"none"`             | nobody: no endpoint is registered, the icon stays empty and a development warning is logged; the default on the `static` and `cloudflare-static` presets |

Names asked within one microtask are one request per prefix, split at 100 names. While the answer is pending the icon is its empty sized box, then it draws. Answers are kept in memory and in `sessionStorage`; a name the answer lacks is remembered as missing for the session.

The endpoint answers in the Iconify API's shape, `200` while at least one asked icon exists (missing ones are listed in `not_found`), `404` when none does, with `cache-control: public, max-age=604800` and an `etag`. `fallbackToApi: true` makes it fetch the icons and collections its bundle lacks from `iconifyApiEndpoint`; it is `false` by default, so the app calls no third party. The `fetchTimeout` (1500 ms) bounds that call, and an API that is down counts as having no icon. The 400, 404, 405 and 504 answers are in the [reference](/api-reference/icon#default).

## Custom collections

Put SVG files in a folder and name it in `customCollections`: `app/assets/icons/logo.svg` is `brand:logo`. With `recursive: true` the folders join with `-`: `social/x.svg` is `social:x`. A file name must match the name rule above. Each file is read once at build by the same sanitiser as `?component` (no `<script>`, `<foreignObject>`, `<style>`, `on*` attribute or external `href`), and the size comes from its `viewBox`, else its `width` and `height`, else 24. A custom icon is in the server bundle, the client bundle, the scan and the endpoint like an installed one. In `hamur dev` an `.svg` added, changed or removed rebuilds the collection and reloads the page.

A module that holds icons as data adds a collection, or replaces one, with the `icon:collections` hook:

````ts [icon/collection-hook.ts]
import { defineConfig } from "hamur"
import icon from "@hamur/icon"

export default defineConfig({
  framework: "react",
  modules: [icon],
  hooks: {
    "icon:collections": (collections) => {
      collections.brand = {
        prefix: "brand",
        width: 24,
        height: 24,
        icons: { logo: { body: '<path fill="currentColor" d="M2 2h20v20H2z"/>' } },
      }
    },
  },
})
````

A prefix that two sources give, or that is also an installed collection, fails the build.

## The class utility

`cssClasses: true` writes the CSS-mode rule for every `i-<prefix>-<name>` or `i-<prefix>:<name>` class the scan finds in your source (`.css` selectors included), as global CSS. `<span class="i-mdi-account">` then works with no `Icon`, in html pages too. The rule's selector is the class as written; `cssSelectorPrefix` (default `i-`) renames the prefix, `cssLayer` wraps the rules in `@layer <name>`, and `cssWherePseudo` (default `true`) writes `:where(.i-mdi\:home)`, specificity 0, so your own rule wins.

## Testing

Under `bun test` no build ran, so the server plugin has not read the collections. `loadIconCollections` reads the installed ones synchronously, and a server render then draws the icon with `fetch` stubbed to throw:

````tsx [icon/react/icon-test.tsx]
import { Icon } from "@hamur/icon/react"
import { loadIconCollections } from "@hamur/icon/testing"
import { expect, test } from "bun:test"
import { renderToString } from "react-dom/server"

loadIconCollections(["mdi"])

test("the home icon is drawn from the installed collection", () => {
  expect(renderToString(<Icon name="mdi:home" />)).toContain("<path")
})
````

A name that is no collection prefix, or a collection that is not installed, throws an error naming the prefix and the files it looked for.

## An icon that does not draw

In `hamur dev` each of these logs once per name:

| Message                                                                                                                        | Fix                                                                         |
| ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `[icon] icon "mdi:nope" not found`                                                                                             | the collection is installed and has no such icon; check the name            |
| `[icon] collection "mdi" is not installed; add @iconify-json/mdi, or set icon.provider "iconify"`                              | install the collection, or let the browser ask the Iconify API              |
| `[icon] Icon name "MyLogo" is not "prefix:name" or "i-prefix-name"; import a component, or put the SVG in a custom collection` | give the name a prefix, add an alias, or put the SVG in a custom collection |
| `[icon] icon.provider is "none": "mdi:home" is not in the payload or the client bundle`                                        | list the icon in `clientBundle.icons`, or set a `provider`                  |

## Not in v1

CSS-mode rules for an icon first shown inside a streamed boundary after the head was sent (use `svg` there), `serverBundle: "remote"` (a render that waits for the Iconify API), looking up an app component by the string in `name`, a `<symbol>` sprite with `<use>`, animated icon sets, an icon picker, search across collections and tinting a multi-colour icon. An icon font is not an icon collection: it is a family of [Fonts](/fonts), and the `googleicons` provider with `glyphs` keeps it small.
