# `@hamur/icon`

The first-party icon module. It gives every adapter one component, `Icon`, that draws an icon of an icon collection by name, as inline `<svg>` or as a CSS rule. Collections are the app's `@iconify-json/<prefix>` packages and those a module adds with the `icon:collections` hook; the module imports no Iconify package and reads the Iconify JSON format itself. Add it to `modules` and set its options under the `icon` config key.

```ts
// hamur.config.ts
import icon from "@hamur/icon"

export default defineConfig({
  modules: [icon],
  icon: { serverBundle: { collections: ["mdi"] }, cssLayer: "icons" },
})
```

```tsx
<Icon name="mdi:home" />
// <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" aria-hidden="true"
//      focusable="false" data-hamur-icon="mdi:home"><path fill="currentColor" d="…"></path></svg>
```

### `default`

The module, as `defineModule({ meta: { name: "icon", configKey: "icon", hooks: ["icon:collections"] } })`. Its setup checks `icon` (a wrong value is a build error naming the key) and generates the options the library entries read; the app imports `Icon` from `@hamur/icon/<library>`.

- **The icon server bundle.** In `modules:done` the module reads each collection of `icon.serverBundle` (`node_modules/@iconify-json/<prefix>/icons.json`, looked for from the app root up, so a hoisted workspace install is found; `@iconify/json/json/<prefix>.json` for a prefix `serverBundle.collections` lists), calls `icon:collections` with them by prefix, and writes each as `<buildDir>/icons/<prefix>.json`, mounted as `useStorage("assets:icons")`: data in the server bundle on every preset, never a public file. The server reads every collection once per process, before the first render.
- **The size line.** The build logs the bundle once, `[icon] server bundle: lucide 0.9 MB, mdi 4.1 MB`.
- **The endpoint.** `GET /_hamur/icons/<prefix>.json?icons=a,b` (and `HEAD`) answers the asked icons only, in the Iconify API's shape, aliases resolved: `{ prefix, icons: { <name>: { body, width, height } }, not_found?: string[] }`, with `content-type: application/json`, `cache-control: public, max-age=604800` (`no-cache` under `hamur dev`) and an `etag` (`if-none-match` answers `304`). It is `200` while at least one asked icon exists, so a missing icon of a batch costs the others nothing. The prefix and every name must match `/^[a-z0-9]+(-[a-z0-9]+)*$/` before they are looked up or put in an outgoing URL, and the endpoint reads no file the request names. It is registered on every preset with a server unless `icon.provider` is `"none"`. Other answers are JSON `{ "error": "<message>" }`:

| Status | Message                                                                                    |
| ------ | ------------------------------------------------------------------------------------------ |
| 400    | `icons query is required`                                                                  |
| 400    | `icons lists 400 names; at most 100`                                                       |
| 400    | `icon name "Mdi Home" must match /^[a-z0-9]+(-[a-z0-9]+)*$/`                               |
| 404    | `collection nope not found`                                                                |
| 404    | `icon mdi:nope not found`, or `icons mdi:a, mdi:b not found` when none of several exists   |
| 405    | `method not allowed` (`allow: GET, HEAD`)                                                  |
| 504    | `iconify api timed out after 1500 ms` (`fallbackToApi` on and no answer in `fetchTimeout`) |

With `fallbackToApi`, the icons or the collection the bundle lacks are fetched from `<iconifyApiEndpoint>/<prefix>.json?icons=…`, added to the answer and not kept. An API that answers an error or cannot be reached counts as having none; only a timeout is `504`.

