# Hover Card

Kartu pratinjau berbasis Popover API yang muncul saat link di-hover atau difokus, untuk profil, repositori, dan pratinjau lain.

- Kategori: Overlay
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/hover-card.json
- CLI: `npx markasui@latest add hover-card`

## Kapan dipakai

Pratinjau isi di balik sebuah link, misalnya profil user, repositori, atau dokumen, tanpa pindah halaman.

- Pemicu harus satu elemen yang bisa difokus, biasanya link ke halaman lengkap
- Jangan menaruh informasi atau aksi yang hanya ada di dalam kartu
- Gunakan Tooltip untuk petunjuk teks singkat dan Popover untuk konten yang dibuka dengan klik

## Kode

### Blade

Simpan di `resources/views/components/markas/hover-card.blade.php`. Dependensi: alpinejs.

```blade
@props([])

@php
    $root = 'inline-block';
    $card = 'inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay';

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-hover-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-hover-card-'.hash('xxh32', $idKey.$idIndex);
@endphp

<span
    x-data="{
        open: false,
        timer: null,
        show() {
            clearTimeout(this.timer);
            {{-- Link again in case a re-render (Livewire morph) dropped aria-describedby from the trigger. --}}
            this.describe();
            this.$refs.card.showPopover();
        },
        showLater() {
            clearTimeout(this.timer);
            if (this.open) return;
            this.timer = setTimeout(() => this.show(), 400);
        },
        hide() {
            clearTimeout(this.timer);
            this.$refs.card.hidePopover();
        },
        {{-- Jeda singkat supaya pointer sempat pindah dari pemicu ke kartu. --}}
        hideLater() {
            clearTimeout(this.timer);
            this.timer = setTimeout(() => this.hide(), 100);
        },
        {{-- Fokus yang pindah ke dalam kartu (misalnya link di kartu) tidak menutup kartu. --}}
        onFocusOut(event) {
            if (! this.$root.contains(event.relatedTarget)) this.hide();
        },
        describe() {
            const trigger = this.$root.firstElementChild;
            const described = trigger?.getAttribute('aria-describedby') ?? '';
            if (trigger && trigger !== this.$refs.card && ! described.split(' ').includes(@js($id))) {
                trigger.setAttribute('aria-describedby', [described, @js($id)].filter(Boolean).join(' '));
            }
        },
        {{-- Letakkan kartu di bawah tengah pemicu, pindah ke atas kalau tidak muat. --}}
        place() {
            const gap = 8;
            const anchor = this.$root.getBoundingClientRect();
            const { width, height } = this.$refs.card.getBoundingClientRect();
            const above = anchor.top - gap - height;
            const below = anchor.bottom + gap;
            const onTop = below + height > window.innerHeight && above >= 0;
            this.$refs.card.style.top = (onTop ? above : below) + 'px';
            this.$refs.card.style.left = Math.max(gap, Math.min(anchor.left + anchor.width / 2 - width / 2, window.innerWidth - width - gap)) + 'px';
        },
        unfollow: null,
        {{-- Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. --}}
        follow() {
            this.unfollow?.();
            const update = () => this.place();
            const scrollOptions = { capture: true, passive: true };
            window.addEventListener('scroll', update, scrollOptions);
            window.addEventListener('resize', update, { passive: true });
            this.unfollow = () => {
                window.removeEventListener('scroll', update, scrollOptions);
                window.removeEventListener('resize', update);
                this.unfollow = null;
            };
        },
        destroy() {
            clearTimeout(this.timer);
            this.unfollow?.();
        },
        onToggle(event) {
            this.open = event.newState === 'open';
            if (! this.open) return this.unfollow?.();
            this.place();
            this.follow();
        },
    }"
    x-init="describe()"
    @mouseenter="showLater()"
    @mouseleave="hideLater()"
    @focusin="show()"
    @focusout="onFocusOut($event)"
    @keydown.escape.window="hide()"
    {{ $attributes->except('id')->class([$root]) }}
>{{ $slot }}<span
        x-ref="card"
        id="{{ $id }}"
        popover="manual"
        wire:ignore.self
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @toggle="onToggle($event)"
        class="{{ $card }}"
    >{{ $content ?? '' }}</span></span>
```

```blade
<x-markas.hover-card>
    <a href="https://github.com/markasui">@markasui</a>
    <x-slot:content>
        <p class="font-medium text-ink">Markas UI</p>
        <p class="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
    </x-slot:content>
</x-markas.hover-card>
```

