# Toast

Short notification in the bottom right corner that dismisses itself, triggered with the toast() function or an event.

- Category: Feedback
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/toast.json
- CLI: `npx markasui@latest add toast`

## When to use

Short feedback after a user action, such as data saved or failed to send.

- Mount only one Toaster in the main layout
- Do not put important actions only inside a toast
- Use duration 0 for errors that must be read before closing

## Code

### Blade

Save at `resources/views/components/markas/toast.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'initial' => [],
    'closeLabel' => 'Close',
    'regionLabel' => 'Notifications',
])

@php
    $region = 'pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2';
    $card = 'pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none';
    $variants = [
        'default' => 'border-line',
        'success' => 'border-success/40',
        'danger' => 'border-danger/40',
    ];
    $iconBase = 'mt-0.5 size-4 shrink-0';
    $iconVariants = [
        'default' => '',
        'success' => 'text-success',
        'danger' => 'text-danger',
    ];
    $icons = [
        'default' => '',
        'success' => 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5',
        'danger' => 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6',
    ];
    $content = 'grid flex-1 gap-1';
    $titleClass = 'font-semibold';
    $descriptionClass = 'text-muted';
    $close = '-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
@endphp

<div
    x-data="{
        toasts: [],
        timers: {},
        nextId: 0,
        variants: @js($variants),
        iconVariants: @js($iconVariants),
        icons: @js($icons),
        add(detail) {
            const variant = detail.variant in this.variants ? detail.variant : 'default';
            const duration = Number.isFinite(detail.duration) ? detail.duration : 5000;
            const id = ++this.nextId;
            this.toasts = [...this.toasts, { id, title: String(detail.title ?? ''), description: detail.description ?? '', variant }];
            if (duration > 0) this.start(id, duration);
        },
        start(id, ms) {
            this.timers[id] = { handle: setTimeout(() => this.dismiss(id), ms), remaining: ms, startedAt: Date.now() };
        },
        dismiss(id) {
            clearTimeout(this.timers[id]?.handle);
            delete this.timers[id];
            this.toasts = this.toasts.filter((item) => item.id !== id);
        },
        pause(id) {
            const timer = this.timers[id];
            if (!timer?.handle) return;
            clearTimeout(timer.handle);
            this.timers[id] = { remaining: timer.remaining - (Date.now() - timer.startedAt), startedAt: 0 };
        },
        resume(id) {
            const timer = this.timers[id];
            if (!timer || timer.handle) return;
            this.start(id, Math.max(timer.remaining, 0));
        },
    }"
    x-init="@js(array_values($initial)).forEach((detail) => add(detail))"
    x-on:markas-toast.window="add($event.detail ?? {})"
    {{ $attributes->merge(['role' => 'status', 'aria-live' => 'polite', 'aria-label' => $regionLabel])->class([$region]) }}
>
    <template x-for="item in toasts" :key="item.id">
        <div
            data-state="open"
            class="{{ $card }}"
            :class="variants[item.variant]"
            x-on:mouseenter="pause(item.id)"
            x-on:mouseleave="if (! $el.contains(document.activeElement)) resume(item.id)"
            x-on:focusin="pause(item.id)"
            x-on:focusout="if (! $el.contains($event.relatedTarget) && ! $el.matches(':hover')) resume(item.id)"
        >
            <template x-if="icons[item.variant]">
                <svg class="{{ $iconBase }}" :class="iconVariants[item.variant]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path :d="icons[item.variant]" /></svg>
            </template>
            <div class="{{ $content }}">
                <p class="{{ $titleClass }}" x-text="item.title"></p>
                <template x-if="item.description">
                    <p class="{{ $descriptionClass }}" x-text="item.description"></p>
                </template>
            </div>
            <button type="button" class="{{ $close }}" aria-label="{{ $closeLabel }}" x-on:click="dismiss(item.id)">
                <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" /></svg>
            </button>
        </div>
    </template>
</div>
```

Mount the region once in your layout, for example before `</body>`:

```blade
<x-markas.toast :initial="session('toast') ? [session('toast')] : []" />
```

Trigger a toast from Alpine or plain JavaScript:

```blade
<x-markas.button x-data x-on:click="$dispatch('markas-toast', { title: 'Changes saved', variant: 'success' })">Save</x-markas.button>
```

