# Text Highlighter

A highlight that draws behind inline text from four directions: in view, on hover or focus, on mount, or on command. Solid, marker, underline, or gradient.

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

## When to use

Key phrases in articles, hero headings, and checklists that should draw the eye as they scroll in or on interaction.

- Highlight a few short phrases, not whole paragraphs
- Use rising delay values to highlight phrases in reading order
- Use trigger hover inside a link or button so keyboard focus works too
- React exposes animate(direction) and reset() through ref, Vue through a template ref, Blade through the markas-highlight and markas-highlight-reset window events
- Blade needs Alpine.js

## Code

### Blade

Save at `resources/views/components/markas/text-highlighter.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'as' => 'span',
    'trigger' => 'view',
    'direction' => 'ltr',
    'variant' => 'solid',
    'color' => 'warning',
    'active' => false,
    'once' => true,
    'threshold' => 0.5,
    'duration' => 700,
    'delay' => 0,
])

@php
    $base = 'bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]';
    $variants = [
        'solid' => 'rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]',
        'marker' => 'rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]',
        'underline' => '[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]',
        'gradient' => 'rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]',
    ];
    $colors = [
        'warning' => '[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]',
        'primary' => '[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]',
        'primary-soft' => '[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]',
        'success' => '[--markas-th-c:var(--color-success)]',
        'danger' => '[--markas-th-c:var(--color-danger)]',
    ];

    // Hanya nama elemen yang valid yang dipakai sebagai tag.
    $tag = preg_match('/^[a-z][a-z0-9]*$/', (string) $as) === 1 ? $as : 'span';
@endphp

<{{ $tag }}
    x-data="{
        active: @js((bool) $active),
        dir: @js($direction),
        trigger: @js($trigger),
        cleanup: () => {},
        {{-- Sorot teks, opsional dengan arah lain. Bisa dipanggil lewat Alpine.$data(el) atau event markas-highlight. --}}
        animate(direction) {
            if (direction) this.dir = direction;
            this.active = true;
        },
        reset() {
            this.active = false;
        },
        init() {
            const trigger = this.trigger;
            const el = this.$el;
            if (trigger === 'manual') return;
            {{-- Hitung gaya awal dulu supaya transisi berjalan dari keadaan kosong. --}}
            if (trigger === 'auto') {
                void el.offsetWidth;
                return (this.active = true);
            }
            if (trigger === 'hover') {
                {{-- Hover dan fokus didengar di elemen interaktif terdekat (link, tombol), atau di teks itu sendiri. --}}
                const target = el.closest('a, button, label, [tabindex]') ?? el;
                const show = () => (this.active = true);
                const hide = () => (this.active = false);
                const events = [['pointerenter', show], ['focusin', show], ['pointerleave', hide], ['focusout', hide]];
                events.forEach(([name, fn]) => target.addEventListener(name, fn));
                this.cleanup = () => events.forEach(([name, fn]) => target.removeEventListener(name, fn));
                return;
            }
            const once = @js((bool) $once);
            const observer = new IntersectionObserver((entries) => {
                const visible = entries.some((entry) => entry.isIntersecting);
                if (visible && once) observer.disconnect();
                if (visible || ! once) this.active = visible;
            }, { threshold: @js((float) $threshold) });
            observer.observe(el);
            this.cleanup = () => observer.disconnect();
        },
        destroy() {
            this.cleanup();
        },
    }"
    x-on:markas-highlight.window="trigger === 'manual' && animate($event.detail?.direction)"
    x-on:markas-highlight-reset.window="trigger === 'manual' && reset()"
    x-bind:data-state="active ? 'active' : 'inactive'"
    x-bind:data-direction="dir"
    {{ $attributes->merge(['data-state' => $active ? 'active' : 'inactive', 'data-direction' => $direction, 'data-trigger' => $trigger, 'style' => 'transition-duration: '.(int) $duration.'ms; transition-delay: '.(int) $delay.'ms'])->class([$base, $variants[$variant] ?? $variants['solid'], $colors[$color] ?? $colors['warning']]) }}
>{{ $slot }}</{{ $tag }}>@php /* Tanpa baris baru setelah tag penutup, supaya tanda baca sesudah komponen tidak terpisah spasi. */ @endphp
```

