@molecule/app-ui-angular

Framework · ui · App (browser) · v1.13.5 · Apache-2.0

Angular UI components for molecule.dev

npm install @molecule/app-ui-angular

npm · Source on GitHub · Implements @molecule/app-ui

How it works

@molecule/app-ui-angular adapts the @molecule/* cores to the ui framework on the app (browser) side.

import { Component } from '@angular/core'
import { setClassMap } from '@molecule/app-ui'
import { classMap } from '@molecule/app-ui-tailwind'
import { Button, Input } from '@molecule/app-ui-angular'

// Once at startup, before the first component renders:
setClassMap(classMap)

@Component({
  selector: 'app-save-panel',
  standalone: true,
  imports: [Button, Input],
  template: `
    <div mol-input placeholder="Name" [value]="name" (change)="name = $event.target.value"></div>
    <button mol-button color="primary" [loading]="saving" (click)="save()">Save</button>
  `,
})
class SavePanel {
  name = ''
  saving = false
  save(): void {}
}

Works with: @molecule/app-angular, @molecule/app-filesystem, @molecule/app-i18n, @molecule/app-icons, @molecule/app-ui

Reference

Angular UI components for molecule.dev.

Provides standalone Angular components at parity with @molecule/app-ui-react: every React export exists here under the same name, with the same props, the same rendered DOM (ClassMap classes, attributes, inline styles, text) and the same behaviour. Molecule's conformance tests render each component in React and Angular and compare the two.

React-named exports include Button, Card (+ CardHeader, CardTitle, CardDescription, CardContent, CardFooter), Input, Select, Textarea, Checkbox, RadioGroup, Switch, Accordion, Alert, Avatar, Badge, EmptyState, Icon, Label, Progress, Separator, Skeleton, Spinner, Tabs, Table, Pagination, Tooltip, Modal, Toast (+ ToastContainer, ToastProvider), ConfirmDialog, PromptDialog, Dropdown (+ DropdownLabel, DropdownSeparator), Form, FormField, LanguagePicker, PageHeader, PageShell, ResponsiveAppShell (+ its TopBar, Sidebar, Drawer, Content parts), SidebarUserCard, UserMenu, UserMenuPopover (+ its Trigger, Panel, SignOut parts), AuthGuard, ConfirmButton, OptimisticToggleButton, ThemeToggle, and the hooks useToast, usePanelClose, useIsDesktop and useUserMenuPopoverClose.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { setClassMap } from '@molecule/app-ui'
import { classMap } from '@molecule/app-ui-tailwind'
import { Button, Input } from '@molecule/app-ui-angular'

// Once at startup, before the first component renders:
setClassMap(classMap)

@Component({
  selector: 'app-save-panel',
  standalone: true,
  imports: [Button, Input],
  template: `
    <div mol-input placeholder="Name" [value]="name" (change)="name = $event.target.value"></div>
    <button mol-button color="primary" [loading]="saving" (click)="save()">Save</button>
  `,
})
class SavePanel {
  name = ''
  saving = false
  save(): void {}
}

Type

framework

Installation

npm install @molecule/app-ui-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-filesystem @molecule/app-i18n @molecule/app-icons @molecule/app-inline-style-dom @molecule/app-overlay-dom @molecule/app-pointer-events-dom @molecule/app-ui

API

Interfaces

KitFieldChangeEvent

Both targets expose the field's string value during the callback.

interface KitFieldChangeEvent extends KitEvent {
  /** The edited field, or its value snapshot on a device. */
  readonly target: EventTarget & { value: string }
  /** The field handling the change. */
  readonly currentTarget: KitFieldChangeEvent['target']
}

CSSProperties

Framework-agnostic CSS properties. Mirrors React.CSSProperties but without React dependency.

interface CSSProperties {
  [key: string]: string | number | undefined
}

KitEvent

The event a web UI kit hands a component's handler: the members shared by the web kits. React's kit passes React's event (so stopPropagation() stops React parent handlers), the other web kits pass the DOM event; both satisfy this type. A handler that needs a member only one of them has (nativeEvent, composedPath(), isComposing) takes the component's ref element (see BaseProps) and listens on it.

type is left out on purpose: kits report different event types for the same moment (a text field's onChange is React's 'change' and the DOM's 'input').

interface KitEvent {
  /** The element the event started on. */
  readonly target: EventTarget | null
  /** The element of the component the handler was passed to. */
  readonly currentTarget: EventTarget | null
  /** Whether a handler already called `KitEvent.preventDefault`. */
  readonly defaultPrevented: boolean
  /** Cancels the browser's default action (a form's submit, a checkbox's toggle). */
  preventDefault(): void
  /** Stops handlers of ancestor components of the same kit. */
  stopPropagation(): void
}

KitModifierKeys

The modifier keys held during a mouse or keyboard event.

interface KitModifierKeys {
  /** Alt (Option) was held. */
  readonly altKey: boolean
  /** Control was held. */
  readonly ctrlKey: boolean
  /** Meta (Command, Windows) was held. */
  readonly metaKey: boolean
  /** Shift was held. */
  readonly shiftKey: boolean
}

KitMouseEvent

A mouse event as every kit hands it to a handler.

interface KitMouseEvent extends KitEvent, KitModifierKeys {
  /** The button that changed state (0 main, 1 auxiliary, 2 secondary). */
  readonly button: number
  /** The buttons held, as a bit mask. */
  readonly buttons: number
  /** The pointer's x position in the viewport. */
  readonly clientX: number
  /** The pointer's y position in the viewport. */
  readonly clientY: number
  /** The pointer's x position in the document. */
  readonly pageX: number
  /** The pointer's y position in the document. */
  readonly pageY: number
  /** The click count of a click event. */
  readonly detail: number
  /** The element the pointer came from or went to, for enter and leave events. */
  readonly relatedTarget: EventTarget | null
}

KitKeyboardEvent

A keyboard event as every kit hands it to a handler.

interface KitKeyboardEvent extends KitEvent, KitModifierKeys {
  /** The key's value (`'Enter'`, `'a'`). */
  readonly key: string
  /** The physical key (`'KeyA'`). */
  readonly code: string
  /** Whether the key is held down and auto-repeating. */
  readonly repeat: boolean
}

KitFocusEvent

A focus event as every kit hands it to a handler.

interface KitFocusEvent extends KitEvent {
  /** The element losing focus (on focus) or gaining it (on blur). */
  readonly relatedTarget: EventTarget | null
}

BaseProps

Base props shared by all components.

Ref element: a component that renders one main element gives the caller that element, the one that takes className and style. Each UI kit hands it over in its framework's own way: React and Solid a ref, Vue a template ref's $el, Svelte bind:ref, Angular the component's element() signal. It is empty while the element is not rendered (a closed Tooltip, Dropdown or Modal). A component's own doc names the element when it is not the outermost one.

interface BaseProps {
  /**
   * Additional CSS class name(s).
   */
  className?: string

  /**
   * Inline styles.
   */
  style?: CSSProperties

  /**
   * Test ID for automated testing.
   */
  testId?: string

  /**
   * Automation ID for AI agents and E2E tests. Maps to the `data-mol-id`
   * HTML attribute. Use `molId()` from `./automation.js` to generate
   * semantic IDs. (Tooling only — screen readers do not expose `data-*`
   * attributes; accessible names come from labels/`aria-*`.)
   */
  automationId?: string

  /**
   * Disables the controls the component renders: a disabled Button, Input, Textarea, Select,
   * Checkbox, Switch, RadioGroup, Tabs, Accordion or Pagination takes no input, a disabled
   * Dropdown never opens, and a disabled Card never calls `onClick` (an interactive one is
   * announced as disabled and leaves the tab order). A component that renders no control
   * (Badge, Spinner, Skeleton, a layout box) ignores it.
   */
  disabled?: boolean
}

HTMLElementProps

Base props for HTML elements. Framework bindings should extend this with framework-specific attributes.

interface HTMLElementProps extends BaseProps, Pick<ElementProps, 'lang'> {
  id?: string
  title?: string
  tabIndex?: number
  role?: ElementRole
  'aria-label'?: string
  'aria-labelledby'?: string
  'aria-describedby'?: string
  'aria-hidden'?: boolean
  'aria-disabled'?: boolean
  'aria-expanded'?: boolean
  'aria-selected'?: boolean
  'aria-checked'?: boolean | 'mixed'
  'aria-pressed'?: boolean | 'mixed'
  'aria-invalid'?: boolean
  'aria-required'?: boolean
  'aria-readonly'?: boolean
  'aria-busy'?: boolean
  'aria-live'?: 'off' | 'polite' | 'assertive'
  onClick?: MouseEventHandler
  onDoubleClick?: MouseEventHandler
  onMouseEnter?: MouseEventHandler
  onMouseLeave?: MouseEventHandler
  onFocus?: FocusEventHandler
  onBlur?: FocusEventHandler
  onKeyDown?: KeyboardEventHandler
  onKeyUp?: KeyboardEventHandler
  onKeyPress?: KeyboardEventHandler
}

InputElementProps

Base props for input elements.

interface InputElementProps extends HTMLElementProps {
  name?: string
  value?: string | number | readonly string[]
  defaultValue?: string | number | readonly string[]
  placeholder?: string
  required?: boolean
  readOnly?: boolean
  autoFocus?: boolean
  autoComplete?: string
  maxLength?: number
  minLength?: number
  pattern?: string
  /** Web change event. Prefer the control's value callback for shared web and native code. */
  onChange?: ChangeEventHandler
  onInput?: FormEventHandler
}

ButtonElementProps

Base props for button elements.

interface ButtonElementProps extends HTMLElementProps {
  /**
   * Defaults to `'button'` in every framework binding, so a button never submits a
   * form by accident. A form's primary action must set `type="submit"`: Enter then
   * submits the form, and tests that select `button[type="submit"]` find it.
   */
  type?: 'button' | 'submit' | 'reset'
  name?: string
  value?: string
  form?: string
}

TextareaElementProps

Base props for textarea elements.

interface TextareaElementProps extends HTMLElementProps {
  name?: string
  value?: string
  defaultValue?: string
  placeholder?: string
  required?: boolean
  readOnly?: boolean
  autoFocus?: boolean
  rows?: number
  cols?: number
  maxLength?: number
  minLength?: number
  wrap?: 'hard' | 'soft' | 'off'
  /** Web change event. `TextareaProps.onValueChange` also works on native. */
  onChange?: EventHandler<KitFieldChangeEvent>
  onInput?: FormEventHandler
}

SelectElementProps

Base props for select elements.

interface SelectElementProps extends HTMLElementProps {
  name?: string
  required?: boolean
  autoFocus?: boolean
  multiple?: boolean
  /** Web change event. `SelectProps.onValueChange` also works on native. */
  onChange?: EventHandler<KitFieldChangeEvent>
}

FormElementProps

Base props for form elements.

interface FormElementProps extends HTMLElementProps {
  action?: string
  method?: 'get' | 'post'
  encType?: string
  target?: string
  noValidate?: boolean
  autoComplete?: 'on' | 'off'
  onSubmit?: FormEventHandler
  onReset?: FormEventHandler
}

ButtonProps

Props for the Button component.

interface ButtonProps extends ButtonElementProps {
  /**
   * Button content.
   */
  children?: Children

  /**
   * Visual variant.
   */
  variant?: ButtonVariant

  /**
   * Color scheme.
   */
  color?: ColorVariant

  /**
   * Button size.
   */
  size?: ButtonSize

  /**
   * Whether the button is in a loading state.
   */
  loading?: boolean

  /**
   * Loading text to display.
   */
  loadingText?: string

  /**
   * Whether the button takes full width.
   */
  fullWidth?: boolean

  /**
   * Icon to display before the label.
   */
  leftIcon?: Children

  /**
   * Icon to display after the label.
   */
  rightIcon?: Children
}

InputProps

Props for the Input component (text field, email, password, etc.).

Ref element: the native <input>.

interface InputProps extends InputElementProps, Pick<TextFieldProps, 'onValueChange'> {
  /** The edited field's text is available as `event.target.value`. */
  onChange?: EventHandler<KitFieldChangeEvent>

  /**
   * Input type.
   */
  type?: InputType

  /**
   * Input size.
   */
  size?: Size

  /**
   * Horizontal text alignment inside the input (see
   * `InputClassOptions.align`). Defaults to the bond's own style.
   */
  align?: 'left' | 'center'

  /**
   * Label text.
   */
  label?: string

  /**
   * Error message.
   */
  error?: string

  /**
   * Hint/help text.
   */
  hint?: string

  /**
   * Element to display on the left.
   */
  leftElement?: Children

  /**
   * Element to display on the right.
   */
  rightElement?: Children

  /**
   * Whether to show a clear button.
   */
  clearable?: boolean

  /**
   * Called when the clear button is clicked.
   */
  onClear?: () => void

  /**
   * Accessible label for the clear button.
   * @default 'Clear'
   */
  clearLabel?: string
}

TextareaProps

Props for the Textarea component.

Ref element: the native <textarea>.

interface TextareaProps extends TextareaElementProps, Pick<TextFieldProps, 'onValueChange'> {
  /**
   * Text size tier (see `TextareaClassOptions.size`) — pass the same
   * `size` as a neighboring Input for identical font sizes.
   */
  size?: Size

  /**
   * Label text.
   */
  label?: string

  /**
   * Error message.
   */
  error?: string

  /**
   * Hint/help text.
   */
  hint?: string

  /**
   * Whether the textarea auto-resizes.
   */
  autoResize?: boolean

  /**
   * Minimum number of rows.
   */
  minRows?: number

  /**
   * Maximum number of rows.
   */
  maxRows?: number
}

SelectOption

A single option in a Select dropdown.

interface SelectOption<T = string> {
  /**
   * Option value.
   */
  value: T

  /**
   * Display label.
   */
  label: string

  /**
   * Whether the option is disabled.
   */
  disabled?: boolean

  /**
   * Option group (for grouped selects).
   */
  group?: string
}

SelectProps

Props for the Select dropdown component (single or multi-select).

Ref element: the native <select>.

interface SelectProps<T = string> extends SelectElementProps {
  /**
   * Select options.
   */
  options: SelectOption<T>[]

  /**
   * Current value.
   */
  value?: T

  /**
   * Called with the selected value on web and native.
   */
  onValueChange?: (value: T) => void

  /**
   * Select size.
   */
  size?: Size

  /**
   * Label text.
   */
  label?: string

  /**
   * Placeholder text.
   */
  placeholder?: string

  /**
   * Error message.
   */
  error?: string

  /**
   * Hint/help text.
   */
  hint?: string

  /**
   * Whether to allow clearing the selection.
   */
  clearable?: boolean
}

CheckboxProps

Props for the Checkbox component.

Ref element: the native <input type="checkbox">.

interface CheckboxProps extends InputElementProps, Pick<CheckFieldProps, 'onCheckedChange'> {
  /**
   * Checkbox label.
   */
  label?: Children

  /**
   * Whether the checkbox is checked.
   */
  checked?: boolean

  /**
   * Whether the checkbox is in an indeterminate state.
   */
  indeterminate?: boolean

  /**
   * Checkbox size.
   */
  size?: Size

  /**
   * Error message.
   */
  error?: string
}

RadioGroupProps

Props for the RadioGroup component.

interface RadioGroupProps<T = string> extends BaseProps {
  /**
   * Radio options.
   */
  options: RadioOption<T>[]

  /**
   * Current value.
   */
  value?: T

  /**
   * Change handler.
   */
  onChange?: (value: T) => void

  /**
   * Radio size.
   */
  size?: Size

  /**
   * Group label.
   */
  label?: string

  /**
   * Shared `name` attribute for the group's radio inputs (used for native
   * form submission). When omitted, a unique per-instance name is generated
   * so separate groups never merge — the visible `label` is deliberately
   * NOT used as the name, because two groups with the same label (e.g. two
   * "Size" pickers) would otherwise form ONE native radio group and
   * deselect each other.
   */
  name?: string

  /**
   * Layout direction.
   */
  direction?: 'horizontal' | 'vertical'

  /**
   * Error message.
   */
  error?: string
}

SwitchProps

Props for the Switch/Toggle component.

Ref element: the role="switch" button.

interface SwitchProps extends InputElementProps, Pick<CheckFieldProps, 'onCheckedChange'> {
  /**
   * Switch label.
   */
  label?: Children

  /**
   * Whether the switch is on.
   */
  checked?: boolean

  /**
   * Switch size.
   */
  size?: Size

  /**
   * Color when on.
   */
  color?: ColorVariant
}

ModalProps

Props for the Modal/Dialog component.

Ref element: the dialog (role="dialog"), empty while closed.

interface ModalProps extends HTMLElementProps {
  /**
   * Whether the modal is open.
   */
  open: boolean

  /**
   * Called when the modal should close.
   */
  onClose: () => void

  /**
   * Modal title.
   */
  title?: string

  /**
   * Modal content.
   */
  children?: Children

  /**
   * Modal size.
   */
  size?: ModalSize

  /**
   * Whether to show a close button.
   */
  showCloseButton?: boolean

  /**
   * Whether clicking the overlay closes the modal.
   */
  closeOnOverlayClick?: boolean

  /**
   * Whether pressing Escape closes the modal.
   */
  closeOnEscape?: boolean

  /**
   * Footer content (typically action buttons).
   */
  footer?: Children

  /**
   * Whether the modal is centered vertically.
   */
  centered?: boolean

  /**
   * Whether to prevent body scroll when open.
   */
  preventScroll?: boolean

  /**
   * Accessible label for the close button.
   * @default 'Close'
   */
  closeLabel?: string

  /**
   * The control that takes focus when the modal opens, such as the field a dialog exists to fill.
   * Without it, focus goes to the first focusable control, or to the dialog when it has none. The
   * modal reads it once the open dialog is in the document, so a control rendered in the
   * children can be named here.
   */
  initialFocus?: OverlayTarget
}

SpinnerProps

Props for the Spinner/loading indicator component.

interface SpinnerProps extends BaseProps {
  /**
   * Spinner size.
   */
  size?: Size

  /**
   * Spinner color.
   */
  color?: ColorVariant | string

  /**
   * Loading label (for accessibility).
   */
  label?: string

  /**
   * Spinner thickness.
   */
  thickness?: number
}

AvatarProps

Props for the Avatar component.

interface AvatarProps extends HTMLElementProps {
  /**
   * Image source URL.
   */
  src?: string

  /**
   * Alt text for the image.
   */
  alt?: string

  /**
   * Name for fallback initials.
   */
  name?: string

  /**
   * Avatar size.
   */
  size?: Size | number

  /**
   * Whether the avatar is rounded.
   */
  rounded?: boolean

  /**
   * Fallback element when no image.
   */
  fallback?: Children
}

BadgeProps

Props for the Badge component (status labels, counts, tags).

interface BadgeProps extends HTMLElementProps {
  /**
   * Badge content.
   */
  children?: Children

  /**
   * Badge color.
   */
  color?: ColorVariant

  /**
   * Badge variant.
   */
  variant?: 'solid' | 'outline' | 'subtle'

  /**
   * Badge size.
   */
  size?: Size

  /**
   * Whether the badge is rounded.
   */
  rounded?: boolean
}

TooltipProps

Props for the Tooltip component (hover/focus popover with informational text).

Ref element: the role="tooltip" box, empty while hidden.

interface TooltipProps extends HTMLElementProps {
  /**
   * Tooltip content.
   */
  content: Children

  /**
   * Element that triggers the tooltip.
   */
  children: Children

  /**
   * Tooltip placement.
   */
  placement?: TooltipPlacement

  /**
   * Delay before showing (ms).
   */
  delay?: number

  /**
   * Whether the tooltip has an arrow.
   */
  hasArrow?: boolean
}

CardProps

Props for the Card container component (elevated, outlined, or filled surface).

interface CardProps extends HTMLElementProps {
  /**
   * Card content.
   */
  children?: Children

  /**
   * Card variant.
   */
  variant?: 'elevated' | 'outlined' | 'filled'

  /**
   * Whether the card is interactive (clickable).
   */
  interactive?: boolean

  /**
   * Padding size.
   */
  padding?: Size | 'none'
}

CardSectionProps

Props of a card's header, title, description, content and footer.

interface CardSectionProps extends ElementProps {
  /** Tooltip text. */
  title?: string

  /** CSS for the web. */
  style?: CSSProperties

  /** Contents. */
  children?: Children
}

ContainerProps

Props for the Container layout component.

interface ContainerProps extends HTMLElementProps {
  /**
   * Container content.
   */
  children?: Children

  /**
   * Maximum width.
   */
  maxWidth?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full' | string

  /**
   * Whether to center the container.
   */
  centered?: boolean

  /**
   * Horizontal padding.
   */
  paddingX?: Size | string
}

FlexProps

Flex container props.

interface FlexProps extends HTMLElementProps {
  /**
   * Flex content.
   */
  children?: Children

  /**
   * Flex direction.
   */
  direction?: 'row' | 'column' | 'row-reverse' | 'column-reverse'

  /**
   * Justify content.
   */
  justify?: 'start' | 'end' | 'center' | 'between' | 'around' | 'evenly'

  /**
   * Align items.
   */
  align?: 'start' | 'end' | 'center' | 'baseline' | 'stretch'

  /**
   * Flex wrap.
   */
  wrap?: 'wrap' | 'nowrap' | 'wrap-reverse'

  /**
   * Gap between items.
   */
  gap?: Size | string | number
}

GridProps

Grid container props.

interface GridProps extends HTMLElementProps {
  /**
   * Grid content.
   */
  children?: Children

  /**
   * Number of columns.
   */
  columns?: number | string

  /**
   * Number of rows.
   */
  rows?: number | string

  /**
   * Gap between items.
   */
  gap?: Size | string | number

  /**
   * Column gap.
   */
  columnGap?: Size | string | number

  /**
   * Row gap.
   */
  rowGap?: Size | string | number
}

SpacerProps

Props for the Spacer layout component (adds whitespace between elements).

interface SpacerProps extends BaseProps {
  /**
   * Space size.
   */
  size?: Size | string | number

  /**
   * Whether the spacer is horizontal.
   */
  horizontal?: boolean
}

FormProps

Props for the Form component (wraps inputs with submission handling and validation).

interface FormProps extends FormElementProps {
  /**
   * Form content.
   */
  children?: Children

  /**
   * Submit handler with form data.
   */
  onFormSubmit?: (data: Record<string, unknown>) => void | Promise<void>

  /**
   * Whether the form is submitting.
   */
  submitting?: boolean
}

FormFieldProps

Form field wrapper props.

interface FormFieldProps extends HTMLElementProps {
  /**
   * Field content.
   */
  children?: Children

  /**
   * Field label.
   */
  label?: string

  /**
   * Field name.
   */
  name?: string

  /**
   * Error message.
   */
  error?: string

  /**
   * Hint/help text.
   */
  hint?: string

  /**
   * Whether the field is required.
   */
  required?: boolean
}

AlertProps

Props for the Alert component.

interface AlertProps extends HTMLElementProps {
  /**
   * Alert content.
   */
  children?: Children

  /**
   * Alert title.
   */
  title?: string

  /**
   * Alert status/type.
   */
  status?: ColorVariant

  /**
   * Alert variant.
   */
  variant?: 'solid' | 'subtle' | 'outline' | 'left-accent'

  /**
   * Whether the alert is dismissible.
   */
  dismissible?: boolean

  /**
   * Called when dismissed.
   */
  onDismiss?: () => void

  /**
   * Icon to display.
   */
  icon?: Children

  /**
   * Accessible label for the dismiss button.
   * @default 'Dismiss'
   */
  dismissLabel?: string
}

ToastProps

Props for the Toast/notification component.

interface ToastProps extends HTMLElementProps {
  /**
   * Toast content.
   */
  children?: Children

  /**
   * Toast title.
   */
  title?: string

  /**
   * Toast description.
   */
  description?: string

  /**
   * Toast status/type.
   */
  status?: ColorVariant

  /**
   * Duration in milliseconds (0 for persistent).
   */
  duration?: number

  /**
   * Whether the toast is dismissible.
   */
  dismissible?: boolean

  /**
   * Called when dismissed.
   */
  onDismiss?: () => void

  /**
   * Toast position.
   */
  position?: 'top' | 'top-right' | 'top-left' | 'bottom' | 'bottom-right' | 'bottom-left'

  /**
   * Accessible label for the close button.
   * @default 'Close'
   */
  closeLabel?: string
}

TabItem

A single tab in a Tabs component.

interface TabItem<T = string> {
  /**
   * Tab value/id.
   */
  value: T

  /**
   * Tab label.
   */
  label: Children

  /**
   * Tab content.
   */
  content?: Children

  /**
   * Whether the tab is disabled.
   */
  disabled?: boolean

  /**
   * Icon to display.
   */
  icon?: Children
}

TabsProps

Props for the Tabs component (switchable tabbed content panels).

interface TabsProps<T = string> extends BaseProps {
  /**
   * Tab items.
   */
  items: TabItem<T>[]

  /**
   * Current active tab.
   */
  value?: T

  /**
   * Default active tab.
   */
  defaultValue?: T

  /**
   * Change handler.
   */
  onChange?: (value: T) => void

  /**
   * Tab variant.
   */
  variant?: 'line' | 'enclosed' | 'soft-rounded' | 'solid-rounded'

  /**
   * Tab size.
   */
  size?: Size

  /**
   * Whether tabs are fitted (take full width).
   */
  fitted?: boolean
}

AccordionItem

A single item in an Accordion component.

interface AccordionItem<T = string> {
  /**
   * Item value/id.
   */
  value: T

  /**
   * Item header/trigger.
   */
  header: Children

  /**
   * Item content.
   */
  content: Children

  /**
   * Whether the item is disabled.
   */
  disabled?: boolean
}

AccordionProps

Props for the Accordion component.

interface AccordionProps<T = string> extends BaseProps {
  /**
   * Accordion items.
   */
  items: AccordionItem<T>[]

  /**
   * Expanded item(s).
   */
  value?: T | T[]

  /**
   * Default expanded item(s).
   */
  defaultValue?: T | T[]

  /**
   * Change handler.
   */
  onChange?: (value: T | T[]) => void

  /**
   * Whether multiple items can be expanded.
   */
  multiple?: boolean

  /**
   * Whether items can be collapsed.
   */
  collapsible?: boolean
}

TableColumn

Table column definition.

interface TableColumn<T> {
  /**
   * Column key (data property).
   */
  key: keyof T | string

  /**
   * Column header.
   */
  header: Children

  /**
   * Custom cell renderer.
   */
  render?: (value: unknown, row: T, index: number) => Children

  /**
   * Column width.
   */
  width?: string | number

  /**
   * Whether the column is sortable.
   */
  sortable?: boolean

  /**
   * Text alignment.
   */
  align?: 'left' | 'center' | 'right'
}

TableProps

Props for the Table component.

Ref element: the <table>.

interface TableProps<T> extends HTMLElementProps {
  /**
   * Table data.
   */
  data: T[]

  /**
   * Column definitions.
   */
  columns: TableColumn<T>[]

  /**
   * Row key extractor.
   */
  rowKey?: keyof T | ((row: T) => string | number)

  /**
   * Whether to show borders.
   */
  bordered?: boolean

  /**
   * Whether rows are striped.
   */
  striped?: boolean

  /**
   * Whether rows are hoverable.
   */
  hoverable?: boolean

  /**
   * Table size.
   */
  size?: Size

  /**
   * Empty state content.
   */
  emptyContent?: Children

  /**
   * Loading state.
   */
  loading?: boolean

  /**
   * Sort configuration.
   */
  sort?: { key: string; direction: 'asc' | 'desc' }

  /**
   * Sort change handler.
   */
  onSort?: (key: string, direction: 'asc' | 'desc') => void

  /**
   * Row click handler.
   */
  onRowClick?: (row: T, index: number) => void
}

PaginationProps

Props for the Pagination component (page navigation with current page, total, page size, and change callbacks).

interface PaginationProps extends BaseProps {
  /**
   * Current page (1-indexed).
   */
  page: number

  /**
   * Total number of pages.
   */
  totalPages: number

  /**
   * Page change handler.
   */
  onChange: (page: number) => void

  /**
   * Number of sibling pages to show.
   */
  siblings?: number

  /**
   * Number of boundary pages to show.
   */
  boundaries?: number

  /**
   * Pagination size.
   */
  size?: Size

  /**
   * Whether to show first/last buttons.
   */
  showFirstLast?: boolean

  /**
   * Whether to show previous/next buttons.
   */
  showPrevNext?: boolean

  /**
   * Accessible labels for pagination controls.
   */
  labels?: {
    nav?: string
    first?: string
    previous?: string
    next?: string
    last?: string
    goToPage?: (page: number) => string
  }
}

SkeletonProps

Props for the Skeleton loading placeholder component.

interface SkeletonProps extends BaseProps {
  /**
   * Skeleton width.
   */
  width?: string | number

  /**
   * Skeleton height.
   */
  height?: string | number

  /**
   * Whether the skeleton is circular.
   */
  circle?: boolean

  /**
   * Border radius.
   */
  borderRadius?: string | number

  /**
   * Animation type.
   */
  animation?: 'pulse' | 'wave' | 'none'
}

PageShellProps

Props for the PageShell component — authenticated page wrapper with navigation.

interface PageShellProps extends BaseProps {
  /** Sidebar content (navigation links). */
  sidebar?: Children
  /** Top bar content (breadcrumbs, user menu). */
  topbar?: Children
  /** Whether the sidebar is collapsed. */
  sidebarCollapsed?: boolean
  /** Callback when sidebar toggle is clicked. */
  onSidebarToggle?: () => void
  /** Main content. */
  children?: Children
}

EmptyStateProps

Props for the EmptyState component — shown when a list or section has no data.

interface EmptyStateProps extends BaseProps {
  /** Icon or illustration to display. */
  icon?: Children
  /** Main heading text. */
  title: string
  /** Description text. */
  description?: string
  /** Primary action button (e.g., "Create first item"). */
  action?: Children
}

PageHeaderProps

Props for the PageHeader component — consistent page title area.

interface PageHeaderProps extends BaseProps {
  /** Page title. */
  title: string
  /** Page description. */
  description?: string
  /** Action buttons (e.g., "Create", "Export"). */
  actions?: Children
  /** Breadcrumb trail. */
  breadcrumbs?: Array<{ label: string; href?: string }>
}

AccordionItemData

One accordion item (React's AccordionItem).

interface AccordionItemData {
  /** The item's value (identity for expansion state). */
  value: string
  /** The header (text, or a TemplateRef from a node value). */
  header?: unknown
  /** The body (text, or a TemplateRef from a node value). */
  content?: unknown
  /** Whether the item's trigger is disabled. */
  disabled?: boolean
}

AuthGuardProps

Props for AuthGuard (React's AuthGuardProps, in Angular's form).

The fallback UI is a string | number | TemplateRef<unknown> input or a projected [slot=loadingFallback]; the authenticated children are projected content, so they have no member.

interface AuthGuardProps {
  /** Element rendered while the auth status is `loading`. */
  loadingFallback?: string | number | TemplateRef<unknown>
  /** i18n key for the default loading-tag text (default `common.loading`). */
  loadingKey?: string
  /** Fallback text if the i18n key is missing (default `Loading...`). */
  loadingDefault?: string
  /** Path to redirect to when unauthenticated (default `/login`). */
  loginPath?: string
  /** Fired when `isAuthenticated` becomes true (also when true at mount). */
  onAuthenticated?: () => void
}

ConfirmButtonProps

Props for ConfirmButton (React's ConfirmButtonProps, in Angular's form).

The three labels are node-valued in React; here each is a string | number | TemplateRef<unknown> input, and a caller may project the same label as [slot=label] / [slot=confirmLabel] / [slot=pendingLabel] instead. The button members React keeps from ButtonProps (variant, color, size, className, style, testId, automationId, disabled) are all accepted here too.

interface ConfirmButtonProps {
  /**
   * Fired ONLY on the confirming (second) click — i.e. when the action
   * actually commits.
   */
  onConfirm?: () => void | Promise<void>
  /** Visible label in the idle (armed-to-be-clicked) state. */
  label?: string | number | TemplateRef<unknown>
  /** Visible label in the armed state (defaults to a localized "Confirm?"). */
  confirmLabel?: string | number | TemplateRef<unknown>
  /** Visible label while `ConfirmButtonProps.onConfirm` is pending. */
  pendingLabel?: string | number | TemplateRef<unknown>
  /** Seconds before the armed state auto-disarms (`0` disables auto-disarm). */
  disarmSeconds?: number
  /** Disables the control entirely (idle and confirming states). */
  disabled?: boolean
  /** `data-testid` for the button. */
  testId?: string
  /** Extra classes joined onto the button classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** Button variant (passed through to the button classes). */
  variant?: ButtonVariant
  /** Button color; the armed state always shows the error color. */
  color?: ColorVariant
  /** Button size. */
  size?: Size
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
}

ConfirmDialogProps

Props for ConfirmDialog (React's ConfirmDialogProps, in Angular's form).

Node-valued members are string | number | TemplateRef<unknown> inputs; a caller may project the same content as [slot=title] / [slot=description] instead. onClose and onConfirm keep React's names and signatures here; the component emits them through its close and confirm outputs.

interface ConfirmDialogProps {
  /** Whether the dialog is open. */
  open: boolean
  /** Called when the dialog should close (carried by the `close` output). */
  onClose: () => void
  /** Title. */
  title?: string | number | TemplateRef<unknown>
  /** Body / warning text. */
  description?: string | number | TemplateRef<unknown>
  /** Confirm-button label. */
  confirmLabel?: string | number | TemplateRef<unknown>
  /** Cancel-button label. */
  cancelLabel?: string | number | TemplateRef<unknown>
  /** Called when the user confirms (carried by the `confirm` output). */
  onConfirm: () => void | Promise<void>
  /** Is the confirm action destructive? Defaults to true. */
  destructive?: boolean
  /** Disables both buttons (the caller owns the pending state). */
  loading?: boolean
}

ReactFormProps

Props for Form (React's ReactFormProps, in Angular's form).

React's form adds one prop to the core FormProps: a failure managed by an external form controller (useForm().formState.submitError). Binding the submitError input is the Angular equivalent — the form then renders the same accessible server-error list instead of the failure it captured.

interface ReactFormProps extends FormProps {
  /** A rejected submission, for example useForm().formState.submitError. */
  submitError?: unknown
}

IconProps

Props for Icon (React's IconProps, in Angular's form).

React extends SVGProps<SVGSVGElement> so any SVG attribute reaches the <svg>; the host IS the <svg>, so extra data-*, aria-*, role and event attributes spread onto it exactly as React spreads them. The named props are typed here.

interface IconProps {
  /** The glyph name from the bonded icon set. */
  name: IconName
  /** Width and height in pixels (default 20). */
  size?: number
  /** Class name forwarded to the `<svg>`. */
  className?: string
  /** Explicit `aria-hidden` (React keeps `false` as the string `"false"`). */
  'aria-hidden'?: boolean | string
}

LanguagePickerProps

Props for LanguagePicker (React's LanguagePickerProps, in Angular's form).

React's renderTrigger is a render function receiving the open action; here it is a TemplateRef<unknown> whose context carries open (also as $implicit). Extra <button> attributes reach the trigger through the host (React's rest spread).

interface LanguagePickerProps {
  /** i18n key for the trigger label / aria-label (default `footer.language`). */
  labelKey?: string
  /** Fallback label if the i18n key is missing (default `Language`). */
  labelDefault?: string
  /** i18n key for the modal title (default `languagePicker.modalTitle`). */
  modalTitleKey?: string
  /** Fallback modal title if the i18n key is missing (default `Choose language`). */
  modalTitleDefault?: string
  /** Icon glyph before the current locale name (default `globe`). */
  icon?: IconName
  /** Pixel size for the rendered icon (default 16). */
  iconSize?: number
  /** What the trigger renders: the locale name, its code, or the icon only. */
  display?: 'name' | 'code' | 'icon'
  /** Extra classes appended to the trigger button. */
  className?: string
  /** Inline style object for the trigger button (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the trigger button. */
  testId?: string
  /** `data-mol-id` for the trigger button (React's `automationId`; default `language-picker-trigger`). */
  automationId?: string
  /** Optional trigger replacement (a node value rendered as a template). */
  renderTrigger?: TemplateRef<unknown>
}

LoadErrorBannerProps

Props for LoadErrorBanner (React's LoadErrorBannerProps, in Angular's form). Rest props (data-*, aria-*, id) land on the host, so they are not enumerated here.

interface LoadErrorBannerProps {
  /** The primary error line. */
  message?: string | number | TemplateRef<unknown>
  /** Secondary line under the message. */
  detail?: string | number | TemplateRef<unknown>
  /** Called when Retry is clicked; a returned promise keeps the button pending. */
  onRetry?: () => void | Promise<void>
  /** Retry-button label. */
  retryLabel?: string | number | TemplateRef<unknown>
  /** `data-mol-id` for the retry button (default `load-error-retry`). */
  retryMolId?: string
  /** Extra classes for the root (React's rest `className`). */
  className?: string
  /** `data-testid` for the root. */
  testId?: string
  /** `data-mol-id` for the root (React's `automationId`). */
  automationId?: string
}

OptimisticToggleButtonProps

Props for OptimisticToggleButton (React's OptimisticToggleButtonProps, in Angular's form).

The labels and icons are node-valued in React; here each is a string | number | TemplateRef<unknown> input, and the labels may also be projected as [slot=activeLabel] / [slot=inactiveLabel] (icons as [slot=leftIcon] / [slot=rightIcon]).

interface OptimisticToggleButtonProps {
  /** The loaded server value. */
  value: boolean
  /** Saves the desired boolean and returns the server-confirmed boolean. */
  commit: (desired: boolean) => Promise<boolean>
  /** Label when the displayed value is true. */
  activeLabel: string | number | TemplateRef<unknown>
  /** Label when the displayed value is false. */
  inactiveLabel: string | number | TemplateRef<unknown>
  /** Receives a failed save after the controller has restored the confirmed value. */
  onError?: (error: unknown) => void
  /** Button variant. */
  variant?: ButtonVariant
  /** Button color. */
  color?: ColorVariant
  /** Button size. */
  size?: Size
  /** Whether the button stretches to fill its container. */
  fullWidth?: boolean
  /** Left icon (node value). */
  leftIcon?: string | number | TemplateRef<unknown>
  /** Right icon (node value). */
  rightIcon?: string | number | TemplateRef<unknown>
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** Disables the button (permissions, never a pending save). */
  disabled?: boolean
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
}

PanelCloseProviderProps

Props for PanelCloseProvider (React's PanelCloseProviderProps, in Angular's form). The panel content is projected content, so it has no member.

interface PanelCloseProviderProps {
  /** Callback that dismisses the enclosing drawer/modal. */
  close: () => void
}

ProgressProps

Props for Progress (React's ProgressProps, in Angular's form).

React.CSSProperties arrives as a plain style record, the same shape every component in this kit takes for its style input.

interface ProgressProps {
  /** Progress value (0–`max`). */
  value: number
  /** Maximum value. Defaults to 100. */
  max?: number
  /** Progress size. */
  size?: Size
  /** Progress color. */
  color?: ColorVariant
  /** Whether the numeric value label renders. */
  showValue?: boolean
  /** Accessible label. */
  label?: string
  /** Whether the progress is indeterminate. */
  indeterminate?: boolean
  /** Extra classes joined onto the wrapper classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
}

PromptDialogProps

Props for PromptDialog (React's PromptDialogProps, in Angular's form).

Node-valued members are string | number | TemplateRef<unknown> inputs; the title may also be projected as [slot=title]. onClose keeps React's name and signature and is carried by the component's close output.

interface PromptDialogProps {
  /** Whether the dialog is open. */
  open: boolean
  /** Called when the dialog should close (carried by the `close` output). */
  onClose: () => void
  /** Dialog heading. */
  title?: string | number | TemplateRef<unknown>
  /** Explanatory line under the title. */
  description?: string | number | TemplateRef<unknown>
  /** Input placeholder. */
  placeholder?: string
  /** Value the input starts from every time the dialog opens. */
  initialValue?: string
  /** Called with the entered value on confirm. */
  onSubmit: (value: string) => void | Promise<void>
  /** Confirm-button label. */
  confirmLabel?: string | number | TemplateRef<unknown>
  /** Cancel-button label. */
  cancelLabel?: string | number | TemplateRef<unknown>
  /** Renders the confirm button in the error color. */
  destructive?: boolean
  /** `data-mol-id` for the text input. */
  inputMolId?: string
  /** `data-mol-id` for the confirm button. */
  confirmMolId?: string
  /** `data-mol-id` for the cancel button. */
  cancelMolId?: string
}

RadioOption

One radio option.

interface RadioOption {
  /** The option's value. */
  value: string
  /** The option's label (text). */
  label?: unknown
  /** Whether this option is disabled. */
  disabled?: boolean
}

ShellContextValue

The shell context value (React's ShellContextValue).

interface ShellContextValue {
  /** Whether the desktop shell (sidebar) is mounted. */
  readonly isDesktop: boolean
  /** The resolved sidebar/drawer width in pixels. */
  readonly sidebarWidthPx: number
  /** Whether the mobile drawer is open. */
  readonly drawerOpen: boolean
  /** Opens the drawer. */
  openDrawer: () => void
  /** Closes the drawer. */
  closeDrawer: () => void
  /** The drawer panel's DOM id. */
  readonly drawerId: string
  /** Whether a `Drawer` sub-component is part of the composition. */
  readonly hasDrawer: boolean
  /**
   * Registers the drawer's presence.
   * @param present - Whether a drawer mounted.
   */
  registerDrawer: (present: boolean) => void
}

ResponsiveAppShellProps

Props for the ResponsiveAppShell root (React's ResponsiveAppShellProps, in Angular's form). The sub-components are projected content, so they have no member.

interface ResponsiveAppShellProps {
  /** Sidebar (and drawer) width: `sm`/`md`/`lg` or an exact pixel number. */
  sidebarWidth?: ShellSidebarWidth
  /** Extra classes on the root flex container. */
  className?: string
  /** `data-mol-id` for the root (default `shell-root`). */
  dataMolId?: string
}

ResponsiveAppShellTopBarProps

Props for ResponsiveAppShellTopBar (React's ResponsiveAppShellTopBarProps, in Angular's form).

interface ResponsiveAppShellTopBarProps {
  /** Brand/title node, rendered after the menu trigger. */
  brand?: string | number | TemplateRef<unknown>
  /** Trailing actions — user menu, theme toggle, search, etc. */
  actions?: string | number | TemplateRef<unknown>
  /** Render the top bar only below the breakpoint (no dead DOM on desktop). */
  mobileOnly?: boolean
  /** Extra classes on the `<header>`. */
  className?: string
  /** `data-mol-id` (default `shell-topbar`). */
  dataMolId?: string
  /** `data-testid`. */
  testId?: string
}

ResponsiveAppShellSidebarProps

Props for ResponsiveAppShellSidebar (React's ResponsiveAppShellSidebarProps, in Angular's form). The nav links are projected content, so they have no member.

interface ResponsiveAppShellSidebarProps {
  /** Accessible name for the sidebar's `<nav>` landmark. */
  navLabel?: string
  /** Below-nav content (user card, quick action), after the `<nav>`. */
  footer?: string | number | TemplateRef<unknown>
  /** Extra classes on the `<aside>`. */
  className?: string
  /** `data-mol-id` (default `shell-sidebar`). */
  dataMolId?: string
  /** `data-testid`. */
  testId?: string
}

ResponsiveAppShellDrawerProps

Props for ResponsiveAppShellDrawer (React's ResponsiveAppShellDrawerProps, in Angular's form). The nav links are projected content, so they have no member.

interface ResponsiveAppShellDrawerProps {
  /** Header row content (typically the brand), next to the close button. */
  header?: string | number | TemplateRef<unknown>
  /** Accessible name for the dialog and its `<nav>` landmark. */
  navLabel?: string
  /** Below-nav content (user card, sign-out), after the `<nav>`. */
  footer?: string | number | TemplateRef<unknown>
  /** Whether the panel shows a close (X) button (default true). */
  showCloseButton?: boolean
  /** Extra classes on the dialog panel. */
  className?: string
  /** `data-mol-id` for the panel (default `shell-drawer`). */
  dataMolId?: string
  /** `data-mol-id` for the close button (default `shell-drawer-close`). */
  closeDataMolId?: string
  /** `data-testid` for the panel. */
  testId?: string
}

ResponsiveAppShellContentProps

Props for ResponsiveAppShellContent (React's ResponsiveAppShellContentProps, in Angular's form). The routed page is projected content, so it has no member.

interface ResponsiveAppShellContentProps {
  /** Extra classes on the `<main>`. */
  className?: string
  /** Inline styles on the `<main>`. */
  style?: Record<string, unknown>
  /** `data-mol-id` (default `shell-content`). */
  dataMolId?: string
  /** `data-testid`. */
  testId?: string
}

SelectPropsOption

One select option (React's SelectOption).

interface SelectPropsOption {
  /** The option's value. */
  value: string
  /** The option's label. */
  label?: unknown
  /** Whether the option is disabled. */
  disabled?: boolean
  /** Group heading the option belongs to. */
  group?: string
}

SeparatorProps

Props for Separator (React's SeparatorProps, in Angular's form).

interface SeparatorProps {
  /** Orientation of the separator. Defaults to `horizontal`. */
  orientation?: 'horizontal' | 'vertical'
  /** Decorative separators are purely visual (default true). */
  decorative?: boolean
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
}

SidebarUserCardProps

Props for SidebarUserCard (React's SidebarUserCardProps, in Angular's form). The panel content is projected content, so it has no member; the trigger's extra <button> attributes land on the host.

interface SidebarUserCardProps {
  /** Display name override. */
  name?: string
  /** Secondary line under the name. */
  secondaryLine?: string
  /** Avatar image URL override. */
  avatarUrl?: string
  /** i18n key for the trigger's aria-label (default `sidebarUserCard.open`). */
  ariaLabelKey?: string
  /** Fallback aria-label if the i18n key is missing. */
  ariaLabelDefault?: string
  /** `data-mol-id` for the trigger (default `sidebar-user-card`). */
  dataMolId?: string
  /** Extra classes for the trigger. */
  className?: string
  /** `data-testid` for the trigger. */
  testId?: string
}

AngularTableColumn

A table column accepts either a cell template or the shared render callback.

interface AngularTableColumn extends Omit<TableColumn<Record<string, unknown>>, 'render'> {
  /** Renders the value, row and row index. */
  render?: TableColumn<Record<string, unknown>>['render'] | TemplateRef<unknown>
}

ThemeToggleProps

Props for ThemeToggle (React's ThemeToggleProps, in Angular's form). Extra <button> attributes (data-*, title, disabled, …) land on the host element, exactly React's spread target.

interface ThemeToggleProps {
  /** i18n key for the `aria-label` (default `theme.toggle`). */
  ariaLabelKey?: string
  /** Fallback `aria-label` if the i18n key is missing. */
  ariaLabelDefault?: string
  /** Icon name rendered in dark mode (default `moon`). */
  darkIcon?: IconName
  /** Icon name rendered in light mode (default `sun`). */
  lightIcon?: IconName
  /** Pixel size for the rendered icon (default 20). */
  iconSize?: number
  /** Extra classes joined onto the toggle classes. */
  className?: string
  /** `data-testid` for the button. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`; default `theme-toggle`). */
  automationId?: string
}

ToastContextValue

The toast context value (React's ToastContextValue).

interface ToastContextValue {
  /** The current toasts, each with its id. */
  toasts: (ToastProps & { id: string })[]
  /**
   * Adds a toast.
   * @param toast - The toast to add.
   * @returns Its id (the caller's when given).
   */
  addToast: (toast: Omit<ToastProps, 'onDismiss'>) => string
  /**
   * Removes a toast by id.
   * @param id - The toast's id.
   */
  removeToast: (id: string) => void
}

UserMenuPopoverContext

The popover context value (React's UserMenuPopoverContextValue).

interface UserMenuPopoverContext {
  /** Whether the popover is open. */
  readonly open: boolean
  /**
   * Sets the open state.
   * @param open - The new state.
   */
  setOpen: (open: boolean) => void
  /** The resolved display name. */
  readonly displayName: string
  /** The resolved account email. */
  readonly email: string | undefined
  /** The id linking the trigger's `aria-controls` to the panel. */
  readonly panelId: string
}

UserMenuPopoverProps

Props for UserMenuPopover (React's UserMenuPopoverProps, in Angular's form). The trigger and panel are projected content, so they have no member.

interface UserMenuPopoverProps {
  /** Label shown when there is no authenticated user (default `Account`). */
  guestName?: string
  /** Extra classes composed onto the relative-positioned container. */
  className?: string
}

UserMenuPopoverTriggerProps

Props for UserMenuPopoverTrigger (React's UserMenuPopoverTriggerProps, in Angular's form).

interface UserMenuPopoverTriggerProps {
  /** i18n key for the trigger's aria-label (default `userMenu.open`). */
  ariaLabelKey?: string
  /** Fallback aria-label (default `Open user menu`). */
  ariaLabelDefault?: string
  /** `data-mol-id` for the trigger (default `user-menu`). */
  dataMolId?: string
  /** Extra classes for the trigger. */
  className?: string
}

UserMenuPopoverPanelProps

Props for UserMenuPopoverPanel (React's UserMenuPopoverPanelProps, in Angular's form). The panel body is projected content, so it has no member.

interface UserMenuPopoverPanelProps {
  /** i18n key for the panel's aria-label (default `userMenu.panelLabel`). */
  ariaLabelKey?: string
  /** Fallback aria-label (default `Account menu`). */
  ariaLabelDefault?: string
  /** `data-mol-id` for the panel (default `user-menu-panel`). */
  dataMolId?: string
  /** Extra classes for the panel. */
  className?: string
}

UserMenuPopoverSignOutProps

Props for UserMenuPopoverSignOut (React's UserMenuPopoverSignOutProps, in Angular's form).

interface UserMenuPopoverSignOutProps {
  /** i18n key for the button label (default `userMenu.signOut`). */
  labelKey?: string
  /** Fallback label (default `Sign out`). */
  labelDefault?: string
  /** `data-mol-id` for the button (default `user-menu-sign-out`). */
  dataMolId?: string
  /** Extra classes for the button. */
  className?: string
}

UserMenuProps

Props for UserMenu (React's UserMenuProps, in Angular's form). The panel content is projected content, so it has no member.

interface UserMenuProps {
  /** i18n key for the trigger's aria-label (default `userMenu.open`). */
  ariaLabelKey?: string
  /** Fallback aria-label (default `Open user menu`). */
  ariaLabelDefault?: string
  /** Icon name for the trigger (default `user`). */
  triggerIcon?: IconName
  /** Pixel size for the trigger icon (default 20). */
  triggerIconSize?: number
  /** `data-mol-id` for the trigger (default `user-menu`). */
  dataMolId?: string
  /** Extra classes composed onto the trigger. */
  className?: string
  /** Whether the trigger is disabled. */
  disabled?: boolean
  /** Overrides the trigger click (called instead of opening the panel). */
  onClick?: (event: MouseEvent) => void
  /** Which side the panel opens from (default `right`). */
  side?: 'left' | 'right'
}

DomContext

One context: what React's createContext returns, in Angular's form.

interface DomContext<T> {
  /**
   * Registers the value on a provider's host element.
   *
   * @param host - The provider component's host element.
   * @param value - The context value.
   */
  provide(host: Element, value: T): void
  /**
   * Removes the registration (on provider destroy).
   *
   * @param host - The provider component's host element.
   */
  remove(host: Element): void
  /**
   * Finds the nearest enclosing value for a consumer's element. The element's
   * own registration is ignored: a provider's children see the provider, the
   * provider does not see itself.
   *
   * @param start - The consumer's host element.
   * @returns The nearest registered value, or `undefined` when there is none.
   */
  find(start: Element | null): T | undefined
}

HasElement

A component that gives callers its ref element.

Implemented by every component whose React export forwards a ref. The generic is the element React's forwardRef<E> names.

interface HasElement<E extends Element> {
  /** The ref element, or `null` while it is not rendered. */
  readonly element: Signal<E | null>
}

FormFieldContext

The values FormField injects into its single child field.

interface FormFieldContext {
  /** Stable id supplied to a control without an explicit id. */
  id?: string
  /** The id of the error/hint paragraph the field should describe itself with. */
  describedBy?: string
  /** Whether the field is invalid (`FormField` render an error). */
  invalid?: boolean
}

OptimisticValueOptions

Options for createOptimisticValue.

interface OptimisticValueOptions<T> {
  /** The loaded server value. */
  value: T
  /** Saves the desired value; resolve with the confirmed value. */
  commit: OptimisticCommit<T>
  /** Equality override (defaults to `shallowEqual`). */
  equals?: (a: T, b: T) => boolean
  /** Called with a failed save after rollback. */
  onError?: (error: unknown, value: T) => void
}

OptimisticValueState

The externally visible state.

interface OptimisticValueState<T> {
  /** The value to render. */
  value: T
  /** Whether a save is in flight. */
  pending: boolean
  /** The newest failure, when the newest save failed. */
  error: unknown
}

OptimisticValue

The controller.

interface OptimisticValue<T> {
  /**
   * Gets the current state.
   * @returns The state snapshot.
   */
  getState(): OptimisticValueState<T>
  /**
   * Sets the desired value (starts or queues a save).
   * @param next - The desired value.
   */
  set(next: T): void
  /**
   * Updates the desired value from the current desired one.
   * @param change - Maps current to next.
   */
  update(change: (current: T) => T): void
  /**
   * Syncs a newer server value.
   * @param value - The confirmed server value.
   */
  sync(value: T): void
  /**
   * Subscribes to state changes.
   * @param listener - Called on every publish.
   * @returns Unsubscribe.
   */
  subscribe(listener: (state: OptimisticValueState<T>) => void): () => void
  /**
   * Resolves when the current save settles.
   * @returns The settled state.
   */
  settled(): Promise<OptimisticValueState<T>>
}

ResolvedIcon

The icon data plus the resolved class name, precomputed so the template only binds (recomputing getIcon per CD pass would be wasteful and can throw mid-template).

interface ResolvedIcon {
  /** The bonded icon data. */
  icon: IconData
  /** Class for the `<svg>` (already joined, possibly empty). */
  className: string
  /** Whether the icon carries stroke styling. */
  stroked: boolean
  /** `0 0 20 20` fallback applied when the icon data has no viewBox. */
  viewBox: string
}

ReapplyRestAttributesOptions

Options for reapplyRestAttributes.

interface ReapplyRestAttributesOptions {
  /**
   * Move `aria-describedby` too. The default keeps it on the host: a
   * component that MERGES the host's `aria-describedby` with its own target
   * (the input/select/textarea family, see below) has already applied it on
   * an inner binding, and re-moving the re-bound value would erase that
   * merge. A component that spreads `aria-describedby` straight onto its
   * `...rest` target has no merge to protect, so it opts in.
   */
  includeDescribedBy?: boolean
  /** The field's validation binding owns aria-invalid on the control. */
  keepInvalid?: boolean
}

Types

Children

Framework-agnostic child content. Use unknown to allow any framework's node type (ReactNode, VNode, etc.).

type Children = unknown

EventHandler

Framework-agnostic event handler. An unannotated handler's event is E. It is declared as a method (as React types its own handlers), so TypeScript compares its parameter both ways: a handler written for the event a kit passes, such as (event: Event) => void on the Vue, Solid, Svelte and Angular kits or (event: React.ChangeEvent<HTMLInputElement>) => void on React's, is accepted too.

type EventHandler<E extends KitEvent = KitEvent> = {
  handle(event: E): void
}['handle']
  • event — The event, as the kit hands it (see KitEvent).

MouseEventHandler

Framework-agnostic mouse event handler.

type MouseEventHandler = EventHandler<KitMouseEvent>

KeyboardEventHandler

Framework-agnostic keyboard event handler.

type KeyboardEventHandler = EventHandler<KitKeyboardEvent>

FocusEventHandler

Framework-agnostic focus event handler.

type FocusEventHandler = EventHandler<KitFocusEvent>

ChangeEventHandler

Framework-agnostic change event handler.

type ChangeEventHandler = EventHandler<KitEvent>

FormEventHandler

Framework-agnostic form event handler.

type FormEventHandler = EventHandler<KitEvent>

Size

Standard size scale used across all molecule UI components (buttons, inputs, badges, etc.).

type Size = 'xs' | 'sm' | 'md' | 'lg' | 'xl'

ColorVariant

Semantic color variants used across components for status indication.

type ColorVariant = 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info'

ButtonVariant

Button visual variant styles.

type ButtonVariant = 'solid' | 'outline' | 'ghost' | 'link'

InputType

Allowed HTML input type attribute values for the Input component.

type InputType =
  | 'text'
  | 'email'
  | 'password'
  | 'number'
  | 'tel'
  | 'url'
  | 'search'
  | 'date'
  | 'time'
  | 'datetime-local'

ModalSize

Modal size variants including full-screen.

type ModalSize = 'sm' | 'md' | 'lg' | 'xl' | 'full'

TooltipPlacement

Position where a tooltip renders relative to its trigger element (top, bottom, left, right, and corner variants).

type TooltipPlacement =
  'top' | 'bottom' | 'left' | 'right' | 'top-start' | 'top-end' | 'bottom-start' | 'bottom-end'

ShellSidebarWidth

Semantic sidebar width — the same stack-agnostic presets React's ShellSidebarWidth uses: sm → 208px, md → 240px (default), lg → 256px. A raw number is an exact pixel width.

type ShellSidebarWidth = 'sm' | 'md' | 'lg' | number

OptimisticCommit

What a commit reports back.

type OptimisticCommit<T> = (
  next: T,
  previous: T,
  confirm: (change: (current: T) => T) => void,
) => Promise<T | void>

Classes

Accordion

Accordion component.

The host is the div.accordionRoot React renders. Items carry their header/content as text or TemplateRef node values; expansion state is internal unless the value input controls it (React's controlled / uncontrolled pair). Each item's trigger and content ids carry the instance's own prefix, so two accordions on one page never share an id (React's useId is unique per item of every instance), and are minted once per item value, so replacing the items array keeps them.

@Component({
  selector: 'div[mol-accordion]',
  standalone: true,
  imports: [MolIconSvg, NgTemplateOutlet],
  inputs: [
    'items',
    'value',
    'defaultValue',
    'multiple',
    'collapsible',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'disabled',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `@for (item of items ?? []; track item.value) {
    <div [class]="cm().accordionItem" [attr.data-state]="isOpen(item.value) ? 'open' : 'closed'">
      <button
        type="button"
        [attr.id]="ids(item.value).trigger"
        [class]="cm().cn(cm().accordion({ variant: 'default' }), cm().accordionTriggerBase)"
        (click)="toggle(item.value)"
        [attr.aria-expanded]="isOpen(item.value) ? 'true' : 'false'"
        [attr.aria-controls]="ids(item.value).content"
        [attr.data-state]="isOpen(item.value) ? 'open' : 'closed'"
        [disabled]="item.disabled || disabled"
      >
        @if (asTemplate(item.header); as tpl) {
          <ng-container [ngTemplateOutlet]="tpl" />
        } @else {
          {{ nodeText(item.header) }}
        }
        <svg mol-icon [data]="chevron()" />
      </button>
      <div
        [attr.id]="ids(item.value).content"
        role="region"
        [attr.aria-labelledby]="ids(item.value).trigger"
        [attr.data-state]="isOpen(item.value) ? 'open' : 'closed'"
        [class]="cm().accordionContent"
        [style.display]="isOpen(item.value) ? 'block' : 'none'"
      >
        <div [class]="cm().accordionContentInner">
          @if (asTemplate(item.content); as tpl) {
            <ng-container [ngTemplateOutlet]="tpl" />
          } @else {
            {{ nodeText(item.content) }}
          }
        </div>
      </div>
    </div>
  }`,
})
export class Accordion implements HasElement<HTMLDivElement> {
  /** The items to render. */
  items?: AccordionItemData[]
  /** Controlled expanded value(s). */
  value?: string | string[]
  /** Uncontrolled initial expanded value(s). */
  defaultValue?: string | string[]
  /** Whether several items may stay expanded. */
  multiple?: boolean
  /** Whether the last expanded item may collapse. */
  collapsible?: boolean
  /** Extra classes joined onto the root classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the root. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string
  /** Disables every header, whatever an item says (React's `disabled`). */
  disabled?: boolean

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string node value. */
  readonly nodeText = nodeText

  /** Fires the new expansion state (single value, or array in multiple mode). */
  @Output() readonly change = new EventEmitter<string | string[]>()

  private internalExpanded: string[] | null = null
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)
  /**
   * The prefix of every id this instance renders. It is this instance's own, from the kit's
   * per-instance counter, where React's `useId` is unique per item of every instance.
   */
  private readonly idBase = nextInstanceId()
  /** Each item value's ids, minted on first render; a value never goes into an id itself. */
  private readonly idMap = new Map<string, { trigger: string; content: string }>()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the root class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().accordionRoot, this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The chevron glyph every trigger renders.
   * @returns The resolved icon.
   */
  chevron(): ResolvedIcon {
    return resolveIcon('chevron-down', this.cm().accordionChevron)
  }

  /**
   * Normalizes a value prop to the expanded list (React's `normalizeValue`).
   *
   * @param v - The single value, array, or undefined.
   * @returns The expanded values.
   */
  private normalize(v: string | string[] | undefined): string[] {
    if (v === undefined) return []
    return Array.isArray(v) ? v : [v]
  }

  /**
   * The expanded items: the controlled `value` when given, else the internal
   * state (seeded from `defaultValue` at first use).
   * @returns The expanded values.
   */
  expandedItems(): string[] {
    if (this.value !== undefined) return this.normalize(this.value)
    if (this.internalExpanded === null) this.internalExpanded = this.normalize(this.defaultValue)
    return this.internalExpanded
  }

  /**
   * Whether one item is expanded.
   *
   * @param value - The item value.
   * @returns True when expanded.
   */
  isOpen(value: string): boolean {
    return this.expandedItems().includes(value)
  }

  /**
   * The ids of one item's trigger and its content region. Both carry this instance's prefix, so
   * every `aria-controls` and `aria-labelledby` resolves inside its own accordion, and each
   * value keeps the ids it was first given, so replacing the `items` array keeps them. The value
   * itself stays out of the id: one with a space would split the `aria-controls` reference.
   *
   * @param value - The item value.
   * @returns The trigger and content ids.
   */
  ids(value: string): { trigger: string; content: string } {
    let ids = this.idMap.get(value)
    if (!ids) {
      const n = this.idMap.size
      ids = { trigger: `${this.idBase}-t${n}`, content: `${this.idBase}-c${n}` }
      this.idMap.set(value, ids)
    }
    return ids
  }

  /**
   * React's `toggleItem`: collapse guards `collapsible`, expand replaces or
   * appends per `multiple`, internal state updates only when uncontrolled,
   * and `onChange` receives the new state (single value or array).
   *
   * @param itemValue - The toggled item's value.
   */
  toggle(itemValue: string): void {
    const current = this.expandedItems()
    let next: string[]
    if (current.includes(itemValue)) {
      if (this.collapsible === false && current.length === 1) return
      next = current.filter((v) => v !== itemValue)
    } else {
      next = this.multiple ? [...current, itemValue] : [itemValue]
    }
    if (this.value === undefined) this.internalExpanded = next
    if (this.multiple) this.change.emit(next)
    else this.change.emit(next[0] ?? '')
  }
}

Alert

Alert component.

role follows live (assertive alert by default, polite status for a banner that is part of the page's normal content).

React renders {(icon || defaultIcon) && <span className={alertIconWrapper}>…}: the icon wrapper span exists only when a custom icon is given or the status has a default glyph, and its content is the custom icon XOR the default glyph. Here the span and the default glyph both always exist in the template (projection capture points) and are taken out of the DOM when React would not render them (setElementPresent); the decision is made in the placement function, where projected content is current.

@Component({
  selector: 'div[mol-alert]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg],
  inputs: [
    'title',
    'status',
    'variant',
    'live',
    'dismissible',
    'dismissLabel',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  outputs: ['dismiss'],
  host: {
    // `title` is this component's heading, which React renders as text; Angular would also keep a
    // static `title="…"` on the host, where the browser shows it as a tooltip.
    '[attr.title]': 'null',
    '[attr.role]': 'live ? "alert" : "status"',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<span [class]="cm().alertIconWrapper" #iconSlot>
      <svg mol-icon [data]="resolvedDefaultIcon()" #defaultGlyph />
      <ng-content select="[slot=icon]"></ng-content>
    </span>
    <div [class]="cm().alertContent">
      @if (title) {
        <h5 [class]="cm().alertTitle">{{ title }}</h5>
      }
      <div [class]="cm().alertDescription"><ng-content></ng-content></div>
    </div>
    @if (dismissible) {
      <button
        type="button"
        [class]="cm().alertDismiss"
        [attr.aria-label]="dismissText()"
        (click)="dismiss.emit($event)"
      >
        <svg mol-icon [data]="closeIcon()" />
      </button>
    }`,
})
export class Alert implements HasElement<HTMLDivElement> {
  /** Alert title. */
  title?: string
  /** Status color. */
  status: ColorVariant = 'info'
  /** Visual variant. */
  variant?: 'solid' | 'subtle' | 'outline' | 'left-accent'
  /** Whether the alert announces assertively (default true). */
  live = true
  /** Whether a dismiss button renders. */
  dismissible?: boolean
  /** Accessible label for the dismiss button. */
  dismissLabel?: string
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** Fires the raw click event when the dismiss button is pressed. */
  @Output() readonly dismiss = new EventEmitter<MouseEvent>()

  /** The icon wrapper span (projection capture point). */
  @ViewChild('iconSlot') iconSlot?: ElementRef<HTMLSpanElement>
  /** The default status glyph (detached when a custom icon is projected). */
  @ViewChild('defaultGlyph', { read: ElementRef }) defaultGlyph?: ElementRef<SVGSVGElement>

  private hasCustomIcon = false

  /** Places the icon wrapper and the default glyph as React renders them. */
  constructor() {
    usePlacement((hasContent) => this.syncIcon(hasContent))
  }

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The class-map variant for the status.
   * @returns The mapped variant.
   */
  get alertVariant(): 'default' | 'info' | 'success' | 'warning' | 'error' {
    return STATUS_VARIANT[this.status] || 'default'
  }

  /**
   * The default status glyph (none for the `default` variant, matching
   * React's `statusIconMap` gap).
   * @returns The resolved icon, or null when the variant has no glyph.
   */
  defaultIcon(): ResolvedIcon | null {
    const name = STATUS_ICON[this.alertVariant]
    return name ? resolveIcon(name, this.cm().iconMd) : null
  }

  /**
   * A non-null glyph to bind (an empty resolved icon when the variant has
   * none; that svg is detached from the DOM anyway).
   * @returns The resolved icon data.
   */
  resolvedDefaultIcon(): ResolvedIcon {
    return (
      this.defaultIcon() ?? {
        icon: { paths: [] },
        className: '',
        stroked: false,
        viewBox: '0 0 20 20',
      }
    )
  }

  /**
   * The dismiss button's X glyph.
   * @returns The resolved icon.
   */
  closeIcon(): ResolvedIcon {
    return resolveIcon('x-mark', this.cm().iconSm)
  }

  /**
   * The dismiss button's accessible label.
   * @returns The label text.
   */
  dismissText(): string {
    return (
      this.dismissLabel ?? this.i18n.t('ui.alert.dismiss', undefined, { defaultValue: 'Dismiss' })
    )
  }

  /**
   * Computes the alert class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().alert({ variant: this.alertVariant }),
      this.variant === 'left-accent' && this.cm().alertLeftAccent({ variant: this.alertVariant }),
      this.className,
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Applies React's `{(icon || defaultIcon) && <span>{icon || defaultIcon}</span>}`.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncIcon(hasContent: SlotReader): void {
    const span = this.iconSlot?.nativeElement
    const glyph = this.defaultGlyph?.nativeElement
    // The capture holds the always-mounted default glyph first, then the slot.
    this.hasCustomIcon = hasContent(span, 1)
    setElementPresent(glyph, !this.hasCustomIcon && this.defaultIcon() !== null)
    setElementPresent(span, this.hasCustomIcon || this.defaultIcon() !== null)
  }
}

AuthGuard

Route-element guard for authenticated sections of a routing tree.

While the auth status is 'loading' it renders the loadingFallback input (or its [slot=loadingFallback] projection, or the default data-mol-id="auth-guard-loading" tag); while 'unauthenticated' off the login path it renders nothing and redirects to loginPath (state from carries the attempted location); otherwise it renders the projected children, or <mol-routed-view /> without them (the matched child route, through whichever routing bond the app wired; it throws when the bond has none: project the page then). React's root is a fragment (or nothing at all while redirecting), so everything the host holds renders in front of the host and the host itself leaves the page. On the login path itself the guard renders its children, so a guard wrapping the whole route tree does not redirect in a loop.

The projected children (and the loading fallback's content) need one stable capture point, so each lives in an always-mounted wrapper whose content is rendered in its own place and whose element leaves the page: React renders them bare, never inside a wrapper element.

@Component({
  selector: 'mol-auth-guard',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolTemplateOutlet, RoutedView],
  inputs: ['loadingFallback', 'loadingKey', 'loadingDefault', 'loginPath', 'onAuthenticated'],
  template: `<div data-mol-id="auth-guard-loading" #defaultLoading>{{ loadingText() }}</div>
    <span #dataFallback
      ><ng-container [molTemplateOutlet]="asTemplate(loadingFallback)"></ng-container
      >{{ nodeText(loadingFallback) }}</span
    >
    <span #fallbackWrap><ng-content select="[slot=loadingFallback]"></ng-content></span>
    <span #childrenWrap><ng-content></ng-content></span>
    @if (routed()) {
      <mol-routed-view />
    }`,
})
export class AuthGuard {
  /**
   * Element rendered while the auth status is `loading` (a node value, or the
   * projected `[slot=loadingFallback]`). Overrides the default loading tag.
   */
  loadingFallback?: AuthGuardProps['loadingFallback']
  /**
   * i18n key for the default loading-tag text (default `common.loading`).
   * Ignored when a `loadingFallback` is given.
   */
  loadingKey?: AuthGuardProps['loadingKey']
  /** Fallback text if the i18n key is missing (default `Loading...`). */
  loadingDefault?: AuthGuardProps['loadingDefault']
  /** Path to redirect to when unauthenticated (default `/login`). */
  loginPath?: AuthGuardProps['loginPath']
  /** Fired when `isAuthenticated` becomes true (also when true at mount). */
  onAuthenticated?: AuthGuardProps['onAuthenticated']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText

  /** The default loading tag. */
  @ViewChild('defaultLoading') defaultLoading?: ElementRef<HTMLDivElement>
  /** The node-valued fallback (shown when the input is given). */
  @ViewChild('dataFallback') dataFallback?: ElementRef<HTMLSpanElement>
  /** The `loadingFallback` slot capture (its content renders in its own place). */
  @ViewChild('fallbackWrap') fallbackWrap?: ElementRef<HTMLSpanElement>
  /** The children capture (their content renders in its own place). */
  @ViewChild('childrenWrap') childrenWrap?: ElementRef<HTMLSpanElement>

  /** Auth state, read in the component's injection context. */
  readonly auth = useAuth()
  /** Router state and actions, read in the component's injection context. */
  readonly router = useRouter()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host = inject(ElementRef)
  private hasFallback = false
  /** Whether the guard was given children to project (read in the placement function). */
  private hasChildren = false
  /** Whether the view queries have resolved, so the children capture can be read. */
  private viewReady = false
  /**
   * Whether the routed view renders: the children branch with no projected children. A signal
   * the template reads, so the routed view is created only then (it throws without one).
   */
  readonly routed = signal(false)
  private lastAuthenticated = false
  /** The login path the guard navigated to for the current redirect state. */
  private redirectedTo: string | null = null

  /**
   * Re-evaluates the guard whenever the auth status, the location or the
   * projected slots change. The placement function reads both signals, so its
   * effect tracks them even though no template binding does.
   */
  constructor() {
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  /**
   * Applies React's branch for the current auth status and location, fires
   * `onAuthenticated` on its rising edge, and redirects once per entry into
   * the redirect state.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private reconcile(hasContent: SlotReader): void {
    this.hasFallback = hasContent(this.fallbackWrap?.nativeElement)
    this.hasChildren = hasContent(this.childrenWrap?.nativeElement)
    this.viewReady = this.childrenWrap !== undefined
    const status = this.auth.status()
    const authenticated = this.auth.isAuthenticated()
    if (this.onAuthenticated && authenticated && !this.lastAuthenticated) this.onAuthenticated()
    this.lastAuthenticated = authenticated

    const pathname = this.router.location().pathname
    const target = this.loginPath ?? '/login'
    const redirecting = status === 'unauthenticated' && pathname !== loginPathname(target)
    if (redirecting) {
      if (this.redirectedTo !== target) {
        this.redirectedTo = target
        this.router.navigate(target, {
          replace: true,
          state: { from: { ...this.router.location() } },
        })
      }
    } else {
      this.redirectedTo = null
    }

    const branch = status === 'loading' ? 'loading' : redirecting ? 'redirect' : 'children'
    this.renderBranch(branch)
  }

  /**
   * Shows exactly one branch's content, the way React's early returns do.
   *
   * React's branch elements render in front of the host, which leaves the
   * page; each capture that holds projected content renders that content in its
   * own place and leaves the page, so the projected nodes are bare, as React
   * renders them.
   *
   * @param branch - The branch to render.
   */
  private renderBranch(branch: 'loading' | 'redirect' | 'children'): void {
    const host = this.host.nativeElement as HTMLElement
    // React's root is a fragment (or nothing): everything the host holds renders in front of it.
    placeContentBefore(host, host)
    setElementPresent(host, false)
    this.routed.set(this.viewReady && branch === 'children' && !this.hasChildren)
    const loading = branch === 'loading'
    const hasNode = isGiven(this.loadingFallback)
    this.placeSlot(this.childrenWrap?.nativeElement, branch === 'children')
    this.placeSlot(this.fallbackWrap?.nativeElement, loading && !hasNode && this.hasFallback)
    this.placeSlot(this.dataFallback?.nativeElement, loading && hasNode)
    setElementPresent(this.defaultLoading?.nativeElement, loading && !hasNode && !this.hasFallback)
  }

  /**
   * Renders a capture's content in the capture's own place while `shown`, and
   * leaves the capture element itself out of the page either way: React
   * renders the content bare, never inside the capture's span.
   *
   * @param capture - The capture element (its own template content, projected or not).
   * @param shown - Whether React would render that content now.
   */
  private placeSlot(capture: HTMLElement | undefined, shown: boolean): void {
    if (!capture) return
    if (shown) placeContentBefore(capture, capture)
    else placeContent(capture, null)
    setElementPresent(capture, false)
  }

  /**
   * The localized default loading text.
   * @returns The translated text.
   */
  loadingText(): string {
    return this.i18n.t(
      this.loadingKey ?? 'common.loading',
      {},
      {
        defaultValue: this.loadingDefault ?? 'Loading...',
      },
    )
  }
}

Avatar

Avatar component.

Renders the image while it loads; an image error (or no src) swaps to the fallback: projected [slot=fallback] content, the name's initials, or a user glyph. The image/fallback swap is a signal-driven @if (an error re-renders); the three fallback variants are always-mounted capture points taken out of the DOM per React's ternary, since projected-content presence is read in the placement function (setElementPresent).

@Component({
  selector: 'div[mol-avatar]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg],
  inputs: [
    'src',
    'alt',
    'name',
    'size',
    'rounded',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `@if (!showFallback()) {
      <img
        [src]="src"
        [attr.alt]="altText()"
        [class]="cm().avatarImage"
        (error)="imageError.set(true)"
      />
    } @else {
      <div [class]="cm().avatarFallback" #fallbackEl>
        <span [class]="cm().avatarInitials" #initialsEl>{{ initials() }}</span>
        <svg mol-icon [data]="userIcon()" #userGlyph />
        <ng-content select="[slot=fallback]"></ng-content>
      </div>
    }`,
})
export class Avatar implements HasElement<HTMLDivElement> {
  /** Image source. */
  src?: string
  /** Image alt text. */
  alt?: string
  /** Display name (drives the initials fallback and default alt). */
  name?: string
  /** Avatar size preset or an exact pixel size. */
  size: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | number = 'md'
  /** Whether the avatar is fully rounded (default true). */
  rounded = true
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** Set when the image fails to load. */
  readonly imageError = signal(false)

  /** The fallback container (React renders it only on the fallback branch). */
  @ViewChild('fallbackEl') fallbackEl?: ElementRef<HTMLDivElement>
  /** The initials span (detached unless the fallback branch picks it). */
  @ViewChild('initialsEl') initialsEl?: ElementRef<HTMLSpanElement>
  /** The user glyph (detached unless the fallback branch picks it). */
  @ViewChild('userGlyph', { read: ElementRef }) userGlyph?: ElementRef<SVGSVGElement>

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Applies the fallback ternary; projected content wins over initials and glyph. */
  constructor() {
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Whether the fallback branch renders.
   * @returns True without a src or after an image error.
   */
  showFallback(): boolean {
    return !this.src || this.imageError()
  }

  /**
   * The image alt text (name or the localized default).
   * @returns The alt text.
   */
  altText(): string {
    return (
      this.alt || this.name || this.i18n.t('ui.avatar.alt', undefined, { defaultValue: 'Avatar' })
    )
  }

  /**
   * The initials for the given name.
   * @returns Up to two uppercase characters.
   */
  initials(): string {
    return getInitials(this.name)
  }

  /**
   * The fallback user glyph.
   * @returns The resolved icon.
   */
  userIcon(): ResolvedIcon {
    return resolveIcon('user', this.cm().avatarFallbackIcon)
  }

  /**
   * Computes the avatar class list.
   * @returns The class string.
   */
  classes(): string {
    const avatarSize = typeof this.size === 'number' ? undefined : this.size
    return this.cm().cn(
      this.cm().avatar({ size: avatarSize }),
      !this.rounded && this.cm().avatarSquare,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style (an exact pixel size inline).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const customSize =
      typeof this.size === 'number' ? { width: this.size, height: this.size } : undefined
    return styleText({ ...this.style, ...customSize })
  }

  /**
   * Applies React's fallback ternary (`fallback ? fallback : name ? initials
   * : glyph`). The capture holds the initials span and the user glyph first,
   * then the projected fallback.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private reconcile(hasContent: SlotReader): void {
    const fallbackHost = this.fallbackEl?.nativeElement
    if (!fallbackHost) return
    const projected = hasContent(fallbackHost, 2)
    setElementPresent(this.initialsEl?.nativeElement, !projected && !!this.name)
    setElementPresent(this.userGlyph?.nativeElement, !projected && !this.name)
  }
}

Badge

Badge component.

The host element is the <span> React renders (span[mol-badge]); the color variant maps to badge({ variant }) exactly as React's Badge.

@Component({
  selector: 'span[mol-badge]',
  standalone: true,
  inputs: [
    'color',
    'variant',
    'size',
    'rounded',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<ng-content></ng-content>`,
})
export class Badge implements HasElement<HTMLSpanElement> {
  private readonly host: ElementRef<HTMLSpanElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<span>`. */
  readonly element = hostElement(this.host)

  /** Named color variant (`primary`, `success`, …). */
  color: ColorVariant = 'primary'
  /** Visual style (kept for React prop parity; the class map keys off `color`). */
  variant: 'solid' | 'outline' | 'subtle' = 'solid'
  /** Badge size. */
  size?: Size
  /** Whether the badge is fully rounded (default) or square. */
  rounded = true
  /** Extra classes joined onto the badge classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the badge. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the badge class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().badge({ variant: this.color, size: this.size }),
      !this.rounded && this.cm().badgeSquare,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }
}

SlotWrapper (deprecated)

Deprecated: Use setElementPresent from @molecule/app-angular.

Attaches or detaches an always-mounted projection wrapper element from its parent. React renders {cond && <span>{slot}</span>} — nothing when the condition is false. Angular needs the <ng-content> capture point to stay mounted, so the wrapper span always exists in the template and this helper removes it from the DOM whenever React would not render it.

It is a thin delegate to setElementPresent, kept for callers' signatures.

class SlotWrapper {
  /**
   * Creates the wrapper helper.
   *
   * @param _host - Kept for callers' constructor signature.
   * @param _renderer - Kept for callers' constructor signature.
   */
  constructor(_host: ElementRef<HTMLElement>, _renderer: Renderer2) {}

  /**
   * Attaches or detaches the element.
   *
   * @param el - The wrapper element.
   * @param shouldAttach - Whether it should be in the DOM.
   * @param _parent - Ignored; the element's own place holds it.
   */
  sync(el: Element | undefined | null, shouldAttach: boolean, _parent?: Node): void {
    setElementPresent(el, shouldAttach)
  }
}

Button

Button component.

While loading is true, the native button is disabled and marked busy. The host element is the <button> itself (button[mol-button]), matching React's root exactly. Icon slots are projected as [slot=leftIcon] / [slot=rightIcon]; each wrapping <span> renders only while the slot carries nodes AND the button is not loading — React's {!loading && !!leftIcon && <span>…} — implemented by detaching the wrapper from the DOM (the projected nodes must have an always-mounted capture point, so the wrapper lives in the template unconditionally).

@Component({
  selector: 'button[mol-button]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Spinner],
  inputs: [
    'variant',
    'color',
    'size',
    'loading',
    'loadingText',
    'fullWidth',
    'className',
    'style',
    'testId',
    'disabled',
    'type',
    'ariaBusy: aria-busy',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.type]': 'type ?? "button"',
    '[disabled]': 'disabled || loading',
    '[attr.aria-busy]': 'ariaBusyAttr()',
  },
  template: `@if (loading) {
      <div mol-spinner [size]="'sm'" [className]="cm().buttonIconLeft"></div>
    }
    <span [class]="cm().buttonIconLeft" #leftSlot
      ><ng-content select="[slot=leftIcon]"></ng-content
    ></span>
    @if (loading && loadingText) {
      <ng-container>{{ loadingText }}</ng-container>
    } @else {
      <ng-content></ng-content>
    }
    <span [class]="cm().buttonIconRight" #rightSlot
      ><ng-content select="[slot=rightIcon]"></ng-content
    ></span>`,
})
export class Button implements HasElement<HTMLButtonElement> {
  /** Button variant. */
  variant: ButtonVariant = 'solid'
  /** Button color. */
  color: ColorVariant = 'primary'
  /** Button size. */
  size: Size = 'md'
  /** Whether the button is in its loading (busy) state. */
  loading = false
  /** Text shown instead of children while loading. */
  loadingText?: string
  /** Whether the button stretches to fill its container. */
  fullWidth = false
  /** Extra classes joined onto the button classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the button. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /**
   * A `data-mol-id` passed as a plain rest attribute (React spreads it onto
   * the root); `automationId` wins when both are given.
   */
  dataMolId?: string
  /** Disables the button. */
  disabled = false
  /** The button's `type` attribute. */
  type: 'button' | 'submit' | 'reset' = 'button'
  /** Explicit `aria-busy` (`loading` stays busy even when this is false). */
  ariaBusy?: AriaBoolean

  /** The left icon wrapper (always in the template; detached when unused). */
  @ViewChild('leftSlot') leftSlot?: ElementRef<HTMLSpanElement>
  /** The right icon wrapper. */
  @ViewChild('rightSlot') rightSlot?: ElementRef<HTMLSpanElement>

  private readonly host: ElementRef<HTMLButtonElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<button>`. */
  readonly element = hostElement(this.host)

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The `data-mol-id` value: `automationId` when given, else a caller's own
   * `data-mol-id` (the `dataMolId` prop or a `[attr.data-mol-id]` binding on
   * the element), matching React's `rootProps` precedence.
   * @returns The attribute value, or undefined.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * The `aria-busy` attribute value (`loading` stays busy even when an explicit
   * `aria-busy` is false; an explicit truthy `aria-busy` applies otherwise).
   * @returns `"true"` or `"false"`.
   */
  ariaBusyAttr(): 'true' | 'false' {
    return this.loading || this.ariaBusy === true || this.ariaBusy === 'true' ? 'true' : 'false'
  }

  /**
   * Computes the button class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().button({
        variant: this.variant,
        color: this.color,
        size: this.size,
        fullWidth: this.fullWidth,
      }),
      this.className,
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  private hasLeft = false
  private hasRight = false

  /** Detaches the icon wrappers React would not render. */
  constructor() {
    usePlacement((hasContent) => this.syncWrappers(hasContent))
  }

  /**
   * Applies React's `{!loading && !!icon}` wrapper conditions.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncWrappers(hasContent: SlotReader): void {
    const left = this.leftSlot?.nativeElement
    const right = this.rightSlot?.nativeElement
    this.hasLeft = left ? hasContent(left) : false
    this.hasRight = right ? hasContent(right) : false
    setElementPresent(left, this.hasLeft && !this.loading)
    setElementPresent(right, this.hasRight && !this.loading)
  }
}

Card

Card component.

An interactive card renders role="button" and joins the keyboard tab order; rest props (id, title, aria-*, data-*) and event bindings ((focusin), (dblclick), (keydown), …) land on the host, and a caller's (keydown) runs before the Enter/Space activation.

@Component({
  selector: 'div[mol-card]',
  standalone: true,
  inputs: [
    'variant',
    'interactive',
    'padding',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'disabled',
    'onClick',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.role]': 'interactive ? "button" : null',
    '[attr.tabindex]': 'interactive ? (disabled ? -1 : 0) : null',
    '[attr.aria-disabled]': 'interactive && disabled ? "true" : null',
    '(click)': 'handleClick($event)',
  },
  template: `<ng-content></ng-content>`,
})
export class Card implements OnInit, HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)
  private readonly renderer = inject(Renderer2)
  private readonly destroyRef = inject(DestroyRef)

  /** Card variant. */
  variant: 'default' | 'elevated' | 'outlined' | 'filled' | 'ghost' = 'elevated'
  /** Whether the card is keyboard-interactive. */
  interactive?: boolean
  /** Padding preset (`none` for no padding class). */
  padding: 'none' | 'sm' | 'md' | 'lg' = 'md'
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string
  /** A disabled card never calls `onClick` (React's `disabled`). */
  disabled?: boolean
  /** React's `onClick` prop: the card's click handler (never called while disabled). */
  onClick?: MouseEventHandler

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the card class list.
   * @returns The class string.
   */
  classes(): string {
    const paddingClass = this.padding === 'none' ? '' : this.cm().cardPadding(this.padding)
    return this.cm().cn(
      this.cm().card({ variant: VARIANT_MAP[this.variant] || 'default' }),
      paddingClass,
      this.interactive && this.cm().cardInteractive,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * Attaches the keyboard activation. A host listener would run before the
   * `(keydown)` a caller binds on the card (Angular registers a component's
   * host listeners first); attached here, after the template's bindings, the
   * caller's handler runs first and its preventDefault() cancels the
   * activation, as React's Card calls `onKeyDown` before activating.
   */
  ngOnInit(): void {
    const unlisten = this.renderer.listen(
      this.host.nativeElement,
      'keydown',
      (event: KeyboardEvent) => this.handleKeyDown(event),
    )
    this.destroyRef.onDestroy(unlisten)
  }

  /**
   * An interactive card is announced as a button and sits in the tab order, so
   * Enter and Space activate it the way they activate a native button: by
   * clicking it, which runs the consumer's click handler with a real click
   * event. Keys pressed in a control inside the card belong to that control,
   * and a card that is not interactive ignores keys.
   *
   * @param event - The key event.
   */
  handleKeyDown(event: KeyboardEvent): void {
    if (event.defaultPrevented || !this.interactive || this.disabled) return
    // The element the listener is bound to (the host, whether the binding is
    // the component's own or a caller's); `this.host` is the fallback when the
    // handler is invoked outside a dispatch.
    const target =
      event.currentTarget instanceof HTMLElement ? event.currentTarget : this.host.nativeElement
    if (event.target !== target) return
    if (event.key !== 'Enter' && event.key !== ' ') return
    event.preventDefault()
    target.click()
  }

  /**
   * React passes no `onClick` to a disabled card, so the consumer's handler
   * never runs; an enabled card's handler is called with the click event.
   *
   * @param event - The click event.
   */
  handleClick(event: MouseEvent): void {
    if (this.disabled) return
    this.onClick?.(event)
  }
}

CardHeader

Card header.

@Component({
  selector: 'div[mol-card-header]',
  standalone: true,
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class CardHeader implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().cardHeader, this.className)
  }
}

CardTitle

Card title (an h3).

@Component({
  selector: 'h3[mol-card-title]',
  standalone: true,
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class CardTitle implements HasElement<HTMLHeadingElement> {
  private readonly host: ElementRef<HTMLHeadingElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<h3>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().cardTitle, this.className)
  }
}

CardDescription

Card description (a p).

@Component({
  selector: 'p[mol-card-description]',
  standalone: true,
  hostDirectives: [{ directive: ElementLanguage, inputs: ['lang'] }],
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class CardDescription implements HasElement<HTMLParagraphElement> {
  private readonly host: ElementRef<HTMLParagraphElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<p>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().cardDescription, this.className)
  }
}

CardContent

Card content.

@Component({
  selector: 'div[mol-card-content]',
  standalone: true,
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class CardContent implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().cardContent, this.className)
  }
}

CardFooter

Card footer.

@Component({
  selector: 'div[mol-card-footer]',
  standalone: true,
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class CardFooter implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().cardFooter, this.className)
  }
}

Checkbox

Checkbox component.

The host is the div.formFieldWrapper React renders. The error message is programmatically associated with the input through aria-describedby; the input is React's ...rest spread target, so rest attributes move there at view init.

@Component({
  selector: 'div[mol-checkbox]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolControlledChecked],
  inputs: [
    'label',
    'checked',
    'indeterminate',
    'size',
    'error',
    'className',
    'style',
    'testId',
    'disabled',
    'name',
    'id',
    'defaultChecked',
    'automationId',
    'dataMolId: data-mol-id',
    'onClick',
    'onFocus',
    'onBlur',
    'onKeyDown',
  ],
  host: {
    '[class]': 'cm().formFieldWrapper',
  },
  template: `<label [class]="cm().controlLabel">
      <input
        type="checkbox"
        [attr.id]="checkboxId()"
        [attr.name]="name"
        [molChecked]="checked"
        [molDefaultChecked]="defaultChecked"
        [disabled]="disabled"
        [attr.data-state]="checked ? 'checked' : 'unchecked'"
        [attr.aria-invalid]="error || fieldContext()?.invalid ? 'true' : 'false'"
        [attr.aria-describedby]="mergedDescribedBy()"
        [class]="classes()"
        [attr.style]="hostStyle()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        (click)="handleClick($event)"
        (change)="handleChange($event)"
        (focusin)="onFocus?.($event)"
        (focusout)="onBlur?.($event)"
        (keydown)="onKeyDown?.($event)"
        #input
      />
      <span [class]="cm().cn(cm().controlText, disabled && cm().controlDisabled)" #labelSlot
        >{{ label }}<ng-content select="[slot=label]"></ng-content
      ></span>
    </label>
    @if (error) {
      <p [attr.id]="errorId()" [class]="cm().cn(cm().formError, cm().sp('mt', 1))">{{ error }}</p>
    }`,
})
export class Checkbox implements AfterViewChecked, HasElement<HTMLInputElement> {
  /** Checkbox label (text, or projected `[slot=label]` nodes). */
  label?: unknown
  /** Whether the checkbox is checked. */
  checked?: boolean
  /** Whether the checkbox renders the indeterminate state. */
  indeterminate?: boolean
  /** Checkbox size (kept for prop parity). */
  size?: Size
  /** Error message (renders and associates via aria-describedby). */
  error?: string
  /** Extra classes joined onto the checkbox classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the input. */
  testId?: string
  /** Disables the checkbox. */
  disabled?: boolean
  /** Form field name. */
  name?: string
  /** Explicit id (defaults to the name). */
  id?: string
  /** Uncontrolled initial checked state (renders as the checked attribute). */
  defaultChecked?: boolean
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** A caller's click handler (React's `onClick`, which React spreads onto the input). */
  onClick?: MouseEventHandler

  /** React's `onFocus`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onFocus?: FocusEventHandler
  /** React's `onBlur`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onBlur?: FocusEventHandler
  /** React's `onKeyDown`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onKeyDown?: KeyboardEventHandler

  /** The genuine native `change` event. */
  @Output() readonly change = new EventEmitter<Event>()
  /** Fires with the new checked state. */
  @Output() readonly checkedChange = new EventEmitter<boolean>()

  /** The native input (React's `...rest` spread target). */
  private input?: ElementRef<HTMLInputElement>
  /** The native input view query; also feeds the caller's ref element. */
  @ViewChild('input')
  set inputQuery(ref: ElementRef<HTMLInputElement> | undefined) {
    this.input = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLInputElement | null>(null)
  /** The element a caller's ref receives: the native `<input>`. */
  readonly element = this.inner.asReadonly()
  /** The label text wrapper. */
  @ViewChild('labelSlot') labelSlot?: ElementRef<HTMLSpanElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /** The per-instance id used when the caller gives no `id` or `name` (React's `useId`). */
  private readonly generatedId = nextInstanceId()
  /** The `aria-describedby` the caller spread onto the host (React's rest). */
  private restDescribedBy: string | null = null
  /** Whether the rest-describedby value was captured. */
  private restDescribedByCaptured = false
  /** The `data-mol-id` a caller bound on the host (React spreads it onto the input). */
  private externalMolId: string | undefined
  private hasLabel = false
  private syncIndeterminate = false

  /** Applies React's `{!!label && <span>}` label condition. */
  constructor() {
    usePlacement((hasContent) => {
      this.hasLabel = !!this.label || hasContent(this.labelSlot?.nativeElement)
      setElementPresent(this.labelSlot?.nativeElement, this.hasLabel)
    })
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The id of the label-side element (`id` or `name`). */
  checkboxId(): string | undefined {
    return this.id || this.fieldContext()?.id || this.name
  }

  /** The error message id (a stable generated id, renumbered consistently by the DOM normalizer like React's `useId`). */
  errorId(): string {
    return `${this.checkboxId() ?? this.generatedId}-error`
  }

  /** The nearest enclosing `FormField` context (React's cloned props). */
  fieldContext(): FormFieldContext | null {
    return fieldContext(this.host.nativeElement)
  }

  /** The final `aria-describedby`: the enclosing FormField's error/hint target, then this checkbox's own error (React's cloneElement join). */
  mergedDescribedBy(): string | null {
    return (
      this.fieldContext()?.describedBy ??
      this.restDescribedBy ??
      (this.error ? this.errorId() : null)
    )
  }

  /** Computes the checkbox class list. */
  classes(): string {
    return this.cm().cn(this.cm().checkbox({ error: !!this.error }), this.className)
  }

  /** Serializes the inline style for the input. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /** The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`). */
  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  handleClick(event: MouseEvent): void {
    this.onClick?.(event)
    this.justClicked = true
    this.emitChange(event)
    queueMicrotask(() => (this.justClicked = false))
  }

  handleChange(event: Event): void {
    event.stopPropagation()
    if (!this.justClicked) this.emitChange(event)
    if (this.checked !== undefined && this.input) this.input.nativeElement.checked = !!this.checked
  }

  private justClicked = false

  /** Reports the checkbox change and its new checked state. */
  private emitChange(event: Event): void {
    const next = this.input?.nativeElement.checked
    this.change.emit(event)
    if (next !== undefined) this.checkedChange.emit(next)
  }

  /** Applies the indeterminate DOM flag (a property, not an attribute). */
  ngAfterViewChecked(): void {
    const input = this.input?.nativeElement
    if (input) {
      if (!this.restDescribedByCaptured) {
        this.restDescribedBy = this.host.nativeElement.getAttribute('aria-describedby')
        this.restDescribedByCaptured = true
      }
      adoptHostDataMolId(
        this.host.nativeElement,
        input,
        (id) => {
          this.externalMolId = id
        },
        () => this.molId(),
      )
      moveRestAttributes(this.host.nativeElement, input)
      if (this.syncIndeterminate !== !!this.indeterminate) {
        input.indeterminate = !!this.indeterminate
        this.syncIndeterminate = !!this.indeterminate
      }
    }
  }
}

(Member comments are shortened to their first sentence, and the 2 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/checkbox.component.d.ts.)

ConfirmButton

ConfirmButton component.

The host is the <button> itself (button[mol-confirm-button]). Each label is a node-valued input (label, confirmLabel, pendingLabel) or the matching projected slot ([slot=label], [slot=confirmLabel], [slot=pendingLabel]); each capture span stays detached from the DOM and the visible phase's projected children are moved onto the button — React renders exactly one label and no wrapper element. When neither the input nor the slot for the armed/pending phase is given, the localized default text renders instead (React's confirmLabel ?? t(…)).

@Component({
  selector: 'button[mol-confirm-button]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolTemplateOutlet],
  inputs: [
    'variant',
    'color',
    'size',
    'onConfirm',
    'label',
    'confirmLabel',
    'pendingLabel',
    'disarmSeconds',
    'disabled',
    'testId',
    'className',
    'style',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[attr.type]': '"button"',
    '(click)': 'handleClick()',
    '[disabled]': 'disabled || phase() === "pending"',
    '[attr.aria-live]': '"polite"',
    '[attr.data-state]': 'phase()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
  },
  template: `@if (phase() === 'armed' && !hasConfirmLabel() && !isGiven(confirmLabel)) {
      Confirm?
    }
    @if (phase() === 'pending' && !hasPendingLabel() && !isGiven(pendingLabel)) {
      Working…
    }
    @if (phase() === 'idle' && isGiven(label)) {
      <ng-container [molTemplateOutlet]="asTemplate(label)"></ng-container>{{ nodeText(label) }}
    }
    @if (phase() === 'armed' && isGiven(confirmLabel)) {
      <ng-container [molTemplateOutlet]="asTemplate(confirmLabel)"></ng-container
      >{{ nodeText(confirmLabel) }}
    }
    @if (phase() === 'pending' && isGiven(pendingLabel)) {
      <ng-container [molTemplateOutlet]="asTemplate(pendingLabel)"></ng-container
      >{{ nodeText(pendingLabel) }}
    }
    <span #labelSlot><ng-content select="[slot=label]"></ng-content></span
    ><span #confirmSlot><ng-content select="[slot=confirmLabel]"></ng-content></span
    ><span #pendingSlot><ng-content select="[slot=pendingLabel]"></ng-content></span>`,
})
export class ConfirmButton implements OnDestroy, HasElement<HTMLButtonElement> {
  /** Button variant (passed through to the button classes). */
  variant?: ConfirmButtonProps['variant']
  /** Button color; the armed state always shows the error color. */
  color?: ConfirmButtonProps['color']
  /** Button size. */
  size?: ConfirmButtonProps['size']
  /** The confirm callback (React's `onConfirm` prop). */
  onConfirm?: ConfirmButtonProps['onConfirm']
  /** Visible label in the idle state (React's `label` node value). */
  label?: ConfirmButtonProps['label']
  /** Visible label in the armed state (React's `confirmLabel` node value). */
  confirmLabel?: ConfirmButtonProps['confirmLabel']
  /** Visible label while the confirm callback is pending. */
  pendingLabel?: ConfirmButtonProps['pendingLabel']
  /** Seconds before the armed state auto-disarms (`0` disables auto-disarm). */
  disarmSeconds?: ConfirmButtonProps['disarmSeconds'] = 4
  /** Disables the control entirely (idle and confirming states). */
  disabled?: ConfirmButtonProps['disabled'] = false
  /** `data-testid` for the button. */
  testId?: ConfirmButtonProps['testId']
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: ConfirmButtonProps['automationId']
  dataMolId?: string
  /** Extra classes joined onto the button classes. */
  className?: ConfirmButtonProps['className']
  /** Inline style object (React camelCase). */
  style?: ConfirmButtonProps['style']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText
  /** Whether a node-valued prop was given. */
  readonly isGiven = isGiven

  /** The label slot capture span (kept out of the DOM). */
  @ViewChild('labelSlot') labelSlot?: ElementRef<HTMLSpanElement>
  /** The armed-state label capture span. */
  @ViewChild('confirmSlot') confirmSlot?: ElementRef<HTMLSpanElement>
  /** The pending-state label capture span. */
  @ViewChild('pendingSlot') pendingSlot?: ElementRef<HTMLSpanElement>

  readonly hasConfirmLabel = signal(false)
  readonly hasPendingLabel = signal(false)

  /** The current phase: idle → armed → pending → idle. */
  readonly phase = signal<'idle' | 'armed' | 'pending'>('idle')

  private readonly el: ElementRef<HTMLButtonElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<button>`. */
  readonly element = hostElement(this.el)
  private disarmTimer: ReturnType<typeof setTimeout> | null = null
  private readonly layer = new OverlayLayer()

  constructor() {
    usePlacement((hasContent) => this.syncLabels(hasContent))
    effect(() => {
      if (this.disarmTimer) {
        clearTimeout(this.disarmTimer)
        this.disarmTimer = null
      }
      const disarmSeconds = this.disarmSeconds ?? 4
      const armed = this.phase() === 'armed'
      const target = { current: this.el.nativeElement }
      this.layer.sync({
        open: armed,
        kind: 'popover',
        surface: target,
        anchor: target,
        dismissKey: true,
        onDismiss: () => this.disarm(),
      })
      if (armed && disarmSeconds > 0) {
        this.disarmTimer = setTimeout(() => {
          this.disarmTimer = null
          this.phase.set('idle')
        }, disarmSeconds * 1000)
      }
    })
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** Computes the button class list (the armed state shows the error color). */
  classes(): string {
    return this.cm().cn(
      this.cm().button({
        color: this.phase() === 'armed' ? 'error' : (this.color ?? 'primary'),
        size: this.size,
        variant: this.variant,
      }),
      this.className,
    )
  }

  /** Serializes the inline style. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /** The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`). */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.el.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  private async handleClick(): Promise<void> {
    const current = this.phase()
    if (current === 'idle') {
      this.phase.set('armed')
      return
    }
    if (current === 'pending') return
    this.phase.set('pending')
    try {
      await this.onConfirm?.()
    } catch (_error) {
      // A rejected confirm means the action failed: the caller owns that
      // error and shows its own message, and the button returns to idle so
      // the user can retry. Ignoring it here only stops it becoming an
      // unhandled rejection.
    } finally {
      this.phase.set('idle')
    }
  }

  /** React's `disarm`: cancels the timer and returns to idle. */
  private disarm(): void {
    if (this.disarmTimer) {
      clearTimeout(this.disarmTimer)
      this.disarmTimer = null
    }
    this.phase.set('idle')
  }

  /** The slot whose content is currently shown on the button. */
  private visibleFrom: HTMLSpanElement | null = null

  private syncLabels(hasContent: SlotReader): void {
    this.hasConfirmLabel.set(hasContent(this.confirmSlot?.nativeElement))
    this.hasPendingLabel.set(hasContent(this.pendingSlot?.nativeElement))
    for (const span of [this.labelSlot, this.confirmSlot, this.pendingSlot])
      setElementPresent(span?.nativeElement, false)
    const phase = this.phase()
    const target =
      phase === 'idle'
        ? (this.labelSlot?.nativeElement ?? null)
        : phase === 'armed' && this.hasConfirmLabel()
          ? (this.confirmSlot?.nativeElement ?? null)
          : phase === 'pending' && this.hasPendingLabel()
            ? (this.pendingSlot?.nativeElement ?? null)
            : null
    this.showSlot(target)
  }

  private showSlot(span: HTMLSpanElement | null): void {
    const host = this.el.nativeElement
    if (span === this.visibleFrom) return
    if (this.visibleFrom) placeContent(this.visibleFrom, null)
    this.visibleFrom = span
    if (!span) return
    placeContent(span, host)
  }

  /** Clears the auto-disarm timer (React's unmount cleanup). */
  ngOnDestroy(): void {
    this.layer.release()
    if (this.disarmTimer) clearTimeout(this.disarmTimer)
  }
}

(Member comments are shortened to their first sentence, and the 7 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/confirm-button.component.d.ts.)

ConfirmDialog

ConfirmDialog component.

Composed from Modal and Button exactly as React composes them; the dialog's own title/description/children are projected content ([slot=title], [slot=description], default) or node-valued inputs. React's root is a Modal, which renders a portal while open and nothing while closed, so the host element leaves the page and the portal renders in document.body.

@Component({
  selector: 'mol-confirm-dialog',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Button, Modal, MolTemplateOutlet],
  inputs: ['open', 'title', 'description', 'confirmLabel', 'cancelLabel', 'destructive', 'loading'],
  outputs: ['close', 'confirm'],
  template: `<mol-modal
    #modal
    [open]="open"
    (close)="close.emit($event)"
    [attr.aria-labelledby]="ariaLabelledBy()"
    [attr.aria-describedby]="ariaDescribedBy()"
    ><div [class]="cm().stack(3)">
      <h2
        #titleSlot
        [attr.id]="ariaLabelledBy()"
        [class]="cm().cn(cm().textSize('lg'), cm().fontWeight('bold'))"
      >
        @if (isGiven(title)) {
          <ng-container [molTemplateOutlet]="asTemplate(title)"></ng-container>{{ nodeText(title) }}
        }
        <ng-content select="[slot=title]"></ng-content>
      </h2>
      <p #descriptionSlot [attr.id]="descriptionId" [class]="cm().textSize('sm')">
        @if (isGiven(description)) {
          <ng-container [molTemplateOutlet]="asTemplate(description)"></ng-container
          >{{ nodeText(description) }}
        }
        <ng-content select="[slot=description]"></ng-content>
      </p>
      <ng-content></ng-content>
      <div [class]="cm().flex({ justify: 'end', gap: 'sm' })">
        <button mol-button [variant]="'ghost'" [disabled]="!!loading" (click)="close.emit($event)">
          @if (isGiven(cancelLabel)) {
            <ng-container [molTemplateOutlet]="asTemplate(cancelLabel)"></ng-container
            >{{ nodeText(cancelLabel) }}
          } @else {
            {{ cancelText() }}
          }</button
        ><button
          mol-button
          [variant]="'solid'"
          [color]="destructive === false ? 'primary' : 'error'"
          [disabled]="!!loading"
          (click)="confirm.emit()"
        >
          @if (isGiven(confirmLabel) && !loading) {
            <ng-container [molTemplateOutlet]="asTemplate(confirmLabel)"></ng-container
            >{{ nodeText(confirmLabel) }}
          } @else {
            {{ confirmText() }}
          }
        </button>
      </div>
    </div></mol-modal
  >`,
})
export class ConfirmDialog {
  /**
   * Per-instance id of the rendered title heading, wired as the dialog's
   * accessible name: the binding on `<mol-modal>` reaches the dialog `<div>`,
   * React's `{...rest}` target (Modal names it with `setHostRoot`) —
   * `aria-labelledby` pointing at the visible `<h2>` (WAI-ARIA dialog
   * pattern; axe `aria-dialog-name`).
   */
  readonly titleId = `mol-confirm-dialog-title-${++confirmDialogInstances}`

  /**
   * Per-instance id of the rendered description paragraph, wired as the
   * dialog's accessible description the same way as the title (only bound when projected description content renders — a
   * reference to an empty paragraph describes nothing, axe
   * `aria-dialog-name`/`aria-valid-attr-value`).
   */
  readonly descriptionId = nextInstanceId()

  /** The rendered description paragraph (its projected nodes decide the wiring). */
  // `static: true` resolves the query during creation, so the projected nodes
  // are readable on the FIRST change-detection pass — a non-static query
  // resolves after view init, one pass too late for the description wiring.
  @ViewChild('descriptionSlot', { static: true })
  descriptionSlot?: ElementRef<HTMLParagraphElement>

  /** The title heading (its projected nodes decide whether the dialog points at it). */
  @ViewChild('titleSlot', { static: true }) titleSlot?: ElementRef<HTMLHeadingElement>

  /** Whether the dialog is open. */
  open: ConfirmDialogProps['open'] = false
  /** Title (node-valued prop). */
  title?: ConfirmDialogProps['title']
  /** Body / warning text (node-valued prop). */
  description?: ConfirmDialogProps['description']
  /** Confirm-button label (node-valued prop). */
  confirmLabel?: ConfirmDialogProps['confirmLabel']
  /** Cancel-button label (node-valued prop). */
  cancelLabel?: ConfirmDialogProps['cancelLabel']
  /** Whether the confirm action is destructive (default true). */
  destructive?: ConfirmDialogProps['destructive'] = true
  /** Disables both buttons (the caller owns the pending state). */
  loading?: ConfirmDialogProps['loading']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText
  /** Whether a node-valued prop was given. */
  readonly isGiven = isGiven

  /** Fires when the dialog should close (escape, backdrop, cancel). */
  @Output() readonly close = new EventEmitter<MouseEvent | undefined>()
  /** Fires when the user confirms. */
  @Output() readonly confirm = new EventEmitter<void>()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The dialog's accessible description id, or null when no description
   * content renders. A signal the template reads, so the association follows
   * the projected description in the pass where it changes.
   */
  readonly ariaDescribedBy = signal<string | null>(null)

  /**
   * The title heading's id, which the dialog's `aria-labelledby` points at, or null while the title
   * renders nothing (React's `slot(title)`): a heading with no text names nothing.
   */
  readonly ariaLabelledBy = signal<string | null>(null)

  /** The composed Modal's element: what the caller binds on this tag lands there, and Modal passes it to its dialog. */
  @ViewChild('modal', { read: ElementRef }) modalElement?: ElementRef<HTMLElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))

  /**
   * Recomputes `ariaLabelledBy` and `ariaDescribedBy` from the
   * title and description inputs and their projected nodes in
   * the placement function, and takes the host out of the page (React renders
   * the composed `Modal`'s portal in `document.body`, nothing here).
   */
  constructor() {
    usePlacement((hasContent) => {
      this.ariaLabelledBy.set(
        rendersNode(this.title) || hasContent(this.titleSlot?.nativeElement) ? this.titleId : null,
      )
      this.ariaDescribedBy.set(
        rendersNode(this.description) || hasContent(this.descriptionSlot?.nativeElement)
          ? this.descriptionId
          : null,
      )
      setElementPresent(this.host.nativeElement, !this.browser && this.open)
      setHostRoot(this.host.nativeElement, this.modalElement?.nativeElement)
    })
  }

  /**
   * The cancel button's label.
   * @returns The label text.
   */
  cancelText(): string {
    return typeof this.cancelLabel === 'string'
      ? this.cancelLabel
      : this.i18n.t('confirm.cancel', {}, { defaultValue: 'Cancel' })
  }

  /**
   * The confirm button's label when no node label is given (React shows an
   * ellipsis while loading).
   * @returns The label text.
   */
  confirmText(): string {
    if (this.loading) return '…'
    return typeof this.confirmLabel === 'string'
      ? this.confirmLabel
      : this.i18n.t('confirm.confirm', {}, { defaultValue: 'Confirm' })
  }
}

Dropdown component.

Implements the WAI-ARIA APG menu-button pattern exactly as React does: a single-element trigger is adopted as the real control (no wrapper) and cloned with aria-haspopup, aria-expanded, aria-controls, tabindex and the open/keyboard handlers; any other trigger (text, several nodes) is wrapped in a role="button" fallback container. The menu is rendered into document.body (React's portal) and carries the position, width and roving-tabindex behavior.

The React root is a FRAGMENT (trigger + portal), so the trigger renders in front of the host (placeContentBefore / placeElementBefore) and the host itself leaves the DOM. The trigger follows the projected content: an element that replaces it becomes the new trigger, text next to it switches to the fallback wrapper.

@Component({
  selector: 'mol-dropdown',
  standalone: true,
  imports: [MolTemplateOutlet],
  hostDirectives: [MolPlacement],
  inputs: [
    'trigger',
    'items',
    'placement',
    'open',
    'align',
    'width',
    'className',
    'style',
    'testId',
    'automationId',
    'disabled',
  ],
  outputs: ['select', 'openChange'],
  template: `<div #fallback role="button" aria-haspopup="menu" [class]="cm().dropdownTrigger">
      <span #triggerCapture><ng-content select="[slot=trigger]"></ng-content></span>
    </div>
    <ng-container #menuAnchor></ng-container
    ><ng-template #menuTpl
      ><div
        [attr.id]="menuId"
        role="menu"
        tabindex="-1"
        data-state="open"
        [class]="menuClasses()"
        [style]="menuStyleText()"
        [attr.data-testid]="menuTestId()"
        [attr.data-mol-id]="menuAutomationId()"
        (keydown)="handleMenuKeyDown($event)"
      >
        @for (item of items; track keyForItem(item, $index)) {
          @if (item.separator) {
            <div [class]="cm().dropdownSeparator" role="separator"></div>
          } @else {
            <div
              role="menuitem"
              [attr.tabindex]="itemTabIndex($index)"
              [class]="itemClasses(item)"
              (click)="handleItemClick(item)"
              (keydown)="handleItemKeyDown($event, item)"
              [attr.aria-disabled]="item.disabled ? 'true' : null"
              [attr.data-disabled]="item.disabled ? 'true' : null"
            >
              @if (item.icon) {
                <span [class]="cm().dropdownItemIcon">
                  @if (asTemplate(item.icon); as iconTpl) {
                    <ng-container [molTemplateOutlet]="iconTpl"></ng-container>
                  } @else {
                    {{ iconText(item.icon) }}
                  }
                </span>
              }
              <span [class]="cm().dropdownItemLabel">{{ item.label }}</span>
              @if (item.shortcut) {
                <span [class]="cm().dropdownItemShortcut">{{ item.shortcut }}</span>
              }
            </div>
          }
        }
      </div></ng-template
    >`,
})
export class Dropdown implements AfterViewInit, DoCheck, OnDestroy, HasElement<HTMLDivElement> {
  trigger?: unknown
  items: DropdownItem<string>[] = []
  placement: DropdownPlacement = 'bottom-start'
  open?: boolean
  align: DropdownAlign = 'start'
  width?: 'trigger' | 'auto' | number | string
  className?: string
  style?: Record<string, unknown>
  testId?: string
  automationId?: string
  disabled?: boolean

  @Output() readonly select = new EventEmitter<string>()
  @Output() readonly openChange = new EventEmitter<boolean>()

  @ViewChild('triggerCapture') triggerCapture?: ElementRef<HTMLSpanElement>
  @ViewChild('fallback') fallback?: ElementRef<HTMLDivElement>
  @ViewChild('menuAnchor', { read: ViewContainerRef }) menuAnchor?: ViewContainerRef
  @ViewChild('menuTpl') menuTpl?: TemplateRef<unknown>

  readonly menuId = nextInstanceId()
  private readonly internalOpen = signal(false)
  private readonly activeIndex = signal(-1)
  private readonly position = signal<Position>({ top: 0, left: 0 })

  readonly router = useRouter()

  private readonly el = inject(ElementRef)
  private readonly inner = signal<HTMLDivElement | null>(null)
  readonly element = this.inner.asReadonly()
  private readonly renderer = inject(Renderer2)
  private readonly layer = new OverlayLayer()
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))
  private readonly cdr = inject(ChangeDetectorRef)
  private readonly injector = inject(Injector)
  private readonly host: HTMLElement = this.el.nativeElement
  private triggerEl: HTMLElement | SVGElement | null = null
  private triggerOwnTestId: string | null = null
  private triggerOwnMolId: string | null = null
  private triggerOwnDisabled = false
  private triggerIsFallback = false
  private triggerOwnTabindex: string | null = null
  private triggerListeners: (() => void)[] = []
  private menuView?: EmbeddedViewRef<unknown>
  private menuEl: HTMLDivElement | null = null
  private lastOpen = false
  private lastPlacement: DropdownPlacement = 'bottom-start'
  private lastAlign: DropdownAlign = 'start'
  private menuWidth: number | string | undefined
  private cancelPosition?: () => void
  private lastRoute: string | null = null
  private pendingOpenFocus: 'first' | 'last' = 'first'
  private focusedItemEl: HTMLElement | null = null
  private checkedItems: DropdownItem<string>[] | null = null
  private itemHadFocus = false
  private readonly routeEffect = effect(() => {
    const location = this.router.location()
    const key = `${location.pathname}${location.search}`
    if (key === this.lastRoute) return
    const mounting = this.lastRoute === null
    this.lastRoute = key
    if (!mounting) this.setOpen(false)
  })

  cm(): UIClassMap {
    return getClassMap()
  }

  asTemplate(value: unknown): TemplateRef<unknown> | null {
    return value instanceof TemplateRef ? value : null
  }

  keyForItem(item: DropdownItem<string>, index: number): string {
    return item.separator ? `separator-${index}` : item.value
  }

  iconText(value: unknown): string {
    return typeof value === 'string' ? value : ''
  }

  isOpen(): boolean {
    if (this.disabled) return false
    return this.open !== undefined ? this.open : this.internalOpen()
  }

  setOpen(open: boolean): void {
    if (this.open === undefined) this.internalOpen.set(open)
    this.openChange.emit(open)
    this.cdr.markForCheck()
  }

  menuClasses(): string {
    return this.cm().cn(this.cm().dropdownContent, this.className)
  }

  menuTestId(): string | null {
    return this.testId ? `${this.testId}-menu` : null
  }

  menuAutomationId(): string | null {
    return this.automationId ? `${this.automationId}-menu` : null
  }

  menuStyleText(): string | null {
    return styleText({
      ...this.style,
      position: 'absolute',
      top: this.position().top,
      left: this.position().left,
      width: this.menuWidth,
      zIndex: 50,
    })
  }

  itemClasses(item: DropdownItem<string>): string {
    return this.cm().cn(this.cm().dropdownItem, item.disabled && this.cm().dropdownItemDisabled)
  }

  itemTabIndex(index: number): number {
    const item = this.items[index]
    if (item?.disabled) return -1
    return index === this.activeIndex() ? 0 : -1
  }

  handleItemClick(item: DropdownItem<string>): void {
    if (item.disabled) return
    this.select.emit(item.value)
    this.closeAndRefocusTrigger()
  }

  handleItemKeyDown(event: KeyboardEvent, item: DropdownItem<string>): void {
    if (event.key !== 'Enter' && event.key !== ' ') return
    event.preventDefault()
    this.handleItemClick(item)
  }

  handleMenuKeyDown(event: KeyboardEvent): void {
    const focusable = this.focusableIndexes()
    if (focusable.length === 0) return
    const currentPos = focusable.indexOf(this.activeIndex())
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault()
        this.activeIndex.set(focusable[(currentPos + 1 + focusable.length) % focusable.length])
        this.focusActive()
        break
      case 'ArrowUp':
        event.preventDefault()
        this.activeIndex.set(focusable[(currentPos - 1 + focusable.length) % focusable.length])
        this.focusActive()
        break
      case 'Home':
        event.preventDefault()
        this.activeIndex.set(focusable[0])
        this.focusActive()
        break
      case 'End':
        event.preventDefault()
        this.activeIndex.set(focusable[focusable.length - 1])
        this.focusActive()
        break
      case 'Tab':
        this.handleClose()
        break
      default:
        break
    }
  }

  handleTriggerClick(): void {
    if (this.disabled) return
    if (!this.isOpen()) this.pendingOpenFocus = 'first'
    this.setOpen(!this.isOpen())
  }
// … truncated — 22 more members: handleTriggerKeyDown, handleClose, closeAndRefocusTrigger, ngAfterViewInit, ngDoCheck, ngOnDestroy, placeTrigger, adopt, release, focusableIndexes, itemElements, elementForIndex, focusActive, constructor, restoreItemFocus, syncMenu, openMenu, destroyMenu, updateMenuWidth, schedulePosition, updatePosition, syncTrigger; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/dropdown.component.d.ts

(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/dropdown.component.d.ts.)

DropdownLabel component: a group label inside a menu.

@Component({
  selector: 'div[mol-dropdown-label]',
  standalone: true,
  hostDirectives: [{ directive: ElementLanguage, inputs: ['lang'] }],
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class DropdownLabel implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().dropdownLabel, this.className)
  }
}

DropdownSeparator component: a dividing rule inside a menu.

@Component({
  selector: 'div[mol-dropdown-separator]',
  standalone: true,
  inputs: ['className'],
  host: {
    '[class]': 'classes()',
    role: 'separator',
  },
  template: ``,
})
export class DropdownSeparator implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().dropdownSeparator, this.className)
  }
}

EmptyState

EmptyState component.

Shown when a list or section has no data: an optional icon badge, a title, a description, and an optional action slot. React renders the icon/action wrapper divs only when those node props exist; here the wrappers always exist as projection capture points and are taken out of the DOM when empty (setElementPresent).

@Component({
  selector: 'div[mol-empty-state]',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: [
    'icon',
    'title',
    'description',
    'action',
    'className',
    'style',
    'testId',
    'automationId',
  ],
  host: {
    // `title` is this component's heading, which React renders as text; Angular would also keep a
    // static `title="…"` on the host, where the browser shows it as a tooltip.
    '[attr.title]': 'null',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'automationId',
  },
  template: `<div [class]="cm().emptyStateIcon" #iconSlot>
      <ng-content select="[slot=icon]"></ng-content>
    </div>
    <h3 [class]="cm().emptyStateTitle">{{ title }}</h3>
    @if (description) {
      <p [class]="cm().emptyStateDescription">{{ description }}</p>
    }
    <div [class]="cm().emptyStateAction" #actionSlot>
      <ng-content select="[slot=action]"></ng-content>
    </div>`,
})
export class EmptyState implements HasElement<HTMLDivElement> {
  /** An `icon` node prop (TemplateRef), when passed as a prop instead of a slot. */
  icon?: unknown
  /** Heading text. */
  title?: string
  /** Description text. */
  description?: string
  /** An `action` node prop (TemplateRef), when passed as a prop instead of a slot. */
  action?: unknown
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id`. */
  automationId?: string

  /** The icon wrapper (detached unless the slot captured nodes). */
  @ViewChild('iconSlot') iconSlot?: ElementRef<HTMLDivElement>
  /** The action wrapper. */
  @ViewChild('actionSlot') actionSlot?: ElementRef<HTMLDivElement>

  private hasIcon = false
  private hasAction = false

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Detaches the icon and action wrappers React would not render. */
  constructor() {
    usePlacement((hasContent) => this.syncWrappers(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().emptyState, this.className)
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * Applies React's `{icon && <div>…}` / `{action && <div>…}` conditions.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncWrappers(hasContent: SlotReader): void {
    this.hasIcon =
      this.icon !== undefined && this.icon !== null
        ? true
        : hasContent(this.iconSlot?.nativeElement)
    this.hasAction =
      this.action !== undefined && this.action !== null
        ? true
        : hasContent(this.actionSlot?.nativeElement)
    setElementPresent(this.iconSlot?.nativeElement, this.hasIcon)
    setElementPresent(this.actionSlot?.nativeElement, this.hasAction)
  }
}

FileField

Renders one focusable target and emits portable file selections.

@Component({
  selector: 'div[mol-file-field]',
  standalone: true,
  host: {
    'data-mol-id': 'file-field',
    '[attr.role]': 'role ?? "button"',
    '[class]': 'className',
    '[attr.tabindex]': 'disabled ? -1 : 0',
    '[attr.aria-disabled]': 'disabled ?? null',
    '(click)': 'handlers.onClick($event)',
    '(keydown)': 'handlers.onKeyDown($event)',
    '(dragover)': 'onDragOver($event)',
    '(drop)': 'handlers.onDrop($event)',
  },
  template: `<input
      #fileInput
      type="file"
      hidden
      [attr.accept]="accept ?? null"
      [multiple]="multiple"
      [disabled]="disabled ?? false"
      (change)="handlers.onChange()"
    /><ng-content />`,
})
export class FileField implements FileFieldHandle {
  /** Comma-separated accepted types and extensions. */
  @Input() accept?: string
  /** ClassMap classes for the host. */
  @Input() className?: string
  /** Prevents picking and delivering files. */
  @Input() disabled?: boolean
  /** Inclusive per-file limit in bytes. */
  @Input() maxSize?: number
  /** Delivers all accepted files in selection order. */
  @Input({ transform: booleanAttribute }) multiple = false
  /** Optional accessibility role for the host. */
  @Input() role?: FileFieldProps['role']
  /** The accepted files. */
  @Output() readonly valueChange = new EventEmitter<readonly PickedFile[]>()
  /** The files rejected by type or size. */
  @Output() readonly rejected = new EventEmitter<readonly PickedFile[]>()
  /** A failure opening or reading the chooser. */
  @Output() readonly pickError = new EventEmitter<Error>()

  @ViewChild('fileInput') private fileInput?: ElementRef<HTMLInputElement>

  /** Shared DOM event handlers for this host and its input. */
  protected readonly handlers = createBrowserFileInput(
    () => this.fileInput?.nativeElement,
    () => ({
      accept: this.accept,
      disabled: this.disabled,
      maxSize: this.maxSize,
      multiple: this.multiple,
      onFiles: (files) => this.valueChange.emit(files),
      onRejected: (files) => this.rejected.emit(files),
      onPickError: (error) => this.pickError.emit(error),
    }),
    fromBrowserFile,
  )

  /** Opens the chooser when called on the field instance from a view query. */
  pick(): void {
    this.handlers.onClick({ target: null, defaultPrevented: false })
  }

  /**
   * Enables dropping on the host when the field is enabled.
   * @param event - The native drag event.
   */
  protected onDragOver(event: DragEvent): void {
    this.handlers.onDragOver(event)
  }
}

FloatingInput

FloatingInput component.

The host is the span.floatingInputWrapper React renders; the input and its floating label sit adjacent with no whitespace (both are inline elements, so a space would draw). Works controlled (value) and uncontrolled (internal state seeded from defaultValue).

@Component({
  selector: 'span[mol-floating-input]',
  standalone: true,
  inputs: [
    'type',
    'name',
    'disabled',
    'required',
    'placeholder',
    'className',
    'value',
    'defaultValue',
    'id',
    'automationId',
    'dataMolId: data-mol-id',
    'onFocus',
    'onBlur',
    'onKeyDown',
  ],
  host: {
    '[class]': 'cm().floatingInputWrapper',
  },
  template: `<input
      [attr.type]="type ?? null"
      [attr.name]="name ?? null"
      [attr.id]="inputId()"
      [attr.placeholder]="placeholder"
      [disabled]="isDisabled()"
      [attr.required]="isRequired() ? '' : null"
      [class]="classes()"
      [attr.value]="currentValue()"
      [attr.data-mol-id]="molId()"
      (input)="handleInput($event)"
      (change)="stopPropagation($event)"
      (focusin)="onFocus?.($event)"
      (focusout)="onBlur?.($event)"
      (keydown)="onKeyDown?.($event)"
      #inputEl
    />
    @if (placeholder) {
      <label [attr.for]="inputId()" [class]="cm().floatingLabel">{{ placeholder }}</label>
    }`,
})
export class FloatingInput
  implements OnInit, AfterViewInit, AfterViewChecked, HasElement<HTMLInputElement>
{
  /** Input type attribute. */
  type?: string
  /** Form field name attribute. */
  name?: string
  /** Whether the input is disabled (accepts boolean binding or static HTML attribute). */
  disabled?: boolean | ''
  /** Whether the input is required (accepts boolean binding or static HTML attribute). */
  required?: boolean | ''
  /** Placeholder text, also rendered as the floating label. */
  placeholder?: string
  /** Extra classes joined onto the input classes. */
  className?: string
  /** Controlled value. */
  value?: string
  /** Uncontrolled initial value (seeds the internal state). */
  defaultValue?: string
  /** Explicit input id. */
  id?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** React's `onFocus`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onFocus?: FocusEventHandler
  /** React's `onBlur`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onBlur?: FocusEventHandler
  /** React's `onKeyDown`, which React spreads onto the <input>: its `currentTarget` is that element. */
  onKeyDown?: KeyboardEventHandler

  /** Fires the raw `input` event (React's text-input onChange). */
  @Output() readonly change = new EventEmitter<Event>()

  /** Emits the typed text on each input event. */
  @Output() readonly valueChange = new EventEmitter<string>()

  /** The native input (React's `...rest` spread target). */
  private inputEl?: ElementRef<HTMLInputElement>
  /** The native input view query; also feeds the caller's ref element. */
  @ViewChild('inputEl')
  set inputElQuery(ref: ElementRef<HTMLInputElement> | undefined) {
    this.inputEl = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLInputElement | null>(null)
  /** The element a caller's ref receives: the native `<input>`. */
  readonly element = this.inner.asReadonly()

  private readonly host = inject(ElementRef)
  /** The per-instance id used when the caller gives none (React's `useId`). */
  private readonly generatedId = nextInstanceId()
  private internalValue = ''
  /** The `data-mol-id` a caller bound on the host (React spreads it onto the input). */
  private externalMolId: string | undefined

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The input id (`id` or a stable generated id; the DOM normalizer renumbers
   * generated ids in order of appearance, like React's `useId`).
   * @returns The id value.
   */
  inputId(): string {
    return this.id || this.generatedId
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  /** Whether the input is disabled (handles `[disabled]="true"` and static `disabled`). */
  isDisabled(): boolean {
    return this.disabled === true || this.disabled === ''
  }

  /** Whether the input is required (handles `[required]="true"` and static `required`). */
  isRequired(): boolean {
    return this.required === true || this.required === ''
  }

  /**
   * Computes the input class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().input(), this.cm().floatingInput, this.className)
  }

  /**
   * The rendered value: the controlled `value`, else the internal state
   * (seeded from `defaultValue`, updated by typing when uncontrolled).
   * @returns The value string.
   */
  currentValue(): string {
    return this.value !== undefined ? String(this.value) : this.internalValue
  }

  /**
   * React's onChange: the raw `input` event, with the internal state updated
   * when uncontrolled and the controlled value restored afterwards. The
   * native change event never reaches the host (its `change` output binding
   * would record it a second time).
   *
   * @param event - The native input event.
   */
  handleInput(event: Event): void {
    event.stopPropagation()
    const input = event.currentTarget
    if (!(input instanceof HTMLInputElement)) return
    if (this.value === undefined) this.internalValue = input.value
    this.change.emit(event)
    this.valueChange.emit(input.value)
    if (this.value !== undefined && input.value !== String(this.value))
      input.value = String(this.value)
  }

  /**
   * Swallows the native change event (React's onChange already fired on the
   * input event).
   *
   * @param event - The native change event.
   */
  stopPropagation(event: Event): void {
    event.stopPropagation()
  }

  /**
   * Seeds the internal state (inputs are set by now, and the template's
   * value binding evaluates only after this hook).
   */
  ngOnInit(): void {
    this.internalValue = String(this.defaultValue ?? '')
  }

  /**
   * Moves rest attributes (`type`, `name`, `disabled`, `readOnly`,
   * `maxLength`, aria/data) onto the input, where React's `{...props}`
   * spread puts them.
   */
  ngAfterViewInit(): void {
    this.adoptHostMolId()
    moveRestAttributes(this.host.nativeElement, this.inputEl?.nativeElement)
  }

  /**
   * Puts a `data-mol-id` bound on the host onto the input in the pass that bound it (the host
   * attribute is written after this component's view is checked).
   */
  ngAfterViewChecked(): void {
    this.adoptHostMolId()
  }

  /** Takes a `data-mol-id` off the host and keeps it for the input's binding. */
  private adoptHostMolId(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.inputEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
  }
}

FormField

FormField component.

The host is the root <div> (div[mol-form-field]). React clones a single child element, adding id, aria-describedby and aria-invalid to its props; Angular cannot clone a projected component, so those values are registered on the host as a FormFieldContext that the field components (Input, Select, Textarea, Checkbox) read.

@Component({
  selector: 'div[mol-form-field]',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: [
    'label',
    'name',
    'error',
    'hint',
    'required',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `@if (label) {
      <label
        [attr.for]="singleChild() ? labelFor() || fieldId() : name || fieldId()"
        [class]="cm().cn(cm().label({ required: !!required }), cm().labelBlock)"
        >{{ label }}</label
      >
    }
    <span #capture data-mol-field-capture><ng-content></ng-content></span>
    @if (error) {
      <p [attr.id]="errorId" [class]="cm().formError">{{ error }}</p>
    }
    @if (hint && !error) {
      <p [attr.id]="hintId" [class]="cm().formHint">{{ hint }}</p>
    }`,
})
export class FormField implements OnChanges, OnDestroy, HasElement<HTMLDivElement> {
  /** Field label. */
  label?: string
  /** Field name. */
  name?: string
  /** Error message (renders and associates via aria-describedby). */
  error?: string
  /** Hint text (shown without an error). */
  hint?: string
  /** Marks the field required (label styling). */
  required?: boolean
  /** Extra classes for the wrapper. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  dataMolId?: string

  /** The projected-children capture point. */
  @ViewChild('capture') capture?: ElementRef<HTMLSpanElement>

  readonly labelFor = signal('')

  private readonly generatedId = nextInstanceId()
  readonly context = signal<FormFieldContext>({})
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)
  private readonly singleState = signal<boolean | null>(null)
  private patched: {
    control: HTMLElement
    attributes: FieldAttributes
    applied: FieldAttributes
  } | null = null
  private adopted: Node | null = null
  /** Whether the adopted content was a single element child. */
  private single = false

  /** Registers the field context before any projected child resolves it. */
  constructor() {
    FormFieldDomContext.provide(this.host.nativeElement, new FormFieldContextValue(this))
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The stable id supplied to a child that has no explicit id. */
  fieldId(): string {
    return this.generatedId
  }

  /** The error paragraph's id. */
  get errorId(): string {
    return `${this.fieldId()}-error`
  }

  /** The hint paragraph's id. */
  get hintId(): string {
    return `${this.fieldId()}-hint`
  }

  /** The id the field should describe itself with (error wins over hint). */
  describedByTarget(): string | undefined {
    if (this.error) return this.errorId
    if (this.hint) return this.hintId
    return undefined
  }

  /** The wrapper class list. */
  classes(): string {
    return this.cm().cn(this.cm().inputWrapper, this.cm().sp('mb', 4), this.className)
  }

  /** Serializes the wrapper's inline style. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  private captureEl(): HTMLElement | null {
    return (
      this.capture?.nativeElement ??
      this.host.nativeElement.querySelector<HTMLElement>('[data-mol-field-capture]')
    )
  }

  singleChild(): boolean {
    const single = this.singleState()
    if (single !== null) return single
    const capture = this.captureEl()
    if (!capture) return false
    const children = Array.from(capture.childNodes)
    const elements = children.filter((node) => node.nodeType === 1)
    const hasText = children.some((node) => node.nodeType === 3 && (node.textContent ?? '').trim())
    return elements.length === 1 && !hasText
  }

  private reconcile(hasContent: SlotReader): void {
    const capture = this.captureEl()
    if (!capture) return
    const children = hasContent.nodes(capture)
    if (children.length === 0) {
      this.adopted = null
      this.single = false
      this.singleState.set(null)
      this.unpatchNativeControl()
      this.labelFor.set(this.fieldId())
      setElementPresent(capture, false)
      return
    }
    const first = children[0]!
    // Angular inserts a list's nodes one at a time, and this runs after each:
    // a second child arriving after the first makes the field "not single" again.
    const single = children.length === 1 && first.nodeType === 1
    const host = this.host.nativeElement
    if (this.adopted !== first || this.single !== single) {
      this.singleState.set(single)
      this.single = single
      this.adopted = first
      placeContent(capture, host, capture)
    }
    const controls = single ? host.querySelectorAll<HTMLElement>(FIELD_SELECTOR) : null
    const control = controls?.length === 1 ? controls[0] : undefined
    const native = control && !control.closest(FIELD_COMPONENT) ? control : undefined
    if (this.patched?.control !== native) {
      this.unpatchNativeControl()
      if (native) this.patchNativeControl(native)
    }
    this.labelFor.set(control?.id || this.fieldId())
    setElementPresent(capture, false)
  }

  /** Applies React's cloned props to a plain native form control child. */
  private patchNativeControl(control: HTMLElement): void {
    const attributes = {
      id: control.getAttribute('id'),
      'aria-describedby': control.getAttribute('aria-describedby'),
      'aria-invalid': control.getAttribute('aria-invalid'),
    }
    this.patched = { control, attributes, applied: { ...attributes } }
    this.syncNativeControl()
  }

  /** Keeps projected fields and plain controls in sync with field validation. */
  ngOnChanges(): void {
    this.context.set({
      id: this.fieldId(),
      describedBy: this.describedByTarget(),
      invalid: !!this.error,
    })
  }

  /** Merges validation with the projected control's latest native bindings. */
  ngAfterContentChecked(): void {
    this.syncNativeControl()
  }

  private syncNativeControl(): void {
    if (!this.patched) return
    const { control, attributes, applied } = this.patched
    for (const name of PATCHED_ATTRIBUTES) {
      const current = control.getAttribute(name)
      if (current !== applied[name]) attributes[name] = current
    }
    const next: FieldAttributes = {
      id: attributes.id || this.fieldId(),
      'aria-describedby': descriptionIds(attributes['aria-describedby'], this.describedByTarget()),
      'aria-invalid': this.error ? 'true' : attributes['aria-invalid'],
    }
    for (const name of PATCHED_ATTRIBUTES) {
      const value = next[name]
      if (control.getAttribute(name) === value) continue
      if (value === null) control.removeAttribute(name)
      else control.setAttribute(name, value)
    }
    this.patched.applied = next
    this.labelFor.set(control.id)
  }

  private unpatchNativeControl(): void {
    if (this.patched === null) return
    const { control, attributes, applied } = this.patched
    this.patched = null
    for (const name of PATCHED_ATTRIBUTES) {
      if (control.getAttribute(name) !== applied[name]) continue
      const value = attributes[name]
      if (value === null) control.removeAttribute(name)
      else control.setAttribute(name, value)
    }
  }

  /** Removes the context registration (unmount). */
  ngOnDestroy(): void {
    FormFieldDomContext.remove(this.host.nativeElement)
  }
}

(Member comments are shortened to their first sentence, and the 13 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/form-field.component.d.ts.)

Form

Form component.

The host is the <form> itself (form[mol-form]), exactly React's root. A rejected async handler renders an accessible server-error list by default; a new submit clears the previous failure. Native action/method forms keep native submission.

@Component({
  selector: 'form[mol-form]',
  standalone: true,
  inputs: [
    'onFormSubmit',
    'onSubmit',
    'onReset',
    'submitting',
    'submitError',
    'action',
    'method',
    'noValidate',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'className',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.action]': 'action ?? null',
    '[attr.method]': 'method ?? null',
    '[attr.novalidate]': 'noValidate ? "" : null',
    '(submit)': 'handleSubmit($event)',
    '(reset)': 'handleReset($event)',
  },
  template: `@if (messages().length > 0) {
      <ul role="alert" [class]="cm().formError">
        @for (message of messages(); track $index) {
          <li>{{ message }}</li>
        }
      </ul>
    }
    <fieldset
      [class]="cm().formFieldsetContents"
      [attr.disabled]="submitting || pending() ? '' : null"
    >
      <ng-content></ng-content>
    </fieldset>`,
})
export class Form implements HasElement<HTMLFormElement> {
  /** Collects the form's data on submit (React's `onFormSubmit`). */
  onFormSubmit?: ReactFormProps['onFormSubmit']
  /** Receives the submit event (React's `onSubmit`). */
  onSubmit?: ReactFormProps['onSubmit']
  /** Receives the reset event (React's `onReset`). */
  onReset?: ReactFormProps['onReset']
  /** Whether the form is submitting (disables the fieldset). */
  submitting?: ReactFormProps['submitting']
  /** Native form action. */
  action?: ReactFormProps['action']
  /** Native form method. */
  method?: ReactFormProps['method']
  /** Whether native validation is disabled. */
  noValidate?: ReactFormProps['noValidate']
  /** Extra classes for the form. */
  className?: ReactFormProps['className']
  /** Inline style object (React camelCase). */
  style?: ReactFormProps['style']
  /** `data-testid`. */
  testId?: ReactFormProps['testId']
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: ReactFormProps['automationId']
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** Whether a submit is in flight. */
  readonly pending = signal(false)
  /** The failure the last submit produced. */
  private readonly failure = signal<{ error: unknown } | null>(null)
  /** A submit counter: a later submit supersedes an earlier settling one. */
  private attempt = 0
  /** The controlled failure's current value. */
  private controlledError: unknown
  /** Whether the caller has written `submitError` (React's `Object.hasOwn`). */
  private controlled = false
  private readonly host: ElementRef<HTMLFormElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<form>`. */
  readonly element = hostElement(this.host)

  /**
   * A failure managed by an external form controller (React's `submitError`
   * prop).
   *
   * An accessor, not a field: Angular writes an input by assigning the
   * property, so the write itself is the "this prop was passed" signal React
   * reads with `Object.hasOwn(props, 'submitError')`. A caller that binds
   * `[submitError]` therefore owns the error UI — an explicit `undefined`
   * clears a failure the form captured itself.
   *
   * @returns The controlled failure, as the caller last wrote it.
   */
  get submitError(): ReactFormProps['submitError'] {
    return this.controlledError
  }

  /**
   * Records the caller's controlled failure (and that the caller passed one).
   *
   * @param value - The caller's failure, or `undefined` to clear the error UI.
   */
  set submitError(value: ReactFormProps['submitError']) {
    this.controlled = true
    this.controlledError = value
  }

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Serializes the form's inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * The error messages to announce (React's `submitError`/`failure` branch).
   * @returns The messages.
   */
  messages(): string[] {
    // React's `Object.hasOwn(props, 'submitError')` branch: once the caller
    // binds the input, it owns the error UI — an explicitly-undefined value
    // clears the list instead of falling back to a captured failure.
    const failure = this.controlled
      ? this.controlledError === undefined
        ? null
        : { error: this.controlledError }
      : this.failure()
    if (!failure) return []
    return formSubmitErrorMessages(
      failure.error,
      this.i18n.t('ui.form.submitError', undefined, {
        defaultValue: 'Unable to submit. Please try again.',
      }),
    )
  }

  /**
   * Handles a submit event: collects `FormData` for `onFormSubmit`, calls
   * both handlers, and tracks failure/pending (React's `handleSubmit`).
   *
   * @param event - The submit event.
   */
  async handleSubmit(event: Event): Promise<void> {
    if (!this.onFormSubmit && !this.onSubmit) return
    const current = ++this.attempt
    this.failure.set(null)
    this.pending.set(true)
    try {
      const submissions: Promise<void>[] = []
      const call = (handler: () => void | Promise<void>): void => {
        try {
          submissions.push(Promise.resolve(handler()))
        } catch (error) {
          submissions.push(Promise.reject(error))
        }
      }
      const form = event.currentTarget instanceof HTMLFormElement ? event.currentTarget : null
      if (this.onFormSubmit) {
        event.preventDefault()
        const entries = Array.from(new FormData(form ?? undefined))
        // `Object.fromEntries` defines every name as an own key: a repeated name
        // keeps its last value, and `__proto__` stays an ordinary field instead
        // of replacing the object's prototype.
        const data: Record<string, unknown> = Object.fromEntries(entries)
        // React reads `process.env.NODE_ENV`; Angular's CLI defines no such
        // global, and `isDevMode()` is false in its optimized (production) builds.
        if (isDevMode() && Object.keys(data).length < entries.length) {
          console.error(
            "Form.onFormSubmit received repeated field names and keeps only their last values. Use the form's onSubmit handler for repeated entries.",
          )
        }
        call(() => this.onFormSubmit?.(data))
      }
      call(() => this.onSubmit?.(event))
      await Promise.all(submissions)
    } catch (error) {
      if (this.attempt === current) this.failure.set({ error })
    } finally {
      if (this.attempt === current) this.pending.set(false)
    }
  }

  /**
   * Calls the reset handler (React's `onReset` through the rest spread).
   *
   * @param event - The reset event.
   */
  handleReset(event: Event): void {
    this.onReset?.(event)
  }
}

Icon

Icon component.

Renders an SVG glyph looked up by name from the bonded icon set. The host IS the <svg> (svg[mol-icon-root]). Extra attributes (data-mol-id, aria-label, role, …) land on the host — React's spread target — and switch the glyph out of decorative mode (no aria-hidden).

@Component({
  selector: 'svg[mol-icon-root]',
  standalone: true,
  inputs: ['name', 'size', 'className', 'ariaHidden: aria-hidden'],
  host: {
    '[attr.width]': 'attrSize()',
    '[attr.height]': 'attrSize()',
    '[attr.viewBox]': 'failed ? "0 0 20 20" : icon().viewBox || "0 0 20 20"',
    '[attr.fill]': 'failed ? "none" : fill()',
    '[attr.stroke]': 'strokeAttrs().stroke',
    '[attr.stroke-width]': 'strokeAttrs().strokeWidth',
    '[attr.stroke-linecap]': 'strokeAttrs().strokeLinecap',
    '[attr.stroke-linejoin]': 'strokeAttrs().strokeLinejoin',
    '[class]': 'className',
    '[attr.aria-hidden]': 'ariaHiddenAttr()',
    '[attr.focusable]': 'decorative() ? "false" : null',
  },
  template: `@if (failed) {
      <svg:circle cx="10" cy="10" r="8" fill="currentColor" opacity="0.15" />
    } @else {
      @for (p of paths(); track $index) {
        <svg:path
          [attr.d]="p.d"
          [attr.fill]="p.fill"
          [attr.fill-rule]="p.fillRule"
          [attr.clip-rule]="p.clipRule"
          [attr.opacity]="p.opacity"
        />
      }
    }`,
})
export class Icon implements OnChanges {
  /** The glyph name from the bonded icon set. */
  name!: IconProps['name']
  /** Width and height in pixels (default 20). */
  size?: IconProps['size'] = 20
  /** Class name forwarded to the `<svg>`. */
  className?: IconProps['className']
  /**
   * Explicit `aria-hidden` (React stringifies `false` to `"false"` rather
   * than dropping the attribute).
   */
  ariaHidden?: IconProps['aria-hidden']

  /** Whether the name is missing from the bonded set (placeholder renders). */
  failed = false

  /**
   * The rendered size (the default applies when a later-bound input writes
   * `undefined` over the field default, matching React's absent-prop default).
   * @returns The pixel size.
   */
  attrSize(): number {
    return this.size ?? 20
  }

  /**
   * Resolves the icon, warning once per render pass like React does.
   */
  ngOnChanges(): void {
    this.failed = false
    this.resolved = undefined
    try {
      this.resolved = getIcon(this.name)
    } catch (error) {
      console.warn(
        `Icon: no bonded glyph for "${String(this.name)}" — rendering a placeholder.`,
        error,
      )
      this.failed = true
    }
    const svg = this.resolved?.svg
    if (svg) (this.host.nativeElement as SVGSVGElement).innerHTML = svg
  }

  private resolved?: IconData

  /**
   * The resolved icon data (throws nothing; placeholder branch covers gaps).
   * @returns The icon data.
   */
  icon(): IconData {
    return this.resolved ?? { paths: [] }
  }

  /**
   * The fill attribute value (`none` for `icon.svg`-backed glyphs without an
   * explicit fill, matching React's two branches).
   * @returns The fill.
   */
  fill(): string {
    const icon = this.icon()
    if (icon.svg) return icon.fill || 'none'
    return icon.stroke ? 'none' : icon.fill || 'currentColor'
  }

  /**
   * Stroke attribute values (null when the icon is not stroked).
   * @returns The stroke attribute bag.
   */
  strokeAttrs(): {
    stroke: string | null
    strokeWidth: number | null
    strokeLinecap: string | null
    strokeLinejoin: string | null
  } {
    const icon = this.icon()
    if (!icon.stroke) {
      return { stroke: null, strokeWidth: null, strokeLinecap: null, strokeLinejoin: null }
    }
    return {
      stroke: icon.stroke ?? null,
      strokeWidth: icon.strokeWidth ?? null,
      strokeLinecap: icon.strokeLinecap ?? null,
      strokeLinejoin: icon.strokeLinejoin ?? null,
    }
  }

  /**
   * The glyph paths (empty for `icon.svg`-backed glyphs).
   * @returns The path list.
   */
  paths(): IconData['paths'] {
    return this.icon().svg ? [] : this.icon().paths
  }

  /**
   * Whether the glyph renders in decorative mode (no caller accessibility
   * props on the host).
   * @returns True when `aria-hidden` applies.
   */
  decorative(): boolean {
    const el = this.host.nativeElement
    return (
      !el.hasAttribute('aria-label') &&
      !el.hasAttribute('aria-labelledby') &&
      !el.hasAttribute('role')
    )
  }

  /**
   * The `aria-hidden` attribute value: an explicit value wins (React keeps
   * `aria-hidden={false}` as `"false"`), otherwise decorative mode applies.
   * @returns The attribute text or null.
   */
  ariaHiddenAttr(): string | null {
    if (this.ariaHidden !== undefined)
      return this.ariaHidden === true
        ? 'true'
        : this.ariaHidden === false
          ? 'false'
          : String(this.ariaHidden)
    return this.decorative() ? 'true' : null
  }

  /** The svg host element. */
  readonly host: ElementRef<SVGSVGElement> = inject(ElementRef)
}

Input

Input component.

The host is the field's outer wrapper React renders (the shared field layout's root, a flex column). React's text-input onChange fires on input events; a controlled value is restored after user input exactly like React's controlled-input state restore.

The adornment wrappers React renders conditionally ({!!leftElement && <div …>} / {(rightElement || (clearable && value)) && …}) are always-mounted <ng-content> capture points that are taken out of the DOM whenever React would render nothing (setElementPresent).

@Component({
  selector: 'div[mol-input]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg, NgTemplateOutlet],
  inputs: [
    'type',
    'size',
    'align',
    'label',
    'error',
    'hint',
    'externalDescription: aria-describedby',
    'externalInvalid: aria-invalid',
    'leftElement',
    'rightElement',
    'clearable',
    'clearLabel',
    'className',
    'style',
    'testId',
    'disabled',
    'required',
    'value',
    'defaultValue',
    'placeholder',
    'name',
    'id',
    'automationId',
    'dataMolId: data-mol-id',
    'onFocus',
    'onBlur',
    'onKeyDown',
  ],
  host: {
    '[class]': 'field().root',
  },
  template: `@if (label) {
      <label
        [attr.for]="inputId()"
        [class]="cm().cn(cm().label({ required: !!required }), cm().labelBlock)"
        >{{ label }}</label
      >
    }
    <div [class]="field().inner">
      <div [class]="cm().inputLeftElement" #leftSlot>
        <ng-content select="[slot=leftElement]"></ng-content>
        @if (asTemplate(leftElement); as tpl) {
          <ng-container [ngTemplateOutlet]="tpl" />
        } @else {
          {{ asText(leftElement) }}
        }
      </div>
      <input
        [attr.type]="type ?? 'text'"
        [attr.id]="inputId()"
        [attr.name]="name"
        [attr.value]="value ?? defaultValue"
        [attr.placeholder]="placeholder"
        [disabled]="disabled"
        [attr.required]="required ? '' : null"
        [attr.aria-invalid]="
          error || fieldContext()?.invalid ? true : (externalInvalid ?? hostAria.invalid() ?? false)
        "
        [attr.aria-describedby]="mergedDescribedBy()"
        [class]="classes()"
        [attr.style]="hostStyle()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        (input)="handleInput($event)"
        (change)="handleChange($event)"
        (focusin)="onFocus?.($event)"
        (focusout)="onBlur?.($event)"
        (keydown)="onKeyDown?.($event)"
        #inputEl
      />
      <div [class]="cm().inputRightElement" #rightSlot>
        @if (clearable && value) {
          <button
            type="button"
            [disabled]="disabled"
            (click)="handleClear($event)"
            [class]="cm().inputClearButton"
            [attr.aria-label]="clearText()"
          >
            <svg mol-icon [data]="clearIcon()" />
          </button>
        }
        <span [class]="cm().textMuted" #rightInner
          ><ng-content select="[slot=rightElement]"></ng-content>
          @if (asTemplate(rightElement); as tpl) {
            <ng-container [ngTemplateOutlet]="tpl" />
          } @else {
            {{ asText(rightElement) }}
          }
        </span>
      </div>
    </div>
    @if (error) {
      <p [attr.id]="describedBy()" [class]="cm().formError">{{ error }}</p>
    }
    @if (hint && !error) {
      <p [attr.id]="describedBy()" [class]="cm().formHint">{{ hint }}</p>
    }`,
})
export class Input implements AfterViewChecked, HasElement<HTMLInputElement> {
  type?: string
  size?: Size
  align?: 'left' | 'center' | 'right'
  label?: string
  error?: string
  hint?: string
  leftElement?: unknown
  rightElement?: unknown
  clearable?: boolean
  clearLabel?: string
  className?: string
  style?: Record<string, unknown>
  testId?: string
  disabled?: boolean
  required?: boolean
  value?: string | number
  defaultValue?: string | number
  placeholder?: string
  name?: string
  id?: string
  automationId?: string
  dataMolId?: string

  onFocus?: FocusEventHandler
  onBlur?: FocusEventHandler
  onKeyDown?: KeyboardEventHandler

  @Output() readonly change = new EventEmitter<Event & KitFieldChangeEvent>()
  @Output() readonly valueChange = new EventEmitter<string>()
  @Output() readonly clear = new EventEmitter<Event>()

  inputEl?: ElementRef<HTMLInputElement>
  @ViewChild('inputEl')
  set inputElQuery(ref: ElementRef<HTMLInputElement> | undefined) {
    this.inputEl = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLInputElement | null>(null)
  readonly element = this.inner.asReadonly()
  @ViewChild('leftSlot') leftSlot?: ElementRef<HTMLDivElement>
  @ViewChild('rightSlot') rightSlot?: ElementRef<HTMLDivElement>
  @ViewChild('rightInner') rightInner?: ElementRef<HTMLSpanElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  private readonly hasLeft = signal(false)
  private readonly hasRight = signal(false)

  constructor() {
    usePlacement((hasContent) => this.syncAdornments(hasContent))
  }

  private readonly generatedId = nextInstanceId()

  private readonly i18n = useTranslation()

  private movedRest = false
  externalDescription?: string | null
  externalInvalid?: AriaBoolean
  protected readonly hostAria = new FieldHostAria()
  private externalMolId: string | undefined

  cm(): UIClassMap {
    return getClassMap()
  }

  field(): ReturnType<typeof fieldLayout> {
    return fieldLayout(this.cm())
  }

  inputId(): string {
    const externalId = !this.label && !this.hint && !this.error ? this.name : undefined
    return this.id || this.fieldContext()?.id || externalId || this.generatedId
  }

  describedBy(): string | null {
    const id = this.fieldContext()?.id === this.inputId() ? this.generatedId : this.inputId()
    return this.error ? `${id}-error` : this.hint ? `${id}-hint` : null
  }

  fieldContext(): FormFieldContext | null {
    return fieldContext(this.host.nativeElement)
  }

  mergedDescribedBy(): string | null {
    return descriptionIds(
      this.externalDescription ?? this.hostAria.description(),
      this.fieldContext()?.describedBy,
      this.describedBy(),
    )
  }

  classes(): string {
    return this.cm().cn(
      this.cm().input({
        error: !!this.error,
        size: this.size ?? 'md',
        align: this.align === 'right' ? undefined : this.align,
      }),
      this.hasLeft() && this.cm().inputPadLeft,
      (this.hasRight() || this.clearable) && this.cm().inputPadRight,
      this.className,
    )
  }

  clearText(): string {
    return this.clearLabel ?? this.i18n.t('ui.input.clear', undefined, { defaultValue: 'Clear' })
  }

  clearIcon(): ResolvedIcon {
    return resolveIcon('x-mark', this.cm().iconSm)
  }

  hostStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  handleInput(event: Event): void {
    if (!isFieldChangeEvent(event)) return
    event.stopPropagation()
    this.change.emit(event)
    const input = this.inputEl?.nativeElement
    if (input) this.valueChange.emit(input.value)
    if (this.value !== undefined && input && input.value !== String(this.value))
      input.value = String(this.value)
  }

  handleClear(event: MouseEvent): void {
    this.clear.emit(event)
    this.valueChange.emit('')
  }

  handleChange(event: Event): void {
    event.stopPropagation()
  }

  ngAfterViewChecked(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.inputEl?.nativeElement ?? this.host.nativeElement.querySelector('input'),
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
  }

  private syncAdornments(hasContent: SlotReader): void {
    const left = this.leftSlot?.nativeElement
    const right = this.rightSlot?.nativeElement
    const inner = this.rightInner?.nativeElement ?? right?.querySelector('span') ?? undefined
    const hasLeft = this.isGiven(this.leftElement) || hasContent(left)
    const hasRight = this.isGiven(this.rightElement) || hasContent(inner)
    this.hasLeft.set(hasLeft)
    this.hasRight.set(hasRight)
    const clear = !!(this.clearable && this.value)
    setElementPresent(left, hasLeft)
    setElementPresent(inner, hasRight && !clear)
    setElementPresent(right, hasRight || clear)
  }
// … truncated — 4 more members: ngDoCheck, asTemplate, asText, isGiven; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/input.component.d.ts

(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/input.component.d.ts.)

Label

Label component.

A <label> with the class map's label styles; required switches to the required variant and htmlFor renders the for attribute.

@Component({
  selector: 'label[mol-label]',
  standalone: true,
  hostDirectives: [{ directive: ElementLanguage, inputs: ['lang'] }],
  inputs: ['required', 'className', 'htmlFor'],
  host: {
    '[class]': 'classes()',
    '[attr.for]': 'htmlFor',
  },
  template: `<ng-content></ng-content>`,
})
export class Label implements HasElement<HTMLLabelElement> {
  private readonly host: ElementRef<HTMLLabelElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<label>`. */
  readonly element = hostElement(this.host)

  /** Whether the label renders its required marker. */
  required?: boolean
  /** Extra classes. */
  className?: string
  /** The associated control's id (`for` attribute). */
  htmlFor?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the label class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().label({ required: !!this.required }), this.className)
  }
}

LanguagePicker

LanguagePicker component.

React's root is a FRAGMENT (trigger button + locale modal), so everything the host holds renders in front of the host (placeContentBefore) and the host itself leaves the page: the rendered tree is React's, with no wrapper element around the trigger. Rest props (title, data-*, aria-*, native event handlers) are spread onto the trigger button in React; here they land on the host and are moved onto it.

@Component({
  selector: 'mol-language-picker',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Icon, Modal, MolTemplateOutlet],
  inputs: [
    'labelKey',
    'labelDefault',
    'modalTitleKey',
    'modalTitleDefault',
    'icon',
    'iconSize',
    'display',
    'className',
    'style',
    'testId',
    'automationId',
    'renderTrigger',
  ],
  template: `@if (asTemplate(renderTrigger); as customTrigger) {
      <ng-container
        [molTemplateOutlet]="customTrigger"
        [molTemplateOutletContext]="triggerContext"
      ></ng-container>
    } @else {
      <button
        #trigger
        type="button"
        [attr.data-mol-id]="automationId ?? 'language-picker-trigger'"
        [attr.data-testid]="testId"
        [attr.aria-label]="ariaLabel()"
        (click)="open()"
        [class]="classes()"
        [style]="hostStyle()"
      >
        <svg mol-icon-root [name]="icon ?? 'globe'" [size]="iconSize ?? 16"></svg>
        @if (triggerLabel(); as label) {
          <span>{{ label }}</span>
        }
      </button>
    }
    <mol-modal
      [open]="isOpen()"
      (close)="isOpen.set(false)"
      [title]="modalTitle()"
      [size]="'lg'"
      data-mol-id="language-picker-modal"
      ><div [class]="cm().languageGrid">
        @for (locale of sortedLocales(); track locale.code) {
          <button
            type="button"
            [attr.data-mol-id]="'language-picker-option-' + locale.code"
            [attr.data-active]="locale.code === currentLocale() ? 'true' : null"
            [attr.aria-pressed]="locale.code === currentLocale() ? 'true' : 'false'"
            (click)="pick(locale.code)"
            [class]="locale.code === currentLocale() ? cm().languageActive : cm().languageOption"
          >
            {{ locale.name }}
          </button>
        }
      </div></mol-modal
    >`,
})
export class LanguagePicker {
  /** i18n key for the trigger label / aria-label (default `footer.language`). */
  labelKey?: LanguagePickerProps['labelKey']
  /** Fallback label if the i18n key is missing (default `Language`). */
  labelDefault?: LanguagePickerProps['labelDefault']
  /** i18n key for the modal title (default `languagePicker.modalTitle`). */
  modalTitleKey?: LanguagePickerProps['modalTitleKey']
  /** Fallback modal title if the i18n key is missing (default `Choose language`). */
  modalTitleDefault?: LanguagePickerProps['modalTitleDefault']
  /** Icon glyph before the current locale name (default `globe`). */
  icon?: LanguagePickerProps['icon']
  /** Pixel size for the rendered icon (default 16). */
  iconSize?: LanguagePickerProps['iconSize']
  /** What the trigger renders: the locale name, its code, or the icon only. */
  display?: LanguagePickerProps['display'] = 'name'
  /** Extra classes appended to the trigger button. */
  className?: LanguagePickerProps['className']
  /** Inline style object for the trigger button (React camelCase). */
  style?: LanguagePickerProps['style']
  /** `data-testid` for the trigger button. */
  testId?: LanguagePickerProps['testId']
  /** `data-mol-id` for the trigger button (React's `automationId`). */
  automationId?: LanguagePickerProps['automationId']
  /** Optional trigger replacement (a node value rendered as a template). */
  renderTrigger?: LanguagePickerProps['renderTrigger']

  /**
   * The context a `renderTrigger` template receives: `open` (also as
   * `$implicit`), React's `renderTrigger(open)` argument.
   */
  readonly triggerContext: Record<string, unknown> = {
    $implicit: (): void => this.open(),
    open: (): void => this.open(),
  }

  /** The default trigger button. */
  @ViewChild('trigger') trigger?: ElementRef<HTMLButtonElement>

  /** Whether the locale modal is open. */
  readonly isOpen = signal(false)

  /**
   * i18n state: locale, locale list and the async setter. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  /**
   * Renders everything the host holds (the trigger, or the caller's
   * `renderTrigger` output, and the locale modal) in front of the host, which
   * leaves the page: React's root is a fragment. What the caller binds on the
   * tag lands on the trigger button, React's `{...rest}` target.
   */
  constructor() {
    usePlacement(() => {
      const host = this.host.nativeElement
      placeContentBefore(host, host)
      setElementPresent(host, false)
      setHostRoot(host, this.trigger?.nativeElement)
    })
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The trigger's accessible label.
   * @returns The label text.
   */
  ariaLabel(): string {
    return this.i18n.t(
      this.labelKey ?? 'footer.language',
      {},
      {
        defaultValue: this.labelDefault ?? 'Language',
      },
    )
  }

  /**
   * The modal title.
   * @returns The title text.
   */
  modalTitle(): string {
    return this.i18n.t(
      this.modalTitleKey ?? 'languagePicker.modalTitle',
      {},
      {
        defaultValue: this.modalTitleDefault ?? 'Choose language',
      },
    )
  }

  /**
   * The trigger's class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().languagePickerTrigger, this.className)
  }

  /**
   * Serializes the trigger's inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * Narrows a node-valued prop to a TemplateRef.
   *
   * @param value - The prop value.
   * @returns The template, or null.
   */
  asTemplate(value: unknown): TemplateRef<unknown> | null {
    return value instanceof TemplateRef ? value : null
  }

  /**
   * The active locale code.
   * @returns The code.
   */
  currentLocale(): string {
    return this.i18n.locale()
  }

  /**
   * The registered locales, sorted by native name (React sorts a copy).
   * @returns The sorted locales.
   */
  sortedLocales(): { code: string; name: string }[] {
    return [...this.i18n.locales()].sort((a, b) => a.name.localeCompare(b.name))
  }

  /**
   * The trigger's text (React's `display` switch).
   * @returns The text, or null for the icon-only display.
   */
  triggerLabel(): string | null {
    if (this.display === 'icon') return null
    if (this.display === 'code') return this.currentLocale()
    const current = this.sortedLocales().find((locale) => locale.code === this.currentLocale())
    return current?.name ?? this.currentLocale()
  }

  /** Opens the locale modal. */
  open(): void {
    this.isOpen.set(true)
  }

  /**
   * Switches the locale and closes the modal (React's option click).
   * @param code - The locale code.
   */
  async pick(code: string): Promise<void> {
    await this.i18n.setLocale(code)
    this.isOpen.set(false)
  }
}

Container

Container component.

Centers a max-width content column; rest props land on the host element.

@Component({
  selector: 'div[mol-container]',
  standalone: true,
  inputs: [
    'maxWidth',
    'centered',
    'paddingX',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<ng-content></ng-content>`,
})
export class Container implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Maximum width preset or CSS length. */
  maxWidth: NonNullable<ContainerProps['maxWidth']> = 'lg'
  /** Whether the column is centered. */
  centered = true
  /** Horizontal padding (accepted for React parity, not rendered). */
  paddingX?: ContainerProps['paddingX']
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the container class list.
   * @returns The class string.
   */
  classes(): string {
    const namedWidth = isContainerSize(this.maxWidth) ? this.maxWidth : undefined
    return this.cm().cn(
      this.cm().container(namedWidth ? { size: namedWidth } : undefined),
      this.centered && this.cm().mxAuto,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const customWidth = !isContainerSize(this.maxWidth) && this.maxWidth ? this.maxWidth : undefined
    const merged = customWidth ? { maxWidth: customWidth, ...this.style } : this.style
    return styleText(merged)
  }
}

Flex

Flex container component.

A numeric or non-preset string gap becomes an inline style.

@Component({
  selector: 'div[mol-flex]',
  standalone: true,
  inputs: [
    'direction',
    'justify',
    'align',
    'wrap',
    'gap',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<ng-content></ng-content>`,
})
export class Flex implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Flex direction. */
  direction: 'row' | 'column' | 'row-reverse' | 'column-reverse' = 'row'
  /** Main-axis justification. */
  justify?: FlexProps['justify']
  /** Cross-axis alignment. */
  align?: FlexProps['align']
  /** Wrapping behavior. */
  wrap?: FlexProps['wrap']
  /** Gap (preset name, number in px, or any CSS value). */
  gap?: number | string
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the flex class list.
   * @returns The class string.
   */
  classes(): string {
    const cmGap = GAP_NAMES.find((name) => name === this.gap)
    return this.cm().cn(
      this.cm().flex({
        direction: DIRECTION_MAP[this.direction] || 'row',
        align: this.align,
        justify: this.justify,
        wrap: this.wrap,
        gap: cmGap,
      }),
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style (numeric or custom gaps inline).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const gapStyle =
      typeof this.gap === 'number'
        ? { gap: this.gap }
        : typeof this.gap === 'string' && !GAP_NAMES.some((name) => name === this.gap)
          ? { gap: this.gap }
          : undefined
    return styleText({ ...this.style, ...gapStyle })
  }
}

Grid

Grid container component.

Numeric columns maps to the class map; a string is a grid-template-columns value. gap/columnGap/rowGap follow the same preset-or-CSS rule as Flex.

@Component({
  selector: 'div[mol-grid]',
  standalone: true,
  inputs: [
    'columns',
    'rows',
    'gap',
    'columnGap',
    'rowGap',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<ng-content></ng-content>`,
})
export class Grid implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Column count or `grid-template-columns` value. */
  columns?: number | string
  /** `grid-template-rows` value. */
  rows?: string
  /** Gap (preset name, number in px, or any CSS value). */
  gap?: number | string
  /** Column gap. */
  columnGap?: number | string
  /** Row gap. */
  rowGap?: number | string
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the grid class list.
   * @returns The class string.
   */
  classes(): string {
    const cmGap = GAP_NAMES.find((name) => name === this.gap)
    return this.cm().cn(
      this.cm().grid({
        cols: typeof this.columns === 'number' ? this.columns : undefined,
        gap: cmGap,
      }),
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    // Only the values this Grid sets, as React's Grid does: an undefined key would erase the same
    // property from the caller's `style`.
    const own: Record<string, unknown> = {}
    if (typeof this.columns === 'string') own.gridTemplateColumns = this.columns
    if (typeof this.rows === 'string') own.gridTemplateRows = this.rows
    if (
      typeof this.gap === 'number' ||
      (typeof this.gap === 'string' && !GAP_NAMES.some((name) => name === this.gap))
    )
      own.gap = this.gap
    if (typeof this.columnGap === 'number' || typeof this.columnGap === 'string')
      own.columnGap = this.columnGap
    if (typeof this.rowGap === 'number' || typeof this.rowGap === 'string') own.rowGap = this.rowGap
    return styleText({ ...this.style, ...own })
  }
}

Spacer

Spacer component.

A preset size uses the class map; a number (px) or custom CSS value uses inline width/height.

@Component({
  selector: 'div[mol-spacer]',
  standalone: true,
  inputs: [
    'size',
    'horizontal',
    'className',
    'style',
    'testId',
    'ariaHidden: aria-hidden',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.aria-hidden]': 'ariaHiddenAttr()',
  },
  template: '',
})
export class Spacer implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Spacer size (preset name, number in px, or CSS value). */
  size: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | number | string = 'md'
  /** Whether the spacer takes width instead of height. */
  horizontal?: boolean
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** Explicit `aria-hidden` (React stringifies booleans). */
  ariaHidden?: boolean | string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The `aria-hidden` attribute value (React renders `true` as `"true"`).
   * @returns The attribute text or null.
   */
  ariaHiddenAttr(): string | null {
    if (this.ariaHidden === undefined) return null
    return this.ariaHidden === true
      ? 'true'
      : this.ariaHidden === false
        ? 'false'
        : String(this.ariaHidden)
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Whether `size` is one of the class map's named sizes.
   * @returns True for preset names.
   */
  get isNamedSize(): boolean {
    return SPACER_SIZES.some((name) => name === this.size)
  }

  /**
   * Computes the spacer class list.
   * @returns The class string.
   */
  classes(): string {
    const namedSize = SPACER_SIZES.find((name) => name === this.size)
    return this.cm().cn(
      namedSize
        ? this.cm().spacer({
            size: namedSize,
            horizontal: !!this.horizontal,
          })
        : this.horizontal
          ? this.cm().displayInlineBlock
          : this.cm().displayBlock,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const sizeStyle =
      typeof this.size === 'number'
        ? this.horizontal
          ? { width: this.size, height: '1px' }
          : { height: this.size, width: '1px' }
        : typeof this.size === 'string' && !this.isNamedSize
          ? this.horizontal
            ? { width: this.size }
            : { height: this.size }
          : undefined
    return styleText({ ...this.style, ...sizeStyle })
  }
}

LoadErrorBanner

LoadErrorBanner component.

The host is the root <div> (div[mol-load-error-banner]); rest props (className, data-*, aria-*, id) land on it exactly as React spreads them. message, detail and retryLabel are node-valued props, projected as [slot=message] / [slot=detail] / [slot=retryLabel]. The detail paragraph and the retry row render only when React would render them.

@Component({
  selector: 'div[mol-load-error-banner]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Alert, MolTemplateOutlet],
  inputs: ['message', 'detail', 'retryLabel', 'retryMolId', 'onRetry', 'testId', 'automationId'],
  host: {
    '[class]': 'className',
    '[attr.data-testid]': 'testId',
  },
  template: `<div mol-alert [status]="'error'" [live]="false">
    <div [class]="cm().stack(2)">
      <p [class]="cm().textSize('sm')">
        <ng-container [molTemplateOutlet]="asTemplate(message)"></ng-container
        ><ng-content select="[slot=message]"></ng-content>{{ nodeText(message) }}
      </p>
      <p #detailSlot [class]="detailClasses()">
        <ng-container [molTemplateOutlet]="asTemplate(detail)"></ng-container
        ><ng-content select="[slot=detail]"></ng-content>{{ nodeText(detail) }}
      </p>
      <ng-content></ng-content>
      <div #retrySlot [class]="cm().flex({ justify: 'start' })">
        <button
          type="button"
          [class]="retryClasses()"
          [attr.aria-busy]="'false'"
          [disabled]="pending()"
          [attr.data-mol-id]="retryMolId"
          (click)="handleRetry()"
        >
          <span #retryLabelSlot><ng-content select="[slot=retryLabel]"></ng-content></span>
          @if (!hasRetryLabel() && isGiven(retryLabel)) {
            <ng-container [molTemplateOutlet]="asTemplate(retryLabel)"></ng-container
            >{{ nodeText(retryLabel) }}
          } @else if (!hasRetryLabel()) {
            {{ retryText() }}
          }
        </button>
      </div>
    </div>
  </div>`,
})
export class LoadErrorBanner implements AfterViewChecked {
  /** The primary error line (node-valued prop). */
  message?: LoadErrorBannerProps['message']
  /** Secondary line under the message (node-valued prop). */
  detail?: LoadErrorBannerProps['detail']
  /** Retry-button label (node-valued prop). */
  retryLabel?: LoadErrorBannerProps['retryLabel']
  /** `data-mol-id` for the retry button (default `load-error-retry`). */
  retryMolId?: LoadErrorBannerProps['retryMolId'] = 'load-error-retry'
  /** Called when Retry is clicked; a returned promise keeps the button pending. */
  onRetry?: LoadErrorBannerProps['onRetry']
  /** Extra classes for the root (React's rest `className`). */
  className?: LoadErrorBannerProps['className']
  /** `data-testid` for the root. */
  testId?: LoadErrorBannerProps['testId']
  /** `data-mol-id` for the root (React's `automationId`). */
  automationId?: LoadErrorBannerProps['automationId']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText
  /** Whether a node-valued prop was given. */
  readonly isGiven = isGiven

  /** Whether a retry is in flight. */
  readonly pending = signal(false)

  /** The detail paragraph (always in the template; detached when unused). */
  @ViewChild('detailSlot') detailSlot?: ElementRef<HTMLParagraphElement>
  /** The retry row (always in the template; detached when no callback). */
  @ViewChild('retrySlot') retrySlot?: ElementRef<HTMLDivElement>
  /** The retry label capture point. */
  @ViewChild('retryLabelSlot') retryLabelSlot?: ElementRef<HTMLSpanElement>

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /** The host element, which is React's root `<div>`. */
  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /** The `data-mol-id` this component last wrote (React's `automationId` wins over a rest `data-mol-id`). */
  private lastWrittenMolId: string | null = null

  /**
   * Applies React's `rootProps` precedence on the root: a rest `data-mol-id`
   * bound on the tag stays, and `automationId` overrides it when given (and
   * leaves no stale value once cleared).
   */
  ngAfterViewChecked(): void {
    const host = this.host.nativeElement
    const current = host.getAttribute('data-mol-id')
    if (this.automationId !== undefined) {
      if (current !== this.automationId) host.setAttribute('data-mol-id', this.automationId)
      this.lastWrittenMolId = this.automationId
      return
    }
    if (current !== null && current === this.lastWrittenMolId) host.removeAttribute('data-mol-id')
    this.lastWrittenMolId = null
  }

  /** Whether the projected retry label exists (a signal the placement function sets). */
  private readonly hasRetryLabel = signal(false)

  /** Reconciles the detail/retry wrappers and the projected retry label. */
  constructor() {
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The detail paragraph classes.
   * @returns The class string.
   */
  detailClasses(): string {
    return this.cm().cn(this.cm().textSize('xs'), this.cm().textMuted)
  }

  /**
   * The retry button classes (React renders `Button variant="outline" size="sm"`).
   * @returns The class string.
   */
  retryClasses(): string {
    return this.cm().button({ variant: 'outline', color: 'primary', size: 'sm' })
  }

  /**
   * The retry button's text: the projected label, or the localized default.
   * @returns The default text (empty while a projected label is shown).
   */
  retryText(): string {
    return this.pending()
      ? this.i18n.t('loadError.retrying', {}, { defaultValue: 'Retrying…' })
      : this.i18n.t('loadError.retry', {}, { defaultValue: 'Retry' })
  }

  /**
   * Runs the retry callback with React's pending semantics: disabled and
   * "Retrying…" while the promise is unsettled; a rejection is not swallowed
   * — the banner stays for the caller.
   */
  handleRetry(): void {
    if (!this.onRetry || this.pending()) return
    this.pending.set(true)
    void Promise.resolve(this.onRetry())
      .catch((_error: unknown) => undefined)
      .finally(() => this.pending.set(false))
  }

  /**
   * Applies React's detail/retry conditions and moves the projected retry
   * label onto the retry button.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private reconcile(hasContent: SlotReader): void {
    const retryLabelSlot = this.retryLabelSlot?.nativeElement
    this.hasRetryLabel.set(hasContent(retryLabelSlot))
    setElementPresent(retryLabelSlot, false)
    setElementPresent(this.detailSlot?.nativeElement, this.detailPresent(hasContent))
    // React renders the retry row exactly when `onRetry` is given.
    setElementPresent(this.retrySlot?.nativeElement, !!this.onRetry)
    this.showRetryLabel()
  }

  /**
   * Whether React would render the detail paragraph (a given node value or
   * projected slot content).
   *
   * @param hasContent - Reads whether a slot has content.
   * @returns True when the detail renders.
   */
  private detailPresent(hasContent: SlotReader): boolean {
    return isGiven(this.detail) || hasContent(this.detailSlot?.nativeElement)
  }

  /** Moves the projected retry label onto the retry button (React: no wrapper). */
  private showRetryLabel(): void {
    const host = this.retrySlot?.nativeElement?.querySelector('button')
    const span = this.retryLabelSlot?.nativeElement
    if (!host || !span) return
    if (!this.hasRetryLabel()) {
      placeContent(span, null)
      return
    }
    placeContent(span, host)
  }
}

Modal component.

React's root is a FRAGMENT portaled into document.body (an overlay <div> and a centering wrapper <div>), so the host element leaves the page and both elements are moved into the body while open: the rendered tree is React's, with no wrapper at the component's place. Implements the WAI-ARIA APG modal dialog pattern (focus into the dialog on open, trapped Tab, focus restored on close, Escape for the topmost dialog only, reference-counted body scroll lock).

Projected content is created with the consumer's view, so a closed modal's body and footer exist while hidden: their components, effects and fetches run. React mounts them only while shown, and again each time they show. Write content with state as *molLazy (MolLazy from @molecule/app-angular): it is created when it shows and destroyed when it hides, as React's is.

@Component({
  selector: 'mol-modal',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg],
  inputs: [
    'open',
    'title',
    'size',
    'showCloseButton',
    'closeOnOverlayClick',
    'closeOnEscape',
    'footer',
    'centered',
    'closeLabel',
    'preventScroll',
    'initialFocus',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'onDoubleClick',
  ],
  outputs: ['close'],
  template: `<div #overlay [class]="cm().dialogOverlay" aria-hidden="true"></div>
    <div
      #wrapper
      [class]="cm().dialogWrapper"
      [style]="wrapperStyle()"
      role="presentation"
      (click)="handleOverlayClick($event)"
    >
      <div
        #dialog
        role="dialog"
        aria-modal="true"
        [attr.aria-labelledby]="title ? titleId : null"
        tabindex="-1"
        [class]="dialogClasses()"
        [style]="dialogStyle()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        (dblclick)="onDoubleClick?.($event)"
      >
        @if (title) {
          <div [class]="cm().dialogHeader">
            <h2 [id]="titleId" [class]="cm().dialogTitle">{{ title }}</h2>
            @if (showCloseButton) {
              <button
                type="button"
                (click)="requestCloseFromButton($event)"
                [class]="cm().dialogClose"
                data-mol-id="modal-close"
                [attr.aria-label]="closeText()"
              >
                <svg mol-icon [data]="closeIcon()" />
              </button>
            }
          </div>
        } @else {
          @if (showCloseButton) {
            <button
              type="button"
              (click)="requestCloseFromButton($event)"
              [class]="cm().dialogCloseFloating"
              data-mol-id="modal-close"
              [attr.aria-label]="closeText()"
            >
              <svg mol-icon [data]="closeIcon()" />
            </button>
          }
        }
        <div [class]="cm().dialogBody"><ng-content></ng-content></div>
        <div #footerSlot [class]="cm().dialogFooter">
          <ng-content select="[slot=footer]"></ng-content>
        </div>
      </div>
    </div>`,
})
export class Modal
  implements AfterViewInit, AfterViewChecked, DoCheck, OnDestroy, HasElement<HTMLDivElement>
{
  /** Whether the dialog is open. */
  open = false
  /** The dialog title. */
  title?: string
  /** Dialog width preset. */
  size: ModalSize = 'md'
  showCloseButton = true
  closeOnOverlayClick = true
  /** Whether Escape closes the dialog. */
  closeOnEscape = true
  /** Footer content (node-valued prop). */
  footer?: unknown
  centered = true
  /** The close button's accessible label. */
  closeLabel?: string
  preventScroll = true
  initialFocus?: OverlayTarget
  /** Extra classes for the dialog. */
  className?: string
  style?: Record<string, unknown>
  /** `data-testid` for the dialog. */
  testId?: string
  automationId?: string
  dataMolId?: string
  onDoubleClick?: MouseEventHandler

  @Output() readonly close = new EventEmitter<MouseEvent | undefined>()

  @ViewChild('overlay') overlay?: ElementRef<HTMLDivElement>
  @ViewChild('wrapper') wrapper?: ElementRef<HTMLDivElement>
  /** The dialog element. */
  @ViewChild('dialog', { static: true }) dialog?: ElementRef<HTMLDivElement>
  @ViewChild('footerSlot') footerSlot?: ElementRef<HTMLDivElement>

  readonly titleId = `mol-modal-title-${++modalInstance}`
  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))
  private readonly environmentInjector = inject(EnvironmentInjector)
  private readonly layer = new OverlayLayer((focus) => {
    if (!this.environmentInjector.destroyed)
      afterNextRender({ read: focus }, { injector: this.environmentInjector })
  })
  private readonly inner = signal<HTMLDivElement | null>(null)
  readonly element = this.inner.asReadonly()

  constructor() {
    usePlacement((hasContent) => this.reconcileFooter(hasContent))
  }

  private readonly i18n = useTranslation()

  private lastOpen: boolean | undefined
  private lastFooter = false
  private externalMolId: string | undefined

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The dialog class list. */
  dialogClasses(): string {
    return this.cm().cn(this.cm().modal({ size: this.size }), this.className)
  }

  /** Serializes the dialog's inline style. */
  dialogStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  wrapperStyle(): string | null {
    return styleText(this.centered ? undefined : { alignItems: 'flex-start' })
  }

  /** The close button's accessible label. */
  closeText(): string {
    return this.closeLabel ?? this.i18n.t('ui.modal.close', undefined, { defaultValue: 'Close' })
  }

  /** The close button's X glyph. */
  closeIcon(): ResolvedIcon {
    return resolveIcon('x-mark', this.cm().iconMd)
  }

  handleOverlayClick(event: MouseEvent): void {
    if (event.target !== event.currentTarget) {
      event.stopPropagation()
      return
    }
    this.layer.dismissBackdrop()
  }

  requestClose(): void {
    this.close.emit()
  }

  requestCloseFromButton(event: MouseEvent): void {
    this.close.emit(event)
  }

  ngAfterViewInit(): void {
    const dialog = this.dialog?.nativeElement
    if (dialog) {
      adoptHostDataMolId(
        this.host.nativeElement,
        dialog,
        (id) => {
          this.externalMolId = id
        },
        () => this.molId(),
      )
    }
    this.syncOpen()
  }

  ngDoCheck(): void {
    this.syncOpen()
  }

  ngAfterViewChecked(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.dialog?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
  }

  ngOnDestroy(): void {
    this.layer.release()
  }

  private reconcileFooter(hasContent: SlotReader): void {
    this.lastFooter = hasContent(this.footerSlot?.nativeElement)
    setElementPresent(this.footerSlot?.nativeElement, this.lastFooter)
    setElementPresent(this.host.nativeElement, false)
    setHostRoot(this.host.nativeElement, this.wrapper ? this.dialog?.nativeElement : null, {
      except: ['data-mol-id'],
    })
  }

  private syncOpen(): void {
    const dialog = this.dialog?.nativeElement
    if (!dialog) return
    const open = !!this.open
    if (open && this.browser) this.syncLayer(dialog)
    if (!this.wrapper) return

    if (open !== this.lastOpen) {
      this.lastOpen = open
      if (open) this.attachPortal()
      else {
        this.layer.release()
        this.detachPortal()
      }
    }
  }

  private syncLayer(dialog: HTMLDivElement): void {
    this.layer.sync({
      open: true,
      kind: 'modal',
      surface: { current: dialog },
      dismissKey: this.closeOnEscape,
      dismissBackdrop: this.closeOnOverlayClick,
      focus: { trap: true, initial: this.initialFocus, restore: 'opener' },
      lockScroll: this.preventScroll,
      onDismiss: () => this.requestClose(),
    })
  }

  private attachPortal(): void {
    const overlay = this.overlay?.nativeElement
    const wrapper = this.wrapper?.nativeElement
    if (!overlay || !wrapper) return
    if (this.browser) {
      const { body } = wrapper.ownerDocument
      placeElement(overlay, body)
      placeElement(wrapper, body)
    } else {
      placeElementBefore(overlay, this.host.nativeElement)
      placeElementBefore(wrapper, this.host.nativeElement)
    }
    this.inner.set(this.dialog?.nativeElement ?? null)
  }

  private detachPortal(): void {
    placeElement(this.overlay?.nativeElement, null)
    setElementPresent(this.overlay?.nativeElement, false)
    placeElement(this.wrapper?.nativeElement, null)
    setElementPresent(this.wrapper?.nativeElement, false)
    this.inner.set(null)
  }
}

(Member comments are shortened to their first sentence, and the 37 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/modal.component.d.ts.)

MoleculeAlert

Angular Alert UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-alert',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div role="alert" [class]="alertClasses" [style]="style" [attr.data-testid]="testId">
      @if (showIcon) {
        <span [class]="cm.alertIconWrapper">
          <span [innerHTML]="statusIconSvg"></span>
        </span>
      }
      <div [class]="cm.alertContent">
        @if (title) {
          <h5 [class]="titleClass">{{ title }}</h5>
        }
        <div [class]="descriptionClass">
          <ng-content></ng-content>
        </div>
      </div>
      @if (dismissible) {
        <button
          type="button"
          (click)="dismiss.emit()"
          [class]="cm.alertDismiss"
          [attr.aria-label]="dismissAriaLabel"
        >
          <span [innerHTML]="dismissIconSvg"></span>
        </button>
      }
    </div>
  `,
})
/**
 * Molecule Alert class.
 * @deprecated Use the React-named component `Alert` instead.
 */
export class MoleculeAlert {
  @Input() title?: string
  @Input() status: ColorVariant = 'info'
  @Input() variant?: 'solid' | 'subtle' | 'outline' | 'left-accent'
  @Input() dismissible = false
  @Input() dismissLabel?: string
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  @Output() dismiss = new EventEmitter<void>()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the accessible dismiss button label.
   * @returns The localized aria-label for the dismiss button.
   */
  get dismissAriaLabel(): string {
    return (
      this.dismissLabel || this.i18n.t('ui.alert.dismiss', undefined, { defaultValue: 'Dismiss' })
    )
  }

  /**
   * Retrieves the CSS class for the alert title.
   * @returns The title class name string.
   */
  get titleClass(): string {
    return this.cm.alertTitle
  }

  /**
   * Retrieves the CSS class for the alert description.
   * @returns The description class name string.
   */
  get descriptionClass(): string {
    return this.cm.alertDescription
  }

  /**
   * Determines the icon type based on the alert status.
   * @returns The mapped icon type string.
   */
  get iconType(): string {
    return statusVariantMap[this.status] || 'default'
  }

  /**
   * Determines whether the status icon should be shown.
   * @returns True if the icon type is not default.
   */
  get showIcon(): boolean {
    return this.iconType !== 'default'
  }

  private statusIconMap: Record<string, IconName> = {
    info: 'info-circle',
    success: 'check-circle',
    warning: 'exclamation-triangle',
    error: 'x-circle',
  }

  /**
   * Generates the SVG markup for the status icon.
   * @returns The SVG string for the current status icon.
   */
  get statusIconSvg(): string {
    const name = this.statusIconMap[this.iconType]
    return name ? getIconSvg(name, this.cm.iconMd) : ''
  }

  /**
   * Generates the SVG markup for the dismiss icon.
   * @returns The SVG string for the dismiss button icon.
   */
  get dismissIconSvg(): string {
    return getIconSvg('x-mark', this.cm.iconSm)
  }

  /**
   * Computes the combined CSS classes for the alert container.
   * @returns The alert container class name string.
   */
  get alertClasses(): string {
    const cmVariant = statusVariantMap[this.status] || 'default'
    return this.cm.cn(this.cm.alert({ variant: cmVariant }), this.className)
  }
}

MoleculeBadge

Angular Badge UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-badge',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <span [class]="badgeClasses" [style]="style" [attr.data-testid]="testId">
      <ng-content></ng-content>
    </span>
  `,
})
/**
 * Molecule Badge class.
 * @deprecated Use the React-named component `Badge` instead.
 */
export class MoleculeBadge {
  @Input() color: ColorVariant = 'primary'
  @Input() variant: 'solid' | 'outline' | 'subtle' = 'solid'
  @Input() size?: Size
  @Input() rounded = true
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  private get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the combined CSS classes for the badge element.
   * @returns The badge class name string.
   */
  get badgeClasses(): string {
    return this.cm.cn(
      this.cm.badge({ variant: this.color, size: this.size }),
      !this.rounded && this.cm.badgeSquare,
      this.className,
    )
  }
}

MoleculeButton

Angular Button UI component with UIClassMap-driven styling.

React's root is the native <button>, so the button element of the template renders in front of the host (placeElementBefore) and the host itself leaves the page: the rendered tree is React's, with no wrapper element around the button.

@Component({
  selector: 'mol-button',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  hostDirectives: [MolPlacement],
  template: `
    <button
      #root
      [type]="type"
      [class]="classes"
      [style]="style"
      [attr.data-testid]="testId"
      [disabled]="disabled || loading"
      [attr.aria-busy]="loading"
      (click)="handleClick.emit($event)"
    >
      @if (loading) {
        <span [class]="cm.buttonSpinner"></span>
      }
      @if (loading && loadingText) {
        {{ loadingText }}
      } @else {
        <ng-content></ng-content>
      }
    </button>
  `,
})
/**
 * Molecule Button class.
 * @deprecated Use the React-named component `Button` instead.
 */
export class MoleculeButton {
  @Input() variant: ButtonVariant = 'solid'
  @Input() color: ColorVariant = 'primary'
  @Input() size: Size = 'md'
  @Input() loading = false
  @Input() loadingText?: string
  @Input() fullWidth = false
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string
  @Input() disabled = false
  @Input() type: 'button' | 'submit' | 'reset' = 'button'

  @Output() handleClick = new EventEmitter<MouseEvent>()

  /** The native button React renders as the component's root. */
  @ViewChild('root') root?: ElementRef<HTMLButtonElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /** Renders the button in front of the host, which leaves the page. */
  constructor() {
    usePlacement(() => {
      const root = this.root?.nativeElement
      if (!root) return
      placeElementBefore(root, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
  }

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the combined CSS classes for the button element.
   * @returns The button class name string.
   */
  get classes(): string {
    return this.cm.cn(
      this.cm.button({
        variant: this.variant,
        color: this.color,
        size: this.size,
        fullWidth: this.fullWidth,
      }),
      this.className,
    )
  }
}

MoleculeCheckbox

Angular Checkbox UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-checkbox',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div [class]="cm.formFieldWrapper">
      <label [class]="cm.controlLabel">
        <input
          type="checkbox"
          [id]="checkboxId"
          [name]="name"
          [checked]="checked"
          [disabled]="disabled"
          [attr.data-state]="checked ? 'checked' : 'unchecked'"
          [attr.aria-invalid]="!!error"
          [class]="checkboxClasses"
          [style]="style"
          [attr.data-testid]="testId"
          (change)="handleChange.emit($event)"
        />
        @if (label) {
          <span [class]="labelClasses">{{ label }}</span>
        }
      </label>
      @if (error) {
        <p [class]="errorClasses">{{ error }}</p>
      }
    </div>
  `,
})
/**
 * Molecule Checkbox class.
 * @deprecated Use the React-named component `Checkbox` instead.
 */
export class MoleculeCheckbox {
  @Input() label?: string
  @Input() checked = false
  @Input() indeterminate = false
  @Input() size?: Size
  @Input() error?: string
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string
  @Input() disabled = false
  @Input() name?: string
  @Input() id?: string

  @Output() handleChange = new EventEmitter<Event>()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Resolves the checkbox input element ID.
   * @returns The resolved ID from the id or name input.
   */
  get checkboxId(): string {
    return this.id || this.name || ''
  }

  /**
   * Computes the combined CSS classes for the checkbox input.
   * @returns The checkbox class name string.
   */
  get checkboxClasses(): string {
    return this.cm.cn(this.cm.checkbox({ error: !!this.error }), this.className)
  }

  /**
   * Computes the CSS classes for the checkbox label text.
   * @returns The label class name string.
   */
  get labelClasses(): string {
    return this.cm.cn(this.cm.controlText, this.disabled && this.cm.controlDisabled)
  }

  /**
   * Computes the CSS classes for the error message.
   * @returns The error class name string.
   */
  get errorClasses(): string {
    return this.cm.cn(this.cm.formError, this.cm.sp('mt', 1))
  }
}

MoleculeInput

Angular Input UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-input',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '[attr.id]': 'null' },
  template: `
    <div [class]="field.root">
      @if (label) {
        <label [attr.for]="inputId" [class]="labelClasses">
          {{ label }}
        </label>
      }
      <div [class]="field.inner">
        <input
          [type]="type"
          [id]="inputId"
          [name]="name"
          [value]="value"
          [placeholder]="placeholder"
          [disabled]="disabled"
          [required]="required"
          [readOnly]="readOnly"
          [attr.aria-invalid]="!!error"
          [attr.aria-describedby]="ariaDescribedBy"
          [class]="inputClasses"
          [style]="style"
          [attr.data-testid]="testId"
          [attr.maxlength]="maxLength"
          [attr.minlength]="minLength"
          [attr.pattern]="pattern"
          [attr.autocomplete]="autoComplete"
          (input)="emitFieldEvent(handleInput, $event)"
          (change)="emitFieldEvent(handleChange, $event)"
          (focus)="handleFocus.emit($event)"
          (blur)="handleBlur.emit($event)"
        />
        @if (clearable && value) {
          <div [class]="cm.inputClearButton">
            <button
              type="button"
              (click)="handleClear.emit()"
              [class]="cm.inputClearButton"
              [attr.aria-label]="clearAriaLabel"
            >
              <span [innerHTML]="clearIconSvg"></span>
            </button>
          </div>
        }
      </div>
      @if (error) {
        <p [id]="inputId + '-error'" [class]="formErrorClass">
          {{ error }}
        </p>
      }
      @if (hint && !error) {
        <p [id]="inputId + '-hint'" [class]="formHintClass">
          {{ hint }}
        </p>
      }
    </div>
  `,
})
/**
 * Molecule Input class.
 * @deprecated Use the React-named component `Input` instead.
 */
export class MoleculeInput {
  @Input() type: InputType = 'text'
  @Input() size: Size = 'md'
  @Input() label?: string
  @Input() error?: string
  @Input() hint?: string
  @Input() clearable = false
  @Input() clearLabel?: string
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string
  @Input() disabled = false
  @Input() required = false
  @Input() readOnly = false
  @Input() value?: string | number
  @Input() placeholder?: string
  @Input() name?: string
  @Input() id?: string
  @Input() maxLength?: number
  @Input() minLength?: number
  @Input() pattern?: string
  @Input() autoComplete?: string

  private readonly generatedId = nextInstanceId()

  @Output() handleInput = new EventEmitter<Event & KitFieldChangeEvent>()
  @Output() handleChange = new EventEmitter<Event & KitFieldChangeEvent>()
  @Output() handleFocus = new EventEmitter<FocusEvent>()
  @Output() handleBlur = new EventEmitter<FocusEvent>()
  @Output() handleClear = new EventEmitter<void>()

  /** Delivers the native event while its field targets are available. */
  emitFieldEvent(output: EventEmitter<Event & KitFieldChangeEvent>, event: Event): void {
    if (isFieldChangeEvent(event)) output.emit(event)
  }

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The classes of the field's two wrappers, from the shared field layout: `root` for the
   * outer wrapper, `inner` for the row that holds the control.
   * @returns The outer wrapper's classes and the control row's classes.
   */
  get field(): ReturnType<typeof fieldLayout> {
    return fieldLayout(this.cm)
  }

  /**
   * Computes the accessible clear button label.
   * @returns The localized aria-label for the clear button.
   */
  get clearAriaLabel(): string {
    return this.clearLabel || this.i18n.t('ui.input.clear', undefined, { defaultValue: 'Clear' })
  }

  /**
   * Retrieves the CSS class for form error messages.
   * @returns The form error class name string.
   */
  get formErrorClass(): string {
    return this.cm.formError
  }

  /**
   * Retrieves the CSS class for form hint messages.
   * @returns The form hint class name string.
   */
  get formHintClass(): string {
    return this.cm.formHint
  }

  /**
   * Resolves the input element ID.
   * @returns The explicit id or this instance's stable fallback.
   */
  get inputId(): string {
    return this.id || this.generatedId
  }

  /**
   * Computes the aria-describedby attribute value.
   * @returns The ID of the describing element, or null if none.
   */
  get ariaDescribedBy(): string | null {
    if (this.error) return `${this.inputId}-error`
    if (this.hint) return `${this.inputId}-hint`
    return null
  }

  /**
   * Computes the CSS classes for the input label.
   * @returns The label class name string.
   */
  get labelClasses(): string {
    return this.cm.cn(this.cm.label({ required: this.required }), this.cm.labelBlock)
  }

  /**
   * Computes the combined CSS classes for the input element.
   * @returns The input class name string.
   */
  get inputClasses(): string {
    return this.cm.cn(
      this.cm.input({ error: !!this.error, size: this.size }),
      this.clearable && this.cm.inputPadRight,
      this.className,
    )
  }

  /**
   * Generates the SVG markup for the clear button icon.
   * @returns The SVG string for the clear icon.
   */
  get clearIconSvg(): string {
    return getIconSvg('x-mark', this.cm.iconSm)
  }
}

MoleculeModal

Angular Modal UI component with UIClassMap-driven styling.

centered (default true) vertically centers the dialog; centered: false top-anchors it instead, via getModalWrapperStyle().

@Component({
  selector: 'mol-modal',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @if (open) {
      <!-- Overlay background -->
      <div [class]="overlayClass" aria-hidden="true"></div>

      <!-- Centering wrapper -->
      <div [class]="wrapperClass" [style]="wrapperStyle" (click)="onOverlayClick($event)">
        <!-- Content -->
        <div
          #dialog
          role="dialog"
          tabindex="-1"
          aria-modal="true"
          [attr.aria-labelledby]="title ? titleId : null"
          [class]="contentClasses"
          [style]="style"
          [attr.data-testid]="testId"
          (click)="$event.stopPropagation()"
        >
          @if (title || showCloseButton) {
            <div [class]="headerClass">
              @if (title) {
                <h2 [id]="titleId" [class]="titleClass">{{ title }}</h2>
              } @else if (showCloseButton) {
                <div></div>
              }
              @if (showCloseButton) {
                <button
                  type="button"
                  (click)="close.emit()"
                  [class]="closeClass"
                  [attr.aria-label]="closeAriaLabel"
                >
                  <span [innerHTML]="closeIconSvg"></span>
                </button>
              }
            </div>
          }

          <div [class]="bodyClass">
            <ng-content></ng-content>
          </div>

          @if (hasFooter) {
            <div [class]="footerClass">
              <ng-content select="[modal-footer]"></ng-content>
            </div>
          }
        </div>
      </div>
    }
  `,
})
/**
 * Molecule Modal class.
 * @deprecated Use the React-named component `Modal` instead.
 */
export class MoleculeModal implements AfterViewChecked, OnDestroy {
  @Input() open = false
  @Input() title?: string
  @Input() size: ModalSize = 'md'
  @Input() showCloseButton = true
  @Input() closeLabel?: string
  @Input() closeOnOverlayClick = true
  @Input() closeOnEscape = true
  @Input() centered = true
  @Input() preventScroll = true
  @Input() hasFooter = false
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  @Output() close = new EventEmitter<void>()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the accessible close button label.
   * @returns The localized aria-label for the close button.
   */
  get closeAriaLabel(): string {
    return this.closeLabel || this.i18n.t('ui.modal.close', undefined, { defaultValue: 'Close' })
  }

  /** Unique heading for this dialog. */
  readonly titleId = nextInstanceId()
  @ViewChild('dialog') private dialog?: ElementRef<HTMLDivElement>
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))
  private readonly layer = new OverlayLayer()

  /**
   * Retrieves the CSS class for the modal wrapper.
   * @returns The wrapper class name string.
   */
  get wrapperClass(): string {
    return this.cm.dialogWrapper
  }

  /**
   * Retrieves the inline style for the modal centering wrapper.
   * @returns An inline style object, or `undefined` when centered.
   */
  get wrapperStyle(): Record<string, string> | undefined {
    return getModalWrapperStyle(this.centered)
  }

  /**
   * Retrieves the CSS class for the modal body.
   * @returns The body class name string.
   */
  get bodyClass(): string {
    return this.cm.dialogBody
  }

  /**
   * Retrieves the CSS class for the modal overlay.
   * @returns The overlay class name string.
   */
  get overlayClass(): string {
    return this.cm.dialogOverlay
  }

  /**
   * Retrieves the CSS class for the modal header.
   * @returns The header class name string.
   */
  get headerClass(): string {
    return this.cm.dialogHeader
  }

  /**
   * Retrieves the CSS class for the modal footer.
   * @returns The footer class name string.
   */
  get footerClass(): string {
    return this.cm.dialogFooter
  }

  /**
   * Retrieves the CSS class for the modal title.
   * @returns The title class name string.
   */
  get titleClass(): string {
    return this.cm.dialogTitle
  }

  /**
   * Retrieves the CSS class for the close button.
   * @returns The close button class name string.
   */
  get closeClass(): string {
    return this.cm.dialogClose
  }

  private sanitizer = inject(DomSanitizer)

  /**
   * Generates the SVG markup for the close button icon.
   * @returns The sanitized SVG for the close icon.
   */
  get closeIconSvg(): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(getIconSvg('x-mark', this.cm.iconMd))
  }

  /**
   * Computes the combined CSS classes for the modal content.
   * @returns The modal content class name string.
   */
  get contentClasses(): string {
    return this.cm.cn(this.cm.modal({ size: this.size }), this.className)
  }

  /** Registers the rendered dialog with the document's shared focus and dismissal stack. */
  ngAfterViewChecked(): void {
    if (!this.browser || !this.dialog) {
      this.layer.release()
      return
    }
    this.layer.sync({
      open: this.open,
      kind: 'modal',
      surface: { current: this.dialog.nativeElement },
      dismissKey: this.closeOnEscape,
      dismissBackdrop: this.closeOnOverlayClick,
      focus: { trap: true, restore: 'opener' },
      lockScroll: this.preventScroll,
      onDismiss: () => this.close.emit(),
    })
  }

  /**
   * Cleans up event listeners and body scroll on component destruction.
   */
  ngOnDestroy(): void {
    this.layer.release()
  }

  /**
   * Handles overlay click to close the modal.
   * @param event - The mouse event from the overlay click.
   */
  onOverlayClick(event: MouseEvent): void {
    if (event.target === event.currentTarget) this.layer.dismissBackdrop()
  }
}

MoleculeRadioGroup

Angular RadioGroup UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-radio-group',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div
      [class]="className"
      [style]="style"
      [attr.data-testid]="testId"
      role="radiogroup"
      [attr.aria-label]="label"
    >
      @if (label) {
        <div [class]="groupLabelClasses">{{ label }}</div>
      }
      <div [class]="directionClasses">
        @for (option of options; track option.value) {
          <label [class]="getOptionLabelClasses(option)">
            <input
              type="radio"
              [name]="label"
              [value]="option.value"
              [checked]="value === option.value"
              [disabled]="disabled || option.disabled"
              [attr.data-state]="value === option.value ? 'checked' : 'unchecked'"
              [class]="radioClasses"
              (change)="onRadioChange(option.value)"
            />
            <span [class]="cm.controlText">{{ option.label }}</span>
          </label>
        }
      </div>
      @if (error) {
        <p [class]="errorClasses">{{ error }}</p>
      }
    </div>
  `,
})
/**
 * Molecule Radio Group class.
 * @deprecated Use the React-named component `RadioGroup` instead.
 */
export class MoleculeRadioGroup {
  @Input() options: RadioOption<string>[] = []
  @Input() value?: string
  @Input() size?: Size
  @Input() label?: string
  @Input() direction: 'horizontal' | 'vertical' = 'vertical'
  @Input() error?: string
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string
  @Input() disabled = false

  @Output() valueChange = new EventEmitter<string>()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the CSS classes for the radio group label.
   * @returns The group label class name string.
   */
  get groupLabelClasses(): string {
    return this.cm.cn(this.cm.label({}), this.cm.radioGroupLabel)
  }

  /**
   * Computes the CSS classes for the layout direction.
   * @returns The direction layout class name string.
   */
  get directionClasses(): string {
    return this.cm.radioGroupLayout(this.direction)
  }

  /**
   * Computes the CSS classes for radio input elements.
   * @returns The radio input class name string.
   */
  get radioClasses(): string {
    return this.cm.cn(this.cm.radio({ error: !!this.error }), this.cm.cursorPointer)
  }

  /**
   * Computes the CSS classes for the error message.
   * @returns The error class name string.
   */
  get errorClasses(): string {
    return this.cm.cn(this.cm.formError, this.cm.sp('mt', 1))
  }

  /**
   * Computes the CSS classes for an individual radio option label.
   * @param option - The radio option to compute classes for.
   * @returns The option label class name string.
   */
  getOptionLabelClasses(option: RadioOption<string>): string {
    const isDisabled = this.disabled || option.disabled
    return this.cm.cn(this.cm.controlLabel, isDisabled && this.cm.controlDisabled)
  }

  /**
   * Handles radio option selection change.
   * @param optionValue - The value of the selected radio option.
   */
  onRadioChange(optionValue: string): void {
    this.valueChange.emit(optionValue)
  }
}

MoleculeSelect

Angular Select UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-select',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '[attr.id]': 'null' },
  template: `
    <div [class]="field.root">
      @if (label) {
        <label [attr.for]="selectId" [class]="labelClasses">
          {{ label }}
        </label>
      }
      <div [class]="field.inner">
        <select
          [id]="selectId"
          [name]="name"
          [value]="value"
          [disabled]="disabled"
          [required]="required"
          [attr.aria-invalid]="!!error"
          [attr.aria-describedby]="ariaDescribedBy"
          [class]="selectClasses"
          [attr.data-testid]="testId"
          (change)="onSelectChange($event)"
        >
          @if (placeholder) {
            <option value="" disabled>{{ placeholder }}</option>
          }
          @if (clearable) {
            <option value="">--</option>
          }
          @for (option of options; track option.value) {
            <option [value]="option.value" [disabled]="option.disabled">
              {{ option.label }}
            </option>
          }
        </select>
      </div>
      @if (error) {
        <p [id]="selectId + '-error'" [class]="formErrorClass">
          {{ error }}
        </p>
      }
      @if (hint && !error) {
        <p [id]="selectId + '-hint'" [class]="formHintClass">
          {{ hint }}
        </p>
      }
    </div>
  `,
})
/**
 * Molecule Select class.
 * @deprecated Use the React-named component `Select` instead.
 */
export class MoleculeSelect {
  @Input() options: SelectOption<string>[] = []
  @Input() value?: string
  @Input() size: Size = 'md'
  @Input() label?: string
  @Input() placeholder?: string
  @Input() error?: string
  @Input() hint?: string
  @Input() clearable = false
  @Input() className?: string
  @Input() testId?: string
  @Input() disabled = false
  @Input() required = false
  @Input() name?: string
  @Input() id?: string

  @Output() valueChange = new EventEmitter<string>()
  @Output() handleChange = new EventEmitter<Event & KitFieldChangeEvent>()

  private readonly generatedId = nextInstanceId()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The classes of the field's two wrappers, from the shared field layout: `root` for the
   * outer wrapper, `inner` for the row that holds the control.
   * @returns The outer wrapper's classes and the control row's classes.
   */
  get field(): ReturnType<typeof fieldLayout> {
    return fieldLayout(this.cm)
  }

  /**
   * Retrieves the CSS class for form error messages.
   * @returns The form error class name string.
   */
  get formErrorClass(): string {
    return this.cm.formError
  }

  /**
   * Retrieves the CSS class for form hint messages.
   * @returns The form hint class name string.
   */
  get formHintClass(): string {
    return this.cm.formHint
  }

  /**
   * Resolves the select element ID.
   * @returns The explicit id or this instance's stable fallback.
   */
  get selectId(): string {
    return this.id || this.generatedId
  }

  /**
   * Computes the aria-describedby attribute value.
   * @returns The ID of the describing element, or null if none.
   */
  get ariaDescribedBy(): string | null {
    if (this.error) return `${this.selectId}-error`
    if (this.hint) return `${this.selectId}-hint`
    return null
  }

  /**
   * Computes the CSS classes for the select label.
   * @returns The label class name string.
   */
  get labelClasses(): string {
    return this.cm.cn(this.cm.label({ required: this.required }), this.cm.labelBlock)
  }

  /**
   * Computes the combined CSS classes for the select element.
   * @returns The select class name string.
   */
  get selectClasses(): string {
    return this.cm.cn(
      this.cm.select({ error: !!this.error, size: this.size }),
      this.cm.selectNative,
      this.className,
    )
  }

  /**
   * Handles select value change events.
   * @param event - The change event from the select element.
   */
  onSelectChange(event: Event): void {
    if (!isFieldChangeEvent(event)) return
    this.handleChange.emit(event)
    this.valueChange.emit(event.target.value)
  }
}

MoleculeSpinner

Angular Spinner UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-spinner',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div
      role="status"
      [attr.aria-label]="spinnerLabel"
      [class]="spinnerClasses"
      [style]="computedStyle"
      [attr.data-testid]="testId"
    >
      @if (label) {
        <span [class]="cm.srOnly">{{ label }}</span>
      }
    </div>
  `,
})
/**
 * Molecule Spinner class.
 * @deprecated Use the React-named component `Spinner` instead.
 */
export class MoleculeSpinner {
  @Input() size: Size = 'md'
  @Input() color?: ColorVariant | string
  @Input() label?: string
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the accessible spinner label.
   * @returns The localized aria-label for the spinner.
   */
  get spinnerLabel(): string {
    return this.label || this.i18n.t('ui.spinner.loading', undefined, { defaultValue: 'Loading' })
  }

  /**
   * Computes the combined CSS classes for the spinner element.
   * @returns The spinner class name string.
   */
  get spinnerClasses(): string {
    return this.cm.cn(this.cm.spinner({ size: this.size }), this.className)
  }

  /**
   * Computes the merged inline styles including custom color.
   * @returns The computed style object with optional custom border color.
   */
  get computedStyle(): Record<string, string> {
    const base: Record<string, string> = { ...this.style }
    if (
      this.color &&
      typeof this.color === 'string' &&
      !['primary', 'secondary', 'success', 'warning', 'error', 'info'].includes(this.color)
    ) {
      base['borderColor'] = this.color
      base['borderTopColor'] = 'transparent'
    }
    return base
  }
}

MoleculeSwitch

Angular Switch UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-switch',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <label [class]="wrapperClasses">
      <button
        type="button"
        role="switch"
        [attr.aria-checked]="checked"
        [disabled]="disabled"
        [attr.data-state]="state"
        [class]="switchClasses"
        [style]="style"
        [attr.data-testid]="testId"
        (click)="onToggle()"
      >
        <span [attr.data-state]="state" [class]="thumbClasses"></span>
      </button>
      @if (label) {
        <span [class]="cm.controlText">{{ label }}</span>
      }
    </label>
  `,
})
/**
 * Molecule Switch class.
 * @deprecated Use the React-named component `Switch` instead.
 */
export class MoleculeSwitch {
  @Input() label?: string
  @Input() checked = false
  @Input() size: Size = 'md'
  @Input() color?: ColorVariant
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string
  @Input() disabled = false

  @Output() checkedChange = new EventEmitter<boolean>()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the current checked/unchecked state string.
   * @returns The state string, either "checked" or "unchecked".
   */
  get state(): string {
    return this.checked ? 'checked' : 'unchecked'
  }

  /**
   * Computes the CSS classes for the switch wrapper label.
   * @returns The wrapper class name string.
   */
  get wrapperClasses(): string {
    return this.cm.cn(this.cm.controlLabel, this.disabled && this.cm.controlDisabled)
  }

  /**
   * Computes the combined CSS classes for the switch button.
   * @returns The switch class name string.
   */
  get switchClasses(): string {
    return this.cm.cn(this.cm.switchBase({ size: this.size }), this.className)
  }

  /**
   * Computes the CSS classes for the switch thumb indicator.
   * @returns The thumb class name string.
   */
  get thumbClasses(): string {
    return this.cm.switchThumb({ size: this.size })
  }

  /**
   * Handles the switch toggle action.
   */
  onToggle(): void {
    if (!this.disabled) {
      this.checkedChange.emit(!this.checked)
    }
  }
}

MoleculeToast

Angular Toast UI component with UIClassMap-driven styling.

@Component({
  selector: 'mol-toast',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @if (isVisible()) {
      <div
        role="alert"
        data-state="open"
        [class]="toastClasses"
        [style]="style"
        [attr.data-testid]="testId"
      >
        @if (showIcon) {
          <span [class]="cm.toastIconWrapper">
            <span [innerHTML]="statusIconSvg"></span>
          </span>
        }
        <div [class]="cm.toastContentWrapper">
          @if (title) {
            <div [class]="titleClass">{{ title }}</div>
          }
          @if (description) {
            <div [class]="descriptionClass">{{ description }}</div>
          } @else {
            <div [class]="descriptionClass">
              <ng-content></ng-content>
            </div>
          }
        </div>
        @if (dismissible) {
          <button
            type="button"
            (click)="onDismiss()"
            [class]="closeButtonClass"
            [attr.aria-label]="closeAriaLabel"
          >
            <span [innerHTML]="dismissIconSvg"></span>
          </button>
        }
      </div>
    }
  `,
})
/**
 * Molecule Toast class.
 * @deprecated Use the React-named component `Toast` instead.
 */
export class MoleculeToast implements OnInit, OnDestroy {
  @Input() title?: string
  @Input() description?: string
  @Input() status: ColorVariant = 'info'
  @Input() duration = 5000
  @Input() dismissible = true
  @Input() closeLabel?: string
  @Input() position: 'top' | 'top-right' | 'top-left' | 'bottom' | 'bottom-right' | 'bottom-left' =
    'bottom-right'
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  @Output() dismiss = new EventEmitter<void>()

  /** Whether the toast shows; a signal, so the auto-dismiss timer's change renders (OnPush). */
  readonly isVisible = signal(true)
  private timer?: ReturnType<typeof setTimeout>

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the accessible close button label.
   * @returns The localized aria-label for the close button.
   */
  get closeAriaLabel(): string {
    return this.closeLabel || this.i18n.t('ui.toast.close', undefined, { defaultValue: 'Close' })
  }

  /**
   * Retrieves the CSS class for the toast title.
   * @returns The title class name string.
   */
  get titleClass(): string {
    return this.cm.toastTitle
  }

  /**
   * Retrieves the CSS class for the toast description.
   * @returns The description class name string.
   */
  get descriptionClass(): string {
    return this.cm.toastDescription
  }

  /**
   * Retrieves the CSS class for the close button.
   * @returns The close button class name string.
   */
  get closeButtonClass(): string {
    return this.cm.toastClose
  }

  /**
   * Determines the icon type based on the toast status.
   * @returns The mapped icon type string.
   */
  get iconType(): string {
    return statusVariantMap[this.status] || 'default'
  }

  /**
   * Determines whether the status icon should be shown.
   * @returns True if the icon type is not default.
   */
  get showIcon(): boolean {
    return this.iconType !== 'default'
  }

  private statusIconMap: Record<string, IconName> = {
    info: 'info-circle',
    success: 'check-circle',
    warning: 'exclamation-triangle',
    error: 'x-circle',
  }

  /**
   * Generates the SVG markup for the status icon.
   * @returns The SVG string for the current status icon.
   */
  get statusIconSvg(): string {
    const name = this.statusIconMap[this.iconType]
    return name ? getIconSvg(name, this.cm.iconMd) : ''
  }

  /**
   * Generates the SVG markup for the dismiss icon.
   * @returns The SVG string for the dismiss button icon.
   */
  get dismissIconSvg(): string {
    return getIconSvg('x-mark', this.cm.iconSm)
  }

  /**
   * Computes the combined CSS classes for the toast container.
   * @returns The toast class name string.
   */
  get toastClasses(): string {
    const variant = statusVariantMap[this.status] || 'default'
    return this.cm.cn(this.cm.toast({ variant }), this.className)
  }

  /**
   * Starts the auto-dismiss timer on component creation.
   */
  ngOnInit(): void {
    if (this.duration > 0) {
      this.timer = setTimeout(() => {
        this.isVisible.set(false)
        this.dismiss.emit()
      }, this.duration)
    }
  }

  /**
   * Clears the auto-dismiss timer on component destruction.
   */
  ngOnDestroy(): void {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  }

  /**
   * Handles the dismiss action by hiding the toast.
   */
  onDismiss(): void {
    this.isVisible.set(false)
    this.dismiss.emit()
  }
}

MoleculeTooltip

Angular Tooltip UI component with UIClassMap-driven styling.

Wraps child content and shows a tooltip on hover/focus. hasArrow renders a small themed pointer at the resolved placement edge.

@Component({
  selector: 'mol-tooltip',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div
      #trigger
      [class]="cm.tooltipTrigger"
      (mouseenter)="show()"
      (mouseleave)="hide()"
      (focus)="show()"
      (blur)="hide()"
    >
      <ng-content></ng-content>
    </div>
    @if (isVisible()) {
      <!--
        Outer positioned wrapper carries the top/left/z-index placement; the
        arrow renders as its SIBLING (not nested inside the visible box),
        because tooltipContent sets overflow-hidden — an arrow meant to poke
        past the box's own edge would be clipped invisible if it were a
        descendant of that element instead.
      -->
      <div [style]="positionStyle()">
        <div
          #tooltipEl
          role="tooltip"
          [class]="tooltipClasses"
          [style]="style"
          [attr.data-testid]="testId"
        >
          {{ content }}
        </div>
        @if (hasArrow) {
          <span aria-hidden="true" [style]="arrowStyle"></span>
        }
      </div>
    }
  `,
})
/**
 * Molecule Tooltip class.
 * @deprecated Use the React-named component `Tooltip` instead.
 */
export class MoleculeTooltip implements OnDestroy {
  @Input() content = ''
  @Input() placement: TooltipPlacement = 'top'
  @Input() delay = 0
  @Input() hasArrow = false
  @Input() className?: string
  @Input() style?: Record<string, string>
  @Input() testId?: string

  @ViewChild('trigger') triggerRef?: ElementRef<HTMLDivElement>
  @ViewChild('tooltipEl') tooltipRef?: ElementRef<HTMLDivElement>

  /** Whether the tooltip shows; a signal, so the delay timer's change renders (OnPush). */
  readonly isVisible = signal(false)
  /** The measured placement; a signal, so the animation frame's measurement renders (OnPush). */
  readonly positionStyle = signal<Record<string, string>>({})
  private timeoutId?: ReturnType<typeof setTimeout>

  /**
   * Retrieves the current UI class map.
   * @returns The UIClassMap instance for styling.
   */
  get cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the combined CSS classes for the tooltip content.
   * @returns The tooltip class name string.
   */
  get tooltipClasses(): string {
    return this.cm.cn(this.cm.tooltipContent, this.className)
  }

  /**
   * Retrieves the inline style for the tooltip's arrow element.
   * @returns Inline style positioning the rotated-square arrow.
   */
  get arrowStyle(): Record<string, string> {
    return getTooltipArrowStyle(this.placement)
  }

  /**
   * Shows the tooltip with optional delay.
   */
  show(): void {
    if (this.delay > 0) {
      this.timeoutId = setTimeout(() => {
        this.isVisible.set(true)
        // Measured once the tooltip has rendered.
        requestAnimationFrame(() => this.updatePosition())
      }, this.delay)
    } else {
      this.isVisible.set(true)
      requestAnimationFrame(() => this.updatePosition())
    }
  }

  /**
   * Hides the tooltip and cancels any pending delay.
   */
  hide(): void {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId)
    }
    this.isVisible.set(false)
  }

  /**
   * Clears pending timeouts on component destruction.
   */
  ngOnDestroy(): void {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId)
    }
  }

  /**
   * Calculates and applies the tooltip position relative to the trigger.
   */
  private updatePosition(): void {
    if (!this.triggerRef?.nativeElement || !this.tooltipRef?.nativeElement) return

    const triggerRect = this.triggerRef.nativeElement.getBoundingClientRect()
    const tooltipRect = this.tooltipRef.nativeElement.getBoundingClientRect()
    const offset = 8

    const { top, left, width, height } = triggerRect
    const tooltipWidth = tooltipRect.width
    const tooltipHeight = tooltipRect.height

    const positions: Record<TooltipPlacement, { top: number; left: number }> = {
      top: {
        top: top + window.scrollY - tooltipHeight - offset,
        left: left + window.scrollX + width / 2 - tooltipWidth / 2,
      },
      bottom: {
        top: top + window.scrollY + height + offset,
        left: left + window.scrollX + width / 2 - tooltipWidth / 2,
      },
      left: {
        top: top + window.scrollY + height / 2 - tooltipHeight / 2,
        left: left + window.scrollX - tooltipWidth - offset,
      },
      right: {
        top: top + window.scrollY + height / 2 - tooltipHeight / 2,
        left: left + window.scrollX + width + offset,
      },
      'top-start': {
        top: top + window.scrollY - tooltipHeight - offset,
        left: left + window.scrollX,
      },
      'top-end': {
        top: top + window.scrollY - tooltipHeight - offset,
        left: left + window.scrollX + width - tooltipWidth,
      },
      'bottom-start': {
        top: top + window.scrollY + height + offset,
        left: left + window.scrollX,
      },
      'bottom-end': {
        top: top + window.scrollY + height + offset,
        left: left + window.scrollX + width - tooltipWidth,
      },
    }

    const pos = positions[this.placement]
    this.positionStyle.set({
      position: 'absolute',
      top: `${pos.top}px`,
      left: `${pos.left}px`,
      zIndex: '9999',
    })
  }
}

OptimisticToggleButton

OptimisticToggleButton component.

The host is the <button> itself (button[mol-optimistic-toggle-button]), exactly React's root (it renders Button). The two labels are node-valued props, projected as [slot=activeLabel] / [slot=inactiveLabel]; exactly one is shown, moved onto the button with no wrapper, matching React's {toggle.value ? activeLabel : inactiveLabel}.

@Component({
  selector: 'button[mol-optimistic-toggle-button]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolTemplateOutlet],
  inputs: [
    'value',
    'commit',
    'activeLabel',
    'inactiveLabel',
    'onError',
    'variant',
    'color',
    'size',
    'fullWidth',
    'leftIcon',
    'rightIcon',
    'className',
    'style',
    'testId',
    'disabled',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    // `value` is the loaded server state, which React keeps off the <button>; Angular would also keep
    // a static `value="…"` on the host as the button's form value.
    '[attr.value]': 'null',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.type]': '"button"',
    '[attr.data-mol-id]': 'molId()',
    '[attr.data-testid]': 'testId',
    '[disabled]': 'disabled',
    '[attr.aria-pressed]': 'state().value ? "true" : "false"',
    '[attr.aria-busy]': 'state().pending ? "true" : "false"',
    '(click)': 'handleClick()',
  },
  template: `<span #leftSlot [class]="cm().buttonIconLeft"
      ><ng-content select="[slot=leftIcon]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(leftIcon)"></ng-container
      >{{ nodeText(leftIcon) }}</span
    ><span #activeSlot
      ><ng-content select="[slot=activeLabel]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(activeLabel)"></ng-container
      >{{ nodeText(activeLabel) }}</span
    ><span #inactiveSlot
      ><ng-content select="[slot=inactiveLabel]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(inactiveLabel)"></ng-container
      >{{ nodeText(inactiveLabel) }}</span
    ><span #rightSlot [class]="cm().buttonIconRight"
      ><ng-content select="[slot=rightIcon]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(rightIcon)"></ng-container
      >{{ nodeText(rightIcon) }}</span
    >`,
})
export class OptimisticToggleButton implements DoCheck, OnDestroy, HasElement<HTMLButtonElement> {
  /** The loaded server value. */
  value: OptimisticToggleButtonProps['value'] = false
  /** Saves the desired boolean and returns the server-confirmed boolean. */
  commit?: OptimisticToggleButtonProps['commit']
  /** Label when the displayed value is true (node-valued prop). */
  activeLabel!: OptimisticToggleButtonProps['activeLabel']
  /** Label when the displayed value is false (node-valued prop). */
  inactiveLabel!: OptimisticToggleButtonProps['inactiveLabel']
  /** Receives a failed save after the controller has restored the last confirmed value. */
  onError?: OptimisticToggleButtonProps['onError']
  /** Button variant. */
  variant?: OptimisticToggleButtonProps['variant']
  /** Button color. */
  color?: OptimisticToggleButtonProps['color']
  /** Button size. */
  size?: OptimisticToggleButtonProps['size']
  /** Whether the button stretches to fill its container. */
  fullWidth?: OptimisticToggleButtonProps['fullWidth'] = false
  /** Left icon (node-valued prop). */
  leftIcon?: OptimisticToggleButtonProps['leftIcon']
  /** Right icon (node-valued prop). */
  rightIcon?: OptimisticToggleButtonProps['rightIcon']
  /** Extra classes. */
  className?: OptimisticToggleButtonProps['className']
  /** Inline style object (React camelCase). */
  style?: OptimisticToggleButtonProps['style']
  /** `data-testid`. */
  testId?: OptimisticToggleButtonProps['testId']
  /** Disables the button (permissions, never a pending save). */
  disabled?: OptimisticToggleButtonProps['disabled'] = false
  /** `data-mol-id` automation id (React's `automationId`; default `optimistic-toggle`). */
  automationId?: OptimisticToggleButtonProps['automationId']
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText

  /** The optimistic controller. */
  private readonly controller: OptimisticValue<boolean>
  /** The controller state (a signal so the zoneless view re-checks on every publish). */
  readonly state = signal<OptimisticValueState<boolean>>({
    value: false,
    pending: false,
    error: null,
  })

  /** The left icon wrapper. */
  @ViewChild('leftSlot') leftSlot?: ElementRef<HTMLSpanElement>
  /** The active-label capture span. */
  @ViewChild('activeSlot') activeSlot?: ElementRef<HTMLSpanElement>
  /** The inactive-label capture span. */
  @ViewChild('inactiveSlot') inactiveSlot?: ElementRef<HTMLSpanElement>
  /** The right icon wrapper. */
  @ViewChild('rightSlot') rightSlot?: ElementRef<HTMLSpanElement>

  private readonly host: ElementRef<HTMLButtonElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<button>`. */
  readonly element = hostElement(this.host)
  private unsubscribe?: () => void
  private lastReceived = false
  private hasLeft = false
  private hasRight = false
  /** The slot whose content is currently shown on the button. */
  private visibleFrom: HTMLSpanElement | null = null

  /** Creates the optimistic controller and mirrors its state into the signal. */
  constructor() {
    this.controller = createOptimisticValue<boolean>({
      value: this.value,
      commit: (next) => this.commit?.(next) ?? Promise.resolve(next),
      onError: (error) => this.onError?.(error),
    })
    this.unsubscribe = this.controller.subscribe((next) => this.state.set({ ...next }))
    this.state.set(this.controller.getState())
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** Computes the button class list. */
  classes(): string {
    return this.cm().cn(
      this.cm().button({
        variant: this.variant ?? 'solid',
        color: this.color ?? 'primary',
        size: this.size ?? 'md',
        fullWidth: this.fullWidth,
      }),
      this.className,
    )
  }

  /** Serializes the inline style. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      'optimistic-toggle'
    )
  }

  /** Flips the displayed value and saves the newest desired value. */
  handleClick(): void {
    this.controller.update((current) => !current)
  }

  /** Reads slot presence and takes the label capture spans out of the DOM, then shows the visible label. */
  private reconcile(hasContent: SlotReader): void {
    this.hasLeft = hasContent(this.leftSlot?.nativeElement)
    this.hasRight = hasContent(this.rightSlot?.nativeElement)
    setElementPresent(this.activeSlot?.nativeElement, false)
    setElementPresent(this.inactiveSlot?.nativeElement, false)
    setElementPresent(this.leftSlot?.nativeElement, this.hasLeft)
    setElementPresent(this.rightSlot?.nativeElement, this.hasRight)
    this.syncLabels()
  }

  ngDoCheck(): void {
    if (this.value !== this.lastReceived) {
      this.lastReceived = this.value
      this.controller.sync(this.value)
    }
  }

  /** Stops mirroring controller state into the signal (unmount). */
  ngOnDestroy(): void {
    this.unsubscribe?.()
  }

  private syncLabels(): void {
    const state = this.controller.getState()
    const shown = state.value
      ? (this.activeSlot?.nativeElement ?? null)
      : (this.inactiveSlot?.nativeElement ?? null)
    const hidden = state.value
      ? (this.inactiveSlot?.nativeElement ?? null)
      : (this.activeSlot?.nativeElement ?? null)
    if (hidden) placeContent(hidden, null)
    // The label goes before the right icon's place (its placeholder while the
    // icon is absent, which placeContent resolves), else at the end.
    if (shown) placeContent(shown, this.host.nativeElement, this.rightSlot?.nativeElement ?? null)
  }
}

(Member comments are shortened to their first sentence, and the 3 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/optimistic-toggle-button.component.d.ts.)

PageHeader component.

The host is the root <div> (div[mol-page-header]), exactly React's root. actions is a node-valued prop, projected as [slot=actions]; its wrapper <div> renders only when the slot carries nodes (React's {actions ? <div>…</div> : null}), implemented by detaching the wrapper from the DOM — the projected nodes need an always-mounted capture point.

@Component({
  selector: 'div[mol-page-header]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Link],
  inputs: ['title', 'description', 'breadcrumbs', 'className', 'style', 'testId', 'automationId'],
  host: {
    // `title` is this component's heading, which React renders as text; Angular would also keep a
    // static `title="…"` on the host, where the browser shows it as a tooltip.
    '[attr.title]': 'null',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'automationId',
  },
  template: `@if (breadcrumbs && breadcrumbs.length > 0) {
      <nav [class]="cm().pageHeaderBreadcrumbs" [attr.aria-label]="breadcrumbLabel()">
        @for (crumb of breadcrumbs; track $index) {
          @if ($index > 0) {
            <span [class]="cm().pageHeaderBreadcrumbSeparator" aria-hidden="true">/</span>
          }
          @if (crumb.href) {
            <a [molLink]="crumb.href" [class]="cm().pageHeaderBreadcrumbItem">{{ crumb.label }}</a>
          } @else {
            <span [class]="cm().pageHeaderBreadcrumbItem">{{ crumb.label }}</span>
          }
        }
      </nav>
    }
    <div [class]="cm().flex({ justify: 'between', align: 'center' })">
      <div>
        <h1 [class]="cm().pageHeaderTitle">{{ title }}</h1>
        @if (description) {
          <p [class]="cm().pageHeaderDescription">{{ description }}</p>
        }
      </div>
      <div #actionsSlot [class]="cm().pageHeaderActions">
        <ng-content select="[slot=actions]"></ng-content>
      </div>
    </div>`,
})
export class PageHeader implements HasElement<HTMLDivElement> {
  /** Page title. */
  title = ''
  /** Page description. */
  description?: string
  /** Breadcrumb trail (empty or absent renders no nav). */
  breadcrumbs?: Breadcrumb[]
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id. */
  automationId?: string

  /** The actions wrapper (always in the template; detached when unused). */
  @ViewChild('actionsSlot') actionsSlot?: ElementRef<HTMLDivElement>

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the label on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)
  private hasActions = false

  /** Applies React's `{actions ? <div>…</div> : null}`. */
  constructor() {
    usePlacement((hasContent) => this.syncActions(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the root class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().pageHeader, this.className)
  }

  /**
   * The breadcrumb nav's accessible label.
   * @returns The label text.
   */
  breadcrumbLabel(): string {
    return this.i18n.t('ui.pageHeader.breadcrumbs', undefined, { defaultValue: 'Breadcrumb' })
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * Applies React's `{actions ? <div>…</div> : null}`.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncActions(hasContent: SlotReader): void {
    this.hasActions = hasContent(this.actionsSlot?.nativeElement)
    setElementPresent(this.actionsSlot?.nativeElement, this.hasActions)
  }
}

PageShell

PageShell component.

The host is the root <div> (div[mol-page-shell]). sidebar and topbar are node-valued props projected as [slot=sidebar] / [slot=topbar]; each wrapper element (<aside>, <header>) renders only when React would render it ({sidebar ? … : null}), implemented by detaching the always-mounted capture element from the DOM.

The sidebar toggle button renders only when the caller passed onSidebarToggle (React's {onSidebarToggle ? … : null}); with an @Output, that presence is the output's subscriber count.

@Component({
  selector: 'div[mol-page-shell]',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: ['sidebar', 'topbar', 'sidebarCollapsed', 'className', 'style', 'testId', 'automationId'],
  outputs: ['sidebarToggle'],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'automationId',
  },
  template: `<aside #sidebarSlot [class]="sidebarClasses()">
      @if (toggleVisible()) {
        <button
          type="button"
          [class]="cm().pageShellSidebarToggle"
          (click)="sidebarToggle.emit($event)"
          [attr.aria-label]="toggleLabel()"
        >
          {{ sidebarCollapsed ? '▶' : '◀' }}
        </button>
      }
      <ng-content select="[slot=sidebar]"></ng-content>
    </aside>
    <div [class]="cm().flex1">
      <header #topbarSlot [class]="cm().pageShellTopbar">
        <ng-content select="[slot=topbar]"></ng-content>
      </header>
      <main [class]="cm().pageShellContent"><ng-content></ng-content></main>
    </div>`,
})
export class PageShell implements HasElement<HTMLDivElement> {
  /** Sidebar content (node-valued prop). */
  sidebar?: unknown
  /** Top bar content (node-valued prop). */
  topbar?: unknown
  /** Whether the sidebar is collapsed. */
  sidebarCollapsed = false
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id. */
  automationId?: string

  /** Fires when the sidebar toggle button is pressed (React's `onSidebarToggle`). */
  @Output() readonly sidebarToggle = new EventEmitter<MouseEvent>()

  /** The sidebar wrapper (always in the template; detached when unused). */
  @ViewChild('sidebarSlot') sidebarSlot?: ElementRef<HTMLElement>
  /** The top bar wrapper (always in the template; detached when unused). */
  @ViewChild('topbarSlot') topbarSlot?: ElementRef<HTMLElement>

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)
  private hasSidebar = false
  private hasTopbar = false

  /** Applies React's `{sidebar ? … : null}` / `{topbar ? … : null}`. */
  constructor() {
    usePlacement((hasContent) => this.syncWrappers(hasContent))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the root class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().pageShell, this.className)
  }

  /**
   * Computes the sidebar wrapper class list.
   * @returns The class string.
   */
  sidebarClasses(): string {
    return this.cm().cn(
      this.cm().pageShellSidebar,
      this.sidebarCollapsed && this.cm().pageShellSidebarCollapsed,
    )
  }

  /**
   * Whether the toggle button renders (React renders it only when
   * `onSidebarToggle` is given; a bound output means the caller listens).
   * @returns True when a listener is attached.
   */
  toggleVisible(): boolean {
    return this.sidebarToggle.observed
  }

  /**
   * The toggle button's accessible label.
   * @returns The label text.
   */
  toggleLabel(): string {
    return this.sidebarCollapsed
      ? this.i18n.t('ui.pageShell.expandSidebar', undefined, { defaultValue: 'Expand sidebar' })
      : this.i18n.t('ui.pageShell.collapseSidebar', undefined, { defaultValue: 'Collapse sidebar' })
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * Applies React's `{sidebar ? … : null}` / `{topbar ? … : null}`.
   *
   * @param hasContent - Reads whether a slot has content.
   */
  private syncWrappers(hasContent: SlotReader): void {
    this.hasSidebar = hasContent(this.sidebarSlot?.nativeElement)
    this.hasTopbar = hasContent(this.topbarSlot?.nativeElement)
    setElementPresent(this.sidebarSlot?.nativeElement, this.hasSidebar)
    setElementPresent(this.topbarSlot?.nativeElement, this.hasTopbar)
  }
}

Pagination

Pagination component.

The host is the <nav> (nav[mol-pagination]), exactly React's root.

@Component({
  selector: 'nav[mol-pagination]',
  standalone: true,
  imports: [MolIconSvg],
  inputs: [
    'page',
    'totalPages',
    'siblings',
    'boundaries',
    'size',
    'showFirstLast',
    'showPrevNext',
    'labels',
    'className',
    'style',
    'testId',
    'disabled',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  outputs: ['change'],
  host: {
    role: 'navigation',
    '[attr.aria-label]': 'navLabel()',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<ul [class]="cm().paginationContent">
    @if (showFirstLast) {
      <li>
        <button
          type="button"
          [class]="buttonClasses(false)"
          (click)="handlePageChange(1)"
          [disabled]="page === 1 || !!disabled"
          [attr.aria-label]="firstLabel()"
        >
          <svg mol-icon [data]="icon('chevrons-left')" />
        </button>
      </li>
    }
    @if (showPrevNext) {
      <li>
        <button
          type="button"
          [class]="buttonClasses(false)"
          (click)="handlePageChange(page - 1)"
          [disabled]="page === 1 || !!disabled"
          [attr.aria-label]="previousLabel()"
        >
          <svg mol-icon [data]="icon('chevron-left')" />
        </button>
      </li>
    }
    @for (item of range(); track $index) {
      @if (item === 'ellipsis') {
        <li>
          <span [class]="cm().paginationEllipsis" aria-hidden="true"
            ><svg mol-icon [data]="icon('ellipsis-horizontal')"
          /></span>
        </li>
      } @else {
        <li>
          <button
            type="button"
            [class]="buttonClasses(item === page)"
            (click)="handlePageChange(item)"
            [disabled]="!!disabled"
            [attr.aria-label]="pageLabel(item)"
            [attr.aria-current]="item === page ? 'page' : null"
          >
            {{ item }}
          </button>
        </li>
      }
    }
    @if (showPrevNext) {
      <li>
        <button
          type="button"
          [class]="buttonClasses(false)"
          (click)="handlePageChange(page + 1)"
          [disabled]="page === totalPages || !!disabled"
          [attr.aria-label]="nextLabel()"
        >
          <svg mol-icon [data]="icon('chevron-right')" />
        </button>
      </li>
    }
    @if (showFirstLast) {
      <li>
        <button
          type="button"
          [class]="buttonClasses(false)"
          (click)="handlePageChange(totalPages)"
          [disabled]="page === totalPages || !!disabled"
          [attr.aria-label]="lastLabel()"
        >
          <svg mol-icon [data]="icon('chevrons-right')" />
        </button>
      </li>
    }
  </ul>`,
})
export class Pagination implements HasElement<HTMLElement> {
  /** The active page. */
  page = 1
  /** The total number of pages. */
  totalPages = 1
  /** Sibling pages around the active page (default 1). */
  siblings = 1
  /** Boundary pages at the start and end (default 1). */
  boundaries = 1
  /** Button size. */
  size: 'xs' | 'sm' | 'md' | 'lg' | 'xl' = 'md'
  /** Whether the first/last buttons render. */
  showFirstLast = false
  /** Whether the previous/next buttons render (default true). */
  showPrevNext = true
  /** Accessible labels. */
  labels?: PaginationLabels
  /** Extra classes for the nav. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** Disables every button. */
  disabled?: boolean
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /** Fires with the requested page (React's `onChange`). */
  @Output() readonly change = new EventEmitter<number>()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<nav>`. */
  readonly element = hostElement(this.host)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The root class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().paginationRoot, this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the root's inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The generated page range.
   * @returns The range.
   */
  range(): (number | 'ellipsis')[] {
    return generatePaginationRange(this.page, this.totalPages, this.siblings, this.boundaries)
  }

  /**
   * A pagination button's class list.
   * @param isActive - Whether it is the active page.
   * @returns The class string.
   */
  buttonClasses(isActive: boolean): string {
    return this.cm().cn(
      this.cm().pagination({ active: isActive, size: this.size }),
      this.cm().paginationInteractive,
    )
  }

  /**
   * A button glyph.
   * @param name - The icon name.
   * @returns The resolved icon.
   */
  icon(
    name:
      'chevrons-left' | 'chevron-left' | 'chevron-right' | 'chevrons-right' | 'ellipsis-horizontal',
  ): ResolvedIcon {
    return resolveIcon(name, this.cm().iconSm)
  }

  /**
   * The nav's accessible label.
   * @returns The label.
   */
  navLabel(): string {
    return (
      this.labels?.nav ??
      this.i18n.t('ui.pagination.nav', undefined, { defaultValue: 'Pagination' })
    )
  }

  /**
   * The first-page button's accessible label.
   * @returns The label.
   */
  firstLabel(): string {
    return (
      this.labels?.first ??
      this.i18n.t('ui.pagination.first', undefined, { defaultValue: 'Go to first page' })
    )
  }

  /**
   * The previous-page button's accessible label.
   * @returns The label.
   */
  previousLabel(): string {
    return (
      this.labels?.previous ??
      this.i18n.t('ui.pagination.previous', undefined, { defaultValue: 'Go to previous page' })
    )
  }

  /**
   * The next-page button's accessible label.
   * @returns The label.
   */
  nextLabel(): string {
    return (
      this.labels?.next ??
      this.i18n.t('ui.pagination.next', undefined, { defaultValue: 'Go to next page' })
    )
  }

  /**
   * The last-page button's accessible label.
   * @returns The label.
   */
  lastLabel(): string {
    return (
      this.labels?.last ??
      this.i18n.t('ui.pagination.last', undefined, { defaultValue: 'Go to last page' })
    )
  }

  /**
   * A numbered page button's accessible label (a custom `labels.goToPage`
   * wins, then the localized default).
   *
   * @param item - The page number.
   * @returns The label.
   */
  pageLabel(item: number): string {
    const custom = this.labels?.goToPage?.(item)
    if (custom !== undefined && custom !== null) return custom
    return this.i18n.t(
      'ui.pagination.goToPage',
      { page: item },
      { defaultValue: 'Go to page {{page}}' },
    )
  }

  /**
   * Requests a page change (React's `handlePageChange`).
   * @param newPage - The requested page.
   */
  handlePageChange(newPage: number): void {
    if (newPage >= 1 && newPage <= this.totalPages && newPage !== this.page && !this.disabled) {
      this.change.emit(newPage)
    }
  }
}

PanelCloseProvider

Provides the drawer-close callback to descendants.

Rendered internally by UserMenu and SidebarUserCard around their panel content; apps do not normally render it directly. React's context provider renders its children and no DOM of its own, so the projected children render in front of the host (placeContentBefore) and the host itself leaves the page. The context is registered on the parent element — the one whose child list the content now belongs to — so a consumer in the content still resolves it from its DOM ancestors.

@Component({
  selector: 'mol-panel-close-provider',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: ['close'],
  template: `<ng-content></ng-content>`,
})
export class PanelCloseProvider implements OnDestroy {
  /** Callback that dismisses the enclosing drawer/modal. */
  close?: PanelCloseProviderProps['close']

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  /** The value consumers read; its closure keeps the CURRENT `close` prop. */
  private readonly value = { close: (): void => this.close?.() }

  /** Renders the children in front of the host and registers the context where they render. */
  constructor() {
    const host = this.host.nativeElement
    PanelCloseDomContext.provide(host, this.value)
    usePlacement(() => {
      placeContentBefore(host, host)
      setElementPresent(host, false)
    })
  }

  /** Removes the context registration (unmount). */
  ngOnDestroy(): void {
    PanelCloseDomContext.remove(this.host.nativeElement)
  }
}

Progress

Progress component.

The host is the wrapper div React renders; aria-valuenow is clamped into [0, max] to match the clamped visual bar.

@Component({
  selector: 'div[mol-progress]',
  standalone: true,
  inputs: [
    'value',
    'max',
    'size',
    'color',
    'showValue',
    'label',
    'indeterminate',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `@if (label || showValue) {
      <div [class]="cm().progressLabelContainer">
        @if (label) {
          <span [class]="cm().progressLabelText">{{ label }}</span>
        }
        @if (showValue) {
          <span [class]="cm().progressLabelText"
            ><ng-container>{{ rounded }}</ng-container
            ><ng-container>{{ '%' }}</ng-container></span
          >
        }
      </div>
    }
    <div
      [class]="cm().cn(cm().progress(), cm().progressHeight(size ?? 'md'))"
      role="progressbar"
      [attr.aria-valuenow]="indeterminate ? null : clamped"
      aria-valuemin="0"
      [attr.aria-valuemax]="max"
      [attr.aria-label]="label ?? progressLabel()"
    >
      <div [class]="barClasses()" [attr.style]="barStyle()"></div>
    </div>`,
})
export class Progress implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host wrapper `<div>`. */
  readonly element = hostElement(this.host)

  /** Progress value (0–max). */
  value: ProgressProps['value'] = 0
  /** Maximum value. */
  max?: ProgressProps['max'] = 100
  /** Progress size. */
  size?: ProgressProps['size']
  /** Progress color. */
  color?: ProgressProps['color']
  /** Whether the numeric value label renders. */
  showValue?: ProgressProps['showValue']
  /** Accessible label. */
  label?: ProgressProps['label']
  /** Whether the progress is indeterminate. */
  indeterminate?: ProgressProps['indeterminate']
  /** Extra classes joined onto the wrapper classes. */
  className?: ProgressProps['className']
  /** Inline style object (React camelCase). */
  style?: ProgressProps['style']
  /** `data-testid`. */
  testId?: ProgressProps['testId']
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: ProgressProps['automationId']
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The percentage, clamped to [0, 100].
   * @returns The percentage.
   */
  get percent(): number {
    const max = this.max ?? 100
    return Math.min(Math.max((this.value / max) * 100, 0), 100)
  }

  /**
   * The rounded percentage shown in the value label.
   * @returns The whole percentage.
   */
  get rounded(): number {
    return Math.round(this.percent)
  }

  /**
   * The clamped aria-valuenow.
   * @returns The clamped value.
   */
  get clamped(): number {
    const max = this.max ?? 100
    return Math.min(Math.max(this.value, 0), max)
  }

  /**
   * The accessible label with the localized default.
   * @returns The label text.
   */
  progressLabel(): string {
    return this.i18n.t('ui.progress.label', undefined, { defaultValue: 'Progress' })
  }

  /**
   * Computes the wrapper class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().progressWrapper, this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Computes the bar class list.
   * @returns The class string.
   */
  barClasses(): string {
    return this.cm().cn(
      this.cm().progressBar(),
      this.cm().progressColor(this.color ?? 'primary'),
      this.indeterminate && this.cm().progressIndeterminate,
    )
  }

  /**
   * Serializes the bar's inline style (the translateX fill, unless indeterminate).
   * @returns The style attribute text.
   */
  barStyle(): string | null {
    if (this.indeterminate) return null
    return styleText({ transform: `translateX(-${100 - this.percent}%)` })
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }
}

PromptDialog

PromptDialog component.

Composed from Modal, Input and Button exactly as React composes them. Resolving onSubmit closes the dialog and resets it; a rejection keeps it open with the value intact. React's root is a Modal, which renders a portal while open and nothing while closed, so the host element leaves the page and the portal renders in document.body.

@Component({
  selector: 'mol-prompt-dialog',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Button, Input, Modal, MolTemplateOutlet],
  inputs: [
    'open',
    'title',
    'description',
    'placeholder',
    'initialValue',
    'onSubmit',
    'confirmLabel',
    'cancelLabel',
    'destructive',
    'inputMolId',
    'confirmMolId',
    'cancelMolId',
  ],
  outputs: ['close'],
  template: `<mol-modal
    #modal
    [open]="open"
    [initialFocus]="inputTarget"
    (close)="onModalClose()"
    [attr.aria-labelledby]="ariaLabelledBy()"
    [attr.aria-describedby]="rendersNode(description) ? descriptionId : null"
    ><form (submit)="handleSubmit($event)">
      <div [class]="cm().stack(3)">
        <h2
          #titleSlot
          [attr.id]="ariaLabelledBy()"
          [class]="cm().cn(cm().textSize('lg'), cm().fontWeight('bold'))"
        >
          @if (isGiven(title)) {
            <ng-container [molTemplateOutlet]="asTemplate(title)"></ng-container
            >{{ nodeText(title) }}
          } @else {
            <ng-content select="[slot=title]"></ng-content>
          }
        </h2>
        @if (asTemplate(description); as descriptionTemplate) {
          <p [attr.id]="descriptionId" [class]="cm().textSize('sm')">
            <ng-container [molTemplateOutlet]="descriptionTemplate"></ng-container>
          </p>
        } @else if (rendersNode(description)) {
          <p
            [attr.id]="descriptionId"
            [class]="cm().textSize('sm')"
            [textContent]="nodeText(description)"
          ></p>
        }
        <div
          mol-input
          [value]="value()"
          [placeholder]="placeholder"
          [disabled]="pending()"
          [attr.data-mol-id]="inputMolId"
          (change)="onInput($event)"
        ></div>
        <ng-content></ng-content>
        <div [class]="cm().flex({ justify: 'end', gap: 'sm' })">
          <button
            mol-button
            [type]="'button'"
            [variant]="'ghost'"
            [disabled]="pending()"
            (click)="close.emit($event)"
            [attr.data-mol-id]="cancelMolId"
          >
            @if (isGiven(cancelLabel)) {
              <ng-container [molTemplateOutlet]="asTemplate(cancelLabel)"></ng-container
              >{{ nodeText(cancelLabel) }}
            } @else {
              {{ cancelText() }}
            }</button
          ><button
            mol-button
            [type]="'submit'"
            [variant]="'solid'"
            [color]="destructive ? 'error' : 'primary'"
            [disabled]="pending()"
            [attr.data-mol-id]="confirmMolId"
          >
            @if (isGiven(confirmLabel)) {
              <ng-container [molTemplateOutlet]="asTemplate(confirmLabel)"></ng-container
              >{{ nodeText(confirmLabel) }}
            } @else {
              {{ confirmText() }}
            }
          </button>
        </div>
      </div>
    </form></mol-modal
  >`,
})
export class PromptDialog implements AfterViewInit, DoCheck {
  /** Whether the dialog is open. */
  open: PromptDialogProps['open'] = false
  /** Dialog heading (node-valued prop). */
  title?: PromptDialogProps['title']
  description?: PromptDialogProps['description']
  /** Input placeholder. */
  placeholder?: PromptDialogProps['placeholder']
  initialValue?: PromptDialogProps['initialValue'] = ''
  /** Called with the entered value on confirm. */
  onSubmit?: PromptDialogProps['onSubmit']
  /** Confirm-button label (node-valued prop). */
  confirmLabel?: PromptDialogProps['confirmLabel']
  /** Cancel-button label (node-valued prop). */
  cancelLabel?: PromptDialogProps['cancelLabel']
  destructive?: PromptDialogProps['destructive'] = false
  /** `data-mol-id` for the text input. */
  inputMolId?: PromptDialogProps['inputMolId']
  /** `data-mol-id` for the confirm button. */
  confirmMolId?: PromptDialogProps['confirmMolId']
  /** `data-mol-id` for the cancel button. */
  cancelMolId?: PromptDialogProps['cancelMolId']

  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText
  /** Whether a node-valued prop was given. */
  readonly isGiven = isGiven
  /** Whether a node-valued prop renders anything. */
  readonly rendersNode = rendersNode

  @Output() readonly close = new EventEmitter<MouseEvent | undefined>()

  @ViewChild('titleSlot') titleSlot?: ElementRef<HTMLHeadingElement>
  @ViewChild(Input) inputComponent?: Input
  @ViewChild('modal', { read: ElementRef }) modalElement?: ElementRef<HTMLElement>

  readonly titleId = nextInstanceId()

  readonly descriptionId = nextInstanceId()

  readonly ariaLabelledBy = signal<string | null>(null)

  /** The current input value. */
  readonly value = signal('')
  /** Whether a submit is in flight. */
  readonly pending = signal(false)

  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  private lastOpen = false
  private lastInitial = ''

  readonly inputTarget = elementTarget(() => this.inputComponent?.inputEl?.nativeElement)

  constructor() {
    usePlacement((hasContent) => {
      setElementPresent(this.host.nativeElement, false)
      setHostRoot(this.host.nativeElement, this.modalElement?.nativeElement)
      this.ariaLabelledBy.set(
        rendersNode(this.title) || hasContent(this.titleSlot?.nativeElement) ? this.titleId : null,
      )
      this.applyInputLabel(hasContent)
    })
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The cancel button's label. */
  cancelText(): string {
    return typeof this.cancelLabel === 'string'
      ? this.cancelLabel
      : this.i18n.t('prompt.cancel', {}, { defaultValue: 'Cancel' })
  }

  /** The confirm button's label. */
  confirmText(): string {
    return typeof this.confirmLabel === 'string'
      ? this.confirmLabel
      : this.i18n.t('prompt.confirm', {}, { defaultValue: 'Confirm' })
  }

  inputLabel(hasContent: SlotReader): string | null {
    const heading = this.titleSlot?.nativeElement
    const nodes = isGiven(this.title)
      ? Array.from(heading?.childNodes ?? [])
      : hasContent.nodes(heading)
    const hasElement = nodes.some((node) => node.nodeType === Node.ELEMENT_NODE)
    const text = nodes
      .filter((node) => node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE)
      .map((node) => node.textContent ?? '')
      .join('')
      .trim()
    if (!hasElement && text) return text
    return this.placeholder ?? null
  }

  ngAfterViewInit(): void {
    this.lastOpen = !!this.open
    this.lastInitial = this.initialValue ?? ''
    if (this.open) {
      this.value.set(this.initialValue ?? '')
      this.pending.set(false)
    }
  }

  ngDoCheck(): void {
    const open = !!this.open
    if (open !== this.lastOpen || (open && this.initialValue !== this.lastInitial)) {
      this.lastOpen = open
      this.lastInitial = this.initialValue ?? ''
      if (open) {
        this.value.set(this.initialValue ?? '')
        this.pending.set(false)
      }
    }
  }

  private applyInputLabel(hasContent: SlotReader): void {
    const input = this.inputComponent?.inputEl?.nativeElement
    if (!input) return
    const label = this.inputLabel(hasContent)
    if (label === null) input.removeAttribute('aria-label')
    else input.setAttribute('aria-label', label)
  }

  onInput(event: KitFieldChangeEvent): void {
    this.value.set(event.target.value)
  }

  onModalClose(): void {
    if (this.pending()) return
    this.close.emit()
  }

  handleSubmit(event: Event): void {
    event.preventDefault()
    if (this.pending()) return
    this.pending.set(true)
    void (async (): Promise<void> => {
      try {
        await this.onSubmit?.(this.value())
        this.pending.set(false)
        this.close.emit()
      } catch (_error: unknown) {
        this.pending.set(false)
      }
    })()
  }
}

(Member comments are shortened to their first sentence, and the 25 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/prompt-dialog.component.d.ts.)

RadioGroup

RadioGroup component.

The host is the role="radiogroup" div React renders. Selecting an option emits that option's VALUE (not the DOM event) through the change output, exactly like React's per-option handler.

@Component({
  selector: 'div[mol-radio-group]',
  standalone: true,
  imports: [MolControlledChecked],
  inputs: [
    'options',
    'value',
    'size',
    'label',
    'name',
    'direction',
    'error',
    'className',
    'style',
    'testId',
    'disabled',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'className',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.role]': '"radiogroup"',
    '[attr.aria-label]': 'groupLabel()',
    '[attr.aria-invalid]': 'error ? "true" : null',
    '[attr.aria-describedby]': 'error ? errorId() : null',
  },
  template: `@if (label) {
      <div [class]="cm().cn(cm().label({ required: false }), cm().sp('mb', 2))">{{ label }}</div>
    }
    <div [class]="cm().radioGroupLayout(direction ?? 'vertical')">
      @for (option of options ?? []; track option.value) {
        <label
          [class]="
            cm().cn(cm().controlLabel, (disabled || option.disabled) && cm().controlDisabled)
          "
        >
          <input
            type="radio"
            [attr.name]="groupName()"
            [attr.value]="option.value"
            [molChecked]="value === option.value"
            [disabled]="disabled || option.disabled"
            (change)="select($event)"
            [attr.data-state]="value === option.value ? 'checked' : 'unchecked'"
            [class]="cm().cn(cm().radio({ error: !!error }), cm().cursorPointer)"
          />
          <span [class]="cm().controlText">{{ option.label }}</span>
        </label>
      }
    </div>
    @if (error) {
      <p [attr.id]="errorId()" [class]="cm().cn(cm().formError, cm().sp('mt', 1))">{{ error }}</p>
    }`,
})
export class RadioGroup implements HasElement<HTMLDivElement> {
  /** The options to render. */
  options?: RadioOption[]
  /** The selected option value. */
  value?: string
  /** Group size (kept for prop parity). */
  size?: Size
  /** Group label. */
  label?: string
  /** Native radio group name (defaults to a stable generated name). */
  name?: string
  /** Layout direction. */
  direction?: 'vertical' | 'horizontal'
  /** Error message. */
  error?: string
  /** Extra classes for the group root. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** Disables every option. */
  disabled?: boolean
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The native radio group name.
   * @returns The name value.
   */
  groupName(): string {
    return this.name || this.generatedName
  }

  /**
   * The error paragraph id.
   * @returns The id value.
   */
  errorId(): string {
    return `${this.groupName()}-error`
  }

  /**
   * The accessible group label.
   * @returns The label text.
   */
  groupLabel(): string {
    return (
      this.label ?? this.i18n.t('ui.radioGroup.label', undefined, { defaultValue: 'Radio group' })
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Emits the selected option's value; the change event stops here so the
   * host-level `change` output binding does not record it a second time. Every
   * radio's checked state is then restored to the controlled `value` — checking
   * one radio natively UNCHECKS the previously selected one, so restoring only
   * the clicked input would leave the group with no selection at all.
   *
   * @param event - The native radio change event.
   */
  select(event: Event): void {
    event.stopPropagation()
    if (!(event.target instanceof HTMLInputElement)) return
    this.change.emit(event.target.value)
    // React always controls radios (checked={value === option.value}); restore.
    const radios = this.host.nativeElement.querySelectorAll<HTMLInputElement>('input[type="radio"]')
    for (const radio of Array.from(radios)) radio.checked = this.value === radio.value
  }

  /** Fires the selected option's value. */
  @Output() readonly change = new EventEmitter<string>()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `role="radiogroup"` `<div>`. */
  readonly element = hostElement(this.host)

  /** The per-instance native radio-group name when the caller gives none (React's `useId`). */
  private readonly generatedName = nextInstanceId()
}

ResponsiveAppShell

Root of the responsive app shell: owns the breakpoint and drawer state, closes the drawer on navigation and on desktop-crossing resizes, and provides everything to the sub-components through the DOM-ancestor context (React's context provider renders no DOM).

@Component({
  selector: 'div[mol-responsive-app-shell]',
  standalone: true,
  inputs: ['sidebarWidth', 'className', 'dataMolId'],
  host: {
    '[class]': 'classes()',
    '[style]': 'rootStyle()',
    '[attr.data-mol-id]': 'dataMolId',
  },
  template: `<ng-content></ng-content>`,
})
export class ResponsiveAppShell implements DoCheck, OnDestroy {
  /** Sidebar (and drawer) width: `sm`/`md`/`lg` or an exact pixel number. */
  sidebarWidth?: ResponsiveAppShellProps['sidebarWidth']
  /** Extra classes on the root flex container. */
  className?: ResponsiveAppShellProps['className']
  /** `data-mol-id` for the root (default `shell-root`). */
  dataMolId?: ResponsiveAppShellProps['dataMolId'] = 'shell-root'

  /** Whether the viewport is at the desktop breakpoint. */
  readonly isDesktop = useIsDesktop()
  /** Whether the mobile drawer is open. */
  readonly drawerOpen = signal(false)
  /** Whether a Drawer sub-component is composed. */
  readonly hasDrawer = signal(false)
  /** The drawer panel's DOM id. */
  readonly drawerId = nextInstanceId()
  /** Router state: navigation closes the drawer. */
  readonly router = useRouter()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private lastRoute: string | null = null
  private readonly routeEffect = effect(() => {
    const location = this.router.location()
    const key = `${location.pathname}${location.search}${(location as { hash?: string }).hash ?? ''}`
    if (this.lastRoute === key) return
    this.lastRoute = key
    // React's effect runs on mount too; closing a closed drawer is a no-op.
    this.drawerOpen.set(false)
  })
  private readonly desktopEffect = effect(() => {
    if (this.isDesktop()) this.drawerOpen.set(false)
  })

  /** Registers the shell context on the host before any projected child resolves it. */
  constructor() {
    ShellDomContext.provide(this.host.nativeElement, new ShellContextValueImpl(this))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The root class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().flex({}),
      this.cm().page,
      this.cm().minH('screen'),
      this.className,
    )
  }

  /**
   * The root's inline style (row on desktop, column below the breakpoint).
   * @returns The style attribute text.
   */
  rootStyle(): string | null {
    return styleText({ flexDirection: this.isDesktop() ? 'row' : 'column' })
  }

  /** Keeps a plain-field drawer width change in sync with the sub-components. */
  ngDoCheck(): void {
    // Nothing to reconcile: every value is read through the context getters.
  }

  /** Removes the context registration (unmount). */
  ngOnDestroy(): void {
    ShellDomContext.remove(this.host.nativeElement)
  }
}

ResponsiveAppShellTopBar

The shell's <header> landmark: the drawer menu trigger (mobile, when a Drawer is composed), the brand, and trailing actions.

@Component({
  selector: 'header[mol-responsive-app-shell-topbar]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg, MolTemplateOutlet],
  inputs: ['brand', 'actions', 'mobileOnly', 'className', 'dataMolId', 'testId'],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-mol-id]': 'dataMolId',
    '[attr.data-testid]': 'testId',
  },
  template: `<div
      [class]="cm().cn(cm().flex({ align: 'center', gap: 'sm' }))"
      [style]="'min-width: 0px'"
    >
      @if (shell().hasDrawer && !shell().isDesktop) {
        <button
          type="button"
          (click)="shell().openDrawer()"
          [attr.aria-label]="triggerLabel()"
          [attr.aria-expanded]="shell().drawerOpen ? 'true' : 'false'"
          [attr.aria-controls]="shell().drawerId"
          data-mol-id="shell-drawer-open"
          [class]="triggerClasses()"
          [style]="triggerStyle()"
        >
          <svg mol-icon [data]="menuIcon()" />
        </button>
      }
      <div #brandSlot [style]="'min-width: 0px'">
        <ng-content select="[slot=brand]"></ng-content
        ><ng-container [molTemplateOutlet]="asTemplate(brand)"></ng-container>{{ nodeText(brand) }}
      </div>
    </div>
    <div #actionsSlot [class]="cm().cn(cm().flex({ align: 'center', gap: 'sm' }), cm().shrink0)">
      <ng-content select="[slot=actions]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(actions)"></ng-container
      >{{ nodeText(actions) }}
    </div>`,
})
export class ResponsiveAppShellTopBar implements OnInit {
  /** Brand/title node (React's `brand`), rendered after the menu trigger. */
  brand?: ResponsiveAppShellTopBarProps['brand']
  /** Trailing actions node (React's `actions`). */
  actions?: ResponsiveAppShellTopBarProps['actions']
  /** Render the top bar only below the breakpoint (no dead DOM on desktop). */
  mobileOnly?: ResponsiveAppShellTopBarProps['mobileOnly'] = false
  /** Extra classes on the `<header>`. */
  className?: ResponsiveAppShellTopBarProps['className']
  /** `data-mol-id` (default `shell-topbar`). */
  dataMolId?: ResponsiveAppShellTopBarProps['dataMolId'] = 'shell-topbar'
  /** `data-testid`. */
  testId?: ResponsiveAppShellTopBarProps['testId']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText

  /** The brand wrapper (detached when no brand is given). */
  @ViewChild('brandSlot') brandSlot?: ElementRef<HTMLDivElement>
  /** The actions wrapper (detached when no actions are given). */
  @ViewChild('actionsSlot') actionsSlot?: ElementRef<HTMLDivElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private hasBrand = false
  private hasActions = false

  /** Prepares the header's mount condition (React's `mobileOnly`). */
  constructor() {
    usePlacement((hasContent) => {
      // Resolve the shell context while the host is still in the page: a mobileOnly header
      // leaves it on desktop, and its ancestors are the only way to the shell root.
      void this.shell()
      this.syncWrappers(hasContent)
    })
    // Leaves no element in the page while the bar is hidden on desktop (React renders null).
    useHostPresence(() => !(this.mobileOnly && this.shell().isDesktop))
  }

  /**
   * The nearest shell context.
   * @returns The context (its defaults outside the shell).
   */
  shell(): ShellContextValue {
    // Cached: a detached (mobileOnly) header loses its DOM ancestors, so the
    // lookup must not be repeated after the element leaves the tree.
    return this.readContext() ?? contextOrDefault(null)
  }

  /**
   * Reads the shell context from the host's place in the rendered tree.
   * @returns The context, or null outside the shell.
   */
  private readContext(): ShellContextValue | null {
    return ShellDomContext.find(this.host.nativeElement) ?? null
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The header class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', justify: 'between', gap: 'sm' }),
      this.cm().sp('px', 4),
      this.cm().h(14),
      this.cm().surface,
      this.cm().borderB,
      this.cm().position('sticky'),
      this.className,
    )
  }

  /**
   * The header's inline style (sticky offset and z-index below the drawer).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText({ top: 0, zIndex: 20 })
  }

  /**
   * The drawer trigger's class list.
   * @returns The class string.
   */
  triggerClasses(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', justify: 'center' }),
      this.cm().shrink0,
      this.cm().roundedFull,
      this.cm().cursorPointer,
    )
  }

  /** The drawer trigger's inline size (44px minimum tap target). */
  triggerStyle(): string | null {
    return styleText({ width: 44, height: 44 })
  }

  /**
   * The trigger's accessible label.
   * @returns The label text.
   */
  triggerLabel(): string {
    return this.i18n.t('appShell.openMenu', {}, { defaultValue: 'Open navigation menu' })
  }

  /**
   * The menu glyph.
   * @returns The resolved icon.
   */
  menuIcon(): ResolvedIcon {
    return resolveIcon('menu', this.cm().iconMd)
  }

  /**
   * Refuses to render outside a shell (React's `useShellContext` throws).
   */
  ngOnInit(): void {
    requireShell(this.readContext(), 'ResponsiveAppShell.TopBar')
  }

  /** Applies React's conditional brand/actions wrappers. */
  private syncWrappers(hasContent: SlotReader): void {
    this.hasBrand = isGiven(this.brand) || hasContent(this.brandSlot?.nativeElement)
    this.hasActions = isGiven(this.actions) || hasContent(this.actionsSlot?.nativeElement)
    setElementPresent(this.brandSlot?.nativeElement, this.hasBrand)
    setElementPresent(this.actionsSlot?.nativeElement, this.hasActions)
  }
}

ResponsiveAppShellSidebar

The desktop sidebar (<aside> + <nav> landmarks); renders nothing below the breakpoint (the Drawer carries the nav there).

@Component({
  selector: 'aside[mol-responsive-app-shell-sidebar]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolTemplateOutlet],
  inputs: ['navLabel', 'footer', 'className', 'dataMolId', 'testId'],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-mol-id]': 'dataMolId',
    '[attr.data-testid]': 'testId',
  },
  template: `<nav [attr.aria-label]="navLabelText()" [class]="cm().cn(cm().flex1, cm().stack(1))">
      <ng-content></ng-content>
    </nav>
    <div
      #footerSlot
      [class]="
        cm().cn(
          cm().flex({ align: 'center', justify: 'between', gap: 'sm' }),
          cm().borderT,
          cm().sp('p', 3),
          cm().shrink0
        )
      "
    >
      <ng-content select="[slot=footer]"></ng-content
      ><ng-container [molTemplateOutlet]="asTemplate(footer)"></ng-container>{{ nodeText(footer) }}
    </div>`,
})
export class ResponsiveAppShellSidebar implements OnInit {
  /** Accessible name for the `<nav>` landmark. */
  navLabel?: ResponsiveAppShellSidebarProps['navLabel']
  /** Below-nav content (React's `footer` node value). */
  footer?: ResponsiveAppShellSidebarProps['footer']
  /** Extra classes on the `<aside>`. */
  className?: ResponsiveAppShellSidebarProps['className']
  /** `data-mol-id` (default `shell-sidebar`). */
  dataMolId?: ResponsiveAppShellSidebarProps['dataMolId'] = 'shell-sidebar'
  /** `data-testid`. */
  testId?: ResponsiveAppShellSidebarProps['testId']

  /** Template helpers (templates see only class members). */
  readonly asTemplate = asTemplate
  /** Renders a plain-string/number node value. */
  readonly nodeText = nodeText

  /** The footer wrapper (detached when no footer is given). */
  @ViewChild('footerSlot') footerSlot?: ElementRef<HTMLDivElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  private hasFooter = false

  /** Prepares the aside's mount condition (React's breakpoint check). */
  constructor() {
    usePlacement((hasContent) => {
      // Resolve the shell context while the host is still in the page: below the breakpoint
      // it leaves the page, and its ancestors are the only way to the shell root.
      void this.shell()
      this.syncWrapper(hasContent)
    })
    // Leaves no element in the page below the breakpoint (React renders null).
    useHostPresence(() => this.shell().isDesktop)
  }

  /**
   * The nearest shell context.
   * @returns The context (its defaults outside the shell).
   */
  shell(): ShellContextValue {
    // Cached: a detached (mobile) sidebar loses its DOM ancestors.
    return this.readContext() ?? contextOrDefault(null)
  }

  /**
   * Reads the shell context from the host's place in the rendered tree.
   * @returns The context, or null outside the shell.
   */
  private readContext(): ShellContextValue | null {
    return ShellDomContext.find(this.host.nativeElement) ?? null
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The aside class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().flex({ direction: 'col' }),
      this.cm().shrink0,
      this.cm().surface,
      this.cm().borderR,
      this.cm().h('screen'),
      this.cm().position('sticky'),
      this.className,
    )
  }

  /**
   * The aside's inline style (exact width, sticky top, internal scroll).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText({ top: 0, width: this.shell().sidebarWidthPx, overflowY: 'auto' })
  }

  /**
   * The nav's accessible label.
   * @returns The label text.
   */
  navLabelText(): string {
    return (
      this.navLabel ??
      this.i18n.t('appShell.primaryNav', {}, { defaultValue: 'Primary navigation' })
    )
  }

  /**
   * Refuses to render outside a shell (React's `useShellContext` throws).
   */
  ngOnInit(): void {
    requireShell(this.readContext(), 'ResponsiveAppShell.Sidebar')
  }

  /** Applies React's conditional footer wrapper. */
  private syncWrapper(hasContent: SlotReader): void {
    this.hasFooter = isGiven(this.footer) || hasContent(this.footerSlot?.nativeElement)
    setElementPresent(this.footerSlot?.nativeElement, this.hasFooter)
  }
}

ResponsiveAppShellDrawer

The mobile nav drawer (<768px): a left-anchored dialog panel over a backdrop, portaled into document.body.

Projected content is created with the consumer's view, so a closed drawer's content exists while hidden: its components, effects and fetches run. React mounts it only while shown, and again each time it shows. Write content with state as *molLazy (MolLazy from @molecule/app-angular): it is created when it shows and destroyed when it hides, as React's is.

@Component({
  selector: 'mol-responsive-app-shell-drawer',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg, MolTemplateOutlet],
  inputs: [
    'header',
    'navLabel',
    'footer',
    'showCloseButton',
    'className',
    'dataMolId',
    'closeDataMolId',
    'testId',
  ],
  template: `<div #overlay [class]="cm().overlay" aria-hidden="true"></div>
    <div
      #wrapper
      [class]="cm().cn(cm().position('fixed'), cm().inset0)"
      [style]="wrapperStyle()"
      role="presentation"
      (click)="handleBackdropClick($event)"
    >
      <div
        #panel
        [id]="shell().drawerId"
        role="dialog"
        aria-modal="true"
        [attr.aria-label]="navLabelText()"
        tabindex="-1"
        [class]="panelClasses()"
        [style]="panelStyle()"
        [attr.data-mol-id]="dataMolId"
        [attr.data-testid]="testId"
      >
        <div
          #headerRow
          [class]="
            cm().cn(
              cm().flex({ align: 'center', justify: 'between', gap: 'sm' }),
              cm().sp('p', 3),
              cm().shrink0
            )
          "
        >
          <div #headerSlot [style]="'min-width: 0px'">
            <ng-content select="[slot=header]"></ng-content
            ><ng-container [molTemplateOutlet]="asTemplate(header)"></ng-container
            >{{ nodeText(header) }}
          </div>
          @if (!headerPresent()) {
            <span aria-hidden="true"></span>
          }
          @if (showCloseButton) {
            <button
              type="button"
              (click)="shell().closeDrawer()"
              [attr.aria-label]="closeLabel()"
              [attr.data-mol-id]="closeDataMolId"
              [class]="closeClasses()"
            >
              <svg mol-icon [data]="closeIcon()" />
            </button>
          }
        </div>
        <nav [attr.aria-label]="navLabelText()" [class]="cm().cn(cm().flex1, cm().stack(1))">
          <ng-content></ng-content>
        </nav>
        <div
          #footerSlot
          [class]="
            cm().cn(
              cm().flex({ direction: 'col', gap: 'sm' }),
              cm().borderT,
              cm().sp('p', 3),
              cm().shrink0
            )
          "
        >
          <ng-content select="[slot=footer]"></ng-content
          ><ng-container [molTemplateOutlet]="asTemplate(footer)"></ng-container
          >{{ nodeText(footer) }}
        </div>
      </div>
    </div>`,
})
export class ResponsiveAppShellDrawer implements OnInit, AfterViewInit, DoCheck, OnDestroy {
  header?: ResponsiveAppShellDrawerProps['header']
  navLabel?: ResponsiveAppShellDrawerProps['navLabel']
  footer?: ResponsiveAppShellDrawerProps['footer']
  showCloseButton?: ResponsiveAppShellDrawerProps['showCloseButton'] = true
  /** Extra classes on the dialog panel. */
  className?: ResponsiveAppShellDrawerProps['className']
  dataMolId?: ResponsiveAppShellDrawerProps['dataMolId'] = 'shell-drawer'
  closeDataMolId?: ResponsiveAppShellDrawerProps['closeDataMolId'] = 'shell-drawer-close'
  /** `data-testid` for the panel. */
  testId?: ResponsiveAppShellDrawerProps['testId']

  readonly asTemplate = asTemplate
  readonly nodeText = nodeText

  /** The backdrop element. */
  @ViewChild('overlay') overlay?: ElementRef<HTMLDivElement>
  /** The fixed wrapper. */
  @ViewChild('wrapper') wrapper?: ElementRef<HTMLDivElement>
  /** The dialog panel. */
  @ViewChild('panel') panel?: ElementRef<HTMLDivElement>
  @ViewChild('headerRow') headerRow?: ElementRef<HTMLDivElement>
  @ViewChild('headerSlot') headerSlot?: ElementRef<HTMLDivElement>
  @ViewChild('footerSlot') footerSlot?: ElementRef<HTMLDivElement>

  readonly headerPresent = signal(false)

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  private readonly i18n = useTranslation()

  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID))
  private readonly environmentInjector = inject(EnvironmentInjector)
  private readonly layer = new OverlayLayer((focus) => {
    if (!this.environmentInjector.destroyed)
      afterNextRender({ read: focus }, { injector: this.environmentInjector })
  })
  private hasFooter = false
  private lastOpen: boolean | undefined

  constructor() {
    usePlacement((hasContent) => {
      void this.shell()
      this.syncWrappers(hasContent)
      this.syncOpen()
    })
  }

  /** The nearest shell context. */
  shell(): ShellContextValue {
    return this.readContext() ?? contextOrDefault(null)
  }

  private readContext(): ShellContextValue | null {
    return ShellDomContext.find(this.host.nativeElement) ?? null
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The panel class list. */
  panelClasses(): string {
    return this.cm().cn(this.cm().flex({ direction: 'col' }), this.cm().surface, this.className)
  }

  panelStyle(): string | null {
    return styleText({
      width: this.shell().sidebarWidthPx,
      maxWidth: '85vw',
      overflowY: 'auto',
    })
  }

  wrapperStyle(): string | null {
    return styleText({ zIndex: 41 })
  }

  /** The close button's class list. */
  closeClasses(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', justify: 'center' }),
      this.cm().w(10),
      this.cm().h(10),
      this.cm().shrink0,
      this.cm().roundedFull,
      this.cm().cursorPointer,
      this.cm().textMuted,
    )
  }

  /** The nav/dialog accessible label. */
  navLabelText(): string {
    return (
      this.navLabel ??
      this.i18n.t('appShell.primaryNav', {}, { defaultValue: 'Primary navigation' })
    )
  }

  /** The close button's accessible label. */
  closeLabel(): string {
    return this.i18n.t('appShell.closeMenu', {}, { defaultValue: 'Close navigation menu' })
  }

  /** The close glyph. */
  closeIcon(): ResolvedIcon {
    return resolveIcon('x-mark', this.cm().iconMd)
  }

  handleBackdropClick(event: MouseEvent): void {
    if (event.target !== event.currentTarget) {
      event.stopPropagation()
      return
    }
    this.layer.dismissBackdrop()
  }

  ngOnInit(): void {
    requireShell(this.readContext(), 'ResponsiveAppShell.Drawer')
  }

  ngAfterViewInit(): void {
    this.shell().registerDrawer(true)
    this.syncOpen()
  }

  ngDoCheck(): void {
    this.syncOpen()
  }

  ngOnDestroy(): void {
    this.shell().registerDrawer(false)
    this.layer.release()
  }

  private syncWrappers(hasContent: SlotReader): void {
    this.headerPresent.set(isGiven(this.header) || hasContent(this.headerSlot?.nativeElement))
    this.hasFooter = isGiven(this.footer) || hasContent(this.footerSlot?.nativeElement)
    setElementPresent(
      this.headerRow?.nativeElement,
      this.headerPresent() || (this.showCloseButton ?? true),
    )
    setElementPresent(this.headerSlot?.nativeElement, this.headerPresent())
    setElementPresent(this.footerSlot?.nativeElement, this.hasFooter)
    setElementPresent(this.host.nativeElement, false)
  }

  private syncOpen(): void {
    const shell = this.shell()
    const open = this.browser && shell.drawerOpen && !shell.isDesktop
    const panel = this.panel?.nativeElement
    const overlay = this.overlay?.nativeElement
    const wrapper = this.wrapper?.nativeElement
    if (!panel || !overlay || !wrapper || open === this.lastOpen) return
    this.lastOpen = open
    if (open) {
      const { body } = panel.ownerDocument
      placeElement(overlay, body)
      placeElement(wrapper, body)
      this.layer.sync({
        open: true,
        kind: 'modal',
        surface: { current: panel },
        dismissKey: true,
        dismissBackdrop: true,
        focus: { trap: true, restore: 'opener' },
        lockScroll: true,
        onDismiss: () => shell.closeDrawer(),
      })
    } else {
      this.layer.release()
      placeElement(overlay, null)
      setElementPresent(overlay, false)
      placeElement(wrapper, null)
      setElementPresent(wrapper, false)
    }
  }
}

(Member comments are shortened to their first sentence, and the 34 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/responsive-app-shell.component.d.ts.)

ResponsiveAppShellContent

The shell's <main> landmark.

@Component({
  selector: 'main[mol-responsive-app-shell-content]',
  standalone: true,
  inputs: ['className', 'style', 'dataMolId', 'testId'],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-mol-id]': 'dataMolId',
    '[attr.data-testid]': 'testId',
  },
  template: `<ng-content></ng-content>`,
})
export class ResponsiveAppShellContent {
  /** Extra classes on the `<main>`. */
  className?: ResponsiveAppShellContentProps['className']
  /** Inline styles on the `<main>`. */
  style?: ResponsiveAppShellContentProps['style']
  /** `data-mol-id` (default `shell-content`). */
  dataMolId?: ResponsiveAppShellContentProps['dataMolId'] = 'shell-content'
  /** `data-testid`. */
  testId?: ResponsiveAppShellContentProps['testId']

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The main class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().flex1, this.className)
  }

  /**
   * The main's inline style (`min-width: 0` plus the caller's style).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText({ minWidth: 0, ...this.style })
  }
}

Select

Select component.

The host is the field's outer wrapper React renders (the shared field layout's root, a flex column). React's select value is written through the value PROPERTY (a select has no value attribute); a controlled value is restored after a change exactly like React's controlled-input state restore.

@Component({
  selector: 'div[mol-select]',
  standalone: true,
  imports: [MolIconSvg],
  inputs: [
    'options',
    'value',
    'defaultValue',
    'size',
    'label',
    'placeholder',
    'error',
    'hint',
    'externalDescription: aria-describedby',
    'externalInvalid: aria-invalid',
    'clearable',
    'className',
    'style',
    'testId',
    'disabled',
    'required',
    'name',
    'id',
    'automationId',
    'dataMolId: data-mol-id',
    'onFocus',
    'onBlur',
    'onKeyDown',
  ],
  host: {
    '[class]': 'field().root',
  },
  template: `@if (label) {
      <label
        [attr.for]="selectId()"
        [class]="cm().cn(cm().label({ required: !!required }), cm().labelBlock)"
        >{{ label }}</label
      >
    }
    <div [class]="field().inner">
      <select
        [attr.id]="selectId()"
        [attr.name]="name"
        [disabled]="disabled"
        [attr.required]="required ? '' : null"
        [attr.aria-invalid]="
          error || fieldContext()?.invalid ? true : (externalInvalid ?? hostAria.invalid() ?? false)
        "
        [attr.aria-describedby]="mergedDescribedBy()"
        [class]="classes()"
        [attr.style]="hostStyle()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        (change)="handleChange($event)"
        (focusin)="onFocus?.($event)"
        (focusout)="onBlur?.($event)"
        (keydown)="onKeyDown?.($event)"
        #selectEl
      >
        @if (placeholder) {
          <option value="" disabled>{{ placeholder }}</option>
        }
        @if (clearable && !placeholder) {
          <option value="">{{ clearText() }}</option>
        }
        @for (entry of optionGroups(); track $index) {
          @if (entry.group === '') {
            @for (option of entry.options; track option.value) {
              <option [attr.value]="option.value" [attr.disabled]="option.disabled ? '' : null">
                {{ option.label }}
              </option>
            }
          } @else {
            <optgroup [attr.label]="entry.group">
              @for (option of entry.options; track option.value) {
                <option [attr.value]="option.value" [attr.disabled]="option.disabled ? '' : null">
                  {{ option.label }}
                </option>
              }
            </optgroup>
          }
        }
      </select>
      <div [class]="cm().inputRightElement" [attr.style]="'pointer-events: none'">
        <svg mol-icon [data]="chevron()" />
      </div>
    </div>
    @if (error) {
      <p [attr.id]="describedBy()" [class]="cm().formError">{{ error }}</p>
    }
    @if (hint && !error) {
      <p [attr.id]="describedBy()" [class]="cm().formHint">{{ hint }}</p>
    }`,
})
export class Select implements AfterViewInit, AfterViewChecked, HasElement<HTMLSelectElement> {
  /** The options to render. */
  options?: SelectPropsOption[]
  /** Controlled value. */
  value?: string
  defaultValue?: string
  /** Select size. */
  size?: Size
  /** Field label. */
  label?: string
  placeholder?: string
  error?: string
  hint?: string
  clearable?: boolean
  className?: string
  style?: Record<string, unknown>
  testId?: string
  /** Disables the select. */
  disabled?: boolean
  required?: boolean
  /** Form field name. */
  name?: string
  /** Explicit select id. */
  id?: string
  automationId?: string
  dataMolId?: string

  onFocus?: FocusEventHandler
  onBlur?: FocusEventHandler
  onKeyDown?: KeyboardEventHandler

  @Output() readonly change = new EventEmitter<Event & KitFieldChangeEvent>()
  @Output() readonly valueChange = new EventEmitter<string>()

  private selectEl?: ElementRef<HTMLSelectElement>
  @ViewChild('selectEl')
  set selectElQuery(ref: ElementRef<HTMLSelectElement> | undefined) {
    this.selectEl = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLSelectElement | null>(null)
  readonly element = this.inner.asReadonly()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  private readonly generatedId = nextInstanceId()

  private readonly i18n = useTranslation()

  externalDescription?: string | null
  externalInvalid?: AriaBoolean
  protected readonly hostAria = new FieldHostAria()
  private externalMolId: string | undefined

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  field(): ReturnType<typeof fieldLayout> {
    return fieldLayout(this.cm())
  }

  selectId(): string {
    const externalId = !this.label && !this.hint && !this.error ? this.name : undefined
    return this.id || this.fieldContext()?.id || externalId || this.generatedId
  }

  describedBy(): string | null {
    const id = this.fieldContext()?.id === this.selectId() ? this.generatedId : this.selectId()
    return this.error ? `${id}-error` : this.hint ? `${id}-hint` : null
  }
  fieldContext(): FormFieldContext | null {
    return fieldContext(this.host.nativeElement)
  }

  mergedDescribedBy(): string | null {
    return descriptionIds(
      this.externalDescription ?? this.hostAria.description(),
      this.fieldContext()?.describedBy,
      this.describedBy(),
    )
  }

  classes(): string {
    return this.cm().cn(
      this.cm().select({ error: !!this.error, size: this.size ?? 'md' }),
      this.cm().selectNative,
      this.cm().inputPadRight,
      this.className,
    )
  }

  /** The clear option's label. */
  clearText(): string {
    return this.i18n.t('ui.select.clear', undefined, { defaultValue: '--' })
  }

  chevron(): ResolvedIcon {
    return resolveIcon('chevron-down', this.cm().cn(this.cm().iconSm, this.cm().textMuted))
  }

  optionGroups(): { group: string; options: SelectPropsOption[] }[] {
    const acc = new Map<string, SelectPropsOption[]>()
    for (const option of this.options ?? []) {
      const group = option.group || ''
      const list = acc.get(group)
      if (list) list.push(option)
      else acc.set(group, [option])
    }
    return [...acc.entries()].map(([group, options]) => ({ group, options }))
  }

  hostStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  handleChange(event: Event): void {
    if (!isFieldChangeEvent(event)) return
    event.stopPropagation()
    this.change.emit(event)
    this.valueChange.emit(event.target.value)
    this.applyValue(false)
  }

  ngDoCheck(): void {
    this.hostAria.read(this.host.nativeElement)
  }

  ngAfterViewInit(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.selectEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
    moveRestAttributes(this.host.nativeElement, this.selectEl?.nativeElement, true)
    this.applyValue(true)
  }

  ngAfterViewChecked(): void {
    void this.i18n.locale()
    adoptHostDataMolId(
      this.host.nativeElement,
      this.selectEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
    reapplyRestAttributes(this.host.nativeElement, this.selectEl?.nativeElement, {
      keepInvalid: true,
    })
    this.applyValue(false)
  }

  private applyValue(initial: boolean): void {
    const select = this.selectEl?.nativeElement
    if (!select) return
    if (this.value !== undefined) {
      const next = String(this.value)
      if (select.value !== next && Array.from(select.options).some((o) => o.value === next))
        select.value = next
    } else if (initial) {
      if (this.defaultValue !== undefined) {
        const target = String(this.defaultValue)
        for (const option of Array.from(select.options)) {
          if (option.value === target) option.setAttribute('selected', '')
          else option.removeAttribute('selected')
        }
        if (select.value !== target) select.value = target
      } else if (select.multiple) {
        select.selectedIndex = -1
      }
    }
  }
}

(Member comments are shortened to their first sentence, and the 45 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/select.component.d.ts.)

Separator

Separator component.

Decorative separators render role="none" and no orientation; a semantic one (decorative={false}) renders role="separator" plus aria-orientation.

@Component({
  selector: 'div[mol-separator]',
  standalone: true,
  inputs: [
    'orientation',
    'decorative',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[attr.role]': 'decorative ? "none" : "separator"',
    '[attr.aria-orientation]': 'decorative ? null : orientation',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: '',
})
export class Separator implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Orientation of the separator. */
  orientation: SeparatorProps['orientation'] = 'horizontal'
  /** Decorative separators are purely visual. */
  decorative: SeparatorProps['decorative'] = true
  /** Extra classes. */
  className?: SeparatorProps['className']
  /** Inline style object (React camelCase). */
  style?: SeparatorProps['style']
  /** `data-testid`. */
  testId?: SeparatorProps['testId']
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: SeparatorProps['automationId']
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the separator class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().separator({ orientation: this.orientation }), this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }
}

SidebarUserCard

SidebarUserCard component.

React's root is a FRAGMENT (the trigger button plus a drawer), so the trigger button renders in front of the host (placeElementBefore) and the host itself leaves the DOM. Identity comes from useAuth() unless the matching props override it.

@Component({
  selector: 'mol-sidebar-user-card',
  standalone: true,
  imports: [Modal, PanelCloseProvider],
  hostDirectives: [MolPlacement],
  inputs: [
    'name',
    'secondaryLine',
    'avatarUrl',
    'ariaLabelKey',
    'ariaLabelDefault',
    'dataMolId',
    'className',
    'testId',
  ],
  template: `<button
      #trigger
      type="button"
      (click)="isOpen.set(true)"
      [attr.aria-label]="ariaLabel()"
      [attr.data-mol-id]="dataMolId"
      [attr.data-testid]="testId"
      [class]="triggerClasses()"
    >
      @if (displayAvatar(); as avatar) {
        <img [src]="avatar" alt="" [class]="avatarClasses()" />
      } @else {
        <span aria-hidden="true" [class]="initialsClasses()" [style]="initialsStyle()">{{
          initials()
        }}</span>
      }
      <span [class]="cm().cn(cm().minW(0), cm().flex1)"
        ><span [class]="nameClasses()">{{ displayName() }}</span>
        @if (displaySecondary(); as secondary) {
          <span [class]="secondaryClasses()">{{ secondary }}</span>
        }
      </span></button
    ><mol-modal
      [open]="isOpen()"
      (close)="isOpen.set(false)"
      [className]="cm().drawer"
      [attr.aria-label]="drawerLabel()"
      ><mol-panel-close-provider [close]="closePanel"
        ><ng-content></ng-content></mol-panel-close-provider
    ></mol-modal>`,
})
export class SidebarUserCard {
  /** Display name override (falls back to the auth user, then the guest label). */
  name?: SidebarUserCardProps['name']
  /** Secondary line under the name (falls back to the auth user's email). */
  secondaryLine?: SidebarUserCardProps['secondaryLine']
  /** Avatar image URL override. */
  avatarUrl?: SidebarUserCardProps['avatarUrl']
  /** i18n key for the trigger's aria-label (default `sidebarUserCard.open`). */
  ariaLabelKey?: SidebarUserCardProps['ariaLabelKey']
  /** Fallback aria-label (default `Open account menu`). */
  ariaLabelDefault?: SidebarUserCardProps['ariaLabelDefault']
  /** `data-mol-id` for the trigger (default `sidebar-user-card`). */
  dataMolId?: SidebarUserCardProps['dataMolId'] = 'sidebar-user-card'
  /** Extra classes for the trigger. */
  className?: SidebarUserCardProps['className']
  /** `data-testid` for the trigger. */
  testId?: SidebarUserCardProps['testId']

  /** Whether the drawer is open. */
  readonly isOpen = signal(false)
  /** Auth state (identity defaults). */
  readonly auth = useAuth<AccountUserShape>()
  /** Router state: a route change closes the drawer. */
  readonly router = useRouter()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /** The trigger button (adopted beside the host). */
  @ViewChild('trigger') trigger?: ElementRef<HTMLButtonElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    usePlacement(() => {
      const trigger = this.trigger?.nativeElement
      if (!trigger) return
      placeElementBefore(trigger, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
  }
  private readonly routeEffect = effect(() => {
    const location = this.router.location()
    void `${location.pathname}${location.search}`
    this.isOpen.set(false)
  })

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The trigger's accessible label. */
  ariaLabel(): string {
    return this.i18n.t(
      this.ariaLabelKey ?? 'sidebarUserCard.open',
      {},
      {
        defaultValue: this.ariaLabelDefault ?? 'Open account menu',
      },
    )
  }

  /**
   * The drawer's accessible label. The drawer is a title-less Modal (its
   * panel content carries its own headings), so it is named with the
   * localized `sidebarUserCard.drawer` label: the binding on `<mol-modal>`
   * lands on its host element, which Modal's rest-attribute move copies onto
   * the dialog `<div>` — screen readers announce "Account" instead of an
   * unnamed dialog (axe `aria-dialog-name`).
   * @returns The label text.
   */
  drawerLabel(): string {
    return this.i18n.t('sidebarUserCard.drawer', {}, { defaultValue: 'Account' })
  }

  /**
   * The resolved display name (React's fallback chain).
   * @returns The name.
   */
  displayName(): string {
    return (
      this.name ??
      this.auth.user()?.name ??
      this.auth.user()?.email ??
      this.i18n.t('sidebarUserCard.guest', {}, { defaultValue: 'Guest' })
    )
  }

  /**
   * The resolved secondary line (prop override, else the auth email).
   * @returns The line, or undefined.
   */
  displaySecondary(): string | undefined {
    return this.secondaryLine ?? this.auth.user()?.email ?? undefined
  }

  /**
   * The resolved avatar URL (prop override, else the auth user's).
   * @returns The URL, or undefined.
   */
  displayAvatar(): string | undefined {
    return this.avatarUrl ?? this.auth.user()?.avatarUrl ?? undefined
  }

  /** The name/email initials. */
  initials(): string {
    return getInitials(this.displayName())
  }

  /** The trigger's class list. */
  triggerClasses(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', gap: 'sm' }),
      this.cm().sp('px', 3),
      this.cm().sp('py', 3),
      this.cm().sidebarUserCardTrigger,
      this.className,
    )
  }

  /** The avatar image class list. */
  avatarClasses(): string {
    return this.cm().cn(
      this.cm().w(10),
      this.cm().h(10),
      this.cm().roundedFull,
      this.cm().shrink0,
      this.cm().objectCover,
    )
  }

  /** The initials badge class list. */
  initialsClasses(): string {
    return this.cm().cn(
      this.cm().w(10),
      this.cm().h(10),
      this.cm().roundedFull,
      this.cm().flex({ align: 'center', justify: 'center' }),
      this.cm().textSize('sm'),
      this.cm().fontWeight('bold'),
      this.cm().shrink0,
    )
  }

  /** The initials badge's inline style. */
  initialsStyle(): string | null {
    return styleText({
      backgroundColor: 'var(--color-primary)',
      color: 'var(--color-on-primary, #ffffff)',
    })
  }

  /** The display-name class list. */
  nameClasses(): string {
    return this.cm().cn(
      this.cm().textSize('sm'),
      this.cm().fontWeight('semibold'),
      this.cm().displayBlock,
      this.cm().textTruncate,
    )
  }

  /** The secondary-line class list. */
  secondaryClasses(): string {
    return this.cm().cn(
      this.cm().textSize('xs'),
      this.cm().displayBlock,
      this.cm().textTruncate,
      this.cm().textMuted,
    )
  }

  /** Closes the drawer (the panel-close context's callback). */
  closePanel = (): void => {
    this.isOpen.set(false)
  }
}

Skeleton

Skeleton loading placeholder.

The host is the skeleton <div>; width/height/borderRadius accept React's number-or-string shapes (numbers become px), and a circle skeleton without a height uses the width for both, exactly like React.

@Component({
  selector: 'div[mol-skeleton]',
  standalone: true,
  inputs: [
    'width',
    'height',
    'circle',
    'borderRadius',
    'animation',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: '',
})
export class Skeleton implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Width (number = px, or any CSS value). */
  width?: number | string
  /** Height (number = px, or any CSS value). */
  height?: number | string
  /** Whether the skeleton is a circle. */
  circle = false
  /** Border radius override (number = px). */
  borderRadius?: number | string
  /** Animation style. */
  animation: 'pulse' | 'wave' | 'none' = 'pulse'
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the skeleton class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().skeleton(),
      this.circle && this.cm().skeletonCircle,
      this.animation === 'none' && this.cm().skeletonNone,
      this.animation === 'wave' && this.cm().skeletonWave,
      this.className,
    )
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const computed: Record<string, unknown> = {
      ...this.style,
      width: typeof this.width === 'number' ? `${this.width}px` : this.width,
      height: typeof this.height === 'number' ? `${this.height}px` : this.height,
      borderRadius: this.circle
        ? '9999px'
        : typeof this.borderRadius === 'number'
          ? `${this.borderRadius}px`
          : this.borderRadius,
    }
    // If circle, make width and height equal.
    if (this.circle && this.width && !this.height) {
      computed.height = computed.width
    }
    return styleText(computed)
  }
}

SkeletonText

Skeleton text lines (a container with N skeleton bars; the last one is 60%).

@Component({
  selector: 'div[mol-skeleton-text]',
  standalone: true,
  imports: [Skeleton],
  inputs: ['lines', 'className'],
  host: {
    '[class]': 'classes()',
  },
  template: `@for (line of lineList; track $index) {
    <div mol-skeleton [height]="16" [width]="$index === lines - 1 ? '60%' : '100%'"></div>
  }`,
})
export class SkeletonText implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** Number of skeleton lines. */
  lines = 3
  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * An array as long as the line count (template iteration).
   * @returns Placeholder items.
   */
  get lineList(): number[] {
    return Array.from({ length: this.lines })
  }

  /**
   * Computes the container class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().skeletonTextContainer, this.className)
  }
}

SkeletonCircle

Skeleton circle (avatar placeholder).

React renders <Skeleton circle width={size} height={size} className/> — a single div; the host IS that div (no wrapper).

@Component({
  selector: 'div[mol-skeleton-circle]',
  standalone: true,
  inputs: ['size', 'className'],
  host: {
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
  },
  template: '',
})
export class SkeletonCircle implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>` (the skeleton itself). */
  readonly element = hostElement(this.host)

  /** Circle diameter in pixels. */
  size = 40
  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Computes the class list (a circle skeleton).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().skeleton(), this.cm().skeletonCircle, this.className)
  }

  /**
   * Serializes the circle inline style.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const px = typeof this.size === 'number' ? `${this.size}px` : this.size
    return styleText({ width: px, height: px, borderRadius: '9999px' })
  }
}

Spinner

Spinner component.

The host element is the <div role="status"> React renders. A raw CSS color (not a known color name) is expressed as inline border colors, and data-*/aria-* rest props land on the host (React's spread target).

@Component({
  selector: 'div[mol-spinner]',
  standalone: true,
  inputs: [
    'size',
    'color',
    'label',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
  ],
  host: {
    '[attr.role]': '"status"',
    '[attr.aria-label]': 'ariaLabel()',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `@if (label) {
    <span [class]="cm().srOnly">{{ label }}</span>
  }`,
})
export class Spinner implements HasElement<HTMLDivElement> {
  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div role="status">`. */
  readonly element = hostElement(this.host)

  /** Spinner size. */
  size: Size = 'md'
  /** Named color variant or a raw CSS color. */
  color?: string
  /** Accessible label; also renders a screen-reader-only text node. */
  label?: string
  /** Extra classes joined onto the spinner classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The accessible label (localized default when not given).
   * @returns The aria-label text.
   */
  ariaLabel(): string {
    return this.label || this.i18n.t('ui.spinner.loading', undefined, { defaultValue: 'Loading' })
  }

  /**
   * Computes the spinner class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().spinner({ size: this.size }), this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /**
   * Serializes the merged inline style (caller style plus a raw-color border
   * override when `color` is a CSS color rather than a named variant).
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    const colorStyle =
      this.color && typeof this.color === 'string' && !NAMED_COLORS.includes(this.color)
        ? { borderColor: this.color, borderTopColor: 'transparent' }
        : undefined
    return styleText({ ...this.style, ...colorStyle })
  }
}

Switch

Switch component.

React's root is a fragment (hidden native checkbox + label): both elements render in front of the host, which leaves the page, so the rendered tree is React's — no wrapper element around the pair. Clicking the visible button clicks the hidden checkbox, whose GENUINE native change event is forwarded as the change output.

@Component({
  selector: 'mol-switch',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolControlledChecked],
  inputs: [
    'label',
    'checked',
    'size',
    'color',
    'className',
    'style',
    'testId',
    'name',
    'value',
    'required',
    'disabled',
    'automationId',
    'dataMolId: data-mol-id',
    'onClick',
  ],
  template: `<input
      type="checkbox"
      [attr.name]="name"
      [attr.value]="value"
      [required]="!!required"
      [molChecked]="!!checked"
      [disabled]="disabled"
      aria-hidden="true"
      tabindex="-1"
      [class]="cm().srOnly"
      (change)="handleChange($event)"
      #hiddenInput
    />
    <label [class]="labelClasses()">
      <button
        type="button"
        role="switch"
        [attr.aria-checked]="checked ? 'true' : 'false'"
        [disabled]="disabled"
        [attr.data-state]="state()"
        (click)="handleClick($event)"
        [class]="classes()"
        [attr.style]="hostStyle()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        #trigger
      >
        <span [attr.data-state]="state()" [class]="cm().switchThumb({ size: size ?? 'md' })"></span>
      </button>
      <span [class]="cm().controlText" #labelSlot
        >{{ label }}<ng-content select="[slot=label]"></ng-content
      ></span>
    </label>`,
})
export class Switch implements AfterViewChecked, HasElement<HTMLButtonElement> {
  /** Switch label (text, or projected `[slot=label]` nodes). */
  label?: unknown
  /** Whether the switch is on. */
  checked?: boolean
  /** Switch size. */
  size?: Size
  /** Switch color. */
  color?: ColorVariant
  /** Extra classes joined onto the switch classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the button. */
  testId?: string
  /** The name submitted with the checked value. */
  name?: string
  /** The value submitted while the switch is checked. */
  value?: string | number | readonly string[]
  /** Requires the switch to be on before submitting. */
  required?: boolean
  /** Disables the switch. */
  disabled?: boolean
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  /** A `data-mol-id` given as a plain rest attribute (React's `rootProps` precedence). */
  dataMolId?: string

  /**
   * A caller's click handler (React's `onClick` prop). Runs BEFORE the toggle
   * and can veto it with `preventDefault()`.
   */
  onClick?: MouseEventHandler

  /** The genuine native `change` event of the hidden checkbox. */
  @Output() readonly change = new EventEmitter<Event>()
  /** Fires with the new checked state. */
  @Output() readonly checkedChange = new EventEmitter<boolean>()

  /** The hidden native checkbox. */
  @ViewChild('hiddenInput') hiddenInput?: ElementRef<HTMLInputElement>
  /** The visible trigger button (React's `...rest` spread target). */
  private trigger?: ElementRef<HTMLButtonElement>
  /** The trigger button view query; also feeds the caller's ref element. */
  @ViewChild('trigger')
  set triggerQuery(ref: ElementRef<HTMLButtonElement> | undefined) {
    this.trigger = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLButtonElement | null>(null)
  /** The element a caller's ref receives: the `role="switch"` button. */
  readonly element = this.inner.asReadonly()
  /** The label text wrapper. */
  @ViewChild('labelSlot') labelSlot?: ElementRef<HTMLSpanElement>

  private readonly host = inject(ElementRef)
  private hasLabel = false
  /** The `data-mol-id` a caller bound on the host (React spreads it onto the trigger). */
  private externalMolId: string | undefined

  /**
   * Renders the host's content (the checkbox and the label) in front of the
   * host, which leaves the page, and applies React's `{!!label && <span>}`
   * label condition.
   */
  constructor() {
    usePlacement((hasContent) => {
      const host = this.host.nativeElement
      placeContentBefore(host, host)
      setElementPresent(host, false)
      // React spreads the rest props on the switch button.
      setHostRoot(host, this.trigger?.nativeElement, {
        except: ['data-mol-id', 'name', 'value', 'required'],
      })
      this.hasLabel = !!this.label || hasContent(this.labelSlot?.nativeElement)
      setElementPresent(this.labelSlot?.nativeElement, this.hasLabel)
    })
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The data-state of the switch and thumb.
   * @returns `checked` or `unchecked`.
   */
  state(): 'checked' | 'unchecked' {
    return this.checked ? 'checked' : 'unchecked'
  }

  /**
   * Computes the switch button class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().switchBase({ size: this.size ?? 'md', color: this.color }),
      this.className,
    )
  }

  /**
   * Computes the label class list.
   * @returns The class string.
   */
  labelClasses(): string {
    return this.cm().cn(this.cm().controlLabel, this.disabled && this.cm().controlDisabled)
  }

  /**
   * Serializes the inline style for the button.
   * @returns The style attribute text.
   */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`).
   * @returns The attribute value.
   */
  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  /**
   * Clicking the button runs the caller's `onClick` first (it may veto the
   * toggle with `preventDefault()`), then clicks the hidden checkbox (unless
   * disabled or the event was vetoed), exactly like React's handler.
   *
   * @param event - The button click event.
   */
  handleClick(event: MouseEvent): void {
    this.onClick?.(event)
    if (!this.disabled && !event.defaultPrevented) this.hiddenInput?.nativeElement.click()
  }

  /**
   * Forwards the hidden checkbox's genuine native `change` event (React
   * forwards the raw browser event, not a React synthetic one) and then
   * restores the controlled value, like React's controlled-input state
   * restore (the input mirrors the `checked` prop, never free user state).
   * The event's propagation stops here so the host-level `change` binding
   * does not record it a second time.
   *
   * @param event - The native change event.
   */
  handleChange(event: Event): void {
    event.stopPropagation()
    const input = this.hiddenInput?.nativeElement
    const next = input?.checked
    this.change.emit(event)
    if (next !== undefined) this.checkedChange.emit(next)
    if (input) input.checked = !!this.checked
  }

  /**
   * Moves rest attributes onto the button after queries resolve.
   */
  ngAfterViewChecked(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.trigger?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
  }
}

Table

Table component.

The host is the wrapper <div> (div[mol-table]), exactly React's root; the <table> carries the className/style/testId/rest. Column render functions are templates (with a0–a2 = the render function's arguments) or plain functions returning text.

@Component({
  selector: 'div[mol-table]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg, MolTemplateOutlet, Spinner],
  inputs: [
    'data',
    'columns',
    'rowKey',
    'bordered',
    'striped',
    'hoverable',
    'size',
    'emptyContent',
    'loading',
    'sort',
    'onSort',
    'onRowClick',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'id',
    'title',
  ],
  host: {
    '[attr.id]': 'null',
    '[attr.title]': 'null',
    '[class]': 'cm().tableWrapper',
  },
  template: `<span #emptySlot><ng-content select="[slot=emptyContent]"></ng-content></span>
    @if (loading) {
      <div [class]="cm().tableLoadingOverlay"><div mol-spinner [size]="'lg'"></div></div>
    }
    <table
      #tableEl
      [class]="tableClasses()"
      [style]="tableStyle()"
      [attr.data-testid]="testId"
      [attr.data-mol-id]="molId()"
      [attr.id]="id"
      [attr.title]="title"
    >
      <thead [class]="cm().tableHeader">
        <tr [class]="cm().tableRow">
          @for (column of columns; track column.key) {
            <th
              [class]="headClasses(column)"
              [style]="columnStyle(column)"
              (click)="handleSort(column)"
              [attr.aria-sort]="ariaSort(column)"
            >
              <div [class]="cm().tableSortWrapper">
                @if (asTemplate(column.header); as headerTpl) {
                  <ng-container [molTemplateOutlet]="headerTpl"></ng-container>
                } @else {
                  {{ nodeText(column.header) }}
                }
                @if (column.sortable && sort?.key === column.key) {
                  <span [class]="cm().tableSortIcon"><svg mol-icon [data]="sortIcon()" /></span>
                }
              </div>
            </th>
          }
        </tr>
      </thead>
      <tbody [class]="cm().tableBody">
        @if (data.length === 0) {
          <tr>
            <td [attr.colspan]="columns.length" [class]="cm().tableEmptyCell" #emptyCell>
              @if (!hasEmpty()) {
                {{ emptyText() }}
              }
            </td>
          </tr>
        } @else {
          @for (row of data; track rowKeyOf(row, $index); let rowIdx = $index) {
            <tr [class]="rowClasses($index)" (click)="handleRowClick(row, $index)">
              @for (column of columns; track column.key) {
                <td [class]="cellClasses(column)">
                  @if (column.render) {
                    @if (asTemplate(column.render); as cellTpl) {
                      <ng-container
                        [molTemplateOutlet]="cellTpl"
                        [molTemplateOutletContext]="cellContext(row, column, rowIdx)"
                      ></ng-container>
                    } @else {
                      {{ renderText(row, column, rowIdx) }}
                    }
                  } @else {
                    {{ cellText(row, column) }}
                  }
                </td>
              }
            </tr>
          }
        }
      </tbody>
    </table>`,
})
export class Table implements AfterViewInit, AfterViewChecked, HasElement<HTMLTableElement> {
  data: Record<string, unknown>[] = []
  columns: AngularTableColumn[] = []
  rowKey?: string | ((row: Record<string, unknown>) => string | number)
  bordered?: boolean
  striped?: boolean
  hoverable = true
  size?: Size
  emptyContent?: unknown
  loading?: boolean
  sort?: { key: string; direction: 'asc' | 'desc' }
  onSort?: (key: string, direction: 'asc' | 'desc') => void
  onRowClick?: (row: Record<string, unknown>, index: number) => void
  className?: string
  style?: Record<string, unknown>
  testId?: string
  automationId?: string
  dataMolId?: string
  id?: string
  title?: string

  @ViewChild('emptySlot') emptySlot?: ElementRef<HTMLSpanElement>
  @ViewChild('emptyCell') emptyCell?: ElementRef<HTMLTableCellElement>
  @ViewChild('tableEl')
  set tableElQuery(ref: ElementRef<HTMLTableElement> | undefined) {
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLTableElement | null>(null)
  readonly element = this.inner.asReadonly()

  readonly hasEmpty = signal(false)

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    usePlacement((hasContent) => this.reconcile(hasContent))
  }

  private readonly i18n = useTranslation()

  private externalMolId: string | undefined

  cm(): UIClassMap {
    return getClassMap()
  }

  tableClasses(): string {
    return this.cm().cn(this.cm().table, this.bordered && this.cm().tableBordered, this.className)
  }

  tableStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  headClasses(column: AngularTableColumn): string {
    return this.cm().cn(
      this.cm().tableHead,
      column.align === 'center' && this.cm().textCenter,
      column.align === 'right' && this.cm().textRight,
      column.sortable && this.cm().tableHeadSortable,
    )
  }

  columnStyle(column: AngularTableColumn): string | null {
    return styleText({ width: column.width })
  }

  cellClasses(column: AngularTableColumn): string {
    return this.cm().cn(
      this.cm().tableCell,
      column.align === 'center' && this.cm().textCenter,
      column.align === 'right' && this.cm().textRight,
    )
  }

  rowClasses(index: number): string {
    return this.cm().cn(
      this.cm().tableRow,
      this.striped && index % 2 === 1 && this.cm().tableRowStriped,
      this.hoverable && this.cm().tableRowHoverable,
      !!this.onRowClick && this.cm().tableRowClickable,
    )
  }

  ariaSort(column: AngularTableColumn): string | null {
    if (!column.sortable) return null
    if (this.sort?.key !== column.key) return 'none'
    return this.sort.direction === 'asc' ? 'ascending' : 'descending'
  }

  sortIcon(): ResolvedIcon {
    return resolveIcon(
      this.sort?.direction === 'asc' ? 'chevron-up' : 'chevron-down',
      this.cm().iconSm,
    )
  }

  emptyText(): string {
    return this.i18n.t('ui.table.empty', undefined, { defaultValue: 'No data available' })
  }

  nodeText(value: unknown): string {
    return nodeText(value)
  }

  asTemplate(value: unknown): TemplateRef<unknown> | null {
    return value instanceof TemplateRef ? value : null
  }

  rowKeyOf(row: Record<string, unknown>, index: number): string | number {
    if (typeof this.rowKey === 'function') return this.rowKey(row)
    const key = this.rowKey ? row[this.rowKey] : undefined
    return typeof key === 'string' || typeof key === 'number' ? key : index
  }

  cellContext(
    row: Record<string, unknown>,
    column: AngularTableColumn,
    index: number,
  ): Record<string, unknown> {
    const value = row[column.key]
    return { $implicit: value, a0: value, a1: row, a2: index }
  }

  renderText(row: Record<string, unknown>, column: AngularTableColumn, index: number): string {
    const render = column.render
    if (typeof render !== 'function') return ''
    return this.nodeText(render(row[column.key], row, index))
  }

  cellText(row: Record<string, unknown>, column: AngularTableColumn): string {
    const value = row[column.key]
    return value === undefined || value === null ? '' : String(value)
  }

  handleSort(column: AngularTableColumn): void {
    if (!column.sortable || !this.onSort) return
    const key = column.key
    const currentDirection = this.sort?.key === key ? this.sort.direction : undefined
    this.onSort(key, currentDirection === 'asc' ? 'desc' : 'asc')
  }

  handleRowClick(row: Record<string, unknown>, index: number): void {
    this.onRowClick?.(row, index)
  }
// … truncated — 5 more members: ngAfterViewInit, ngAfterViewChecked, ngDoCheck, reconcile, placeEmptyContent; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/table.component.d.ts

(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/table.component.d.ts.)

Tabs

Tabs component.

The host is the root <div> (div[mol-tabs]). Implements the WAI-ARIA APG "automatic activation" tabs pattern: roving tabindex, Left/Right/Home/End move both focus and the active tab, and disabled tabs are skipped. Item icon and content are node values (templates); label is a string or a node value.

@Component({
  selector: 'div[mol-tabs]',
  standalone: true,
  imports: [MolTemplateOutlet],
  inputs: [
    'items',
    'value',
    'defaultValue',
    'variant',
    'size',
    'fitted',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'disabled',
  ],
  outputs: ['change'],
  host: {
    '[class]': 'className',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
  },
  template: `<div [class]="listClasses()" role="tablist">
      @for (item of items; track item.value) {
        <button
          #tabBtn
          [id]="tabId(item.value)"
          type="button"
          role="tab"
          [attr.aria-selected]="item.value === activeValue() ? 'true' : 'false'"
          [attr.aria-controls]="controlsId(item)"
          [attr.data-state]="item.value === activeValue() ? 'active' : 'inactive'"
          [attr.tabindex]="item.value === activeValue() ? 0 : -1"
          [disabled]="!!item.disabled || disabled"
          (click)="selectTab(item.value)"
          (keydown)="handleKeyDown($event)"
          [class]="triggerClasses()"
        >
          @if (item.icon) {
            <span [class]="cm().tabTriggerIcon">
              @if (asTemplate(item.icon); as iconTpl) {
                <ng-container [molTemplateOutlet]="iconTpl"></ng-container>
              } @else {
                {{ nodeText(item.icon) }}
              }
            </span>
          }
          @if (asTemplate(item.label); as labelTpl) {
            <ng-container [molTemplateOutlet]="labelTpl"></ng-container>
          } @else {
            {{ nodeText(item.label) }}
          }
        </button>
      }
    </div>
    @if (hasContent()) {
      @if (activeContent(); as contentTpl) {
        <div
          role="tabpanel"
          [id]="panelId(activeValue() ?? '')"
          [attr.aria-labelledby]="tabId(activeValue() ?? '')"
          [class]="contentClasses()"
        >
          <ng-container [molTemplateOutlet]="contentTpl"></ng-container>
        </div>
      } @else {
        <div
          role="tabpanel"
          [id]="panelId(activeValue() ?? '')"
          [attr.aria-labelledby]="tabId(activeValue() ?? '')"
          [class]="contentClasses()"
          [textContent]="contentText()"
        ></div>
      }
    }`,
})
export class Tabs implements OnInit, HasElement<HTMLDivElement> {
  /** The tabs. */
  items: TabItem<string>[] = []
  /** Controlled active value. */
  value?: string
  /** Initial active value for the uncontrolled form. */
  defaultValue?: string
  /** Tab-list visual variant. */
  variant?: 'line' | 'enclosed' | 'soft-rounded' | 'solid-rounded'
  /** Tab size. */
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
  /** Whether tabs stretch to fill the list. */
  fitted?: boolean
  /** Extra classes for the root. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  dataMolId?: string
  /** Disables every tab, whatever an item says (React's `disabled`). */
  disabled?: boolean

  /** Fires with the selected tab's value (React's `onChange`). */
  @Output() readonly change = new EventEmitter<string>()

  private readonly host: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.host)

  /** The tab buttons (for focus movement). */
  @ViewChildren('tabBtn') tabButtons?: QueryList<ElementRef<HTMLButtonElement>>
  /** The per-instance id base (the normalizer renumbers ids). */
  readonly idBase = nextInstanceId()
  /** The uncontrolled active value. */
  private readonly internalValue = signal<string | undefined>(undefined)

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** Seeds the uncontrolled selection once so reordering tabs preserves it. */
  ngOnInit(): void {
    this.internalValue.set(this.defaultValue ?? this.items.find((item) => !item.disabled)?.value)
  }

  activeValue(): string | undefined {
    const selected = this.value ?? this.internalValue()
    return this.items.some((item) => item.value === selected && !item.disabled)
      ? selected
      : this.items.find((item) => !item.disabled)?.value
  }

  /** The tab button id for a value. */
  tabId(value: string): string {
    return `${this.idBase}-tab-${value}`
  }

  /** The tabpanel id for a value. */
  panelId(value: string): string {
    return `${this.idBase}-tabpanel-${value}`
  }

  controlsId(item: TabItem<string>): string | null {
    return item.value === this.activeValue() && rendersNode(item.content)
      ? this.panelId(item.value)
      : null
  }

  /** The tab-list class list. */
  listClasses(): string {
    return this.cm().cn(
      this.cm().tabsList({ variant: this.variant, size: this.size }),
      this.fitted && this.cm().tabsFitted,
    )
  }

  /** The tab-button class list. */
  triggerClasses(): string {
    return this.cm().cn(
      this.cm().tabsTrigger({ variant: this.variant, size: this.size }),
      this.fitted && this.cm().tabTriggerFitted,
    )
  }

  /** The tabpanel class list. */
  contentClasses(): string {
    return this.cm().tabsContent({ variant: this.variant, size: this.size })
  }

  /** Serializes the root's inline style. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  molId(): string | undefined {
    return (
      this.automationId ??
      this.dataMolId ??
      this.host.nativeElement.getAttribute('data-mol-id') ??
      undefined
    )
  }

  /** Narrows a node-valued prop to a TemplateRef. */
  asTemplate(value: unknown): TemplateRef<unknown> | null {
    return value instanceof TemplateRef ? value : null
  }

  /** A plain-string node value's text. */
  nodeText(value: unknown): string {
    return nodeText(value)
  }

  hasContent(): boolean {
    const active = this.items.find((item) => item.value === this.activeValue())
    return rendersNode(active?.content)
  }

  /** The active tab's content as a template. */
  activeContent(): TemplateRef<unknown> | null {
    const active = this.items.find((item) => item.value === this.activeValue())
    return active ? this.asTemplate(active.content) : null
  }

  /** The active tab's plain-string content. */
  contentText(): string {
    const active = this.items.find((item) => item.value === this.activeValue())
    return this.nodeText(active?.content)
  }

  /** Selects a tab and notifies the caller (React's `selectTab`). */
  selectTab(tabValue: string): void {
    if (this.value === undefined) this.internalValue.set(tabValue)
    this.change.emit(tabValue)
  }

  /** The APG keyboard model: Left/Right/Home/End move focus AND selection. */
  handleKeyDown(event: KeyboardEvent): void {
    if (this.disabled) return
    const enabled = this.items.filter((item) => !item.disabled)
    if (enabled.length === 0) return
    const active = this.activeValue()
    const currentIndex = enabled.findIndex((item) => item.value === active)
    let nextIndex: number
    switch (event.key) {
      case 'ArrowRight':
        nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % enabled.length
        break
      case 'ArrowLeft':
        nextIndex = currentIndex === -1 ? 0 : (currentIndex - 1 + enabled.length) % enabled.length
        break
      case 'Home':
        nextIndex = 0
        break
      case 'End':
        nextIndex = enabled.length - 1
        break
      default:
        return
    }
    event.preventDefault()
    const nextValue = enabled[nextIndex].value
    this.selectTab(nextValue)
    this.focusTab(nextValue)
  }

  private focusTab(value: string): void {
    const match = this.tabButtons?.find((ref) => ref.nativeElement.id === this.tabId(value))
    match?.nativeElement.focus()
  }
}

(Member comments are shortened to their first sentence, and the 6 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/tabs.component.d.ts.)

Textarea

Textarea component.

The host is the field's outer wrapper React renders (the shared field layout's root, a flex column). React's textarea onChange fires on input events; a controlled value is restored after user input exactly like React's controlled-input state restore. autoResize recomputes the inline height after every check and on real input events (matching React's effect + native listener pair).

@Component({
  selector: 'div[mol-textarea]',
  standalone: true,
  inputs: [
    'size',
    'label',
    'error',
    'hint',
    'externalDescription: aria-describedby',
    'externalInvalid: aria-invalid',
    'autoResize',
    'minRows',
    'maxRows',
    'className',
    'style',
    'testId',
    'disabled',
    'required',
    'value',
    'defaultValue',
    'placeholder',
    'name',
    'id',
    'rows',
    'automationId',
    'dataMolId: data-mol-id',
    'onFocus',
    'onBlur',
    'onKeyDown',
  ],
  host: {
    '[class]': 'field().root',
  },
  template: `@if (label) {
      <label
        [attr.for]="textareaId()"
        [class]="cm().cn(cm().label({ required: !!required }), cm().labelBlock)"
        >{{ label }}</label
      >
    }
    <textarea
      [attr.id]="textareaId()"
      [attr.name]="name"
      [attr.placeholder]="placeholder"
      [disabled]="disabled"
      [attr.required]="required ? '' : null"
      [attr.rows]="rows || minRows || 3"
      [attr.aria-invalid]="
        error || fieldContext()?.invalid ? true : (externalInvalid ?? hostAria.invalid() ?? false)
      "
      [attr.aria-describedby]="mergedDescribedBy()"
      [class]="classes()"
      [attr.style]="hostStyle()"
      [attr.data-testid]="testId"
      [attr.data-mol-id]="molId()"
      (input)="handleInput($event)"
      (change)="handleChange($event)"
      (focusin)="onFocus?.($event)"
      (focusout)="onBlur?.($event)"
      (keydown)="onKeyDown?.($event)"
      #textareaEl
    ></textarea>
    @if (error) {
      <p [attr.id]="describedBy()" [class]="cm().formError">{{ error }}</p>
    }
    @if (hint && !error) {
      <p [attr.id]="describedBy()" [class]="cm().formHint">{{ hint }}</p>
    }`,
})
export class Textarea implements AfterViewInit, AfterViewChecked, HasElement<HTMLTextAreaElement> {
  /** Textarea size. */
  size?: Size
  /** Field label. */
  label?: string
  /** Error message (associates via aria-describedby). */
  error?: string
  /** Hint text (shown without an error). */
  hint?: string
  /** Whether the box resizes to its content. */
  autoResize?: boolean
  /** Minimum rendered rows (autoResize floor). */
  minRows?: number
  /** Maximum rendered rows (autoResize ceiling). */
  maxRows?: number
  /** Extra classes joined onto the textarea classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid` for the textarea. */
  testId?: string
  /** Disables the textarea. */
  disabled?: boolean
  /** Marks the textarea required (label styling). */
  required?: boolean
  /** Controlled value. */
  value?: string
  /** Uncontrolled initial value. */
  defaultValue?: string
  /** Placeholder text. */
  placeholder?: string
  /** Form field name. */
  name?: string
  /** Explicit textarea id. */
  id?: string
  /** Explicit rows attribute. */
  rows?: number
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  dataMolId?: string

  onFocus?: FocusEventHandler
  onBlur?: FocusEventHandler
  onKeyDown?: KeyboardEventHandler

  /** Fires the raw `input` event (React's textarea onChange). */
  @Output() readonly change = new EventEmitter<Event & KitFieldChangeEvent>()
  /** Fires with the edited text. */
  @Output() readonly valueChange = new EventEmitter<string>()

  /** The native textarea (React's `...rest` spread target). */
  private textareaEl?: ElementRef<HTMLTextAreaElement>
  @ViewChild('textareaEl')
  set textareaElQuery(ref: ElementRef<HTMLTextAreaElement> | undefined) {
    this.textareaEl = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLTextAreaElement | null>(null)
  readonly element = this.inner.asReadonly()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /** Stable fallback for label and feedback associations. */
  private readonly generatedId = nextInstanceId()

  /** Reactive translation, read in the injection context. */
  private readonly i18n = useTranslation()

  /** Additional description ids supplied by the caller. */
  externalDescription?: string | null
  externalInvalid?: AriaBoolean
  protected readonly hostAria = new FieldHostAria()
  private externalMolId: string | undefined

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  field(): ReturnType<typeof fieldLayout> {
    return fieldLayout(this.cm())
  }

  textareaId(): string {
    const externalId = !this.label && !this.hint && !this.error ? this.name : undefined
    return this.id || this.fieldContext()?.id || externalId || this.generatedId
  }

  /** The aria-describedby target (error or hint paragraph). */
  describedBy(): string | null {
    const id = this.fieldContext()?.id === this.textareaId() ? this.generatedId : this.textareaId()
    return this.error ? `${id}-error` : this.hint ? `${id}-hint` : null
  }
  fieldContext(): FormFieldContext | null {
    return fieldContext(this.host.nativeElement)
  }

  mergedDescribedBy(): string | null {
    return descriptionIds(
      this.externalDescription ?? this.hostAria.description(),
      this.fieldContext()?.describedBy,
      this.describedBy(),
    )
  }

  /** Computes the textarea class list. */
  classes(): string {
    return this.cm().cn(
      this.cm().textarea({ error: !!this.error, size: this.size }),
      this.className,
    )
  }

  /** Serializes the inline style for the textarea. */
  hostStyle(): string | null {
    return styleText(
      this.autoResize
        ? {
            resize: 'none',
            ...this.style,
            minHeight: `${Math.min(this.minRows ?? 3, this.maxRows ?? Infinity)}lh`,
            ...(this.maxRows === undefined ? {} : { maxHeight: `${this.maxRows}lh` }),
          }
        : this.style,
    )
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }

  handleInput(event: Event): void {
    if (!isFieldChangeEvent(event)) return
    event.stopPropagation()
    this.change.emit(event)
    const textarea = this.textareaEl?.nativeElement
    if (textarea) this.valueChange.emit(textarea.value)
    if (this.value !== undefined && textarea && textarea.value !== this.value)
      textarea.value = this.value
    this.resize()
  }

  handleChange(event: Event): void {
    event.stopPropagation()
  }

  /** Sizes the box to its content. */
  resize(): void {
    const element = this.textareaEl?.nativeElement
    if (!this.autoResize || !element) return
    element.style.height = 'auto'
    element.style.height = `${element.scrollHeight}px`
  }

  ngDoCheck(): void {
    this.hostAria.read(this.host.nativeElement)
  }

  ngAfterViewInit(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.textareaEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
    moveRestAttributes(this.host.nativeElement, this.textareaEl?.nativeElement, true)
    this.applyValue(true)
    this.resize()
  }

  ngAfterViewChecked(): void {
    // detection never re-checks this view — the parent's re-bound
    // `[attr.aria-label]` would land on the host and stay there.
    void this.i18n.locale()
    adoptHostDataMolId(
      this.host.nativeElement,
      this.textareaEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
    reapplyRestAttributes(this.host.nativeElement, this.textareaEl?.nativeElement, {
      keepInvalid: true,
    })
    this.applyValue(false)
    this.resize()
  }

  private applyValue(initial: boolean): void {
    const textarea = this.textareaEl?.nativeElement
    if (!textarea) return
    if (this.value !== undefined) {
      const next = String(this.value)
      if (textarea.value !== next) textarea.value = next
    } else if (initial && this.defaultValue !== undefined && textarea.value === '') {
      textarea.value = String(this.defaultValue)
    }
  }
}

(Member comments are shortened to their first sentence, and the 23 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/textarea.component.d.ts.)

ThemeToggle

ThemeToggle component.

Button that flips the wired theme bond between light and dark. The host is the <button> itself (button[mol-theme-toggle]), matching React's root exactly. Ships React's conventions out of the box: data-mol-id, data-mode, aria-pressed and the theme.toggle i18n aria-label. Extra attributes (data-*, title, …) land on the host — React's spread target — and unknown props like disabled bind the host attribute directly, so the browser suppresses the click exactly as React does.

@Component({
  selector: 'button[mol-theme-toggle]',
  standalone: true,
  imports: [Icon],
  inputs: [
    'ariaLabelKey',
    'ariaLabelDefault',
    'darkIcon',
    'lightIcon',
    'iconSize',
    'className',
    'testId',
    'automationId',
  ],
  host: {
    type: 'button',
    '[attr.data-mol-id]': 'molId()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mode]': 'mode()',
    '[attr.aria-pressed]': 'mode() === "dark" ? "true" : "false"',
    '[attr.aria-label]': 'labelText()',
    '[class]': 'classes()',
    '(click)': 'theme.toggleTheme()',
  },
  template: `@if (mode() === 'dark') {
      <svg mol-icon-root [name]="darkIcon ?? 'moon'" [size]="iconSizePx()"></svg>
    } @else {
      <svg mol-icon-root [name]="lightIcon ?? 'sun'" [size]="iconSizePx()"></svg>
    }`,
})
export class ThemeToggle {
  /** i18n key for the `aria-label` (default `theme.toggle`). */
  ariaLabelKey?: ThemeToggleProps['ariaLabelKey']
  /** Fallback `aria-label` if the i18n key is missing. */
  ariaLabelDefault?: ThemeToggleProps['ariaLabelDefault']
  /** Icon name rendered in dark mode (default `moon`). */
  darkIcon?: ThemeToggleProps['darkIcon']
  /** Icon name rendered in light mode (default `sun`). */
  lightIcon?: ThemeToggleProps['lightIcon']
  /** Pixel size for the rendered icon (default 20). */
  iconSize?: ThemeToggleProps['iconSize']
  /** Extra classes joined onto the toggle classes. */
  className?: ThemeToggleProps['className']
  /** `data-testid` for the button. */
  testId?: ThemeToggleProps['testId']
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: ThemeToggleProps['automationId']

  /** Theme state and actions, read in the component's injection context. */
  readonly theme = useTheme()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current theme mode.
   * @returns `'light'` or `'dark'`.
   */
  mode(): 'light' | 'dark' {
    return this.theme.mode()
  }

  /**
   * The localized `aria-label`.
   * @returns The translated label text.
   */
  labelText(): string {
    return this.i18n.t(
      this.ariaLabelKey ?? 'theme.toggle',
      {},
      {
        defaultValue: this.ariaLabelDefault ?? 'Toggle theme',
      },
    )
  }

  /**
   * Computes the toggle class list.
   * @returns The class string.
   */
  classes(): string {
    const cm: UIClassMap = getClassMap()
    return cm.cn(cm.themeToggleButton, this.className)
  }

  /**
   * The `data-mol-id` value (`automationId` wins over the default).
   * @returns The automation id.
   */
  molId(): string {
    return this.automationId ?? 'theme-toggle'
  }

  /**
   * The rendered icon pixel size.
   * @returns The size (default 20 when a later-bound write left it unset).
   */
  iconSizePx(): number {
    return this.iconSize ?? 20
  }
}

Toast

Toast component.

The host is the toast <div> (div[mol-toast]), exactly React's root. The auto-dismiss countdown pauses on hover AND focus (WCAG 2.2.1) and resumes with the remaining time; the announced role follows status (warning/error assertive, everything else polite).

@Component({
  selector: 'div[mol-toast]',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [MolIconSvg, MolTemplateOutlet],
  inputs: [
    'title',
    'description',
    'status',
    'duration',
    'dismissible',
    'closeLabel',
    'className',
    'style',
    'testId',
    'position',
    'automationId',
    'dataMolId: data-mol-id',
    'id',
    'roleOverride: role',
    'live: aria-live',
  ],
  outputs: ['dismiss'],
  host: {
    // static `title="…"` on the host, where the browser shows it as a tooltip.
    '[attr.title]': 'null',
    '[class]': 'classes()',
    '[style]': 'hostStyle()',
    '[attr.data-testid]': 'testId',
    '[attr.data-mol-id]': 'molId()',
    '[attr.id]': 'id',
    '[attr.role]': 'role()',
    '[attr.aria-live]': 'live',
    '[attr.data-state]': 'visible() ? "open" : null',
    '(mouseenter)': 'setHovered(true)',
    '(mouseleave)': 'setHovered(false)',
    '(focusin)': 'setFocused(true)',
    '(focusout)': 'leaveFocus($event)',
  },
  template: `@if (statusIcon(); as icon) {
      <span [class]="cm().toastIconWrapper"><svg mol-icon [data]="icon" /></span>
    }
    <div [class]="cm().toastContentWrapper">
      @if (title) {
        <div [class]="cm().toastTitle">{{ title }}</div>
      }
      <div #descriptionSlot [class]="cm().toastDescription">
        @if (descriptionText(); as descriptionTextValue) {
          {{ descriptionTextValue }}
        }
        <ng-container [molTemplateOutlet]="descriptionTemplate()"></ng-container
        ><span #childrenSlot><ng-content></ng-content></span>
      </div>
    </div>
    @if (dismissible) {
      <button
        type="button"
        [class]="cm().toastClose"
        [attr.aria-label]="closeText()"
        (click)="handleDismiss()"
      >
        <svg mol-icon [data]="closeIcon()" />
      </button>
    }`,
})
export class Toast implements AfterViewInit, DoCheck, OnDestroy, HasElement<HTMLDivElement> {
  /** The toast title. */
  title?: string
  /** The toast description (a string or a node value rendered as a template). */
  description?: unknown
  /** The toast status. */
  status: ColorVariant = 'info'
  /** Auto-dismiss delay in ms (`0` keeps it until dismissed). */
  duration = 5000
  /** Whether the close button renders. */
  dismissible = true
  /** The close button's accessible label. */
  closeLabel?: string
  /** Extra classes. */
  className?: string
  /** Inline style object (React camelCase). */
  style?: Record<string, unknown>
  /** `data-testid`. */
  testId?: string
  /** Accepted for prop parity; positioning is the container's job. */
  position?: ToastPosition
  /** `data-mol-id` automation id (React's `automationId`). */
  automationId?: string
  dataMolId?: string
  id?: string
  /** Overrides the status-derived role. */
  roleOverride?: ToastProps['role']
  /** Overrides the live-region priority, including `off`. */
  live?: ToastProps['aria-live']

  /** Fires when the toast dismisses itself or its close button is pressed. */
  @Output() readonly dismiss = new EventEmitter<void>()

  /** The description wrapper (always in the template; detached when empty). */
  @ViewChild('descriptionSlot') descriptionSlot?: ElementRef<HTMLDivElement>
  /** The children capture point. */
  @ViewChild('childrenSlot') childrenSlot?: ElementRef<HTMLSpanElement>

  /** Whether the toast is still rendered (React's `isVisible`). */
  readonly visible = signal(true)

  private readonly el = inject(ElementRef)
  private readonly hostRef: ElementRef<HTMLDivElement> = inject(ElementRef)
  /** The element a caller's ref receives: the host `<div>`. */
  readonly element = hostElement(this.hostRef)

  /** Reactive translation, read in the injection context. */
  private readonly i18n = useTranslation()

  private readonly host: HTMLElement = this.el.nativeElement
  private readonly countdown = new ToastCountdown(() => {
    this.visible.set(false)
    this.dismiss.emit()
  })
  private lastDuration: number
  private hasChildren = false

  /** Prepares the countdown state (the timer starts at view init). */
  constructor() {
    usePlacement((hasContent) => this.reconcile(hasContent))
    useHostPresence(() => this.visible())
    this.lastDuration = this.duration
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The mapped class-map variant. */
  variant(): 'default' | 'success' | 'warning' | 'error' | 'info' {
    return STATUS_VARIANT[this.status] || 'default'
  }

  /** The toast class list. */
  classes(): string {
    return this.cm().cn(this.cm().toast({ variant: this.variant() }), this.className)
  }

  /** Serializes the inline style. */
  hostStyle(): string | null {
    return styleText(this.style)
  }

  /** The `data-mol-id` value (`automationId` wins over a rest `data-mol-id`). */
  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.host.getAttribute('data-mol-id') ?? undefined
  }

  /** The announced role: assertive for warnings/errors, polite otherwise. */
  role(): string {
    return (
      this.roleOverride ??
      (this.variant() === 'warning' || this.variant() === 'error' ? 'alert' : 'status')
    )
  }

  /** The status glyph, when the variant has one. */
  statusIcon(): ResolvedIcon | null {
    const name = STATUS_ICON[this.variant()]
    return name ? resolveIcon(name, this.cm().iconMd) : null
  }

  /** The close button's X glyph. */
  closeIcon(): ResolvedIcon {
    return resolveIcon('x-mark', this.cm().iconSm)
  }

  /** The string description, when the description is a string. */
  descriptionText(): string | null {
    return typeof this.description === 'string' ? this.description : null
  }

  /** The description as a template, when it is a node value. */
  descriptionTemplate(): TemplateRef<unknown> | null {
    return this.description instanceof TemplateRef ? this.description : null
  }

  /** The close button's accessible label. */
  closeText(): string {
    return this.closeLabel ?? this.i18n.t('ui.toast.close', undefined, { defaultValue: 'Close' })
  }

  /** Dismisses the toast and calls the callback (React's `handleDismiss`). */
  handleDismiss(): void {
    this.countdown.dismiss()
  }

  /** Tracks the pointer's presence on the notification. */
  setHovered(hovered: boolean): void {
    this.countdown.setPaused('hover', hovered)
  }

  /** Tracks focus anywhere inside the notification. */
  setFocused(focused: boolean): void {
    this.countdown.setPaused('focus', focused)
  }

  /** Keeps the countdown paused when focus moves to another toast control. */
  leaveFocus(event: FocusEvent): void {
    if (!focusStaysWithin(event)) this.setFocused(false)
  }

  ngAfterViewInit(): void {
    this.countdown.start(this.duration)
  }

  ngDoCheck(): void {
    if (this.duration !== this.lastDuration) {
      this.lastDuration = this.duration
      this.countdown.start(this.duration)
    }
  }

  /** Stops the countdown (React's unmount cleanup). */
  ngOnDestroy(): void {
    this.countdown.stop()
  }

  private reconcile(hasContent: SlotReader): void {
    this.hasChildren = hasContent(this.childrenSlot?.nativeElement)
    this.adoptChildren()
  }

  private adoptChildren(): void {
    const span = this.childrenSlot?.nativeElement
    if (!span) return
    const wrapper = this.descriptionSlot?.nativeElement
    const descWins = this.descriptionText() !== null || this.descriptionTemplate() !== null
    setElementPresent(span, false)
    if (wrapper && !descWins && this.hasChildren) placeContent(span, wrapper)
    else placeContent(span, null)
    this.syncDescription()
  }

  /** Applies React's `{!!(description || children) && <div>…</div>}`. */
  private syncDescription(): void {
    const wrapper = this.descriptionSlot?.nativeElement
    if (!wrapper) return
    const hasDescription = this.descriptionText() !== null || this.descriptionTemplate() !== null
    setElementPresent(wrapper, hasDescription || this.hasChildren)
  }
}

(Member comments are shortened to their first sentence, and the 8 longest are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/toast.component.d.ts.)

ToastContainer

Toast container: positions toasts on screen via a body portal.

React's root is a portal: the container <div> is moved into document.body and the host element leaves the page, so nothing is left at the component's place.

@Component({
  selector: 'mol-toast-container',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: ['position', 'className'],
  template: `<div #container [class]="classes()"><ng-content></ng-content></div>`,
})
export class ToastContainer implements HasElement<HTMLDivElement> {
  /** The container position (default `bottom-right`). */
  position: ToastPosition = 'bottom-right'
  /** Extra classes. */
  className?: string

  /** The container element (moved to `document.body`). */
  private container?: ElementRef<HTMLDivElement>
  /** The container view query; also feeds the caller's ref element. */
  @ViewChild('container')
  set containerQuery(ref: ElementRef<HTMLDivElement> | undefined) {
    this.container = ref
    this.inner.set(ref?.nativeElement ?? null)
  }

  private readonly inner = signal<HTMLDivElement | null>(null)
  /** The element a caller's ref receives: the positioned container `<div>`. */
  readonly element = this.inner.asReadonly()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /** Renders the container in `document.body` (React's portal) and takes the host out of the page. */
  constructor() {
    usePlacement(() => {
      if (typeof document !== 'undefined')
        placeElement(this.container?.nativeElement, document.body)
      setElementPresent(this.host.nativeElement, false)
    })
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The container class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().toastContainer({ position: this.position }), this.className)
  }
}

ToastProvider

ToastProvider: manages global toast state and renders children plus a positioned toast container (React's context provider + portal).

The context value is registered on a DOM element (React context flows through the rendered tree, which Angular DI cannot reach for projected content); useToast() reads it through the DOM ancestors. React's provider renders its children and the container's portal, no element of its own, so the children render in front of the host and the host leaves the page; the context is registered on the parent element, the one whose child list the children now belong to.

@Component({
  selector: 'mol-toast-provider',
  standalone: true,
  hostDirectives: [MolPlacement],
  imports: [Toast],
  inputs: ['position'],
  template: `<span #childrenCapture><ng-content></ng-content></span>
    <div #container [class]="containerClasses()">
      @for (toast of toasts(); track toast.id) {
        <div
          mol-toast
          [title]="toast.title"
          [description]="toast.description"
          [status]="toast.status ?? 'info'"
          [duration]="toast.duration ?? 5000"
          [dismissible]="toast.dismissible ?? true"
          [closeLabel]="toast.closeLabel"
          [className]="toast.className"
          [style]="toast.style"
          [testId]="toast.testId"
          [automationId]="toast.automationId"
          [id]="toast.id"
          [role]="toast.role"
          [aria-live]="toast['aria-live']"
          (dismiss)="removeToast(toast.id)"
        ></div>
      }
    </div>`,
})
export class ToastProvider implements OnDestroy {
  /** The default position for toasts (default `bottom-right`). */
  position: ToastPosition = 'bottom-right'

  /** The children capture point (removed once children are adopted). */
  @ViewChild('childrenCapture') childrenCapture?: ElementRef<HTMLSpanElement>
  /** The toast container (moved to `document.body`). */
  @ViewChild('container') container?: ElementRef<HTMLDivElement>

  /** The current toasts. */
  readonly toasts = signal<(ToastProps & { id: string })[]>([])

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  /** The value consumers read; its closures keep the live toast state. */
  private readonly value = new ToastContextImplementation(this)

  /**
   * Renders the children in front of the host (which leaves the page),
   * registers the context where they render, and portals the container.
   */
  constructor() {
    ToastDomContext.provide(this.host.nativeElement, this.value)
    usePlacement(() => {
      const capture = this.childrenCapture?.nativeElement
      const host = this.host.nativeElement
      if (capture) {
        placeContentBefore(capture, host)
        setElementPresent(capture, false)
      }
      setElementPresent(host, false)
      if (typeof document !== 'undefined')
        placeElement(this.container?.nativeElement, document.body)
    })
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The container class list.
   * @returns The class string.
   */
  containerClasses(): string {
    return this.cm().toastContainer({ position: this.position })
  }

  /**
   * Adds a toast and returns its handle (React's `addToast`). A caller's `id`
   * is the handle and the toast element's id; otherwise one is generated.
   * @param toast - The toast to add.
   * @returns The id.
   */
  addToast(toast: Omit<ToastProps, 'onDismiss'>): string {
    const id = toast.id ?? `toast-${++toastCounter}`
    this.toasts.update((prev) => [...prev, { ...toast, id }])
    return id
  }

  /**
   * Removes a toast by id (React's `removeToast`).
   * @param id - The toast's id.
   */
  removeToast(id: string): void {
    this.toasts.update((prev) => prev.filter((toast) => toast.id !== id))
  }

  /** Removes the context registration (unmount). */
  ngOnDestroy(): void {
    ToastDomContext.remove(this.host.nativeElement)
  }
}

Tooltip

Tooltip component.

React's root is a FRAGMENT (a trigger wrapper <div> plus a portal), so the trigger wrapper renders in front of the host (placeElementBefore), the host itself leaves the DOM, and the portal element renders in document.body while visible: the rendered tree and focus paths are React's. A single-element trigger receives aria-describedby while the tooltip shows; show/hide are coordinated across instances exactly like React's module-level activeTooltips map.

Projected content is created with the consumer's view, so a tooltip's [slot=content] exists while hidden: its components, effects and fetches run. React mounts it only while shown, and again each time it shows. Write content with state as *molLazy (MolLazy from @molecule/app-angular): it is created when it shows and destroyed when it hides, as React's is.

@Component({
  selector: 'mol-tooltip',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: [
    'content',
    'placement',
    'delay',
    'hasArrow',
    'className',
    'style',
    'testId',
    'automationId',
    'dataMolId: data-mol-id',
    'id',
    'title',
    'onDoubleClick',
  ],
  template: `<div
      #triggerWrap
      [class]="cm().tooltipTrigger"
      role="presentation"
      (mouseover)="show()"
      (mouseout)="scheduleHide()"
      (focusin)="handleFocus($event)"
      (focusout)="hide()"
      (keydown)="handleKeyDown($event)"
      (click)="hide()"
    >
      <span #childrenCapture><ng-content></ng-content></span>
    </div>
    <div #portalWrap [style]="portalStyleText()">
      <div
        #contentEl
        role="tooltip"
        [id]="boxId()"
        [class]="contentClasses()"
        [style]="contentStyleText()"
        [attr.data-testid]="testId"
        [attr.data-mol-id]="molId()"
        [attr.title]="title"
        (dblclick)="onDoubleClick?.($event)"
        (mouseover)="keepVisible()"
        (mouseout)="scheduleHide()"
      >
        <ng-content select="[slot=content]"></ng-content>
      </div>
      @if (hasArrow) {
        <span aria-hidden="true" [style]="arrowStyleText()"></span>
      }
    </div>`,
})
export class Tooltip
  implements AfterViewInit, AfterViewChecked, DoCheck, OnDestroy, HasElement<HTMLDivElement>
{
  content?: unknown
  placement: TooltipPlacement = 'top'
  delay = 0
  hasArrow = false
  className?: string
  style?: Record<string, unknown>
  testId?: string
  automationId?: string
  dataMolId?: string
  id?: string
  title?: string
  onDoubleClick?: MouseEventHandler

  readonly tooltipId = nextInstanceId()
  boxId(): string {
    return this.id ?? this.tooltipId
  }

  molId(): string | undefined {
    return this.automationId ?? this.dataMolId ?? this.externalMolId
  }
  readonly visible = signal(false)
  private readonly position = signal<Position>({ top: 0, left: 0 })

  @ViewChild('triggerWrap') triggerWrap?: ElementRef<HTMLDivElement>
  @ViewChild('childrenCapture') childrenCapture?: ElementRef<HTMLSpanElement>
  @ViewChild('portalWrap') portalWrap?: ElementRef<HTMLDivElement>
  @ViewChild('contentEl') contentEl?: ElementRef<HTMLDivElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private readonly inner = signal<HTMLDivElement | null>(null)
  readonly element = this.inner.asReadonly()
  private readonly cdr = inject(ChangeDetectorRef)
  private showTimer: ReturnType<typeof setTimeout> | undefined
  private hideTimer: ReturnType<typeof setTimeout> | undefined
  private readonly hideListener = (): void => this.hide()
  private readonly layer = new OverlayLayer()
  private owner?: Document
  private lastVisible = false
  private lastContentText: string | null = null
  private lastPlacement: TooltipPlacement | null = null
  private associateEl: Element | null = null
  private externalMolId: string | undefined

  constructor() {
    afterEveryRender(() => this.repositionForContentChange())
    usePlacement((hasContent) => {
      const wrap = this.triggerWrap?.nativeElement
      const capture = this.childrenCapture?.nativeElement
      if (!wrap || !capture) return
      placeElementBefore(wrap, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
      setHostRoot(this.host.nativeElement, this.contentEl?.nativeElement, {
        except: ['data-mol-id'],
      })
      placeContent(capture, wrap)
      setElementPresent(capture, false)
      const children = hasContent.nodes(capture)
      const only = children.length === 1 ? slotElement(children[0]) : null
      if (only === this.associateEl) return
      if (this.visible()) {
        this.associateEl?.removeAttribute('aria-describedby')
        only?.setAttribute('aria-describedby', this.boxId())
      }
      this.associateEl = only
    })
  }

  private repositionForContentChange(): void {
    const text = this.contentEl?.nativeElement.textContent ?? null
    if (text === this.lastContentText && this.placement === this.lastPlacement) return
    this.lastContentText = text
    this.lastPlacement = this.placement
    if (this.visible()) this.updatePosition()
  }

  cm(): UIClassMap {
    return getClassMap()
  }

  contentClasses(): string {
    return this.cm().cn(this.cm().tooltipContent, this.className)
  }

  contentStyleText(): string | null {
    return styleText(this.style)
  }

  portalStyleText(): string | null {
    return styleText({
      position: 'absolute',
      top: this.position().top,
      left: this.position().left,
      zIndex: 9999,
    })
  }

  arrowStyleText(): string | null {
    return styleText(arrowStyle(this.placement))
  }

  show(): void {
    const doc = this.triggerWrap?.nativeElement.ownerDocument
    if (doc) {
      this.releaseOwner()
      this.owner = doc
      const previous = activeTooltips.get(doc)
      if (previous !== this.hideListener) previous?.()
      activeTooltips.set(doc, this.hideListener)
    }
    clearTimeout(this.hideTimer)
    clearTimeout(this.showTimer)
    if (this.delay > 0) {
      this.showTimer = setTimeout(() => {
        this.visible.set(true)
        this.cdr.markForCheck()
      }, this.delay)
    } else {
      this.visible.set(true)
      this.cdr.markForCheck()
    }
  }

  hide(): void {
    clearTimeout(this.showTimer)
    clearTimeout(this.hideTimer)
    this.releaseOwner()
    this.visible.set(false)
    this.cdr.markForCheck()
  }

  scheduleHide(): void {
    clearTimeout(this.showTimer)
    clearTimeout(this.hideTimer)
    this.hideTimer = setTimeout(() => this.hide(), 150)
  }

  keepVisible(): void {
    clearTimeout(this.hideTimer)
  }

  handleFocus(event: FocusEvent): void {
    const target = event.target
    try {
      if (target instanceof Element && target.matches(':focus-visible')) this.show()
    } catch (_error) {
    }
  }

  handleKeyDown(event: KeyboardEvent): void {
    if (!this.visible() && event.key === 'Escape') this.hide()
  }

  ngAfterViewInit(): void {
    setElementPresent(this.portalWrap?.nativeElement, false)
    this.lastVisible = false
  }

  ngAfterViewChecked(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.contentEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
  }

  ngDoCheck(): void {
    adoptHostDataMolId(
      this.host.nativeElement,
      this.contentEl?.nativeElement,
      (id) => {
        this.externalMolId = id
      },
      () => this.molId(),
    )
    const visible = this.visible()
    if (visible === this.lastVisible) return
    this.lastVisible = visible
    if (visible) this.attachPortal()
    else this.detachPortal()
  }

  ngOnDestroy(): void {
    clearTimeout(this.showTimer)
    clearTimeout(this.hideTimer)
    this.releaseOwner()
    this.layer.release()
    this.associateEl = null
  }

  private releaseOwner(): void {
    if (this.owner && activeTooltips.get(this.owner) === this.hideListener)
      activeTooltips.delete(this.owner)
    this.owner = undefined
  }

  private attachPortal(): void {
    const portal = this.portalWrap?.nativeElement
    const trigger = this.triggerWrap?.nativeElement
    if (!portal || !trigger) return
    placeElement(portal, trigger.ownerDocument.body)
    const surface = this.contentEl?.nativeElement ?? null
    this.inner.set(surface)
    this.updatePosition()
    this.associateEl?.setAttribute('aria-describedby', this.boxId())
    this.layer.sync({
      open: true,
      kind: 'tooltip',
      surface: { current: surface },
      anchor: { current: trigger },
      dismissKey: true,
      onDismiss: this.hideListener,
    })
  }

  private detachPortal(): void {
    const portal = this.portalWrap?.nativeElement
    placeElement(portal, null)
    setElementPresent(portal, false)
    this.inner.set(null)
    this.associateEl?.removeAttribute('aria-describedby')
    this.layer.release()
  }
// … truncated — 1 more member: updatePosition; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/tooltip.component.d.ts

(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-ui-angular/dist/components/tooltip.component.d.ts.)

UserMenuPopover

UserMenuPopover root: owns the open state and the auto-dismiss behavior (route change, outside click, Escape) and provides the identity context.

@Component({
  selector: 'div[mol-user-menu-popover]',
  standalone: true,
  inputs: ['guestName', 'className'],
  host: {
    '[class]': 'classes()',
  },
  template: `<ng-content></ng-content>`,
})
export class UserMenuPopover implements AfterViewInit, DoCheck, OnDestroy {
  /** Label shown when there is no authenticated user (default `Account`). */
  guestName?: UserMenuPopoverProps['guestName']
  /** Extra classes composed onto the relative-positioned container. */
  className?: UserMenuPopoverProps['className']

  /** Whether the popover is open. */
  readonly isOpen = signal(false)
  /** The popover's shared id (the normalizer renumbers it). */
  readonly panelId = nextInstanceId()
  /** Auth state (identity defaults). */
  readonly auth = useAuth<AccountUser>()
  /**
   * Translation state. Its `t` reads the locale, so the views that render it
   * re-render on a locale switch (the static `t` does not follow a switch).
   */
  readonly i18n = useTranslation()
  /** Router state: a route change closes the popover. */
  readonly router = useRouter()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)
  private readonly cdr = inject(ChangeDetectorRef)
  private readonly layer = new OverlayLayer()
  private readonly close = (): void => {
    this.isOpen.set(false)
    this.cdr.markForCheck()
  }
  private lastOpen = false
  private lastRoute: string | null = null
  /** Closes the popover on any route change (React's location effect). */
  private readonly routeEffect = effect(() => {
    const location = this.router.location()
    const key = `${location.pathname}${location.search}${(location as { hash?: string }).hash ?? ''}`
    if (this.lastRoute === null) {
      this.lastRoute = key
      this.isOpen.set(false)
      return
    }
    if (key !== this.lastRoute) {
      this.lastRoute = key
      this.isOpen.set(false)
    }
  })

  /** Registers the context on the host before any projected child resolves it. */
  constructor() {
    PopoverDomContext.provide(this.host.nativeElement, new UserMenuPopoverContextValue(this))
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The container class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().position('relative'), this.className)
  }

  /**
   * The resolved display name (auth name, then email, then the guest label).
   * @returns The name.
   */
  displayName(): string {
    const user = this.auth.user()
    return (
      user?.name ??
      user?.email ??
      this.guestName ??
      this.i18n.t('userMenuPopover.guest', {}, { defaultValue: 'Account' })
    )
  }

  /** Schedules a re-render of this component's view. */
  markForCheck(): void {
    this.cdr.markForCheck()
  }

  /** Observes the host window's history, including navigation to the same URL. */
  ngAfterViewInit(): void {
    this.host.nativeElement.ownerDocument.defaultView?.addEventListener('popstate', this.close)
  }

  /** Registers the mounted disclosure with the document stack while open. */
  ngDoCheck(): void {
    const open = this.isOpen()
    if (open === this.lastOpen) return
    this.lastOpen = open
    const target = { current: this.host.nativeElement }
    this.layer.sync({
      open,
      kind: 'popover',
      surface: target,
      anchor: target,
      dismissKey: true,
      outside: { inside: [target], phase: 'start' },
      onDismiss: this.close,
    })
  }

  /** Removes listeners and the context registration (unmount). */
  ngOnDestroy(): void {
    this.host.nativeElement.ownerDocument.defaultView?.removeEventListener('popstate', this.close)
    this.layer.release()
    PopoverDomContext.remove(this.host.nativeElement)
  }
}

UserMenuPopoverTrigger

The trigger: an initials avatar plus the account name and email, toggling the popover (the disclosure aria-expanded + aria-controls contract).

@Component({
  selector: 'button[mol-user-menu-popover-trigger]',
  standalone: true,
  inputs: ['ariaLabelKey', 'ariaLabelDefault', 'dataMolId', 'className'],
  host: {
    type: 'button',
    '[attr.aria-expanded]': 'open() ? "true" : "false"',
    '[attr.aria-controls]': 'context()?.panelId',
    '[attr.aria-label]': 'ariaLabel()',
    '[attr.data-mol-id]': 'dataMolId',
    '[class]': 'classes()',
    '(click)': 'toggle()',
  },
  template: `<span aria-hidden="true" [class]="initialsClasses()" [style]="initialsStyle()">{{
      initials()
    }}</span
    ><span [class]="cm().cn(cm().flex1, cm().minW(0))"
      ><span [class]="nameClasses()">{{ displayName() }}</span>
      @if (email(); as accountEmail) {
        <span [class]="secondaryClasses()">{{ accountEmail }}</span>
      }
    </span>`,
})
export class UserMenuPopoverTrigger {
  /** i18n key for the trigger's aria-label (default `userMenu.open`). */
  ariaLabelKey?: UserMenuPopoverTriggerProps['ariaLabelKey']
  /** Fallback aria-label (default `Open user menu`). */
  ariaLabelDefault?: UserMenuPopoverTriggerProps['ariaLabelDefault']
  /** `data-mol-id` for the trigger (default `user-menu`). */
  dataMolId?: UserMenuPopoverTriggerProps['dataMolId'] = 'user-menu'
  /** Extra classes for the trigger. */
  className?: UserMenuPopoverTriggerProps['className']

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The nearest popover context (React's context value).
   * @returns The context, or null outside a popover.
   */
  context(): UserMenuPopoverContext | null {
    return PopoverDomContext.find(this.host.nativeElement) ?? null
  }

  /**
   * Whether the popover is open.
   * @returns The open state (false outside a popover).
   */
  open(): boolean {
    return this.context()?.open ?? false
  }

  /**
   * The trigger's accessible label.
   * @returns The label text.
   */
  ariaLabel(): string {
    return this.i18n.t(
      this.ariaLabelKey ?? 'userMenu.open',
      {},
      {
        defaultValue: this.ariaLabelDefault ?? 'Open user menu',
      },
    )
  }

  /**
   * The resolved display name.
   * @returns The name.
   */
  displayName(): string {
    return this.context()?.displayName ?? ''
  }

  /**
   * The resolved account email.
   * @returns The email, or undefined.
   */
  email(): string | undefined {
    return this.context()?.email
  }

  /** The initials shown in the avatar badge. */
  initials(): string {
    return getInitials(this.displayName())
  }

  /** The trigger's class list. */
  classes(): string {
    return this.cm().cn(
      this.cm().flex({ align: 'center', gap: 'sm' }),
      this.cm().sp('px', 3),
      this.cm().sp('py', 3),
      this.cm().userMenuPopoverTrigger,
      this.className,
    )
  }

  /** The initials badge class list. */
  initialsClasses(): string {
    return this.cm().cn(
      this.cm().w(10),
      this.cm().h(10),
      this.cm().roundedFull,
      this.cm().flex({ align: 'center', justify: 'center' }),
      this.cm().textSize('sm'),
      this.cm().fontWeight('bold'),
      this.cm().shrink0,
    )
  }

  /** The initials badge's inline style. */
  initialsStyle(): string | null {
    return styleText({
      backgroundColor: 'var(--color-primary)',
      color: 'var(--color-on-primary, #ffffff)',
    })
  }

  /** The display-name class list. */
  nameClasses(): string {
    return this.cm().cn(
      this.cm().textSize('sm'),
      this.cm().fontWeight('semibold'),
      this.cm().displayBlock,
      this.cm().textTruncate,
    )
  }

  /** The email class list. */
  secondaryClasses(): string {
    return this.cm().cn(
      this.cm().textSize('xs'),
      this.cm().displayBlock,
      this.cm().textTruncate,
      this.cm().textMuted,
    )
  }

  /** Toggles the popover (React's `setOpen(!open)`). */
  toggle(): void {
    this.context()?.setOpen(!this.open())
  }
}

UserMenuPopoverPanel

The popover panel: an absolutely-positioned card with an identity header and a <nav> wrapping the caller's items. The host element is the card (React's one <div>), and it is out of the DOM while the popover is closed (React renders null).

Projected content is created with the consumer's view, so a closed popover's items exist while hidden: their components, effects and fetches run. React mounts them only while shown, and again each time they show. Write content with state as *molLazy (MolLazy from @molecule/app-angular): it is created when it shows and destroyed when it hides, as React's is.

@Component({
  selector: 'div[mol-user-menu-popover-panel]',
  standalone: true,
  inputs: ['ariaLabelKey', 'ariaLabelDefault', 'dataMolId', 'className'],
  host: {
    '[attr.id]': 'panelId()',
    '[attr.data-mol-id]': 'dataMolId',
    '[class]': 'classes()',
  },
  template: `<header [class]="cm().cn(cm().sp('pb', 4), cm().userMenuPopoverHeader)">
      <p [class]="cm().cn(cm().textSize('sm'), cm().fontWeight('semibold'))">{{ displayName() }}</p>
      @if (email(); as accountEmail) {
        <p [class]="cm().cn(cm().textSize('xs'), cm().textMuted)">{{ accountEmail }}</p>
      }
    </header>
    <nav [class]="cm().cn(cm().sp('mt', 4), cm().stack(1))" [attr.aria-label]="navLabel()">
      <ng-content></ng-content>
    </nav>`,
})
export class UserMenuPopoverPanel {
  /** i18n key for the panel's aria-label (default `userMenu.panelLabel`). */
  ariaLabelKey?: UserMenuPopoverPanelProps['ariaLabelKey']
  /** Fallback aria-label (default `Account menu`). */
  ariaLabelDefault?: UserMenuPopoverPanelProps['ariaLabelDefault']
  /** `data-mol-id` for the panel (default `user-menu-panel`). */
  dataMolId?: UserMenuPopoverPanelProps['dataMolId'] = 'user-menu-panel'
  /** Extra classes for the panel. */
  className?: UserMenuPopoverPanelProps['className']

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  constructor() {
    useHostPresence(() => this.open())
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The nearest popover context.
   * @returns The context, or null outside a popover.
   */
  context(): UserMenuPopoverContext | null {
    return PopoverDomContext.find(this.host.nativeElement) ?? null
  }

  /**
   * Whether the popover is open.
   * @returns The open state.
   */
  open(): boolean {
    return this.context()?.open ?? false
  }

  /** The panel's shared id. */
  panelId(): string | null {
    return this.context()?.panelId ?? null
  }

  /** The resolved display name. */
  displayName(): string {
    return this.context()?.displayName ?? ''
  }

  /** The resolved account email. */
  email(): string | undefined {
    return this.context()?.email
  }

  /**
   * The nav's accessible label.
   * @returns The label text.
   */
  navLabel(): string {
    return this.i18n.t(
      this.ariaLabelKey ?? 'userMenu.panelLabel',
      {},
      {
        defaultValue: this.ariaLabelDefault ?? 'Account menu',
      },
    )
  }

  /**
   * The panel card class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(this.cm().userMenuPopoverPanel, this.className)
  }
}

UserMenuPopoverSignOut

The sign-out nav item: closes the popover and signs out.

@Component({
  selector: 'button[mol-user-menu-popover-sign-out]',
  standalone: true,
  inputs: ['labelKey', 'labelDefault', 'dataMolId', 'className'],
  host: {
    type: 'button',
    '[attr.data-mol-id]': 'dataMolId',
    '[class]': 'classes()',
    '(click)': 'signOut()',
  },
  template: `{{ label() }}`,
})
export class UserMenuPopoverSignOut {
  /** i18n key for the button label (default `userMenu.signOut`). */
  labelKey?: UserMenuPopoverSignOutProps['labelKey']
  /** Fallback label (default `Sign out`). */
  labelDefault?: UserMenuPopoverSignOutProps['labelDefault']
  /** `data-mol-id` for the button (default `user-menu-sign-out`). */
  dataMolId?: UserMenuPopoverSignOutProps['dataMolId'] = 'user-menu-sign-out'
  /** Extra classes for the button. */
  className?: UserMenuPopoverSignOutProps['className']

  /** Auth state (the logout action). */
  readonly auth = useAuth()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The nearest popover context.
   * @returns The context, or null outside a popover.
   */
  context(): UserMenuPopoverContext | null {
    return PopoverDomContext.find(this.host.nativeElement) ?? null
  }

  /**
   * The button label.
   * @returns The label text.
   */
  label(): string {
    return this.i18n.t(
      this.labelKey ?? 'userMenu.signOut',
      {},
      {
        defaultValue: this.labelDefault ?? 'Sign out',
      },
    )
  }

  /**
   * The button class list.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().sp('px', 3),
      this.cm().sp('py', 2),
      this.cm().textSize('sm'),
      this.cm().fontWeight('semibold'),
      this.cm().displayBlock,
      this.cm().w('full'),
      this.cm().textError,
      this.cm().userMenuPopoverSignOut,
      this.className,
    )
  }

  /** Closes the popover and signs out (React's click handler). */
  async signOut(): Promise<void> {
    this.context()?.setOpen(false)
    try {
      await this.auth.logout()
    } catch (_error) {
      // A logout failure should not crash the panel — the user is already
      // treated as signed out from the UI's perspective.
    }
  }
}

UserMenu

UserMenu component.

React's root is a FRAGMENT (the trigger button plus a drawer), so the trigger button renders in front of the host (placeElementBefore) and the host itself leaves the DOM — the rendered tree and focus paths match React's (a route change must restore focus to the trigger). The panel content is projected inside the drawer through PanelCloseProvider.

@Component({
  selector: 'mol-user-menu',
  standalone: true,
  imports: [Button, Icon, Modal, PanelCloseProvider],
  hostDirectives: [MolPlacement],
  inputs: [
    'ariaLabelKey',
    'ariaLabelDefault',
    'triggerIcon',
    'triggerIconSize',
    'dataMolId',
    'className',
    'disabled',
    'onClick',
    'side',
  ],
  template: `<button
      #trigger
      mol-button
      [variant]="'ghost'"
      [size]="'sm'"
      [className]="triggerClasses()"
      [disabled]="!!disabled"
      (click)="handleTriggerClick($event)"
      [attr.aria-label]="ariaLabel()"
      [attr.data-mol-id]="dataMolId"
    >
      <svg
        mol-icon-root
        [name]="triggerIcon ?? 'user'"
        [size]="triggerIconSize ?? 20"
      ></svg></button
    ><mol-modal
      [open]="isOpen()"
      (close)="isOpen.set(false)"
      [className]="drawerClasses()"
      [attr.aria-label]="panelLabel()"
      ><mol-panel-close-provider [close]="closePanel"
        ><ng-content></ng-content></mol-panel-close-provider
    ></mol-modal>`,
})
export class UserMenu {
  /** i18n key for the trigger's aria-label (default `userMenu.open`). */
  ariaLabelKey?: UserMenuProps['ariaLabelKey']
  /** Fallback aria-label (default `Open user menu`). */
  ariaLabelDefault?: UserMenuProps['ariaLabelDefault']
  /** Icon name for the trigger (default `user`). */
  triggerIcon?: UserMenuProps['triggerIcon']
  /** Pixel size for the trigger icon (default 20). */
  triggerIconSize?: UserMenuProps['triggerIconSize']
  /** `data-mol-id` for the trigger (default `user-menu`). */
  dataMolId?: UserMenuProps['dataMolId'] = 'user-menu'
  /** Extra classes composed onto the trigger. */
  className?: UserMenuProps['className']
  /** Whether the trigger is disabled. */
  disabled?: UserMenuProps['disabled']
  /** Overrides the trigger click (called instead of opening the panel). */
  onClick?: UserMenuProps['onClick']
  /** Which side the panel opens from (default `right`). */
  side?: UserMenuProps['side'] = 'right'

  /** Whether the drawer is open. */
  readonly isOpen = signal(false)
  /** Router state: a route change closes the drawer (React's effect). */
  readonly router = useRouter()

  /**
   * Reactive translation, read in the injection context. Its `t` reads the
   * locale, so the view re-renders the text on a locale switch (the static `t`
   * does not).
   */
  private readonly i18n = useTranslation()

  /** The trigger button (adopted beside the host). */
  @ViewChild('trigger', { read: ElementRef }) trigger?: ElementRef<HTMLButtonElement>

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    usePlacement(() => {
      const trigger = this.trigger?.nativeElement
      if (!trigger) return
      placeElementBefore(trigger, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
  }
  private readonly routeEffect = effect(() => {
    const location = this.router.location()
    void `${location.pathname}${location.search}`
    // React's effect runs on mount too; closing an already-closed drawer is a no-op.
    this.isOpen.set(false)
  })

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The trigger's accessible label.
   * @returns The label text.
   */
  ariaLabel(): string {
    return this.i18n.t(
      this.ariaLabelKey ?? 'userMenu.open',
      {},
      {
        defaultValue: this.ariaLabelDefault ?? 'Open user menu',
      },
    )
  }

  /**
   * The drawer panel's accessible label.
   * @returns The label text.
   */
  panelLabel(): string {
    return this.i18n.t('userMenu.panelLabel', {}, { defaultValue: 'Account menu' })
  }

  /**
   * The trigger's class list (a 40x40 minimum target plus the caller's classes).
   * @returns The class string.
   */
  triggerClasses(): string {
    return this.cm().cn(this.cm().minH(10), this.cm().minW(10), this.className)
  }

  /**
   * The drawer's class list (side-aware).
   * @returns The class string.
   */
  drawerClasses(): string {
    return this.side === 'left'
      ? this.cm().cn(this.cm().drawer, this.cm().drawerLeft)
      : this.cm().drawer
  }

  /** Closes the drawer (the panel-close context's callback). */
  closePanel = (): void => {
    this.isOpen.set(false)
  }

  /**
   * Opens the drawer unless a custom click handler intercepts (React passes
   * the handler straight to the button, so it receives the click event).
   *
   * @param event - The click event.
   */
  handleTriggerClick(event: MouseEvent): void {
    if (this.onClick) this.onClick(event)
    else this.isOpen.set(true)
  }
}

ElementPropsWriter

Writes a React element-prop record onto one Angular element, re-applying only what changed since the previous ElementPropsWriter.write.

The rules are React's spread:

  • on[A-Z]* functions become listeners (onClick → click, a Capture suffix → capture phase, onDoubleClick → dblclick); a non-function value removes the listener, and so does dropping the key.
  • className and class compose into one class attribute with cn.
  • An object style is serialized with reactStyleText.
  • Every other key becomes an attribute: null/undefined removes it, false removes it (except text booleans, which write "false"), and true writes "" (text booleans write "true"). Any other value is stringified.
class ElementPropsWriter {
  private readonly renderer: Renderer2
  private readonly element: Element
  private applied = new Map<string, unknown>()
  private readonly listeners = new Map<string, () => void>()

  /**
   * Creates a writer bound to one element.
   *
   * @param renderer - Angular's renderer, which owns the platform's DOM writes.
   * @param element - The element the props are written onto.
   */
  constructor(renderer: Renderer2, element: Element) {
    this.renderer = renderer
    this.element = element
  }

  /**
   * Applies `props` to the element, touching only the keys whose value
   * changed since the previous call (and removing the ones that went).
   *
   * A key in `skip` is left alone: the caller's own template binding or
   * router link owns it. The channel keys are controlled the same way —
   * `className`/`class` compose into `class` unless `skip` holds `class`, and
   * `style` is serialized unless `skip` holds `style` (so a component whose
   * template already binds the class and style of the same element keeps
   * them).
   *
   * @param props - The React-shaped props record to write.
   * @param skip - Keys the caller owns; they are never written and any value
   * written by an earlier call is removed.
   */
  write(props: Readonly<Record<string, unknown>>, skip?: ReadonlySet<string>): void {
    const next = new Map<string, unknown>()
    for (const [key, value] of Object.entries(props)) {
      if (skip?.has(key)) continue
      if (key === 'className' || key === 'class') continue
      if (key === 'style') {
        next.set('style', reactStyleText(value, ' '))
        continue
      }
      next.set(key, value)
    }
    if (!skip?.has('class')) {
      const classes = cn(
        typeof props.className === 'string' ? props.className : undefined,
        typeof props.class === 'string' ? props.class : undefined,
      )
      if (classes) next.set('class', classes)
    }
    // A key the caller has since taken over stays as it is, and stays tracked
    // so a later call without the skip still removes what this writer applied.
    const kept = new Map<string, unknown>()
    for (const [key, value] of this.applied) if (skip?.has(key)) kept.set(key, value)
    const keys = new Set(next.keys())
    for (const key of this.applied.keys()) if (!skip?.has(key)) keys.add(key)
    for (const key of keys) {
      const value = next.get(key)
      if (this.applied.has(key) && this.applied.get(key) === value) continue
      this.removeListener(key)
      if (isListener(key)) {
        if (typeof value === 'function') {
          const capture = key.endsWith('Capture')
          const event = key.slice(2, capture ? -7 : undefined).toLowerCase()
          this.listeners.set(
            key,
            this.renderer.listen(
              this.element,
              event === 'doubleclick' ? 'dblclick' : event,
              (browserEvent: Event) => {
                value(browserEvent)
              },
              { capture },
            ),
          )
        }
      } else if (value == null || (value === false && !TEXT_BOOLEAN.test(key))) {
        this.renderer.removeAttribute(this.element, key)
      } else {
        this.renderer.setAttribute(
          this.element,
          key,
          value === true && !TEXT_BOOLEAN.test(key) ? '' : String(value),
        )
      }
    }
    this.applied = new Map([...kept, ...next])
  }

  /**
   * Removes every listener the writer added. The caller's element may outlive
   * the props: an Angular port calls this when the element is destroyed or
   * replaced.
   */
  destroy(): void {
    for (const remove of this.listeners.values()) remove()
    this.listeners.clear()
    this.applied = new Map()
  }

  /**
   * Removes the listener registered for one key, if any.
   *
   * @param key - The prop key whose listener goes.
   */
  private removeListener(key: string): void {
    const remove = this.listeners.get(key)
    if (!remove) return
    remove()
    this.listeners.delete(key)
  }
}

FieldHostAria

Reflects native attribute bindings from a field's Angular host into its control.

class FieldHostAria {
  readonly description = signal<string | null>(null)
  readonly invalid = signal<string | null>(null)

  /** Reads the caller's latest native bindings during each parent check. */
  read(host: Element): void {
    this.description.set(host.getAttribute('aria-describedby'))
    this.invalid.set(host.getAttribute('aria-invalid'))
  }
}

MolIconSvg

Internal SVG renderer used by every React-parity component where React renders through renderIcon / Icon.

The component's selector is an attribute on the <svg> itself (<svg mol-icon …>), so the host IS the svg element and no wrapper element exists. Attribute parity with React's renderIcon: xmlns, aria-hidden="true", focusable="false", class, viewBox, fill (or the stroke group when the icon is stroked) and <path> children. icon.svg-backed glyphs inject the bond's raw inner markup (the bond is the trust boundary, exactly as React's dangerouslySetInnerHTML).

@Component({
  selector: 'svg[mol-icon]',
  standalone: true,
  inputs: ['data'],
  host: {
    xmlns: 'http://www.w3.org/2000/svg',
    '[attr.aria-hidden]': '"true"',
    '[attr.focusable]': '"false"',
    '[class]': 'data?.className',
    '[attr.viewBox]': 'data?.viewBox',
    '[attr.fill]': 'fill',
    '[attr.stroke]': 'strokeAttrs.stroke',
    '[attr.stroke-width]': 'strokeAttrs.strokeWidth',
    '[attr.stroke-linecap]': 'strokeAttrs.strokeLinecap',
    '[attr.stroke-linejoin]': 'strokeAttrs.strokeLinejoin',
  },
  template: `@for (p of paths; track $index) {
    <svg:path
      [attr.d]="p.d"
      [attr.fill]="p.fill"
      [attr.fill-rule]="p.fillRule"
      [attr.clip-rule]="p.clipRule"
      [attr.opacity]="p.opacity"
    />
  }`,
})
export class MolIconSvg implements OnChanges {
  /** The resolved icon data (plain field input, JIT-visible). */
  data?: ResolvedIcon

  /**
   * The fill attribute value, matching React's `renderIcon` (which writes the
   * icon's own fill or `currentColor`, even for a stroked glyph) and React
   * `Icon`'s svg-backed branch (`icon.fill` or `none`).
   * @returns The fill value.
   */
  get fill(): string {
    if (this.data?.icon.svg) return this.data.icon.fill || 'none'
    return this.data?.icon.fill || 'currentColor'
  }

  /**
   * Stroke attribute values (null when the icon is not stroked).
   * @returns The stroke attribute bag.
   */
  get strokeAttrs(): {
    stroke: string | null
    strokeWidth: number | null
    strokeLinecap: string | null
    strokeLinejoin: string | null
  } {
    if (!this.data?.stroked) {
      return { stroke: null, strokeWidth: null, strokeLinecap: null, strokeLinejoin: null }
    }
    const icon = this.data.icon
    return {
      stroke: icon.stroke ?? null,
      strokeWidth: icon.strokeWidth ?? null,
      strokeLinecap: icon.strokeLinecap ?? null,
      strokeLinejoin: icon.strokeLinejoin ?? null,
    }
  }

  /**
   * The paths to render (empty for `icon.svg`-backed glyphs).
   * @returns The path list.
   */
  get paths(): IconData['paths'] {
    return this.data?.icon.svg ? [] : (this.data?.icon.paths ?? [])
  }

  /**
   * Injects raw `icon.svg` markup into the svg host when the icon carries it.
   *
   * @param changes - The changed inputs.
   */
  ngOnChanges(changes: { data?: { currentValue: ResolvedIcon } }): void {
    if (!changes.data) return
    const svg = changes.data.currentValue.icon.svg
    if (svg) (this.host.nativeElement as SVGSVGElement).innerHTML = svg
  }

  private readonly host: ElementRef<SVGSVGElement> = inject(ElementRef)
}

WebDragDirective

Binds an HTML or SVG element to the web kits' shared drag gesture. Import WebDragDirective into a standalone component and bind [molDrag]="handlers". Pass a drag or { drag, zoom }. Undefined disables the gesture.

@Directive({
  selector: '[molDrag]',
  standalone: true,
  host: { '(pointerdown)': 'onPointerDown($event)' },
})
export class WebDragDirective implements OnDestroy {
  private readonly host = inject<ElementRef<HTMLElement | SVGElement>>(ElementRef).nativeElement
  private readonly gesture = createWebDrag()

  /** The current handlers for this host. */
  @Input()
  set molDrag(options: WebDragOptions | undefined) {
    this.gesture.attach(this.host)
    this.gesture.update(options)
  }

  /**
   * Offers a primary pointer press to this directive's element.
   *
   * @param event - The native bubbling pointer event.
   */
  onPointerDown(event: PointerEvent): void {
    this.gesture.start(this.host, event)
  }

  /** Cancels the gesture when Angular destroys its host. */
  ngOnDestroy(): void {
    this.gesture.attach(null)
  }
}

WebHoverDirective

Handles shared mouse and pen hover. Import WebHoverDirective into a standalone component, add molHover to the host and listen for (molHoverEnter) and (molHoverLeave). Bind [molHover]="false" to disable hover.

@Directive({
  selector: '[molHover]',
  standalone: true,
  outputs: ['molHoverEnter', 'molHoverLeave'],
})
export class WebHoverDirective implements OnDestroy {
  /** Emits when a mouse or pen enters the host. */
  readonly molHoverEnter = new EventEmitter<MouseEvent>()

  /** Emits when the hovering mouse or pen leaves the host. */
  readonly molHoverLeave = new EventEmitter<MouseEvent>()

  private readonly binding = bindWebHover(
    inject<ElementRef<HTMLElement | SVGElement>>(ElementRef).nativeElement,
  )

  private readonly handlers = {
    onEnter: (event: MouseEvent) => this.molHoverEnter.emit(event),
    onLeave: (event: MouseEvent) => this.molHoverLeave.emit(event),
  }

  /** Enables the gesture on this host. */
  @Input({ transform: booleanAttribute })
  set molHover(enabled: boolean) {
    this.binding.update(enabled ? this.handlers : undefined)
  }

  /** Removes the hover listeners when Angular destroys the host. */
  ngOnDestroy(): void {
    this.binding.destroy()
  }
}

WebWheelZoomDirective

Handles shared Ctrl-wheel zoom steps. Import WebWheelZoomDirective into a standalone component and bind [molWheelZoom]="onStep". Pass undefined to leave the wheel to the browser.

@Directive({ selector: '[molWheelZoom]', standalone: true })
export class WebWheelZoomDirective implements OnDestroy {
  private readonly binding = bindWebWheelZoom(
    inject<ElementRef<HTMLElement | SVGElement>>(ElementRef).nativeElement,
  )

  /** Sets the callback that receives each handled zoom step. */
  @Input()
  set molWheelZoom(onStep: WebWheelZoomHandler | undefined) {
    this.binding.update(onStep)
  }

  /** Removes the wheel listener when Angular destroys the host. */
  ngOnDestroy(): void {
    this.binding.destroy()
  }
}

Functions

hasNodes(el) (deprecated)

Deprecated: Read the slot with the reader usePlacement from @molecule/app-angular passes to the placement function.

Whether an ng-content wrapper captured any element or text node, read from a lifecycle hook, which can lag the content: a hook runs before the consumer's @if adds its node, and no hook runs at all when the content comes through an OnPush component in between.

function hasNodes(el: Element | undefined | null): boolean
  • el — The wrapper element.

Returns: True when at least one projected node exists.

getModalWrapperStyle(centered)

Get the inline style for the modal centering wrapper. dialogWrapper has no dedicated ClassMap resolver option (it's a fixed token, not a { centered }-parameterized one), so a top-anchored (non-centered) layout is expressed via the one inline-style exception the workspace styling rule allows for values ClassMap genuinely cannot express.

A standalone function (rather than a class member) so it's unit-testable without constructing MoleculeModal — the class can't be new'd outside an Angular injection context (sanitizer = inject(DomSanitizer) runs at field-initializer time).

function getModalWrapperStyle(centered: boolean): Record<string, string> | undefined
  • centered — Whether the modal is vertically centered.

Returns: An inline style object, or undefined when centered.

getTooltipArrowStyle(placement)

Returns the arrow's inline position style for a given placement. The arrow has no dedicated ClassMap resolver (tooltip() takes no options), so its shape/position is expressed via a small inline style — the sanctioned exception for values ClassMap cannot express. Its color is NOT hardcoded: var(--color-surface) / var(--color-border) are the same CSS custom properties the bg-surface/border classes in tooltipContent resolve to, so the arrow always matches the tooltip body in both themes.

A standalone function (rather than a class member) so it's unit-testable in isolation, matching getModalWrapperStyle() in modal.component.ts.

function getTooltipArrowStyle(placement: TooltipPlacement): Record<string, string>
  • placement — The tooltip's resolved placement.

Returns: Inline style positioning the rotated-square arrow for that placement.

usePanelClose()

Returns the callback that dismisses the drawer the current panel is mounted in. Safe to call anywhere — a no-op outside a provider.

Must be called in an injection context (a component field initializer or constructor).

function usePanelClose(): () => void

Returns: A function that closes the enclosing drawer, or a no-op.

useToast()

Accesses the toast context for adding and removing toasts.

Must be called in an injection context (a component field initializer or constructor).

function useToast(): ToastContextValue

Returns: The toast context value.

useUserMenuPopoverClose()

Returns a callback that closes the enclosing UserMenuPopover (a no-op outside one).

Must be called in an injection context (a component field initializer or constructor).

function useUserMenuPopoverClose(): () => void

Returns: A function that closes the popover.

useIsDesktop(query)

Whether the viewport is at least 768px wide (the fleet's md breakpoint).

Reads window.matchMedia synchronously when the value is created, so the first render is already correct (no mobile-then-desktop swap frame), then follows change events. Guarded for non-browser environments (SSR/node): false (the mobile shell) when no window.matchMedia exists.

Must be called in an injection context (a component field initializer or constructor).

function useIsDesktop(query?: string): Signal<boolean>
  • query — Override the media query. Defaults to (min-width: 768px).

Returns: A signal of whether the desktop shell should mount.

createDomContext(name)

Creates a context (React's createContext).

function createDomContext<T>(name: string): DomContext<T>
  • name — The context's name, for debugging.

Returns: The context.

provideDomContext(host, value) (deprecated)

Deprecated: Use a context of your own: createDomContext.

Registers a value on a provider's host element, in the one context every caller of these three functions shares: a consumer then finds the nearest registration of ANY of them.

function provideDomContext(host: Element, value: unknown): void
  • host — The provider component's host element.
  • value — The context value.

removeDomContext(host) (deprecated)

Deprecated: Use a context of your own: createDomContext.

Removes a registration (on provider destroy).

function removeDomContext(host: Element): void
  • host — The provider component's host element.

findDomContext(start) (deprecated)

Deprecated: Use a context of your own: createDomContext.

Finds the nearest enclosing value for a consumer's element.

function findDomContext<T>(start: Element | null): T | undefined
  • start — The consumer's element (its own registration is ignored).

Returns: The nearest registered value, or undefined when there is none.

findDomContextIncludingSelf(start) (deprecated)

Deprecated: Use a context of your own: createDomContext. A provider registers on its own host and a consumer looks up from its own host, so no lookup needs to include itself.

Finds the value registered on the element itself, or else the nearest enclosing one.

function findDomContextIncludingSelf<T>(start: Element | null): T | undefined
  • start — The consumer's element.

Returns: The registered value, or undefined when there is none.

hostElement(host)

The ref element of a component whose host IS the element React forwards.

The kit's selectors name the native element React renders at its root, so the host element is that element.

function hostElement<E extends Element>(host: ElementRef<E>): Signal<E | null>
  • host — The component's host ElementRef.

Returns: A read-only signal holding the host element.

elementTarget(read)

A target that reads an element each time an overlay asks for it, such as a Modal's initialFocus naming a control in the dialog's content. A class field can build it, since the arrow keeps this: readonly emailTarget = elementTarget(() => this.email?.nativeElement).

function elementTarget(read: () => ElementHandle | null | undefined): OverlayTarget
  • read — Returns the element, or null or undefined while it is not rendered.

Returns: The target, whose current is the element or null.

getFocusableElements(container)

Returns the tab-stop elements inside a container, in DOM (tab) order.

function getFocusableElements(container: HTMLElement): HTMLElement[]
  • container — The element to search within.

Returns: The focusable descendants, in document order.

createScrollLock()

Reference-counted body scroll lock. Two dialogs can be open at once (a drawer with a confirm above it); a shared counter means closing either one only restores overflow when the last one closes.

One counter per call site family — React keeps Modal's and the responsive shell drawer's counters in separate module scopes, so each createScrollLock() result is independent, matching that behavior.

function createScrollLock(): {
  /** Locks body scroll on the first caller; later callers just increment the count. */
  lock: () => void
  /** Decrements the count; restores the original overflow only once it reaches zero. */
  unlock: () => void
}

Returns: Lock/unlock functions with a shared reference count.

descriptionIds(values)

Combines ARIA ID references while preserving their order.

function descriptionIds(...values: (string | null | undefined)[]): string | null

fieldContext(host)

Finds the nearest enclosing FormField context for a field's host element.

Resolved on every read: the field's own view is created before FormField moves its projected children into place, so a value captured once at construction could be stale.

function fieldContext(host: Element | null): FormFieldContext | null
  • host — The field component's host element.

Returns: The context, or null outside a FormField.

formSubmitErrorMessages(error, fallback)

Reads auth/HTTP response bodies, field-error dictionaries and ordinary failures. Server text is rendered as text by Form; malformed or empty bodies use the fallback.

function formSubmitErrorMessages(error: unknown, fallback: string): string[]
  • error — A rejected submission or a controlled server error.
  • fallback — The already translated generic failure message.

Returns: Nonempty messages suitable for a visible error list.

getIconSvg(name, className) (deprecated)

Deprecated: Used only by the deprecated Molecule* spike components.

Generates SVG markup string from an icon name.

function getIconSvg(name: IconName, className: string): string
  • name — Icon name from the icon set
  • className — CSS class for sizing

Returns: SVG markup string

nextInstanceId()

Mints a unique DOM id. React's useId() produces per-render-instance ids that the conformance normalizer renumbers by document order, so the exact format does not matter — only uniqueness and stable per-instance identity (one call per logical id, kept in a field).

function nextInstanceId(): string

Returns: A unique id string.

getInitials(value)

Compute up-to-two-letter initials from a display name or email.

function getInitials(value: string | null | undefined): string
  • value — The name or email to derive initials from.

Returns: The uppercased initials, or '?' when no usable input is given.

asTemplate(value)

Whether a node-valued prop arrived as a TemplateRef.

function asTemplate(value: unknown): TemplateRef<unknown> | null
  • value — The prop value.

Returns: The TemplateRef, or null for any other value.

nodeText(value)

Renders a plain-string (or numeric) node value (React renders both as text).

function nodeText(value: unknown): string
  • value — The prop value.

Returns: The text, or empty.

isGiven(value)

Whether a node-valued prop was passed at all (presence check for conditional wrappers).

function isGiven(value: unknown): boolean
  • value — The prop value.

Returns: True when given.

rendersNode(value)

Whether a node-valued prop renders anything: React's slot(node) !== undefined for the values an Angular input carries (not null, undefined, a boolean or ''; a template counts).

function rendersNode(value: unknown): boolean
  • value — The prop value.

Returns: True when it renders something.

shallowEqual(a, b)

Shallow equality (React's @molecule/app-state semantics).

function shallowEqual(a: unknown, b: unknown): boolean
  • a — One value.
  • b — The other value.

Returns: Whether the values are shallowly equal.

createOptimisticValue(options)

Creates the optimistic-value controller.

function createOptimisticValue<T>(options: OptimisticValueOptions<T>): OptimisticValue<T>
  • options — Initial value, commit and callbacks.

Returns: The controller.

resolveIcon(name, className)

Resolves an icon from the bonded set, throwing on unknown names exactly like @molecule/app-icons's getIcon (an unknown name is a runtime error, not a blank).

function resolveIcon(name: IconName, className?: string): ResolvedIcon
  • name — The icon name.
  • className — The class for the <svg> (a cm.* token).

Returns: The resolved icon data.

moveRestAttributes(host, target, keepFieldAria)

Moves every rest attribute (aria-*, data-*, id, …) from the host element onto the element React spreads {...rest} onto.

The first move happens at view init; a caller whose rest attributes follow state (an accessible label that switches with the locale) re-moves the re-bound ones with reapplyRestAttributes.

function moveRestAttributes(
  host: Element,
  target: Element | undefined | null,
  keepFieldAria?: boolean,
): string[]
  • host — The component host element.
  • target — The element React's ...rest targets.
  • keepFieldAria — Keep the host attributes used by a field's description and validation bindings.

Returns: The moved attribute names.

reapplyRestAttributes(host, target, options)

Moves the rest attributes a caller RE-BOUND since the last move.

Angular writes a changed [attr.x] binding back onto the host after moveRestAttributes took its first value off it, so without this the inner element keeps the first label forever while the host accumulates the new one. aria-describedby is left alone by default: the input family captured the host's value once and merges it with the field context's own target on its inner binding, so re-moving a re-bound value would erase that merge. A component that spreads the attribute onto ...rest with no merge passes ReapplyRestAttributesOptions.includeDescribedBy.

Idempotent: a host with nothing re-bound moves nothing.

function reapplyRestAttributes(
  host: Element,
  target: Element | undefined | null,
  options?: ReapplyRestAttributesOptions,
): string[]
  • host — The component host element.
  • target — The element React's ...rest targets.
  • options — Whether to move aria-describedby too.

Returns: The moved attribute names.

takeDataMolId(host)

Reads and removes a caller's data-mol-id from the host, for a component whose React ...rest target is an inner element: the value is re-rendered on that element by the component's own data-mol-id binding, so it must not stay on the wrapper as a duplicate.

function takeDataMolId(host: Element): string | undefined
  • host — The component host element.

Returns: The value, or undefined when the host had none.

adoptHostDataMolId(host, target, store, molId)

Takes a data-mol-id the caller bound on the host ([attr.data-mol-id]) and writes the id the component renders onto its element in the same pass, as React spreads it there in the render that passed it. Call it from ngAfterViewInit and ngAfterViewChecked, before moveRestAttributes / reapplyRestAttributes: by then the host attribute of this pass is written, while the element's own [attr.data-mol-id] binding already ran. A component that only stored the id showed it a change detection late, and a move that ran first carried the raw host value over the component's own automationId.

function adoptHostDataMolId(
  host: Element,
  target: Element | undefined | null,
  store: (hostId: string) => void,
  molId: () => string | undefined,
): void
  • host — The component host element.
  • target — The element that carries the id, when rendered.
  • store — Keeps the taken host id for the component's molId().
  • molId — The id the component renders, read after store.

styleText(style)

Serializes a React-shaped style object for Angular's [style] binding. Resolves overlapping properties that Angular would apply out of order.

function styleText(style: Record<string, unknown> | undefined | null): string | null
  • style — The style object, or an absent value.

Returns: CSS declaration text, or null when there are no declarations.

cn(inputs)

Merge class names, filtering out falsy values.

function cn(...inputs: (string | undefined | null | false)[]): string
  • inputs — The inputs.

Returns: The resulting string.

kebab(name)

Converts a React property name to its CSS spelling.

function kebab(name: string): string
  • name — A camelCase, vendor-prefixed or custom property name.

Returns: The CSS property name.

reactStyleText(style, space)

Serializes a React-shaped style object as React DOM's style attribute value. The renderer escapes the value when it writes HTML.

function reactStyleText(style: unknown, space?: '' | ' '): string | undefined
  • style — The style object, or an absent value.
  • space — An optional space after separators for existing bindings that use spaced CSS.

Returns: The CSS declaration text, or undefined when there are no declarations.

toStyleProps(style)

Normalizes a React-shaped style object for renderers that accept a CSS property map.

function toStyleProps(style: unknown): Record<string, string> | undefined
  • style — The style object, or an absent value.

Returns: CSS property names and string values, or undefined for an absent object.

Constants

FOCUSABLE_SELECTOR

Elements the WAI-ARIA APG dialog pattern treats as tab-stops for the focus trap.

const FOCUSABLE_SELECTOR: 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'

FormFieldDomContext

The context FormField registers on its host.

const FormFieldDomContext: DomContext<FormFieldContext>

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.16.1 || ^4.0.0
  • @molecule/app-filesystem ^1.1.0
  • @molecule/app-i18n ^1.0.1
  • @molecule/app-icons ^1.0.1
  • @molecule/app-ui ^1.18.0

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @molecule/app-angular

  • @molecule/app-filesystem

  • @molecule/app-i18n

  • @molecule/app-icons

  • @molecule/app-inline-style-dom

  • @molecule/app-overlay-dom

  • @molecule/app-pointer-events-dom

  • @molecule/app-ui

  • setClassMap() must run before any component renders — every component resolves its classes through getClassMap(), which THROWS until a ClassMap bond (e.g. @molecule/app-ui-tailwind) is set. Call it in main.ts before bootstrapApplication.

  • Components are standalone — add them to the imports array of the consuming component or route; there is no NgModule.

  • A component's selector names the native element React renders at its root (an attribute selector such as button[mol-button]), so the host IS the root element. A component whose React root is a fragment or a portal renders its template in the host's place and leaves the page itself, so no wrapper element stands among React's nodes.

  • Hooks (useToast, usePanelClose, useIsDesktop, useUserMenuPopoverClose) are called in an injection context (a component field initializer or constructor).

  • Every component whose React export forwards a ref implements HasElement: take it with a template variable (<div mol-input #email>) or viewChild, then read email.element(). That is the same element React's ref receives and is null while it is not rendered (a closed Tooltip, Dropdown or Modal).

  • The first-pass components remain exported under their Molecule* names (MoleculeButton, MoleculeInput, MoleculeModal, …) as deprecated, separate components: they do not render what the React-named ones above do.

Import WebDragDirective, WebHoverDirective, or WebWheelZoomDirective into a standalone component. Bind [molDrag] or [molWheelZoom] to the current handler, or add molHover and listen for (molHoverEnter) and (molHoverLeave).

Translations

Translation strings are provided by @molecule/app-locales-ui.