# Alert

Displays a callout for user attention.

Source: https://webjs.dev/ui/docs/components/alert

```ts
import { html } from '@webjsdev/core';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';
import { CheckCircle2Icon, InfoIcon } from '#lib/ui/lucide.ts';

export default function AlertDemo() {
  return html`
    <div class="grid w-full max-w-md items-start gap-4">
      <div data-slot="alert" role="alert" class=${alertClass()}>
        ${CheckCircle2Icon()}
        <div data-slot="alert-title" class=${alertTitleClass()}>Payment successful</div>
        <div data-slot="alert-description" class=${alertDescriptionClass()}>
          Your payment of $29.99 has been processed. A receipt has been sent to
          your email address.
        </div>
      </div>
      <div data-slot="alert" role="alert" class=${alertClass()}>
        ${InfoIcon()}
        <div data-slot="alert-title" class=${alertTitleClass()}>New feature available</div>
        <div data-slot="alert-description" class=${alertDescriptionClass()}>
          We've added dark mode support. You can enable it in your account
          settings.
        </div>
      </div>
    </div>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add alert
```

### Copy and paste the following code into your project.

````ts title="components/ui/alert.ts"
/**
 * Alert: informational banner. Tier-1 class helpers; compose with a
 * native `<div role="alert">` (or `role="status"` for non-urgent updates).
 *
 * shadcn parity:
 *   Alert (variant: default | destructive)  → alertClass({ variant })
 *   AlertTitle                              → alertTitleClass()
 *   AlertDescription                        → alertDescriptionClass()
 *   AlertAction                             → alertActionClass() with data-slot="alert-action"
 *                                             (a button or link in the alert's corner)
 *
 * A11y (required for accessible output): put role="alert" on the container
 * for an urgent, interrupting message, or role="status" for a polite,
 * non-urgent update. The class helper sets no role, so without one the
 * banner is silent to assistive tech.
 *
 * Design tokens used: --card, --card-foreground, --destructive, --muted-foreground.
 *
 * @example
 * ```html
 * <div role="alert" class=${alertClass()}>
 *   <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="10" /><path d="M12 16v-4M12 8h.01" /></svg>
 *   <div data-slot="alert-title" class=${alertTitleClass()}>Heads up</div>
 *   <div data-slot="alert-description" class=${alertDescriptionClass()}>
 *     Something happened. Probably fine.
 *   </div>
 * </div>
 *
 * <!-- Destructive variant: accent stripe plus colored title and description. -->
 * <div role="alert" class=${alertClass({ variant: 'destructive' })}>
 *   <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><path d="M12 9v4M12 17h.01" /></svg>
 *   <div data-slot="alert-title" class=${alertTitleClass()}>Failed</div>
 *   <div data-slot="alert-description" class=${alertDescriptionClass()}>
 *     Couldn't save your changes.
 *   </div>
 * </div>
 * ```
 */
import { cn } from '../lib/utils.ts';

const BASE =
  'grid grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current has-data-[slot=alert-action]:pe-18 group/alert relative w-full';

const VARIANTS = {
  default: 'bg-card text-card-foreground',
  destructive: 'bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current',
} as const;

export type AlertVariant = keyof typeof VARIANTS;

export function alertClass(opts: { variant?: AlertVariant } = {}): string {
  return cn(BASE, VARIANTS[opts.variant ?? 'default']);
}

export const alertTitleClass = (): string =>
  'col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight';

export const alertDescriptionClass = (): string =>
  'col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed';

/** The alert's action, in its corner. Set `data-slot="alert-action"`, which the alert reserves room for. */
export const alertActionClass = (): string =>
  'absolute top-2.5 end-3';
````

### Update the import paths to match your project setup.

## Usage

```ts
import {
  alertClass,
  alertTitleClass,
  alertDescriptionClass,
} from '#components/ui/alert.ts';
```

```ts
<div data-slot="alert" role="alert" class=${alertClass()}>
  ${InfoIcon()}
  <div data-slot="alert-title" class=${alertTitleClass()}>Heads up!</div>
  <div data-slot="alert-description" class=${alertDescriptionClass()}>
    You can add components and dependencies to your app using the cli.
  </div>
  <div data-slot="alert-action" class="absolute top-2 right-2">
    <button class=${buttonClass({ variant: 'outline' })}>Enable</button>
  </div>
</div>
```

## Composition

Use the following composition to build an alert:

```text
alertClass()
├── Icon
├── alertTitleClass()
├── alertDescriptionClass()
└── data-slot="alert-action"
```

## Basic

A basic alert with an icon, title and description.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';
import { CheckCircle2Icon } from '#lib/ui/lucide.ts';

export default function AlertBasic() {
  return html`
    <div data-slot="alert" role="alert" class=${cn(alertClass(), 'max-w-md')}>
      ${CheckCircle2Icon()}
      <div data-slot="alert-title" class=${alertTitleClass()}>Account updated successfully</div>
      <div data-slot="alert-description" class=${alertDescriptionClass()}>
        Your profile information has been saved. Changes will be reflected
        immediately.
      </div>
    </div>
  `;
}
```

## Destructive

Use `alertClass({ variant: 'destructive' })` to create a destructive alert.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';
import { AlertCircleIcon } from '#lib/ui/lucide.ts';