Butuh Alpine.js.

### React

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

```tsx
"use client";

import {
  useEffect,
  useId,
  useRef,
  useState,
  type ComponentProps,
  type FocusEvent,
  type ReactNode,
  type ToggleEvent,
} from "react";

const root = "inline-block";
const card =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

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

const GAP = 8;
const SHOW_DELAY = 400;
/** Jeda singkat supaya pointer sempat pindah dari pemicu ke kartu. */
const HIDE_DELAY = 100;

/** Letakkan kartu di bawah tengah pemicu, pindah ke atas kalau tidak muat. */
function placeCard(trigger: HTMLElement, target: HTMLElement) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = target.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const onTop = below + height > window.innerHeight && above >= 0;
  const left = Math.max(
    GAP,
    Math.min(
      anchor.left + anchor.width / 2 - width / 2,
      window.innerWidth - width - GAP,
    ),
  );
  target.style.top = `${onTop ? above : below}px`;
  target.style.left = `${left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

export type HoverCardProps = Omit<ComponentProps<"span">, "content"> & {
  /** Isi kartu pratinjau. */
  content: ReactNode;
};

export function HoverCard({
  content,
  id,
  className,
  children,
  ...props
}: HoverCardProps) {
  const generatedId = useId();
  const cardId = id ?? generatedId;
  const rootRef = useRef<HTMLSpanElement>(null);
  const cardRef = useRef<HTMLSpanElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const [open, setOpen] = useState(false);

  const show = () => {
    clearTimeout(timer.current);
    cardRef.current?.showPopover();
  };
  const showLater = () => {
    clearTimeout(timer.current);
    if (open) return;
    timer.current = setTimeout(show, SHOW_DELAY);
  };
  const hide = () => {
    clearTimeout(timer.current);
    cardRef.current?.hidePopover();
  };
  const hideLater = () => {
    clearTimeout(timer.current);
    timer.current = setTimeout(hide, HIDE_DELAY);
  };
  // Fokus yang pindah ke dalam kartu (misalnya link di kartu) tidak menutup kartu.
  const handleBlur = (event: FocusEvent<HTMLSpanElement>) => {
    if (!rootRef.current?.contains(event.relatedTarget)) hide();
  };

  useEffect(() => {
    const trigger = rootRef.current?.firstElementChild;
    const described = trigger?.getAttribute("aria-describedby") ?? "";
    if (
      trigger &&
      trigger !== cardRef.current &&
      !described.split(" ").includes(cardId)
    )
      trigger.setAttribute(
        "aria-describedby",
        [described, cardId].filter(Boolean).join(" "),
      );

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      clearTimeout(timer.current);
      cardRef.current?.hidePopover();
    };
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      clearTimeout(timer.current);
    };
  }, [cardId]);

  useEffect(() => {
    if (!open) return;
    return followViewport(() => {
      if (rootRef.current && cardRef.current)
        placeCard(rootRef.current, cardRef.current);
    });
  }, [open]);

  const handleToggle = (event: ToggleEvent<HTMLSpanElement>) => {
    const isOpen = event.newState === "open";
    setOpen(isOpen);
    if (isOpen && rootRef.current && cardRef.current)
      placeCard(rootRef.current, cardRef.current);
  };

  return (
    <span
      ref={rootRef}
      {...props}
      className={cx(root, className)}
      onMouseEnter={showLater}
      onMouseLeave={hideLater}
      onFocus={show}
      onBlur={handleBlur}
    >
      {children}
      <span
        ref={cardRef}
        id={cardId}
        popover="manual"
        data-state={open ? "open" : "closed"}
        className={card}
        onToggle={handleToggle}
      >
        {content}
      </span>
    </span>
  );
}
```

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

<HoverCard
  content={
    <>
      <p className="font-medium text-ink">Markas UI</p>
      <p className="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
    </>
  }
>
  <a href="https://github.com/markasui">@markasui</a>
</HoverCard>;
```

### Vue

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

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

const props = withDefaults(defineProps<{ id?: string }>(), { id: undefined });

const root = "inline-block";
const card =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

const GAP = 8;
const SHOW_DELAY = 400;
/** Jeda singkat supaya pointer sempat pindah dari pemicu ke kartu. */
const HIDE_DELAY = 100;

