# Text Rotate

Words or phrases that take turns, animating out and in per letter or per word with a stagger from the first, last, center, or a shuffled unit.

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

## When to use

Rotating a key word in a hero headline, a hiring badge, or a list of names or products.

- Put the static part of the sentence outside the component
- Use split words for phrases of more than one word
- Keep three to five short entries
- Blade needs Alpine.js

## Code

### Blade

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

```blade
@props([
    'words' => [],
    'split' => 'chars',
    'from' => 'first',
    'interval' => 2500,
    'stagger' => 25,
    'duration' => 400,
    'pauseOnHover' => true,
])

@php
    $root = 'relative inline-flex overflow-hidden align-bottom';
    $unit = 'inline-block whitespace-pre';

    $words = array_values($words);
    $first = (string) ($words[0] ?? '');
    // Potong frasa menjadi huruf, atau kata beserta spasi sesudahnya.
    $parts = $split === 'chars' ? mb_str_split($first) : preg_split('/(?<= )/u', $first);
@endphp

<span
    x-data="{
        words: @js($words),
        index: 0,
        timer: null,
        observer: null,
        cleanup: () => {},
        units() {
            return [...this.$el.querySelectorAll('[data-unit]')];
        },
        {{-- Jeda stagger tiap bagian sesuai titik awal. Random memakai urutan acak tetap (hash). --}}
        ranks(count) {
            const from = @js($from);
            const order = [...Array(count).keys()];
            const hash = (i) => Math.imul(i + 1, 2654435761) >>> 0;
            if (from === 'random') order.sort((a, b) => hash(a) - hash(b));
            const rank = [];
            order.forEach((index, position) => {
                const middle = Math.abs(index - (count - 1) / 2);
                rank[index] = from === 'last' ? count - 1 - index : from === 'center' ? middle : position;
            });
            return rank;
        },
        {{-- Pasang kata berikutnya, masuk dari bawah per bagian, dan lebar pembungkus ikut berubah halus. --}}
        swap() {
            const width = this.$el.offsetWidth;
            const text = this.words[this.index];
            const parts = @js($split) === 'chars' ? Array.from(text) : text.split(/(?<= )/);
            this.units().forEach((el) => el.remove());
            parts.forEach((part) => {
                const el = document.createElement('span');
                el.setAttribute('aria-hidden', 'true');
                el.dataset.unit = '';
                el.className = @js($unit);
                el.textContent = part;
                this.$el.append(el);
            });
            const list = this.units();
            const rank = this.ranks(list.length);
            list.forEach((el, i) => el.animate?.([{ transform: 'translateY(100%)', opacity: 0 }, { transform: 'none', opacity: 1 }], { duration: @js((int) $duration), delay: rank[i] * @js((int) $stagger), easing: 'cubic-bezier(0.22, 1, 0.36, 1)', fill: 'backwards' }));
            this.$el.animate?.([{ width: `${width}px` }, { width: `${this.$el.offsetWidth}px` }], { duration: @js((int) $duration), easing: 'cubic-bezier(0.22, 1, 0.36, 1)' });
        },
        {{-- Kata lama keluar ke atas, lalu kata berikutnya dipasang. Berhenti saat di-hover, di luar layar, atau tab tersembunyi. --}}
        init() {
            if (this.words.length < 2 || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            let hovered = false;
            let busy = false;
            const tick = () => {
                if (busy || (hovered && @js((bool) $pauseOnHover)) || document.hidden) return;
                busy = true;
                const list = this.units();
                const rank = this.ranks(list.length);
                const exits = list.map((el, i) => el.animate?.([{ transform: 'none', opacity: 1 }, { transform: 'translateY(-100%)', opacity: 0 }], { duration: @js((int) $duration), delay: rank[i] * @js((int) $stagger), easing: 'cubic-bezier(0.55, 0, 1, 0.45)', fill: 'forwards' }));
                Promise.all(exits.map((animation) => animation?.finished))
                    .then(() => {
                        this.index = (this.index + 1) % this.words.length;
                        this.swap();
                    })
                    .catch(() => {})
                    .finally(() => (busy = false));
            };
            const enter = () => (hovered = true);
            const leave = () => (hovered = false);
            this.$el.addEventListener('pointerenter', enter);
            this.$el.addEventListener('pointerleave', leave);
            this.cleanup = () => {
                this.$el.removeEventListener('pointerenter', enter);
                this.$el.removeEventListener('pointerleave', leave);
            };
            if (typeof IntersectionObserver === 'undefined') return (this.timer = setInterval(tick, @js((int) $interval)));
            this.observer = new IntersectionObserver((entries) => {
                clearInterval(this.timer);
                if (entries.some((entry) => entry.isIntersecting)) this.timer = setInterval(tick, @js((int) $interval));
            });
            this.observer.observe(this.$el);
        },
        destroy() {
            this.observer?.disconnect();
            clearInterval(this.timer);
            this.cleanup();
        },
    }"
    {{ $attributes->class([$root]) }}
><span class="sr-only">{{ implode(', ', $words) }}</span>@foreach ($parts as $part)<span aria-hidden="true" data-unit class="{{ $unit }}">{{ $part }}</span>@endforeach</span>
```

