/ Examples
gridmasonryselectiongroupsscrollbarsnapshots
Source
// Photo Album — Vue variant
// Builds the list with core createVList, the layout passed as a plugin: a
// layout change remounts the list, which plugins read once at mount require
// Layout mode toggle: Grid ↔ Masonry

import {
  createApp,
  ref,
  computed,
  watch,
  nextTick,
  onMounted,
  onUnmounted,
} from "vue";
import { createVList, grid, masonry, scrollbar } from "vlist";
import {
  ITEM_COUNT,
  ASPECT_RATIO,
  items,
  itemTemplate,
  watchPhoto,
  watchPhotosIn,
} from "../shared.js";
import { createStats } from "../../stats.js";
import {
  photoUrl,
  photoSrcSet,
  photoPicsumUrl,
  photoCredit,
} from "../../../src/data/photos.js";
import { createInfoUpdater } from "../../info.js";

// =============================================================================
// Item config helpers
// =============================================================================

function getItemConfig(mode, orientation) {
  if (mode === "masonry") {
    return {
      height: (_index, ctx) =>
        ctx ? Math.round(ctx.columnWidth * items[_index].aspectRatio) : 200,
      width:
        orientation === "horizontal"
          ? (_index, ctx) =>
              ctx
                ? Math.round(ctx.columnWidth * items[_index].aspectRatio)
                : 200
          : undefined,
      template: itemTemplate,
    };
  }

  // Grid — horizontal needs fixed cross-axis height
  if (orientation === "horizontal") {
    return {
      height: 200,
      width: (_index, ctx) =>
        ctx ? Math.round(ctx.columnWidth * (4 / 3)) : 200,
      template: itemTemplate,
    };
  }

  return {
    height: (_index, ctx) =>
      ctx ? Math.round(ctx.columnWidth * ASPECT_RATIO) : 200,
    template: itemTemplate,
  };
}

// =============================================================================
// Stats (module-level)
// =============================================================================

let statsInstance = null;
let infoUpdater = null;

// =============================================================================
// App
// =============================================================================

