# Vertical Cut Reveal

Teks yang naik dari balik garis potong per huruf, kata, atau baris saat masuk layar. Dibuat untuk judul hero.

- Kategori: Animasi
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/vertical-cut-reveal.json
- CLI: `npx markasui@latest add vertical-cut-reveal`

## Kapan dipakai

Judul hero, judul bagian, dan judul kartu yang perlu muncul dengan tegas saat masuk layar.

- Letakkan komponen di dalam elemen heading
- Pakai split lines dengan \n untuk judul hero beberapa baris
- Pakai delay bertingkat untuk memunculkan beberapa blok berurutan
- Blade butuh Alpine.js

## Kode

### Blade

Simpan di `resources/views/components/markas/vertical-cut-reveal.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'text' => '',
    'split' => 'words',
    'direction' => 'up',
    'from' => 'first',
    'stagger' => 60,
    'duration' => 700,
    'delay' => 0,
])

@php
    $root = 'block';
    $line = 'block';
    $lineCut = 'block overflow-hidden pb-[0.12em] -mb-[0.12em]';
    $cut = 'inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]';
    $unit = 'inline-block whitespace-pre';
    $lineUnit = 'block';

    $offsets = ['up' => 'translateY(120%)', 'down' => 'translateY(-120%)'];

    // Baris baru (\n) memecah teks menjadi beberapa baris.
    $lines = explode("\n", (string) $text);
@endphp

<span
    x-data="{
        observer: null,
        units: [],
        {{-- Sembunyikan setiap bagian di balik garis potong, lalu munculkan bergiliran saat teks masuk layar. --}}
        init() {
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const from = @js($from);
            const offset = @js($offsets[$direction]);
            this.units = [...this.$el.querySelectorAll('[data-unit]')];
            const count = this.units.length;
            {{-- Jeda stagger tiap bagian sesuai titik awal. Random memakai urutan acak tetap (hash). --}}
            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;
            });
            this.units.forEach((el) => (el.style.transform = offset));
            const reveal = () => this.units.forEach((el, i) => {
                el.animate?.([{ transform: offset }, { transform: 'none' }], { duration: @js((int) $duration), delay: @js((int) $delay) + rank[i] * @js((int) $stagger), easing: 'cubic-bezier(0.22, 1, 0.36, 1)', fill: 'backwards' });
                el.style.transform = '';
            });
            if (typeof IntersectionObserver === 'undefined') return reveal();
            this.observer = new IntersectionObserver((entries) => {
                if (! entries.some((entry) => entry.isIntersecting)) return;
                this.observer.disconnect();
                reveal();
            });
            this.observer.observe(this.$el);
        },
        destroy() {
            this.observer?.disconnect();
            this.units.forEach((el) => (el.style.transform = ''));
        },
    }"
    {{ $attributes->class([$root]) }}
><span class="sr-only">{{ implode(' ', $lines) }}</span><span aria-hidden="true">@foreach ($lines as $lineText)@if ($split === 'lines')<span class="{{ $lineCut }}"><span data-unit class="{{ $lineUnit }}">{{ $lineText }}</span></span>@else<span class="{{ $line }}">@foreach (explode(' ', $lineText) as $w => $word){{ $w > 0 ? ' ' : '' }}<span class="{{ $cut }}">@if ($split === 'words')<span data-unit class="{{ $unit }}">{{ $word }}</span>@else @foreach (mb_str_split($word) as $char)<span data-unit class="{{ $unit }}">{{ $char }}</span>@endforeach @endif</span>@endforeach</span>@endif @endforeach</span></span>
```

```blade
<h1 class="text-5xl leading-tight font-semibold">
    <x-markas.vertical-cut-reveal :text="implode(chr(10), ['Desain sekali.', 'Rilis di mana saja.'])" split="lines" />
</h1>
<p class="text-lg">
    <x-markas.vertical-cut-reveal text="Blade, React, dan Vue" split="chars" from="center" :delay="300" />
</p>
```

### React

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