```js
window.dispatchEvent(
  new CustomEvent("markas-toast", {
    detail: { title: "Could not send", variant: "danger", duration: 0 },
  }),
);
```

Needs Alpine.js. Livewire 3 and 4 already ship it.

### Livewire

```php
$this->dispatch('markas-toast', title: 'Saved', variant: 'success');
```

Livewire 3 and 4 dispatch browser events on `window`, so a toast can come straight from a component action. Place `<x-markas.toast />` once in the layout.

### React

Save at `src/components/markas/Toast.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useSyncExternalStore,
  type ComponentProps,
  type FocusEvent,
  type MouseEvent,
} from "react";

const region =
  "pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2";
const card =
  "pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none";
const variants = {
  default: "border-line",
  success: "border-success/40",
  danger: "border-danger/40",
};
const iconBase = "mt-0.5 size-4 shrink-0";
const iconVariants = {
  default: "",
  success: "text-success",
  danger: "text-danger",
};
const icons = {
  default: "",
  success: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5",
  danger: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6",
};
const content = "grid flex-1 gap-1";
const titleClass = "font-semibold";
const descriptionClass = "text-muted";
const close =
  "-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const DEFAULT_DURATION = 5000;

export type ToastVariant = keyof typeof variants;
export type ToastOptions = {
  title: string;
  description?: string;
  variant?: ToastVariant;
  /** Milidetik sebelum toast hilang sendiri. 0 berarti tetap tampil. */
  duration?: number;
};
type ToastItem = Required<Omit<ToastOptions, "description">> & {
  id: number;
  description?: string;
};
type Timer = {
  handle?: ReturnType<typeof setTimeout>;
  remaining: number;
  startedAt: number;
};

// Store modul: satu antrean toast untuk seluruh aplikasi.
const EMPTY: ToastItem[] = [];
let toasts: ToastItem[] = EMPTY;
let nextId = 0;
const listeners = new Set<() => void>();
const timers = new Map<number, Timer>();

const emit = () => listeners.forEach((listener) => listener());
const subscribe = (listener: () => void) => {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
};

/** Di server (SSR) tidak ada antrean maupun timer, jadi semua fungsi toast tidak melakukan apa pun. */
const isServer = () => typeof window === "undefined";

function startTimer(id: number, ms: number) {
  timers.set(id, {
    handle: setTimeout(() => dismissToast(id), ms),
    remaining: ms,
    startedAt: Date.now(),
  });
}

export function dismissToast(id: number) {
  if (isServer()) return;
  clearTimeout(timers.get(id)?.handle);
  timers.delete(id);
  toasts = toasts.filter((item) => item.id !== id);
  emit();
}

export function pauseToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer?.handle) return;
  clearTimeout(timer.handle);
  timers.set(id, {
    remaining: timer.remaining - (Date.now() - timer.startedAt),
    startedAt: 0,
  });
}

export function resumeToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer || timer.handle) return;
  startTimer(id, Math.max(timer.remaining, 0));
}

/** Tampilkan toast dari mana saja. Mengembalikan id untuk dismissToast(), atau 0 di server. */
export function toast({
  title,
  description,
  variant = "default",
  duration = DEFAULT_DURATION,
}: ToastOptions): number {
  if (isServer()) return 0;
  const id = ++nextId;
  toasts = [...toasts, { id, title, description, variant, duration }];
  if (duration > 0) startTimer(id, duration);
  emit();
  return id;
}

export type ToasterProps = ComponentProps<"div"> & {
  /** Label aksesibel tombol tutup di setiap toast. */
  closeLabel?: string;
  /** Label aksesibel region live. */
  regionLabel?: string;
};

export function Toaster({
  closeLabel = "Close",
  regionLabel = "Notifications",
  className,
  ...props
}: ToasterProps) {
  const items = useSyncExternalStore(
    subscribe,
    () => toasts,
    () => EMPTY,
  );

  const handleMouseLeave = (id: number, event: MouseEvent<HTMLElement>) => {
    if (!event.currentTarget.contains(document.activeElement)) resumeToast(id);
  };
  const handleBlur = (id: number, event: FocusEvent<HTMLElement>) => {
    const target = event.currentTarget;
    if (target.contains(event.relatedTarget) || target.matches(":hover"))
      return;
    resumeToast(id);
  };

  return (
    <div
      role="status"
      aria-live="polite"
      aria-label={regionLabel}
      className={cx(region, className)}
      {...props}
    >
      {items.map((item) => (
        <div
          key={item.id}
          data-state="open"
          className={cx(card, variants[item.variant])}
          onMouseEnter={() => pauseToast(item.id)}
          onMouseLeave={(event) => handleMouseLeave(item.id, event)}
          onFocus={() => pauseToast(item.id)}
          onBlur={(event) => handleBlur(item.id, event)}
        >
          {icons[item.variant] && (
            <svg
              className={cx(iconBase, iconVariants[item.variant])}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <path d={icons[item.variant]} />
            </svg>
          )}
          <div className={content}>
            <p className={titleClass}>{item.title}</p>
            {item.description && (
              <p className={descriptionClass}>{item.description}</p>
            )}
          </div>
          <button
            type="button"
            className={close}
            aria-label={closeLabel}
            onClick={() => dismissToast(item.id)}
          >
            <svg
              className="size-4"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
      ))}
    </div>
  );
}
```

