# FAQ

Ready made FAQ section on native details and summary, with six layouts, optional search, category tabs, and FAQPage JSON-LD.

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

## When to use

A frequently asked questions block on a landing, pricing, or help page.

- Keep answers short and plain text; put links in the contact slot
- Use searchable for long lists and categories when questions fall into clear groups
- Enable schema only once per page, on the main FAQ

## Code

### Blade

Save at `resources/views/components/markas/faq.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'items' => [],
    'title' => '',
    'description' => '',
    'variant' => 'simple',
    'exclusive' => false,
    'schema' => false,
    'contact' => null,
    'searchLabel' => 'Search questions',
    'emptyLabel' => 'No questions match your search',
    'categoriesLabel' => 'Question categories',
])

@php
    $root = '@container w-full [interpolate-size:allow-keywords]';
    $layouts = [
        'simple' => ['root' => 'mx-auto grid max-w-3xl gap-8', 'header' => 'grid gap-2', 'list' => 'border-t border-line', 'item' => 'border-b border-line'],
        'split' => ['root' => 'grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12', 'header' => 'grid content-start gap-2', 'list' => 'border-t border-line', 'item' => 'border-b border-line'],
        'cards' => ['root' => 'grid gap-8', 'header' => 'grid gap-2', 'list' => 'grid items-start gap-3 @xl:grid-cols-2', 'item' => 'rounded-xl border border-line bg-surface px-5'],
        'centered' => ['root' => 'mx-auto grid max-w-2xl gap-8 text-center', 'header' => 'grid justify-items-center gap-2', 'list' => 'grid gap-2 text-left', 'item' => 'rounded-lg bg-subtle px-4'],
        'searchable' => ['root' => 'mx-auto grid max-w-3xl gap-6', 'header' => 'grid gap-2', 'list' => 'border-t border-line', 'item' => 'border-b border-line'],
        'categories' => ['root' => 'mx-auto grid max-w-3xl gap-6', 'header' => 'grid gap-2', 'list' => 'border-t border-line', 'item' => 'border-b border-line'],
    ];
    $titleClass = 'text-2xl font-semibold tracking-tight text-balance text-ink';
    $descriptionClass = 'max-w-prose text-sm text-pretty text-muted';
    $contactClass = 'text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4';
    $body = 'grid content-start gap-4';
    $details = 'group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none';
    $summary = 'flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden';
    $icon = 'size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none';
    $answer = 'pb-4 text-sm leading-relaxed text-pretty text-muted';
    $search = 'relative';
    $searchIcon = 'pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted';
    $searchInput = 'h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
    $status = 'contents';
    $empty = 'py-6 text-center text-sm text-muted';
    $tablist = 'flex flex-wrap gap-2';
    $tab = 'inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none';

    $layout = $layouts[$variant] ?? $layouts['simple'];
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-faq|'.(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-faq-'.hash('xxh32', $idKey.$idIndex);
    $searchable = $variant === 'searchable';
    $interactive = $searchable || $variant === 'categories';
    $hasContact = filled(trim((string) $contact));

    // Kelompokkan pertanyaan per kategori (varian categories) atau satu kelompok berisi semua pertanyaan.
    $groups = [];
    foreach (array_values($items) as $index => $item) {
        $groups[$variant === 'categories' ? (string) ($item['category'] ?? '') : ''][$index] = $item;
    }
    $categories = $variant === 'categories' ? array_keys($groups) : [];

    $schemaJson = json_encode([
        '@context' => 'https://schema.org',
        '@type' => 'FAQPage',
        'mainEntity' => array_map(fn ($item) => [
            '@type' => 'Question',
            'name' => $item['question'],
            'acceptedAnswer' => ['@type' => 'Answer', 'text' => $item['answer']],
        ], array_values($items)),
    ], JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
@endphp

<section
    @if ($interactive)
        x-data="{
            query: '',
            active: 0,
            texts: @js(array_map(fn ($item) => $item['question'].' '.$item['answer'], array_values($items))).map((text) => text.toLowerCase()),
            {{-- Pertanyaan cocok kalau teks pertanyaan atau jawabannya memuat kata kunci. --}}
            shows(index) {
                return this.texts[index].includes(this.query.trim().toLowerCase());
            },
            get none() {
                return ! this.texts.some((text, index) => this.shows(index));
            },
            {{-- Panah, Home, dan End memindahkan tab aktif (pola Tabs WAI-ARIA). --}}
            onTabKeydown(event) {
                const count = @js(count($categories));
                const target = { ArrowRight: (this.active + 1) % count, ArrowLeft: (this.active - 1 + count) % count, Home: 0, End: count - 1 }[event.key];
                if (target === undefined) return;
                event.preventDefault();
                this.active = target;
                this.$nextTick(() => document.getElementById(@js($id) + '-tab-' + target).focus());
            },
        }"
    @endif
    @if (filled($title)) aria-labelledby="{{ $id }}-title" @endif
    {{ $attributes->merge(['id' => $id])->class([$root]) }}
>
    <div class="{{ $layout['root'] }}">
        <div class="{{ $layout['header'] }}">
            @if (filled($title))
                <h2 id="{{ $id }}-title" class="{{ $titleClass }}">{{ $title }}</h2>
            @endif
            @if (filled($description))
                <p class="{{ $descriptionClass }}">{{ $description }}</p>
            @endif
            @if ($variant === 'split' && $hasContact)
                <div class="{{ $contactClass }}">{{ $contact }}</div>
            @endif
        </div>
        <div class="{{ $body }}">
            @if ($searchable)
                <div class="{{ $search }}">
                    <svg class="{{ $searchIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>
                    <input type="search" autocomplete="off" aria-label="{{ $searchLabel }}" placeholder="{{ $searchLabel }}" x-model="query" class="{{ $searchInput }}" />
                </div>
            @endif
            @if ($categories)
                <div role="tablist" aria-label="{{ $categoriesLabel }}" class="{{ $tablist }}" @keydown="onTabKeydown($event)">
                    @foreach ($categories as $index => $category)
                        <button
                            type="button"
                            role="tab"
                            id="{{ $id }}-tab-{{ $index }}"
                            aria-controls="{{ $id }}-panel-{{ $index }}"
                            aria-selected="{{ $index === 0 ? 'true' : 'false' }}"
                            tabindex="{{ $index === 0 ? '0' : '-1' }}"
                            data-state="{{ $index === 0 ? 'active' : 'inactive' }}"
                            :aria-selected="active === {{ $index }} ? 'true' : 'false'"
                            :tabindex="active === {{ $index }} ? 0 : -1"
                            :data-state="active === {{ $index }} ? 'active' : 'inactive'"
                            @click="active = {{ $index }}"
                            class="{{ $tab }}"
                        >{{ $category }}</button>
                    @endforeach
                </div>
            @endif
            @foreach (array_values($groups) as $groupIndex => $group)
                <div
                    @if ($categories)
                        role="tabpanel"
                        id="{{ $id }}-panel-{{ $groupIndex }}"
                        aria-labelledby="{{ $id }}-tab-{{ $groupIndex }}"
                        @if ($groupIndex !== 0) hidden @endif
                        :hidden="active !== {{ $groupIndex }}"
                    @endif
                    class="{{ $layout['list'] }}"
                >
                    @foreach ($group as $index => $item)
                        <details
                            wire:ignore.self
                            class="{{ $details }} {{ $layout['item'] }}"
                            @if ($exclusive) name="{{ $id }}-item" @endif
                            @if ($searchable) :hidden="! shows({{ $index }})" @endif
                        >
                            <summary class="{{ $summary }}">
                                <span>{{ $item['question'] }}</span>
                                <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14" /></svg>
                            </summary>
                            <p class="{{ $answer }}">{{ $item['answer'] }}</p>
                        </details>
                    @endforeach
                </div>
            @endforeach
            @if ($searchable)
                <div role="status" class="{{ $status }}">
                    <template x-if="none"><p class="{{ $empty }}">{{ $emptyLabel }}</p></template>
                </div>
            @endif
        </div>
        @if ($variant !== 'split' && $hasContact)
            <div class="{{ $contactClass }}">{{ $contact }}</div>
        @endif
    </div>
    @if ($schema)
        <script type="application/ld+json">{!! $schemaJson !!}</script>
    @endif
</section>
```