- **The payload.** Each icon a server render drew goes into `app.modulePayload.icon`, `{ <prefix>: { icons: { <name>: { body, width, height } } } }`, so the hydration draws the same markup with no request; an icon the client bundle holds is left out of it. A later client navigation does not change it.
- **The client bundle.** In `modules:done`, after `icon:collections`, the module writes `#hamur/icon/client`: the icons of `icon.clientBundle.icons` and, with `scan`, every string literal of the app's source that is an icon name of a known prefix (`"mdi:home"`, `'i-mdi-home'`, a token of `class="… i-mdi-home"`), in the same shape as the payload and resolved through aliases. The scan is a text scan of the `.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`, `.mts`, `.cts`, `.vue`, `.svelte`, `.css`, `.html`, `.md` and `.mdx` files below `srcDir`, `shared` and each layer's, not `node_modules`, `serverDir`, dot folders or `.d.ts` files; `scan: { include, exclude }` are globs from the app's (or the layer's) root. A name made from a variable is not found: list it in `icons`. The client bundle is loaded with the app, so the browser draws these icons with no request, on a client navigation too. A scanned or listed name its collection lacks logs `[icon] "mdi:nope" (app/pages/index.tsx) is not in the mdi collection` (`icon.clientBundle.icons` in place of a file for a listed one) and is left out. A bundle above `sizeLimitKb` fails the build, `icon client bundle is 300 KB, over icon.clientBundle.sizeLimitKb 256`; the size is the module's data in KB rounded up. Under `hamur dev` a saved source file rescans, and a changed set rewrites the module.
- **Fetching in the browser.** An icon in neither the payload nor the client bundle is asked for when its `Icon` renders in the browser: `<app.baseURL>_hamur/icons/<prefix>.json?icons=a,b,c` with `provider: "server"` (the endpoint is an app route, so it is under `app.baseURL` and never on `cdnURL`), `<iconifyApiEndpoint>/<prefix>.json?icons=a,b,c` with `"iconify"`. Names asked within one microtask are one request per prefix, split at 100 names. While the answer is pending the `Icon` draws its empty sized box; when it arrives every `Icon` that asked draws, in each adapter with its own state (`useSyncExternalStore` in React, `ref` in Vue, `$state` in Svelte, a signal in Solid, `useState` in Preact, and for html a repaint of the page). The body of an answer goes through the same sanitiser as every other body. Answers are kept in memory and in `sessionStorage` (`hamur:icon:<provider>:<prefix>:<name>`, every access in `try`/`catch`); a name the answer lacks (`not_found`, or a `404`) is kept as missing, so it is not asked again, and logs once under `hamur dev`. A request that fails (network, timeout, another status) marks its icons missing for the page only. With `provider: "none"` nothing is asked and the log is `[icon] icon.provider is "none": "mdi:home" is not in the payload or the client bundle`.
- **Hooks.** `icon:collections(collections: Record<string, IconifyJSON>)` runs once in `modules:done` with every installed collection: a module or `hooks` in the config adds a collection, or replaces one, by assigning its prefix. A value without an `icons` object fails the build: `icon:collections: collections["brand"] must be Iconify JSON, { prefix, icons }`.

