# Expandable Card

Compact card that grows into a centered detail view built on a native dialog, then shrinks back into place on close.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/expandable-card.json
- CLI: `npx markasui@latest add expandable-card`

## When to use

Grids of products, articles, projects, or people where a short summary is enough at first and details open on demand without leaving the page.

- Place several cards in a grid, the component renders one card
- Keep the card text short; put specs, long text, and actions in children and footer
- Do not put links or buttons in title, description, or media, the whole card is a button
- Use a page route instead when the detail needs its own URL

## Code

### Blade

Save at `resources/views/components/markas/expandable-card.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'title',
    'description' => null,
    'closeLabel' => 'Close',
])

@php
    $wrapper = 'contents';
    $trigger = 'group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0';
    $cardMedia = 'block h-28 overflow-hidden rounded-lg bg-subtle';
    $cardText = 'grid gap-1 px-1 pb-1';
    $cardTitle = 'text-sm font-medium text-ink';
    $cardDescription = 'line-clamp-2 text-sm text-muted';
    $expandIcon = 'absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none';
    $dialogClass = 'm-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40';
    $panel = 'relative';
    $dialogMedia = 'h-48 overflow-hidden bg-subtle';
    $dialogBody = 'grid gap-3 p-5';
    $dialogTitle = 'pr-10 text-lg font-semibold text-ink';
    $dialogDescription = 'text-sm text-muted';
    $details = 'grid gap-3 text-sm text-ink';
    $footerClass = 'flex flex-wrap justify-end gap-2 pt-2';
    $close = 'absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
    $icon = 'size-4';

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-expandable-card|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-expandable-card-'.hash('xxh32', $idKey.$idIndex);
    $hasDetails = $slot->isNotEmpty();
@endphp

{{-- The card grows into a native modal dialog (FLIP) and shrinks back on close. Escape, the backdrop, and the close button all animate. --}}
<div
    class="{{ $wrapper }}"
    x-data="{
        open: false,
        closing: false,
        canAnimate(el) {
            return !! el.animate && ! matchMedia('(prefers-reduced-motion: reduce)').matches;
        },
        overCard(card, dialog) {
            const box = dialog.getBoundingClientRect();
            return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
        },
        morph(card, opening) {
            const { dialog, panel } = this.$refs;
            dialog.getAnimations({ subtree: true }).forEach((animation) => animation.cancel());
            const options = { duration: opening ? 420 : 320, easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)', direction: opening ? 'normal' : 'reverse', fill: opening ? 'none' : 'forwards' };
            panel.animate([{ opacity: 0 }, { opacity: 0, offset: 0.35 }, { opacity: 1 }], options);
            dialog.animate([{ opacity: 0 }, { opacity: 1 }], { ...options, pseudoElement: '::backdrop' });
            return dialog.animate([
                { transform: this.overCard(card, dialog), transformOrigin: 'top left' },
                { transform: 'none', transformOrigin: 'top left' },
            ], options);
        },
        show(event) {
            const { dialog, trigger } = this.$refs;
            if (event.defaultPrevented || dialog.open) return;
            const from = trigger.getBoundingClientRect();
            dialog.showModal();
            this.open = true;
            if (this.canAnimate(dialog)) this.morph(from, true);
        },
        hide() {
            const { dialog, trigger } = this.$refs;
            if (! dialog.open || this.closing) return;
            if (! this.canAnimate(dialog)) return dialog.close();
            this.closing = true;
            this.morph(trigger.getBoundingClientRect(), false).onfinish = () => dialog.close();
        },
        closed() {
            this.$refs.dialog.getAnimations({ subtree: true }).forEach((animation) => animation.cancel());
            this.closing = false;
            this.open = false;
            this.$refs.trigger.focus();
        },
    }"
>
    <button
        x-ref="trigger"
        data-state="closed"
        x-bind:data-state="open ? 'open' : 'closed'"
        x-on:click="show($event)"
        {{ $attributes->merge(['id' => $id, 'type' => 'button', 'aria-haspopup' => 'dialog', 'aria-controls' => $id.'-dialog'])->class([$trigger]) }}
    >
        @isset($media)
            <span class="{{ $cardMedia }}">{{ $media }}</span>
        @endisset
        <span class="{{ $cardText }}">
            <span class="{{ $cardTitle }}">{{ $title }}</span>
            @if ($description)
                <span class="{{ $cardDescription }}">{{ $description }}</span>
            @endif
        </span>
        <span aria-hidden="true" class="{{ $expandIcon }}">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="M12 5v14M5 12h14" /></svg>
        </span>
    </button>
    <dialog
        wire:ignore.self
        x-ref="dialog"
        id="{{ $id }}-dialog"
        aria-labelledby="{{ $id }}-title"
        data-state="closed"
        x-bind:data-state="open ? 'open' : 'closed'"
        x-on:close="closed()"
        x-on:cancel.prevent="hide()"
        x-on:keydown.escape.prevent="hide()"
        x-on:click.self="hide()"
        class="{{ $dialogClass }}"
    >
        <div x-ref="panel" class="{{ $panel }}">
            <button type="button" aria-label="{{ $closeLabel }}" x-on:click="hide()" class="{{ $close }}">
                <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="M18 6 6 18M6 6l12 12" /></svg>
            </button>
            @isset($media)
                <div class="{{ $dialogMedia }}">{{ $media }}</div>
            @endisset
            <div class="{{ $dialogBody }}">
                <h2 id="{{ $id }}-title" class="{{ $dialogTitle }}">{{ $title }}</h2>
                @if ($description)
                    <p class="{{ $dialogDescription }}">{{ $description }}</p>
                @endif
                @if ($hasDetails)
                    <div class="{{ $details }}">{{ $slot }}</div>
                @endif
                @isset($footer)
                    <div class="{{ $footerClass }}">{{ $footer }}</div>
                @endisset
            </div>
        </div>
    </dialog>
</div>
```

