# Tooltip

Short helper text built on the Popover API, shown when the trigger is hovered or focused.

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

## When to use

Explaining an icon button or a short action whose label is not clear enough.

- Tooltip content is short text only, never links or buttons
- The trigger must be a single focusable element
- Never keep important information only in a tooltip

## Code

### Blade

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

```blade
@props([
    'content',
    'side' => 'top',
])

@php
    $root = 'inline-flex';
    $tooltip = 'inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas 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-tooltip|'.(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-tooltip-'.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.tip.showPopover();
        },
        showLater() {
            clearTimeout(this.timer);
            this.timer = setTimeout(() => this.show(), 300);
        },
        hide() {
            clearTimeout(this.timer);
            this.$refs.tip.hidePopover();
        },
        describe() {
            const trigger = this.$root.firstElementChild;
            const described = trigger?.getAttribute('aria-describedby') ?? '';
            if (trigger && trigger !== this.$refs.tip && !described.split(' ').includes(@js($id))) {
                trigger.setAttribute('aria-describedby', [described, @js($id)].filter(Boolean).join(' '));
            }
        },
        {{-- Letakkan tooltip di tengah pemicu pada sisi yang dipilih, pindah sisi kalau tidak muat. --}}
        place() {
            const gap = 6;
            const anchor = this.$root.getBoundingClientRect();
            const { width, height } = this.$refs.tip.getBoundingClientRect();
            const above = anchor.top - gap - height;
            const below = anchor.bottom + gap;
            const fitsAbove = above >= 0;
            const fitsBelow = below + height <= window.innerHeight;
            const onTop = @js($side) === 'top' ? fitsAbove || ! fitsBelow : ! fitsBelow && fitsAbove;
            this.$refs.tip.style.top = (onTop ? above : below) + 'px';
            this.$refs.tip.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() {
            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="hide()"
    @focusin="show()"
    @focusout="hide()"
    @keydown.escape.window="hide()"
    {{ $attributes->except('id')->class([$root]) }}
>{{ $slot }}<span
        x-ref="tip"
        id="{{ $id }}"
        popover="manual"
        wire:ignore.self
        role="tooltip"
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @toggle="onToggle($event)"
        class="{{ $tooltip }}"
    >{{ $content }}</span></span>
```

```blade
<x-markas.tooltip content="Copy link to clipboard">
    <x-markas.button variant="secondary">Copy link</x-markas.button>
</x-markas.tooltip>
```

Needs Alpine.js.

### React

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

```tsx
"use client";

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

const root = "inline-flex";
const tooltip =
  "inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas shadow-overlay";

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

const GAP = 6;
const SHOW_DELAY = 300;

type Side = "top" | "bottom";

/** Letakkan tooltip di tengah pemicu pada sisi yang dipilih, pindah sisi kalau tidak muat. */
function placeTooltip(trigger: HTMLElement, tip: HTMLElement, side: Side) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = tip.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const fitsAbove = above >= 0;
  const fitsBelow = below + height <= window.innerHeight;
  const onTop =
    side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
  const left = Math.max(
    GAP,
    Math.min(
      anchor.left + anchor.width / 2 - width / 2,
      window.innerWidth - width - GAP,
    ),
  );
  tip.style.top = `${onTop ? above : below}px`;
  tip.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 TooltipProps = ComponentProps<"span"> & {
  content: string;
  side?: Side;
};

export function Tooltip({
  content,
  side = "top",
  id,
  className,
  children,
  ...props
}: TooltipProps) {
  const generatedId = useId();
  const tooltipId = id ?? generatedId;
  const rootRef = useRef<HTMLSpanElement>(null);
  const tipRef = useRef<HTMLSpanElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const [open, setOpen] = useState(false);

  const show = () => {
    clearTimeout(timer.current);
    tipRef.current?.showPopover();
  };
  const showLater = () => {
    clearTimeout(timer.current);
    timer.current = setTimeout(show, SHOW_DELAY);
  };
  const hide = () => {
    clearTimeout(timer.current);
    tipRef.current?.hidePopover();
  };

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

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

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

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

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

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

<Tooltip content="Copy link to clipboard">
  <Button variant="secondary">Copy link</Button>
</Tooltip>;
```