```tsx
"use client";

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

const root = "block";
const line = "block";
const lineCut = "block overflow-hidden pb-[0.12em] -mb-[0.12em]";
const cut = "inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]";
const unit = "inline-block whitespace-pre";
const lineUnit = "block";

const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
const offsets = { up: "translateY(120%)", down: "translateY(-120%)" };

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

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

/** Jeda stagger tiap bagian sesuai titik awal. Random memakai urutan acak tetap (hash). */
function ranks(count: number, from: VerticalCutRevealProps["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 VerticalCutRevealProps = Omit<
  ComponentProps<"span">,
  "children"
> & {
  /** Baris baru (\n) memecah teks menjadi beberapa baris. */
  text: string;
  split?: "chars" | "words" | "lines";
  direction?: keyof typeof offsets;
  from?: "first" | "last" | "center" | "random";
  stagger?: number;
  duration?: number;
  delay?: number;
};

export function VerticalCutReveal({
  text,
  split = "words",
  direction = "up",
  from = "first",
  stagger = 60,
  duration = 700,
  delay = 0,
  className,
  ...props
}: VerticalCutRevealProps) {
  const rootRef = useRef<HTMLSpanElement>(null);
  const lines = text.split("\n");

  // Sembunyikan setiap bagian di balik garis potong, lalu munculkan bergiliran saat teks masuk layar.
  useLayoutEffect(() => {
    const element = rootRef.current;
    if (!element || reducedMotion()) return;
    const units = [...element.querySelectorAll<HTMLElement>("[data-unit]")];
    const rank = ranks(units.length, from);
    const offset = offsets[direction];
    units.forEach((el) => (el.style.transform = offset));
    const reveal = () =>
      units.forEach((el, i) => {
        el.animate?.([{ transform: offset }, { transform: "none" }], {
          duration,
          delay: delay + rank[i]! * stagger,
          easing: EASING,
          fill: "backwards",
        });
        el.style.transform = "";
      });
    if (typeof IntersectionObserver === "undefined") {
      reveal();
      return;
    }
    const observer = new IntersectionObserver((entries) => {
      if (!entries.some((entry) => entry.isIntersecting)) return;
      observer.disconnect();
      reveal();
    });
    observer.observe(element);
    return () => {
      observer.disconnect();
      units.forEach((el) => (el.style.transform = ""));
    };
  }, [text, split, direction, from, stagger, duration, delay]);

  return (
    <span ref={rootRef} {...props} className={cx(root, className)}>
      <span className="sr-only">{lines.join(" ")}</span>
      <span aria-hidden="true">
        {lines.map((lineText, l) =>
          split === "lines" ? (
            <span key={l} className={lineCut}>
              <span data-unit="" className={lineUnit}>
                {lineText}
              </span>
            </span>
          ) : (
            <span key={l} className={line}>
              {lineText.split(" ").map((word, w) => (
                <Fragment key={w}>
                  {w > 0 && " "}
                  <span className={cut}>
                    {split === "words" ? (
                      <span data-unit="" className={unit}>
                        {word}
                      </span>
                    ) : (
                      Array.from(word).map((char, c) => (
                        <span key={c} data-unit="" className={unit}>
                          {char}
                        </span>
                      ))
                    )}
                  </span>
                </Fragment>
              ))}
            </span>
          ),
        )}
      </span>
    </span>
  );
}
```

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

<h1 className="text-5xl leading-tight font-semibold">
  <VerticalCutReveal text={'Desain sekali.\nRilis di mana saja.'} split="lines" />
</h1>
<p className="text-lg">
  <VerticalCutReveal text="Blade, React, dan Vue" split="chars" from="center" delay={300} />
