carousel
Carousel
Infinite-loop photo carousel powered by the
carousel() plugin — aligned with
Material Design 3. Items wrap seamlessly with smooth snap-to-item. Switch between
variant layouts to see hero, multi-browse,
uncontained, and full-screen modes.
Photo Carousel
0%
0.00 /
0.00
px/ms
0 /
0
items
variant full
step 1 / 24
Source
// Carousel — Shared data re-exported from curated carousel data
// Each variant uses unique photos with hand-written descriptions
export {
getItems,
getItemCount,
getItemWidth,
getImageUrl,
preloadImages,
} from "../../src/data/carousel.js";
// =============================================================================
// Photo load timeout
// =============================================================================
//
// A slide's picture comes from the self-hosted set, or from picsum when that file is missing. When the host accepts the
// connection and never answers, neither `load` nor `error` fires, so the
// once-only onerror swap the templates carry never runs and the slide stays
// blank. Watch each picture and swap a still-pending one for its committed
// SVG after PHOTO_TIMEOUT_MS; the swap discards the pending request.
//
// The photo-album example carries the same helper in its own shared.js — each
// example is meant to be read on its own. test/scripts/photo-load.test.ts runs
// one suite against both copies, so they cannot drift apart unnoticed.
export const PHOTO_TIMEOUT_MS = 4000;
const FALLBACK_ATTR = "data-photo-fallback";
const SVG_ATTR = "data-photo-svg";
// Pictures this module has armed, by element, so a recycled or removed picture
// is stopped instead of firing a swap at whatever it shows next.
const watched = new WeakMap();
/**
* Watch one picture: when it errors, or when it is still pending after
* `timeoutMs`, move it to the next URL in `fallbacks` — a single URL or a list,
* the chain a page keeps: the self-hosted file, then picsum, then the photo's
* committed SVG. Each step gets its own clock; reaching the end stops the watch.
* Returns a handle whose `stop()` clears the timer, the listeners and any
* IntersectionObserver.
*
* Safe to call again on a recycled element — the previous watch is stopped and
* the new picture gets its own clock.
*/
export function watchPhoto(img, fallbacks, timeoutMs = PHOTO_TIMEOUT_MS) {
watched.get(img)?.stop();
const steps = (Array.isArray(fallbacks) ? fallbacks : [fallbacks]).filter(
Boolean,
);
// An element is reused for the next picture (a pooled item, or a detail panel
// that keeps its <img>): a src that is none of the fallbacks means a new
// photo, so the marker from the picture before must not block its swap.
if (!steps.includes(img.getAttribute("src"))) delete img.dataset.fallback;
const state = { timer: null, observer: null, stopped: false, step: 0 };
function stop() {
if (state.stopped) return;
state.stopped = true;
if (state.timer !== null) clearTimeout(state.timer);
state.timer = null;
state.observer?.disconnect();
state.observer = null;
img.removeEventListener("load", onLoad);
img.removeEventListener("error", onError);
if (watched.get(img) === handle) watched.delete(img);
}
function advance() {
if (state.stopped) return;
// A step reached by an error is still inside the previous step's clock:
// clear it, so arm() gives the next source its own full timeout.
if (state.timer !== null) {
clearTimeout(state.timer);
state.timer = null;
}
if (!img.isConnected) {
// Recycled away from us: never swap whatever it shows now.
stop();
return;
}
const current = img.getAttribute("src");
while (state.step < steps.length && steps[state.step] === current) {
state.step++;
}
if (state.step >= steps.length) {
stop();
return;
}
img.dataset.fallback = "1";
// A template's inline onerror, where a page still carries one, must not
// race the step this watch takes.
img.onerror = null;
// srcset wins over src: while a candidate list is there, the browser keeps
// asking for the old box instead of the URL this step sets.
img.removeAttribute?.("srcset");
img.removeAttribute?.("sizes");
img.src = steps[state.step++];
// The next request is a new one: it gets its own clock.
arm();
}
function arm() {
if (state.stopped || state.timer !== null) return;
state.timer = setTimeout(() => {
state.timer = null;
advance();
}, timeoutMs);
}
function onLoad() {
stop();
}
function onError() {
advance();
}
const handle = { stop };
img.addEventListener("load", onLoad);
img.addEventListener("error", onError);
if (img.complete) {
// Settled before we got here: a cached picture needs no clock, a broken one
// (no pixels, its error already fired) moves on now.
if (img.naturalWidth === 0) advance();
else stop();
return handle;
}
if (img.loading === "lazy" && typeof IntersectionObserver === "function") {
// A lazy picture the browser has not asked for yet is not pending; timing
// it out now would flash the fallback on cards far below the fold. Start
// the clock when the picture comes near the viewport instead.
state.observer = new IntersectionObserver(
(entries) => {
if (!entries.some((entry) => entry.isIntersecting)) return;
state.observer?.disconnect();
state.observer = null;
arm();
},
{ rootMargin: "200px" },
);
state.observer.observe(img);
} else {
arm();
}
watched.set(img, handle);
return handle;
}
/**
* Arm every picture under `root` that carries data-photo-fallback, including
* the ones vlist renders later and the ones it recycles — a pooled item's
* innerHTML is replaced, so its old timer is stopped and its new picture armed.
* Returns a function that disconnects the observer and stops every watch.
*/
export function watchPhotosIn(root, timeoutMs = PHOTO_TIMEOUT_MS) {
if (!root) return () => {};
const armed = new Map();
function armImage(img) {
// A card names the chain in two attributes: picsum, then the SVG. An image
// already showing one of its fallbacks is either mid-chain (its own watch
// is running) or done — never re-armed over.
const steps = [
img.getAttribute(FALLBACK_ATTR),
img.getAttribute(SVG_ATTR),
].filter(Boolean);
if (steps.length === 0) return;
if (steps.includes(img.getAttribute("src"))) return;
armed.get(img)?.stop();
armed.delete(img);
armed.set(img, watchPhoto(img, steps, timeoutMs));
}
function stopImage(img) {
armed.get(img)?.stop();
armed.delete(img);
}
function scan(node) {
if (!node || node.nodeType !== 1) return;
if (node.matches(`img[${FALLBACK_ATTR}]`)) armImage(node);
for (const img of node.querySelectorAll(`img[${FALLBACK_ATTR}]`)) {
armImage(img);
}
}
const observer = new MutationObserver((records) => {
for (const record of records) {
if (record.type === "attributes") {
armImage(record.target);
continue;
}
for (const node of record.addedNodes) scan(node);
for (const node of record.removedNodes) {
if (node.nodeType !== 1) continue;
if (node.matches?.(`img[${FALLBACK_ATTR}]`)) stopImage(node);
for (const img of node.querySelectorAll?.(`img[${FALLBACK_ATTR}]`) ??
[]) {
stopImage(img);
}
}
}
});
observer.observe(root, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["src"],
});
// The container can already hold pictures when this is called: a framework
// variant creates its list in an effect that runs before its own watch, so
// the initial cards are armed here, not only the ones the observer sees.
scan(root);
return () => {
observer.disconnect();
for (const handle of armed.values()) handle.stop();
armed.clear();
};
}
/* Carousel Example — MD3-aligned photo carousel
Common styles (.container, h1, .description, .split-*, .ui-*)
are provided by styles/ui.css and examples/styles.css using design tokens. */
/* ============================================================================
Carousel wrap — container for list + nav + dots
============================================================================ */
.carousel-wrap {
position: relative;
width: 100%;
}
.carousel-wrap--vertical {
width: 300px;
height: 522px;
margin: 0 auto;
}
/* ============================================================================
List container
============================================================================ */
.split-main {
display: flex;
align-items: center;
justify-content: center;
min-height: 520px;
padding: 32px;
}
#list-container {
width: 100%;
height: 360px;
overflow: hidden;
border-radius: 28px;
}
.carousel-wrap--vertical #list-container {
height: 522px;
}
#list-container .vlist {
border: none !important;
border-radius: 28px !important;
background: transparent;
width: 100%;
}
#list-container .vlist-viewport {
width: 100% !important;
}
#list-container .vlist-item {
padding: 0 !important;
border: none !important;
background: transparent;
}
/* ============================================================================
Photo slide — adapts to --vlist-carousel-width
============================================================================ */
.photo-slide {
--vlist-carousel-radius: 28px;
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
border-radius: 28px;
background: var(--surface-container);
}
.photo-slide__img {
opacity: 0;
transition: opacity 0.4s ease;
}
.photo-slide__img--loaded {
opacity: 1;
}
.photo-slide__overlay {
padding: 32px 24px 24px;
background: linear-gradient(
0deg,
rgba(0, 0, 0, 0.7) 0%,
rgba(0, 0, 0, 0.3) 60%,
transparent 100%
);
display: flex;
flex-direction: column;
gap: 4px;
transition: opacity 0.15s ease;
}
.photo-slide__title {
font-size: 20px;
font-weight: var(--fw-bold, 700);
color: #fff;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
}
.photo-slide__location {
font-size: 14px;
color: rgba(255, 255, 255, 0.8);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
/* ============================================================================
Navigation arrows
============================================================================ */
.carousel-nav {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 10;
width: 48px;
height: 48px;
border-radius: 50%;
border: none;
background: rgba(0, 0, 0, 0.45);
color: #fff;
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
transition:
background 0.2s,
opacity 0.2s,
transform 0.15s;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
opacity: 0;
}
.carousel-wrap:hover .carousel-nav {
opacity: 1;
}
.carousel-nav:hover {
background: rgba(0, 0, 0, 0.65);
transform: translateY(-50%) scale(1.08);
}
.carousel-nav:active {
transform: translateY(-50%) scale(0.95);
}
.carousel-nav--prev {
left: 16px;
}
.carousel-nav--next {
right: 16px;
}
.carousel-wrap--vertical .carousel-nav {
display: none;
}
/* ============================================================================
Dot indicators
============================================================================ */
.carousel-dots {
display: flex;
justify-content: center;
gap: 8px;
padding: 16px 0 4px;
flex-wrap: wrap;
cursor: pointer;
}
.carousel-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--text-muted, #666);
opacity: 0.4;
pointer-events: none;
transition:
opacity 0.2s,
transform 0.2s,
background 0.2s;
}
.carousel-dot:hover {
opacity: 0.7;
transform: scale(1.3);
}
.carousel-dot--active {
opacity: 1;
background: var(--accent, #667eea);
transform: scale(1.3);
}
.carousel-wrap--vertical .carousel-dots {
flex-direction: column;
position: absolute;
right: -24px;
top: 50%;
transform: translateY(-50%);
padding: 0;
}
/* ============================================================================
Photo detail (panel)
============================================================================ */
.photo-detail {
display: flex;
flex-direction: column;
gap: 8px;
}
.photo-detail__frame {
padding: 16px;
border-radius: 16px;
background: var(--surface-container, #e8e8f0);
}
.photo-detail__img {
width: 100%;
aspect-ratio: 1;
object-fit: contain;
border-radius: 12px;
}
.photo-detail__meta {
display: flex;
flex-direction: column;
gap: 2px;
}
.photo-detail__meta strong {
font-weight: var(--fw-bold, 700);
font-size: 14px;
}
.photo-detail__meta span {
font-size: 12px;
color: var(--text-muted, #888);
}
/* "Photo by <author> on Unsplash" — the detail panels' credit line */
.photo-credit {
font-size: 11px;
color: var(--text-muted, #888);
text-decoration: none;
}
.photo-credit:hover {
text-decoration: underline;
}
/* ============================================================================
Variant button group wrap
============================================================================ */
.ui-btn-group--wrap {
flex-wrap: wrap;
}