```blade
<h1 class="text-4xl font-semibold">
    Build for
    <x-markas.text-rotate :words="['Laravel', 'React', 'Vue']" />
</h1>
<x-markas.text-rotate :words="['faster', 'with confidence', 'every Friday']" split="words" from="center" :interval="3000" />
```

### React

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

```tsx
"use client";

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

const root = "relative inline-flex overflow-hidden align-bottom";
const unit = "inline-block whitespace-pre";

const EASE_IN = "cubic-bezier(0.55, 0, 1, 0.45)";
const EASE_OUT = "cubic-bezier(0.22, 1, 0.36, 1)";
const WORD_SEPARATOR = "\n";

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

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Potong frasa menjadi huruf, atau kata beserta spasi sesudahnya. */
const splitText = (text: string, split: "chars" | "words") =>
  split === "chars" ? Array.from(text) : text.split(/(?<= )/);

/** Jeda stagger tiap bagian sesuai titik awal. Random memakai urutan acak tetap (hash). */
function ranks(count: number, from: TextRotateProps["from"]) {
  const order = [...Array(count).keys()];
  const hash = (i: number) => Math.imul(i + 1, 2654435761) >>> 0;
  if (from === "random") order.sort((a, b) => hash(a) - hash(b));
  const rank: number[] = [];
  order.forEach((index, position) => {
    const middle = Math.abs(index - (count - 1) / 2);
    rank[index] =
      from === "last"
        ? count - 1 - index
        : from === "center"
          ? middle
          : position;
  });
  return rank;
}

export type TextRotateProps = Omit<ComponentProps<"span">, "children"> & {
  words: string[];
  split?: "chars" | "words";
  from?: "first" | "last" | "center" | "random";
  interval?: number;
  stagger?: number;
  duration?: number;
  pauseOnHover?: boolean;
};

export function TextRotate({
  words,
  split = "chars",
  from = "first",
  interval = 2500,
  stagger = 25,
  duration = 400,
  pauseOnHover = true,
  className,
  ...props
}: TextRotateProps) {
  const rootRef = useRef<HTMLSpanElement>(null);
  const width = useRef(0);
  const [index, setIndex] = useState(0);
  const key = words.join(WORD_SEPARATOR);
  const units = () => [
    ...(rootRef.current?.querySelectorAll<HTMLElement>("[data-unit]") ?? []),
  ];

  // Kata baru masuk dari bawah per bagian, dan lebar pembungkus ikut melebar atau menyempit halus.
  useLayoutEffect(() => {
    const element = rootRef.current;
    if (!element || !width.current) return;
    const list = units();
    const rank = ranks(list.length, from);
    list.forEach((el, i) =>
      el.animate?.(
        [
          { transform: "translateY(100%)", opacity: 0 },
          { transform: "none", opacity: 1 },
        ],
        {
          duration,
          delay: rank[i]! * stagger,
          easing: EASE_OUT,
          fill: "backwards",
        },
      ),
    );
    element.animate?.(
      [{ width: `${width.current}px` }, { width: `${element.offsetWidth}px` }],
      { duration, easing: EASE_OUT },
    );
    width.current = 0;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [index]);

  // Kata lama keluar ke atas, lalu kata berikutnya dipasang. Berhenti saat di-hover, di luar layar, atau tab tersembunyi.
  useEffect(() => {
    const element = rootRef.current;
    const count = key.split(WORD_SEPARATOR).length;
    if (!element || count < 2 || reducedMotion()) return;
    let hovered = false;
    let busy = false;
    let timer: ReturnType<typeof setInterval> | undefined;
    const tick = () => {
      if (busy || (hovered && pauseOnHover) || document.hidden) return;
      busy = true;
      const list = units();
      const rank = ranks(list.length, from);
      const exits = list.map((el, i) =>
        el.animate?.(
          [
            { transform: "none", opacity: 1 },
            { transform: "translateY(-100%)", opacity: 0 },
          ],
          {
            duration,
            delay: rank[i]! * stagger,
            easing: EASE_IN,
            fill: "forwards",
          },
        ),
      );
      Promise.all(exits.map((animation) => animation?.finished))
        .then(() => {
          width.current = element.offsetWidth;
          setIndex((current) => (current + 1) % count);
        })
        .catch(() => {})
        .finally(() => (busy = false));
    };
    const enter = () => (hovered = true);
    const leave = () => (hovered = false);
    element.addEventListener("pointerenter", enter);
    element.addEventListener("pointerleave", leave);
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver((entries) => {
            clearInterval(timer);
            if (entries.some((entry) => entry.isIntersecting))
              timer = setInterval(tick, interval);
          });
    if (observer) observer.observe(element);
    else timer = setInterval(tick, interval);
    return () => {
      observer?.disconnect();
      clearInterval(timer);
      element.removeEventListener("pointerenter", enter);
      element.removeEventListener("pointerleave", leave);
    };
  }, [key, split, from, interval, stagger, duration, pauseOnHover]);

  // Modulo menjaga indeks tetap sah saat daftar kata berganti.
  const current = words[index % Math.max(words.length, 1)] ?? "";

  return (
    <span ref={rootRef} {...props} className={cx(root, className)}>
      <span className="sr-only">{words.join(", ")}</span>
      {splitText(current, split).map((part, i) => (
        <span
          key={`${index}-${i}`}
          aria-hidden="true"
          data-unit=""
          className={unit}
        >
          {part}
        </span>
      ))}
    </span>
  );
}
```

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

