# 🧱 @stokr/components-library

Pure UI library for the STOKR apps: **React components**, **small helpers** and the **design system** (colours, type, spacing, dark mode).

- 📖 **Storybook** — every component live, with controls and code to copy: [storybook.stokr.io](https://storybook.stokr.io/)
- 🎨 **Design system guide** — [src/design-system/README.md](src/design-system/README.md)
- 📝 **Changelog** — [CHANGELOG.md](CHANGELOG.md)
- 🤖 **Rules for stories and AI agents** — [AGENTS.md](AGENTS.md)

> ℹ️ The library holds **no business logic**: no API calls, no authentication, no Firebase, no runtime configuration. Auth, 2FA and data fetching live in the apps. Components receive data and callbacks as props.

## 📑 Contents

- [🚀 Quick start](#quick-start)
- [📦 What is inside](#inside)
- [🎨 Design system](#design-system)
- [🧰 Helpers](#helpers)
- [🛠️ Development](#development)
- [⬆️ Upgrading to 5.0.0](#upgrading)
- [🧯 Troubleshooting](#troubleshooting)
- [📤 Releasing](#releasing)

---

<a id="quick-start"></a>

## 🚀 Quick start

**1. Install**

```bash
npm install @stokr/components-library
npm install react react-dom styled-components react-router-dom
```

Peers: React 18 or 19, styled-components 6, react-router-dom 6 or 7.

**2. Import the design-system stylesheet once**, at the entry point of the app. It brings the fonts, the CSS variables (`--text-primary`, `--status-info-bg`, `--space-4`…), the text classes and the baseline. Without it components render unstyled.

```tsx
import '@stokr/components-library/design-system.css'
```

**3. Use a component**

```tsx
import { Button, Input, Modal, ConfirmModal } from '@stokr/components-library'

`<Button onClick={save}>Save</Button>
```

Each component's page in [Storybook](https://storybook.stokr.io/) has a **Show code** button with the snippet to copy, and the **Controls** panel lists every prop (required ones first).

**4. Only if you use them**

| You use…                                                                                                         | You need                  | How                                                                                       |
| ---------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------- |
| 🔗 Links and navigation (`SmartLink`, `TextLink`, `BackButton`, `MenuNav`, `Modal` back link)                    | A React Router above them | Wrap the app in `BrowserRouter` (or your router)                                          |
| 🔣 Icons (`MaterialIcon`, and the components that draw one: `Modal`, `Pagination`, `Checkbox`, `Select`, `FAQ`…) | The icons registered once | `registerMaterialIcons(...)`, see below                                                   |
| 🌍 Texts (`<Copy id="…" />`)                                                                                     | A copy source             | `setCopySource(en)` once at startup; without one, `Copy` shows its `fallback` then the id |

**Registering icons.** Only the Material Symbols you register are bundled. `requiredMaterialIcons` lists the keys the library's own components draw; an unregistered icon renders empty.

```tsx
import { registerMaterialIcons } from '@stokr/components-library'
import home from '@material-symbols/svg-400/outlined/home.svg?react'
import check600 from '@material-symbols/svg-600/outlined/check.svg?react'

// Call once at module scope, in code shared by server and client.
registerMaterialIcons({
  'outlined/home': home,
  'outlined/check@600': check600, // `@<weight>` for a weight other than 400, `-fill` for filled
  // …plus every key of `requiredMaterialIcons` (see src/storybook/materialIcons.ts for a full example)
})
```

With Module Federation the host's registration covers the remotes (the library is a shared singleton).

---

<a id="inside"></a>

## 📦 What is inside

Everything is imported from the package root: `import { … } from '@stokr/components-library'`. The sidebar of [Storybook](https://storybook.stokr.io/) follows these groups.

|     | Group            | Examples                                                                                                                                                                          |
| --- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 🎨  | **Foundations**  | `Text`, `Logo`, `Background`, `LottieAnimation`, `MaterialIcon`, `Copy`, and the design-system pages (Colors, Typography, Layout)                                                 |
| 🔘  | **Buttons**      | `Button`, `GlareButton`, `BackButton`, `RefreshButton`, `TextLink`                                                                                                                |
| ⌨️  | **Inputs**       | `Input`, `InputPassword`, `Textarea`, `Select`, `MultiSelect`, `CountrySelect`, `DatePickerInput`, `OtpInput`, `RangeInput`, `SearchInput`, `Checkbox`, `Radio`, `Switch`, `Form` |
| 💬  | **Feedback**     | `Modal`, `SideModal`, `ConfirmModal`, `SuccessModal`, `PaymentModal`, `Snackbar`, `Tooltip`, `InfoBox`, `InfoIcon`, `StatusTag`, `StatusDot`, `Skeleton`, `StokrLoader`           |
| 🧭  | **Navigation**   | `Tabs`, `TabsNav`, `CardTabs`, `Pagination`, `StepController`, `Timeline`                                                                                                         |
| 🗂️  | **Data display** | `ReactTable`, `BasicTable`, `Card`, `Section`, `FAQ`, `Chip`, `Collapsible`, `QRCode`, `ProfileBox`, `CryptoAddress`, `ChartLegend`, `IdentityInfo`, `TaxResidenceCard`           |
| 💳  | **Payment**      | `PaymentDisplay`, `PaymentDetailsCard`, `PaymentPendingCard`, `PaymentSuccessCard`, `DetailRows`, `TimerComponent`                                                                |
| 📐  | **Layout**       | `ComponentWrapper`, `Grid` helpers (`grid`, `layoutGrid`), `DisplayOnBreakpoint`                                                                                                  |

Components that open (modals, drawers) are controlled by an `isOpen` prop; fields are controlled with `value` and `onChange`. Storybook shows the exact pattern for each.

---

<a id="design-system"></a>

## 🎨 Design system

**One source for the look.** The colours, type, spacing, radius, shadows and breakpoints of the STOKR UI kit are written once, in this library, and reach every app as CSS variables (`--*`). Components and apps use the **names**, never the values, and dark mode comes for free.

```tsx
import '@stokr/components-library/design-system.css' // once, at the app entry
import { text, breakpoint } from '@stokr/components-library'

const Title = styled.h1`
  ${text('titleXl')}
  color: var(--text-primary);
  ${breakpoint.Medium` padding: var(--space-8); `}
`
```

📚 **Full guide** (what to use, where to change what, dark mode, fonts): [src/design-system/README.md](src/design-system/README.md) · 📖 **Browse it:** Foundations in [Storybook](https://storybook.stokr.io/)

---

<a id="helpers"></a>

## 🧰 Helpers

Pure functions and hooks, also exported from the package root.

| Area                      | Exports                                                                                                                                   |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| 💶 Amounts and currencies | `formatAmount`, `formatAmountParts`, `formatPercent`, `parseAmount`, `projectUnit`, `paymentUnit`, `getCurrencySymbol`, `CURRENCY_CONFIG` |
| 📅 Dates and text         | `formatDate`, `formatDateRange`, `capitalize`, `shortenAddress`, `km_ify`                                                                 |
| 📱 Responsive             | `breakpoint`, `useMediaQuery`, `useMobileView`, `useContainerSize`, `DisplayOnBreakpoint`                                                 |
| 📋 Clipboard and files    | `copyTextToClipboard`, `useCopyToClipboard`, `saveAs`, `downloadCsv`, `toCsv`                                                             |
| ⏱️ Timers and polling     | `useTimer`, `useTransactionPolling`, `useCooldown`                                                                                        |
| 🔐 Validation             | `getPasswordCriteria`, `isPasswordValid`, `getPasswordEntropy`, `safeUrl`                                                                 |
| 🌍 Copy                   | `Copy`, `setCopySource`, `resolveCopy`, `t`                                                                                               |

`formatAmount` and `formatDate` have a page under **Utils** in Storybook with live examples.

---

<a id="development"></a>

## 🛠️ Development

| Command                           | What it does                                                                                 |
| --------------------------------- | -------------------------------------------------------------------------------------------- |
| `npm start` / `npm run storybook` | 📖 Storybook on port 6006 (regenerates the tokens first)                                     |
| `npm test`                        | ✅ Vitest: design system (tokens vs the UI kit), every story renders, components and helpers |
| `npm run lint`                    | 🔎 ESLint on `src`, then `check:css-vars`                                                    |
| `npm run gen:tokens`              | ⚙️ Regenerate `src/design-system/generated` from `tokens/`                                   |
| `npm run check:tokens`            | 🔒 Fails if `generated/` is out of date                                                      |
| `npm run check:css-vars`          | 🔎 Fails on an undefined CSS variable                                                |
| `npm run check:media`             | 📱 Fails if a raw width `@media` is added (use `breakpoint`)                                 |
| `npm run build:dist`              | 📦 Library build + static files + design-system stylesheet                                   |
| `npm run build-storybook`         | 🏗️ Static Storybook in `storybook-static`                                                    |

**The rules in one list** (details in [AGENTS.md](AGENTS.md) and the [design-system guide](src/design-system/README.md)):

- 🎨 Colours by role from the semantic tokens (`--text-*`, `--background-*`, `--border-*`, `--action-*`, `--status-*`, `--tag-*`); never a hex, `font-family` or raw `@media` in a component.
- 📖 One story file per component, with a `Default` story that sets only the required props.
- 🧩 New and touched components are TypeScript, without `prop-types`.
- 🔁 Changing a token: edit `tokens/`, run `npm run gen:tokens`, commit `generated/`.

---

<a id="upgrading"></a>

## ⬆️ Upgrading to 5.0.0

5.0.0 is a major release. The full list is in [CHANGELOG.md](CHANGELOG.md); the points that need an action in an app:

1. 🧵 **Import `@stokr/components-library/design-system.css` once.** Components now read CSS variables, so without it they are unstyled.
2. 📱 **`rwd` is now `breakpoint`**, and `Large` moved from 1024px to 1200px (992 < 1200 < 1440).
3. 🎨 **`colors`** is now the UI kit's colour ramp (`colors['blue-500']`, hex values). The old flat object (`colors.blue`, `colors.grey2`…), the old `theme` keys (`theme.cPrimary`…), `GlobalStyle`, `spacing`, `typography`, `media` and `getMedia` are gone: use `var(--name)`, `text()` and `breakpoint`.
4. 🔣 **Register `requiredMaterialIcons`**: components draw Material icons, not the old icon fonts.
5. 🌗 **Dark mode** is `data-theme="dark"` on `<html>`; nothing to change in components that use the semantic tokens.
6. 📏 **`rem` became `px`**: the library no longer depends on a 10px root font size.

---

<a id="troubleshooting"></a>

## 🧯 Troubleshooting

| Symptom                                                            | Cause and fix                                                                                                                       |
| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| 😶 Components look unstyled, wrong font                            | The stylesheet is not imported: `import '@stokr/components-library/design-system.css'` once at the entry.                           |
| 🌗 Something stays light (or unreadable) in dark mode              | A hard-coded colour in the app. Use a semantic token (`var(--text-primary)`…).                                                |
| 🔣 An icon renders empty                                           | The icon is not registered: `registerMaterialIcons(...)`, including every key of `requiredMaterialIcons`.                           |
| 🧭 `useNavigate()` may be used only in the context of a `<Router>` | Wrap the app in a router. `SmartLink`, `TextLink`, `BackButton` and `MenuNav` need one.                                             |
| ⚛️ Invalid hook call / duplicated React or styled-components       | Dedupe the peers in Vite: `resolve: { dedupe: ['react', 'react-dom', 'styled-components'] }`.                                       |
| 📏 A layout switches at the wrong width                            | Use `breakpoint` (`Large` is 1200px since 5.0.0) and check the width in the [design-system guide](src/design-system/README.md#app). |

---

<a id="releasing"></a>

## 📤 Releasing

1. Add the changelog entry in [CHANGELOG.md](CHANGELOG.md).
2. `npm version <patch|minor|major>`.
3. `npm run pub` (builds `dist`, then publishes; `npm login` first).

Apps pick the new version up by updating their dependency (library first, then host, then remotes).