```ts
// hamur.config.ts
import icon from "@hamur/icon"

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

### `IconOptions`

| Key                  | Type                                                                                                       | Default                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| -------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `provider`           | `"server" \| "iconify" \| "none"`                                                                          | `"server"`; `"none"` on the `static` and `cloudflare-static` presets. Where the browser asks for an icon the payload and the client bundle lack: `"server"` the app's own `/_hamur/icons/` endpoint, `"iconify"` `iconifyApiEndpoint`, `"none"` nobody (no endpoint is registered, no request is made, the icon stays empty and logs once)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `iconifyApiEndpoint` | `string`                                                                                                   | `"https://api.iconify.design"`: an `http:` or `https:` URL, a trailing `/` removed. Read when `fallbackToApi` is on and by the browser when `provider` is `"iconify"`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `fallbackToApi`      | `boolean`                                                                                                  | `false`: the endpoint asks `iconifyApiEndpoint` for icons and collections its bundle lacks; off, the app calls no third party                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `fetchTimeout`       | `number`                                                                                                   | `1500` ms: the Iconify API call of the endpoint, and the browser's request for icons                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `serverBundle`       | `"local" \| false \| { collections: string[] }`                                                            | `"local"`: every `@iconify-json/<prefix>` the app's `package.json` lists in `dependencies` or `devDependencies`; `{ collections }` exactly those (the only way to use `@iconify/json`); `false` none                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `clientBundle`       | `{ icons?: string[]; scan?: boolean \| { include?: string[]; exclude?: string[] }; sizeLimitKb?: number }` | `{ icons: [], scan: true, sizeLimitKb: 256 }`: `icons` are `"prefix:name"`, `scan` is `false`, `true` or `{ include?, exclude? }` globs, `sizeLimitKb` the largest client bundle                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `customCollections`  | `Array<{ prefix: string; dir: string; recursive?: boolean }>`                                              | `[]`: each `.svg` of `dir` is one icon of the collection `prefix`, named by its file name (`logo.svg` is `brand:logo`); with `recursive` the subfolders are read and the path segments joined with `-` (`social/x.svg` is `social:x`, `social/deep/y.svg` is `social:deep-y`). A file name must match `/^[a-z0-9]+(-[a-z0-9]+)*$/`. A relative `dir` is resolved from the app root, then from each layer's root, the first that has it (a layer's config is merged into the app's, so the declaring layer is not known). Each file is read once at build by the sanitiser of `?component` (no `<script>`, `<foreignObject>`, `<style>`, `on*` attribute or external `href`) and stored as `{ body, width, height }` with `left` and `top` when the `viewBox` has them; without a `viewBox` the `width` and `height` attributes are used, else 24. The paint attributes of the file's own `<svg>` (`fill`, `stroke`, `stroke-width`, …) stay on a `<g>` around the body. Custom icons are in the server bundle, the client bundle, the scan and the endpoint like installed ones. Under `hamur dev` an `.svg` added, changed or removed in `dir` rebuilds the collection and reloads the page, with no restart |
| `cssLayer`           | `string`                                                                                                   | unset: wraps the CSS-mode rules in `@layer <name> { … }`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `cssSelectorPrefix`  | `string`                                                                                                   | `"i-"`: the class prefix of CSS mode, and of the `i-prefix-name` form of `name`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `cssWherePseudo`     | `boolean`                                                                                                  | `true`: writes `:where(.i-mdi\:home)`, specificity 0, so an app's own rule wins                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `cssClasses`         | `boolean`                                                                                                  | `false`: every `i-<prefix>-<name>` and `i-<prefix>:<name>` class (with `cssSelectorPrefix`) the scan finds in the app's source gets the CSS-mode rule of `Icon` in global CSS (`#hamur/icon/classes.css`, imported by the module's app plugin), so `<span class="i-mdi-home">` works with no `Icon`, in html pages too. The scan reads string literals as for the client bundle and, in a `.css` file, the `.i-…` selectors (`.i-mdi\:home` for the colon form); `scan: false` still scans for this, `scan: { include, exclude }` narrows it. `cssLayer` and `cssWherePseudo` apply. A class whose icon its collection lacks logs the warning of the client bundle once and adds no rule. Under `hamur dev` a saved source file rewrites the stylesheet                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `size`               | `string \| number`                                                                                         | unset: the `size` of an `Icon` that has none; a number is CSS pixels                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `class`              | `string`                                                                                                   | unset: the `class` of an `Icon` that has none                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `mode`               | `"svg" \| "css"`                                                                                           | unset (`"svg"`): the `mode` of an `Icon` that has none                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `aliases`            | `Record<string, string>`                                                                                   | `{}`: a `name` that is an own key is replaced by its value before it is read, so `aliases: { logo: "brand:logo" }` makes `<Icon name="logo">` the icon `brand:logo`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |

The load errors name the key: `icon.provider "cdn" is not "server", "iconify" or "none"`, `icon.iconifyApiEndpoint must be an http or https URL (got "api")`, `icon.fetchTimeout must be a positive integer (got 0)`, `icon.serverBundle must be "local", false or { collections: string[] } (got "all")`, `icon.serverBundle.collections[0] "mdi" is not installed; add @iconify-json/mdi to the app's dependencies`, `icon.clientBundle.icons[0] "home" must be "prefix:name" (got "home")`, `icon.clientBundle.sizeLimitKb must be a positive integer (got 0)`, `icon.clientBundle.scan must be a boolean or { include?, exclude? } (got "yes")`, `icon.customCollections[0].prefix "My Icons" must match /^[a-z0-9]+(-[a-z0-9]+)*$/`, `icon.customCollections[0].dir must be a non-empty string (got undefined)`, `icon.customCollections[0].dir "./app/assets/svg" does not exist`, `icon.customCollections[0].prefix "mdi" is already an installed collection`, `icon.customCollections[1].prefix "brand" is used twice`, `app/assets/icons/a.svg: not an SVG file (no <svg> element)`, `app/assets/icons/Arrow_Left.svg: icon name "Arrow_Left" must match /^[a-z0-9]+(-[a-z0-9]+)*$/`, `app/assets/icons/a/b.svg: icon name "a-b" is also the name of app/assets/icons/a-b.svg`, `icon.cssSelectorPrefix "1" must match /^[a-z_][a-z0-9_-]*$/i`, `icon.cssLayer must be a non-empty string (got "")`, `icon.cssWherePseudo must be a boolean (got "yes")` (and the same for `fallbackToApi` and `cssClasses`), `icon.size must be a string or a positive number (got 0)`, `icon.class must be a string (got 1)`, `icon.mode "x" is not "svg" or "css"`, `icon.aliases must be an object of strings (got [])` and `icon.theme is not an option; use provider, iconifyApiEndpoint, fallbackToApi, fetchTimeout, serverBundle, clientBundle, customCollections, cssLayer, cssSelectorPrefix, cssWherePseudo, cssClasses, size, class, mode, aliases`.

`size`, `class`, `mode` and `aliases` reach the browser as `runtimeConfig.public.icon`, which `Icon` reads through `useRuntimeConfig().public`; a prop of `Icon` wins over them. A key the app sets itself under `runtimeConfig.public.icon` wins over the option of that key, and `aliases` merge per alias, the app's winning. `customize(content, name, prefix)` is a prop of `Icon` only: a function cannot be sent to the browser, so `icon.customize` fails as an unknown option.

```ts
export default defineConfig({ modules: [icon], icon: { size: "1.25em", aliases: { logo: "brand:logo" } } })
```

### `IconProps`