<h1 className="text-4xl font-semibold">
  Build for <TextRotate words={["Laravel", "React", "Vue"]} />
</h1>
<TextRotate words={['faster', 'with confidence', 'every Friday']} split="words" from="center" interval={3000} />
```

### Vue

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

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

type From = "first" | "last" | "center" | "random";

const props = withDefaults(
  defineProps<{
    words: string[];
    split?: "chars" | "words";
    from?: From;
    interval?: number;
    stagger?: number;
    duration?: number;
    pauseOnHover?: boolean;
  }>(),
  {
    split: "chars",
    from: "first",
    interval: 2500,
    stagger: 25,
    duration: 400,
    pauseOnHover: true,
  },
);

const root = "relative inline-flex overflow-hidden align-bottom";
const unit = "inline-block whitespace-pre";

const EASE_IN = "cubic-bezier(0.55, 0, 1, 0.45)";
const EASE_OUT = "cubic-bezier(0.22, 1, 0.36, 1)";

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Potong frasa menjadi huruf, atau kata beserta spasi sesudahnya. */
const splitText = (text: string, split: "chars" | "words") =>
  split === "chars" ? Array.from(text) : text.split(/(?<= )/);

/** Jeda stagger tiap bagian sesuai titik awal. Random memakai urutan acak tetap (hash). */
function ranks(count: number, from: From) {
  const order = [...Array(count).keys()];
  const hash = (i: number) => Math.imul(i + 1, 2654435761) >>> 0;
  if (from === "random") order.sort((a, b) => hash(a) - hash(b));
  const rank: number[] = [];
  order.forEach((index, position) => {
    const middle = Math.abs(index - (count - 1) / 2);
    rank[index] =
      from === "last"
        ? count - 1 - index
        : from === "center"
          ? middle
          : position;
  });
  return rank;
}

const rootEl = useTemplateRef<HTMLSpanElement>("rootRef");
const index = ref(0);
const parts = computed(() =>
  splitText(props.words[index.value] ?? props.words[0] ?? "", props.split),
);
const units = () => [
  ...(rootEl.value?.querySelectorAll<HTMLElement>("[data-unit]") ?? []),
];
let cleanup = () => {};

// Kata baru masuk dari bawah per bagian, dan lebar pembungkus ikut melebar atau menyempit halus.
function enter(element: HTMLElement, width: number) {
  const { duration, stagger } = props;
  const list = units();
  const rank = ranks(list.length, props.from);
  list.forEach((el, i) =>
    el.animate?.(
      [
        { transform: "translateY(100%)", opacity: 0 },
        { transform: "none", opacity: 1 },
      ],
      {
        duration,
        delay: rank[i]! * stagger,
        easing: EASE_OUT,
        fill: "backwards",
      },
    ),
  );
  element.animate?.(
    [{ width: `${width}px` }, { width: `${element.offsetWidth}px` }],
    { duration, easing: EASE_OUT },
  );
}

// Kata lama keluar ke atas, lalu kata berikutnya dipasang. Berhenti saat di-hover, di luar layar, atau tab tersembunyi.
function start() {
  cleanup();
  index.value = 0;
  const element = rootEl.value;
  const count = props.words.length;
  if (!element || count < 2 || reducedMotion()) return;
  const { duration, stagger, interval, pauseOnHover } = props;
  let hovered = false;
  let busy = false;
  let timer: ReturnType<typeof setInterval> | undefined;
  const tick = () => {
    if (busy || (hovered && pauseOnHover) || document.hidden) return;
    busy = true;
    const list = units();
    const rank = ranks(list.length, props.from);
    const exits = list.map((el, i) =>
      el.animate?.(
        [
          { transform: "none", opacity: 1 },
          { transform: "translateY(-100%)", opacity: 0 },
        ],
        {
          duration,
          delay: rank[i]! * stagger,
          easing: EASE_IN,
          fill: "forwards",
        },
      ),
    );
    Promise.all(exits.map((animation) => animation?.finished))
      .then(async () => {
        const width = element.offsetWidth;
        index.value = (index.value + 1) % count;
        await nextTick();
        enter(element, width);
      })
      .catch(() => {})
      .finally(() => (busy = false));
  };
  const onEnter = () => (hovered = true);
  const onLeave = () => (hovered = false);
  element.addEventListener("pointerenter", onEnter);
  element.addEventListener("pointerleave", onLeave);
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver((entries) => {
          clearInterval(timer);
          if (entries.some((entry) => entry.isIntersecting))
            timer = setInterval(tick, interval);
        });
  if (observer) observer.observe(element);
  else timer = setInterval(tick, interval);
  cleanup = () => {
    observer?.disconnect();
    clearInterval(timer);
    element.removeEventListener("pointerenter", onEnter);
    element.removeEventListener("pointerleave", onLeave);
  };
}

onMounted(start);
watch(
  () => [
    props.words.join("\n"),
    props.split,
    props.from,
    props.interval,
    props.stagger,
    props.duration,
    props.pauseOnHover,
  ],
  start,
  { flush: "post" },
);
onBeforeUnmount(() => cleanup());
</script>

<template>
  <span ref="rootRef" :class="root"
    ><span class="sr-only">{{ props.words.join(", ") }}</span
    ><span
      v-for="(part, i) in parts"
      :key="`${index}-${i}`"
      aria-hidden="true"
      data-unit
      :class="unit"
      >{{ part }}</span
    ></span
  >
</template>
```