```blade
<div class="grid grid-cols-2 gap-3">
    @foreach ($products as $product)
        <x-markas.expandable-card :title="$product->name" :description="$product->summary">
            <x-slot:media>
                <img src="{{ $product->image }}" alt="" class="size-full object-cover" />
            </x-slot:media>
            <p class="text-base font-semibold">{{ $product->price }}</p>
            <x-slot:footer>
                <x-markas.button>Add to cart</x-markas.button>
            </x-slot:footer>
        </x-markas.expandable-card>
    @endforeach
</div>
```

Needs Alpine.js.

### React

Save at `src/components/markas/ExpandableCard.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useId,
  useRef,
  useState,
  type ComponentProps,
  type KeyboardEvent,
  type MouseEvent,
  type ReactNode,
  type SyntheticEvent,
} from "react";

const wrapper = "contents";
const trigger =
  "group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0";
const cardMedia = "block h-28 overflow-hidden rounded-lg bg-subtle";
const cardText = "grid gap-1 px-1 pb-1";
const cardTitle = "text-sm font-medium text-ink";
const cardDescription = "line-clamp-2 text-sm text-muted";
const expandIcon =
  "absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none";
const dialogClass =
  "m-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "relative";
const dialogMedia = "h-48 overflow-hidden bg-subtle";
const dialogBody = "grid gap-3 p-5";
const dialogTitle = "pr-10 text-lg font-semibold text-ink";
const dialogDescription = "text-sm text-muted";
const details = "grid gap-3 text-sm text-ink";
const footerClass = "flex flex-wrap justify-end gap-2 pt-2";
const close =
  "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const icon = "size-4";

const OPEN_MS = 420;
const CLOSE_MS = 320;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const canAnimate = (el: HTMLElement) =>
  typeof el.animate === "function" &&
  !(
    typeof matchMedia === "function" &&
    matchMedia("(prefers-reduced-motion: reduce)").matches
  );

/** Transform that puts the dialog exactly over the card (FLIP "first" frame). */
function overCard(card: DOMRect, dialog: HTMLElement) {
  const box = dialog.getBoundingClientRect();
  return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
}

/** Grow the dialog out of the card, or shrink it back into it. */
function morph(
  dialog: HTMLElement,
  panelEl: HTMLElement,
  card: DOMRect,
  opening: boolean,
) {
  const duration = opening ? OPEN_MS : CLOSE_MS;
  // Stop a running grow or shrink first so the measurement below is not mid-flight.
  dialog
    .getAnimations?.({ subtree: true })
    .forEach((animation) => animation.cancel());
  const frames: Keyframe[] = [
    { transform: overCard(card, dialog), transformOrigin: "top left" },
    { transform: "none", transformOrigin: "top left" },
  ];
  const fade: Keyframe[] = [
    { opacity: 0 },
    { opacity: 0, offset: 0.35 },
    { opacity: 1 },
  ];
  // Closing holds the last frame until the dialog is closed, so it never flashes back to full size.
  const options: KeyframeAnimationOptions = {
    duration,
    easing: EASE,
    direction: opening ? "normal" : "reverse",
    fill: opening ? "none" : "forwards",
  };
  panelEl.animate(fade, options);
  dialog.animate([{ opacity: 0 }, { opacity: 1 }], {
    ...options,
    pseudoElement: "::backdrop",
  });
  return dialog.animate(frames, options);
}

export type ExpandableCardProps = Omit<
  ComponentProps<"button">,
  "title" | "type"
> & {
  title: ReactNode;
  /** Short text, clamped to two lines on the card and shown in full when open. */
  description?: ReactNode;
  /** Image or illustration shown on top of the card and the open view. */
  media?: ReactNode;
  /** Actions at the bottom of the open view. */
  footer?: ReactNode;
  closeLabel?: string;
};

export function ExpandableCard({
  title,
  description,
  media,
  footer,
  closeLabel = "Close",
  id,
  className,
  children,
  onClick,
  ...props
}: ExpandableCardProps) {
  const generatedId = useId();
  const cardId = id ?? generatedId;
  const dialogId = `${cardId}-dialog`;
  const triggerRef = useRef<HTMLButtonElement>(null);
  const dialogRef = useRef<HTMLDialogElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const closing = useRef(false);
  const [open, setOpen] = useState(false);

  const show = (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    const dialog = dialogRef.current;
    const card = triggerRef.current;
    if (event.defaultPrevented || !dialog || !card || dialog.open) return;
    const from = card.getBoundingClientRect();
    dialog.showModal();
    setOpen(true);
    if (canAnimate(dialog) && panelRef.current)
      morph(dialog, panelRef.current, from, true);
  };

  const hide = () => {
    const dialog = dialogRef.current;
    const card = triggerRef.current;
    if (!dialog?.open || closing.current) return;
    if (!card || !panelRef.current || !canAnimate(dialog)) {
      dialog.close();
      return;
    }
    closing.current = true;
    const animation = morph(
      dialog,
      panelRef.current,
      card.getBoundingClientRect(),
      false,
    );
    animation.onfinish = () => dialog.close();
  };

  const handleClosed = () => {
    dialogRef.current
      ?.getAnimations?.({ subtree: true })
      .forEach((animation) => animation.cancel());
    closing.current = false;
    setOpen(false);
    triggerRef.current?.focus();
  };

  const handleCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
    event.preventDefault();
    hide();
  };
  const handleKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
    if (event.key !== "Escape") return;
    event.preventDefault();
    hide();
  };
  const handleBackdrop = (event: MouseEvent<HTMLDialogElement>) => {
    if (event.target === event.currentTarget) hide();
  };

  return (
    <div className={wrapper}>
      <button
        ref={triggerRef}
        id={cardId}
        type="button"
        aria-haspopup="dialog"
        aria-controls={dialogId}
        data-state={open ? "open" : "closed"}
        className={cx(trigger, className)}
        onClick={show}
        {...props}
      >
        {media && <span className={cardMedia}>{media}</span>}
        <span className={cardText}>
          <span className={cardTitle}>{title}</span>
          {description && (
            <span className={cardDescription}>{description}</span>
          )}
        </span>
        <span aria-hidden="true" className={expandIcon}>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            className={icon}
          >
            <path d="M12 5v14M5 12h14" />
          </svg>
        </span>
      </button>
      <dialog
        ref={dialogRef}
        id={dialogId}
        aria-labelledby={`${cardId}-title`}
        data-state={open ? "open" : "closed"}
        className={dialogClass}
        onClose={handleClosed}
        onCancel={handleCancel}
        onKeyDown={handleKeyDown}
        onClick={handleBackdrop}
      >
        <div ref={panelRef} className={panel}>
          <button
            type="button"
            aria-label={closeLabel}
            className={close}
            onClick={hide}
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              className={icon}
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
          {media && <div className={dialogMedia}>{media}</div>}
          <div className={dialogBody}>
            <h2 id={`${cardId}-title`} className={dialogTitle}>
              {title}
            </h2>
            {description && <p className={dialogDescription}>{description}</p>}
            {children && <div className={details}>{children}</div>}
            {footer && <div className={footerClass}>{footer}</div>}
          </div>
        </div>
      </dialog>
    </div>
  );
}
```

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