const App = {
  setup() {
    const mode = ref("grid");
    const orientation = ref("vertical");
    const columns = ref(4);
    const gap = ref(8);
    const selectedPhoto = ref(null);

    // Computed layout config
    const vlistConfig = computed(() => {
      const m = mode.value;
      const o = orientation.value;
      const c = columns.value;
      const g = gap.value;

      const layoutConfig =
        m === "masonry"
          ? { layout: "masonry", masonry: { columns: c, gap: g } }
          : { layout: "grid", grid: { columns: c, gap: g } };

      return {
        ariaLabel: "Photo gallery",
        orientation: o,
        ...layoutConfig,
        item: getItemConfig(m, o),
        items,
        scroll: {
          scrollbar: { autoHide: true },
        },
      };
    });

    const containerRef = ref(null);
    const instance = ref(null);
    const detailImgRef = ref(null);
    let detailWatch = null;
    let stopWatchingCards = null;

    // Manual lifecycle: plugins are read once at mount, so a layout change
    // destroys the list and builds a new one
    let cleanup = null;

    function mount() {
      if (!containerRef.value) return;

      const config = vlistConfig.value;

      const plugins = [];
      if (config.layout === "grid" && config.grid) {
        plugins.push(grid(config.grid));
      }
      if (config.layout === "masonry" && config.masonry) {
        plugins.push(masonry(config.masonry));
      }
      plugins.push(scrollbar({ autoHide: true }));

      const inst = createVList({
        ...config,
        container: containerRef.value,
      }, plugins);
      instance.value = inst;

      // Stats
      if (!statsInstance) {
        statsInstance = createStats({
          getScrollPosition: () => instance.value?.getScrollPosition() ?? 0,
          getTotal: () => ITEM_COUNT,
          getItemSize: () => {
            const el = containerRef.value;
            if (!el) return 200;
            const innerWidth = el.clientWidth - 2;
            const colW =
              (innerWidth - (columns.value - 1) * gap.value) /
              columns.value;
            return mode.value === "masonry"
              ? Math.round(colW * 1.05)
              : Math.round(colW * ASPECT_RATIO);
          },
          getColumns: () => columns.value,
          getContainerSize: () => {
            const el = containerRef.value;
            if (!el) return 0;
            return orientation.value === "horizontal"
              ? el.clientWidth
              : el.clientHeight;
          },
        });
      }

      if (!infoUpdater) {
        infoUpdater = createInfoUpdater(statsInstance);
      }

      // Events
      inst.on("scroll", () => infoUpdater());
      inst.on("range:change", () => infoUpdater());
      inst.on("velocity:change", ({ velocity }) => {
        statsInstance.onVelocity(velocity);
        infoUpdater();
      });
      inst.on("item:click", ({ item }) => {
        selectedPhoto.value = item;
      });

      infoUpdater();
      updateInfoContext();
    }

    function unmount() {
      if (instance.value) {
        instance.value.destroy();
        instance.value = null;
      }
      if (containerRef.value) {
        containerRef.value.innerHTML = "";
      }
    }

    function updateInfoContext() {
      const infoMode = document.getElementById("info-mode");
      const infoOrientation = document.getElementById("info-orientation");
      if (infoMode) infoMode.textContent = mode.value;
      if (infoOrientation) infoOrientation.textContent = orientation.value;
    }

    // Recreate on config change
    watch([mode, orientation, columns, gap], () => {
      unmount();
      mount();
    });

    // Arm the load timeout for the card pictures. The container outlives the
    // list instance this component mounts into it, so one watch covers both.
    onMounted(() => {
      mount();
      if (containerRef.value) {
        stopWatchingCards = watchPhotosIn(containerRef.value);
      }
    });
    onUnmounted(() => {
      stopWatchingCards?.();
      stopWatchingCards = null;
      detailWatch?.stop();
      unmount();
    });

    // The detail panel is outside the list container: Vue renders its picture
    // after selectedPhoto changes, so arm the one on screen each time.
    watch(selectedPhoto, async () => {
      detailWatch?.stop();
      detailWatch = null;
      await nextTick();
      const img = detailImgRef.value;
      if (!img || !selectedPhoto.value) return;
      detailWatch = watchPhoto(img, [
        photoPicsumUrl(selectedPhoto.value.picId, 400, 300),
        `/examples/photo-album/images/${selectedPhoto.value.picId}.svg`,
      ]);
    });

    // Navigation
    const scrollToFirst = () => instance.value?.scrollToIndex(0, "start");
    const scrollToMiddle = () =>
      instance.value?.scrollToIndex(Math.floor(ITEM_COUNT / 2), "center");
    const scrollToLast = () =>
      instance.value?.scrollToIndex(ITEM_COUNT - 1, "end");

    return {
      mode,
      orientation,
      columns,
      gap,
      selectedPhoto,
      containerRef,
      detailImgRef,
      photoUrl,
      photoSrcSet,
      scrollToFirst,
      scrollToMiddle,
      scrollToLast,
      photoCredit,
      ITEM_COUNT,
    };
  },

  template: `
    <div class="container">
      <header>
        <h1>Photo Album</h1>
        <p class="description">
          Virtualized 2D photo gallery with real images from Lorem Picsum.
          Toggle between grid and masonry layouts, adjust columns and gap —
          only visible rows are rendered.
        </p>
      </header>

      <div class="split-layout">
        <div class="split-main split-main--full">
          <h2 class="sr-only">Photos</h2>
          <div ref="containerRef" id="list-container"></div>
        </div>

        <aside class="split-panel">
          <!-- Layout -->
          <section class="ui-section">
            <h3 class="ui-title">Layout</h3>

            <div class="ui-row">
              <label class="ui-label">Mode</label>
              <div class="ui-segmented">
                <button
                  v-for="m in ['grid', 'masonry']"
                  :key="m"
                  :class="['ui-segmented__btn', { 'ui-segmented__btn--active': m === mode }]"
                  @click="mode = m"
                >
                  {{ m === 'grid' ? 'Grid' : 'Masonry' }}
                </button>
              </div>
            </div>

            <div class="ui-row">
              <label class="ui-label">Orientation</label>
              <div class="ui-segmented">
                <button
                  v-for="o in ['vertical', 'horizontal']"
                  :key="o"
                  :class="['ui-segmented__btn', { 'ui-segmented__btn--active': o === orientation }]"
                  @click="orientation = o"
                >
                  {{ o === 'vertical' ? 'Vertical' : 'Horizontal' }}
                </button>
              </div>
            </div>

            <div class="ui-row">
              <label class="ui-label">{{ orientation === 'horizontal' ? 'Rows' : 'Columns' }}</label>
              <div class="ui-btn-group">
                <button
                  v-for="c in [3, 4, 5, 6, 10]"
                  :key="c"
                  :class="['ui-ctrl-btn', { 'ui-ctrl-btn--active': c === columns }]"
                  @click="columns = c"
                >
                  {{ c }}
                </button>
              </div>
            </div>

            <div class="ui-row">
              <label class="ui-label">Gap</label>
              <div class="ui-btn-group">
                <button
                  v-for="g in [0, 4, 8, 12, 16]"
                  :key="g"
                  :class="['ui-ctrl-btn', { 'ui-ctrl-btn--active': g === gap }]"
                  @click="gap = g"
                >
                  {{ g }}
                </button>
              </div>
            </div>
          </section>

          <!-- Navigation -->
          <section class="ui-section">
            <h3 class="ui-title">Navigation</h3>
            <div class="ui-row">
              <div class="ui-btn-group">
                <button class="ui-btn ui-btn--icon" title="First" @click="scrollToFirst">
                  <i class="icon icon--up"></i>
                </button>
                <button class="ui-btn ui-btn--icon" title="Middle" @click="scrollToMiddle">
                  <i class="icon icon--center"></i>
                </button>
                <button class="ui-btn ui-btn--icon" title="Last" @click="scrollToLast">
                  <i class="icon icon--down"></i>
                </button>
              </div>
            </div>
          </section>

          <!-- Photo Detail -->
          <section class="ui-section">
            <h3 class="ui-title">Last clicked</h3>
            <div class="ui-detail">
              <template v-if="selectedPhoto">
                <img
                  ref="detailImgRef"
                  class="detail__img"
                  :src="photoUrl(selectedPhoto.picId, 400, 300)"
                  :srcset="photoSrcSet(selectedPhoto.picId, 400, 300)"
                  :alt="selectedPhoto.title"
                />
                <div class="detail__meta">
                  <strong>{{ selectedPhoto.title }}</strong>
                  <span>{{ selectedPhoto.category }} · ♥ {{ selectedPhoto.likes }}</span>
                  <a
                    v-if="photoCredit(selectedPhoto.picId)"
                    class="photo-credit"
                    :href="photoCredit(selectedPhoto.picId).url"
                    target="_blank"
                    rel="noopener"
                  >Photo by {{ photoCredit(selectedPhoto.picId).author }} on Unsplash</a>
                </div>
              </template>
              <span v-else class="ui-detail__empty">Click a photo to see details</span>
            </div>
          </section>
        </aside>
      </div>

      <div class="example-info" id="example-info">
        <div class="example-info__left">
          <span class="example-info__stat">
            <strong id="info-progress">0%</strong>
          </span>
          <span class="example-info__stat">
            <span id="info-velocity">0.00</span> /
            <strong id="info-velocity-avg">0.00</strong>
            <span class="example-info__unit">px/ms</span>
          </span>
          <span class="example-info__stat">
            <span id="info-dom">0</span> /
            <strong id="info-total">0</strong>
            <span class="example-info__unit">items</span>
          </span>
        </div>
        <div class="example-info__right">
          <span class="example-info__stat">
            <strong id="info-mode">grid</strong>
          </span>
          <span class="example-info__stat">
            <strong id="info-orientation">vertical</strong>
          </span>
        </div>
      </div>
    </div>
  `,
};