### Vue

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

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

type Side = "top" | "bottom";

const props = withDefaults(
  defineProps<{
    content: string;
    side?: Side;
    id?: string;
  }>(),
  { side: "top", id: undefined },
);

const root = "inline-flex";
const tooltip =
  "inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas shadow-overlay";

const GAP = 6;
const SHOW_DELAY = 300;

/** Letakkan tooltip di tengah pemicu pada sisi yang dipilih, pindah sisi kalau tidak muat. */
function placeTooltip(trigger: HTMLElement, tip: HTMLElement, side: Side) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = tip.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const fitsAbove = above >= 0;
  const fitsBelow = below + height <= window.innerHeight;
  const onTop =
    side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
  const left = Math.max(
    GAP,
    Math.min(
      anchor.left + anchor.width / 2 - width / 2,
      window.innerWidth - width - GAP,
    ),
  );
  tip.style.top = `${onTop ? above : below}px`;
  tip.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 tooltipId = computed(() => props.id ?? generatedId);
const rootEl = useTemplateRef<HTMLSpanElement>("rootRef");
const tipEl = useTemplateRef<HTMLSpanElement>("tip");
const open = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;
let unfollow: (() => void) | undefined;

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

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

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

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

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

function place() {
  if (rootEl.value && tipEl.value)
    placeTooltip(rootEl.value, tipEl.value, props.side);
}

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 && !described.split(" ").includes(tooltipId.value))
    trigger.setAttribute(
      "aria-describedby",
      [described, tooltipId.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="hide"
    @focusin="show"
    @focusout="hide"
  >
    <slot />
    <span
      :id="tooltipId"
      ref="tip"
      popover="manual"
      role="tooltip"
      :data-state="open ? 'open' : 'closed'"
      :class="tooltip"
      @toggle="onToggle"
      >{{ props.content }}</span
    >
  </span>
</template>
```

```vue
<template>
  <Tooltip content="Copy link to clipboard">
    <Button variant="secondary">Copy link</Button>
  </Tooltip>
</template>
```

### Svelte

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

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

  const root = "inline-flex";
  const tooltip =
    "inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas shadow-overlay";

  const GAP = 6;
  const SHOW_DELAY = 300;

  type Side = "top" | "bottom";

  /** Places the tooltip centered on the trigger on the chosen side, flipping when it does not fit. */
  function placeTooltip(trigger: HTMLElement, tip: HTMLElement, side: Side) {
    const anchor = trigger.getBoundingClientRect();
    const { width, height } = tip.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const fitsAbove = above >= 0;
    const fitsBelow = below + height <= window.innerHeight;
    const onTop =
      side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
    const left = Math.max(
      GAP,
      Math.min(
        anchor.left + anchor.width / 2 - width / 2,
        window.innerWidth - width - GAP,
      ),
    );
    tip.style.top = `${onTop ? above : below}px`;
    tip.style.left = `${left}px`;
  }

  /** Re-runs placement on scroll and resize. Returns the cleanup function. */
  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);
    };
  }

  type Props = HTMLAttributes<HTMLSpanElement> & {
    content: string;
    side?: Side;
    children?: Snippet;
  };

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

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

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

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

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

  function place() {
    if (rootEl && tip) placeTooltip(rootEl, tip, side);
  }

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

  $effect(() => {
    const trigger = rootEl?.firstElementChild;
    const described = trigger?.getAttribute("aria-describedby") ?? "";
    if (trigger && trigger !== tip && !described.split(" ").includes(tooltipId))
      trigger.setAttribute(
        "aria-describedby",
        [described, tooltipId].filter(Boolean).join(" "),
      );

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

  $effect(() => {
    if (open) return followViewport(place);
  });
</script>

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

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

<Tooltip content="Copy link to clipboard">
  <Button variant="secondary">Copy link</Button>
</Tooltip>
```

### Astro

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

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

const root = "inline-flex";
const tooltip =
  "inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas shadow-overlay";

type Props = HTMLAttributes<"span"> & {
  content: string;
  side?: "top" | "bottom";
};

const { content, side = "top", id, class: className, ...rest } = Astro.props;
const tooltipId = id ?? `markas-tooltip-${crypto.randomUUID().slice(0, 8)}`;
---

<markas-tooltip class="contents" data-side={side}>
  <span class:list={[root, className]} {...rest}
    ><slot /><span
      id={tooltipId}
      popover="manual"
      role="tooltip"
      data-state="closed"
      class={tooltip}>{content}</span
    ></span
  >
</markas-tooltip>

<script>
  const GAP = 6;
  const SHOW_DELAY = 300;

  /** Places the tooltip centered on the trigger on the chosen side, flipping when it does not fit. */
  function placeTooltip(trigger: HTMLElement, tip: HTMLElement, side: string) {
    const anchor = trigger.getBoundingClientRect();
    const { width, height } = tip.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const fitsAbove = above >= 0;
    const fitsBelow = below + height <= window.innerHeight;
    const onTop =
      side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
    const left = Math.max(
      GAP,
      Math.min(
        anchor.left + anchor.width / 2 - width / 2,
        window.innerWidth - width - GAP,
      ),
    );
    tip.style.top = `${onTop ? above : below}px`;
    tip.style.left = `${left}px`;
  }

  // One element per tooltip: setup runs for markup added later and after view transitions.
  class MarkasTooltip extends HTMLElement {
    private timer: ReturnType<typeof setTimeout> | undefined;
    private cleanup: (() => void) | undefined;

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      const tip = root?.querySelector<HTMLElement>(":scope > [role=tooltip]");
      if (!root || !tip) return;

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

      const show = () => {
        clearTimeout(this.timer);
        tip.showPopover();
      };
      const showLater = () => {
        clearTimeout(this.timer);
        this.timer = setTimeout(show, SHOW_DELAY);
      };
      const hide = () => {
        clearTimeout(this.timer);
        if (tip.matches(":popover-open")) tip.hidePopover();
      };
      const onKeydown = (event: KeyboardEvent) => {
        if (event.key === "Escape") hide();
      };
      const place = () => placeTooltip(root, tip, this.dataset.side ?? "top");
      const scrollOptions = { capture: true, passive: true };
      const follow = (on: boolean) => {
        const method = on ? "addEventListener" : "removeEventListener";
        window[method]("scroll", place, scrollOptions);
        window[method]("resize", place, { passive: true });
      };
      const onToggle = (event: Event) => {
        const open = (event as ToggleEvent).newState === "open";
        tip.dataset.state = open ? "open" : "closed";
        follow(open);
        if (open) place();
      };

      root.addEventListener("mouseenter", showLater);
      root.addEventListener("mouseleave", hide);
      root.addEventListener("focusin", show);
      root.addEventListener("focusout", hide);
      tip.addEventListener("toggle", onToggle);
      document.addEventListener("keydown", onKeydown);
      this.cleanup = () => {
        clearTimeout(this.timer);
        follow(false);
        root.removeEventListener("mouseenter", showLater);
        root.removeEventListener("mouseleave", hide);
        root.removeEventListener("focusin", show);
        root.removeEventListener("focusout", hide);
        tip.removeEventListener("toggle", onToggle);
        document.removeEventListener("keydown", onKeydown);
      };
    }

    disconnectedCallback() {
      this.cleanup?.();
    }
  }

  if (!customElements.get("markas-tooltip"))
    customElements.define("markas-tooltip", MarkasTooltip);
</script>
```

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

<Tooltip content="Copy link to clipboard">
  <Button variant="secondary">Copy link</Button>
</Tooltip>
```

Each tooltip is wrapped in a `markas-tooltip` custom element with `display: contents`, so it also works for markup added later and after view transitions.

### Angular

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

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

const root = "inline-flex";
const tooltip =
  "inset-auto m-0 max-w-64 rounded-md bg-ink px-2 py-1 text-xs font-medium text-canvas shadow-overlay";

const GAP = 6;
const SHOW_DELAY = 300;

export type TooltipSide = "top" | "bottom";

/** Places the tooltip centered on the trigger on the chosen side, flipping when it does not fit. */
function placeTooltip(
  trigger: HTMLElement,
  tip: HTMLElement,
  side: TooltipSide,
) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = tip.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const fitsAbove = above >= 0;
  const fitsBelow = below + height <= window.innerHeight;
  const onTop =
    side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
  const left = Math.max(
    GAP,
    Math.min(
      anchor.left + anchor.width / 2 - width / 2,
      window.innerWidth - width - GAP,
    ),
  );
  tip.style.top = `${onTop ? above : below}px`;
  tip.style.left = `${left}px`;
}

