# Stacking Cards

Kartu yang menempel dan menumpuk saat discroll, sementara kartu yang tertutup mengecil, menyebar, atau buram. Kartu dengan fokus keyboard kembali ke depan.

- Kategori: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/stacking-cards.json
- CLI: `npx markasui@latest add stacking-cards`

## Kapan dipakai

Cerita scroll berisi 3 sampai 6 langkah atau fitur: fitur produk, langkah onboarding, paket harga, testimoni, atau linimasa singkat perusahaan.

- Setiap anak langsung adalah kartu, jadi beri masing-masing latar solid, border, dan tinggi yang sama
- Sisakan ruang scroll setelah tumpukan (padding atau bagian lain) agar kartu terakhir bisa diam
- Pakai article atau item daftar per kartu bila kartu punya judul
- Cukup 3 sampai 6 kartu; lebih dari itu efeknya melelahkan

## Kode

### Blade

Simpan di `resources/views/components/markas/stacking-cards.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'variant' => 'scale',
    'top' => 16,
    'offset' => 16,
])

@php
    $base = 'relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]';
    $variants = [
        'scale' => '[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]',
        'fan' => '[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]',
        'blur' => '[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]',
    ];
    $style = '--stack-top: '.(float) $top.'px; --stack-step: '.(float) $offset.'px';
@endphp

{{-- Every card gets its index; while on screen, --stack-depth says how much the later cards already cover it. --}}
<div
    wire:ignore
    x-data="{
        frame: 0,
        observer: null,
        stop: null,
        init() {
            const root = this.$root;
            const step = {{ (float) $offset }};
            const cards = () => [...root.children];
            cards().forEach((card, i) => {
                card.style.setProperty('--stack-i', String(i));
                card.style.setProperty('--stack-turn', i % 2 ? '1' : '-1');
            });
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches || typeof IntersectionObserver !== 'function') return;
            const clamp = (n) => Math.min(Math.max(n, 0), 1);
            const update = () => {
                this.frame = 0;
                const list = cards();
                let depth = 0;
                for (let i = list.length - 1; i >= 0; i--) {
                    const card = list[i];
                    card.style.setProperty('--stack-depth', String(Math.round(Math.min(depth, 6) * 1000) / 1000));
                    const prev = list[i - 1];
                    if (! prev) continue;
                    const gap = card.offsetTop - prev.offsetTop;
                    depth += clamp((prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1));
                }
            };
            const schedule = () => {
                this.frame ||= requestAnimationFrame(update);
            };
            const listen = (on) => {
                const method = on ? 'addEventListener' : 'removeEventListener';
                document[method]('scroll', schedule, { capture: true, passive: true });
                window[method]('resize', schedule);
            };
            this.observer = new IntersectionObserver(([entry]) => {
                listen(Boolean(entry?.isIntersecting));
                schedule();
            });
            this.observer.observe(root);
            this.stop = () => listen(false);
        },
        destroy() {
            this.observer?.disconnect();
            this.stop?.();
            cancelAnimationFrame(this.frame);
        },
    }"
    {{ $attributes->merge(['style' => $style])->class([$base, $variants[$variant] ?? $variants['scale']]) }}
>
    {{ $slot }}
</div>
```

```blade
<div class="pb-64">
    <x-markas.stacking-cards variant="fan" :top="96" :offset="12" class="gap-6">
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Rencanakan minggumu</article>
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Bagikan ke tim</article>
        <article class="h-64 rounded-xl border border-line bg-surface p-6">Dibayar tepat waktu</article>
    </x-markas.stacking-cards>
</div>
```

Butuh Alpine.js.

### React

Simpan di `src/components/markas/StackingCards.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import { useEffect, useRef, type ComponentProps } from "react";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

export type StackingCardsProps = ComponentProps<"div"> & {
  /** What happens to the cards that the next ones cover. */
  variant?: StackingCardsVariant;
  /** Sticky top of the first card in px. */
  top?: number;
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  offset?: number;
};

export function StackingCards({
  variant = "scale",
  top = 16,
  offset = 16,
  className,
  style,
  children,
  ...props
}: StackingCardsProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  useEffect(() => createStack(rootRef.current!, offset), [offset]);
  return (
    <div
      {...props}
      ref={rootRef}
      className={cx(base, variants[variant], className)}
      style={
        {
          "--stack-top": `${top}px`,
          "--stack-step": `${offset}px`,
          ...style,
        } as ComponentProps<"div">["style"]
      }
    >
      {children}
    </div>
  );
}
```