```blade
<x-markas.faq
    variant="split"
    title="Frequently asked questions"
    description="Everything you need to know about plans and billing."
    exclusive
    schema
    :items="[
        ['question' => 'Is there a free trial?', 'answer' => 'Yes. Every plan starts with a 14 day trial.'],
        ['question' => 'Can I cancel at any time?', 'answer' => 'Yes. Your plan stays active until the end of the period.'],
    ]"
>
    <x-slot:contact>Still have questions? <a href="/contact">Contact support</a></x-slot:contact>
</x-markas.faq>

<x-markas.faq variant="searchable" title="Help center" :items="$faqs" />
```

### React

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

```tsx
"use client";

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

const root = "@container w-full [interpolate-size:allow-keywords]";
const header = "grid gap-2";
const lined = { list: "border-t border-line", item: "border-b border-line" };
const withTools = { root: "mx-auto grid max-w-3xl gap-6", header, ...lined };
const layouts = {
  simple: { root: "mx-auto grid max-w-3xl gap-8", header, ...lined },
  split: {
    root: "grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12",
    header: "grid content-start gap-2",
    ...lined,
  },
  cards: {
    root: "grid gap-8",
    header,
    list: "grid items-start gap-3 @xl:grid-cols-2",
    item: "rounded-xl border border-line bg-surface px-5",
  },
  centered: {
    root: "mx-auto grid max-w-2xl gap-8 text-center",
    header: "grid justify-items-center gap-2",
    list: "grid gap-2 text-left",
    item: "rounded-lg bg-subtle px-4",
  },
  searchable: withTools,
  categories: withTools,
};
const titleClass =
  "text-2xl font-semibold tracking-tight text-balance text-ink";
const descriptionClass = "max-w-prose text-sm text-pretty text-muted";
const contactClass =
  "text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4";
const body = "grid content-start gap-4";
const details =
  "group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none";
const summary =
  "flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden";
const icon =
  "size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none";
const answer = "pb-4 text-sm leading-relaxed text-pretty text-muted";
const search = "relative";
const searchIcon =
  "pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted";
const searchInput =
  "h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const status = "contents";
const empty = "py-6 text-center text-sm text-muted";
const tablist = "flex flex-wrap gap-2";
const tab =
  "inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none";

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

export type FaqItem = { question: string; answer: string; category?: string };
export type FaqVariant = keyof typeof layouts;

/** Pertanyaan cocok kalau teks pertanyaan atau jawabannya memuat kata kunci. */
const matches = (item: FaqItem, query: string) =>
  `${item.question} ${item.answer}`
    .toLowerCase()
    .includes(query.trim().toLowerCase());

/** Data terstruktur FAQPage untuk mesin pencari. `<` di-escape supaya tidak bisa menutup tag script. */
const faqSchema = (items: FaqItem[]) =>
  JSON.stringify({
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: items.map((item) => ({
      "@type": "Question",
      name: item.question,
      acceptedAnswer: { "@type": "Answer", text: item.answer },
    })),
  }).replace(/</g, "\\u003c");

/** Indeks tab tujuan untuk tombol panah, Home, dan End (pola Tabs WAI-ARIA). */
const targetTab = (key: string, index: number, count: number) =>
  ({
    ArrowRight: (index + 1) % count,
    ArrowLeft: (index - 1 + count) % count,
    Home: 0,
    End: count - 1,
  })[key];

export type FaqProps = Omit<ComponentProps<"section">, "title"> & {
  items: FaqItem[];
  title?: string;
  description?: string;
  variant?: FaqVariant;
  exclusive?: boolean;
  schema?: boolean;
  contact?: ReactNode;
  searchLabel?: string;
  emptyLabel?: string;
  categoriesLabel?: string;
};

export function Faq({
  items,
  title = "",
  description = "",
  variant = "simple",
  exclusive = false,
  schema = false,
  contact,
  searchLabel = "Search questions",
  emptyLabel = "No questions match your search",
  categoriesLabel = "Question categories",
  id,
  className,
  ...props
}: FaqProps) {
  const generatedId = useId();
  const baseId = id ?? generatedId;
  const [query, setQuery] = useState("");
  const [active, setActive] = useState(0);
  const layout = layouts[variant];
  const searchable = variant === "searchable";
  const categories =
    variant === "categories"
      ? [...new Set(items.map((item) => item.category ?? ""))]
      : [];
  /** Satu panel per kategori (varian categories) atau satu daftar berisi semua pertanyaan. */
  const groups = categories.length
    ? categories.map((category) =>
        items.filter((item) => (item.category ?? "") === category),
      )
    : [items];
  const noMatches = searchable && !items.some((item) => matches(item, query));

  const focusTab = (index: number) => {
    setActive(index);
    document.getElementById(`${baseId}-tab-${index}`)?.focus();
  };
  const onTabKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const target = targetTab(event.key, active, categories.length);
    if (target === undefined) return;
    event.preventDefault();
    focusTab(target);
  };

  const renderItem = (item: FaqItem) => (
    <details
      key={item.question}
      className={cx(details, layout.item)}
      name={exclusive ? `${baseId}-item` : undefined}
      hidden={searchable && !matches(item, query)}
    >
      <summary className={summary}>
        <span>{item.question}</span>
        <svg
          className={icon}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          aria-hidden="true"
        >
          <path d="M12 5v14M5 12h14" />
        </svg>
      </summary>
      <p className={answer}>{item.answer}</p>
    </details>
  );
  const contactBlock = contact ? (
    <div className={contactClass}>{contact}</div>
  ) : null;

  return (
    <section
      id={baseId}
      aria-labelledby={title ? `${baseId}-title` : undefined}
      className={cx(root, className)}
      {...props}
    >
      <div className={layout.root}>
        <div className={layout.header}>
          {title ? (
            <h2 id={`${baseId}-title`} className={titleClass}>
              {title}
            </h2>
          ) : null}
          {description ? (
            <p className={descriptionClass}>{description}</p>
          ) : null}
          {variant === "split" ? contactBlock : null}
        </div>
        <div className={body}>
          {searchable ? (
            <div className={search}>
              <svg
                className={searchIcon}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                aria-hidden="true"
              >
                <circle cx="11" cy="11" r="7" />
                <path d="m20 20-3.5-3.5" />
              </svg>
              <input
                type="search"
                autoComplete="off"
                aria-label={searchLabel}
                placeholder={searchLabel}
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                className={searchInput}
              />
            </div>
          ) : null}
          {categories.length ? (
            <div
              role="tablist"
              aria-label={categoriesLabel}
              className={tablist}
              onKeyDown={onTabKeyDown}
            >
              {categories.map((category, index) => (
                <button
                  key={category}
                  type="button"
                  role="tab"
                  id={`${baseId}-tab-${index}`}
                  aria-controls={`${baseId}-panel-${index}`}
                  aria-selected={index === active}
                  tabIndex={index === active ? 0 : -1}
                  data-state={index === active ? "active" : "inactive"}
                  onClick={() => setActive(index)}
                  className={tab}
                >
                  {category}
                </button>
              ))}
            </div>
          ) : null}
          {groups.map((group, index) => {
            const panel = categories.length > 0;
            return (
              <div
                key={index}
                role={panel ? "tabpanel" : undefined}
                id={panel ? `${baseId}-panel-${index}` : undefined}
                aria-labelledby={panel ? `${baseId}-tab-${index}` : undefined}
                hidden={panel && index !== active}
                className={layout.list}
              >
                {group.map(renderItem)}
              </div>
            );
          })}
          {searchable ? (
            <div role="status" className={status}>
              {noMatches ? <p className={empty}>{emptyLabel}</p> : null}
            </div>
          ) : null}
        </div>
        {variant === "split" ? null : contactBlock}
      </div>
      {schema ? (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: faqSchema(items) }}
        />
      ) : null}
    </section>
  );
}
```

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