// =============================================================================
// Mount
// =============================================================================

createApp(App).mount("#vue-root");
<div id="vue-root"></div>
// Photo Album — Shared data, constants, template, and state
// Imported by all framework implementations to avoid duplication

import { rebuild } from "vlist";
import {
  photoUrl,
  photoSrcSet,
  photoPicsumUrl,
} from "../../src/data/photos.js";

// =============================================================================
// Constants
// =============================================================================

export const ITEM_COUNT = 900;
export let ASPECT_RATIO = 0.75; // 4:3 landscape

const CATEGORIES = [
  "Nature",
  "Urban",
  "Portrait",
  "Abstract",
  "Travel",
  "Food",
  "Animals",
  "Architecture",
  "Art",
  "Space",
];

// Variable aspect ratios for masonry mode (height/width)
const ASPECT_RATIOS = [0.75, 1.0, 1.33, 1.5, 0.66];

// =============================================================================
// Valid Picsum IDs — excludes first 8 and all known 404s
// =============================================================================

const DEAD_IDS = new Set([
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 86, 97, 105, 138, 148, 150, 205,
  207, 224, 226, 245, 246, 262, 285, 286, 298, 303, 332, 333, 346, 359, 394,
  414, 422, 438, 462, 463, 470, 489, 540, 561, 578, 587, 589, 592, 595, 597,
  601, 624, 632, 636, 644, 647, 673, 697, 706, 707, 708, 709, 710, 711, 712,
  713, 714, 720, 725, 734, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754,
  759, 761, 762, 763, 771, 792, 801, 812, 843, 850, 854, 895, 897, 899, 917,
  920, 934, 956, 963, 968, 1007, 1017, 1030, 1034, 1046,
]);