<div className="grid grid-cols-2 gap-3">
  {products.map((product) => (
    <ExpandableCard
      key={product.id}
      title={product.name}
      description={product.summary}
      media={
        <img src={product.image} alt="" className="size-full object-cover" />
      }
      footer={<Button>Add to cart</Button>}
    >
      <p className="text-base font-semibold">{product.price}</p>
    </ExpandableCard>
  ))}
</div>;
```

### Vue

Save at `src/components/markas/ExpandableCard.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { computed, ref, useId, useTemplateRef } from "vue";

defineOptions({ inheritAttrs: false });

const props = withDefaults(
  defineProps<{
    title: string;
    /** Short text, clamped to two lines on the card and shown in full when open. */
    description?: string;
    closeLabel?: string;
    id?: string;
  }>(),
  { description: undefined, closeLabel: "Close", id: undefined },
);

const wrapper = "contents";
const trigger =
  "group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0";
const cardMedia = "block h-28 overflow-hidden rounded-lg bg-subtle";
const cardText = "grid gap-1 px-1 pb-1";
const cardTitle = "text-sm font-medium text-ink";
const cardDescription = "line-clamp-2 text-sm text-muted";
const expandIcon =
  "absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none";
const dialogClass =
  "m-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "relative";
const dialogMedia = "h-48 overflow-hidden bg-subtle";
const dialogBody = "grid gap-3 p-5";
const dialogTitle = "pr-10 text-lg font-semibold text-ink";
const dialogDescription = "text-sm text-muted";
const details = "grid gap-3 text-sm text-ink";
const footerClass = "flex flex-wrap justify-end gap-2 pt-2";
const close =
  "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const icon = "size-4";

const OPEN_MS = 420;
const CLOSE_MS = 320;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";

const generatedId = useId();
const cardId = computed(() => props.id ?? generatedId);
const triggerEl = useTemplateRef<HTMLButtonElement>("triggerRef");
const dialogEl = useTemplateRef<HTMLDialogElement>("dialogRef");
const panelEl = useTemplateRef<HTMLDivElement>("panelRef");
const open = ref(false);
let closing = false;

const canAnimate = (el: HTMLElement) =>
  typeof el.animate === "function" &&
  !(
    typeof matchMedia === "function" &&
    matchMedia("(prefers-reduced-motion: reduce)").matches
  );

type Frames = Parameters<HTMLElement["animate"]>[0];
type AnimateOptions = Exclude<
  Parameters<HTMLElement["animate"]>[1],
  number | undefined
>;

/** Transform that puts the dialog exactly over the card (FLIP "first" frame). */
function overCard(card: DOMRect, dialog: HTMLElement) {
  const box = dialog.getBoundingClientRect();
  return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
}

/** Grow the dialog out of the card, or shrink it back into it. */
function morph(
  dialog: HTMLElement,
  panelNode: HTMLElement,
  card: DOMRect,
  opening: boolean,
) {
  // Stop a running grow or shrink first so the measurement below is not mid-flight.
  dialog
    .getAnimations?.({ subtree: true })
    .forEach((animation) => animation.cancel());
  const frames: Frames = [
    { transform: overCard(card, dialog), transformOrigin: "top left" },
    { transform: "none", transformOrigin: "top left" },
  ];
  const fade: Frames = [
    { opacity: 0 },
    { opacity: 0, offset: 0.35 },
    { opacity: 1 },
  ];
  // Closing holds the last frame until the dialog is closed, so it never flashes back to full size.
  const options: AnimateOptions = {
    duration: opening ? OPEN_MS : CLOSE_MS,
    easing: EASE,
    direction: opening ? "normal" : "reverse",
    fill: opening ? "none" : "forwards",
  };
  panelNode.animate(fade, options);
  dialog.animate([{ opacity: 0 }, { opacity: 1 }], {
    ...options,
    pseudoElement: "::backdrop",
  });
  return dialog.animate(frames, options);
}

function onTrigger(event: MouseEvent) {
  if (!event.defaultPrevented) show();
}

function show() {
  const dialog = dialogEl.value;
  const card = triggerEl.value;
  if (!dialog || !card || dialog.open) return;
  const from = card.getBoundingClientRect();
  dialog.showModal();
  open.value = true;
  if (canAnimate(dialog) && panelEl.value)
    morph(dialog, panelEl.value, from, true);
}

function hide() {
  const dialog = dialogEl.value;
  const card = triggerEl.value;
  if (!dialog?.open || closing) return;
  if (!card || !panelEl.value || !canAnimate(dialog)) {
    dialog.close();
    return;
  }
  closing = true;
  const animation = morph(
    dialog,
    panelEl.value,
    card.getBoundingClientRect(),
    false,
  );
  animation.onfinish = () => dialog.close();
}

function onClosed() {
  dialogEl.value
    ?.getAnimations?.({ subtree: true })
    .forEach((animation) => animation.cancel());
  closing = false;
  open.value = false;
  triggerEl.value?.focus();
}

