Notifikasi singkat di pojok kanan bawah yang hilang sendiri, dipicu lewat fungsi toast() atau event.
<div class="flex flex-wrap items-center gap-3" x-data>
<x-markas.button x-on:click="$dispatch('markas-toast', { title: 'Changes saved', description: 'Your profile has been updated', variant: 'success', duration: 0 })">Show toast</x-markas.button>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Draft saved automatically' })">Temporary toast</x-markas.button>
</div>
<x-markas.toast />import { Button } from "@/components/markas/Button";
import { Toaster, toast } from "@/components/markas/Toast";
export default function ToastExample() {
return (
<>
<div className="flex flex-wrap items-center gap-3">
<Button
onClick={() =>
toast({
title: "Changes saved",
description: "Your profile has been updated",
variant: "success",
duration: 0,
})
}
>
Show toast
</Button>
<Button
variant="secondary"
onClick={() => toast({ title: "Draft saved automatically" })}
>
Temporary toast
</Button>
</div>
<Toaster />
</>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<Button
@click="
toast({
title: 'Changes saved',
description: 'Your profile has been updated',
variant: 'success',
duration: 0,
})
"
>
Show toast
</Button>
<Button
variant="secondary"
@click="toast({ title: 'Draft saved automatically' })"
>
Temporary toast
</Button>
</div>
<Toaster />
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Toaster, { toast } from "$lib/components/markas/Toast.svelte";
</script>
<div class="flex flex-wrap items-center gap-3">
<Button
onclick={() =>
toast({
title: "Changes saved",
description: "Your profile has been updated",
variant: "success",
duration: 0,
})}>Show toast</Button
>
<Button
variant="secondary"
onclick={() => toast({ title: "Draft saved automatically" })}
>Temporary toast</Button
>
</div>
<Toaster />---
import Button from "@/components/markas/Button.astro";
import Toaster from "@/components/markas/Toast.astro";
---
<div class="flex flex-wrap items-center gap-3">
<Button data-toast={JSON.stringify({ title: "Changes saved", description: "Your profile has been updated", variant: "success", duration: 0 })}>Show toast</Button>
<Button variant="secondary" data-toast={JSON.stringify({ title: "Draft saved automatically" })}>Temporary toast</Button>
</div>
<Toaster />
<script>
// Toaster listens for the markas-toast event on window.
document.addEventListener("click", (event) => {
const button = (event.target as Element).closest<HTMLElement>("[data-toast]");
if (!button) return;
window.dispatchEvent(
new CustomEvent("markas-toast", { detail: JSON.parse(button.dataset.toast!) }),
);
});
</script>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Toaster, toast } from "./markas/toast.component";
@Component({
selector: "markas-example",
imports: [Button, Toaster],
template: `
<div class="flex flex-wrap items-center gap-3">
<button
markas-button
(click)="
toast({
title: 'Changes saved',
description: 'Your profile has been updated',
variant: 'success',
duration: 0,
})
"
>
Show toast
</button>
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Draft saved automatically' })"
>
Temporary toast
</button>
</div>
<markas-toaster />
`,
})
export default class ToastExample {
protected readonly toast = toast;
}Contoh
Varian
<div class="flex flex-wrap items-center gap-3" x-data>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Link copied' })">Default</x-markas.button>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Invitation sent', variant: 'success' })">Success</x-markas.button>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Upload failed', variant: 'danger' })">Danger</x-markas.button>
</div>
<x-markas.toast />import { Button } from "@/components/markas/Button";
import { Toaster, toast } from "@/components/markas/Toast";
export default function Example() {
return (
<>
<div className="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
onClick={() => toast({ title: "Link copied" })}
>
Default
</Button>
<Button
variant="secondary"
onClick={() =>
toast({ title: "Invitation sent", variant: "success" })
}
>
Success
</Button>
<Button
variant="secondary"
onClick={() => toast({ title: "Upload failed", variant: "danger" })}
>
Danger
</Button>
</div>
<Toaster />
</>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" @click="toast({ title: 'Link copied' })"
>Default</Button
>
<Button
variant="secondary"
@click="toast({ title: 'Invitation sent', variant: 'success' })"
>Success</Button
>
<Button
variant="secondary"
@click="toast({ title: 'Upload failed', variant: 'danger' })"
>Danger</Button
>
</div>
<Toaster />
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Toaster, { toast } from "$lib/components/markas/Toast.svelte";
</script>
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" onclick={() => toast({ title: "Link copied" })}
>Default</Button
>
<Button
variant="secondary"
onclick={() => toast({ title: "Invitation sent", variant: "success" })}
>Success</Button
>
<Button
variant="secondary"
onclick={() => toast({ title: "Upload failed", variant: "danger" })}
>Danger</Button
>
</div>
<Toaster />---
import Button from "@/components/markas/Button.astro";
import Toaster from "@/components/markas/Toast.astro";
---
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" data-toast={JSON.stringify({ title: "Link copied" })}>Default</Button>
<Button variant="secondary" data-toast={JSON.stringify({ title: "Invitation sent", variant: "success" })}>Success</Button>
<Button variant="secondary" data-toast={JSON.stringify({ title: "Upload failed", variant: "danger" })}>Danger</Button>
</div>
<Toaster />
<script>
// Toaster listens for the markas-toast event on window.
document.addEventListener("click", (event) => {
const button = (event.target as Element).closest<HTMLElement>("[data-toast]");
if (!button) return;
window.dispatchEvent(
new CustomEvent("markas-toast", { detail: JSON.parse(button.dataset.toast!) }),
);
});
</script>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Toaster, toast } from "./markas/toast.component";
@Component({
selector: "markas-example",
imports: [Button, Toaster],
template: `
<div class="flex flex-wrap items-center gap-3">
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Link copied' })"
>
Default
</button>
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Invitation sent', variant: 'success' })"
>
Success
</button>
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Upload failed', variant: 'danger' })"
>
Danger
</button>
</div>
<markas-toaster />
`,
})
export default class ToastVariantsExample {
protected readonly toast = toast;
}Dengan deskripsi
<div class="flex flex-wrap items-center gap-3" x-data>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Settings updated' })">Title only</x-markas.button>
<x-markas.button x-on:click="$dispatch('markas-toast', { title: 'Payment failed', description: 'Your card was declined. Try another payment method.', variant: 'danger' })">With description</x-markas.button>
</div>
<x-markas.toast />import { Button } from "@/components/markas/Button";
import { Toaster, toast } from "@/components/markas/Toast";
export default function Example() {
return (
<>
<div className="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
onClick={() => toast({ title: "Settings updated" })}
>
Title only
</Button>
<Button
onClick={() =>
toast({
title: "Payment failed",
description:
"Your card was declined. Try another payment method.",
variant: "danger",
})
}
>
With description
</Button>
</div>
<Toaster />
</>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" @click="toast({ title: 'Settings updated' })"
>Title only</Button
>
<Button
@click="
toast({
title: 'Payment failed',
description: 'Your card was declined. Try another payment method.',
variant: 'danger',
})
"
>With description</Button
>
</div>
<Toaster />
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Toaster, { toast } from "$lib/components/markas/Toast.svelte";
</script>
<div class="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
onclick={() => toast({ title: "Settings updated" })}>Title only</Button
>
<Button
onclick={() =>
toast({
title: "Payment failed",
description: "Your card was declined. Try another payment method.",
variant: "danger",
})}>With description</Button
>
</div>
<Toaster />---
import Button from "@/components/markas/Button.astro";
import Toaster from "@/components/markas/Toast.astro";
---
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" data-toast={JSON.stringify({ title: "Settings updated" })}>Title only</Button>
<Button data-toast={JSON.stringify({ title: "Payment failed", description: "Your card was declined. Try another payment method.", variant: "danger" })}>With description</Button>
</div>
<Toaster />
<script>
// Toaster listens for the markas-toast event on window.
document.addEventListener("click", (event) => {
const button = (event.target as Element).closest<HTMLElement>("[data-toast]");
if (!button) return;
window.dispatchEvent(
new CustomEvent("markas-toast", { detail: JSON.parse(button.dataset.toast!) }),
);
});
</script>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Toaster, toast } from "./markas/toast.component";
@Component({
selector: "markas-example",
imports: [Button, Toaster],
template: `
<div class="flex flex-wrap items-center gap-3">
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Settings updated' })"
>
Title only
</button>
<button
markas-button
(click)="
toast({
title: 'Payment failed',
description: 'Your card was declined. Try another payment method.',
variant: 'danger',
})
"
>
With description
</button>
</div>
<markas-toaster />
`,
})
export default class ToastDescriptionExample {
protected readonly toast = toast;
}Durasi
<div class="flex flex-wrap items-center gap-3" x-data>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Message archived', duration: 3000 })">Short (3s)</x-markas.button>
<x-markas.button variant="secondary" x-on:click="$dispatch('markas-toast', { title: 'Report is ready', description: 'Download it from the exports page.' })">Default (5s)</x-markas.button>
<x-markas.button x-on:click="$dispatch('markas-toast', { title: 'New version available', description: 'Reload the page to update.', duration: 0 })">Stay open</x-markas.button>
</div>
<x-markas.toast />import { Button } from "@/components/markas/Button";
import { Toaster, toast } from "@/components/markas/Toast";
export default function Example() {
return (
<>
<div className="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
onClick={() => toast({ title: "Message archived", duration: 3000 })}
>
Short (3s)
</Button>
<Button
variant="secondary"
onClick={() =>
toast({
title: "Report is ready",
description: "Download it from the exports page.",
})
}
>
Default (5s)
</Button>
<Button
onClick={() =>
toast({
title: "New version available",
description: "Reload the page to update.",
duration: 0,
})
}
>
Stay open
</Button>
</div>
<Toaster />
</>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
@click="toast({ title: 'Message archived', duration: 3000 })"
>Short (3s)</Button
>
<Button
variant="secondary"
@click="
toast({
title: 'Report is ready',
description: 'Download it from the exports page.',
})
"
>Default (5s)</Button
>
<Button
@click="
toast({
title: 'New version available',
description: 'Reload the page to update.',
duration: 0,
})
"
>Stay open</Button
>
</div>
<Toaster />
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import Toaster, { toast } from "$lib/components/markas/Toast.svelte";
</script>
<div class="flex flex-wrap items-center gap-3">
<Button
variant="secondary"
onclick={() => toast({ title: "Message archived", duration: 3000 })}
>Short (3s)</Button
>
<Button
variant="secondary"
onclick={() =>
toast({
title: "Report is ready",
description: "Download it from the exports page.",
})}>Default (5s)</Button
>
<Button
onclick={() =>
toast({
title: "New version available",
description: "Reload the page to update.",
duration: 0,
})}>Stay open</Button
>
</div>
<Toaster />---
import Button from "@/components/markas/Button.astro";
import Toaster from "@/components/markas/Toast.astro";
---
<div class="flex flex-wrap items-center gap-3">
<Button variant="secondary" data-toast={JSON.stringify({ title: "Message archived", duration: 3000 })}>Short (3s)</Button>
<Button variant="secondary" data-toast={JSON.stringify({ title: "Report is ready", description: "Download it from the exports page." })}>Default (5s)</Button>
<Button data-toast={JSON.stringify({ title: "New version available", description: "Reload the page to update.", duration: 0 })}>Stay open</Button>
</div>
<Toaster />
<script>
// Toaster listens for the markas-toast event on window.
document.addEventListener("click", (event) => {
const button = (event.target as Element).closest<HTMLElement>("[data-toast]");
if (!button) return;
window.dispatchEvent(
new CustomEvent("markas-toast", { detail: JSON.parse(button.dataset.toast!) }),
);
});
</script>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Toaster, toast } from "./markas/toast.component";
@Component({
selector: "markas-example",
imports: [Button, Toaster],
template: `
<div class="flex flex-wrap items-center gap-3">
<button
markas-button
variant="secondary"
(click)="toast({ title: 'Message archived', duration: 3000 })"
>
Short (3s)
</button>
<button
markas-button
variant="secondary"
(click)="
toast({
title: 'Report is ready',
description: 'Download it from the exports page.',
})
"
>
Default (5s)
</button>
<button
markas-button
(click)="
toast({
title: 'New version available',
description: 'Reload the page to update.',
duration: 0,
})
"
>
Stay open
</button>
</div>
<markas-toaster />
`,
})
export default class ToastDurationExample {
protected readonly toast = toast;
}Instalasi
npx markasui@latest add toastpnpm dlx markasui@latest add toastyarn dlx markasui@latest add toastbunx --bun markasui@latest add toast- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
resources/views/components/markas/toast.blade.php.
resources/views/components/markas/toast.blade.php
@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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/Toast.tsx.
src/components/markas/Toast.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>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/Toast.vue.
src/components/markas/Toast.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/lib/components/markas/Toast.svelte.
src/lib/components/markas/Toast.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/Toast.astro.
src/components/markas/Toast.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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/app/markas/toast.component.ts.
src/app/markas/toast.component.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);
}
}Pemakaian
Pasang region sekali di layout, misalnya sebelum </body>:
<x-markas.toast
:initial="session('toast') ? [session('toast')] : []"
close-label="Tutup"
region-label="Notifikasi"
/>Picu toast dari Alpine atau JavaScript biasa:
<x-markas.button x-data x-on:click="$dispatch('markas-toast', { title: 'Perubahan disimpan', variant: 'success' })">Simpan</x-markas.button>window.dispatchEvent(
new CustomEvent("markas-toast", {
detail: { title: "Gagal mengirim", variant: "danger", duration: 0 },
}),
);Butuh Alpine.js. Livewire 3 dan 4 sudah membawa Alpine, jadi tidak perlu dipasang lagi.
Livewire
$this->dispatch('markas-toast', title: 'Saved', variant: 'success');Livewire 3 dan 4 memancarkan event browser di window, jadi toast bisa langsung dari action komponen. Pasang <x-markas.toast /> sekali di layout.
import { Toaster, toast } from "@/components/markas/Toast";
// Di layout
<Toaster closeLabel="Tutup" regionLabel="Notifikasi" />;
// Di mana saja
toast({
title: "Perubahan disimpan",
description: "Profil Anda sudah diperbarui.",
variant: "success",
});<script setup lang="ts">
import Toaster, { toast } from "@/components/markas/Toast.vue";
</script>
<template>
<Button @click="toast({ title: 'Perubahan disimpan', variant: 'success' })">
Simpan
</Button>
<Toaster close-label="Tutup" region-label="Notifikasi" />
</template><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 />---
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>Komponen Astro tidak bisa mengekspor fungsi ke halaman, jadi Toaster Astro mendengarkan event markas-toast yang sama dengan Blade. Prop initial menampilkan toast langsung.
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" });
}
}- Detail toast:
title,description,variant(default,success,danger), dandurationdalam milidetik (default 5000,0berarti tetap tampil sampai ditutup). - Timer berhenti saat toast di-hover atau berisi fokus.
toast()mengembalikan id. Di React dan Vue, panggildismissToast(id)untuk menutup dari kode.- Antrean toast disimpan di level modul, jadi cukup satu
Toasterper aplikasi. - Panggil
toast()hanya di browser, misalnya di event handler,useEffect(React), atauonMounted(Vue). Saat render di server (SSR)toast()tidak melakukan apa pun dan mengembalikan0. - Label region default dalam bahasa Inggris (“Notifications”) dan tombol tutup “Close”. Isi
regionLabeldengan “Notifikasi” dancloseLabeldengan “Tutup” (Blade:region-label,close-label) untuk situs berbahasa Indonesia.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
title | string | - | Judul toast. Opsi untuk toast() atau detail event markas-toast (Blade, Astro). |
description | string | - | Teks pendukung di bawah judul. |
variant | 'default' | 'success' | 'danger' | default | Warna border dan ikon. |
duration | number | 5000 | Milidetik sebelum toast hilang sendiri. 0 berarti tetap tampil sampai ditutup. |
initial | array | [] | Khusus Blade dan Astro: daftar toast yang langsung tampil, misalnya dari flash session. |
closeLabel | string | Close | Label aksesibel tombol tutup di setiap toast. Isi "Tutup" untuk situs berbahasa Indonesia. |
regionLabel | string | Notifications | Label aksesibel region live. Isi "Notifikasi" untuk situs berbahasa Indonesia. |
Aksesibilitas
- Region memakai role status dan aria-live polite, jadi toast baru dibacakan tanpa memindahkan fokus.
- Timer berhenti saat toast di-hover atau berisi fokus, lalu lanjut setelah keduanya lepas.
- Tombol tutup punya aria-label dari closeLabel (default Close) dan bisa dijangkau dengan Tab.
- Animasi masuk dimatikan saat prefers-reduced-motion.
Komponen terkait
Komponen feedback lain dengan class yang sama di setiap framework.
- AlertPesan penting di dalam halaman dengan varian info, success, warning, dan danger.
- BadgeLabel status kecil berbentuk pil dengan titik warna untuk neutral, primary, success, warning, dan danger.
- ProgressBilah kemajuan berbasis elemen progress native dengan label, persentase, dan mode tak tentu.
- SkeletonPlaceholder berdenyut untuk konten yang sedang dimuat, ukurannya diatur lewat class.