<Faq
  variant="split"
  title="Frequently asked questions"
  items={faqs}
  exclusive
  schema
  contact={
    <>
      Still have questions? <a href="/contact">Contact support</a>
    </>
  }
/>

<Faq variant="categories" title="Help center" items={faqsWithCategory} />
```

### Vue

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

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

export type FaqItem = { question: string; answer: string; category?: string };
export type FaqVariant =
  "simple" | "split" | "cards" | "centered" | "searchable" | "categories";

const props = withDefaults(
  defineProps<{
    items: FaqItem[];
    title?: string;
    description?: string;
    variant?: FaqVariant;
    exclusive?: boolean;
    schema?: boolean;
    contact?: string;
    id?: string;
    searchLabel?: string;
    emptyLabel?: string;
    categoriesLabel?: string;
  }>(),
  {
    title: "",
    description: "",
    variant: "simple",
    exclusive: false,
    schema: false,
    contact: "",
    id: undefined,
    searchLabel: "Search questions",
    emptyLabel: "No questions match your search",
    categoriesLabel: "Question categories",
  },
);
const slots = useSlots();

const root = "@container w-full [interpolate-size:allow-keywords]";
const header = "grid gap-2";
const lined = { list: "border-t border-line", item: "border-b border-line" };
const withTools = { root: "mx-auto grid max-w-3xl gap-6", header, ...lined };
const layouts = {
  simple: { root: "mx-auto grid max-w-3xl gap-8", header, ...lined },
  split: {
    root: "grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12",
    header: "grid content-start gap-2",
    ...lined,
  },
  cards: {
    root: "grid gap-8",
    header,
    list: "grid items-start gap-3 @xl:grid-cols-2",
    item: "rounded-xl border border-line bg-surface px-5",
  },
  centered: {
    root: "mx-auto grid max-w-2xl gap-8 text-center",
    header: "grid justify-items-center gap-2",
    list: "grid gap-2 text-left",
    item: "rounded-lg bg-subtle px-4",
  },
  searchable: withTools,
  categories: withTools,
};
const titleClass =
  "text-2xl font-semibold tracking-tight text-balance text-ink";
const descriptionClass = "max-w-prose text-sm text-pretty text-muted";
const contactClass =
  "text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4";
const body = "grid content-start gap-4";
const details =
  "group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none";
const summary =
  "flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden";
const icon =
  "size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none";
const answer = "pb-4 text-sm leading-relaxed text-pretty text-muted";
const search = "relative";
const searchIcon =
  "pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted";
const searchInput =
  "h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const status = "contents";
const empty = "py-6 text-center text-sm text-muted";
const tablist = "flex flex-wrap gap-2";
const tab =
  "inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none";

/** Pertanyaan cocok kalau teks pertanyaan atau jawabannya memuat kata kunci. */
const matches = (item: FaqItem, query: string) =>
  `${item.question} ${item.answer}`
    .toLowerCase()
    .includes(query.trim().toLowerCase());

/** Data terstruktur FAQPage untuk mesin pencari. `<` di-escape supaya tidak bisa menutup tag script. */
const faqSchema = (items: FaqItem[]) =>
  JSON.stringify({
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: items.map((item) => ({
      "@type": "Question",
      name: item.question,
      acceptedAnswer: { "@type": "Answer", text: item.answer },
    })),
  }).replace(/</g, "\\u003c");

/** Tag script JSON-LD. innerHTML dipakai supaya isi tidak di-escape saat SSR. */
const JsonLd = (p: { json: string }) =>
  h("script", { type: "application/ld+json", innerHTML: p.json });

/** Indeks tab tujuan untuk tombol panah, Home, dan End (pola Tabs WAI-ARIA). */
const targetTab = (key: string, index: number, count: number) =>
  ({
    ArrowRight: (index + 1) % count,
    ArrowLeft: (index - 1 + count) % count,
    Home: 0,
    End: count - 1,
  })[key];

const generatedId = useId();
const baseId = computed(() => props.id ?? generatedId);
const query = ref("");
const active = ref(0);
const layout = computed(() => layouts[props.variant]);
const searchable = computed(() => props.variant === "searchable");
const categories = computed(() =>
  props.variant === "categories"
    ? [...new Set(props.items.map((item) => item.category ?? ""))]
    : [],
);
const noMatches = computed(
  () =>
    searchable.value && !props.items.some((item) => matches(item, query.value)),
);
const hasContact = computed(() => Boolean(slots.contact || props.contact));
/** Satu panel per kategori (varian categories) atau satu daftar berisi semua pertanyaan. */
const groups = computed(() =>
  categories.value.length
    ? categories.value.map((category) =>
        props.items.filter((item) => (item.category ?? "") === category),
      )
    : [props.items],
);

async function onTabKeydown(event: KeyboardEvent) {
  const target = targetTab(event.key, active.value, categories.value.length);
  if (target === undefined) return;
  event.preventDefault();
  active.value = target;
  await nextTick();
  document.getElementById(`${baseId.value}-tab-${target}`)?.focus();
}
</script>

<template>
  <section
    :id="baseId"
    :aria-labelledby="props.title ? `${baseId}-title` : undefined"
    :class="root"
  >
    <div :class="layout.root">
      <div :class="layout.header">
        <h2 v-if="props.title" :id="`${baseId}-title`" :class="titleClass">
          {{ props.title }}
        </h2>
        <p v-if="props.description" :class="descriptionClass">
          {{ props.description }}
        </p>
        <div
          v-if="props.variant === 'split' && hasContact"
          :class="contactClass"
        >
          <slot name="contact">{{ props.contact }}</slot>
        </div>
      </div>
      <div :class="body">
        <div v-if="searchable" :class="search">
          <svg
            :class="searchIcon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            aria-hidden="true"
          >
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3.5-3.5" />
          </svg>
          <input
            v-model="query"
            type="search"
            autocomplete="off"
            :aria-label="props.searchLabel"
            :placeholder="props.searchLabel"
            :class="searchInput"
          />
        </div>
        <div
          v-if="categories.length"
          role="tablist"
          :aria-label="props.categoriesLabel"
          :class="tablist"
          @keydown="onTabKeydown"
        >
          <button
            v-for="(category, index) in categories"
            :id="`${baseId}-tab-${index}`"
            :key="category"
            type="button"
            role="tab"
            :aria-controls="`${baseId}-panel-${index}`"
            :aria-selected="index === active ? 'true' : 'false'"
            :tabindex="index === active ? 0 : -1"
            :data-state="index === active ? 'active' : 'inactive'"
            :class="tab"
            @click="active = index"
          >
            {{ category }}
          </button>
        </div>
        <div
          v-for="(group, index) in groups"
          :id="categories.length ? `${baseId}-panel-${index}` : undefined"
          :key="index"
          :role="categories.length ? 'tabpanel' : undefined"
          :aria-labelledby="
            categories.length ? `${baseId}-tab-${index}` : undefined
          "
          :hidden="categories.length > 0 && index !== active"
          :class="layout.list"
        >
          <details
            v-for="item in group"
            :key="item.question"
            :class="[details, layout.item]"
            :name="props.exclusive ? `${baseId}-item` : undefined"
            :hidden="searchable && !matches(item, query)"
          >
            <summary :class="summary">
              <span>{{ item.question }}</span>
              <svg
                :class="icon"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                aria-hidden="true"
              >
                <path d="M12 5v14M5 12h14" />
              </svg>
            </summary>
            <p :class="answer">{{ item.answer }}</p>
          </details>
        </div>
        <div v-if="searchable" role="status" :class="status">
          <p v-if="noMatches" :class="empty">{{ props.emptyLabel }}</p>
        </div>
      </div>
      <div v-if="props.variant !== 'split' && hasContact" :class="contactClass">
        <slot name="contact">{{ props.contact }}</slot>
      </div>
    </div>
    <JsonLd v-if="props.schema" :json="faqSchema(props.items)" />
  </section>
</template>
```