```tsx
import { StackingCards } from "@/components/markas/StackingCards";

<div className="pb-64">
  <StackingCards variant="fan" top={96} offset={12} className="gap-6">
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Rencanakan minggumu
    </article>
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Bagikan ke tim
    </article>
    <article className="h-64 rounded-xl border border-line bg-surface p-6">
      Dibayar tepat waktu
    </article>
  </StackingCards>
</div>;
```

### Vue

Simpan di `src/components/markas/StackingCards.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const props = withDefaults(
  defineProps<{
    /** What happens to the cards that the next ones cover. */
    variant?: StackingCardsVariant;
    /** Sticky top of the first card in px. */
    top?: number;
    /** Extra px each later card sticks below the one before, so earlier cards peek out. */
    offset?: number;
  }>(),
  { variant: "scale", top: 16, offset: 16 },
);

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
const start = () => {
  stop();
  stop = createStack(rootEl.value!, props.offset);
};
onMounted(start);
watch(() => props.offset, start);
onBeforeUnmount(() => stop());
</script>

<template>
  <div
    ref="rootRef"
    :class="[base, variants[props.variant]]"
    :style="{
      '--stack-top': `${props.top}px`,
      '--stack-step': `${props.offset}px`,
    }"
  >
    <slot />
  </div>
</template>
```

```vue
<template>
  <div class="pb-64">
    <StackingCards variant="fan" :top="96" :offset="12" class="gap-6">
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Rencanakan minggumu
      </article>
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Bagikan ke tim
      </article>
      <article class="h-64 rounded-xl border border-line bg-surface p-6">
        Dibayar tepat waktu
      </article>
    </StackingCards>
  </div>
</template>
```

### Svelte

Simpan di `src/lib/components/markas/StackingCards.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  type StackingCardsVariant = "scale" | "fan" | "blur";

  const base =
    "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
  const variants: Record<StackingCardsVariant, string> = {
    scale:
      "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
    fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
    blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
  };

  const MAX_DEPTH = 6;

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

  /**
   * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
   * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
   */
  function createStack(root: HTMLElement, step: number) {
    const cards = () => [...root.children] as HTMLElement[];
    cards().forEach((card, i) => {
      card.style.setProperty("--stack-i", String(i));
      card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
    });
    if (still() || typeof IntersectionObserver !== "function") return () => {};

    let frame = 0;
    const update = () => {
      frame = 0;
      const list = cards();
      let depth = 0;
      for (let i = list.length - 1; i >= 0; i--) {
        const card = list[i]!;
        card.style.setProperty(
          "--stack-depth",
          String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
        );
        const prev = list[i - 1];
        if (!prev) continue;
        const gap = card.offsetTop - prev.offsetTop;
        depth += clamp(
          (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
        );
      }
    };
    const schedule = () => {
      frame ||= requestAnimationFrame(update);
    };
    const listen = (on: boolean) => {
      const method = on ? "addEventListener" : "removeEventListener";
      document[method]("scroll", schedule, { capture: true, passive: true });
      window[method]("resize", schedule);
    };
    const observer = new IntersectionObserver(([entry]) => {
      listen(Boolean(entry?.isIntersecting));
      schedule();
    });
    observer.observe(root);
    return () => {
      observer.disconnect();
      listen(false);
      cancelAnimationFrame(frame);
    };
  }

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** What happens to the cards that the next ones cover. */
    variant?: StackingCardsVariant;
    /** Sticky top of the first card in px. */
    top?: number;
    /** Extra px each later card sticks below the one before, so earlier cards peek out. */
    offset?: number;
    children?: Snippet;
  };

  let {
    variant = "scale",
    top = 16,
    offset = 16,
    class: className,
    style,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();

  $effect(() => {
    const step = offset;
    if (root) return createStack(root, step);
  });
</script>

<div
  {...rest}
  bind:this={root}
  class={[base, variants[variant], className]}
  style={`--stack-top: ${top}px; --stack-step: ${offset}px;${style ? ` ${style}` : ""}`}
>
  {@render children?.()}
</div>
```

```svelte
<script lang="ts">
  import StackingCards from "$lib/components/markas/StackingCards.svelte";
</script>

<StackingCards variant="fan" class="gap-4">
  <article class="h-48 rounded-xl border border-line bg-surface p-5">
    One
  </article>
  <article class="h-48 rounded-xl border border-line bg-surface p-5">
    Two
  </article>
</StackingCards>
```

### Astro