```blade
<p>Keep body text at <x-markas.text-highlighter>45 to 75 characters</x-markas.text-highlighter> per line, with a <x-markas.text-highlighter variant="marker" :delay="400">line height near 1.5</x-markas.text-highlighter>.</p>

<a href="/docs"><x-markas.text-highlighter trigger="hover" direction="rtl" color="success">Read the docs</x-markas.text-highlighter></a>

<div x-data>
    <x-markas.text-highlighter trigger="manual">Ready to publish</x-markas.text-highlighter>
    <button type="button" x-on:click="$dispatch('markas-highlight', { direction: 'ltr' })">Highlight</button>
    <button type="button" x-on:click="$dispatch('markas-highlight-reset')">Reset</button>
</div>
```

### React

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

```tsx
"use client";

import {
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  type ComponentPropsWithoutRef,
  type ElementType,
  type Ref,
} from "react";

const base =
  "bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]";
const variants = {
  solid:
    "rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]",
  marker:
    "rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]",
  underline:
    "[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]",
  gradient:
    "rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]",
};
const colors = {
  warning:
    "[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]",
  primary: "[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]",
  "primary-soft":
    "[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]",
  success: "[--markas-th-c:var(--color-success)]",
  danger: "[--markas-th-c:var(--color-danger)]",
};

/** Hover dan fokus didengar di elemen interaktif terdekat (link, tombol), atau di teks itu sendiri. */
const TRIGGER = "a, button, label, [tabindex]";
/** Dua event pertama menyalakan sorotan, dua terakhir mematikannya. */
const EVENTS = ["pointerenter", "focusin", "pointerleave", "focusout"];

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

export type TextHighlighterDirection = "ltr" | "rtl" | "ttb" | "btt";

export type TextHighlighterHandle = {
  /** Sorot teks, opsional dengan arah lain. */
  animate: (direction?: TextHighlighterDirection) => void;
  /** Hapus sorotan. */
  reset: () => void;
};

export type TextHighlighterProps = ComponentPropsWithoutRef<"span"> & {
  as?: ElementType;
  trigger?: "view" | "hover" | "auto" | "manual";
  direction?: TextHighlighterDirection;
  variant?: keyof typeof variants;
  color?: keyof typeof colors;
  /** Keadaan sorotan untuk trigger manual. */
  active?: boolean;
  /** Trigger view: sorot sekali saja, atau hapus lagi saat keluar layar. */
  once?: boolean;
  /** Trigger view: bagian teks yang harus terlihat (0 sampai 1). */
  threshold?: number;
  duration?: number;
  delay?: number;
  ref?: Ref<TextHighlighterHandle>;
};

export function TextHighlighter({
  as: Tag = "span",
  trigger = "view",
  direction = "ltr",
  variant = "solid",
  color = "warning",
  active = false,
  once = true,
  threshold = 0.5,
  duration = 700,
  delay = 0,
  className,
  style,
  ref,
  ...props
}: TextHighlighterProps) {
  const rootRef = useRef<HTMLElement>(null);
  const [on, setOn] = useState(active);
  // Arah dari animate(direction) menimpa prop direction.
  const [override, setOverride] = useState<TextHighlighterDirection>();

  useImperativeHandle(ref, () => ({
    animate: (next) => {
      if (next) setOverride(next);
      setOn(true);
    },
    reset: () => setOn(false),
  }));

  // Trigger manual mengikuti prop active setiap kali nilainya berubah.
  const [lastActive, setLastActive] = useState(active);
  if (active !== lastActive) {
    setLastActive(active);
    if (trigger === "manual") setOn(active);
  }

  useEffect(() => {
    const element = rootRef.current;
    if (!element || trigger === "manual") return;
    if (trigger === "hover") {
      const target = element.closest<HTMLElement>(TRIGGER) ?? element;
      const toggle = (event: Event) => setOn(EVENTS.indexOf(event.type) < 2);
      EVENTS.forEach((name) => target.addEventListener(name, toggle));
      return () =>
        EVENTS.forEach((name) => target.removeEventListener(name, toggle));
    }
    // Auto menyorot di frame berikutnya, supaya transisi berjalan dari keadaan kosong.
    if (trigger === "auto") {
      const frame = requestAnimationFrame(() => setOn(true));
      return () => cancelAnimationFrame(frame);
    }
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.some((entry) => entry.isIntersecting);
        if (visible && once) observer.disconnect();
        if (visible || !once) setOn(visible);
      },
      { threshold },
    );
    observer.observe(element);
    return () => observer.disconnect();
  }, [trigger, once, threshold]);

  return (
    <Tag
      ref={rootRef}
      data-state={on ? "active" : "inactive"}
      data-direction={override ?? direction}
      data-trigger={trigger}
      {...props}
      className={cx(base, variants[variant], colors[color], className)}
      style={{
        transitionDuration: `${duration}ms`,
        transitionDelay: `${delay}ms`,
        ...style,
      }}
    />
  );
}
```