</p>
```

### Vue

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

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

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

const props = withDefaults(
  defineProps<{
    /** Baris baru (\n) memecah teks menjadi beberapa baris. */
    text: string;
    split?: "chars" | "words" | "lines";
    direction?: "up" | "down";
    from?: From;
    stagger?: number;
    duration?: number;
    delay?: number;
  }>(),
  {
    split: "words",
    direction: "up",
    from: "first",
    stagger: 60,
    duration: 700,
    delay: 0,
  },
);

const root = "block";
const line = "block";
const lineCut = "block overflow-hidden pb-[0.12em] -mb-[0.12em]";
const cut = "inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]";
const unit = "inline-block whitespace-pre";
const lineUnit = "block";

const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
const offsets = { up: "translateY(120%)", down: "translateY(-120%)" };

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

/** 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 lines = computed(() => props.text.split("\n"));
const rootEl = useTemplateRef<HTMLSpanElement>("rootRef");
let cleanup = () => {};

// Sembunyikan setiap bagian di balik garis potong, lalu munculkan bergiliran saat teks masuk layar.
function start() {
  cleanup();
  const element = rootEl.value;
  if (!element || reducedMotion()) return;
  const { duration, delay, stagger } = props;
  const units = [...element.querySelectorAll<HTMLElement>("[data-unit]")];
  const rank = ranks(units.length, props.from);
  const offset = offsets[props.direction];
  units.forEach((el) => (el.style.transform = offset));
  const reveal = () =>
    units.forEach((el, i) => {
      el.animate?.([{ transform: offset }, { transform: "none" }], {
        duration,
        delay: delay + rank[i]! * stagger,
        easing: EASING,
        fill: "backwards",
      });
      el.style.transform = "";
    });
  if (typeof IntersectionObserver === "undefined") return reveal();
  const observer = new IntersectionObserver((entries) => {
    if (!entries.some((entry) => entry.isIntersecting)) return;
    observer.disconnect();
    reveal();
  });
  observer.observe(element);
  cleanup = () => {
    observer.disconnect();
    units.forEach((el) => (el.style.transform = ""));
  };
}

onMounted(start);
watch(
  () => [
    props.text,
    props.split,
    props.direction,
    props.from,
    props.stagger,
    props.duration,
    props.delay,
  ],
  start,
  { flush: "post" },
);
onBeforeUnmount(() => cleanup());
</script>

<template>
  <span ref="rootRef" :class="root"
    ><span class="sr-only">{{ lines.join(" ") }}</span
    ><span aria-hidden="true"
      ><template v-for="(lineText, l) in lines" :key="l"
        ><span v-if="props.split === 'lines'" :class="lineCut"
          ><span data-unit :class="lineUnit">{{ lineText }}</span></span
        ><span v-else :class="line"
          ><template v-for="(word, w) in lineText.split(' ')" :key="w"
            >{{ w > 0 ? " " : ""
            }}<span :class="cut"
              ><span v-if="props.split === 'words'" data-unit :class="unit">{{
                word
              }}</span
              ><template v-else
                ><span
                  v-for="(char, c) in Array.from(word)"
                  :key="c"
                  data-unit
                  :class="unit"
                  >{{ char }}</span
                ></template
              ></span
            ></template
          ></span
        ></template
      ></span
    ></span
  >
</template>
```

```vue
<template>
  <h1 class="text-5xl leading-tight font-semibold">
    <VerticalCutReveal
      :text="'Desain sekali.\nRilis di mana saja.'"
      split="lines"
    />
  </h1>
  <p class="text-lg">
    <VerticalCutReveal
      text="Blade, React, dan Vue"
      split="chars"
      from="center"
      :delay="300"
    />
  </p>
</template>
```

### Svelte

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

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

  const root = "block";
  const line = "block";
  const lineCut = "block overflow-hidden pb-[0.12em] -mb-[0.12em]";
  const cut = "inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]";
  const unit = "inline-block whitespace-pre";
  const lineUnit = "block";

  const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
  const offsets = { up: "translateY(120%)", down: "translateY(-120%)" };

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

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

  /** 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"> & {
    /** A line break (\n) splits the text into several lines. */
    text: string;
    split?: "chars" | "words" | "lines";
    direction?: keyof typeof offsets;
    from?: From;
    stagger?: number;
    duration?: number;
    delay?: number;
  };

  let {
    text,
    split = "words",
    direction = "up",
    from = "first",
    stagger = 60,
    duration = 700,
    delay = 0,
    class: className,
    ...rest
  }: Props = $props();

  let element = $state<HTMLSpanElement>();
  const lines = $derived(text.split("\n"));

  // Hide every unit behind the cut line, then reveal them in turn once the text scrolls into view.
  $effect(() => {
    // Read every prop up front so the effect reruns when one changes.
    const options = { from, stagger, duration, delay, split, lines };
    const offset = offsets[direction];
    if (!element || reducedMotion()) return;
    const units = [...element.querySelectorAll<HTMLElement>("[data-unit]")];
    const rank = ranks(units.length, options.from);
    units.forEach((el) => (el.style.transform = offset));
    const reveal = () =>
      units.forEach((el, i) => {
        el.animate?.([{ transform: offset }, { transform: "none" }], {
          duration: options.duration,
          delay: options.delay + rank[i]! * options.stagger,
          easing: EASING,
          fill: "backwards",
        });
        el.style.transform = "";
      });
    if (typeof IntersectionObserver === "undefined") return reveal();
    const observer = new IntersectionObserver((entries) => {
      if (!entries.some((entry) => entry.isIntersecting)) return;
      observer.disconnect();
      reveal();
    });
    observer.observe(element);
    return () => {
      observer.disconnect();
      units.forEach((el) => (el.style.transform = ""));
    };
  });