Simpan di `src/components/markas/StackingCards.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

type Props = HTMLAttributes<"div"> & {
  /** What happens to the cards that the next ones cover. */
  variant?: StackingCardsVariant;
  /** Sticky top of the first card in px. */
  top?: number;
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  offset?: number;
};

const {
  variant = "scale",
  top = 16,
  offset = 16,
  class: className,
  style,
  ...rest
} = Astro.props;
const userStyle = typeof style === "string" && style ? ` ${style}` : "";
---

<markas-stacking-cards class="contents">
  <div
    {...rest}
    class:list={[base, variants[variant], className]}
    style={`--stack-top: ${top}px; --stack-step: ${offset}px;${userStyle}`}
  >
    <slot />
  </div>
</markas-stacking-cards>

<script>
  const MAX_DEPTH = 6;
  const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

  /**
   * Per instance: give every card its index, then, while the stack is on screen, set --stack-depth
   * on each card: how many of the cards after it already cover it (0 to 1 each), from layout boxes
   * that ignore transforms.
   */
  class StackingCards extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      if (!root) return;
      const step = parseFloat(root.style.getPropertyValue("--stack-step")) || 0;
      const cards = () => [...root.children] as HTMLElement[];
      cards().forEach((card, i) => {
        card.style.setProperty("--stack-i", String(i));
        card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
      });
      if (
        window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ||
        typeof IntersectionObserver !== "function"
      )
        return;

      let frame = 0;
      const update = () => {
        frame = 0;
        const list = cards();
        let depth = 0;
        for (let i = list.length - 1; i >= 0; i--) {
          const card = list[i]!;
          card.style.setProperty(
            "--stack-depth",
            String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
          );
          const prev = list[i - 1];
          if (!prev) continue;
          const gap = card.offsetTop - prev.offsetTop;
          depth += clamp(
            (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
          );
        }
      };
      const schedule = () => {
        frame ||= requestAnimationFrame(update);
      };
      const listen = (on: boolean) => {
        const method = on ? "addEventListener" : "removeEventListener";
        document[method]("scroll", schedule, { capture: true, passive: true });
        window[method]("resize", schedule);
      };
      const observer = new IntersectionObserver(([entry]) => {
        listen(Boolean(entry?.isIntersecting));
        schedule();
      });
      observer.observe(root);
      this.#stop = () => {
        observer.disconnect();
        listen(false);
        cancelAnimationFrame(frame);
      };
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-stacking-cards"))
    customElements.define("markas-stacking-cards", StackingCards);
</script>
```

```astro
---
import StackingCards from "@/components/markas/StackingCards.astro";
---

<StackingCards variant="fan" class="gap-4">
  <article class="h-48 rounded-xl border border-line bg-surface p-5">One</article>
  <article class="h-48 rounded-xl border border-line bg-surface p-5">Two</article>
</StackingCards>
```

Satu script kecil yang dibundel mengukur setiap tumpukan lewat elemen `markas-stacking-cards`.

### Angular