/** Letakkan kartu di bawah tengah pemicu, pindah ke atas kalau tidak muat. */
function placeCard(trigger: HTMLElement, target: HTMLElement) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = target.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const onTop = below + height > window.innerHeight && above >= 0;
  const left = Math.max(
    GAP,
    Math.min(
      anchor.left + anchor.width / 2 - width / 2,
      window.innerWidth - width - GAP,
    ),
  );
  target.style.top = `${onTop ? above : below}px`;
  target.style.left = `${left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

const generatedId = useId();
const cardId = computed(() => props.id ?? generatedId);
const rootEl = useTemplateRef<HTMLSpanElement>("rootRef");
const cardEl = useTemplateRef<HTMLSpanElement>("cardRef");
const open = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;
let unfollow: (() => void) | undefined;

function show() {
  clearTimeout(timer);
  cardEl.value?.showPopover();
}

function showLater() {
  clearTimeout(timer);
  if (open.value) return;
  timer = setTimeout(show, SHOW_DELAY);
}

function hide() {
  clearTimeout(timer);
  cardEl.value?.hidePopover();
}

function hideLater() {
  clearTimeout(timer);
  timer = setTimeout(hide, HIDE_DELAY);
}

// Fokus yang pindah ke dalam kartu (misalnya link di kartu) tidak menutup kartu.
function onFocusOut(event: FocusEvent) {
  if (!rootEl.value?.contains(event.relatedTarget as Node | null)) hide();
}

function onKeydown(event: KeyboardEvent) {
  if (event.key === "Escape") hide();
}

function stopFollowing() {
  unfollow?.();
  unfollow = undefined;
}

function place() {
  if (rootEl.value && cardEl.value) placeCard(rootEl.value, cardEl.value);
}

function onToggle(event: Event) {
  stopFollowing();
  open.value = (event as ToggleEvent).newState === "open";
  if (!open.value) return;
  place();
  unfollow = followViewport(place);
}

onMounted(() => {
  const trigger = rootEl.value?.firstElementChild;
  const described = trigger?.getAttribute("aria-describedby") ?? "";
  if (
    trigger &&
    trigger !== cardEl.value &&
    !described.split(" ").includes(cardId.value)
  )
    trigger.setAttribute(
      "aria-describedby",
      [described, cardId.value].filter(Boolean).join(" "),
    );
  document.addEventListener("keydown", onKeydown);
});

onBeforeUnmount(() => {
  document.removeEventListener("keydown", onKeydown);
  clearTimeout(timer);
  stopFollowing();
});
</script>

<template>
  <span
    ref="rootRef"
    :class="root"
    @mouseenter="showLater"
    @mouseleave="hideLater"
    @focusin="show"
    @focusout="onFocusOut"
  >
    <slot />
    <span
      :id="cardId"
      ref="cardRef"
      popover="manual"
      :data-state="open ? 'open' : 'closed'"
      :class="card"
      @toggle="onToggle"
      ><slot name="content"
    /></span>
  </span>
</template>
```

```vue
<template>
  <HoverCard>
    <a href="https://github.com/markasui">@markasui</a>
    <template #content>
      <p class="font-medium text-ink">Markas UI</p>
      <p class="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
    </template>
  </HoverCard>
</template>
```