const VALID_IDS = [];
for (let id = 0; id <= 1084; id++) {
  if (!DEAD_IDS.has(id)) VALID_IDS.push(id);
}

// =============================================================================
// Data
// =============================================================================

const BASE_DATE = new Date(2026, 4, 31).getTime(); // May 31, 2026
const DAY_MS = 86_400_000;

export const items = Array.from({ length: ITEM_COUNT }, (_, i) => {
  const picId = VALID_IDS[i % VALID_IDS.length];
  const category = CATEGORIES[i % CATEGORIES.length];
  const date = new Date(BASE_DATE - i * DAY_MS);
  const month = date.toLocaleDateString("en-US", { year: "numeric", month: "long" });
  return {
    id: i + 1,
    title: `Photo ${i + 1}`,
    category,
    date,
    month,
    likes: Math.floor(Math.abs(Math.sin(i * 2.1)) * 500),
    picId,
    aspectRatio: ASPECT_RATIOS[i % ASPECT_RATIOS.length],
  };
});

// =============================================================================
// Template
// =============================================================================

// A card's picture comes from the self-hosted set (/photos/<id>-300x225.webp),
// with its 2x file in srcset. data-photo-fallback and data-photo-svg name the
// rest of the chain to watchPhotosIn, which walks it when a source is missing,
// errors, or stays pending without ever firing load or error (see the section
// at the bottom).
export const itemTemplate = (item) => {
  const url = photoUrl(item.picId, 300, 225);
  const srcset = photoSrcSet(item.picId, 300, 225);
  const picsum = photoPicsumUrl(item.picId, 300, 225);
  const svg = `/examples/photo-album/images/${item.picId}.svg`;
  return `
  <div class="card">
    <img
      class="card__img"
      src="${url}"
      srcset="${srcset}"
      alt="${item.title}"
      loading="lazy"
      decoding="async"
      data-photo-fallback="${picsum}"
      data-photo-svg="${svg}"
      data-t="${performance.now()}"
      onload="if(performance.now()-this.dataset.t<100){this.style.transition='none';this.offsetHeight}this.classList.add('card__img--loaded')"
    />
    <div class="card__overlay">
      <span class="card__title">${item.title}</span>
      <span class="card__category">${item.category}</span>
    </div>
    <div class="card__likes">♥ ${item.likes}</div>
  </div>
`;
};

// =============================================================================
// State — mutable, shared across script.js and controls.js
// =============================================================================

export let currentMode = "grid";
export let currentOrientation = "vertical";
export let currentColumns = 4;
export let currentGap = 8;
export let currentRadius = 8;
export let followFocus = true;
export let useGroups = false;
export let list = null;

export function setCurrentMode(v) {
  currentMode = v;
}
export function setCurrentOrientation(v) {
  currentOrientation = v;
}
export function setCurrentColumns(v) {
  currentColumns = v;
}
export function setCurrentGap(v) {
  currentGap = v;
}
export function setCurrentRadius(v) {
  currentRadius = v;
}
export function setFollowFocus(v) {
  followFocus = v;
}
export function setUseGroups(v) {
  useGroups = v;
}
export function setAspectRatio(v) {
  ASPECT_RATIO = v;
}
export function setList(v) {
  list = v;
}

// =============================================================================
// View lifecycle
// =============================================================================

let _factory = null;
let _rebuildOptions = {};
let _readyCallbacks = [];
let _createViewFn = null;
let _viewVersion = 0;

export function setFactory(fn, options) {
  _factory = fn;
  _rebuildOptions = options || {};
  // The shell's native/synthetic switch calls this so the album rebuilds with
  // fresh plugins and its own snapshot, instead of reusing the live grid. Only
  // a variant that registers a factory (vanilla) can rebuild this way; the
  // framework variants import this file for its data and take the switch's
  // own rebuild (vlist.io#91).
  globalThis.__vlistRecreate = () => createView();
}

export function onReady(fn) {
  _readyCallbacks.push(fn);
}

export function setCreateView(fn) {
  _createViewFn = fn;
}

export async function createView() {
  if (_factory) {
    const version = ++_viewVersion;
    const newList = await rebuild(list, _factory, _rebuildOptions);
    if (version !== _viewVersion) {
      newList.destroy();
      return;
    }
    list = newList;
    for (const fn of _readyCallbacks) fn(list);
  } else if (_createViewFn) {
    _createViewFn();
  }
}