function onBackdrop(event: MouseEvent) {
  if (event.target === event.currentTarget) hide();
}
</script>

<template>
  <div :class="wrapper">
    <button
      :id="cardId"
      ref="triggerRef"
      type="button"
      aria-haspopup="dialog"
      :aria-controls="`${cardId}-dialog`"
      :data-state="open ? 'open' : 'closed'"
      :class="trigger"
      v-bind="$attrs"
      @click="onTrigger"
    >
      <span v-if="$slots.media" :class="cardMedia"><slot name="media" /></span>
      <span :class="cardText">
        <span :class="cardTitle">{{ props.title }}</span>
        <span v-if="props.description" :class="cardDescription">{{
          props.description
        }}</span>
      </span>
      <span aria-hidden="true" :class="expandIcon">
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          :class="icon"
        >
          <path d="M12 5v14M5 12h14" />
        </svg>
      </span>
    </button>
    <dialog
      :id="`${cardId}-dialog`"
      ref="dialogRef"
      :aria-labelledby="`${cardId}-title`"
      :data-state="open ? 'open' : 'closed'"
      :class="dialogClass"
      @close="onClosed"
      @cancel.prevent="hide"
      @keydown.esc.prevent="hide"
      @click="onBackdrop"
    >
      <div ref="panelRef" :class="panel">
        <button
          type="button"
          :aria-label="props.closeLabel"
          :class="close"
          @click="hide"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            :class="icon"
          >
            <path d="M18 6 6 18M6 6l12 12" />
          </svg>
        </button>
        <div v-if="$slots.media" :class="dialogMedia">
          <slot name="media" />
        </div>
        <div :class="dialogBody">
          <h2 :id="`${cardId}-title`" :class="dialogTitle">
            {{ props.title }}
          </h2>
          <p v-if="props.description" :class="dialogDescription">
            {{ props.description }}
          </p>
          <div v-if="$slots.default" :class="details"><slot /></div>
          <div v-if="$slots.footer" :class="footerClass">
            <slot name="footer" />
          </div>
        </div>
      </div>
    </dialog>
  </div>
</template>
```

```vue
<template>
  <div class="grid grid-cols-2 gap-3">
    <ExpandableCard
      v-for="product in products"
      :key="product.id"
      :title="product.name"
      :description="product.summary"
    >
      <template #media>
        <img :src="product.image" alt="" class="size-full object-cover" />
      </template>
      <p class="text-base font-semibold">{{ product.price }}</p>
      <template #footer>
        <Button>Add to cart</Button>
      </template>
    </ExpandableCard>
  </div>
</template>
```

### Svelte

Save at `src/lib/components/markas/ExpandableCard.svelte`. No extra dependencies.

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

  const wrapper = "contents";
  const trigger =
    "group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0";
  const cardMedia = "block h-28 overflow-hidden rounded-lg bg-subtle";
  const cardText = "grid gap-1 px-1 pb-1";
  const cardTitle = "text-sm font-medium text-ink";
  const cardDescription = "line-clamp-2 text-sm text-muted";
  const expandIcon =
    "absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none";
  const dialogClass =
    "m-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
  const panel = "relative";
  const dialogMedia = "h-48 overflow-hidden bg-subtle";
  const dialogBody = "grid gap-3 p-5";
  const dialogTitle = "pr-10 text-lg font-semibold text-ink";
  const dialogDescription = "text-sm text-muted";
  const details = "grid gap-3 text-sm text-ink";
  const footerClass = "flex flex-wrap justify-end gap-2 pt-2";
  const close =
    "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
  const icon = "size-4";

  const OPEN_MS = 420;
  const CLOSE_MS = 320;
  const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";

  const canAnimate = (el: HTMLElement) =>
    typeof el.animate === "function" &&
    !(
      typeof matchMedia === "function" &&
      matchMedia("(prefers-reduced-motion: reduce)").matches
    );

  /** Transform that puts the dialog exactly over the card (FLIP "first" frame). */
  function overCard(card: DOMRect, dialog: HTMLElement) {
    const box = dialog.getBoundingClientRect();
    return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
  }

  /** Grow the dialog out of the card, or shrink it back into it. */
  function morph(
    dialog: HTMLElement,
    panelEl: HTMLElement,
    card: DOMRect,
    opening: boolean,
  ) {
    const duration = opening ? OPEN_MS : CLOSE_MS;
    // Stop a running grow or shrink first so the measurement below is not mid-flight.
    dialog
      .getAnimations?.({ subtree: true })
      .forEach((animation) => animation.cancel());
    const frames: Keyframe[] = [
      { transform: overCard(card, dialog), transformOrigin: "top left" },
      { transform: "none", transformOrigin: "top left" },
    ];
    const fade: Keyframe[] = [
      { opacity: 0 },
      { opacity: 0, offset: 0.35 },
      { opacity: 1 },
    ];
    // Closing holds the last frame until the dialog is closed, so it never flashes back to full size.
    const options: KeyframeAnimationOptions = {
      duration,
      easing: EASE,
      direction: opening ? "normal" : "reverse",
      fill: opening ? "none" : "forwards",
    };
    panelEl.animate(fade, options);
    dialog.animate([{ opacity: 0 }, { opacity: 1 }], {
      ...options,
      pseudoElement: "::backdrop",
    });
    return dialog.animate(frames, options);
  }

  type Props = Omit<HTMLButtonAttributes, "title" | "type"> & {
    title: string;
    /** Short text, clamped to two lines on the card and shown in full when open. */
    description?: string;
    /** Image or illustration shown on top of the card and the open view. */
    media?: Snippet;
    /** Actions at the bottom of the open view. */
    footer?: Snippet;
    closeLabel?: string;
    children?: Snippet;
  };

  let {
    title,
    description,
    media,
    footer,
    closeLabel = "Close",
    id,
    class: className,
    children,
    onclick,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const cardId = $derived(id ?? generatedId);
  const dialogId = $derived(`${cardId}-dialog`);
  let triggerEl = $state<HTMLButtonElement>();
  let dialogEl = $state<HTMLDialogElement>();
  let panelEl = $state<HTMLDivElement>();
  let closing = false;
  let open = $state(false);

  function show(event: MouseEvent & { currentTarget: HTMLButtonElement }) {
    onclick?.(event);
    if (event.defaultPrevented || !dialogEl || !triggerEl || dialogEl.open)
      return;
    const from = triggerEl.getBoundingClientRect();
    dialogEl.showModal();
    open = true;
    if (canAnimate(dialogEl) && panelEl) morph(dialogEl, panelEl, from, true);
  }

  function hide() {
    const dialog = dialogEl;
    if (!dialog?.open || closing) return;
    if (!triggerEl || !panelEl || !canAnimate(dialog)) {
      dialog.close();
      return;
    }
    closing = true;
    const animation = morph(
      dialog,
      panelEl,
      triggerEl.getBoundingClientRect(),
      false,
    );
    animation.onfinish = () => dialog.close();
  }

  function handleClosed() {
    dialogEl
      ?.getAnimations?.({ subtree: true })
      .forEach((animation) => animation.cancel());
    closing = false;
    open = false;
    triggerEl?.focus();
  }

  function handleCancel(event: Event) {
    event.preventDefault();
    hide();
  }

  function handleKeydown(event: KeyboardEvent) {
    if (event.key !== "Escape") return;
    event.preventDefault();
    hide();
  }

  function handleBackdrop(event: MouseEvent) {
    if (event.target === event.currentTarget) hide();
  }
</script>

<div class={wrapper}>
  <button
    bind:this={triggerEl}
    id={cardId}
    type="button"
    aria-haspopup="dialog"
    aria-controls={dialogId}
    data-state={open ? "open" : "closed"}
    class={[trigger, className]}
    onclick={show}
    {...rest}
  >
    {#if media}
      <span class={cardMedia}>{@render media()}</span>
    {/if}
    <span class={cardText}>
      <span class={cardTitle}>{title}</span>
      {#if description}
        <span class={cardDescription}>{description}</span>
      {/if}
    </span>
    <span aria-hidden="true" class={expandIcon}>
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        class={icon}
      >
        <path d="M12 5v14M5 12h14" />
      </svg>
    </span>
  </button>
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
  <!-- svelte-ignore a11y_click_events_have_key_events -->
  <dialog
    bind:this={dialogEl}
    id={dialogId}
    aria-labelledby={`${cardId}-title`}
    data-state={open ? "open" : "closed"}
    class={dialogClass}
    onclose={handleClosed}
    oncancel={handleCancel}
    onkeydown={handleKeydown}
    onclick={handleBackdrop}
  >
    <div bind:this={panelEl} class={panel}>
      <button
        type="button"
        aria-label={closeLabel}
        class={close}
        onclick={hide}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path d="M18 6 6 18M6 6l12 12" />
        </svg>
      </button>
      {#if media}
        <div class={dialogMedia}>{@render media()}</div>
      {/if}
      <div class={dialogBody}>
        <h2 id={`${cardId}-title`} class={dialogTitle}>{title}</h2>
        {#if description}
          <p class={dialogDescription}>{description}</p>
        {/if}
        {#if children}
          <div class={details}>{@render children()}</div>
        {/if}
        {#if footer}
          <div class={footerClass}>{@render footer()}</div>
        {/if}
      </div>
    </div>
  </dialog>
</div>
```

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