```tsx
import { Toaster, toast } from "@/components/markas/Toast";

// In the layout
<Toaster />;

// Anywhere
toast({
  title: "Changes saved",
  description: "Your profile has been updated",
  variant: "success",
});
```

### Vue

Save at `src/components/markas/Toast.vue`. No extra dependencies.

```vue
<script lang="ts">
import { shallowRef } from "vue";

const DEFAULT_DURATION = 5000;

export type ToastVariant = "default" | "success" | "danger";
export type ToastOptions = {
  title: string;
  description?: string;
  variant?: ToastVariant;
  /** Milidetik sebelum toast hilang sendiri. 0 berarti tetap tampil. */
  duration?: number;
};
type ToastItem = Required<Omit<ToastOptions, "description">> & {
  id: number;
  description?: string;
};
type Timer = {
  handle?: ReturnType<typeof setTimeout>;
  remaining: number;
  startedAt: number;
};

// Store modul: satu antrean toast untuk seluruh aplikasi.
const toasts = shallowRef<ToastItem[]>([]);
const timers = new Map<number, Timer>();
let nextId = 0;

/** Di server (SSR) tidak ada antrean maupun timer, jadi semua fungsi toast tidak melakukan apa pun. */
const isServer = () => typeof window === "undefined";

function startTimer(id: number, ms: number) {
  timers.set(id, {
    handle: setTimeout(() => dismissToast(id), ms),
    remaining: ms,
    startedAt: Date.now(),
  });
}

export function dismissToast(id: number) {
  if (isServer()) return;
  clearTimeout(timers.get(id)?.handle);
  timers.delete(id);
  toasts.value = toasts.value.filter((item) => item.id !== id);
}

export function pauseToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer?.handle) return;
  clearTimeout(timer.handle);
  timers.set(id, {
    remaining: timer.remaining - (Date.now() - timer.startedAt),
    startedAt: 0,
  });
}

export function resumeToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer || timer.handle) return;
  startTimer(id, Math.max(timer.remaining, 0));
}

/** Tampilkan toast dari mana saja. Mengembalikan id untuk dismissToast(), atau 0 di server. */
export function toast({
  title,
  description,
  variant = "default",
  duration = DEFAULT_DURATION,
}: ToastOptions): number {
  if (isServer()) return 0;
  const id = ++nextId;
  toasts.value = [
    ...toasts.value,
    { id, title, description, variant, duration },
  ];
  if (duration > 0) startTimer(id, duration);
  return id;
}
</script>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    closeLabel?: string;
    regionLabel?: string;
  }>(),
  { closeLabel: "Close", regionLabel: "Notifications" },
);

const region =
  "pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2";
const card =
  "pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none";
const variants = {
  default: "border-line",
  success: "border-success/40",
  danger: "border-danger/40",
};
const iconBase = "mt-0.5 size-4 shrink-0";
const iconVariants = {
  default: "",
  success: "text-success",
  danger: "text-danger",
};
const icons = {
  default: "",
  success: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5",
  danger: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6",
};
const content = "grid flex-1 gap-1";
const titleClass = "font-semibold";
const descriptionClass = "text-muted";
const close =
  "-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";

function onMouseLeave(id: number, event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  if (!target.contains(document.activeElement)) resumeToast(id);
}

function onFocusOut(id: number, event: FocusEvent) {
  const target = event.currentTarget as HTMLElement;
  if (target.contains(event.relatedTarget as Node | null)) return;
  if (target.matches(":hover")) return;
  resumeToast(id);
}
</script>

<template>
  <div
    role="status"
    aria-live="polite"
    :aria-label="props.regionLabel"
    :class="region"
  >
    <div
      v-for="item in toasts"
      :key="item.id"
      data-state="open"
      :class="[card, variants[item.variant]]"
      @mouseenter="pauseToast(item.id)"
      @mouseleave="onMouseLeave(item.id, $event)"
      @focusin="pauseToast(item.id)"
      @focusout="onFocusOut(item.id, $event)"
    >
      <svg
        v-if="icons[item.variant]"
        :class="[iconBase, iconVariants[item.variant]]"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path :d="icons[item.variant]" />
      </svg>
      <div :class="content">
        <p :class="titleClass">{{ item.title }}</p>
        <p v-if="item.description" :class="descriptionClass">
          {{ item.description }}
        </p>
      </div>
      <button
        type="button"
        :class="close"
        :aria-label="props.closeLabel"
        @click="dismissToast(item.id)"
      >
        <svg
          class="size-4"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M18 6 6 18M6 6l12 12" />
        </svg>
      </button>
    </div>
  </div>
</template>
```