```vue
<template>
  <Faq
    variant="split"
    title="Frequently asked questions"
    :items="faqs"
    exclusive
    schema
  >
    <template #contact>
      Still have questions? <a href="/contact">Contact support</a>
    </template>
  </Faq>

  <Faq variant="searchable" title="Help center" :items="faqs" />
</template>
```

### Svelte

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

```svelte
<script module lang="ts">
  export type FaqItem = { question: string; answer: string; category?: string };
  export type FaqVariant =
    "simple" | "split" | "cards" | "centered" | "searchable" | "categories";
</script>

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

  const root = "@container w-full [interpolate-size:allow-keywords]";
  const header = "grid gap-2";
  const lined = { list: "border-t border-line", item: "border-b border-line" };
  const withTools = { root: "mx-auto grid max-w-3xl gap-6", header, ...lined };
  const layouts = {
    simple: { root: "mx-auto grid max-w-3xl gap-8", header, ...lined },
    split: {
      root: "grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12",
      header: "grid content-start gap-2",
      ...lined,
    },
    cards: {
      root: "grid gap-8",
      header,
      list: "grid items-start gap-3 @xl:grid-cols-2",
      item: "rounded-xl border border-line bg-surface px-5",
    },
    centered: {
      root: "mx-auto grid max-w-2xl gap-8 text-center",
      header: "grid justify-items-center gap-2",
      list: "grid gap-2 text-left",
      item: "rounded-lg bg-subtle px-4",
    },
    searchable: withTools,
    categories: withTools,
  };
  const titleClass =
    "text-2xl font-semibold tracking-tight text-balance text-ink";
  const descriptionClass = "max-w-prose text-sm text-pretty text-muted";
  const contactClass =
    "text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4";
  const body = "grid content-start gap-4";
  const details =
    "group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none";
  const summary =
    "flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden";
  const icon =
    "size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none";
  const answer = "pb-4 text-sm leading-relaxed text-pretty text-muted";
  const search = "relative";
  const searchIcon =
    "pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted";
  const searchInput =
    "h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
  const status = "contents";
  const empty = "py-6 text-center text-sm text-muted";
  const tablist = "flex flex-wrap gap-2";
  const tab =
    "inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none";

  /** A question matches when its question or answer text contains the search term. */
  const matches = (item: FaqItem, query: string) =>
    `${item.question} ${item.answer}`
      .toLowerCase()
      .includes(query.trim().toLowerCase());

  /** FAQPage structured data for search engines. `<` is escaped so it cannot close the script tag. */
  const faqSchema = (items: FaqItem[]) =>
    JSON.stringify({
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: items.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: { "@type": "Answer", text: item.answer },
      })),
    }).replace(/</g, "\\u003c");

  /** Target tab index for the arrow keys, Home, and End (WAI-ARIA Tabs pattern). */
  const targetTab = (key: string, index: number, count: number) =>
    (
      ({
        ArrowRight: (index + 1) % count,
        ArrowLeft: (index - 1 + count) % count,
        Home: 0,
        End: count - 1,
      }) as Record<string, number>
    )[key];

  type Props = Omit<HTMLAttributes<HTMLElement>, "title"> & {
    items: FaqItem[];
    title?: string;
    description?: string;
    variant?: FaqVariant;
    exclusive?: boolean;
    schema?: boolean;
    /** Text or snippet below the questions (in the header for split). */
    contact?: Snippet | string;
    searchLabel?: string;
    emptyLabel?: string;
    categoriesLabel?: string;
  };

  let {
    items,
    title = "",
    description = "",
    variant = "simple",
    exclusive = false,
    schema = false,
    contact,
    searchLabel = "Search questions",
    emptyLabel = "No questions match your search",
    categoriesLabel = "Question categories",
    id,
    class: className,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const baseId = $derived(id ?? generatedId);
  let query = $state("");
  let active = $state(0);
  const layout = $derived(layouts[variant]);
  const searchable = $derived(variant === "searchable");
  const categories = $derived(
    variant === "categories"
      ? [...new Set(items.map((item) => item.category ?? ""))]
      : [],
  );
  /** One panel per category (categories variant) or one list with every question. */
  const groups = $derived(
    categories.length
      ? categories.map((category) =>
          items.filter((item) => (item.category ?? "") === category),
        )
      : [items],
  );
  const noMatches = $derived(
    searchable && !items.some((item) => matches(item, query)),
  );

  async function onTabKeydown(event: KeyboardEvent) {
    const target = targetTab(event.key, active, categories.length);
    if (target === undefined) return;
    event.preventDefault();
    active = target;
    await tick();
    document.getElementById(`${baseId}-tab-${target}`)?.focus();
  }
</script>

{#snippet contactBlock()}
  {#if contact}
    <div class={contactClass}>
      {#if typeof contact === "string"}{contact}{:else}{@render contact()}{/if}
    </div>
  {/if}
{/snippet}

<section
  id={baseId}
  aria-labelledby={title ? `${baseId}-title` : undefined}
  class={[root, className]}
  {...rest}
>
  <div class={layout.root}>
    <div class={layout.header}>
      {#if title}
        <h2 id={`${baseId}-title`} class={titleClass}>{title}</h2>
      {/if}
      {#if description}
        <p class={descriptionClass}>{description}</p>
      {/if}
      {#if variant === "split"}{@render contactBlock()}{/if}
    </div>
    <div class={body}>
      {#if searchable}
        <div class={search}>
          <svg
            class={searchIcon}
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            aria-hidden="true"
          >
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3.5-3.5" />
          </svg>
          <input
            type="search"
            autocomplete="off"
            aria-label={searchLabel}
            placeholder={searchLabel}
            bind:value={query}
            class={searchInput}
          />
        </div>
      {/if}
      {#if categories.length}
        <!-- svelte-ignore a11y_interactive_supports_focus -->
        <div
          role="tablist"
          aria-label={categoriesLabel}
          class={tablist}
          onkeydown={onTabKeydown}
        >
          {#each categories as category, index (category)}
            <button
              type="button"
              role="tab"
              id={`${baseId}-tab-${index}`}
              aria-controls={`${baseId}-panel-${index}`}
              aria-selected={index === active}
              tabindex={index === active ? 0 : -1}
              data-state={index === active ? "active" : "inactive"}
              onclick={() => (active = index)}
              class={tab}>{category}</button
            >
          {/each}
        </div>
      {/if}
      {#each groups as group, index (index)}
        {@const panel = categories.length > 0}
        <div
          role={panel ? "tabpanel" : undefined}
          id={panel ? `${baseId}-panel-${index}` : undefined}
          aria-labelledby={panel ? `${baseId}-tab-${index}` : undefined}
          hidden={panel && index !== active}
          class={layout.list}
        >
          {#each group as item (item.question)}
            <details
              class={[details, layout.item]}
              name={exclusive ? `${baseId}-item` : undefined}
              hidden={searchable && !matches(item, query)}
            >
              <summary class={summary}>
                <span>{item.question}</span>
                <svg
                  class={icon}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  aria-hidden="true"
                >
                  <path d="M12 5v14M5 12h14" />
                </svg>
              </summary>
              <p class={answer}>{item.answer}</p>
            </details>
          {/each}
        </div>
      {/each}
      {#if searchable}
        <div role="status" class={status}>
          {#if noMatches}
            <p class={empty}>{emptyLabel}</p>
          {/if}
        </div>
      {/if}
    </div>
    {#if variant !== "split"}{@render contactBlock()}{/if}
  </div>
  {#if schema}
    {@html `<script type="application/ld+json">${faqSchema(items)}</` +
      `script>`}
  {/if}
</section>
```

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