Simpan di `src/app/markas/stacking-cards.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  afterRenderEffect,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  numberAttribute,
  viewChild,
} from "@angular/core";

export type StackingCardsVariant = "scale" | "fan" | "blur";

const base =
  "relative grid [&>*]:sticky [&>*]:top-[calc(var(--stack-top)+var(--stack-i,0)*var(--stack-step))] [&>*]:origin-top [&>*]:transition-[scale,rotate,filter] [&>*]:duration-150 [&>*]:ease-out motion-reduce:[&>*]:transition-none [&>*:has(:focus-visible)]:z-10 [&>*:has(:focus-visible)]:[scale:1] [&>*:has(:focus-visible)]:[rotate:0deg] [&>*:has(:focus-visible)]:[filter:none]";
const variants: Record<StackingCardsVariant, string> = {
  scale:
    "[&>*]:[scale:calc(1-var(--stack-depth,0)*0.05)] [&>*]:[filter:brightness(calc(1-var(--stack-depth,0)*0.12))]",
  fan: "[&>*]:[rotate:calc(var(--stack-depth,0)*var(--stack-turn,1)*2.5deg)] [&>*]:[scale:calc(1-var(--stack-depth,0)*0.02)]",
  blur: "[&>*]:[filter:blur(calc(var(--stack-depth,0)*1.5px))_brightness(calc(1-var(--stack-depth,0)*0.08))]",
};

const MAX_DEPTH = 6;

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const clamp = (n: number) => Math.min(Math.max(n, 0), 1);

/**
 * Give every card its index, then, while the stack is on screen, set --stack-depth on each card:
 * how many of the cards after it already cover it (0 to 1 each), from layout boxes that ignore transforms.
 */
function createStack(root: HTMLElement, step: number) {
  const cards = () => [...root.children] as HTMLElement[];
  cards().forEach((card, i) => {
    card.style.setProperty("--stack-i", String(i));
    card.style.setProperty("--stack-turn", i % 2 ? "1" : "-1");
  });
  if (still() || typeof IntersectionObserver !== "function") return () => {};

  let frame = 0;
  const update = () => {
    frame = 0;
    const list = cards();
    let depth = 0;
    for (let i = list.length - 1; i >= 0; i--) {
      const card = list[i]!;
      card.style.setProperty(
        "--stack-depth",
        String(Math.round(Math.min(depth, MAX_DEPTH) * 1000) / 1000),
      );
      const prev = list[i - 1];
      if (!prev) continue;
      const gap = card.offsetTop - prev.offsetTop;
      depth += clamp(
        (prev.offsetHeight - gap) / Math.max(prev.offsetHeight - step, 1),
      );
    }
  };
  const schedule = () => {
    frame ||= requestAnimationFrame(update);
  };
  const listen = (on: boolean) => {
    const method = on ? "addEventListener" : "removeEventListener";
    document[method]("scroll", schedule, { capture: true, passive: true });
    window[method]("resize", schedule);
  };
  const observer = new IntersectionObserver(([entry]) => {
    listen(Boolean(entry?.isIntersecting));
    schedule();
  });
  observer.observe(root);
  return () => {
    observer.disconnect();
    listen(false);
    cancelAnimationFrame(frame);
  };
}

/** Every projected element is one card. The host stays out of layout; the user's class and role land on the stack. */
@Component({
  selector: "markas-stacking-cards",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.role]": "null" },
  template: `
    <div
      #rootEl
      [attr.role]="role()"
      [class]="classes()"
      [style.--stack-top]="top() + 'px'"
      [style.--stack-step]="offset() + 'px'"
    >
      <ng-content />
    </div>
  `,
})
export class StackingCards {
  /** What happens to the cards that the next ones cover. */
  readonly variant = input<StackingCardsVariant>("scale");
  /** Sticky top of the first card in px. */
  readonly top = input(16, { transform: numberAttribute });
  /** Extra px each later card sticks below the one before, so earlier cards peek out. */
  readonly offset = input(16, { transform: numberAttribute });
  /** Lands on the stack, for example role="list" around li cards. */
  readonly role = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly classes = computed(() =>
    [base, variants[this.variant()], this.userClass()]
      .filter(Boolean)
      .join(" "),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      onCleanup(createStack(this.root().nativeElement, this.offset()));
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { StackingCards } from "./markas/stacking-cards.component";

@Component({
  selector: "app-features",
  imports: [StackingCards],
  template: `
    <markas-stacking-cards variant="fan" class="gap-4">
      <article class="h-48 rounded-xl border border-line bg-surface p-5">
        One
      </article>
      <article class="h-48 rounded-xl border border-line bg-surface p-5">
        Two
      </article>
    </markas-stacking-cards>
  `,
})
export class Features {}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `variant` | `"scale" \| "fan" \| "blur"` | "scale" | Apa yang terjadi pada kartu yang tertutup. scale: mengecil dan meredup. fan: miring kiri dan kanan seperti tumpukan kartu. blur: buram dan meredup. |
| `top` | `number` | 16 | Posisi sticky kartu pertama dalam px, diukur dari atas area scroll. |
| `offset` | `number` | 16 | Tambahan px tiap kartu berikutnya menempel di bawah kartu sebelumnya, sehingga tepi kartu sebelumnya terlihat. 0 menumpuk tepat. |
| `children / slot` | `ReactNode / slot` | - | Kartu-kartunya. Setiap anak langsung adalah satu kartu; beri masing-masing latar sendiri agar menutupi kartu di bawahnya. |

## Aksesibilitas

- Kartu tetap dalam urutan baca normal; tumpukan hanya visual.
- Kartu yang memegang fokus keyboard melompat ke depan dalam ukuran penuh, sehingga fokus tidak pernah tersembunyi di balik kartu berikutnya.
- Dengan reduced motion kartu tetap menempel tetapi tidak mengecil, miring, atau buram.

## Catatan

- Setiap anak langsung adalah kartu. Kartu menempel di `top` ditambah `offset` per kartu, sehingga kartu sebelumnya terlihat di atas kartu berikutnya.
- `--stack-depth` pada tiap kartu menyatakan seberapa jauh kartu berikutnya sudah menutupinya. `scale` mengecil dan meredup, `fan` miring kiri dan kanan, `blur` buram dan meredup.
- Listener scroll bersifat pasif, digabung dalam satu requestAnimationFrame, dan hanya terpasang selama tumpukan terlihat. Bekerja di halaman maupun di dalam kontainer scroll mana pun.
- Kartu yang memegang fokus keyboard melompat ke depan dalam ukuran penuh. Dengan reduced motion kartu tetap menempel tetapi tidak berubah. Atribut dan `class` jatuh ke tumpukan.