```tsx
import { useRef } from "react";
import {
  TextHighlighter,
  type TextHighlighterHandle,
} from "@/components/markas/TextHighlighter";

const highlight = useRef<TextHighlighterHandle>(null);

<p>
  Keep body text at <TextHighlighter>45 to 75 characters</TextHighlighter> per
  line, with a{" "}
  <TextHighlighter variant="marker" delay={400}>
    line height near 1.5
  </TextHighlighter>
  .
</p>

<TextHighlighter ref={highlight} trigger="manual">Ready to publish</TextHighlighter>
<button type="button" onClick={() => highlight.current?.animate("rtl")}>Highlight</button>
<button type="button" onClick={() => highlight.current?.reset()}>Reset</button>
```

### Vue

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

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

type Direction = "ltr" | "rtl" | "ttb" | "btt";

const props = withDefaults(
  defineProps<{
    as?: string;
    trigger?: "view" | "hover" | "auto" | "manual";
    direction?: Direction;
    variant?: "solid" | "marker" | "underline" | "gradient";
    color?: "warning" | "primary" | "primary-soft" | "success" | "danger";
    /** Keadaan sorotan untuk trigger manual. */
    active?: boolean;
    /** Trigger view: sorot sekali saja, atau hapus lagi saat keluar layar. */
    once?: boolean;
    /** Trigger view: bagian teks yang harus terlihat (0 sampai 1). */
    threshold?: number;
    duration?: number;
    delay?: number;
  }>(),
  {
    as: "span",
    trigger: "view",
    direction: "ltr",
    variant: "solid",
    color: "warning",
    active: false,
    once: true,
    threshold: 0.5,
    duration: 700,
    delay: 0,
  },
);

const base =
  "bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]";
const variants = {
  solid:
    "rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]",
  marker:
    "rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]",
  underline:
    "[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]",
  gradient:
    "rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]",
};
const colors = {
  warning:
    "[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]",
  primary: "[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]",
  "primary-soft":
    "[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]",
  success: "[--markas-th-c:var(--color-success)]",
  danger: "[--markas-th-c:var(--color-danger)]",
};

/** Hover dan fokus didengar di elemen interaktif terdekat (link, tombol), atau di teks itu sendiri. */
const TRIGGER = "a, button, label, [tabindex]";
/** Dua event pertama menyalakan sorotan, dua terakhir mematikannya. */
const EVENTS = ["pointerenter", "focusin", "pointerleave", "focusout"];

const on = ref(props.active);
/** Arah dari animate(direction) menimpa prop direction. */
const override = ref<Direction>();
const rootEl = useTemplateRef<HTMLElement>("rootRef");
// Dijalankan ulang (dengan cleanup) setiap kali trigger, once, threshold, atau active berubah.
watchPostEffect((onCleanup) => {
  const element = rootEl.value;
  const { trigger, once, threshold } = props;
  if (trigger === "manual") on.value = props.active;
  if (!element || trigger === "manual") return;
  if (trigger === "hover") {
    const target = element.closest<HTMLElement>(TRIGGER) ?? element;
    const toggle = (event: Event) =>
      (on.value = EVENTS.indexOf(event.type) < 2);
    EVENTS.forEach((name) => target.addEventListener(name, toggle));
    onCleanup(() =>
      EVENTS.forEach((name) => target.removeEventListener(name, toggle)),
    );
    return;
  }
  // Auto langsung menyorot. offsetWidth menghitung gaya awal dulu supaya transisi berjalan dari keadaan kosong.
  if (trigger === "auto") {
    void element.offsetWidth;
    on.value = true;
    return;
  }
  const observer = new IntersectionObserver(
    (entries) => {
      const visible = entries.some((entry) => entry.isIntersecting);
      if (visible && once) observer.disconnect();
      if (visible || !once) on.value = visible;
    },
    { threshold },
  );
  observer.observe(element);
  onCleanup(() => observer.disconnect());
});