### Svelte

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

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

  const root = "inline-block";
  const card =
    "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

  const GAP = 8;
  const SHOW_DELAY = 400;
  /** Short delay so the pointer can move from the trigger to the card. */
  const HIDE_DELAY = 100;

  type Props = HTMLAttributes<HTMLSpanElement> & {
    /** Content of the preview card. */
    content?: Snippet;
    children?: Snippet;
  };

  let { content, id, class: className, children, ...rest }: Props = $props();

  const generatedId = $props.id();
  const cardId = $derived(id ?? generatedId);
  let rootEl = $state<HTMLSpanElement>();
  let cardEl = $state<HTMLSpanElement>();
  let open = $state(false);
  let timer: ReturnType<typeof setTimeout> | undefined;

  function show() {
    clearTimeout(timer);
    cardEl?.showPopover();
  }

  function showLater() {
    clearTimeout(timer);
    if (open) return;
    timer = setTimeout(show, SHOW_DELAY);
  }

  function hide() {
    clearTimeout(timer);
    cardEl?.hidePopover();
  }

  function hideLater() {
    clearTimeout(timer);
    timer = setTimeout(hide, HIDE_DELAY);
  }

  // Focus that moves into the card (a link in the card, for example) keeps it open.
  function handleFocusOut(event: FocusEvent) {
    if (!rootEl?.contains(event.relatedTarget as Node | null)) hide();
  }

  /** Place the card below the center of the trigger, flip above when it does not fit. */
  function place() {
    if (!rootEl || !cardEl) return;
    const anchor = rootEl.getBoundingClientRect();
    const { width, height } = cardEl.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const onTop = below + height > window.innerHeight && above >= 0;
    const left = Math.max(
      GAP,
      Math.min(
        anchor.left + anchor.width / 2 - width / 2,
        window.innerWidth - width - GAP,
      ),
    );
    cardEl.style.top = `${onTop ? above : below}px`;
    cardEl.style.left = `${left}px`;
  }

  function handleToggle(event: ToggleEvent) {
    open = event.newState === "open";
    if (open) place();
  }

  // The first element is the trigger: link it to the card. Escape hides the card anywhere.
  $effect(() => {
    const trigger = rootEl?.firstElementChild;
    const described = trigger?.getAttribute("aria-describedby") ?? "";
    if (trigger && trigger !== cardEl && !described.split(" ").includes(cardId))
      trigger.setAttribute(
        "aria-describedby",
        [described, cardId].filter(Boolean).join(" "),
      );

    const onKeydown = (event: KeyboardEvent) => {
      if (event.key === "Escape") hide();
    };
    document.addEventListener("keydown", onKeydown);
    return () => {
      document.removeEventListener("keydown", onKeydown);
      clearTimeout(timer);
    };
  });

  // Re-place while open when the page scrolls or the window resizes.
  $effect(() => {
    if (!open) return;
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", place, scrollOptions);
    window.addEventListener("resize", place, { passive: true });
    return () => {
      window.removeEventListener("scroll", place, scrollOptions);
      window.removeEventListener("resize", place);
    };
  });
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
  bind:this={rootEl}
  {...rest}
  class={[root, className]}
  onmouseenter={showLater}
  onmouseleave={hideLater}
  onfocusin={show}
  onfocusout={handleFocusOut}
>
  {@render children?.()}<span
    bind:this={cardEl}
    id={cardId}
    popover="manual"
    data-state={open ? "open" : "closed"}
    class={card}
    ontoggle={handleToggle}>{@render content?.()}</span
  >
</span>
```

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

<HoverCard>
  <a href="https://github.com/markasui">@markasui</a>
  {#snippet content()}
    <p class="font-medium text-ink">Markas UI</p>
    <p class="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
  {/snippet}
</HoverCard>
```

### Astro

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

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

const root = "inline-block";
const card =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

type Props = HTMLAttributes<"span">;

const { id, class: className, ...rest } = Astro.props;
const cardId = id ?? `markas-hover-card-${crypto.randomUUID().slice(0, 8)}`;
---

<markas-hover-card class="contents"
  ><span {...rest} class:list={[root, className]}
    ><slot /><span
      id={cardId}
      popover="manual"
      data-state="closed"
      class={card}><slot name="content" /></span
    ></span
  ></markas-hover-card
>