```vue
<template>
  <h1 class="text-4xl font-semibold">
    Build for
    <TextRotate :words="['Laravel', 'React', 'Vue']" />
  </h1>
  <TextRotate
    :words="['faster', 'with confidence', 'every Friday']"
    split="words"
    from="center"
    :interval="3000"
  />
</template>
```

### Svelte

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

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

  const root = "relative inline-flex overflow-hidden align-bottom";
  const unit = "inline-block whitespace-pre";

  const EASE_IN = "cubic-bezier(0.55, 0, 1, 0.45)";
  const EASE_OUT = "cubic-bezier(0.22, 1, 0.36, 1)";
  const WORD_SEPARATOR = "\n";

  type From = "first" | "last" | "center" | "random";

  const reducedMotion = () =>
    typeof matchMedia === "function" &&
    matchMedia("(prefers-reduced-motion: reduce)").matches;

  /** Splits a phrase into letters, or into words with the space after them. */
  const splitText = (text: string, split: "chars" | "words") =>
    split === "chars" ? Array.from(text) : text.split(/(?<= )/);

  /** Stagger rank of each unit from the starting point. Random uses a fixed shuffled order (hash). */
  function ranks(count: number, from: From) {
    const order = [...Array(count).keys()];
    const hash = (i: number) => Math.imul(i + 1, 2654435761) >>> 0;
    if (from === "random") order.sort((a, b) => hash(a) - hash(b));
    const rank: number[] = [];
    order.forEach((index, position) => {
      const middle = Math.abs(index - (count - 1) / 2);
      rank[index] =
        from === "last"
          ? count - 1 - index
          : from === "center"
            ? middle
            : position;
    });
    return rank;
  }

  type Props = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
    words: string[];
    split?: "chars" | "words";
    from?: From;
    interval?: number;
    stagger?: number;
    duration?: number;
    pauseOnHover?: boolean;
  };

  let {
    words,
    split = "chars",
    from = "first",
    interval = 2500,
    stagger = 25,
    duration = 400,
    pauseOnHover = true,
    class: className,
    ...rest
  }: Props = $props();

  let element = $state<HTMLSpanElement>();
  let index = $state(0);
  const key = $derived(words.join(WORD_SEPARATOR));
  // Modulo keeps the index valid when the list of words changes.
  const parts = $derived(
    splitText(words[index % Math.max(words.length, 1)] ?? "", split),
  );
  const units = (host: HTMLElement) => [
    ...host.querySelectorAll<HTMLElement>("[data-unit]"),
  ];

  $effect(() => {
    // Read every prop up front so the effect reruns when one changes.
    const options = { from, interval, stagger, duration, pauseOnHover, split };
    const count = key.split(WORD_SEPARATOR).length;
    const host = element;
    index = 0;
    if (!host || count < 2 || reducedMotion()) return;
    let hovered = false;
    let busy = false;
    let timer: ReturnType<typeof setInterval> | undefined;

    // The new word rises in unit by unit, and the width of the wrapper follows smoothly.
    const enter = (width: number) => {
      const list = units(host);
      const rank = ranks(list.length, options.from);
      list.forEach((el, i) =>
        el.animate?.(
          [
            { transform: "translateY(100%)", opacity: 0 },
            { transform: "none", opacity: 1 },
          ],
          {
            duration: options.duration,
            delay: rank[i]! * options.stagger,
            easing: EASE_OUT,
            fill: "backwards",
          },
        ),
      );
      host.animate?.(
        [{ width: `${width}px` }, { width: `${host.offsetWidth}px` }],
        { duration: options.duration, easing: EASE_OUT },
      );
    };

    // The old word leaves upward, then the next one is rendered. Paused on hover, off screen, or in a hidden tab.
    const next = () => {
      if (busy || (hovered && options.pauseOnHover) || document.hidden) return;
      busy = true;
      const list = units(host);
      const rank = ranks(list.length, options.from);
      const exits = list.map((el, i) =>
        el.animate?.(
          [
            { transform: "none", opacity: 1 },
            { transform: "translateY(-100%)", opacity: 0 },
          ],
          {
            duration: options.duration,
            delay: rank[i]! * options.stagger,
            easing: EASE_IN,
            fill: "forwards",
          },
        ),
      );
      Promise.all(exits.map((animation) => animation?.finished))
        .then(async () => {
          const width = host.offsetWidth;
          index = (index + 1) % count;
          await tick();
          enter(width);
        })
        .catch(() => {})
        .finally(() => (busy = false));
    };
    const onEnter = () => (hovered = true);
    const onLeave = () => (hovered = false);
    host.addEventListener("pointerenter", onEnter);
    host.addEventListener("pointerleave", onLeave);
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver((entries) => {
            clearInterval(timer);
            if (entries.some((entry) => entry.isIntersecting))
              timer = setInterval(next, options.interval);
          });
    if (observer) observer.observe(host);
    else timer = setInterval(next, options.interval);
    return () => {
      observer?.disconnect();
      clearInterval(timer);
      host.removeEventListener("pointerenter", onEnter);
      host.removeEventListener("pointerleave", onLeave);
    };
  });