<Faq
  variant="split"
  title="Frequently asked questions"
  items={faqs}
  exclusive
  schema
>
  {#snippet contact()}
    Still have questions? <a href="/contact">Contact support</a>
  {/snippet}
</Faq>

<Faq variant="searchable" title="Help center" items={faqs} />
```

### Astro

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

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

const root = "@container w-full [interpolate-size:allow-keywords]";
const header = "grid gap-2";
const lined = { list: "border-t border-line", item: "border-b border-line" };
const withTools = { root: "mx-auto grid max-w-3xl gap-6", header, ...lined };
const layouts = {
  simple: { root: "mx-auto grid max-w-3xl gap-8", header, ...lined },
  split: {
    root: "grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12",
    header: "grid content-start gap-2",
    ...lined,
  },
  cards: {
    root: "grid gap-8",
    header,
    list: "grid items-start gap-3 @xl:grid-cols-2",
    item: "rounded-xl border border-line bg-surface px-5",
  },
  centered: {
    root: "mx-auto grid max-w-2xl gap-8 text-center",
    header: "grid justify-items-center gap-2",
    list: "grid gap-2 text-left",
    item: "rounded-lg bg-subtle px-4",
  },
  searchable: withTools,
  categories: withTools,
};
const titleClass =
  "text-2xl font-semibold tracking-tight text-balance text-ink";
const descriptionClass = "max-w-prose text-sm text-pretty text-muted";
const contactClass =
  "text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4";
const body = "grid content-start gap-4";
const details =
  "group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none";
const summary =
  "flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden";
const icon =
  "size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none";
const answer = "pb-4 text-sm leading-relaxed text-pretty text-muted";
const search = "relative";
const searchIcon =
  "pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted";
const searchInput =
  "h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const status = "contents";
const empty = "py-6 text-center text-sm text-muted";
const tablist = "flex flex-wrap gap-2";
const tab =
  "inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none";

export type FaqItem = { question: string; answer: string; category?: string };
export type FaqVariant = keyof typeof layouts;

/** FAQPage structured data for search engines. `<` is escaped so it cannot close the script tag. */
const faqSchema = (items: FaqItem[]) =>
  JSON.stringify({
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: items.map((item) => ({
      "@type": "Question",
      name: item.question,
      acceptedAnswer: { "@type": "Answer", text: item.answer },
    })),
  }).replace(/</g, "\\u003c");

type Props = Omit<HTMLAttributes<"section">, "title"> & {
  items: FaqItem[];
  title?: string;
  description?: string;
  variant?: FaqVariant;
  exclusive?: boolean;
  schema?: boolean;
  /** Text below the questions (in the header for split). The contact slot takes precedence. */
  contact?: string;
  searchLabel?: string;
  emptyLabel?: string;
  categoriesLabel?: string;
};

const {
  items,
  title = "",
  description = "",
  variant = "simple",
  exclusive = false,
  schema = false,
  contact = "",
  searchLabel = "Search questions",
  emptyLabel = "No questions match your search",
  categoriesLabel = "Question categories",
  id,
  class: className,
  ...rest
} = Astro.props;
const baseId = id ?? `markas-faq-${crypto.randomUUID().slice(0, 8)}`;
const layout = layouts[variant];
const searchable = variant === "searchable";
const categories =
  variant === "categories"
    ? [...new Set(items.map((item) => item.category ?? ""))]
    : [];
/** One panel per category (categories variant) or one list with every question. */
const groups = categories.length
  ? categories.map((category) =>
      items.filter((item) => (item.category ?? "") === category),
    )
  : [items];
const contactHtml = Astro.slots.has("contact")
  ? await Astro.slots.render("contact")
  : "";
const hasContact = Boolean(contactHtml || contact);
---

<section
  id={baseId}
  aria-labelledby={title ? `${baseId}-title` : undefined}
  data-markas-faq
  class:list={[root, className]}
  {...rest}
>
  <div class={layout.root}>
    <div class={layout.header}>
      {
        title && (
          <h2 id={`${baseId}-title`} class={titleClass}>
            {title}
          </h2>
        )
      }
      {description && <p class={descriptionClass}>{description}</p>}
      {
        variant === "split" && hasContact && (
          <div class={contactClass}>
            {contactHtml ? <Fragment set:html={contactHtml} /> : contact}
          </div>
        )
      }
    </div>
    <div class={body}>
      {
        searchable && (
          <div class={search}>
            <svg
              class={searchIcon}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              aria-hidden="true"
            >
              <circle cx="11" cy="11" r="7" />
              <path d="m20 20-3.5-3.5" />
            </svg>
            <input
              type="search"
              autocomplete="off"
              aria-label={searchLabel}
              placeholder={searchLabel}
              data-markas-faq-search
              class={searchInput}
            />
          </div>
        )
      }
      {
        categories.length > 0 && (
          <div role="tablist" aria-label={categoriesLabel} class={tablist}>
            {categories.map((category, index) => (
              <button
                type="button"
                role="tab"
                id={`${baseId}-tab-${index}`}
                aria-controls={`${baseId}-panel-${index}`}
                aria-selected={index === 0 ? "true" : "false"}
                tabindex={index === 0 ? 0 : -1}
                data-state={index === 0 ? "active" : "inactive"}
                class={tab}
              >
                {category}
              </button>
            ))}
          </div>
        )
      }
      {
        groups.map((group, index) => {
          const panel = categories.length > 0;
          return (
            <div
              role={panel ? "tabpanel" : undefined}
              id={panel ? `${baseId}-panel-${index}` : undefined}
              aria-labelledby={panel ? `${baseId}-tab-${index}` : undefined}
              hidden={panel && index !== 0}
              class={layout.list}
            >
              {group.map((item) => (
                <details
                  class:list={[details, layout.item]}
                  name={exclusive ? `${baseId}-item` : undefined}
                  data-text={`${item.question} ${item.answer}`.toLowerCase()}
                >
                  <summary class={summary}>
                    <span>{item.question}</span>
                    <svg
                      class={icon}
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      aria-hidden="true"
                    >
                      <path d="M12 5v14M5 12h14" />
                    </svg>
                  </summary>
                  <p class={answer}>{item.answer}</p>
                </details>
              ))}
            </div>
          );
        })
      }
      {
        searchable && (
          <div role="status" class={status}>
            <p class={empty} data-label={emptyLabel} hidden />
          </div>
        )
      }
    </div>
    {
      variant !== "split" && hasContact && (
        <div class={contactClass}>
          {contactHtml ? <Fragment set:html={contactHtml} /> : contact}
        </div>
      )
    }
  </div>
  {
    schema && (
      <script
        is:inline
        type="application/ld+json"
        set:html={faqSchema(items)}
      />
    )
  }
</section>

<script>
  // One set of listeners per page serves every FAQ, including markup added later and pages
  // reached through view transitions.
  const faqOf = (node: EventTarget | null) =>
    node instanceof Element ? node.closest("[data-markas-faq]") : null;

  /** A question matches when its question or answer text contains the search term. */
  document.addEventListener("input", (event) => {
    const input = event.target;
    if (
      !(input instanceof HTMLInputElement) ||
      !input.hasAttribute("data-markas-faq-search")
    )
      return;
    const faq = faqOf(input);
    if (!faq) return;
    const query = input.value.trim().toLowerCase();
    let shown = 0;
    faq.querySelectorAll<HTMLElement>("details[data-text]").forEach((item) => {
      const match = (item.dataset.text ?? "").includes(query);
      item.hidden = !match;
      if (match) shown += 1;
    });
    const message = faq.querySelector<HTMLElement>("[role=status] p");
    if (!message) return;
    message.hidden = shown > 0;
    message.textContent = shown > 0 ? "" : (message.dataset.label ?? "");
  });

  const selectTab = (tabs: HTMLElement[], index: number) => {
    tabs.forEach((tab, position) => {
      const active = position === index;
      tab.setAttribute("aria-selected", String(active));
      tab.tabIndex = active ? 0 : -1;
      tab.dataset.state = active ? "active" : "inactive";
      const panel = document.getElementById(
        tab.getAttribute("aria-controls") ?? "",
      );
      if (panel) panel.hidden = !active;
    });
  };
  const tabsOf = (tab: Element) =>
    [
      ...(tab.closest("[role=tablist]")?.querySelectorAll("[role=tab]") ?? []),
    ] as HTMLElement[];

  document.addEventListener("click", (event) => {
    const tab = (event.target as Element).closest?.<HTMLElement>("[role=tab]");
    if (!tab || !faqOf(tab)) return;
    const tabs = tabsOf(tab);
    selectTab(tabs, tabs.indexOf(tab));
  });

  /** Arrow keys, Home, and End move the active tab (WAI-ARIA Tabs pattern). */
  document.addEventListener("keydown", (event) => {
    const tab = (event.target as Element).closest?.<HTMLElement>("[role=tab]");
    if (!tab || !faqOf(tab)) return;
    const tabs = tabsOf(tab);
    const index = tabs.indexOf(tab);
    const count = tabs.length;
    const target = (
      {
        ArrowRight: (index + 1) % count,
        ArrowLeft: (index - 1 + count) % count,
        Home: 0,
        End: count - 1,
      } as Record<string, number>
    )[event.key];
    if (target === undefined) return;
    event.preventDefault();
    selectTab(tabs, target);
    tabs[target].focus();
  });
</script>
```

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

<Faq variant="split" title="Frequently asked questions" items={faqs} exclusive schema>
  <Fragment slot="contact">
    Still have questions? <a href="/contact">Contact support</a>
  </Fragment>
</Faq>

<Faq variant="categories" title="Help center" items={faqsWithCategory} />
```

searchable and categories use one small bundled script per page. The other variants ship no JavaScript.

### Angular

Save at `src/app/markas/faq.component.ts`. No extra dependencies.

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

const root = "@container w-full [interpolate-size:allow-keywords]";
const header = "grid gap-2";
const lined = { list: "border-t border-line", item: "border-b border-line" };
const withTools = { root: "mx-auto grid max-w-3xl gap-6", header, ...lined };
const layouts = {
  simple: { root: "mx-auto grid max-w-3xl gap-8", header, ...lined },
  split: {
    root: "grid gap-8 @2xl:grid-cols-[2fr_3fr] @2xl:gap-12",
    header: "grid content-start gap-2",
    ...lined,
  },
  cards: {
    root: "grid gap-8",
    header,
    list: "grid items-start gap-3 @xl:grid-cols-2",
    item: "rounded-xl border border-line bg-surface px-5",
  },
  centered: {
    root: "mx-auto grid max-w-2xl gap-8 text-center",
    header: "grid justify-items-center gap-2",
    list: "grid gap-2 text-left",
    item: "rounded-lg bg-subtle px-4",
  },
  searchable: withTools,
  categories: withTools,
};
const titleClass =
  "text-2xl font-semibold tracking-tight text-balance text-ink";
const descriptionClass = "max-w-prose text-sm text-pretty text-muted";
const contactClass =
  "text-sm text-muted [&_a]:font-medium [&_a]:text-ink [&_a]:underline [&_a]:underline-offset-4";
const body = "grid content-start gap-4";
const details =
  "group details-content:h-0 details-content:overflow-hidden details-content:transition-[height,content-visibility] details-content:transition-discrete details-content:duration-200 details-content:ease-out open:details-content:h-auto motion-reduce:details-content:transition-none";
const summary =
  "flex cursor-pointer list-none items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary [&::-webkit-details-marker]:hidden";
const icon =
  "size-4 shrink-0 text-muted transition-transform duration-200 ease-out group-open:rotate-45 motion-reduce:transition-none";
const answer = "pb-4 text-sm leading-relaxed text-pretty text-muted";
const search = "relative";
const searchIcon =
  "pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted";
const searchInput =
  "h-10 w-full rounded-lg border border-line bg-surface pr-3 pl-9 text-sm text-ink placeholder:text-faint focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const status = "contents";
const empty = "py-6 text-center text-sm text-muted";
const tablist = "flex flex-wrap gap-2";
const tab =
  "inline-flex h-8 items-center rounded-full border border-line px-3 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-on-primary motion-reduce:transition-none";

export type FaqItem = { question: string; answer: string; category?: string };
export type FaqVariant = keyof typeof layouts;

/** A question matches when its question or answer text contains the search term. */
const matches = (item: FaqItem, query: string) =>
  `${item.question} ${item.answer}`
    .toLowerCase()
    .includes(query.trim().toLowerCase());

/** FAQPage structured data for search engines. `<` is escaped so it cannot close the script tag. */
const faqSchema = (items: FaqItem[]) =>
  JSON.stringify({
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: items.map((item) => ({
      "@type": "Question",
      name: item.question,
      acceptedAnswer: { "@type": "Answer", text: item.answer },
    })),
  }).replace(/</g, "\\u003c");

/** Target tab index for the arrow keys, Home, and End (WAI-ARIA Tabs pattern). */
const targetTab = (key: string, index: number, count: number) =>
  (
    ({
      ArrowRight: (index + 1) % count,
      ArrowLeft: (index - 1 + count) % count,
      Home: 0,
      End: count - 1,
    }) as Record<string, number>
  )[key];

let nextId = 0;

/**
 * Contact: the `contact` text input or an element with the `contact` attribute (an
 * ng-container works). Host stays out of layout; id, title, and class move to the section.
 */
@Component({
  selector: "markas-faq",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents", "[attr.id]": "null", "[attr.title]": "null" },
  template: `
    <ng-template #contactSlot><ng-content select="[contact]" /></ng-template>
    <ng-template #contactBlock>
      <div #contactBox [class]="contactClass" [hidden]="!hasContact()">
        {{ contact() }}<ng-container [ngTemplateOutlet]="contactSlot" />
      </div>
    </ng-template>
    <section
      #section
      [id]="baseId()"
      [attr.aria-labelledby]="title() ? baseId() + '-title' : null"
      [class]="rootClasses()"
    >
      <div [class]="layout().root">
        <div [class]="layout().header">
          @if (title()) {
            <h2 [id]="baseId() + '-title'" [class]="titleClass">
              {{ title() }}
            </h2>
          }
          @if (description()) {
            <p [class]="descriptionClass">{{ description() }}</p>
          }
          @if (variant() === "split") {
            <ng-container [ngTemplateOutlet]="contactBlock" />
          }
        </div>
        <div [class]="body">
          @if (searchable()) {
            <div [class]="search">
              <svg
                [class]="searchIcon"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                aria-hidden="true"
              >
                <circle cx="11" cy="11" r="7" />
                <path d="m20 20-3.5-3.5" />
              </svg>
              <input
                #field
                type="search"
                autocomplete="off"
                [attr.aria-label]="searchLabel()"
                [placeholder]="searchLabel()"
                [value]="query()"
                (input)="query.set(field.value)"
                [class]="searchInput"
              />
            </div>
          }
          @if (categories().length) {
            <div
              role="tablist"
              [attr.aria-label]="categoriesLabel()"
              [class]="tablist"
              (keydown)="onTabKeydown($event)"
            >
              @for (
                category of categories();
                track category;
                let index = $index
              ) {
                <button
                  type="button"
                  role="tab"
                  [id]="baseId() + '-tab-' + index"
                  [attr.aria-controls]="baseId() + '-panel-' + index"
                  [attr.aria-selected]="index === active()"
                  [tabIndex]="index === active() ? 0 : -1"
                  [attr.data-state]="index === active() ? 'active' : 'inactive'"
                  (click)="active.set(index)"
                  [class]="tab"
                >
                  {{ category }}
                </button>
              }
            </div>
          }
          @for (group of groups(); track $index; let index = $index) {
            <div
              [attr.role]="hasPanels() ? 'tabpanel' : null"
              [attr.id]="hasPanels() ? baseId() + '-panel-' + index : null"
              [attr.aria-labelledby]="
                hasPanels() ? baseId() + '-tab-' + index : null
              "
              [hidden]="hasPanels() && index !== active()"
              [class]="layout().list"
            >
              @for (item of group; track item.question) {
                <details
                  [class]="details + ' ' + layout().item"
                  [attr.name]="exclusive() ? baseId() + '-item' : null"
                  [hidden]="searchable() && !matches(item, query())"
                >
                  <summary [class]="summary">
                    <span>{{ item.question }}</span>
                    <svg
                      [class]="icon"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      aria-hidden="true"
                    >
                      <path d="M12 5v14M5 12h14" />
                    </svg>
                  </summary>
                  <p [class]="answer">{{ item.answer }}</p>
                </details>
              }
            </div>
          }
          @if (searchable()) {
            <div role="status" [class]="status">
              @if (noMatches()) {
                <p [class]="empty">{{ emptyLabel() }}</p>
              }
            </div>
          }
        </div>
        @if (variant() !== "split") {
          <ng-container [ngTemplateOutlet]="contactBlock" />
        }
      </div>
    </section>
  `,
})
export class Faq {
  readonly items = input.required<FaqItem[]>();
  readonly title = input("");
  readonly description = input("");
  readonly variant = input<FaqVariant>("simple");
  readonly exclusive = input(false, { transform: booleanAttribute });
  readonly schema = input(false, { transform: booleanAttribute });
  /** Plain text contact line. For links, project an element with the contact attribute. */
  readonly contact = input("");
  readonly searchLabel = input("Search questions");
  readonly emptyLabel = input("No questions match your search");
  readonly categoriesLabel = input("Question categories");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly contactClass = contactClass;
  protected readonly titleClass = titleClass;
  protected readonly descriptionClass = descriptionClass;
  protected readonly body = body;
  protected readonly details = details;
  protected readonly summary = summary;
  protected readonly icon = icon;
  protected readonly answer = answer;
  protected readonly search = search;
  protected readonly searchIcon = searchIcon;
  protected readonly searchInput = searchInput;
  protected readonly status = status;
  protected readonly empty = empty;
  protected readonly tablist = tablist;
  protected readonly tab = tab;
  protected readonly matches = matches;

  protected readonly query = signal("");
  protected readonly active = signal(0);
  private readonly projectedContact = signal(false);
  private readonly generatedId = `markas-faq-${nextId++}`;
  protected readonly baseId = computed(() => this.id() ?? this.generatedId);
  protected readonly layout = computed(() => layouts[this.variant()]);
  protected readonly searchable = computed(
    () => this.variant() === "searchable",
  );
  protected readonly categories = computed(() =>
    this.variant() === "categories"
      ? [...new Set(this.items().map((item) => item.category ?? ""))]
      : [],
  );
  protected readonly hasPanels = computed(() => this.categories().length > 0);
  /** One panel per category (categories variant) or one list with every question. */
  protected readonly groups = computed(() =>
    this.hasPanels()
      ? this.categories().map((category) =>
          this.items().filter((item) => (item.category ?? "") === category),
        )
      : [this.items()],
  );
  protected readonly noMatches = computed(
    () =>
      this.searchable() &&
      !this.items().some((item) => matches(item, this.query())),
  );
  protected readonly hasContact = computed(
    () => this.projectedContact() || this.contact() !== "",
  );
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );

  private readonly section =
    viewChild.required<ElementRef<HTMLElement>>("section");
  private readonly contactBox =
    viewChild.required<ElementRef<HTMLElement>>("contactBox");
  private readonly renderer = inject(Renderer2);

  constructor() {
    // Projected content is only known after the first render.
    afterNextRender(() => {
      const box = this.contactBox().nativeElement;
      this.projectedContact.set(
        (box.textContent ?? "").trim() !== this.contact().trim(),
      );
    });
    // Angular strips script tags from templates, so the JSON-LD is added through the renderer.
    let script: HTMLScriptElement | null = null;
    effect(() => {
      const section = this.section().nativeElement;
      if (script) this.renderer.removeChild(section, script);
      script = null;
      if (!this.schema()) return;
      script = this.renderer.createElement("script") as HTMLScriptElement;
      this.renderer.setAttribute(script, "type", "application/ld+json");
      this.renderer.appendChild(
        script,
        this.renderer.createText(faqSchema(this.items())),
      );
      this.renderer.appendChild(section, script);
    });
  }

  protected onTabKeydown(event: KeyboardEvent) {
    const target = targetTab(
      event.key,
      this.active(),
      this.categories().length,
    );
    if (target === undefined) return;
    event.preventDefault();
    this.active.set(target);
    document.getElementById(`${this.baseId()}-tab-${target}`)?.focus();
  }
}
```

```ts
import { Component } from "@angular/core";
import { Faq, type FaqItem } from "./markas/faq.component";

@Component({
  selector: "app-help",
  imports: [Faq],
  template: `
    <markas-faq
      variant="split"
      title="Frequently asked questions"
      [items]="faqs"
      exclusive
      schema
    >
      <ng-container contact>
        Still have questions? <a href="/contact">Contact support</a>
      </ng-container>
    </markas-faq>
  `,
})
export class Help {
  faqs: FaqItem[] = [];
}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `{ question: string; answer: string; category?: string }[]` | [] | Questions with plain text answers. category is used by the categories variant. |
| `title` | `string` | '' | Section heading (h2). It also names the section landmark. |
| `description` | `string` | '' | Short text under the heading. |
| `variant` | `'simple' \| 'split' \| 'cards' \| 'centered' \| 'searchable' \| 'categories'` | 'simple' | Layout. split puts the heading beside the list on wide containers, cards uses a two column grid, searchable adds a filter box, categories adds tabs. |
| `exclusive` | `boolean` | false | Only one question open at a time, through a shared name attribute on details. |
| `schema` | `boolean` | false | Render FAQPage JSON-LD for search engines. |
| `contact` | `Blade: slot or string · React: ReactNode · Vue: slot or string` | - | Closing line such as "Still have questions?" with a link. Svelte: string or snippet. Astro: contact slot or string. Angular: contact text input or an element with the contact attribute. |
| `searchLabel` | `string` | 'Search questions' | Label and placeholder of the search box (searchable). |
| `emptyLabel` | `string` | 'No questions match your search' | Message announced when the search finds nothing (searchable). |
| `categoriesLabel` | `string` | 'Question categories' | Accessible name of the category tab list (categories). |

## Accessibility

- Questions use native details and summary, so Enter and Space open them without JavaScript.
- The section is labelled by its heading, and the plus icon is aria-hidden.
- The search box has an accessible name and the empty result is announced through a role status region.
- Category tabs follow the WAI-ARIA Tabs pattern: arrow keys, Home, and End move between tabs.

## Notes

- Opening and closing is native `details`, so simple, split, cards, and centered need no JavaScript. Heights animate with `::details-content` and `interpolate-size` where supported and simply snap elsewhere.
- searchable and categories need a little state. The Blade version needs Alpine.js for those two variants only.
- Layouts react to the section width through container queries, so split and cards stack inside narrow columns.
- `schema` prints FAQPage JSON-LD built from the same items. Use it once per page.
