عرض البيانات
carousel
شرائح تتحرك أفقيًا مع نقاط تثبيت وأزرار أسهم.
<x-ui.carousel class="w-full max-w-xs">
@foreach (range(1, 5) as $i)
<x-ui.carousel.item>
<x-ui.card class="flex aspect-square items-center justify-center">
<span class="text-4xl font-semibold">{{ $i }}</span>
</x-ui.card>
</x-ui.carousel.item>
@endforeach
</x-ui.carousel>
التثبيت
php artisan ui:add carousel
1. ثبّت الاعتماديات
- composer:
gehrisandro/tailwind-merge-laravel
2.
انسخ كل ملف إلى
resources/views/components/ui/
resources/views/components/ui/carousel/index.blade.php
@props([
// false drops the two built-in arrow buttons so you can place your own
// in the controls slot. Any element inside the root carrying
// data-ui-carousel-prev or data-ui-carousel-next works as an arrow.
'arrows' => true,
// Extra classes for the scrolling track, merged over its defaults: a
// different gap, or padding plus matching scroll-padding for slides that
// peek past the container edges.
'track' => null,
])
@php
$classes = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'relative',
$attributes->get('class'),
);
$trackClasses = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',
$track,
);
$arrow =
'absolute top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center rounded-full border border-input bg-background shadow-xs outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 dark:bg-input/30 dark:hover:bg-input/50';
@endphp
{{-- Scroll-snap carries the whole interaction: swipe, trackpad, scrollbar
dragging and keyboard scrolling are the browser's, not ours. Script is
only needed for the arrow buttons and the optional dots, which have no
declarative equivalent. Strip the script and everything else still
works.
The default slot holds the slides only. Anything else (your own
arrows, dots, a caption) goes in the controls slot, which renders after
the track inside the same positioned root.
Dots: put an empty element with data-ui-carousel-dots in the controls
slot. The script fills it with one button per slide and marks the
current one with aria-current and data-active, so style it with
data-active: utilities. Its data-label attribute sets the accessible
name prefix (default "Go to slide"). --}}
<div data-ui-carousel
{{ $attributes->except('class')->merge(['class' => $classes]) }}>
<div data-ui-carousel-track class="{{ $trackClasses }}">
{{ $slot }}
</div>
{{ $controls ?? '' }}
@if ($arrows)
<button type="button" data-ui-carousel-prev aria-label="Previous slide"
class="{{ $arrow }} -start-4">
<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 rtl:rotate-180" aria-hidden="true">
<path d="m15 18-6-6 6-6" />
</svg>
</button>
<button type="button" data-ui-carousel-next aria-label="Next slide"
class="{{ $arrow }} -end-4">
<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 rtl:rotate-180" aria-hidden="true">
<path d="m9 18 6-6-6-6" />
</svg>
</button>
@endif
</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.__laralcnCarousel) return;
window.__laralcnCarousel = true;
// Every slide's start edge, as the scroll position that brings it
// to the start of the track. Positions are measured from the
// track's start edge. Under dir="rtl" that is the right edge and
// scrollLeft runs from 0 down to negative values, so both are
// mirrored into the same positive scale and flipped back for
// scrollTo. A padded track (with matching scroll-padding, so the
// slides peek past the edges) puts the first slide that far in at
// scroll 0, so every edge is taken relative to the first slide.
// The computed scroll-padding cannot be read instead: it comes
// back unresolved when it holds a percentage.
function measure(track) {
var rtl = getComputedStyle(track).direction === 'rtl';
var box = track.getBoundingClientRect();
var scrolled = Math.abs(track.scrollLeft);
var edges = Array.prototype.map.call(track.children, function(item) {
var rect = item.getBoundingClientRect();
return scrolled + (rtl ? box.right - rect.right : rect.left - box.left);
});
return {
rtl: rtl,
here: Math.round(scrolled),
edges: edges.map(function(edge) {
return Math.round(edge - edges[0]);
}),
};
}
function go(track, rtl, edge) {
track.scrollTo({
left: rtl ? -edge : edge,
behavior: 'smooth'
});
}
// Builds the dots on first use (and again if the slide count
// changed), then marks the slide nearest the start as current.
function sync(root) {
var dots = root.querySelector('[data-ui-carousel-dots]');
if (!dots) return;
var at = measure(root.querySelector('[data-ui-carousel-track]'));
var count = at.edges.length;
if (dots.children.length !== count) {
var label = dots.getAttribute('data-label') || 'Go to slide';
dots.textContent = '';
for (var i = 0; i < count; i++) {
var dot = document.createElement('button');
dot.type = 'button';
dot.setAttribute('data-ui-carousel-dot', i);
dot.setAttribute('aria-label', label + ' ' + (i + 1));
dot.className =
'relative size-2 shrink-0 rounded-full bg-muted-foreground/30 outline-none transition-colors after:absolute after:-inset-1 hover:bg-muted-foreground/60 focus-visible:ring-[3px] focus-visible:ring-ring/50 data-active:bg-foreground';
dots.appendChild(dot);
}
}
var active = 0;
at.edges.forEach(function(edge, i) {
if (Math.abs(edge - at.here) < Math.abs(at.edges[active] - at.here)) active = i;
});
Array.prototype.forEach.call(dots.children, function(dot, i) {
if (i === active) {
dot.setAttribute('aria-current', 'true');
dot.setAttribute('data-active', '');
} else {
dot.removeAttribute('aria-current');
dot.removeAttribute('data-active');
}
});
}
document.addEventListener('click', function(event) {
var dot = event.target.closest('[data-ui-carousel-dot]');
var button = dot || event.target.closest(
'[data-ui-carousel-prev], [data-ui-carousel-next]');
if (!button) return;
var root = button.closest('[data-ui-carousel]');
if (!root) return;
var track = root.querySelector('[data-ui-carousel-track]');
var at = measure(track);
if (dot) {
var edge = at.edges[Number(dot.getAttribute('data-ui-carousel-dot'))];
if (edge !== undefined) go(track, at.rtl, edge);
return;
}
// Scroll to the next item's own edge, not by one viewport
// width. Slides are separated by a gap, so a viewport-sized
// step drifts by that gap every press and scroll-snap
// eventually resolves the drift by skipping a slide. The 1px
// slack absorbs sub-pixel scroll positions, which would
// otherwise make the current slide look like a valid target.
var back = button.hasAttribute('data-ui-carousel-prev');
var target = back ?
at.edges.filter(function(edge) {
return edge < at.here - 1;
}).pop() :
at.edges.filter(function(edge) {
return edge > at.here + 1;
})[0];
// Already at the first or last slide.
if (target === undefined) return;
go(track, at.rtl, target);
});
// Scroll events do not bubble, so listen in the capture phase to
// keep one delegated listener for every carousel on the page.
function settled(event) {
var track = event.target;
if (track.nodeType !== 1 || !track.hasAttribute('data-ui-carousel-track')) return;
sync(track.closest('[data-ui-carousel]'));
}
if ('onscrollend' in window) {
document.addEventListener('scrollend', settled, true);
} else {
var timer;
document.addEventListener('scroll', function(event) {
clearTimeout(timer);
timer = setTimeout(function() {
settled(event);
}, 100);
}, true);
}
function start() {
document.querySelectorAll('[data-ui-carousel]').forEach(sync);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();
</script>
@endonce
resources/views/components/ui/carousel/item.blade.php
@props([])
@php
// basis-full shows one slide at a time. Override it through class for a
// multi-up carousel, e.g. class="basis-1/2 md:basis-1/3".
$classes = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'min-w-0 shrink-0 grow-0 basis-full snap-start',
$attributes->get('class'),
);
@endphp
<div role="group" aria-roledescription="slide"
{{ $attributes->except('class')->merge(['class' => $classes]) }}>
{{ $slot }}
</div>
الاستخدام
<x-ui.carousel class="w-full max-w-xs">
@foreach ($slides as $slide)
{{-- basis-full by default; use class="basis-1/2" for a multi-up row. --}}
<x-ui.carousel.item>
<x-ui.card>{{ $slide }}</x-ui.card>
</x-ui.carousel.item>
@endforeach
</x-ui.carousel>
يتولى CSS scroll-snap التمرير، ولا يشغّل وسم <script> المضمَّن إلا الأسهم والنقاط الاختيارية، ولا توجد اعتماديات JS. العناصر بعرض basis-full افتراضيًا، ويمكن تغييره عبر class لعرض عدة شرائح معًا. اضبط :arrows="false" لإخفاء الأسهم المدمجة، وضع أزرارك الخاصة التي تحمل data-ui-carousel-prev / data-ui-carousel-next داخل الفتحة controls التي تُعرض بعد المسار. أضف هناك عنصرًا فارغًا يحمل data-ui-carousel-dots لتظهر نقطة لكل شريحة، وتحصل النقطة الحالية على aria-current و data-active. تضيف الخاصية track أصنافًا إلى مسار التمرير (المسافة بين الشرائح، الحشوة، scroll-padding).
الخصائص
كل خاصية مع قيمتها الافتراضية. مرّر أيًّا منها كسمة، واستخدم : لربط قيمة PHP.
@props([
// false drops the two built-in arrow buttons so you can place your own
// in the controls slot. Any element inside the root carrying
// data-ui-carousel-prev or data-ui-carousel-next works as an arrow.
'arrows' => true,
// Extra classes for the scrolling track, merged over its defaults: a
// different gap, or padding plus matching scroll-padding for slides that
// peek past the container edges.
'track' => null,
])