</script>

<span bind:this={element} {...rest} class={[root, className]}
  ><span class="sr-only">{words.join(", ")}</span
  >{#each parts as part, i (`${index}-${i}`)}<span
      aria-hidden="true"
      data-unit=""
      class={unit}>{part}</span
    >{/each}</span
>
```

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

<h1 class="text-4xl font-semibold">
  Build for <TextRotate words={["Laravel", "React", "Vue"]} />
</h1>
<TextRotate
  words={["faster", "with confidence", "every Friday"]}
  split="words"
  from="center"
  interval={3000}
/>
```

### Astro

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

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

const root = "relative inline-flex overflow-hidden align-bottom";
const unit = "inline-block whitespace-pre";

type Props = Omit<HTMLAttributes<"span">, "children"> & {
  words: string[];
  split?: "chars" | "words";
  from?: "first" | "last" | "center" | "random";
  interval?: number;
  stagger?: number;
  duration?: number;
  pauseOnHover?: boolean;
};

const {
  words,
  split = "chars",
  from = "first",
  interval = 2500,
  stagger = 25,
  duration = 400,
  pauseOnHover = true,
  class: className,
  ...rest
} = Astro.props;
const first = words[0] ?? "";
// Split a phrase into letters, or into words with the space after them.
const parts = split === "chars" ? Array.from(first) : first.split(/(?<= )/);
---

<span {...rest} class:list={[root, className]}><markas-text-rotate class="sr-only" data-words={JSON.stringify(words)} data-split={split} data-from={from} data-interval={interval} data-stagger={stagger} data-duration={duration} data-pause-on-hover={String(pauseOnHover)}>{words.join(", ")}</markas-text-rotate>{parts.map((part) => <span aria-hidden="true" data-unit="" class={unit}>{part}</span>)}</span>

<script>
  const UNIT = "inline-block whitespace-pre";
  const EASE_IN = "cubic-bezier(0.55, 0, 1, 0.45)";
  const EASE_OUT = "cubic-bezier(0.22, 1, 0.36, 1)";

  /** Splits a phrase into letters, or into words with the space after them. */
  const splitText = (text: string, split: string | undefined) =>
    split === "chars" ? Array.from(text) : text.split(/(?<= )/);

  /** Stagger rank of each unit from the starting point. Random uses a fixed shuffled order (hash). */
  function ranks(count: number, from: string | undefined) {
    const order = [...Array(count).keys()];
    const hash = (i: number) => Math.imul(i + 1, 2654435761) >>> 0;
    if (from === "random") order.sort((a, b) => hash(a) - hash(b));
    const rank: number[] = [];
    order.forEach((index, position) => {
      const middle = Math.abs(index - (count - 1) / 2);
      rank[index] =
        from === "last"
          ? count - 1 - index
          : from === "center"
            ? middle
            : position;
    });
    return rank;
  }

  /**
   * The element is the visually hidden copy of the words, inside the root span. That keeps
   * the root a plain span (like the other frameworks) while setup still runs per instance,
   * for markup added later and after view transitions.
   */
  class MarkasTextRotate extends HTMLElement {
    private cleanup = () => {};

    connectedCallback() {
      const host = this.parentElement;
      const words = JSON.parse(this.dataset.words ?? "[]") as string[];
      if (!host || words.length < 2) return;
      if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
      const { split, from } = this.dataset;
      const interval = Number(this.dataset.interval);
      const stagger = Number(this.dataset.stagger);
      const duration = Number(this.dataset.duration);
      const pauseOnHover = this.dataset.pauseOnHover !== "false";
      const units = () => [
        ...host.querySelectorAll<HTMLElement>("[data-unit]"),
      ];
      let index = 0;
      let hovered = false;
      let busy = false;
      let timer: ReturnType<typeof setInterval> | undefined;

      // Render the next word, rise it in unit by unit, and let the width of the wrapper follow smoothly.
      const swap = () => {
        const width = host.offsetWidth;
        units().forEach((el) => el.remove());
        splitText(words[index] ?? "", split).forEach((part) => {
          const el = document.createElement("span");
          el.setAttribute("aria-hidden", "true");
          el.dataset.unit = "";
          el.className = UNIT;
          el.textContent = part;
          host.append(el);
        });
        const list = units();
        const rank = ranks(list.length, from);
        list.forEach((el, i) =>
          el.animate?.(
            [
              { transform: "translateY(100%)", opacity: 0 },
              { transform: "none", opacity: 1 },
            ],
            {
              duration,
              delay: rank[i]! * stagger,
              easing: EASE_OUT,
              fill: "backwards",
            },
          ),
        );
        host.animate?.(
          [{ width: `${width}px` }, { width: `${host.offsetWidth}px` }],
          { duration, easing: EASE_OUT },
        );
      };

      // The old word leaves upward, then the next one is rendered. Paused on hover, off screen, or in a hidden tab.
      const next = () => {
        if (busy || (hovered && pauseOnHover) || document.hidden) return;
        busy = true;
        const list = units();
        const rank = ranks(list.length, from);
        const exits = list.map((el, i) =>
          el.animate?.(
            [
              { transform: "none", opacity: 1 },
              { transform: "translateY(-100%)", opacity: 0 },
            ],
            {
              duration,
              delay: rank[i]! * stagger,
              easing: EASE_IN,
              fill: "forwards",
            },
          ),
        );
        Promise.all(exits.map((animation) => animation?.finished))
          .then(() => {
            index = (index + 1) % words.length;
            swap();
          })
          .catch(() => {})
          .finally(() => (busy = false));
      };
      const onEnter = () => (hovered = true);
      const onLeave = () => (hovered = false);
      host.addEventListener("pointerenter", onEnter);
      host.addEventListener("pointerleave", onLeave);
      const observer =
        typeof IntersectionObserver === "undefined"
          ? undefined
          : new IntersectionObserver((entries) => {
              clearInterval(timer);
              if (entries.some((entry) => entry.isIntersecting))
                timer = setInterval(next, interval);
            });
      if (observer) observer.observe(host);
      else timer = setInterval(next, interval);
      this.cleanup = () => {
        observer?.disconnect();
        clearInterval(timer);
        host.removeEventListener("pointerenter", onEnter);
        host.removeEventListener("pointerleave", onLeave);
      };
    }

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

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

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

<h1 class="text-4xl font-semibold">
  Build for <TextRotate words={["Laravel", "React", "Vue"]} />
</h1>
<TextRotate
  words={["faster", "with confidence", "every Friday"]}
  split="words"
  from="center"
  interval={3000}
/>
```

### Angular

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

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

const root = "relative inline-flex overflow-hidden align-bottom";
const unit = "inline-block whitespace-pre";

const EASE_IN = "cubic-bezier(0.55, 0, 1, 0.45)";
const EASE_OUT = "cubic-bezier(0.22, 1, 0.36, 1)";

const reducedMotion = () =>
  typeof matchMedia === "function" &&
  matchMedia("(prefers-reduced-motion: reduce)").matches;

export type TextRotateSplit = "chars" | "words";
export type TextRotateFrom = "first" | "last" | "center" | "random";

/** Splits a phrase into letters, or into words with the space after them. */
const splitText = (text: string, split: TextRotateSplit) =>
  split === "chars" ? Array.from(text) : text.split(/(?<= )/);

/** Stagger rank of each unit from the starting point. Random uses a fixed shuffled order (hash). */
function ranks(count: number, from: TextRotateFrom) {
  const order = [...Array(count).keys()];
  const hash = (i: number) => Math.imul(i + 1, 2654435761) >>> 0;
  if (from === "random") order.sort((a, b) => hash(a) - hash(b));
  const rank: number[] = [];
  order.forEach((index, position) => {
    const middle = Math.abs(index - (count - 1) / 2);
    rank[index] =
      from === "last"
        ? count - 1 - index
        : from === "center"
          ? middle
          : position;
  });
  return rank;
}

const unitsOf = (host: HTMLElement) => [
  ...host.querySelectorAll<HTMLElement>("[data-unit]"),
];

type RotateOptions = {
  count: number;
  from: TextRotateFrom;
  interval: number;
  stagger: number;
  duration: number;
  pauseOnHover: boolean;
};

/**
 * The old word leaves upward unit by unit, then `advance` renders the next one. Paused on
 * hover, off screen, or in a hidden tab. Returns a stop function.
 */
function startRotation(
  host: HTMLElement,
  options: RotateOptions,
  advance: (width: number) => void,
) {
  let hovered = false;
  let busy = false;
  let timer: ReturnType<typeof setInterval> | undefined;
  const next = () => {
    if (busy || (hovered && options.pauseOnHover) || document.hidden) return;
    busy = true;
    const list = unitsOf(host);
    const rank = ranks(list.length, options.from);
    const exits = list.map((el, i) =>
      el.animate?.(
        [
          { transform: "none", opacity: 1 },
          { transform: "translateY(-100%)", opacity: 0 },
        ],
        {
          duration: options.duration,
          delay: rank[i]! * options.stagger,
          easing: EASE_IN,
          fill: "forwards",
        },
      ),
    );
    Promise.all(exits.map((animation) => animation?.finished))
      .then(() => advance(host.offsetWidth))
      .catch(() => {})
      .finally(() => (busy = false));
  };
  const onEnter = () => (hovered = true);
  const onLeave = () => (hovered = false);
  host.addEventListener("pointerenter", onEnter);
  host.addEventListener("pointerleave", onLeave);
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver((entries) => {
          clearInterval(timer);
          if (entries.some((entry) => entry.isIntersecting))
            timer = setInterval(next, options.interval);
        });
  if (observer) observer.observe(host);
  else timer = setInterval(next, options.interval);
  return () => {
    observer?.disconnect();
    clearInterval(timer);
    host.removeEventListener("pointerenter", onEnter);
    host.removeEventListener("pointerleave", onLeave);
  };
}

/** The new word rises in unit by unit, and the width of the wrapper follows smoothly. */
function enter(
  host: HTMLElement,
  width: number,
  options: Pick<RotateOptions, "from" | "stagger" | "duration">,
) {
  const list = unitsOf(host);
  const rank = ranks(list.length, options.from);
  list.forEach((el, i) =>
    el.animate?.(
      [
        { transform: "translateY(100%)", opacity: 0 },
        { transform: "none", opacity: 1 },
      ],
      {
        duration: options.duration,
        delay: rank[i]! * options.stagger,
        easing: EASE_OUT,
        fill: "backwards",
      },
    ),
  );
  host.animate?.(
    [{ width: `${width}px` }, { width: `${host.offsetWidth}px` }],
    { duration: options.duration, easing: EASE_OUT },
  );
}

/** Attribute selector on a span, so the user's class and aria-* stay on the root. */
@Component({
  selector: "span[markas-text-rotate]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[class]": "root" },
  template: `<span class="sr-only">{{ label() }}</span>
    @for (part of parts(); track part.key) {
      <span aria-hidden="true" data-unit="" [class]="unit">{{
        part.text
      }}</span>
    }`,
})
export class TextRotate {
  readonly words = input.required<string[]>();
  readonly split = input<TextRotateSplit>("chars");
  readonly from = input<TextRotateFrom>("first");
  readonly interval = input(2500, { transform: numberAttribute });
  readonly stagger = input(25, { transform: numberAttribute });
  readonly duration = input(400, { transform: numberAttribute });
  readonly pauseOnHover = input(true, { transform: booleanAttribute });

  protected readonly root = root;
  protected readonly unit = unit;
  protected readonly label = computed(() => this.words().join(", "));
  /** Index of the word on screen. It goes back to the first word when the words change. */
  private readonly index = linkedSignal({
    source: this.words,
    computation: () => 0,
  });
  /** Width before the last swap, so the enter step can animate from it. Undefined when no swap is pending. */
  private pendingWidth: number | undefined;
  // Modulo keeps the index valid when the list of words changes.
  protected readonly parts = computed(() => {
    const words = this.words();
    const index = this.index();
    const current = words[index % Math.max(words.length, 1)] ?? "";
    return splitText(current, this.split()).map((text, i) => ({
      key: `${index}-${i}`,
      text,
    }));
  });
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    afterRenderEffect(() => {
      this.parts();
      const width = this.pendingWidth;
      if (width === undefined) return;
      this.pendingWidth = undefined;
      enter(this.host.nativeElement, width, {
        from: this.from(),
        stagger: this.stagger(),
        duration: this.duration(),
      });
    });
    afterRenderEffect((onCleanup) => {
      const options = {
        count: this.words().length,
        from: this.from(),
        interval: this.interval(),
        stagger: this.stagger(),
        duration: this.duration(),
        pauseOnHover: this.pauseOnHover(),
      };
      this.split();
      if (options.count < 2 || reducedMotion()) return;
      onCleanup(
        startRotation(this.host.nativeElement, options, (width) => {
          this.pendingWidth = width;
          this.index.update((current) => (current + 1) % options.count);
        }),
      );
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { TextRotate } from "./markas/text-rotate.component";

@Component({
  selector: "app-hero",
  imports: [TextRotate],
  template: `
    <h1 class="text-4xl font-semibold">
      Build for
      <span markas-text-rotate [words]="stacks"></span>
    </h1>
    <span
      markas-text-rotate
      [words]="phrases"
      split="words"
      from="center"
      interval="3000"
    ></span>
  `,
})
export class Hero {
  protected readonly stacks = ["Laravel", "React", "Vue"];
  protected readonly phrases = ["faster", "with confidence", "every Friday"];
}
```

Angular uses an attribute selector on a span, so `class` and `aria-*` land on the root. Astro renders the first word on the server and rotates it with a small script.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `words` | `string[]` | - | Words or phrases shown in turn. The first one is rendered on the server. |
| `split` | `"chars" \| "words"` | "chars" | Animate each letter or each word. |
| `from` | `"first" \| "last" \| "center" \| "random"` | "first" | Where the stagger starts. random uses a fixed shuffled order. |
| `interval` | `number` | 2500 | Milliseconds between two words. |
| `stagger` | `number` | 25 | Milliseconds between one unit and the next. |
| `duration` | `number` | 400 | Milliseconds each unit takes to leave or enter. The width follows over the same time. |
| `pauseOnHover` | `boolean` | true | Hold the current word while the pointer is over it. |

## Accessibility

- Screen readers read all words once from a visually hidden copy, joined with commas; the animated units are aria-hidden and nothing is announced on each turn.
- The rotation pauses on hover, when the text is off screen, and when the tab is hidden.
- With reduced motion, the first word stays and does not rotate.

## Notes

- The old word leaves upward unit by unit, then the next one rises in, and the width of the wrapper follows smoothly.
- The rotation pauses on hover (turn it off with `pauseOnHover`), when the text is off screen, and when the tab is hidden.
- Screen readers hear every word once, joined with commas, and nothing is announced on each turn.
- With reduced motion, the first word stays. The Blade version needs Alpine.js.