<script>
  const GAP = 8;
  const SHOW_DELAY = 400;
  /** Short delay so the pointer can move from the trigger to the card. */
  const HIDE_DELAY = 100;

  // Per instance: timers, the aria-describedby link, and placement while open.
  class MarkasHoverCard extends HTMLElement {
    private timer: ReturnType<typeof setTimeout> | undefined;
    private abort: AbortController | undefined;
    private open = false;

    private get root() {
      return this.firstElementChild as HTMLElement;
    }

    private get card() {
      return this.root.lastElementChild as HTMLElement;
    }

    connectedCallback() {
      const { root, card } = this;
      if (!root || !card) return;
      this.abort = new AbortController();
      const { signal } = this.abort;

      const trigger = root.firstElementChild;
      const described = trigger?.getAttribute("aria-describedby") ?? "";
      if (trigger && trigger !== card && !described.split(" ").includes(card.id))
        trigger.setAttribute(
          "aria-describedby",
          [described, card.id].filter(Boolean).join(" "),
        );

      root.addEventListener("mouseenter", () => this.showLater(), { signal });
      root.addEventListener("mouseleave", () => this.hideLater(), { signal });
      root.addEventListener("focusin", () => this.show(), { signal });
      // Focus that moves into the card (a link in the card, for example) keeps it open.
      root.addEventListener(
        "focusout",
        (event) => {
          if (!root.contains(event.relatedTarget as Node | null)) this.hide();
        },
        { signal },
      );
      card.addEventListener(
        "toggle",
        (event) => {
          this.open = (event as ToggleEvent).newState === "open";
          card.dataset.state = this.open ? "open" : "closed";
          if (this.open) this.place();
        },
        { signal },
      );
      document.addEventListener(
        "keydown",
        (event) => {
          if (event.key === "Escape") this.hide();
        },
        { signal },
      );
      // Re-place while open when the page scrolls or the window resizes.
      const update = () => {
        if (this.open) this.place();
      };
      window.addEventListener("scroll", update, {
        capture: true,
        passive: true,
        signal,
      });
      window.addEventListener("resize", update, { passive: true, signal });
    }

    disconnectedCallback() {
      clearTimeout(this.timer);
      this.abort?.abort();
    }

    private show() {
      clearTimeout(this.timer);
      this.card.showPopover();
    }

    private showLater() {
      clearTimeout(this.timer);
      if (this.open) return;
      this.timer = setTimeout(() => this.show(), SHOW_DELAY);
    }

    private hide() {
      clearTimeout(this.timer);
      this.card.hidePopover();
    }

    private hideLater() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => this.hide(), HIDE_DELAY);
    }

    /** Place the card below the center of the trigger, flip above when it does not fit. */
    private place() {
      const anchor = this.root.getBoundingClientRect();
      const { width, height } = this.card.getBoundingClientRect();
      const above = anchor.top - GAP - height;
      const below = anchor.bottom + GAP;
      const onTop = below + height > window.innerHeight && above >= 0;
      const left = Math.max(
        GAP,
        Math.min(
          anchor.left + anchor.width / 2 - width / 2,
          window.innerWidth - width - GAP,
        ),
      );
      this.card.style.top = `${onTop ? above : below}px`;
      this.card.style.left = `${left}px`;
    }
  }

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

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

<HoverCard>
  <a href="https://github.com/markasui">@markasui</a>
  <Fragment slot="content">
    <p class="font-medium text-ink">Markas UI</p>
    <p class="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
  </Fragment>
</HoverCard>
```

Setiap kartu dibungkus custom element kecil `markas-hover-card` dengan `display: contents`, jadi tetap jalan setelah view transition.

### Angular

Simpan di `src/app/markas/hover-card.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  afterNextRender,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  type ElementRef,
  inject,
  input,
  signal,
  viewChild,
} from "@angular/core";

const root = "inline-block";
const card =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

const GAP = 8;
const SHOW_DELAY = 400;
/** Short delay so the pointer can move from the trigger to the card. */
const HIDE_DELAY = 100;

let nextId = 0;

/**
 * Slots: an element with the `content` attribute (an ng-container works) fills the card,
 * everything else is the trigger. The first element of the trigger gets aria-describedby.
 * Host stays out of layout; id and class move to the root element and the card.
 */
@Component({
  selector: "markas-hover-card",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "(document:keydown.escape)": "hide()",
  },
  template: `<span
    #root
    [class]="rootClasses()"
    (mouseenter)="showLater()"
    (mouseleave)="hideLater()"
    (focusin)="show()"
    (focusout)="handleFocusOut($event)"
    ><ng-content /><span
      #cardEl
      [id]="cardId()"
      popover="manual"
      [attr.data-state]="open() ? 'open' : 'closed'"
      [class]="card"
      (toggle)="handleToggle($event)"
      ><ng-content select="[content]" /></span
  ></span>`,
})
export class HoverCard {
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly card = card;
  protected readonly open = signal(false);
  private readonly generatedId = `markas-hover-card-${nextId++}`;
  protected readonly cardId = computed(() => this.id() ?? this.generatedId);
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly rootRef =
    viewChild.required<ElementRef<HTMLSpanElement>>("root");
  private readonly cardRef =
    viewChild.required<ElementRef<HTMLSpanElement>>("cardEl");
  private timer: ReturnType<typeof setTimeout> | undefined;
  private readonly update = () => this.place();
  private readonly scrollOptions = { capture: true, passive: true };