</script>

<span bind:this={element} {...rest} class={[root, className]}
  ><span class="sr-only">{lines.join(" ")}</span><span aria-hidden="true"
    >{#each lines as lineText, l (l)}{#if split === "lines"}<span
          class={lineCut}
          ><span data-unit="" class={lineUnit}>{lineText}</span></span
        >{:else}<span class={line}
          >{#each lineText.split(" ") as word, w (w)}{#if w > 0}{" "}{/if}<span
              class={cut}
              >{#if split === "words"}<span data-unit="" class={unit}
                  >{word}</span
                >{:else}{#each Array.from(word) as char, c (c)}<span
                    data-unit=""
                    class={unit}>{char}</span
                  >{/each}{/if}</span
            >{/each}</span
        >{/if}{/each}</span
  ></span
>
```

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

<h1 class="text-5xl leading-tight font-semibold">
  <VerticalCutReveal
    text={"Desain sekali.\nRilis di mana saja."}
    split="lines"
  />
</h1>
<p class="text-lg">
  <VerticalCutReveal
    text="Blade, React, dan Vue"
    split="chars"
    from="center"
    delay={300}
  />
</p>
```

### Astro

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

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

const root = "block";
const line = "block";
const lineCut = "block overflow-hidden pb-[0.12em] -mb-[0.12em]";
const cut = "inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]";
const unit = "inline-block whitespace-pre";
const lineUnit = "block";

const offsets = { up: "translateY(120%)", down: "translateY(-120%)" };

type Props = Omit<HTMLAttributes<"span">, "children"> & {
  /** A line break (\n) splits the text into several lines. */
  text: string;
  split?: "chars" | "words" | "lines";
  direction?: keyof typeof offsets;
  from?: "first" | "last" | "center" | "random";
  stagger?: number;
  duration?: number;
  delay?: number;
};

const {
  text,
  split = "words",
  direction = "up",
  from = "first",
  stagger = 60,
  duration = 700,
  delay = 0,
  class: className,
  ...rest
} = Astro.props;
const lines = text.split("\n");
---

<markas-vertical-cut-reveal class="contents" data-offset={offsets[direction]} data-from={from} data-stagger={stagger} data-duration={duration} data-delay={delay}><span {...rest} class:list={[root, className]}><span class="sr-only">{lines.join(" ")}</span><span aria-hidden="true">{
  lines.map((lineText) =>
    split === "lines" ? (
      <span class={lineCut}><span data-unit="" class={lineUnit}>{lineText}</span></span>
    ) : (
      <span class={line}>{lineText.split(" ").map((word, w) => (
        <Fragment>{w > 0 && " "}<span class={cut}>{split === "words" ? (
          <span data-unit="" class={unit}>{word}</span>
        ) : (
          Array.from(word).map((char) => <span data-unit="" class={unit}>{char}</span>)
        )}</span></Fragment>
      ))}</span>
    ),
  )
}</span></span></markas-vertical-cut-reveal>

<script>
  const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";

  /** 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;
  }

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

    // Hide every unit behind the cut line, then reveal them in turn once the text scrolls into view.
    connectedCallback() {
      const element = this.firstElementChild;
      if (!element || matchMedia("(prefers-reduced-motion: reduce)").matches)
        return;
      const offset = this.dataset.offset ?? "";
      const duration = Number(this.dataset.duration);
      const delay = Number(this.dataset.delay);
      const stagger = Number(this.dataset.stagger);
      const units = [...element.querySelectorAll<HTMLElement>("[data-unit]")];
      const rank = ranks(units.length, this.dataset.from);
      units.forEach((el) => (el.style.transform = offset));
      const reveal = () =>
        units.forEach((el, i) => {
          el.animate?.([{ transform: offset }, { transform: "none" }], {
            duration,
            delay: delay + rank[i]! * stagger,
            easing: EASING,
            fill: "backwards",
          });
          el.style.transform = "";
        });
      if (typeof IntersectionObserver === "undefined") return reveal();
      const observer = new IntersectionObserver((entries) => {
        if (!entries.some((entry) => entry.isIntersecting)) return;
        observer.disconnect();
        reveal();
      });
      observer.observe(element);
      this.cleanup = () => {
        observer.disconnect();
        units.forEach((el) => (el.style.transform = ""));
      };
    }

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

  if (!customElements.get("markas-vertical-cut-reveal"))
    customElements.define("markas-vertical-cut-reveal", MarkasVerticalCutReveal);
</script>
```

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

<h1 class="text-5xl leading-tight font-semibold">
  <VerticalCutReveal text={"Desain sekali.\nRilis di mana saja."} split="lines" />
</h1>
<p class="text-lg">
  <VerticalCutReveal text="Blade, React, dan Vue" split="chars" from="center" delay={300} />
</p>
```

### Angular

Simpan di `src/app/markas/vertical-cut-reveal.component.ts`. Tanpa dependensi tambahan.

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

const root = "block";
const line = "block";
const lineCut = "block overflow-hidden pb-[0.12em] -mb-[0.12em]";
const cut = "inline-flex overflow-hidden pb-[0.12em] -mb-[0.12em]";
const unit = "inline-block whitespace-pre";
const lineUnit = "block";

const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
const offsets = { up: "translateY(120%)", down: "translateY(-120%)" };

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

export type VerticalCutRevealSplit = "chars" | "words" | "lines";
export type VerticalCutRevealDirection = keyof typeof offsets;
export type VerticalCutRevealFrom = "first" | "last" | "center" | "random";

/** Stagger rank of each unit from the starting point. Random uses a fixed shuffled order (hash). */
function ranks(count: number, from: VerticalCutRevealFrom) {
  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 RevealOptions = {
  direction: VerticalCutRevealDirection;
  from: VerticalCutRevealFrom;
  stagger: number;
  duration: number;
  delay: number;
};

/** Hide every unit behind the cut line, then reveal them in turn once the text scrolls into view. */
function startReveal(element: HTMLElement, options: RevealOptions) {
  const units = [...element.querySelectorAll<HTMLElement>("[data-unit]")];
  const rank = ranks(units.length, options.from);
  const offset = offsets[options.direction];
  units.forEach((el) => (el.style.transform = offset));
  const reveal = () =>
    units.forEach((el, i) => {
      el.animate?.([{ transform: offset }, { transform: "none" }], {
        duration: options.duration,
        delay: options.delay + rank[i]! * options.stagger,
        easing: EASING,
        fill: "backwards",
      });
      el.style.transform = "";
    });
  if (typeof IntersectionObserver === "undefined") {
    reveal();
    return () => {};
  }
  const observer = new IntersectionObserver((entries) => {
    if (!entries.some((entry) => entry.isIntersecting)) return;
    observer.disconnect();
    reveal();
  });
  observer.observe(element);
  return () => {
    observer.disconnect();
    units.forEach((el) => (el.style.transform = ""));
  };
}

/** Attribute selector on a span, so the user's class and aria-* stay on the root. */
@Component({
  selector: "span[markas-vertical-cut-reveal]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[class]": "root" },
  template: `<span class="sr-only">{{ label() }}</span
    ><span aria-hidden="true">
      @for (lineText of lines(); track $index) {
        @if (split() === "lines") {
          <span [class]="lineCut"
            ><span data-unit="" [class]="lineUnit">{{ lineText }}</span></span
          >
        } @else {
          <span [class]="line">
            @for (word of lineText.split(" "); track $index; let w = $index) {
              @if (w > 0) {
                &ngsp;
              }
              <span [class]="cut">
                @if (split() === "words") {
                  <span data-unit="" [class]="unit">{{ word }}</span>
                } @else {
                  @for (char of chars(word); track $index) {
                    <span data-unit="" [class]="unit">{{ char }}</span>
                  }
                }
              </span>
            }
          </span>
        }
      }
    </span>`,
})
export class VerticalCutReveal {
  /** A line break (\n) splits the text into several lines. */
  readonly text = input.required<string>();
  readonly split = input<VerticalCutRevealSplit>("words");
  readonly direction = input<VerticalCutRevealDirection>("up");
  readonly from = input<VerticalCutRevealFrom>("first");
  readonly stagger = input(60, { transform: numberAttribute });
  readonly duration = input(700, { transform: numberAttribute });
  readonly delay = input(0, { transform: numberAttribute });

  protected readonly root = root;
  protected readonly line = line;
  protected readonly lineCut = lineCut;
  protected readonly cut = cut;
  protected readonly unit = unit;
  protected readonly lineUnit = lineUnit;
  protected readonly lines = computed(() => this.text().split("\n"));
  protected readonly label = computed(() => this.lines().join(" "));
  protected readonly chars = (word: string) => Array.from(word);
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    afterRenderEffect((onCleanup) => {
      const options = {
        direction: this.direction(),
        from: this.from(),
        stagger: this.stagger(),
        duration: this.duration(),
        delay: this.delay(),
      };
      this.lines();
      this.split();
      if (reducedMotion()) return;
      onCleanup(startReveal(this.host.nativeElement, options));
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { VerticalCutReveal } from "./markas/vertical-cut-reveal.component";

@Component({
  selector: "app-launch",
  imports: [VerticalCutReveal],
  template: `
    <h1 class="text-5xl leading-tight font-semibold">
      <span markas-vertical-cut-reveal [text]="title" split="lines"></span>
    </h1>
    <p class="text-lg">
      <span
        markas-vertical-cut-reveal
        text="Blade, React, dan Vue"
        split="chars"
        from="center"
        delay="300"
      ></span>
    </p>
  `,
})
export class Launch {
  protected readonly title = "Desain sekali.\nRilis di mana saja.";
}
```

Angular memakai attribute selector pada span: `<span markas-vertical-cut-reveal>`. Teks dengan baris baru dikirim lewat property binding.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `text` | `string` | - | Teks yang dimunculkan. Baris baru (\n) memulai baris berikutnya. |
| `split` | `"chars" \| "words" \| "lines"` | "words" | Munculkan per huruf, per kata, atau per baris. |
| `direction` | `"up" \| "down"` | "up" | Bagian naik dari bawah garis potong atau turun dari atasnya. |
| `from` | `"first" \| "last" \| "center" \| "random"` | "first" | Titik awal stagger. random memakai urutan acak yang tetap. |
| `stagger` | `number` | 60 | Milidetik antara satu bagian dan bagian berikutnya. |
| `duration` | `number` | 700 | Milidetik yang dibutuhkan setiap bagian untuk muncul. |
| `delay` | `number` | 0 | Milidetik menunggu setelah teks masuk layar. Pakai delay bertingkat untuk memunculkan judul lalu subjudulnya. |

## Aksesibilitas

- Screen reader membaca teks utuh sekali dari salinan tersembunyi; bagian yang bergerak memakai aria-hidden.
- Teks dirender di tempatnya oleh server sehingga terbaca tanpa JavaScript.
- Dengan reduced motion, teks langsung tampil.

## Catatan

- Teks dirender di tempatnya oleh server. Di browser setiap bagian bersembunyi di balik garis potong dan naik saat teks masuk layar.
- Baris baru (`\n`) memulai baris berikutnya. Di Blade, buat dengan `implode(chr(10), [...])` atau string PHP berkutip ganda.
- Pakai `delay` bertingkat untuk memunculkan judul, harga, dan keterangan berurutan.
- Screen reader membaca teks utuh sekali. Dengan reduced motion, teks langsung tampil. Versi Blade butuh Alpine.js.