defineExpose({
  /** Sorot teks, opsional dengan arah lain. */
  animate(next?: Direction) {
    if (next) override.value = next;
    on.value = true;
  },
  /** Hapus sorotan. */
  reset() {
    on.value = false;
  },
});
</script>

<template>
  <component
    :is="props.as"
    ref="rootRef"
    :data-state="on ? 'active' : 'inactive'"
    :data-direction="override ?? props.direction"
    :data-trigger="props.trigger"
    :class="[base, variants[props.variant], colors[props.color]]"
    :style="{
      transitionDuration: `${props.duration}ms`,
      transitionDelay: `${props.delay}ms`,
    }"
    ><slot
  /></component>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import TextHighlighter from "@/components/markas/TextHighlighter.vue";

const active = ref(false);
</script>

<template>
  <p>
    Keep body text at <TextHighlighter>45 to 75 characters</TextHighlighter> per
    line, with a
    <TextHighlighter variant="marker" :delay="400"
      >line height near 1.5</TextHighlighter
    >.
  </p>
  <TextHighlighter trigger="manual" :active="active"
    >Ready to publish</TextHighlighter
  >
  <button type="button" @click="active = !active">Toggle</button>
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type TextHighlighterDirection = "ltr" | "rtl" | "ttb" | "btt";
</script>

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

  const base =
    "bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]";
  const variants = {
    solid:
      "rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]",
    marker:
      "rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]",
    underline:
      "[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]",
    gradient:
      "rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]",
  };
  const colors = {
    warning:
      "[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]",
    primary: "[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]",
    "primary-soft":
      "[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]",
    success: "[--markas-th-c:var(--color-success)]",
    danger: "[--markas-th-c:var(--color-danger)]",
  };

  /** Hover and focus are heard on the closest interactive element (link, button), or on the text itself. */
  const TRIGGER = "a, button, label, [tabindex]";
  /** The first two events draw the highlight, the last two clear it. */
  const EVENTS = ["pointerenter", "focusin", "pointerleave", "focusout"];

  type Props = HTMLAttributes<HTMLElement> & {
    as?: string;
    trigger?: "view" | "hover" | "auto" | "manual";
    direction?: TextHighlighterDirection;
    variant?: keyof typeof variants;
    color?: keyof typeof colors;
    /** Highlight state for trigger manual. */
    active?: boolean;
    /** Trigger view: draw once, or clear again when the text leaves the viewport. */
    once?: boolean;
    /** Trigger view: how much of the text must be visible (0 to 1). */
    threshold?: number;
    duration?: number;
    delay?: number;
    children?: Snippet;
  };

  let {
    as = "span",
    trigger = "view",
    direction = "ltr",
    variant = "solid",
    color = "warning",
    active = false,
    once = true,
    threshold = 0.5,
    duration = 700,
    delay = 0,
    class: className,
    style,
    children,
    ...rest
  }: Props = $props();

  let element = $state<HTMLElement>();
  let on = $state(untrack(() => active));
  /** A direction from animate(direction) wins over the direction prop. */
  let override = $state<TextHighlighterDirection>();

  // Manual follows active every time it changes.
  $effect.pre(() => {
    if (trigger === "manual") on = active;
  });

  $effect(() => {
    const options = { trigger, once, threshold };
    if (!element || options.trigger === "manual") return;
    if (options.trigger === "hover") {
      const target = element.closest<HTMLElement>(TRIGGER) ?? element;
      const toggle = (event: Event) => (on = EVENTS.indexOf(event.type) < 2);
      EVENTS.forEach((name) => target.addEventListener(name, toggle));
      return () =>
        EVENTS.forEach((name) => target.removeEventListener(name, toggle));
    }
    // Auto draws right away. offsetWidth applies the empty start first, so the transition runs.
    if (options.trigger === "auto") {
      void element.offsetWidth;
      on = true;
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.some((entry) => entry.isIntersecting);
        if (visible && options.once) observer.disconnect();
        if (visible || !options.once) on = visible;
      },
      { threshold: options.threshold },
    );
    observer.observe(element);
    return () => observer.disconnect();
  });

  const styleText = $derived(
    [`transition-duration: ${duration}ms; transition-delay: ${delay}ms`, style]
      .filter(Boolean)
      .join("; "),
  );

  /** Draws the highlight, optionally from another direction. */
  export function animate(next?: TextHighlighterDirection) {
    if (next) override = next;
    on = true;
  }

  /** Clears the highlight. */
  export function reset() {
    on = false;
  }