  constructor() {
    // Projected content is only known after the first render.
    afterNextRender(() => this.describe());
    inject(DestroyRef).onDestroy(() => {
      clearTimeout(this.timer);
      this.stopFollowing();
    });
  }

  protected show() {
    clearTimeout(this.timer);
    this.cardRef().nativeElement.showPopover();
  }

  protected showLater() {
    clearTimeout(this.timer);
    if (this.open()) return;
    this.timer = setTimeout(() => this.show(), SHOW_DELAY);
  }

  protected hide() {
    clearTimeout(this.timer);
    this.cardRef().nativeElement.hidePopover();
  }

  protected hideLater() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => this.hide(), HIDE_DELAY);
  }

  // Focus that moves into the card (a link in the card, for example) keeps it open.
  protected handleFocusOut(event: FocusEvent) {
    if (
      !this.rootRef().nativeElement.contains(event.relatedTarget as Node | null)
    )
      this.hide();
  }

  protected handleToggle(event: Event) {
    this.stopFollowing();
    const isOpen = (event as ToggleEvent).newState === "open";
    this.open.set(isOpen);
    if (!isOpen) return;
    this.place();
    // Re-place while open when the page scrolls or the window resizes.
    window.addEventListener("scroll", this.update, this.scrollOptions);
    window.addEventListener("resize", this.update, { passive: true });
  }

  private describe() {
    const id = this.cardId();
    const trigger = this.rootRef().nativeElement.firstElementChild;
    const described = trigger?.getAttribute("aria-describedby") ?? "";
    if (
      trigger &&
      trigger !== this.cardRef().nativeElement &&
      !described.split(" ").includes(id)
    )
      trigger.setAttribute(
        "aria-describedby",
        [described, id].filter(Boolean).join(" "),
      );
  }

  /** Place the card below the center of the trigger, flip above when it does not fit. */
  private place() {
    const target = this.cardRef().nativeElement;
    const anchor = this.rootRef().nativeElement.getBoundingClientRect();
    const { width, height } = target.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const onTop = below + height > window.innerHeight && above >= 0;
    const left = Math.max(
      GAP,
      Math.min(
        anchor.left + anchor.width / 2 - width / 2,
        window.innerWidth - width - GAP,
      ),
    );
    target.style.top = `${onTop ? above : below}px`;
    target.style.left = `${left}px`;
  }

  private stopFollowing() {
    window.removeEventListener("scroll", this.update, this.scrollOptions);
    window.removeEventListener("resize", this.update);
  }
}
```

```ts
import { Component } from "@angular/core";
import { HoverCard } from "./markas/hover-card.component";

@Component({
  selector: "app-maintainer",
  imports: [HoverCard],
  template: `
    <markas-hover-card>
      <a href="https://github.com/markasui">&#64;markasui</a>
      <ng-container content>
        <p class="font-medium text-ink">Markas UI</p>
        <p class="text-muted">Komponen UI untuk Blade, React, dan Vue.</p>
      </ng-container>
    </markas-hover-card>
  `,
})
export class Maintainer {}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `children / slot` | `slot / ReactNode` | - | Satu elemen pemicu yang bisa difokus, biasanya link. |
| `content` | `slot / ReactNode / snippet` | - | Isi kartu. Blade, Vue, dan Astro memakai slot content, React memakai prop content, Svelte snippet content, Angular elemen dengan atribut content. |
| `id` | `string` | auto | Id elemen kartu, dipakai untuk aria-describedby pemicu. |

## Aksesibilitas

- Pemicu otomatis mendapat aria-describedby ke kartu, jadi pembaca layar mengumumkan pratinjaunya.
- Muncul saat hover setelah 400ms dan langsung saat pemicu mendapat fokus keyboard.
- Mouse keluar, fokus pindah ke luar pemicu dan kartu, atau Escape menyembunyikan kartu.
- Kartu hanya pratinjau: link pemicu harus menuju informasi yang sama.

## Catatan

- Elemen pertama di dalam HoverCard adalah pemicu dan otomatis mendapat `aria-describedby` ke kartu.
- Kartu muncul di bawah pemicu dan pindah ke atas bila tidak ada ruang.
- Di dalam paragraf, isi kartu cukup elemen inline (span, a, strong), karena `div` atau `p` akan memecah paragraf pada HTML hasil render server.
- Hover Card tidak punya teks bawaan. Tulis isinya dalam bahasa situs Anda.