```vue
<script setup lang="ts">
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>

<template>
  <Button @click="toast({ title: 'Changes saved', variant: 'success' })">
    Save
  </Button>
  <Toaster />
</template>
```

### Svelte

Save at `src/lib/components/markas/Toast.svelte`. No extra dependencies.

```svelte
<script module lang="ts">
  const DEFAULT_DURATION = 5000;

  export type ToastVariant = "default" | "success" | "danger";
  export type ToastOptions = {
    title: string;
    description?: string;
    variant?: ToastVariant;
    /** Milliseconds before the toast dismisses itself. 0 keeps it open. */
    duration?: number;
  };
  type ToastItem = Required<Omit<ToastOptions, "description">> & {
    id: number;
    description?: string;
  };
  type Timer = {
    handle?: ReturnType<typeof setTimeout>;
    remaining: number;
    startedAt: number;
  };

  // Module store: one toast queue for the whole app.
  let toasts = $state<ToastItem[]>([]);
  const timers = new Map<number, Timer>();
  let nextId = 0;

  /** On the server (SSR) there is no queue or timer, so every toast function does nothing. */
  const isServer = () => typeof window === "undefined";

  function startTimer(id: number, ms: number) {
    timers.set(id, {
      handle: setTimeout(() => dismissToast(id), ms),
      remaining: ms,
      startedAt: Date.now(),
    });
  }

  export function dismissToast(id: number) {
    if (isServer()) return;
    clearTimeout(timers.get(id)?.handle);
    timers.delete(id);
    toasts = toasts.filter((item) => item.id !== id);
  }

  export function pauseToast(id: number) {
    if (isServer()) return;
    const timer = timers.get(id);
    if (!timer?.handle) return;
    clearTimeout(timer.handle);
    timers.set(id, {
      remaining: timer.remaining - (Date.now() - timer.startedAt),
      startedAt: 0,
    });
  }

  export function resumeToast(id: number) {
    if (isServer()) return;
    const timer = timers.get(id);
    if (!timer || timer.handle) return;
    startTimer(id, Math.max(timer.remaining, 0));
  }

  /** Show a toast from anywhere. Returns an id for dismissToast(), or 0 on the server. */
  export function toast({
    title,
    description,
    variant = "default",
    duration = DEFAULT_DURATION,
  }: ToastOptions): number {
    if (isServer()) return 0;
    const id = ++nextId;
    toasts = [...toasts, { id, title, description, variant, duration }];
    if (duration > 0) startTimer(id, duration);
    return id;
  }
</script>

<script lang="ts">
  import type { HTMLAttributes } from "svelte/elements";

  const region =
    "pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2";
  const card =
    "pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none";
  const variants = {
    default: "border-line",
    success: "border-success/40",
    danger: "border-danger/40",
  };
  const iconBase = "mt-0.5 size-4 shrink-0";
  const iconVariants = {
    default: "",
    success: "text-success",
    danger: "text-danger",
  };
  const icons = {
    default: "",
    success: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5",
    danger: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6",
  };
  const content = "grid flex-1 gap-1";
  const titleClass = "font-semibold";
  const descriptionClass = "text-muted";
  const close =
    "-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Accessible label of the close button on each toast. */
    closeLabel?: string;
    /** Accessible label of the live region. */
    regionLabel?: string;
  };

  let {
    closeLabel = "Close",
    regionLabel = "Notifications",
    class: className,
    ...rest
  }: Props = $props();

  function handleMouseLeave(
    id: number,
    event: MouseEvent & { currentTarget: HTMLElement },
  ) {
    if (!event.currentTarget.contains(document.activeElement)) resumeToast(id);
  }

  function handleFocusOut(
    id: number,
    event: FocusEvent & { currentTarget: HTMLElement },
  ) {
    const target = event.currentTarget;
    if (target.contains(event.relatedTarget as Node | null)) return;
    if (target.matches(":hover")) return;
    resumeToast(id);
  }
</script>

<div
  role="status"
  aria-live="polite"
  aria-label={regionLabel}
  class={[region, className]}
  {...rest}
>
  {#each toasts as item (item.id)}
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div
      data-state="open"
      class={[card, variants[item.variant]]}
      onmouseenter={() => pauseToast(item.id)}
      onmouseleave={(event) => handleMouseLeave(item.id, event)}
      onfocusin={() => pauseToast(item.id)}
      onfocusout={(event) => handleFocusOut(item.id, event)}
    >
      {#if icons[item.variant]}
        <svg
          class={[iconBase, iconVariants[item.variant]]}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d={icons[item.variant]} />
        </svg>
      {/if}
      <div class={content}>
        <p class={titleClass}>{item.title}</p>
        {#if item.description}
          <p class={descriptionClass}>{item.description}</p>
        {/if}
      </div>
      <button
        type="button"
        class={close}
        aria-label={closeLabel}
        onclick={() => dismissToast(item.id)}
      >
        <svg
          class="size-4"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M18 6 6 18M6 6l12 12" />
        </svg>
      </button>
    </div>
  {/each}
</div>
```