</script>

<svelte:element
  this={as}
  bind:this={element}
  data-state={on ? "active" : "inactive"}
  data-direction={override ?? direction}
  data-trigger={trigger}
  {...rest}
  class={[base, variants[variant], colors[color], className]}
  style={styleText}>{@render children?.()}</svelte:element
>
```

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

  let active = $state(false);
</script>

<p>
  Keep body text at <TextHighlighter>45 to 75 characters</TextHighlighter> per line,
  with a
  <TextHighlighter variant="marker" delay={400}
    >line height near 1.5</TextHighlighter
  >.
</p>
<TextHighlighter trigger="manual" {active}>Ready to publish</TextHighlighter>
<button type="button" onclick={() => (active = !active)}>Toggle</button>
```

### Astro

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

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

const base =
  "bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]";
const variants = {
  solid:
    "rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]",
  marker:
    "rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]",
  underline:
    "[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]",
  gradient:
    "rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]",
};
const colors = {
  warning:
    "[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]",
  primary: "[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]",
  "primary-soft":
    "[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]",
  success: "[--markas-th-c:var(--color-success)]",
  danger: "[--markas-th-c:var(--color-danger)]",
};

type Props = HTMLAttributes<"span"> & {
  as?: string;
  trigger?: "view" | "hover" | "auto" | "manual";
  direction?: "ltr" | "rtl" | "ttb" | "btt";
  variant?: keyof typeof variants;
  color?: keyof typeof colors;
  /** Highlight state for trigger manual. */
  active?: boolean;
  /** Trigger view: draw once, or clear again when the text leaves the viewport. */
  once?: boolean;
  /** Trigger view: how much of the text must be visible (0 to 1). */
  threshold?: number;
  duration?: number;
  delay?: number;
};

const {
  as = "span",
  trigger = "view",
  direction = "ltr",
  variant = "solid",
  color = "warning",
  active = false,
  once = true,
  threshold = 0.5,
  duration = 700,
  delay = 0,
  class: className,
  style,
  ...rest
} = Astro.props;
// Only a valid element name is used as the tag.
const Tag = (/^[a-z][a-z0-9]*$/.test(as) ? as : "span") as HTMLTag;
const styleText = [
  `transition-duration: ${duration}ms; transition-delay: ${delay}ms`,
  typeof style === "string" ? style : "",
]
  .filter(Boolean)
  .join("; ");
---

<markas-text-highlighter class="contents" data-once={once ? "" : undefined} data-threshold={threshold}><Tag data-state={active ? "active" : "inactive"} data-direction={direction} data-trigger={trigger} {...rest} class:list={[base, variants[variant], colors[color], className]} style={styleText}><slot /></Tag></markas-text-highlighter>

