# @3dsource/source-ui-native

> Lightweight UI primitives with zero dependencies (only `tslib`). **No Angular peer dependency** — works without Angular entirely. Can be used in any project (React, Vue, plain HTML, Lovable, etc.) by importing just the compiled CSS stylesheet. Angular components use signals API (`input()`, `output()`), zoneless change detection, `ViewEncapsulation.None`, and CSS custom properties (`--src-*`) for theming.

For CDK/Material components (color-picker, popover, tabs, tooltip, CDK modal, styled Material form fields) see the companion library `@3dsource/source-ui`.

- [Live demo site](https://preview.3dsource.com/front-libraries/develop/): Interactive examples of all components with live code snippets (uses HashLocationStrategy — routes like `/#/components/SourceButtonComponent`). The `/develop/` branch always has the latest published version.

## Key concepts

- All components use the `src-` selector prefix (e.g. `<src-button>`, `<src-badge>`)
- Inputs use Angular signals: `input()`, `input.required()`, `output()`
- Enum-like inputs are typed as union types derived from `as const` objects (e.g. `SourceButtonAppearanceKeys` = `"plain" | "inline" | "filled" | "default"`)
- Design tokens are SCSS CSS custom properties with `--src-` prefix, organized by category: color (light/dark themes), layout (responsive breakpoints), typeface, UI sizing
- The library provides TWO levels of styling: Angular Components (with `input()/output()` API) AND CSS-only Source Elements (BEM classes on native HTML tags — no Angular imports needed)
- Modals use native `<dialog>` element — opened via `SourceModalElementService.open(data)` where `data: SourceModalElementData`. No CDK dependency.
- The `section_3dsourcecom` class must be placed on the root app container element for Source UI styles to apply. Place it on `<app-root>` inner wrapper, the root `<section>`, or `<body>` as a last resort. Do NOT place it on `<html>`. Example: `<body class="section_3dsourcecom">` or `<div class="section_3dsourcecom">` as the first child of `<app-root>`.
- **Dark theme**: add `section_3dsourcecom--dark` class alongside `section_3dsourcecom` to activate the dark color scheme. Toggle between light and dark by adding/removing the `--dark` class. Both light and dark tokens are bundled — no extra import needed.
- **Scrollbar**: global scrollbar styling is applied automatically (`scrollbar-width: thin`). Override with `--srcScrollbarThumbColor` and `--srcScrollbarTrackColor` CSS custom properties on any ancestor element.
- STRICT RULE: Do NOT use Tailwind CSS or any utility-first CSS framework. All styling must use Source UI design tokens (`--src-*` CSS custom properties), Source Element BEM classes (`src-*`), and standard CSS/SCSS. Never generate Tailwind classes (`flex`, `p-4`, `bg-blue-500`, etc.).

## Components

- **Angular Components** (require Angular): badge, banner, button, copyright, divider, hint, icon-button, loading, logo-loading, modal-element, slider, tile
- **Source Elements (CSS-only, no Angular needed)**: badge, banner, button, checkbox, divider, hint, icon-button, input, label, list, modal, radio, select, textarea, tile, toggle — pure CSS classes applied to standard HTML elements

## Component API reference

Machine-readable JSON API docs for each component. Each file contains: `name`, `selector`, `library`, `kind`, `inputs[]` (with `name`, `type`, `description`, `resolvedValues`, `defaultValue`, `isRequired`, `alias`), `outputs[]`.

- [SourceBadgeComponent API](./docs/api/badge.json): `src-badge` — Inline status indicator. Use for labels, tags, counters, status markers. Supports `context` (info/success/warning/error) and `size` (sm/md/lg).
- [SourceBannerComponent API](./docs/api/banner.json): `src-banner` — Full-width notification bar. Use for page-level alerts, warnings, info messages. Supports `context` variants for severity.
- [SourceButtonComponent API](./docs/api/button.json): `src-button` — Primary interactive element. Use when you need Angular bindings (loading state, disabled via signal, programmatic control). Supports `appearance` (plain/inline/filled/default), `weight` (primary/secondary/ghost), `context` (info/success/error), `size` (sm/md/lg/xl). For simple HTML buttons without Angular — use Source Element `src-button` CSS class instead.
- [SourceCopyrightComponent API](./docs/api/copyright.json): `src-copyright` — "Powered by 3D Source" branding link. Use in footers. Supports `isCollapsed` toggle.
- [SourceDividerComponent API](./docs/api/divider.json): `src-divider` — Visual separator line. Use between content sections or list groups.
- [SourceHintComponent API](./docs/api/hint.json): `src-hint` — Contextual message below form fields or content. Use for validation messages, helper text. Supports `context` for severity (info/success/warning/error).
- [SourceIconButtonComponent API](./docs/api/icon-button.json): `src-icon-button` — Icon-only action button. Use for toolbars, compact actions. Supports `counter` for notification badges, and same appearance/weight/size/context as button. For simple HTML icon buttons — use Source Element `src-icon-button` CSS class instead.
- [SourceLoadingComponent API](./docs/api/loading.json): `src-loading` — Circular SVG progress/loading indicator. Use for inline loading states. Supports `size`, `progress`, custom stroke colors.
- [SourceLogoLoadingComponent API](./docs/api/logo-loading.json): `src-logo-loading` — Full-screen branded loading animation with 3D Source logo. Use for app/page-level loading states.
- [SourceModalElementComponent API](./docs/api/modal-element.json): `src-modal-element` — Lightweight modal using native HTML `<dialog>` element. No Angular CDK dependency. Opened via `SourceModalElementService.open(data)` where `data: SourceModalElementData` configures title, content, context, footer buttons. Requires `<src-overlay-container>` in app root.
- [SourceSliderComponent API](./docs/api/slider.json): `src-slider` — Low-level range slider. Supports horizontal/vertical orientation, ticks, custom thumb template, min/max/step.
- [SourceTileComponent API](./docs/api/tile.json): `src-tile` — Image thumbnail tile. Use for material previews, preset cards, option selectors. Supports `isActive`, `isDisabled`, `isLoading` states, `counter` badge with placement, `aspectRatio`, `titleLineClamp`, and content projection via `srcTileImage`, `srcTileTitle`, `srcTileProps`, `srcTileDelete` attributes.

## Source Elements (CSS-only styling)

Source Elements let you style standard HTML elements (`<button>`, `<input>`, `<select>`, etc.) using BEM CSS classes — no Angular component imports needed. Just add the class to a native HTML tag. All styles come from the `source.ui.native.scss` stylesheet.

- [Source Elements API (JSON)](./docs/api/source-elements.json): Machine-readable reference for all CSS-only elements with modifiers, sub-elements, and usage examples.

Use Source Elements when: you don't need Angular signal bindings, you want minimal overhead, or you're prototyping without Angular.

## Stylesheet import paths

STRICT RULE: Use ONLY the paths listed below. Do NOT fabricate paths like `@3dsource/source-ui-native/src/lib/styles/...` or `dist/...`.

**SCSS import (Angular projects with a builder) — add to your `styles.scss`:**
```
@use '../node_modules/@3dsource/source-ui-native/styles/source.ui.native.scss' as source-ui-native;
```

**Compiled CSS import (non-Angular / CSS-only / no builder) — add to `<head>` or import in your bundler:**
```
node_modules/@3dsource/source-ui-native/styles/source-ui-native.min.css
```

IMPORTANT: SCSS entry files use dots in the name (`source.ui.native.scss`), while compiled CSS uses dashes (`source-ui-native.min.css`). Do not confuse them.

## Icons

The library is icon-agnostic — no icon font is bundled. Icons are projected into components via `<ng-content>` (Angular) or placed directly inside elements (CSS-only).

STRICT RULE: Do NOT use the Material Icons font (`<link href="https://fonts.google.com/icon?family=Material+Icons">` or the `material-icons` CSS class). The font-based icon approach conflicts with Source UI styles. Use **SVG icons** instead.

Recommended icon source: [Material Symbols (Rounded)](https://fonts.google.com/icons?icon.style=Rounded) with settings: Style Rounded, Weight 400, Fill On, Optical size 20dp.

### SVG icon setup (Angular projects)

1. Create an `assets/icons/` folder in your project.
2. Download SVG icons from your design or from [Material Symbols](https://fonts.google.com/icons?icon.style=Rounded).
3. In each SVG file: set `fill="currentColor"` (for CSS color control), remove `width`/`height` attributes, keep `viewBox`.
4. Create an `SvgIconComponent` in your project (this component is NOT part of the library — copy it into your codebase):

```typescript
import { HttpClient } from '@angular/common/http';
import { Component, effect, inject, input, signal, untracked } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { first } from 'rxjs';

@Component({
  selector: 'src-icon',
  imports: [],
  template: `@if (svg()) {
    <div [innerHTML]="svg()" class="src-icon" [style.--srcIconSize]="size()"></div>
  }`,
  styles: [`
    .src-icon { width: var(--srcIconSize); height: var(--srcIconSize); color: inherit; }
    .src-icon svg { width: 100%; height: 100%; fill: currentColor; }
  `],
})
export class SvgIconComponent {
  name = input<string>('');
  size = input<string>('20px');
  PATH_TO_ICON_FOLDER = 'assets/icons';
  svg = signal<SafeHtml | null>(null);
  http = inject(HttpClient);
  sanitizer = inject(DomSanitizer);

  _ = effect(() => {
    const path = this.PATH_TO_ICON_FOLDER + '/' + this.name() + '.svg';
    untracked(() => {
      this.http.get(path, { responseType: 'text' }).pipe(first()).subscribe({
        next: (rawSvg) => this.svg.set(this.sanitizer.bypassSecurityTrustHtml(rawSvg)),
        error: () => console.warn('Icon "' + this.name() + '" not found at ' + path),
      });
    });
  });
}
```

5. Usage: `<src-icon name="close"></src-icon>`, `<src-icon name="chevron_left" size="32px"></src-icon>`
6. Default size: `20px`. Color inherits from parent element.

### SVG icon setup (non-Angular / CSS-only projects)

Inline the SVG directly in your HTML:
```html
<button class="src-icon-button">
  <svg viewBox="0 0 24 24" fill="currentColor"><path d="..."/></svg>
</button>
```

### Icon design tokens

- `--src-icon-size` — default icon size (16px)
- `--src-icon-default`, `--src-icon-info`, `--src-icon-success`, `--src-icon-error`, `--src-icon-warning` — contextual icon colors

- [Icons documentation](https://preview.3dsource.com/front-libraries/develop/#/icons)

## Component registry

- [Component Registry](./docs/api/_registry.json): Index of all source-ui-native components with selectors, kinds, and JSON file references

## Design tokens

Design tokens are defined as SCSS CSS custom properties with `--src-` prefix. Machine-readable JSON with all 1020 tokens. See "Design system rules" section below for token selection and usage rules.

- [Design Tokens JSON](./docs/design-tokens.json): All tokens grouped by category (primitives, color-light, color-dark, typeface, ui-sm/md/lg/xl, layout-sm/md/lg/xl) with scope and value info
- [Per-category token index](./docs/tokens/_index.json): Load only the token category you need to save context. Categories: primitives, color-light, color-dark, typeface, ui-sm/md/lg/xl, layout-sm/md/lg/xl

Token source files are in `src/lib/styles/variables/` (relative to this package):

- Color tokens: `color/light.scss` (light theme), `color/dark.scss` (dark theme)
- Layout tokens: `layout/_sm.scss` (base defaults, global scope), `layout/_md.scss`, `layout/_lg.scss`, `layout/_xl.scss` (responsive breakpoints — activate at 768px / 1440px / 1920px)
- UI tokens: `ui/_sm.scss`, `ui/_md.scss`, `ui/_lg.scss`, `ui/_xl.scss` (component sizing per breakpoint)
- Typography tokens: `typeface/web.scss`
- Primitive values: `primitives/primitives.scss`

## Design system rules

Before building custom UI, always search for an existing Source UI component or Source Element with the same semantic meaning. Only create new components as a last resort.

Full design system rules reference: [Design System Rules](./docs/llms-design-rules.md)

### Token selection priority

When styling, follow this priority chain:
1. Use an existing semantic token from `design-tokens.json` (`--src-space-*`, `--src-padding-*`, etc.)
2. If no exact semantic token exists — use the closest primitive from `design-tokens.json`
3. If no primitive fits — use a raw value (px/rem). **A raw value is always better than an invented token.**

STRICT RULE: Never invent a token name that does not exist in `design-tokens.json`.

### Token groups cheat sheet

- **Spacing**: `--src-space-*` (0–96 scale, e.g. `--src-space-4` = 16px)
- **UI sizing**: `--src-padding-*`, `--src-height-*`, `--src-gap-*`, `--src-icon-size`
- **Border radius**: `--src-border-rounded-*` (component-level), `--src-layout-radius-*` (layout-level)
- **Layout**: `--src-layout-padding-(const|var)-*`, `--src-layout-gap-(const|var)-*`, `--src-layout-height-(const|var)-*`
- **Typography**: `--src-font-*` (primitives), `--src-typography-var-*` (responsive composites)

### Responsive: `var` vs `const` tokens

- `var` tokens change by breakpoint (sm/md/lg/xl) — use for adaptive/responsive UI
- `const` tokens stay the same across all screen sizes — use for fixed-size UI
- `layout-sm` tokens are the base (global) defaults — they apply at all viewport widths. `layout-md/lg/xl` override them at their respective breakpoints (768px / 1440px / 1920px)
- Example: `--src-layout-padding-var-*` scales with viewport; `--src-layout-padding-const-*` does not

### Semantic color layers

Always use semantic color tokens, not raw color primitives:
- Surfaces: `--src-surface-*` — backgrounds
- Text: `--src-text-*` — font colors
- Icons: `--src-icon-*` — icon fills
- Borders: `--src-border-*` — border colors
- Accents/status: `--src-ui-*` — interactive states, status indicators
- Shadows: `--src-shadow-*` — elevation
- Gradients: `--src-gradient-*`

**Alpha rule**: Alpha tokens (`--src-color-alpha-*`) may only be used as overlays on top of a solid surface layer. Never use alpha as the only background without a solid surface under it.

### Radius hierarchy

Border radius tokens follow a hierarchy: smaller level number = bigger radius. Parent containers must have a larger (or equal) radius than nested children. Use only `--src-border-rounded-*` and `--src-layout-radius-*` tokens.

### Anti-patterns

- Using primitive color tokens (`--src-color-red-500`) for UI instead of semantic tokens (`--src-ui-accent-error`)
- Alpha token as standalone background (no solid surface beneath)
- Mixing `const` and `var` layout tokens in the same adaptive context
- Breaking radius hierarchy (child radius > parent radius)

## Theming: Custom Accent Colors

The accent color palette drives all primary interactive elements (buttons, selections, focus rings, links). You can override the default blue (`#017BFF`) with any brand color.

### How accent colors work

1. **Primitives** define the raw palette in `primitives/primitives.scss`:
   - `--src-color-primary-50` through `--src-color-primary-950` (11 shades)
   - `--src-color-alpha-accent-10` through `--src-color-alpha-accent-400` (5 alpha variants)

2. **Semantic tokens** in `color/light.scss` and `color/dark.scss` reference the primitives:
   - `--src-ui-accent-default: var(--src-ui-accent-default, #017bffff)` (primary action color)
   - `--src-ui-accent-default-hover: var(--src-color-primary-600)` (hover state)
   - `--src-ui-secondary-active: var(--src-color-alpha-accent-50)` (selected backgrounds)
   - etc.

3. **You only override primitives** — semantic mappings stay intact, so all components update automatically.

### Agent instruction: Override accent color

To change the accent color to a custom brand color (e.g. `#FF5722`):

1. Create `_accent-override.scss` in the user's project (NOT in the library):

```scss
// _accent-override.scss
// Custom accent color palette — override Source UI default blue
// Generated from base color: #FF5722
:root {
  // ── primary shades (50=lightest, 950=darkest) ──
  --src-color-primary-50:  #FFF3E0ff;
  --src-color-primary-100: #FFE0B2ff;
  --src-color-primary-200: #FFCC80ff;
  --src-color-primary-300: #FFB74Dff;
  --src-color-primary-400: #FFA726ff;
  --src-color-primary-500: #FF5722ff;  // ← your base color
  --src-color-primary-600: #F4511Eff;
  --src-color-primary-700: #E64A19ff;
  --src-color-primary-800: #D84315ff;
  --src-color-primary-900: #BF360Cff;
  --src-color-primary-950: #7F1D04ff;

  // ── Alpha variants (for backgrounds, hover states) ──
  // Format: base color (#FF5722) + alpha hex suffix
  --src-color-alpha-accent-10:  #FF572214;
  --src-color-alpha-accent-50:  #FF57221f;
  --src-color-alpha-accent-100: #FF572229;
  --src-color-alpha-accent-200: #FF57223d;
  --src-color-alpha-accent-300: #FF572252;
  --src-color-alpha-accent-400: #FF57225c;
}
```

2. Import it in `styles.scss` AFTER the Source UI stylesheets:

```scss
@use '../node_modules/@3dsource/source-ui-native/styles/source.ui.native.scss' as source-ui-native;
@use './accent-override'; // ← after library styles
```

### Palette generation algorithm

From a single base hex color, generate the 50–950 scale using HSL lightness steps:

| Shade | Lightness target |
|-------|-----------------|
| 50    | 95% |
| 100   | 88% |
| 200   | 78% |
| 300   | 68% |
| 400   | 58% |
| 500   | Base color (keep original lightness) |
| 600   | Base lightness − 5% |
| 700   | Base lightness − 12% |
| 800   | Base lightness − 18% |
| 900   | Base lightness − 28% |
| 950   | Base lightness − 40% |

Alpha variants use the base 500 color with these hex alpha suffixes:
- `10` → `14` (8% opacity)
- `50` → `1f` (12% opacity)
- `100` → `29` (16% opacity)
- `200` → `3d` (24% opacity)
- `300` → `52` (32% opacity)
- `400` → `5c` (36% opacity)

### Rules

- **NEVER modify** `primitives.scss`, `light.scss`, or `dark.scss` in the library
- **NEVER modify** semantic tokens — they reference primitives automatically
- The override file MUST be loaded AFTER the library stylesheet
- All 11 shades (50–950) and 6 alpha variants must be defined for full coverage
- Suffix `ff` on hex colors = fully opaque; alpha variants use partial opacity suffixes

## Optional

- [Full documentation (self-contained)](./docs/llms-full.txt): Comprehensive reference with all component APIs and design tokens inlined — no external links needed
- [Full component registry JSON](./docs/api/_registry.json): Machine-readable index for programmatic discovery