```svelte
<script lang="ts">
  import Button from "$lib/components/markas/Button.svelte";
  import Toaster, { toast } from "$lib/components/markas/Toast.svelte";
</script>

<Button onclick={() => toast({ title: "Changes saved", variant: "success" })}>
  Save
</Button>
<Toaster />
```

### Astro

Save at `src/components/markas/Toast.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const region =
  "pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2";
const card =
  "pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none";
const variants = {
  default: "border-line",
  success: "border-success/40",
  danger: "border-danger/40",
};
const iconBase = "mt-0.5 size-4 shrink-0";
const iconVariants = {
  default: "",
  success: "text-success",
  danger: "text-danger",
};
const icons = {
  default: "",
  success: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5",
  danger: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6",
};
const content = "grid flex-1 gap-1";
const titleClass = "font-semibold";
const descriptionClass = "text-muted";
const close =
  "-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";

export type ToastOptions = {
  title: string;
  description?: string;
  variant?: keyof typeof variants;
  /** Milliseconds before the toast dismisses itself. 0 keeps it open. */
  duration?: number;
};

type Props = HTMLAttributes<"div"> & {
  /** Toasts shown right away, for example from a session flash. */
  initial?: ToastOptions[];
  /** Accessible label of the close button on each toast. */
  closeLabel?: string;
  /** Accessible label of the live region. */
  regionLabel?: string;
};

const {
  initial = [],
  closeLabel = "Close",
  regionLabel = "Notifications",
  class: className,
  ...rest
} = Astro.props;
const config = JSON.stringify({ variants, iconVariants, icons, initial });
---

<markas-toaster class="contents" data-config={config}>
  <div
    role="status"
    aria-live="polite"
    aria-label={regionLabel}
    class:list={[region, className]}
    {...rest}></div>
  <template>
    <div data-state="open" class={card}>
      <svg
        class={iconBase}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path></path>
      </svg>
      <div class={content}>
        <p class={titleClass}></p>
        <p class={descriptionClass}></p>
      </div>
      <button type="button" class={close} aria-label={closeLabel}>
        <svg
          class="size-4"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M18 6 6 18M6 6l12 12"></path>
        </svg>
      </button>
    </div>
  </template>
</markas-toaster>

<script>
  type Variant = "default" | "success" | "danger";
  type Detail = {
    title?: unknown;
    description?: unknown;
    variant?: unknown;
    duration?: unknown;
  };
  type Config = {
    variants: Record<Variant, string>;
    iconVariants: Record<Variant, string>;
    icons: Record<Variant, string>;
    initial: Detail[];
  };
  type Timer = {
    handle?: ReturnType<typeof setTimeout>;
    remaining: number;
    startedAt: number;
  };

  const DEFAULT_DURATION = 5000;

  /**
   * Listens for the markas-toast event on window, like the Blade version. One custom element
   * per Toaster, so markup added later and view transitions keep working.
   */
  class MarkasToaster extends HTMLElement {
    private timers = new Map<HTMLElement, Timer>();
    private readonly onToast = (event: Event) =>
      this.add((event as CustomEvent<Detail | null>).detail ?? {});

    connectedCallback() {
      const config = this.config();
      window.addEventListener("markas-toast", this.onToast);
      config.initial.forEach((detail) => this.add(detail));
    }

    disconnectedCallback() {
      window.removeEventListener("markas-toast", this.onToast);
      this.timers.forEach((timer) => clearTimeout(timer.handle));
      this.timers.clear();
    }

    private config(): Config {
      return JSON.parse(this.dataset.config ?? "{}") as Config;
    }

    private add(detail: Detail) {
      const config = this.config();
      const region = this.querySelector<HTMLElement>("[role=status]");
      const template = this.querySelector("template");
      if (!region || !template) return;
      const variant: Variant =
        typeof detail.variant === "string" && detail.variant in config.variants
          ? (detail.variant as Variant)
          : "default";
      const duration =
        typeof detail.duration === "number" && Number.isFinite(detail.duration)
          ? detail.duration
          : DEFAULT_DURATION;
      const item = (
        template.content.firstElementChild as HTMLElement
      ).cloneNode(true) as HTMLElement;
      item.classList.add(config.variants[variant]);

      const icon = item.querySelector("svg")!;
      if (config.icons[variant]) {
        icon.classList.add(config.iconVariants[variant]);
        icon.querySelector("path")!.setAttribute("d", config.icons[variant]);
      } else icon.remove();

      const [title, description] = item.querySelectorAll("p");
      title.textContent = String(detail.title ?? "");
      if (detail.description) description.textContent = String(detail.description);
      else description.remove();

      item
        .querySelector("button")!
        .addEventListener("click", () => this.dismiss(item));
      item.addEventListener("mouseenter", () => this.pause(item));
      item.addEventListener("mouseleave", () => {
        if (!item.contains(document.activeElement)) this.resume(item);
      });
      item.addEventListener("focusin", () => this.pause(item));
      item.addEventListener("focusout", (event) => {
        if (item.contains(event.relatedTarget as Node | null)) return;
        if (item.matches(":hover")) return;
        this.resume(item);
      });

      region.append(item);
      if (duration > 0) this.start(item, duration);
    }

    private start(item: HTMLElement, ms: number) {
      this.timers.set(item, {
        handle: setTimeout(() => this.dismiss(item), ms),
        remaining: ms,
        startedAt: Date.now(),
      });
    }

    private dismiss(item: HTMLElement) {
      clearTimeout(this.timers.get(item)?.handle);
      this.timers.delete(item);
      item.remove();
    }

    private pause(item: HTMLElement) {
      const timer = this.timers.get(item);
      if (!timer?.handle) return;
      clearTimeout(timer.handle);
      this.timers.set(item, {
        remaining: timer.remaining - (Date.now() - timer.startedAt),
        startedAt: 0,
      });
    }

    private resume(item: HTMLElement) {
      const timer = this.timers.get(item);
      if (!timer || timer.handle) return;
      this.start(item, Math.max(timer.remaining, 0));
    }
  }

  if (!customElements.get("markas-toaster"))
    customElements.define("markas-toaster", MarkasToaster);
</script>
```