/** Re-runs placement on scroll and resize. Returns the cleanup function. */
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);
  };
}

let nextId = 0;

/**
 * The host is the inline-flex wrapper (the span in other frameworks), so class and other
 * attributes stay on it. The first projected element is the trigger; id moves to the tooltip.
 */
@Component({
  selector: "markas-tooltip",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: root,
    "[attr.id]": "null",
    "(mouseenter)": "showLater()",
    "(mouseleave)": "hide()",
    "(focusin)": "show()",
    "(focusout)": "hide()",
    "(document:keydown.escape)": "hide()",
  },
  template: `<ng-content /><span
      #tip
      [id]="tooltipId()"
      popover="manual"
      role="tooltip"
      [attr.data-state]="open() ? 'open' : 'closed'"
      [class]="tooltip"
      (toggle)="handleToggle($event)"
      >{{ content() }}</span
    >`,
})
export class Tooltip {
  readonly content = input.required<string>();
  readonly side = input<TooltipSide>("top");
  readonly id = input<string>();

  protected readonly tooltip = tooltip;
  protected readonly open = signal(false);
  private readonly generatedId = `markas-tooltip-${nextId++}`;
  protected readonly tooltipId = computed(() => this.id() ?? this.generatedId);
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly tip = viewChild.required<ElementRef<HTMLElement>>("tip");
  private timer: ReturnType<typeof setTimeout> | undefined;
  private unfollow: (() => void) | undefined;