| Prop    | Type               | Default                                                                                                                                                                                                                                                 |
| ------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`  | `string`           | required: `"mdi:home"`, or the class form `"i-mdi-home"` or `"i-mdi:home"` (the `cssSelectorPrefix`); the dash form is read against the known prefixes, the longest that leaves a name winning, so `i-material-symbols-home` is `material-symbols:home` |
| `size`  | `string \| number` | `"1em"`; a number is CSS pixels                                                                                                                                                                                                                         |
| `mode`  | `"svg" \| "css"`   | `"svg"`                                                                                                                                                                                                                                                 |
| `title` | `string`           | none: the icon is decorative (`aria-hidden="true"`); with it, `role="img"` and a `<title>` child (`aria-label` in CSS mode)                                                                                                                             |

Every other attribute goes on the `<svg>` or the `<span>` (`className` in React). An `aria-label` or `aria-labelledby` of the app's makes the icon `role="img"` without `aria-hidden`.

### `IconifyJSON`, `IconifyIcon`

The Iconify JSON format: `{ prefix, icons: Record<string, IconifyIcon>, aliases?, width?, height?, left?, top? }`, an icon `{ body, width?, height?, left?, top?, rotate?, hFlip?, vFlip?, hidden? }` and an alias `{ parent, …the same without body }`. A size not given is the collection's, then 16. An alias is resolved through its `parent` chain: the nearer alias's size and offsets win, quarter turns add up and flips cancel in pairs, written into the body as a `<g transform>`.

## `@hamur/icon/react`, `@hamur/icon/vue`, `@hamur/icon/preact`, `@hamur/icon/svelte`, `@hamur/icon/solid`, `@hamur/icon/html`

Each exports `Icon` for its library, imported where it is used (`import { Icon } from "@hamur/icon/vue"`), with `modules: [icon]` (`import icon from "@hamur/icon"`) in the config. In html, `Icon({ name, size, mode }): string` is imported and its string placed in the page.

### `Icon`

- **SVG mode** (the default). `<svg xmlns viewBox width height aria-hidden focusable="false" data-hamur-icon="<prefix>:<name>">` with the body drawn as elements: the body is read once by `sanitizeSvg` of `hamur/adapter` into nodes, and each library renders them with its own element call, so nothing sets `innerHTML`, and an icon's ids are prefixed per instance with the library's SSR-stable id. The markup is whole where it stands, so it is right in a streamed page.
- **CSS mode.** `<span class="i-mdi:home" role="img" aria-hidden="true">` and one rule per icon in one `<style>` pushed through `useHead` under the key `hamur-icons`; two `Icon`s of one name give one rule, and each push holds every rule of the page so far. 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 `size` other than `1em` is the span's inline `width` and `height`. A CSS-mode `Icon` first rendered in a streamed boundary after the head was sent has no rule; use SVG mode there.

```css
:where(.i-mdi\:home) {
  display: inline-block;
  width: 1em;
  height: 1em;
  background-color: currentColor;
  -webkit-mask: var(--svg) no-repeat center / 100% 100%;
  mask: var(--svg) no-repeat center / 100% 100%;
  --svg: url("data:image/svg+xml,…");
}
```

- **Not found.** An icon no collection has renders an empty `<svg>` or `<span>` of the icon's size, and under `hamur dev` logs once per name: `[icon] icon "mdi:nope" not found` when the collection is known, `[icon] collection "mdi" is not installed; add @iconify-json/mdi, or set icon.provider "iconify"` when it is not (the server render of `provider: "iconify"` logs nothing for an unknown collection: the browser asks the API), `[icon] icon.provider is "none": "mdi:home" is not in the payload or the client bundle` when `provider` is `"none"`, and `[icon] Icon name "MyLogo" is not "prefix:name" or "i-prefix-name"; import a component, or put the SVG in a custom collection` for a name with no prefix that is no key of the `aliases` option.

```tsx
import { Icon } from "@hamur/icon/react"

;<Icon name="i-mdi-home" mode="css" size={24} />
// <span class="i-mdi:home" role="img" aria-hidden="true" style="width:24px;height:24px"></span>
```

## `@hamur/icon/angular`

In Angular `Icon` is the component `<hamur-icon>` (`<hamur-icon name="mdi:home" mode="svg" />`, inputs `name`, `size`, `mode`, `title` and `customize`): the `<svg>` or `<span>` is drawn inside its own element, which the other libraries have not, and a class written on `<hamur-icon>` stays on it; a static `aria-label` or `aria-labelledby` is also written on the drawn element.

## `@hamur/icon/testing`

For component tests under `bun test`, where no build ran and the icon server plugin did not read the collections.

### `loadIconCollections`

`loadIconCollections(prefixes: string[]): void` reads each `node_modules/@iconify-json/<prefix>/icons.json` (or `@iconify/json/json/<prefix>.json`) synchronously, looked for from `process.cwd()` up, into the registry a server render reads. Afterwards a server render of `<Icon name="mdi:home" mode="svg">` draws the icon's `<path d>` with no request, so a test that stubs `fetch` to throw still passes. 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. `@hamur/test-utils` (M30) will call it.

```ts
import { loadIconCollections } from "@hamur/icon/testing"

loadIconCollections(["mdi"])
```