```astro
---
import Toaster from "@/components/markas/Toast.astro";
---

<!-- In the layout -->
<Toaster />

<script>
  // Anywhere in the browser
  window.dispatchEvent(
    new CustomEvent("markas-toast", {
      detail: { title: "Changes saved", variant: "success" },
    }),
  );
</script>
```

An Astro component cannot export functions to the page, so the Astro Toaster listens for the same `markas-toast` event as Blade. The `initial` prop shows toasts right away.

### Angular

Save at `src/app/markas/toast.component.ts`. No extra dependencies.

```ts
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  computed,
  DestroyRef,
  inject,
  input,
  signal,
} from "@angular/core";

const region =
  "pointer-events-none fixed right-4 bottom-4 z-50 flex w-[calc(100%-2rem)] max-w-sm flex-col gap-2";
const card =
  "pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-4 text-sm text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none";
const variants = {
  default: "border-line",
  success: "border-success/40",
  danger: "border-danger/40",
};
const iconBase = "mt-0.5 size-4 shrink-0";
const iconVariants = {
  default: "",
  success: "text-success",
  danger: "text-danger",
};
const icons = {
  default: "",
  success: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM8.5 12l2.5 2.5 4.5-5",
  danger: "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM15 9l-6 6M9 9l6 6",
};
const content = "grid flex-1 gap-1";
const titleClass = "font-semibold";
const descriptionClass = "text-muted";
const close =
  "-mt-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";

const DEFAULT_DURATION = 5000;

export type ToastVariant = keyof typeof variants;
export type ToastOptions = {
  title: string;
  description?: string;
  variant?: ToastVariant;
  /** Milliseconds before the toast dismisses itself. 0 keeps it open. */
  duration?: number;
};
type ToastItem = Required<Omit<ToastOptions, "description">> & {
  id: number;
  description?: string;
};
type Timer = {
  handle?: ReturnType<typeof setTimeout>;
  remaining: number;
  startedAt: number;
};

// Module store: one toast queue for the whole app.
const toasts = signal<ToastItem[]>([]);
const timers = new Map<number, Timer>();
/** Mounted Toasters render right away, so a toast shows even when timers are paused or faked. */
const renderers = new Set<() => void>();
let nextId = 0;

const update = (change: (items: ToastItem[]) => ToastItem[]) => {
  toasts.update(change);
  renderers.forEach((render) => render());
};

/** On the server (SSR) there is no queue or timer, so every toast function does nothing. */
const isServer = () => typeof window === "undefined";

function startTimer(id: number, ms: number) {
  timers.set(id, {
    handle: setTimeout(() => dismissToast(id), ms),
    remaining: ms,
    startedAt: Date.now(),
  });
}

export function dismissToast(id: number) {
  if (isServer()) return;
  clearTimeout(timers.get(id)?.handle);
  timers.delete(id);
  update((items) => items.filter((item) => item.id !== id));
}

export function pauseToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer?.handle) return;
  clearTimeout(timer.handle);
  timers.set(id, {
    remaining: timer.remaining - (Date.now() - timer.startedAt),
    startedAt: 0,
  });
}

export function resumeToast(id: number) {
  if (isServer()) return;
  const timer = timers.get(id);
  if (!timer || timer.handle) return;
  startTimer(id, Math.max(timer.remaining, 0));
}

/** Show a toast from anywhere. Returns an id for dismissToast(), or 0 on the server. */
export function toast({
  title,
  description,
  variant = "default",
  duration = DEFAULT_DURATION,
}: ToastOptions): number {
  if (isServer()) return 0;
  const id = ++nextId;
  update((items) => [...items, { id, title, description, variant, duration }]);
  if (duration > 0) startTimer(id, duration);
  return id;
}

/**
 * Mount once in the app shell. Host stays out of layout (display: contents); the class moves to
 * the live region.
 */
@Component({
  selector: "markas-toaster",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `
    <div
      role="status"
      aria-live="polite"
      [attr.aria-label]="regionLabel()"
      [class]="regionClasses()"
    >
      @for (item of toasts(); track item.id) {
        <div
          data-state="open"
          [class]="cardClasses[item.variant]"
          (mouseenter)="pause(item.id)"
          (mouseleave)="onMouseLeave(item.id, $event)"
          (focusin)="pause(item.id)"
          (focusout)="onFocusOut(item.id, $event)"
        >
          @if (icons[item.variant]) {
            <svg
              [class]="iconClasses[item.variant]"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path [attr.d]="icons[item.variant]" />
            </svg>
          }
          <div [class]="content">
            <p [class]="titleClass">{{ item.title }}</p>
            @if (item.description) {
              <p [class]="descriptionClass">{{ item.description }}</p>
            }
          </div>
          <button
            type="button"
            [class]="close"
            [attr.aria-label]="closeLabel()"
            (click)="dismiss(item.id)"
          >
            <svg
              class="size-4"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
      }
    </div>
  `,
})
export class Toaster {
  /** Accessible label of the close button on each toast. */
  readonly closeLabel = input("Close");
  /** Accessible label of the live region. */
  readonly regionLabel = input("Notifications");
  readonly userClass = input("", { alias: "class" });

  protected readonly toasts = toasts.asReadonly();
  protected readonly icons = icons;
  protected readonly content = content;
  protected readonly titleClass = titleClass;
  protected readonly descriptionClass = descriptionClass;
  protected readonly close = close;
  protected readonly cardClasses = {
    default: `${card} ${variants.default}`,
    success: `${card} ${variants.success}`,
    danger: `${card} ${variants.danger}`,
  };
  protected readonly iconClasses = {
    default: `${iconBase} ${iconVariants.default}`,
    success: `${iconBase} ${iconVariants.success}`,
    danger: `${iconBase} ${iconVariants.danger}`,
  };
  protected readonly regionClasses = computed(() =>
    [region, this.userClass()].filter(Boolean).join(" "),
  );

  constructor() {
    const changes = inject(ChangeDetectorRef);
    const render = () => changes.detectChanges();
    renderers.add(render);
    inject(DestroyRef).onDestroy(() => renderers.delete(render));
  }

  protected pause(id: number) {
    pauseToast(id);
  }

  protected dismiss(id: number) {
    dismissToast(id);
  }

  protected onMouseLeave(id: number, event: MouseEvent) {
    const target = event.currentTarget as HTMLElement;
    if (!target.contains(document.activeElement)) resumeToast(id);
  }

  protected onFocusOut(id: number, event: FocusEvent) {
    const target = event.currentTarget as HTMLElement;
    if (target.contains(event.relatedTarget as Node | null)) return;
    if (target.matches(":hover")) return;
    resumeToast(id);
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Toaster, toast } from "./markas/toast.component";

@Component({
  selector: "app-root",
  imports: [Button, Toaster],
  template: `
    <button markas-button (click)="save()">Save</button>
    <markas-toaster />
  `,
})
export class App {
  save() {
    toast({ title: "Changes saved", variant: "success" });
  }
}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` | - | Toast title. Option for toast() or the markas-toast event detail (Blade, Astro). |
| `description` | `string` | - | Supporting text below the title. |
| `variant` | `'default' \| 'success' \| 'danger'` | default | Border and icon color. |
| `duration` | `number` | 5000 | Milliseconds before the toast dismisses itself. 0 keeps it until closed. |
| `initial` | `array` | [] | Blade and Astro only: toasts shown right away, for example from a session flash. |
| `closeLabel` | `string` | Close | Accessible label of each toast close button. |
| `regionLabel` | `string` | Notifications | Accessible label of the live region. |

## Accessibility

- The region uses role status and aria-live polite, so new toasts are announced without moving focus.
- The timer pauses while a toast is hovered or holds focus, and resumes once both are gone.
- The close button is labelled by closeLabel and reachable with Tab.
- The entry animation is turned off under prefers-reduced-motion.

## Notes

- Toast details: `title`, `description`, `variant` (`default`, `success`, `danger`), and `duration` in milliseconds (default 5000, `0` keeps it until closed).
- The timer pauses while a toast is hovered or holds focus.
- `toast()` returns an id. In React and Vue, call `dismissToast(id)` to close it from code.
- The toast queue lives at module level, so one `Toaster` per app is enough.
- Call `toast()` only in the browser, for example in an event handler, `useEffect` (React), or `onMounted` (Vue). During server rendering (SSR) `toast()` does nothing and returns `0`.
- The region is labelled "Notifications" and each close button "Close". Translate them with `regionLabel` and `closeLabel` (Blade: `region-label`, `close-label`).