  constructor() {
    afterNextRender(() => {
      const tip = this.tip().nativeElement;
      const trigger = this.host.nativeElement.firstElementChild;
      const id = this.tooltipId();
      const described = trigger?.getAttribute("aria-describedby") ?? "";
      if (trigger && trigger !== tip && !described.split(" ").includes(id))
        trigger.setAttribute(
          "aria-describedby",
          [described, id].filter(Boolean).join(" "),
        );
    });
    inject(DestroyRef).onDestroy(() => {
      clearTimeout(this.timer);
      this.unfollow?.();
    });
  }

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

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

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

  private place() {
    placeTooltip(
      this.host.nativeElement,
      this.tip().nativeElement,
      this.side(),
    );
  }

  protected handleToggle(event: Event) {
    this.unfollow?.();
    this.unfollow = undefined;
    const isOpen = (event as ToggleEvent).newState === "open";
    this.open.set(isOpen);
    if (!isOpen) return;
    this.place();
    this.unfollow = followViewport(() => this.place());
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Tooltip } from "./markas/tooltip.component";

@Component({
  selector: "app-share",
  imports: [Button, Tooltip],
  template: `
    <markas-tooltip content="Copy link to clipboard">
      <button markas-button variant="secondary">Copy link</button>
    </markas-tooltip>
  `,
})
export class Share {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `content` | `string` | - | Tooltip text. |
| `side` | `top \| bottom` | top | Side of the trigger to show the tooltip on. Flips to the other side when it does not fit on screen. |
| `children / slot` | `slot / ReactNode / snippet` | - | A single focusable trigger element, such as a button. |
| `id` | `string` | auto | Tooltip element id, used for the trigger aria-describedby. |

## Accessibility

- Uses role=tooltip, and the trigger automatically gets aria-describedby pointing to the tooltip.
- Shows when the trigger receives keyboard focus and on hover (300ms delay).
- Escape, blur, or moving the mouse away hides the tooltip.

## Notes

- The first element inside Tooltip automatically gets `aria-describedby` pointing to the tooltip.
- Use `side="bottom"` to show the tooltip below the trigger.
- Tooltip has no built-in text. Write `content` in the language of your site.
