<!--
  GENERATED FILE - do not edit by hand.
  Source of truth: docs/agents/ in the magma monorepo.
  Regenerate with: npm run sync.agent-docs (from the stencil package).
-->
# install web-components.md

## Purpose

Install Magma as plain custom elements - for static HTML, vanilla JS, or any
framework that can render custom elements directly. For React or Angular use the
dedicated wrappers ([`install.md`](install.md), [`install.md`](install.md)).

First do the shared asset setup in [`assets.md`](assets.md) (styles, fonts, icons).
This file only covers package install and registration.

## 1. Install

```bash
npm i @maggioli-design-system/magma
```

Then install the assets from [`assets.md`](assets.md):

```bash
npm i @maggioli-design-system/styles @maggioli-design-system/design-tokens
npm i @fontsource/karla @fontsource/merriweather @fontsource/roboto @fontsource/roboto-mono
```

## 2. Register the components

Two entry points, with different bundle-size trade-offs. Pick one - do not mix them
in the same app, or a tag ends up registered from two different builds.

### Per component (recommended, tree-shakeable)

Import only the components you use from `@maggioli-design-system/magma/components`
and call their `defineCustomElement*` function. Everything else is dropped by the
bundler:

```javascript
import {
  defineCustomElementMdsButton,
  defineCustomElementMdsIcon,
} from '@maggioli-design-system/magma/components';

defineCustomElementMdsButton();
defineCustomElementMdsIcon();
```

Each `defineCustomElement*` also registers the component's own children
recursively, so you only list the tags you write yourself.

A deep import is available too, when you want the bundler to resolve one file:

```javascript
import { defineCustomElement } from '@maggioli-design-system/magma/components/mds-button.js';
```

### All at once (lazy loader)

Simplest to wire up, but it ships every `mds-*` component: the loader resolves
chunks at runtime, so nothing can be tree-shaken away. Use it for prototypes, or
when the app genuinely uses most of the library.

```javascript
import { defineCustomElements } from '@maggioli-design-system/magma/loader';

defineCustomElements();
```

Either way, the tags are then plain HTML:

```html
<mds-button variant="primary" tone="strong">Save</mds-button>
<mds-icon name="mi/baseline/email"></mds-icon>
```

### Without a bundler (CDN / static page)

If you cannot bundle, load the loader from the package's `loader/` entry and serve
`@maggioli-design-system/magma/dist/` as a static folder. The recommended path is
still a bundler - the lazy loader resolves component chunks relative to its own
location.

## 3. Set the icon path

Before components hydrate (see [`assets.md`](assets.md) section 3):

```javascript
import { IconsSetService } from '@maggioli-design-system/magma';

IconsSetService.setSvgPath('/svg/');
```

Without a bundler, import it from the served `dist/index.js` (the same module), or set
the `mdsIconSvgPath` key of `sessionStorage`, which needs no import where the browser
allows storage.

Serve the icons at that path with one of the routes of [`assets.md`](assets.md) section 3
(iconsauce or the copy script, which also install the icon packages): with Vite the
static folder is `public/`, so `public/svg/` is served at `/svg/`.

## 4. Anti-FOUC

`hydrated.css` (imported in the [`assets.md`](assets.md) block) hides components
until Stencil sets the hydrated attribute. Keep it in the `base` layer and load it
before the first render to avoid a flash of unstyled custom elements. Once a component
is hydrated, the same file hands back the margin, padding and border it gives itself,
which a page reset such as Tailwind's preflight would zero: that works only from the
`base` layer itself, next to the reset.

Before hydration the same file gives `mds-img` the box of its picture, as a native
`<img>` reserves its room: give it `width` and `height`, and the page below it does not
move when it hydrates. The ratio needs typed `attr()` (Chromium 133+); where a browser
lacks it, a page that needs the room there too sets `aspect-ratio` on the host.

## 5. Server-side rendering (SSR)

`@maggioli-design-system/magma/hydrate` exposes `renderToString()`: it serializes
components to HTML with their shadow DOM inlined as
`<template shadowrootmode="open">` (declarative shadow DOM), reflected props as
attributes and the `hydrated` flag already set - so the markup paints with its
final geometry (no layout shift) and `hydrated.css` does not hide it.

```javascript
// server only - the module bundles all components and must not reach the client
import { renderToString } from '@maggioli-design-system/magma/hydrate';

const { html, diagnostics } = await renderToString(
  '<mds-button variant="primary">Save</mds-button>',
  { fullDocument: false, serializeShadowRoot: 'declarative-shadow-dom' },
);
```

Always check `diagnostics` for `level: 'error'` entries: component failures
during serialization are reported there, not thrown, and the partial HTML is
returned anyway.

SSR caveats (by design):

- **Icons render empty on the server** - `mds-icon` fetches SVGs at runtime and
  skips the fetch during SSR. The box is still reserved (`aspect-ratio` +
  `width` on `:host`), so nothing shifts; the icon appears after hydration.
- **The default theme is rendered** - user preferences live in `localStorage`,
  which does not exist server-side. Publish the `pref-*` classes on `<html>`
  from an inline script if you need the right theme at first paint.

React consumers get this automatically through the generated server wrappers -
see [`install.md`](install.md).

## 6. Client-side routing

The links of the components (`href` of `mds-button`, `mds-tab-item`, ...) are real anchors
the browser follows, loading the page. In a single-page app register the router once and every
plain click on a component link is routed on the client instead; a modifier or middle click,
`target="blank"`, `download` and a link to another origin stay with the browser.

```javascript
import { NavigationService } from '@maggioli-design-system/magma/services';

NavigationService.setHandler((href) => router.navigate(href));
```

`setHandler` returns the function that removes the handler. Return `false` from the handler
for a link the browser is to load. Without a registered router, a click listener on the
component can still cancel the event with `preventDefault()` and route by hand.

## 7. Lint

The ESLint and Stylelint rules ship in `@maggioli-design-system/magma`: nothing more to
install from Magma. Add the block for this target to the project's ESLint configuration and
the Stylelint preset for its stylesheets, as [`lint.md`](lint.md) shows ([HTML and web components](lint.md#html-and-web-components)),
merging into what the project already has, and run both after every change.

## Gotchas

- Call `defineCustomElements()` exactly once. Calling it twice is harmless but
  pointless; never call it after manually defining the same tags.
- Do not mix `/loader` and `/components` in the same app: they are two separate
  builds of the same components, and loading both doubles the bytes.
- Set the icon path before the first `mds-icon` renders, or icons will fetch from the
  wrong path. `IconsSetService.setSvgPath()` reloads the icons already mounted; after a
  late write of the `sessionStorage` key, dispatch
  `window.dispatchEvent(new CustomEvent('mdsIconSvgPathUpdate'))` to refresh.
- The default slot accepts plain text only unless a component's own `AGENTS.md` says
  otherwise - see [`conventions.md`](conventions.md).

## See also

- [`assets.md`](assets.md) - styles / fonts / icons / identity (canonical)
- [`conventions.md`](conventions.md) - component conventions