<script>
  type Direction = "ltr" | "rtl" | "ttb" | "btt";

  /** Hover and focus are heard on the closest interactive element (link, button), or on the text itself. */
  const TRIGGER = "a, button, label, [tabindex]";
  /** The first two events draw the highlight, the last two clear it. */
  const EVENTS = ["pointerenter", "focusin", "pointerleave", "focusout"];

  // One element per highlight: setup runs for markup added later and after view transitions.
  class MarkasTextHighlighter extends HTMLElement {
    private cleanup = () => {};

    private get mark() {
      return this.firstElementChild as HTMLElement | null;
    }

    /** Draws the highlight, optionally from another direction. Not named animate: that is Element.animate(). */
    highlight(direction?: Direction) {
      if (!this.mark) return;
      if (direction) this.mark.dataset.direction = direction;
      this.mark.dataset.state = "active";
    }

    /** Clears the highlight. */
    reset() {
      if (this.mark) this.mark.dataset.state = "inactive";
    }

    connectedCallback() {
      const element = this.mark;
      if (!element) return;
      const set = (on: boolean) => (on ? this.highlight() : this.reset());
      const trigger = element.dataset.trigger;
      if (trigger === "manual") {
        // Same window events as the Blade version.
        const show = (event: Event) =>
          this.highlight((event as CustomEvent<{ direction?: Direction } | null>).detail?.direction);
        const hide = () => this.reset();
        window.addEventListener("markas-highlight", show);
        window.addEventListener("markas-highlight-reset", hide);
        this.cleanup = () => {
          window.removeEventListener("markas-highlight", show);
          window.removeEventListener("markas-highlight-reset", hide);
        };
        return;
      }
      if (trigger === "hover") {
        const target = element.closest<HTMLElement>(TRIGGER) ?? element;
        const toggle = (event: Event) => set(EVENTS.indexOf(event.type) < 2);
        EVENTS.forEach((name) => target.addEventListener(name, toggle));
        this.cleanup = () =>
          EVENTS.forEach((name) => target.removeEventListener(name, toggle));
        return;
      }
      // Auto draws right away. offsetWidth applies the empty start first, so the transition runs.
      if (trigger === "auto") {
        void element.offsetWidth;
        return set(true);
      }
      const once = this.hasAttribute("data-once");
      const observer = new IntersectionObserver(
        (entries) => {
          const visible = entries.some((entry) => entry.isIntersecting);
          if (visible && once) observer.disconnect();
          if (visible || !once) set(visible);
        },
        { threshold: Number(this.dataset.threshold) },
      );
      observer.observe(element);
      this.cleanup = () => observer.disconnect();
    }

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

  if (!customElements.get("markas-text-highlighter"))
    customElements.define("markas-text-highlighter", MarkasTextHighlighter);
</script>
```

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

<p>
  Keep body text at <TextHighlighter>45 to 75 characters</TextHighlighter> per
  line, with a{" "}
  <TextHighlighter variant="marker" delay={400}>line height near 1.5</TextHighlighter>.
</p>
<TextHighlighter trigger="manual">Ready to publish</TextHighlighter>
<button
  type="button"
  onclick="window.dispatchEvent(new CustomEvent('markas-highlight'))"
>
  Highlight
</button>
```

### Angular

Save at `src/app/markas/text-highlighter.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  ElementRef,
  inject,
  input,
  linkedSignal,
  numberAttribute,
  signal,
} from "@angular/core";

const base =
  "bg-transparent text-ink bg-no-repeat box-decoration-clone [--markas-th-fill:color-mix(in_oklab,var(--markas-th-c)_var(--markas-th-a,28%),transparent)] -mx-[0.12em] px-[0.12em] bg-left [background-size:var(--markas-th-size,0%_100%)] data-[direction=rtl]:bg-right data-[direction=ttb]:bg-top data-[direction=btt]:bg-bottom data-[direction$=b]:[--markas-th-size:100%_0%] data-[state=active]:[background-size:100%_100%] transition-[background-size] ease-out motion-reduce:transition-none motion-reduce:data-[trigger=view]:[background-size:100%_100%] motion-reduce:data-[trigger=auto]:[background-size:100%_100%]";
const variants = {
  solid:
    "rounded-[0.2em] [background-image:linear-gradient(var(--markas-th-fill)_0_0)]",
  marker:
    "rounded-[0.1em_0.5em_0.2em_0.6em] [background-image:linear-gradient(transparent_40%,var(--markas-th-fill)_40%_94%,transparent_94%)]",
  underline:
    "[background-image:linear-gradient(transparent_84%,var(--markas-th-c)_84%)]",
  gradient:
    "rounded-[0.2em] [background-image:linear-gradient(100deg,var(--markas-th-fill),color-mix(in_oklab,var(--markas-th-c2,var(--color-warning))_var(--markas-th-a,28%),transparent))]",
};
const colors = {
  warning:
    "[--markas-th-c:var(--color-warning)] [--markas-th-c2:var(--color-danger)]",
  primary: "[--markas-th-a:16%] [--markas-th-c:var(--color-primary)]",
  "primary-soft":
    "[--markas-th-a:100%] [--markas-th-c:var(--color-primary-soft)]",
  success: "[--markas-th-c:var(--color-success)]",
  danger: "[--markas-th-c:var(--color-danger)]",
};

/** Hover and focus are heard on the closest interactive element (link, button), or on the text itself. */
const TRIGGER = "a, button, label, [tabindex]";
/** The first two events draw the highlight, the last two clear it. */
const EVENTS = ["pointerenter", "focusin", "pointerleave", "focusout"];

export type TextHighlighterTrigger = "view" | "hover" | "auto" | "manual";
export type TextHighlighterDirection = "ltr" | "rtl" | "ttb" | "btt";
export type TextHighlighterVariant = keyof typeof variants;
export type TextHighlighterColor = keyof typeof colors;

/**
 * Attribute selector, so the element you put it on is the highlight (span, strong, mark). That
 * replaces the as prop. For trigger manual, bind active or call animate() and reset() through a
 * template reference: #mark="markasTextHighlighter".
 */
@Component({
  selector: "[markas-text-highlighter]",
  exportAs: "markasTextHighlighter",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.data-state]": "on() ? 'active' : 'inactive'",
    "[attr.data-direction]": "override() ?? direction()",
    "[attr.data-trigger]": "trigger()",
    "[class]": "classes()",
    "[style.transition-duration.ms]": "duration()",
    "[style.transition-delay.ms]": "delay()",
  },
  template: `<ng-content />`,
})
export class TextHighlighter {
  readonly trigger = input<TextHighlighterTrigger>("view");
  readonly direction = input<TextHighlighterDirection>("ltr");
  readonly variant = input<TextHighlighterVariant>("solid");
  readonly color = input<TextHighlighterColor>("warning");
  /** Highlight state for trigger manual. */
  readonly active = input(false, { transform: booleanAttribute });
  /** Trigger view: draw once, or clear again when the text leaves the viewport. */
  readonly once = input(true, { transform: booleanAttribute });
  /** Trigger view: how much of the text must be visible (0 to 1). */
  readonly threshold = input(0.5, { transform: numberAttribute });
  readonly duration = input(700, { transform: numberAttribute });
  readonly delay = input(0, { transform: numberAttribute });

  /** Follows active every time it changes; triggers and animate() set it in between. */
  protected readonly on = linkedSignal(() => this.active());
  /** A direction from animate(direction) wins over the direction input. */
  protected readonly override = signal<TextHighlighterDirection | undefined>(
    undefined,
  );
  protected readonly classes = computed(
    () => `${base} ${variants[this.variant()]} ${colors[this.color()]}`,
  );
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    afterRenderEffect((onCleanup) => {
      const trigger = this.trigger();
      const once = this.once();
      const threshold = this.threshold();
      if (trigger === "manual") return;
      onCleanup(this.listen(trigger, once, threshold));
    });
  }

  /** Draws the highlight, optionally from another direction. */
  animate(direction?: TextHighlighterDirection) {
    if (direction) this.override.set(direction);
    this.on.set(true);
  }

  /** Clears the highlight. */
  reset() {
    this.on.set(false);
  }

  private listen(
    trigger: Exclude<TextHighlighterTrigger, "manual">,
    once: boolean,
    threshold: number,
  ) {
    const element = this.host.nativeElement;
    if (trigger === "hover") {
      const target = element.closest<HTMLElement>(TRIGGER) ?? element;
      const toggle = (event: Event) =>
        this.on.set(EVENTS.indexOf(event.type) < 2);
      EVENTS.forEach((name) => target.addEventListener(name, toggle));
      return () =>
        EVENTS.forEach((name) => target.removeEventListener(name, toggle));
    }
    // Auto draws right away. offsetWidth applies the empty start first, so the transition runs.
    if (trigger === "auto") {
      void element.offsetWidth;
      this.on.set(true);
      return () => {};
    }
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.some((entry) => entry.isIntersecting);
        if (visible && once) observer.disconnect();
        if (visible || !once) this.on.set(visible);
      },
      { threshold },
    );
    observer.observe(element);
    return () => observer.disconnect();
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { TextHighlighter } from "./markas/text-highlighter.component";

@Component({
  selector: "app-checklist",
  imports: [TextHighlighter],
  template: `
    <p>
      Keep body text at
      <span markas-text-highlighter>45 to 75 characters</span> per line, with a
      <mark markas-text-highlighter variant="marker" delay="400"
        >line height near 1.5</mark
      >.
    </p>
    <span markas-text-highlighter trigger="manual" [active]="active()"
      >Ready to publish</span
    >
    <button type="button" (click)="active.set(!active())">Toggle</button>
  `,
})
export class Checklist {
  active = signal(false);
}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `as` | `string` | "span" | The element to render. Keep it inline, such as span, strong, or mark. Angular: put the markas-text-highlighter attribute on that element. |
| `trigger` | `"view" \| "hover" \| "auto" \| "manual"` | "view" | view draws when the text scrolls into view, hover follows hover and keyboard focus of the closest link or button, auto draws on mount, manual follows active. |
| `direction` | `"ltr" \| "rtl" \| "ttb" \| "btt"` | "ltr" | Where the highlight grows from: left to right, right to left, top to bottom, or bottom to top. |
| `variant` | `"solid" \| "marker" \| "underline" \| "gradient"` | "solid" | solid fills the line, marker covers the lower 60% like a highlighter pen, underline draws a thick bar under the text, gradient blends two tokens. |
| `color` | `"warning" \| "primary" \| "primary-soft" \| "success" \| "danger"` | "warning" | Token used for the highlight, mixed with transparency so the text stays readable. |
| `active` | `boolean` | false | Highlight state for trigger manual. |
| `once` | `boolean` | true | trigger view: draw once, or clear again when the text leaves the viewport. |
| `threshold` | `number` | 0.5 | trigger view: how much of the text must be visible, from 0 to 1. |
| `duration` | `number` | 700 | Milliseconds the highlight takes to draw. |
| `delay` | `number` | 0 | Milliseconds to wait before drawing. Use rising delays to highlight a paragraph in order. |

## Accessibility

- The text stays plain text; the highlight is a background image and is not announced.
- Text on the highlight uses the ink token, which keeps AA contrast in light and dark themes.
- trigger hover also responds to keyboard focus on the closest link, button, or focusable element.
- With reduced motion, view and auto highlights are shown at once and every change happens without a transition.

## Notes

- The highlight is a background gradient that grows with a CSS transition of `background-size`, so it follows the text across line breaks (`box-decoration-break: clone`).
- `trigger="view"` uses IntersectionObserver with `once` and `threshold`; `hover` listens on the closest link, button, label, or element with `tabindex`, so keyboard focus draws it too.
- For `trigger="manual"`, React and Vue expose `animate(direction?)` and `reset()` through a ref. Blade listens for the `markas-highlight` (with an optional `direction` in the detail) and `markas-highlight-reset` window events, and `Alpine.$data(el)` exposes the same two methods. Svelte exposes them through `bind:this`, Astro listens for the same window events as Blade and exposes `highlight(direction?)` and `reset()` on the `markas-text-highlighter` element, and Angular exposes them through `#mark="markasTextHighlighter"`.
- Angular has no `as` input: put the `markas-text-highlighter` attribute on the element you want, such as `span`, `strong`, or `mark`.
- `duration` and `delay` set `transition-duration` and `transition-delay` on the element. Give each phrase a higher `delay` to highlight a paragraph in reading order.
- With reduced motion, `view` and `auto` highlights are shown at once, and every change happens without a transition.