export default function AlertDestructive() {
  return html`
    <div data-slot="alert" role="alert" class=${cn(alertClass({ variant: 'destructive' }), 'max-w-md')}>
      ${AlertCircleIcon()}
      <div data-slot="alert-title" class=${alertTitleClass()}>Payment failed</div>
      <div data-slot="alert-description" class=${alertDescriptionClass()}>
        Your payment could not be processed. Please check your payment method
        and try again.
      </div>
    </div>
  `;
}
```

## Action

Add an element marked `data-slot="alert-action"` to hold a button or other action element. The alert reserves room for it on the inline end, and `absolute top-2 right-2` places it in the corner.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';

// The alert makes room for any child marked data-slot="alert-action"; the
// action itself is positioned in the top corner.
export default function AlertActionExample() {
  return html`
    <div data-slot="alert" role="alert" class=${cn(alertClass(), 'max-w-md')}>
      <div data-slot="alert-title" class=${alertTitleClass()}>Dark mode is now available</div>
      <div data-slot="alert-description" class=${alertDescriptionClass()}>
        Enable it under your profile settings to get started.
      </div>
      <div data-slot="alert-action" class="absolute top-2 right-2">
        <button type="button" data-slot="button" data-variant="default" data-size="xs" class=${buttonClass({ size: 'xs' })}>
          Enable
        </button>
      </div>
    </div>
  `;
}
```

## Custom Colors

You can customize the alert colors by adding custom classes such as `bg-amber-50 dark:bg-amber-950`, merged with `alertClass()` through `cn()`.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';
import { AlertTriangleIcon } from '#lib/ui/lucide.ts';

export default function AlertColors() {
  return html`
    <div data-slot="alert" role="alert" class=${cn(alertClass(), 'max-w-md border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-50')}>
      ${AlertTriangleIcon()}
      <div data-slot="alert-title" class=${alertTitleClass()}>Your subscription will expire in 3 days.</div>
      <div data-slot="alert-description" class=${alertDescriptionClass()}>
        Renew now to avoid service interruption or upgrade to a paid plan to
        continue using the service.
      </div>
    </div>
  `;
}
```

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl).

```ts
import { html } from '@webjsdev/core';
import { alertClass, alertTitleClass, alertDescriptionClass } from '#components/ui/alert.ts';
import { CheckCircle2Icon, InfoIcon } from '#lib/ui/lucide.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      paymentTitle: 'Payment successful',
      paymentDescription:
        'Your payment of $29.99 has been processed. A receipt has been sent to your email address.',
      featureTitle: 'New feature available',
      featureDescription:
        "We've added dark mode support. You can enable it in your account settings.",
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      paymentTitle: 'تم الدفع بنجاح',
      paymentDescription:
        'تمت معالجة دفعتك البالغة 29.99 دولارًا. تم إرسال إيصال إلى عنوان بريدك الإلكتروني.',
      featureTitle: 'ميزة جديدة متاحة',
      featureDescription:
        'لقد أضفنا دعم الوضع الداكن. يمكنك تفعيله في إعدادات حسابك.',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      paymentTitle: 'התשלום בוצע בהצלחה',
      paymentDescription:
        'התשלום שלך בסך 29.99 דולר עובד. קבלה נשלחה לכתובת האימייל שלך.',
      featureTitle: 'תכונה חדשה זמינה',
      featureDescription:
        'הוספנו תמיכה במצב כהה. אתה יכול להפעיל אותו בהגדרות החשבון שלך.',
    },
  },
};

const alerts = [
  { icon: CheckCircle2Icon, titleKey: 'paymentTitle', descriptionKey: 'paymentDescription' },
  { icon: InfoIcon, titleKey: 'featureTitle', descriptionKey: 'featureDescription' },
] as const;

export default function AlertRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div class="grid w-full max-w-md items-start gap-4" dir=${dir} lang=${lang}>
      ${alerts.map((alert) => html`
        <div data-slot="alert" role="alert" class=${alertClass()}>
          ${alert.icon()}
          <div data-slot="alert-title" class=${alertTitleClass()}>${t[alert.titleKey]}</div>
          <div data-slot="alert-description" class=${alertDescriptionClass()}>${t[alert.descriptionKey]}</div>
        </div>
      `)}
    </div>
  `;
}
```

## API Reference

An alert is a native `<div>` with the classes below. The helpers set no role, so put `role="alert"` on an urgent, interrupting message, or `role="status"` on a polite, non-urgent update.

### alertClass

`alertClass()` returns the classes for the alert container, which displays a callout for user attention.

| Option | Type | Default |
| --- | --- | --- |
| `variant` | `"default" \| "destructive"` | `"default"` |

### alertTitleClass

`alertTitleClass()` returns the classes for the title of the alert. It takes no options. Mark the element `data-slot="alert-title"`.

### alertDescriptionClass

`alertDescriptionClass()` returns the classes for the description or content of the alert. It takes no options. Mark the element `data-slot="alert-description"`.

### Alert action

An action element (like a button) positioned absolutely in the top-right corner of the alert. Mark the element `data-slot="alert-action"` and position it with `absolute top-2 right-2`.