// =============================================================================
// Photo load timeout
// =============================================================================
//
// A card'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 template carries never runs and the card 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 carousel 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();
  };
}
/* Photo Album — shared styles for all variants (javascript, react, vue, svelte)
   Common styles (.container, h1, .description, .stats, footer)
   are provided by example/example.css using shell.css design tokens.
   UI components (.split-layout, .split-panel, .ui-*)
   is also provided by example/example.css. */

.split-main {
    background-color: transparent !important;
}

/* Grid container */
#list-container {
    --item-radius: 8px;
    height: 590px;
    margin: 0 auto;
}

#list-container .vlist {
    border: none;
    background-color: transparent;
}

/* Horizontal orientation - swap dimensions */
#list-container.vlist--horizontal {
    height: 300px;
    width: 100%;
}

#list-container.vlist--horizontal .vlist-viewport {
    overflow-x: auto;
    overflow-y: hidden;
}

/* ============================================================================
   Grid Info Bar
   ============================================================================ */

.grid-info {
    /* surface via .ui-card .ui-card--compact */
    margin-bottom: 16px;
    font-size: 13px;
    color: var(--text-muted);
}

.grid-info strong {
    color: var(--text);
}

/* ============================================================================
   Photo Card (inside grid items)
   ============================================================================ */

.card {
    position: relative;
    height: 100%;
    overflow: hidden;
    border-radius: var(--item-radius);
    background: var(--bg-card);
    cursor: pointer;
}

.card__img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    opacity: 0;
    transition:
        opacity 0.4s ease,
        transform 0.25s ease;
}

.card__img.card__img--loaded {
    opacity: 1;
}

.card:hover .card__img {
    transform: scale(1.05);
}

.card__overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 24px 8px 8px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
    display: flex;
    flex-direction: column;
    gap: 2px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.card:hover .card__overlay {
    opacity: 1;
}

.card__title {
    font-size: 12px;
    font-weight: var(--fw-bold);
    color: white;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.card__category {
    font-size: 10px;
    color: rgba(255, 255, 255, 0.7);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.card__likes {
    position: absolute;
    top: 6px;
    right: 6px;
    padding: 2px 8px;
    border-radius: 10px;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    font-size: 11px;
    font-weight: var(--fw-bold);
    opacity: 0;
    transition: opacity 0.2s ease;
}

.card:hover .card__likes {
    opacity: 1;
}

/* ============================================================================
   Photo Detail (panel)
   ============================================================================ */

.detail__img {
    width: 100%;
    height: 214.5px;
    border-radius: var(--item-radius, 8px);
    display: none;
    margin-bottom: 8px;
}

.detail__meta {
    display: flex;
    flex-direction: column;
    gap: 2px;
    font-size: 13px;
}

.detail__meta strong {
    font-weight: var(--fw-bold);
}

.detail__meta span {
    font-size: 12px;
    color: var(--text-muted);
}

/* "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;
}

/* ============================================================================
   vlist grid overrides — remove item borders/padding for photo cards
   ============================================================================ */

#list-container .vlist-item {
    padding: 0;
    border: none;
    background: transparent;
}

#list-container .vlist-item:hover {
    background: transparent;
}

#list-container .vlist-item.vlist-item--selected,
#list-container .vlist-item.vlist-item--focused,
#list-container .vlist-grid-item.vlist-item--focused,
#list-container .vlist-grid-item.vlist-item--selected,
#list-container .vlist-masonry-item.vlist-item--focused,
#list-container .vlist-masonry-item.vlist-item--selected {
    outline: none;
    box-shadow: 0 0 0 2px var(--vlist-focus-ring, #3b82f6);
    border-radius: var(--item-radius);
    background: transparent;
}

/* ============================================================================
   Group Headers
   ============================================================================ */

#list-container .vlist-group-header {
    display: flex;
    align-items: center;
    padding: 0 8px;
    font-size: 0.6875rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--text-muted, #9ca3af);
    background: transparent;
}

#list-container .vlist-sticky-header {
    z-index: 5;
    font-size: 0.6875rem;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--text-muted, #9ca3af);
    background: transparent;
    border-bottom: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.06));
}

#list-container .vlist-sticky-header .sticky-group {
    display: flex;
    align-items: center;
    padding: 0 8px;
    height: 100%;
}

/* ============================================================================
   Responsive
   ============================================================================ */

@media (max-width: 820px) {
    #list-container {
        height: 400px;
    }

    #list-container.vlist--horizontal {
        height: 250px;
    }
}