التنبيهات
toast
قائمة إشعارات منبثقة: أطلق حدث toast على window أو استدعِ toast() لعرض إشعارات متراكمة بأنواع مختلفة وأزرار إجراءات وتحديث في مكانها.
<div class="flex flex-wrap items-center justify-center gap-2">
<x-ui.button variant="outline"
onclick="window.dispatchEvent(new CustomEvent('toast', { detail: { title: 'تم الحفظ', description: 'حُفظت تغييراتك.' } }))">
افتراضي
</x-ui.button>
<x-ui.button variant="outline" onclick="toast.success('حُدّث الملف الشخصي')">نجاح</x-ui.button>
<x-ui.button variant="outline"
onclick="toast.error('فشل الدفع', { description: 'رُفضت بطاقتك.' })">خطأ</x-ui.button>
<x-ui.button variant="outline"
onclick="toast.info('يتوفر إصدار جديد', { description: 'أعد تحميل الصفحة للتحديث.' })">معلومة</x-ui.button>
<x-ui.button variant="outline"
onclick="toast.warning('المساحة شبه ممتلئة', { duration: 0 })">تحذير (ثابت)</x-ui.button>
{{-- Loading, then the same id turns it into a success. --}}
<x-ui.button variant="outline"
onclick="const id = toast.loading('جارٍ رفع report.pdf'); setTimeout(() => toast.success('اكتمل الرفع', { id, description: 'الملف report.pdf جاهز.' }), 2000)">
وعد (Promise)
</x-ui.button>
{{-- The action fires a window event named 'undo-archive'. --}}
<x-ui.button variant="outline"
onclick="toast('أُرشفت الرسالة', { action: { label: 'تراجع', event: 'undo-archive' } })">
إجراء التراجع
</x-ui.button>
<script>
window.addEventListener('undo-archive', () => toast.info('استُعيدت الرسالة'));
</script>
<x-ui.toast position="bottom-left" label="الإشعارات" close-label="إغلاق" />
</div>
التثبيت
php artisan ui:add toast
1. ثبّت الاعتماديات
- composer:
gehrisandro/tailwind-merge-laravel
2.
انسخ الكود إلى
resources/views/components/ui/
resources/views/components/ui/toast.blade.php
@props([
'position' => 'bottom-right',
// How many toasts show at once; the rest wait their turn.
'max' => 3,
'label' => 'Notifications',
'closeLabel' => 'Close',
])
@php
$anchor = match ($position) {
'top-right' => 'top-4 right-4',
'top-left' => 'top-4 left-4',
'top-center' => 'top-4 inset-x-0 mx-auto',
'bottom-left' => 'bottom-4 left-4',
'bottom-center' => 'bottom-4 inset-x-0 mx-auto',
default => 'bottom-4 right-4',
};
$side = str_starts_with($position, 'top') ? 'top' : 'bottom';
$regionClasses = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'group/toasts fixed z-[100] w-[calc(100%-2rem)] max-w-sm transition-[height] duration-300',
$anchor,
$attributes->get('class'),
);
@endphp
<div data-ui-toast-region data-side="{{ $side }}" data-max="{{ $max }}"
data-expanded="false" role="region" aria-label="{{ $label }}"
aria-live="polite" class="{{ $regionClasses }}"
{{ $attributes->except('class') }}>
{{-- Cloned once per toast; edit the markup here to restyle them. --}}
<template data-ui-toast-template>
<div data-ui-toast role="status" data-state="entering"
data-variant="default" data-front="true"
class="group/toast pointer-events-auto absolute inset-x-0 {{ $side === 'top' ? 'top-0 origin-bottom' : 'bottom-0 origin-top' }} overflow-hidden rounded-lg border bg-background p-4 text-foreground opacity-0 shadow-lg transition-all duration-300 data-[state=visible]:opacity-100 data-[state=queued]:hidden data-[state=hidden]:pointer-events-none data-[variant=error]:border-destructive/50">
<div
class="flex items-start gap-3 transition-opacity duration-200 group-data-[expanded=false]/toasts:group-data-[front=false]/toast:opacity-0">
<svg data-ui-toast-icon="success" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="mt-0.5 hidden size-4 shrink-0 text-primary" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<path d="m9 12 2 2 4-4" />
</svg>
<svg data-ui-toast-icon="error" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="mt-0.5 hidden size-4 shrink-0 text-destructive" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<path d="m15 9-6 6" />
<path d="m9 9 6 6" />
</svg>
<svg data-ui-toast-icon="info" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="mt-0.5 hidden size-4 shrink-0 text-foreground" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<path d="M12 16v-4" />
<path d="M12 8h.01" />
</svg>
<svg data-ui-toast-icon="warning" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="mt-0.5 hidden size-4 shrink-0 text-foreground" aria-hidden="true">
<path
d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" />
<path d="M12 9v4" />
<path d="M12 17h.01" />
</svg>
<svg data-ui-toast-icon="loading" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="mt-0.5 hidden size-4 shrink-0 animate-spin text-muted-foreground"
aria-hidden="true">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
<div class="min-w-0 flex-1">
<p class="text-sm font-semibold group-data-[variant=error]/toast:text-destructive"
data-ui-toast-title></p>
<p class="hidden text-sm text-muted-foreground"
data-ui-toast-description></p>
</div>
<button type="button" data-ui-toast-action
hidden
class="inline-flex h-7 shrink-0 items-center rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground outline-none hover:bg-primary/90 focus-visible:ring-[3px] focus-visible:ring-ring/50"></button>
<a data-ui-toast-action
hidden
class="inline-flex h-7 shrink-0 items-center rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground outline-none hover:bg-primary/90 focus-visible:ring-[3px] focus-visible:ring-ring/50"></a>
<button type="button" aria-label="{{ $closeLabel }}"
data-ui-toast-close
class="shrink-0 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round" class="size-4"
aria-hidden="true">
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
</button>
</div>
</div>
</template>
</div>
@once
<script>
(function() {
// The Blade once-directive above keeps this to a single copy per
// page, except when a component is rendered into a slot that is
// echoed twice, the way the sidebar does for its desktop and its
// mobile panel. Then the markup ships twice and every click would
// fire the handler twice, so this flag is the real guard.
if (window.__laralcnToast) return;
window.__laralcnToast = true;
var GAP = 8; // px between toasts when the stack is expanded
var PEEK = 14; // px of each older toast showing when collapsed
var count = 0;
function regions() {
return document.querySelectorAll('[data-ui-toast-region]');
}
// Toasts that are on screen or waiting, oldest first.
function live(region) {
return Array.prototype.filter.call(region.querySelectorAll('[data-ui-toast]'), function(t) {
return t.dataset.state !== 'hidden';
});
}
function startTimer(t) {
clearTimeout(t._timer);
t._timer = null;
if (t._sticky || t.dataset.state !== 'visible' || t.parentNode.dataset.expanded === 'true') return;
t._started = Date.now();
t._timer = setTimeout(function() {
dismiss(t);
}, t._remaining);
}
function pauseTimer(t) {
if (!t._timer) return;
clearTimeout(t._timer);
t._timer = null;
t._remaining -= Date.now() - t._started;
}
// Places every toast: the newest `max` are shown, the rest queue.
// Collapsed, older toasts sit scaled behind the newest; expanded,
// they fan out in a column. Offsets need measured heights, so they
// go in inline styles.
function layout(region) {
var toasts = live(region).reverse();
var max = parseInt(region.dataset.max, 10) || 3;
var expanded = region.dataset.expanded === 'true';
var sign = region.dataset.side === 'top' ? 1 : -1;
var shown = toasts.slice(0, max);
toasts.slice(max).forEach(function(t) {
pauseTimer(t);
t.dataset.state = 'queued';
});
shown.forEach(function(t) {
if (t.dataset.state !== 'visible') {
// Slide in from the screen edge.
t.dataset.state = 'entering';
t.style.transform = 'translateY(' + (-sign * 100) + '%)';
}
t.style.height = '';
});
// Reading heights also flushes the start position above, so
// the move below animates (no requestAnimationFrame, which
// would stall in a background tab).
var heights = shown.map(function(t) {
return t.offsetHeight;
});
var offset = 0;
shown.forEach(function(t, i) {
var y = expanded ? offset : i * PEEK;
var scale = expanded ? 1 : 1 - i * 0.05;
t.style.transform = 'translateY(' + sign * y + 'px) scale(' + scale + ')';
t.style.zIndex = String(shown.length - i);
t.style.height = expanded || i === 0 ? '' : heights[0] + 'px';
t.dataset.front = i === 0 ? 'true' : 'false';
offset += heights[i] + GAP;
if (t.dataset.state === 'entering') {
t.dataset.state = 'visible';
startTimer(t);
}
});
region.style.height = !shown.length ? '' :
(expanded ? offset - GAP : heights[0] + (shown.length - 1) * PEEK) + 'px';
}
function dismiss(t) {
if (!t || t.dataset.state === 'hidden') return;
clearTimeout(t._timer);
t.dataset.state = 'hidden';
layout(t.parentNode);
setTimeout(function() {
t.remove();
}, 300);
}
function fill(t, detail) {
var variant = detail.variant || 'default';
var duration = detail.duration == null ? 4000 : Number(detail.duration);
t._detail = detail;
t._remaining = duration;
// 0 or Infinity means stay until dismissed; loading waits for an update.
t._sticky = variant === 'loading' || !(duration > 0) || duration === Infinity;
t.dataset.variant = variant;
t.setAttribute('role', variant === 'error' ? 'alert' : 'status');
t.querySelector('[data-ui-toast-title]').textContent = detail.title || '';
var description = t.querySelector('[data-ui-toast-description]');
description.textContent = detail.description || '';
description.classList.toggle('hidden', !detail.description);
t.querySelectorAll('[data-ui-toast-icon]').forEach(function(icon) {
icon.classList.toggle('hidden', icon.getAttribute('data-ui-toast-icon') !== variant);
});
var action = detail.action;
var button = t.querySelector('button[data-ui-toast-action]');
var link = t.querySelector('a[data-ui-toast-action]');
button.hidden = !action || !!action.href;
link.hidden = !action || !action.href;
if (action) {
(action.href ? link : button).textContent = action.label || '';
if (action.href) link.href = action.href;
}
}
function show(region, detail) {
var t = live(region).filter(function(x) {
return x.dataset.id === detail.id;
})[0];
if (!t) {
t = region.querySelector('[data-ui-toast-template]').content.firstElementChild.cloneNode(true);
t.dataset.id = detail.id;
region.appendChild(t);
}
clearTimeout(t._timer);
t._timer = null;
fill(t, detail);
layout(region);
// Same id again: restart the timer with the new duration.
startTimer(t);
}
function setExpanded(region, on) {
if ((region.dataset.expanded === 'true') === on) return;
region.dataset.expanded = on ? 'true' : 'false';
live(region).forEach(on ? pauseTimer : startTimer);
layout(region);
}
function regionOf(node) {
return node && node.closest ? node.closest('[data-ui-toast-region]') : null;
}
window.addEventListener('toast', function(event) {
var detail = Object.assign({}, event.detail || {});
detail.id = detail.id == null ? 'toast-' + (++count) : String(detail.id);
regions().forEach(function(region) {
show(region, detail);
});
});
// Hover or focus expands the stack and pauses every timer.
document.addEventListener('mouseover', function(event) {
var region = regionOf(event.target);
if (region) setExpanded(region, true);
});
document.addEventListener('focusin', function(event) {
var region = regionOf(event.target);
if (region) setExpanded(region, true);
});
document.addEventListener('mouseout', function(event) {
var region = regionOf(event.target);
if (region && !region.contains(event.relatedTarget) && !region.contains(document.activeElement)) {
setExpanded(region, false);
}
});
document.addEventListener('focusout', function(event) {
var region = regionOf(event.target);
if (region && !region.contains(event.relatedTarget) && !region.matches(':hover')) {
setExpanded(region, false);
}
});
document.addEventListener('click', function(event) {
var t = event.target.closest('[data-ui-toast]');
if (!t) return;
if (event.target.closest('[data-ui-toast-close]')) return dismiss(t);
if (event.target.closest('[data-ui-toast-action]')) {
var action = t._detail.action || {};
if (action.event) {
window.dispatchEvent(new CustomEvent(action.event, {
detail: t._detail
}));
}
dismiss(t);
}
});
// Sugar over the event: toast('Saved'), toast.success('Saved', { description }).
// Each returns the id, to update or dismiss that toast later.
function toast(title, options) {
var detail = Object.assign({
title: title
}, options || {});
if (detail.id == null) detail.id = 'toast-' + (++count);
window.dispatchEvent(new CustomEvent('toast', {
detail: detail
}));
return detail.id;
}
['success', 'error', 'info', 'warning', 'loading'].forEach(function(variant) {
toast[variant] = function(title, options) {
return toast(title, Object.assign({}, options, {
variant: variant
}));
};
});
// No id dismisses every toast.
toast.dismiss = function(id) {
regions().forEach(function(region) {
live(region).forEach(function(t) {
if (id == null || t.dataset.id === String(id)) dismiss(t);
});
});
};
window.toast = toast;
})();
</script>
@endonce
الاستخدام
{{-- One region per page, near </body>. position: bottom-right (default),
bottom-left, bottom-center, top-right, top-left or top-center.
max: how many show at once (default 3); the rest wait in a queue. --}}
<x-ui.toast position="top-center" :max="3" close-label="Close" />
{{-- Show one by dispatching the event. Every field but title is optional. --}}
<x-ui.button
onclick="window.dispatchEvent(new CustomEvent('toast', { detail: {
title: 'Saved',
description: 'Your changes have been saved.',
variant: 'success', // default | success | error | info | warning | loading
duration: 4000, // 0 or Infinity stays until dismissed
} }))">
Save
</x-ui.button>
<script>
// Same id updates the toast in place and restarts its timer.
window.dispatchEvent(new CustomEvent('toast', { detail: { id: 'export', title: 'Exporting…', variant: 'loading' } }));
fetch('/export').then(() => window.dispatchEvent(new CustomEvent('toast', {
detail: { id: 'export', title: 'Export ready', variant: 'success', action: { label: 'Download', href: '/exports/latest' } },
})));
// An action button fires a window event with the toast's detail, then closes it.
window.dispatchEvent(new CustomEvent('toast', { detail: {
title: 'Message archived', action: { label: 'Undo', event: 'undo-archive' },
} }));
window.addEventListener('undo-archive', (event) => restore(event.detail));
// Optional helpers do the same and return the id.
const id = toast.loading('Uploading…');
toast.success('Uploaded', { id });
toast.error('Upload failed', { description: 'Try again.' });
toast.dismiss(id); // no id dismisses all
</script>
{{-- From a controller: flash it, then dispatch it from the layout.
return back()->with('toast', ['title' => 'Saved', 'variant' => 'success']);
--}}
@if (session('toast'))
<script>
window.addEventListener('DOMContentLoaded', () => {
window.dispatchEvent(new CustomEvent('toast', { detail: @json(session('toast')) }));
});
</script>
@endif
ضع منطقة واحدة قرب </body>، فهي تحمل سكربتها المضمّن. اعرض إشعارًا عبر window.dispatchEvent(new CustomEvent('toast', { detail: { title, description, variant, duration, id, action } })) أو الدوال المساعدة مثل toast.success(title, options) التي تُرجع المعرّف. إعادة استخدام id تحدّث الإشعار نفسه (من التحميل إلى النجاح)، وduration: 0 يبقيه ظاهرًا، وaction: { label, event } يطلق حدثًا على window بهذا الاسم. الخصائص: position وmax وlabel وclose-label.
الخصائص
كل خاصية مع قيمتها الافتراضية. مرّر أيًّا منها كسمة، واستخدم : لربط قيمة PHP.
@props([
'position' => 'bottom-right',
// How many toasts show at once; the rest wait their turn.
'max' => 3,
'label' => 'Notifications',
'closeLabel' => 'Close',
])