<div class="grid grid-cols-2 gap-3">
  {#each products as product (product.id)}
    <ExpandableCard title={product.name} description={product.summary}>
      {#snippet media()}
        <img src={product.image} alt="" class="size-full object-cover" />
      {/snippet}
      {#snippet footer()}
        <Button>Add to cart</Button>
      {/snippet}
      <p class="text-base font-semibold">{product.price}</p>
    </ExpandableCard>
  {/each}
</div>
```

### Astro

Save at `src/components/markas/ExpandableCard.astro`. No extra dependencies.

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

const wrapper = "contents";
const trigger =
  "group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0";
const cardMedia = "block h-28 overflow-hidden rounded-lg bg-subtle";
const cardText = "grid gap-1 px-1 pb-1";
const cardTitle = "text-sm font-medium text-ink";
const cardDescription = "line-clamp-2 text-sm text-muted";
const expandIcon =
  "absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none";
const dialogClass =
  "m-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "relative";
const dialogMedia = "h-48 overflow-hidden bg-subtle";
const dialogBody = "grid gap-3 p-5";
const dialogTitle = "pr-10 text-lg font-semibold text-ink";
const dialogDescription = "text-sm text-muted";
const details = "grid gap-3 text-sm text-ink";
const footerClass = "flex flex-wrap justify-end gap-2 pt-2";
const close =
  "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const icon = "size-4";

type Props = Omit<HTMLAttributes<"button">, "title" | "type"> & {
  title: string;
  /** Short text, clamped to two lines on the card and shown in full when open. */
  description?: string;
  closeLabel?: string;
};

const {
  title,
  description,
  closeLabel = "Close",
  id,
  class: className,
  ...rest
} = Astro.props;

const cardId = id ?? `markas-expandable-card-${crypto.randomUUID().slice(0, 8)}`;
const dialogId = `${cardId}-dialog`;
// Media shows on the card and in the open view, so it is rendered once and placed twice.
const media = Astro.slots.has("media") ? await Astro.slots.render("media") : "";
const hasDetails = Astro.slots.has("default");
const hasFooter = Astro.slots.has("footer");
---

<markas-expandable-card class={wrapper}>
  <button
    id={cardId}
    type="button"
    aria-haspopup="dialog"
    aria-controls={dialogId}
    data-state="closed"
    class:list={[trigger, className]}
    {...rest}
  >
    {media && <span class={cardMedia} set:html={media} />}
    <span class={cardText}>
      <span class={cardTitle}>{title}</span>
      {description && <span class={cardDescription}>{description}</span>}
    </span>
    <span aria-hidden="true" class={expandIcon}>
      <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      class={icon}
    >
      <path d="M12 5v14M5 12h14" />
    </svg>
    </span>
  </button>
  <dialog
    id={dialogId}
    aria-labelledby={`${cardId}-title`}
    data-state="closed"
    class={dialogClass}
  >
    <div class={panel}>
      <button type="button" aria-label={closeLabel} class={close} data-close>
        <svg
        aria-hidden="true"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        class={icon}
      >
        <path d="M18 6 6 18M6 6l12 12" />
      </svg>
      </button>
      {media && <div class={dialogMedia} set:html={media} />}
      <div class={dialogBody}>
        <h2 id={`${cardId}-title`} class={dialogTitle}>{title}</h2>
        {description && <p class={dialogDescription}>{description}</p>}
        {
          hasDetails && (
            <div class={details}>
              <slot />
            </div>
          )
        }
        {
          hasFooter && (
            <div class={footerClass}>
              <slot name="footer" />
            </div>
          )
        }
      </div>
    </div>
  </dialog>
</markas-expandable-card>

<script>
  const OPEN_MS = 420;
  const CLOSE_MS = 320;
  const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";

  const canAnimate = (el: HTMLElement) =>
    typeof el.animate === "function" &&
    !(
      typeof matchMedia === "function" &&
      matchMedia("(prefers-reduced-motion: reduce)").matches
    );

  /** Transform that puts the dialog exactly over the card (FLIP "first" frame). */
  function overCard(card: DOMRect, dialog: HTMLElement) {
    const box = dialog.getBoundingClientRect();
    return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
  }

  /** Grow the dialog out of the card, or shrink it back into it. */
  function morph(
    dialog: HTMLElement,
    panelEl: HTMLElement,
    card: DOMRect,
    opening: boolean,
  ) {
    const duration = opening ? OPEN_MS : CLOSE_MS;
    // Stop a running grow or shrink first so the measurement below is not mid-flight.
    dialog
      .getAnimations?.({ subtree: true })
      .forEach((animation) => animation.cancel());
    const frames: Keyframe[] = [
      { transform: overCard(card, dialog), transformOrigin: "top left" },
      { transform: "none", transformOrigin: "top left" },
    ];
    const fade: Keyframe[] = [
      { opacity: 0 },
      { opacity: 0, offset: 0.35 },
      { opacity: 1 },
    ];
    // Closing holds the last frame until the dialog is closed, so it never flashes back to full size.
    const options: KeyframeAnimationOptions = {
      duration,
      easing: EASE,
      direction: opening ? "normal" : "reverse",
      fill: opening ? "none" : "forwards",
    };
    panelEl.animate(fade, options);
    dialog.animate([{ opacity: 0 }, { opacity: 1 }], {
      ...options,
      pseudoElement: "::backdrop",
    });
    return dialog.animate(frames, options);
  }

  // Each card morphs into its own dialog, so it is a custom element: it also works for markup
  // added later and for pages reached through view transitions.
  class MarkasExpandableCard extends HTMLElement {
    private closing = false;
    private ready = false;

    connectedCallback() {
      const card = this.querySelector<HTMLButtonElement>("[aria-haspopup=dialog]");
      const dialog = this.querySelector("dialog");
      const panelEl = dialog?.firstElementChild;
      if (this.ready || !card || !dialog || !(panelEl instanceof HTMLElement)) return;
      this.ready = true;
      const setState = (state: string) => {
        card.dataset.state = state;
        dialog.dataset.state = state;
      };
      const hide = () => {
        if (!dialog.open || this.closing) return;
        if (!canAnimate(dialog)) {
          dialog.close();
          return;
        }
        this.closing = true;
        const animation = morph(dialog, panelEl, card.getBoundingClientRect(), false);
        animation.onfinish = () => dialog.close();
      };
      card.addEventListener("click", (event) => {
        if (event.defaultPrevented || dialog.open) return;
        const from = card.getBoundingClientRect();
        dialog.showModal();
        setState("open");
        if (canAnimate(dialog)) morph(dialog, panelEl, from, true);
      });
      dialog.addEventListener("close", () => {
        dialog
          .getAnimations?.({ subtree: true })
          .forEach((animation) => animation.cancel());
        this.closing = false;
        setState("closed");
        card.focus();
      });
      dialog.addEventListener("cancel", (event) => {
        event.preventDefault();
        hide();
      });
      dialog.addEventListener("keydown", (event) => {
        if (event.key !== "Escape") return;
        event.preventDefault();
        hide();
      });
      dialog.addEventListener("click", (event) => {
        const target = event.target as Element;
        if (target === dialog || target.closest("[data-close]")) hide();
      });
    }
  }

  if (!customElements.get("markas-expandable-card"))
    customElements.define("markas-expandable-card", MarkasExpandableCard);
</script>
```

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

<div class="grid grid-cols-2 gap-3">
  {
    products.map((product) => (
      <ExpandableCard title={product.name} description={product.summary}>
        <img slot="media" src={product.image} alt="" class="size-full object-cover" />
        <Button slot="footer">Add to cart</Button>
        <p class="text-base font-semibold">{product.price}</p>
      </ExpandableCard>
    ))
  }
</div>
```

The media slot is rendered once and shown on both the card and the open view. A small custom element opens the dialog and plays the grow and shrink.

### Angular

Save at `src/app/markas/expandable-card.component.ts`. No extra dependencies.

```ts
import { NgTemplateOutlet } from "@angular/common";
import {
  afterNextRender,
  ChangeDetectionStrategy,
  Component,
  computed,
  contentChild,
  Directive,
  type ElementRef,
  inject,
  input,
  signal,
  TemplateRef,
  viewChild,
} from "@angular/core";

const wrapper = "contents";
const trigger =
  "group relative grid w-full content-start gap-3 rounded-xl border border-line bg-surface p-3 text-left text-ink transition-[translate,border-color] duration-200 ease-out hover:-translate-y-0.5 hover:border-primary-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:opacity-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0";
const cardMedia = "block h-28 overflow-hidden rounded-lg bg-subtle";
const cardText = "grid gap-1 px-1 pb-1";
const cardTitle = "text-sm font-medium text-ink";
const cardDescription = "line-clamp-2 text-sm text-muted";
const expandIcon =
  "absolute top-5 right-5 inline-flex size-7 items-center justify-center rounded-full border border-line bg-surface text-ink transition-transform duration-200 ease-out group-hover:rotate-90 motion-reduce:transition-none";
const dialogClass =
  "m-auto max-h-[calc(100%-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "relative";
const dialogMedia = "h-48 overflow-hidden bg-subtle";
const dialogBody = "grid gap-3 p-5";
const dialogTitle = "pr-10 text-lg font-semibold text-ink";
const dialogDescription = "text-sm text-muted";
const details = "grid gap-3 text-sm text-ink";
const footerClass = "flex flex-wrap justify-end gap-2 pt-2";
const close =
  "absolute top-3 right-3 z-10 inline-flex size-8 items-center justify-center rounded-full border border-line bg-surface text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const icon = "size-4";

const OPEN_MS = 420;
const CLOSE_MS = 320;
const EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";

const canAnimate = (el: HTMLElement) =>
  typeof el.animate === "function" &&
  !(
    typeof matchMedia === "function" &&
    matchMedia("(prefers-reduced-motion: reduce)").matches
  );

/** Transform that puts the dialog exactly over the card (FLIP "first" frame). */
function overCard(card: DOMRect, dialog: HTMLElement) {
  const box = dialog.getBoundingClientRect();
  return `translate(${card.left - box.left}px, ${card.top - box.top}px) scale(${card.width / box.width}, ${card.height / box.height})`;
}

/** Grow the dialog out of the card, or shrink it back into it. */
function morph(
  dialog: HTMLElement,
  panelEl: HTMLElement,
  card: DOMRect,
  opening: boolean,
) {
  const duration = opening ? OPEN_MS : CLOSE_MS;
  // Stop a running grow or shrink first so the measurement below is not mid-flight.
  dialog
    .getAnimations?.({ subtree: true })
    .forEach((animation) => animation.cancel());
  const frames: Keyframe[] = [
    { transform: overCard(card, dialog), transformOrigin: "top left" },
    { transform: "none", transformOrigin: "top left" },
  ];
  const fade: Keyframe[] = [
    { opacity: 0 },
    { opacity: 0, offset: 0.35 },
    { opacity: 1 },
  ];
  // Closing holds the last frame until the dialog is closed, so it never flashes back to full size.
  const options: KeyframeAnimationOptions = {
    duration,
    easing: EASE,
    direction: opening ? "normal" : "reverse",
    fill: opening ? "none" : "forwards",
  };
  panelEl.animate(fade, options);
  dialog.animate([{ opacity: 0 }, { opacity: 1 }], {
    ...options,
    pseudoElement: "::backdrop",
  });
  return dialog.animate(frames, options);
}

/** Media shown on the card and in the open view: `<ng-template markasCardMedia>...</ng-template>`. */
@Directive({ selector: "ng-template[markasCardMedia]" })
export class ExpandableCardMedia {
  readonly template = inject(TemplateRef);
}

let nextId = 0;

/**
 * Slots: `<ng-template markasCardMedia>` for the media, an element with the `footer` attribute
 * for the actions, everything else is the detail text of the open view.
 * Host stays out of layout; id and class move to the card button.
 */
@Component({
  selector: "markas-expandable-card",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents", "[attr.id]": "null", "[attr.title]": "null" },
  template: `
    <div [class]="wrapper">
      <button
        #triggerEl
        [id]="cardId()"
        type="button"
        aria-haspopup="dialog"
        [attr.aria-controls]="dialogId()"
        [attr.data-state]="open() ? 'open' : 'closed'"
        [class]="triggerClasses()"
        (click)="show()"
      >
        @if (media(); as item) {
          <span [class]="cardMedia"
            ><ng-container [ngTemplateOutlet]="item.template"
          /></span>
        }
        <span [class]="cardText">
          <span [class]="cardTitle">{{ title() }}</span>
          @if (description()) {
            <span [class]="cardDescription">{{ description() }}</span>
          }
        </span>
        <span aria-hidden="true" [class]="expandIcon">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            [class]="icon"
          >
            <path d="M12 5v14M5 12h14" />
          </svg>
        </span>
      </button>
      <dialog
        #dialogEl
        [id]="dialogId()"
        [attr.aria-labelledby]="cardId() + '-title'"
        [attr.data-state]="open() ? 'open' : 'closed'"
        [class]="dialogClass"
        (close)="handleClosed()"
        (cancel)="handleCancel($event)"
        (keydown)="handleKeydown($event)"
        (click)="handleBackdrop($event)"
      >
        <div #panelEl [class]="panel">
          <button
            type="button"
            [attr.aria-label]="closeLabel()"
            [class]="close"
            (click)="hide()"
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              [class]="icon"
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
          @if (media(); as item) {
            <div [class]="dialogMedia">
              <ng-container [ngTemplateOutlet]="item.template" />
            </div>
          }
          <div [class]="dialogBody">
            <h2 [id]="cardId() + '-title'" [class]="dialogTitle">
              {{ title() }}
            </h2>
            @if (description()) {
              <p [class]="dialogDescription">{{ description() }}</p>
            }
            <div #detailsEl [class]="details" [hidden]="!hasDetails()">
              <ng-content />
            </div>
            <div #footerEl [class]="footerClass" [hidden]="!hasFooter()">
              <ng-content select="[footer]" />
            </div>
          </div>
        </div>
      </dialog>
    </div>
  `,
})
export class ExpandableCard {
  readonly title = input.required<string>();
  /** Short text, clamped to two lines on the card and shown in full when open. */
  readonly description = input<string>();
  readonly closeLabel = input("Close");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly media = contentChild(ExpandableCardMedia);
  protected readonly wrapper = wrapper;
  protected readonly cardMedia = cardMedia;
  protected readonly cardText = cardText;
  protected readonly cardTitle = cardTitle;
  protected readonly cardDescription = cardDescription;
  protected readonly expandIcon = expandIcon;
  protected readonly dialogClass = dialogClass;
  protected readonly panel = panel;
  protected readonly dialogMedia = dialogMedia;
  protected readonly dialogBody = dialogBody;
  protected readonly dialogTitle = dialogTitle;
  protected readonly dialogDescription = dialogDescription;
  protected readonly details = details;
  protected readonly footerClass = footerClass;
  protected readonly close = close;
  protected readonly icon = icon;
  protected readonly open = signal(false);
  protected readonly hasDetails = signal(false);
  protected readonly hasFooter = signal(false);
  private readonly generatedId = `markas-expandable-card-${nextId++}`;
  protected readonly cardId = computed(() => this.id() ?? this.generatedId);
  protected readonly dialogId = computed(() => `${this.cardId()}-dialog`);
  protected readonly triggerClasses = computed(() =>
    [trigger, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly triggerEl =
    viewChild.required<ElementRef<HTMLButtonElement>>("triggerEl");
  private readonly dialogEl =
    viewChild.required<ElementRef<HTMLDialogElement>>("dialogEl");
  private readonly panelEl =
    viewChild.required<ElementRef<HTMLDivElement>>("panelEl");
  private readonly detailsEl =
    viewChild.required<ElementRef<HTMLDivElement>>("detailsEl");
  private readonly footerEl =
    viewChild.required<ElementRef<HTMLDivElement>>("footerEl");
  private closing = false;

  constructor() {
    // Projected content is only known after the first render.
    afterNextRender(() => {
      const details = this.detailsEl().nativeElement;
      this.hasDetails.set(
        details.childElementCount > 0 || Boolean(details.textContent?.trim()),
      );
      this.hasFooter.set(this.footerEl().nativeElement.childElementCount > 0);
    });
  }

  /** Opens the card. Also callable from a template reference: card.show(). */
  show() {
    const dialog = this.dialogEl().nativeElement;
    const card = this.triggerEl().nativeElement;
    if (dialog.open) return;
    const from = card.getBoundingClientRect();
    dialog.showModal();
    this.open.set(true);
    if (canAnimate(dialog))
      morph(dialog, this.panelEl().nativeElement, from, true);
  }

  protected hide() {
    const dialog = this.dialogEl().nativeElement;
    if (!dialog.open || this.closing) return;
    if (!canAnimate(dialog)) {
      dialog.close();
      return;
    }
    this.closing = true;
    const animation = morph(
      dialog,
      this.panelEl().nativeElement,
      this.triggerEl().nativeElement.getBoundingClientRect(),
      false,
    );
    animation.onfinish = () => dialog.close();
  }

  protected handleClosed() {
    this.dialogEl()
      .nativeElement.getAnimations?.({ subtree: true })
      .forEach((animation) => animation.cancel());
    this.closing = false;
    this.open.set(false);
    this.triggerEl().nativeElement.focus();
  }

  protected handleCancel(event: Event) {
    event.preventDefault();
    this.hide();
  }

  protected handleKeydown(event: KeyboardEvent) {
    if (event.key !== "Escape") return;
    event.preventDefault();
    this.hide();
  }

  protected handleBackdrop(event: MouseEvent) {
    if (event.target === event.currentTarget) this.hide();
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import {
  ExpandableCard,
  ExpandableCardMedia,
} from "./markas/expandable-card.component";

@Component({
  selector: "app-products",
  imports: [Button, ExpandableCard, ExpandableCardMedia],
  template: `
    @for (product of products; track product.id) {
      <markas-expandable-card
        [title]="product.name"
        [description]="product.summary"
      >
        <ng-template markasCardMedia>
          <img [src]="product.image" alt="" class="size-full object-cover" />
        </ng-template>
        <button markas-button footer>Add to cart</button>
        <p class="text-base font-semibold">{{ product.price }}</p>
      </markas-expandable-card>
    }
  `,
})
export class Products {
  products = [
    {
      id: 1,
      name: "Desk lamp",
      summary: "Warm light.",
      image: "/lamp.jpg",
      price: "$48",
    },
  ];
}
```

Media sits in an `ng-template markasCardMedia` because it is shown twice. An element with the `footer` attribute fills the action row.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `title` | `string` | - | Card title. Also the heading and accessible name of the open view. |
| `description` | `string` | - | Short summary. Clamped to two lines on the card, shown in full when open. |
| `media` | `Blade: named slot · React: ReactNode · Vue: #media slot` | - | Image or illustration. Rendered 112px tall on the card and 192px tall in the open view. |
| `children` | `Blade: default slot · React: children · Vue: default slot` | - | Extra detail shown only in the open view. |
| `footer` | `Blade: named slot · React: ReactNode · Vue: #footer slot` | - | Actions at the bottom of the open view, for example Add to cart. |
| `closeLabel` | `string` | Close | Accessible name of the close button. |
| `id` | `string` | auto | Id of the card button. The dialog uses the same id with a -dialog suffix. |
| `markasCardMedia` | `ng-template` | - | Angular only. Put the media in <ng-template markasCardMedia> (import ExpandableCardMedia), since it shows on the card and in the open view. An element with the footer attribute fills the actions. |

## Accessibility

- The card is a real button with aria-haspopup dialog, so Enter and Space open it.
- The detail view is a native modal dialog labelled by its heading. Focus moves inside and the page behind is inert.
- Escape, a backdrop click, or the close button closes it, and focus returns to the card.
- With reduced motion the dialog opens and closes instantly without the grow and shrink animation.

## Notes

- One component renders one card and its dialog. Arrange several in your own grid or list.
- Opening measures the card, shows the native modal dialog, and animates it from the card's box to the center (FLIP). Closing plays it backwards and the card reappears in place.
- Escape, a backdrop click, and the close button all run the shrink animation. Focus returns to the card.
- The media slot renders twice, once on the card and once in the dialog. Give images `alt=""` when the title already names them.
- Attributes and `class` go to the card button.
