# Pixel Trail

Grid sel kecil yang menyala di bawah kursor lalu memudar, digambar di satu canvas. Fokus keyboard menyalakan sel di sekitar elemen yang difokus.

- Kategori: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/pixel-trail.json
- CLI: `npx markasui@latest add pixel-trail`

## Kapan dipakai

Latar hero interaktif, kartu ajakan bertindak, strip navbar, atau area coret-coret yang ceria tempat kursor meninggalkan jejak piksel.

- Beri komponen tinggi dan latar; sel berada di belakang konten
- Pakai sel besar (20 sampai 32 px) untuk area luas dan sel kecil (8 sampai 12 px) untuk strip tipis
- Jaga fade antara 400 dan 1500 ms agar jejak tidak tertinggal lama
- Pakai satu pixel trail per layar dan jaga kontras konten tetap tinggi

## Kode

### Blade

Simpan di `resources/views/components/markas/pixel-trail.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'cellSize' => 24,
    'fade' => 600,
    'variant' => 'pixel',
    'color' => 'primary',
    'showGrid' => false,
    'autoplay' => false,
])

@php
    $base = 'relative isolate overflow-hidden';
    $canvasClass = 'pointer-events-none absolute inset-0 -z-10 size-full';
    $gridClass = 'bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]';
    $colors = [
        'primary' => 'text-primary',
        'success' => 'text-success',
        'warning' => 'text-warning',
        'danger' => 'text-danger',
        'ink' => 'text-ink',
    ];
    $options = [
        'size' => (float) $cellSize,
        'fade' => (float) $fade,
        'variant' => in_array($variant, ['pixel', 'dot', 'brush'], true) ? $variant : 'pixel',
        'autoplay' => (bool) $autoplay,
    ];
@endphp

{{-- Lights the cell under the pointer on a canvas and fades it over `fade` ms. Keyboard focus lights the cells around the focused element. --}}
<div
    x-data="{
        stop: null,
        init() {
            const { size, fade, variant, autoplay } = @js($options);
            const root = this.$root;
            const canvas = this.$refs.canvas;
            const context = canvas.getContext?.('2d');
            if (! context || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const lit = new Map();
            let last = null;
            let frame = 0;
            let color = '';
            let inside = false;
            const resize = () => {
                const ratio = window.devicePixelRatio || 1;
                canvas.width = canvas.clientWidth * ratio;
                canvas.height = canvas.clientHeight * ratio;
                context.setTransform(ratio, 0, 0, ratio, 0, 0);
            };
            const draw = (now) => {
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.fillStyle = color;
                for (const [key, cell] of lit) {
                    const alpha = cell.strength * (1 - (now - cell.time) / fade);
                    if (alpha <= 0) {
                        lit.delete(key);
                        continue;
                    }
                    const [col, row] = key.split(',').map(Number);
                    context.globalAlpha = Math.min(alpha, 1);
                    context.beginPath();
                    if (variant === 'dot') context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
                    else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
                    context.fill();
                }
                frame = lit.size ? requestAnimationFrame(draw) : 0;
            };
            const light = (col, row, strength = 1) => {
                const key = `${col},${row}`;
                const current = lit.get(key);
                if (! current || current.strength * 0.8 <= strength) lit.set(key, { time: performance.now(), strength });
                if (frame) return;
                color = getComputedStyle(canvas).color;
                frame = requestAnimationFrame(draw);
            };
            const paint = (x, y) => {
                const col = Math.floor(x / size);
                const row = Math.floor(y / size);
                light(col, row);
                if (variant !== 'brush') return;
                for (let dx = -2; dx <= 2; dx++)
                    for (let dy = -2; dy <= 2; dy++) {
                        const far = Math.max(Math.abs(dx), Math.abs(dy));
                        if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
                    }
            };
            {{-- Paint every half cell between the last point and this one, so fast moves leave no gaps. --}}
            const trail = (x, y) => {
                const from = last ?? { x, y };
                const steps = Math.max(1, Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)));
                for (let i = 1; i <= steps; i++) paint(from.x + ((x - from.x) * i) / steps, from.y + ((y - from.y) * i) / steps);
                last = { x, y };
            };
            const move = (event) => {
                inside = true;
                const rect = root.getBoundingClientRect();
                trail(event.clientX - rect.left, event.clientY - rect.top);
            };
            const leave = () => {
                inside = false;
                last = null;
            };
            const focus = (event) => {
                const target = event.target;
                if (target === root || ! target.matches?.(':focus-visible')) return;
                const box = root.getBoundingClientRect();
                const rect = target.getBoundingClientRect();
                const left = Math.floor((rect.left - box.left) / size) - 1;
                const top = Math.floor((rect.top - box.top) / size) - 1;
                const right = Math.floor((rect.right - box.left) / size) + 1;
                const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
                for (let col = left; col <= right; col++)
                    for (let row = top; row <= bottom; row++)
                        if (col === left || col === right || row === top || row === bottom) light(col, row, 0.8);
            };
            resize();
            const resizer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null;
            resizer?.observe(canvas);
            root.addEventListener('pointermove', move);
            root.addEventListener('pointerleave', leave);
            root.addEventListener('focusin', focus);
            {{-- Autoplay: a trail of its own while visible, the tab is shown, and the pointer is elsewhere. --}}
            let auto = 0;
            let observer = null;
            let sync = null;
            if (autoplay && typeof IntersectionObserver === 'function') {
                let seen = false;
                const run = (now) => {
                    if (! inside) {
                        const t = now / 1000;
                        trail(canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)), canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)));
                    }
                    auto = requestAnimationFrame(run);
                };
                sync = () => {
                    cancelAnimationFrame(auto);
                    if (seen && ! document.hidden) auto = requestAnimationFrame(run);
                };
                observer = new IntersectionObserver(([entry]) => {
                    seen = Boolean(entry?.isIntersecting);
                    sync();
                });
                observer.observe(root);
                document.addEventListener('visibilitychange', sync);
            }
            this.stop = () => {
                resizer?.disconnect();
                observer?.disconnect();
                if (sync) document.removeEventListener('visibilitychange', sync);
                root.removeEventListener('pointermove', move);
                root.removeEventListener('pointerleave', leave);
                root.removeEventListener('focusin', focus);
                cancelAnimationFrame(auto);
                cancelAnimationFrame(frame);
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->merge(['style' => '--cell: '.(float) $cellSize.'px'])->class([$base]) }}
>
    <canvas x-ref="canvas" wire:ignore aria-hidden="true" @class([$canvasClass, $colors[$color] ?? $colors['primary'], $gridClass => $showGrid])></canvas>
    {{ $slot }}
</div>
```

```blade
<x-markas.pixel-trail variant="dot" color="success" :cell-size="16" :fade="900" show-grid class="grid h-80 place-items-center rounded-xl bg-surface">
    <h1 class="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
</x-markas.pixel-trail>
```

Butuh Alpine.js.

### React

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

```tsx
"use client";

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

export type PixelTrailVariant = "pixel" | "dot" | "brush";

const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
  "bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
  ink: "text-ink",
};

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

type TrailOptions = {
  size: number;
  fade: number;
  variant: PixelTrailVariant;
  autoplay: boolean;
};

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

/**
 * Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
 * the cells around the focused element. The canvas only redraws while some cell is still lit.
 */
function createPixels(
  root: HTMLElement,
  canvas: HTMLCanvasElement,
  options: TrailOptions,
) {
  const { size, fade, variant } = options;
  const context = canvas.getContext?.("2d");
  if (!context || still()) return () => {};
  const lit = new Map<string, { time: number; strength: number }>();
  let last: { x: number; y: number } | null = null;
  let frame = 0;
  let color = "";

  const resize = () => {
    const ratio = window.devicePixelRatio || 1;
    canvas.width = canvas.clientWidth * ratio;
    canvas.height = canvas.clientHeight * ratio;
    context.setTransform(ratio, 0, 0, ratio, 0, 0);
  };
  const draw = (now: number) => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = color;
    for (const [key, cell] of lit) {
      const alpha = cell.strength * (1 - (now - cell.time) / fade);
      if (alpha <= 0) {
        lit.delete(key);
        continue;
      }
      const [col = 0, row = 0] = key.split(",").map(Number);
      context.globalAlpha = Math.min(alpha, 1);
      context.beginPath();
      if (variant === "dot")
        context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
      else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
      context.fill();
    }
    frame = lit.size ? requestAnimationFrame(draw) : 0;
  };
  const light = (col: number, row: number, strength = 1) => {
    const key = `${col},${row}`;
    const time = performance.now();
    const current = lit.get(key);
    if (!current || current.strength * 0.8 <= strength)
      lit.set(key, { time, strength });
    if (frame) return;
    color = getComputedStyle(canvas).color;
    frame = requestAnimationFrame(draw);
  };
  const paint = (x: number, y: number) => {
    const col = Math.floor(x / size);
    const row = Math.floor(y / size);
    light(col, row);
    if (variant !== "brush") return;
    for (let dx = -2; dx <= 2; dx++)
      for (let dy = -2; dy <= 2; dy++) {
        const far = Math.max(Math.abs(dx), Math.abs(dy));
        if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
      }
  };
  /** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
  const trail = (x: number, y: number) => {
    const from = last ?? { x, y };
    const steps = Math.max(
      1,
      Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
    );
    for (let i = 1; i <= steps; i++)
      paint(
        from.x + ((x - from.x) * i) / steps,
        from.y + ((y - from.y) * i) / steps,
      );
    last = { x, y };
  };

  let inside = false;
  const move = (event: PointerEvent) => {
    inside = true;
    const rect = root.getBoundingClientRect();
    trail(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
  };
  const focus = (event: FocusEvent) => {
    const target = event.target as HTMLElement;
    if (target === root || !target.matches?.(":focus-visible")) return;
    const box = root.getBoundingClientRect();
    const rect = target.getBoundingClientRect();
    const left = Math.floor((rect.left - box.left) / size) - 1;
    const top = Math.floor((rect.top - box.top) / size) - 1;
    const right = Math.floor((rect.right - box.left) / size) + 1;
    const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
    for (let col = left; col <= right; col++)
      for (let row = top; row <= bottom; row++)
        if (col === left || col === right || row === top || row === bottom)
          light(col, row, 0.8);
  };

  resize();
  const observer =
    typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
  observer?.observe(canvas);
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  root.addEventListener("focusin", focus);
  const stopAuto =
    options.autoplay && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1000;
          trail(
            canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
            canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
          );
        })
      : null;

  return () => {
    observer?.disconnect();
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    root.removeEventListener("focusin", focus);
    stopAuto?.();
    cancelAnimationFrame(frame);
  };
}

export type PixelTrailProps = ComponentProps<"div"> & {
  /** Side of one cell in px. */
  cellSize?: number;
  /** How long a lit cell takes to fade out, in ms. */
  fade?: number;
  /** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
  variant?: PixelTrailVariant;
  /** Light color token. */
  color?: keyof typeof colors;
  /** Draws faint grid lines between the cells. */
  showGrid?: boolean;
  /** Draws a trail on its own while visible and the pointer is elsewhere. */
  autoplay?: boolean;
};

export function PixelTrail({
  cellSize = 24,
  fade = 600,
  variant = "pixel",
  color = "primary",
  showGrid = false,
  autoplay = false,
  className,
  style,
  children,
  ...props
}: PixelTrailProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(
    () =>
      createPixels(rootRef.current!, canvasRef.current!, {
        size: cellSize,
        fade,
        variant,
        autoplay,
      }),
    [cellSize, fade, variant, autoplay],
  );
  return (
    <div
      {...props}
      ref={rootRef}
      className={cx(base, className)}
      style={
        {
          "--cell": `${cellSize}px`,
          ...style,
        } as ComponentProps<"div">["style"]
      }
    >
      <canvas
        ref={canvasRef}
        aria-hidden="true"
        className={cx(canvasClass, colors[color], showGrid && gridClass)}
      ></canvas>
      {children}
    </div>
  );
}
```

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

<PixelTrail
  variant="dot"
  color="success"
  cellSize={16}
  fade={900}
  showGrid
  className="grid h-80 place-items-center rounded-xl bg-surface"
>
  <h1 className="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
</PixelTrail>;
```

### Vue

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

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

export type PixelTrailVariant = "pixel" | "dot" | "brush";

const colors = {
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
  ink: "text-ink",
};

const props = withDefaults(
  defineProps<{
    /** Side of one cell in px. */
    cellSize?: number;
    /** How long a lit cell takes to fade out, in ms. */
    fade?: number;
    /** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
    variant?: PixelTrailVariant;
    /** Light color token. */
    color?: keyof typeof colors;
    /** Draws faint grid lines between the cells. */
    showGrid?: boolean;
    /** Draws a trail on its own while visible and the pointer is elsewhere. */
    autoplay?: boolean;
  }>(),
  {
    cellSize: 24,
    fade: 600,
    variant: "pixel",
    color: "primary",
    showGrid: false,
    autoplay: false,
  },
);

const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
  "bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

/**
 * Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
 * the cells around the focused element. The canvas only redraws while some cell is still lit.
 */
function createPixels(root: HTMLElement, canvas: HTMLCanvasElement) {
  const { cellSize: size, fade, variant } = props;
  const context = canvas.getContext?.("2d");
  if (!context || still()) return () => {};
  const lit = new Map<string, { time: number; strength: number }>();
  let last: { x: number; y: number } | null = null;
  let frame = 0;
  let color = "";

  const resize = () => {
    const ratio = window.devicePixelRatio || 1;
    canvas.width = canvas.clientWidth * ratio;
    canvas.height = canvas.clientHeight * ratio;
    context.setTransform(ratio, 0, 0, ratio, 0, 0);
  };
  const draw = (now: number) => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = color;
    for (const [key, cell] of lit) {
      const alpha = cell.strength * (1 - (now - cell.time) / fade);
      if (alpha <= 0) {
        lit.delete(key);
        continue;
      }
      const [col = 0, row = 0] = key.split(",").map(Number);
      context.globalAlpha = Math.min(alpha, 1);
      context.beginPath();
      if (variant === "dot")
        context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
      else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
      context.fill();
    }
    frame = lit.size ? requestAnimationFrame(draw) : 0;
  };
  const light = (col: number, row: number, strength = 1) => {
    const key = `${col},${row}`;
    const time = performance.now();
    const current = lit.get(key);
    if (!current || current.strength * 0.8 <= strength)
      lit.set(key, { time, strength });
    if (frame) return;
    color = getComputedStyle(canvas).color;
    frame = requestAnimationFrame(draw);
  };
  const paint = (x: number, y: number) => {
    const col = Math.floor(x / size);
    const row = Math.floor(y / size);
    light(col, row);
    if (variant !== "brush") return;
    for (let dx = -2; dx <= 2; dx++)
      for (let dy = -2; dy <= 2; dy++) {
        const far = Math.max(Math.abs(dx), Math.abs(dy));
        if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
      }
  };
  /** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
  const trail = (x: number, y: number) => {
    const from = last ?? { x, y };
    const steps = Math.max(
      1,
      Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
    );
    for (let i = 1; i <= steps; i++)
      paint(
        from.x + ((x - from.x) * i) / steps,
        from.y + ((y - from.y) * i) / steps,
      );
    last = { x, y };
  };

  let inside = false;
  const move = (event: PointerEvent) => {
    inside = true;
    const rect = root.getBoundingClientRect();
    trail(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
  };
  const focus = (event: FocusEvent) => {
    const target = event.target as HTMLElement;
    if (target === root || !target.matches?.(":focus-visible")) return;
    const box = root.getBoundingClientRect();
    const rect = target.getBoundingClientRect();
    const left = Math.floor((rect.left - box.left) / size) - 1;
    const top = Math.floor((rect.top - box.top) / size) - 1;
    const right = Math.floor((rect.right - box.left) / size) + 1;
    const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
    for (let col = left; col <= right; col++)
      for (let row = top; row <= bottom; row++)
        if (col === left || col === right || row === top || row === bottom)
          light(col, row, 0.8);
  };

  resize();
  const observer =
    typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
  observer?.observe(canvas);
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  root.addEventListener("focusin", focus);
  const stopAuto =
    props.autoplay && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1000;
          trail(
            canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
            canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
          );
        })
      : null;

  return () => {
    observer?.disconnect();
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    root.removeEventListener("focusin", focus);
    stopAuto?.();
    cancelAnimationFrame(frame);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
const canvasEl = useTemplateRef<HTMLCanvasElement>("canvasRef");
let stop = () => {};
const start = () => {
  stop();
  stop = createPixels(rootEl.value!, canvasEl.value!);
};
onMounted(start);
watch(() => [props.cellSize, props.fade, props.variant, props.autoplay], start);
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="base" :style="{ '--cell': `${props.cellSize}px` }">
    <canvas
      ref="canvasRef"
      aria-hidden="true"
      :class="[canvasClass, colors[props.color], props.showGrid && gridClass]"
    ></canvas>
    <slot />
  </div>
</template>
```

```vue
<template>
  <PixelTrail
    variant="dot"
    color="success"
    :cell-size="16"
    :fade="900"
    show-grid
    class="grid h-80 place-items-center rounded-xl bg-surface"
  >
    <h1 class="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
  </PixelTrail>
</template>
```

### Svelte

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

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

  type PixelTrailVariant = "pixel" | "dot" | "brush";

  const base = "relative isolate overflow-hidden";
  const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
  const gridClass =
    "bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
  const colors = {
    primary: "text-primary",
    success: "text-success",
    warning: "text-warning",
    danger: "text-danger",
    ink: "text-ink",
  };

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  type TrailOptions = {
    size: number;
    fade: number;
    variant: PixelTrailVariant;
    autoplay: boolean;
  };

  /** Run `tick` on every frame while the element is on screen and the tab is visible. */
  function whileVisible(element: Element, tick: (now: number) => void) {
    let frame = 0;
    let seen = false;
    const run = (now: number) => {
      tick(now);
      frame = requestAnimationFrame(run);
    };
    const sync = () => {
      cancelAnimationFrame(frame);
      if (seen && !document.hidden) frame = requestAnimationFrame(run);
    };
    const observer = new IntersectionObserver(([entry]) => {
      seen = Boolean(entry?.isIntersecting);
      sync();
    });
    observer.observe(element);
    document.addEventListener("visibilitychange", sync);
    return () => {
      observer.disconnect();
      document.removeEventListener("visibilitychange", sync);
      cancelAnimationFrame(frame);
    };
  }

  /**
   * Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
   * the cells around the focused element. The canvas only redraws while some cell is still lit.
   */
  function createPixels(
    root: HTMLElement,
    canvas: HTMLCanvasElement,
    options: TrailOptions,
  ) {
    const { size, fade, variant } = options;
    const context = canvas.getContext?.("2d");
    if (!context || still()) return () => {};
    const lit = new Map<string, { time: number; strength: number }>();
    let last: { x: number; y: number } | null = null;
    let frame = 0;
    let color = "";

    const resize = () => {
      const ratio = window.devicePixelRatio || 1;
      canvas.width = canvas.clientWidth * ratio;
      canvas.height = canvas.clientHeight * ratio;
      context.setTransform(ratio, 0, 0, ratio, 0, 0);
    };
    const draw = (now: number) => {
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle = color;
      for (const [key, cell] of lit) {
        const alpha = cell.strength * (1 - (now - cell.time) / fade);
        if (alpha <= 0) {
          lit.delete(key);
          continue;
        }
        const [col = 0, row = 0] = key.split(",").map(Number);
        context.globalAlpha = Math.min(alpha, 1);
        context.beginPath();
        if (variant === "dot")
          context.arc(
            (col + 0.5) * size,
            (row + 0.5) * size,
            size * 0.32,
            0,
            7,
          );
        else
          context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
        context.fill();
      }
      frame = lit.size ? requestAnimationFrame(draw) : 0;
    };
    const light = (col: number, row: number, strength = 1) => {
      const key = `${col},${row}`;
      const time = performance.now();
      const current = lit.get(key);
      if (!current || current.strength * 0.8 <= strength)
        lit.set(key, { time, strength });
      if (frame) return;
      color = getComputedStyle(canvas).color;
      frame = requestAnimationFrame(draw);
    };
    const paint = (x: number, y: number) => {
      const col = Math.floor(x / size);
      const row = Math.floor(y / size);
      light(col, row);
      if (variant !== "brush") return;
      for (let dx = -2; dx <= 2; dx++)
        for (let dy = -2; dy <= 2; dy++) {
          const far = Math.max(Math.abs(dx), Math.abs(dy));
          if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
        }
    };
    /** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
    const trail = (x: number, y: number) => {
      const from = last ?? { x, y };
      const steps = Math.max(
        1,
        Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
      );
      for (let i = 1; i <= steps; i++)
        paint(
          from.x + ((x - from.x) * i) / steps,
          from.y + ((y - from.y) * i) / steps,
        );
      last = { x, y };
    };

    let inside = false;
    const move = (event: PointerEvent) => {
      inside = true;
      const rect = root.getBoundingClientRect();
      trail(event.clientX - rect.left, event.clientY - rect.top);
    };
    const leave = () => {
      inside = false;
      last = null;
    };
    const focus = (event: FocusEvent) => {
      const target = event.target as HTMLElement;
      if (target === root || !target.matches?.(":focus-visible")) return;
      const box = root.getBoundingClientRect();
      const rect = target.getBoundingClientRect();
      const left = Math.floor((rect.left - box.left) / size) - 1;
      const top = Math.floor((rect.top - box.top) / size) - 1;
      const right = Math.floor((rect.right - box.left) / size) + 1;
      const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
      for (let col = left; col <= right; col++)
        for (let row = top; row <= bottom; row++)
          if (col === left || col === right || row === top || row === bottom)
            light(col, row, 0.8);
    };

    resize();
    const observer =
      typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
    observer?.observe(canvas);
    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);
    root.addEventListener("focusin", focus);
    const stopAuto =
      options.autoplay && typeof IntersectionObserver === "function"
        ? whileVisible(root, (now) => {
            if (inside) return;
            const t = now / 1000;
            trail(
              canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
              canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
            );
          })
        : null;

    return () => {
      observer?.disconnect();
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      root.removeEventListener("focusin", focus);
      stopAuto?.();
      cancelAnimationFrame(frame);
    };
  }

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Side of one cell in px. */
    cellSize?: number;
    /** How long a lit cell takes to fade out, in ms. */
    fade?: number;
    /** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
    variant?: PixelTrailVariant;
    /** Light color token. */
    color?: keyof typeof colors;
    /** Draws faint grid lines between the cells. */
    showGrid?: boolean;
    /** Draws a trail on its own while visible and the pointer is elsewhere. */
    autoplay?: boolean;
    children?: Snippet;
  };

  let {
    cellSize = 24,
    fade = 600,
    variant = "pixel",
    color = "primary",
    showGrid = false,
    autoplay = false,
    class: className,
    style,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();
  let canvas = $state<HTMLCanvasElement>();

  $effect(() => {
    const options = { size: cellSize, fade, variant, autoplay };
    if (root && canvas) return createPixels(root, canvas, options);
  });
</script>

<div
  {...rest}
  bind:this={root}
  class={[base, className]}
  style={`--cell: ${cellSize}px;${style ? ` ${style}` : ""}`}
>
  <canvas
    bind:this={canvas}
    aria-hidden="true"
    class={[canvasClass, colors[color], showGrid && gridClass]}
  ></canvas>
  {@render children?.()}
</div>
```

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

<PixelTrail
  variant="dot"
  showGrid
  class="grid h-64 place-items-center rounded-xl"
>
  <h2 class="text-2xl font-semibold">Move your mouse</h2>
</PixelTrail>
```

### Astro

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

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

type PixelTrailVariant = "pixel" | "dot" | "brush";

const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
  "bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
  ink: "text-ink",
};

type Props = HTMLAttributes<"div"> & {
  /** Side of one cell in px. */
  cellSize?: number;
  /** How long a lit cell takes to fade out, in ms. */
  fade?: number;
  /** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
  variant?: PixelTrailVariant;
  /** Light color token. */
  color?: keyof typeof colors;
  /** Draws faint grid lines between the cells. */
  showGrid?: boolean;
  /** Draws a trail on its own while visible and the pointer is elsewhere. */
  autoplay?: boolean;
};

const {
  cellSize = 24,
  fade = 600,
  variant = "pixel",
  color = "primary",
  showGrid = false,
  autoplay = false,
  class: className,
  style,
  ...rest
} = Astro.props;
const options = JSON.stringify({
  size: Number(cellSize),
  fade: Number(fade),
  variant,
  autoplay: Boolean(autoplay),
});
const userStyle = typeof style === "string" && style ? ` ${style}` : "";
---

<markas-pixel-trail class="contents" data-options={options}>
  <div
    {...rest}
    class:list={[base, className]}
    style={`--cell: ${cellSize}px;${userStyle}`}
  >
    <canvas
      aria-hidden="true"
      class:list={[canvasClass, colors[color], showGrid && gridClass]}
    ></canvas>
    <slot />
  </div>
</markas-pixel-trail>

<script>
  type PixelTrailVariant = "pixel" | "dot" | "brush";

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  type TrailOptions = {
    size: number;
    fade: number;
    variant: PixelTrailVariant;
    autoplay: boolean;
  };

  /** Run `tick` on every frame while the element is on screen and the tab is visible. */
  function whileVisible(element: Element, tick: (now: number) => void) {
    let frame = 0;
    let seen = false;
    const run = (now: number) => {
      tick(now);
      frame = requestAnimationFrame(run);
    };
    const sync = () => {
      cancelAnimationFrame(frame);
      if (seen && !document.hidden) frame = requestAnimationFrame(run);
    };
    const observer = new IntersectionObserver(([entry]) => {
      seen = Boolean(entry?.isIntersecting);
      sync();
    });
    observer.observe(element);
    document.addEventListener("visibilitychange", sync);
    return () => {
      observer.disconnect();
      document.removeEventListener("visibilitychange", sync);
      cancelAnimationFrame(frame);
    };
  }

  /**
   * Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
   * the cells around the focused element. The canvas only redraws while some cell is still lit.
   */
  function createPixels(
    root: HTMLElement,
    canvas: HTMLCanvasElement,
    options: TrailOptions,
  ) {
    const { size, fade, variant } = options;
    const context = canvas.getContext?.("2d");
    if (!context || still()) return () => {};
    const lit = new Map<string, { time: number; strength: number }>();
    let last: { x: number; y: number } | null = null;
    let frame = 0;
    let color = "";

    const resize = () => {
      const ratio = window.devicePixelRatio || 1;
      canvas.width = canvas.clientWidth * ratio;
      canvas.height = canvas.clientHeight * ratio;
      context.setTransform(ratio, 0, 0, ratio, 0, 0);
    };
    const draw = (now: number) => {
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle = color;
      for (const [key, cell] of lit) {
        const alpha = cell.strength * (1 - (now - cell.time) / fade);
        if (alpha <= 0) {
          lit.delete(key);
          continue;
        }
        const [col = 0, row = 0] = key.split(",").map(Number);
        context.globalAlpha = Math.min(alpha, 1);
        context.beginPath();
        if (variant === "dot")
          context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
        else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
        context.fill();
      }
      frame = lit.size ? requestAnimationFrame(draw) : 0;
    };
    const light = (col: number, row: number, strength = 1) => {
      const key = `${col},${row}`;
      const time = performance.now();
      const current = lit.get(key);
      if (!current || current.strength * 0.8 <= strength)
        lit.set(key, { time, strength });
      if (frame) return;
      color = getComputedStyle(canvas).color;
      frame = requestAnimationFrame(draw);
    };
    const paint = (x: number, y: number) => {
      const col = Math.floor(x / size);
      const row = Math.floor(y / size);
      light(col, row);
      if (variant !== "brush") return;
      for (let dx = -2; dx <= 2; dx++)
        for (let dy = -2; dy <= 2; dy++) {
          const far = Math.max(Math.abs(dx), Math.abs(dy));
          if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
        }
    };
    /** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
    const trail = (x: number, y: number) => {
      const from = last ?? { x, y };
      const steps = Math.max(
        1,
        Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
      );
      for (let i = 1; i <= steps; i++)
        paint(
          from.x + ((x - from.x) * i) / steps,
          from.y + ((y - from.y) * i) / steps,
        );
      last = { x, y };
    };

    let inside = false;
    const move = (event: PointerEvent) => {
      inside = true;
      const rect = root.getBoundingClientRect();
      trail(event.clientX - rect.left, event.clientY - rect.top);
    };
    const leave = () => {
      inside = false;
      last = null;
    };
    const focus = (event: FocusEvent) => {
      const target = event.target as HTMLElement;
      if (target === root || !target.matches?.(":focus-visible")) return;
      const box = root.getBoundingClientRect();
      const rect = target.getBoundingClientRect();
      const left = Math.floor((rect.left - box.left) / size) - 1;
      const top = Math.floor((rect.top - box.top) / size) - 1;
      const right = Math.floor((rect.right - box.left) / size) + 1;
      const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
      for (let col = left; col <= right; col++)
        for (let row = top; row <= bottom; row++)
          if (col === left || col === right || row === top || row === bottom)
            light(col, row, 0.8);
    };

    resize();
    const observer =
      typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
    observer?.observe(canvas);
    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);
    root.addEventListener("focusin", focus);
    const stopAuto =
      options.autoplay && typeof IntersectionObserver === "function"
        ? whileVisible(root, (now) => {
            if (inside) return;
            const t = now / 1000;
            trail(
              canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
              canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
            );
          })
        : null;

    return () => {
      observer?.disconnect();
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      root.removeEventListener("focusin", focus);
      stopAuto?.();
      cancelAnimationFrame(frame);
    };
  }


  // Per instance: each area owns its canvas, pointer trail, and autoplay loop.
  class PixelTrail extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      const canvas = root?.firstElementChild;
      if (!root || !(canvas instanceof HTMLCanvasElement)) return;
      this.#stop = createPixels(
        root,
        canvas,
        JSON.parse(this.dataset.options ?? "{}") as TrailOptions,
      );
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-pixel-trail"))
    customElements.define("markas-pixel-trail", PixelTrail);
</script>
```

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

<PixelTrail variant="dot" showGrid class="grid h-64 place-items-center rounded-xl">
  <h2 class="text-2xl font-semibold">Move your mouse</h2>
</PixelTrail>
```

Satu script kecil yang dibundel menggambar setiap canvas lewat elemen `markas-pixel-trail`.

### Angular

Simpan di `src/app/markas/pixel-trail.component.ts`. Tanpa dependensi tambahan.

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

export type PixelTrailVariant = "pixel" | "dot" | "brush";

const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
  "bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
  ink: "text-ink",
};

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

type TrailOptions = {
  size: number;
  fade: number;
  variant: PixelTrailVariant;
  autoplay: boolean;
};

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

/**
 * Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
 * the cells around the focused element. The canvas only redraws while some cell is still lit.
 */
function createPixels(
  root: HTMLElement,
  canvas: HTMLCanvasElement,
  options: TrailOptions,
) {
  const { size, fade, variant } = options;
  const context = canvas.getContext?.("2d");
  if (!context || still()) return () => {};
  const lit = new Map<string, { time: number; strength: number }>();
  let last: { x: number; y: number } | null = null;
  let frame = 0;
  let color = "";

  const resize = () => {
    const ratio = window.devicePixelRatio || 1;
    canvas.width = canvas.clientWidth * ratio;
    canvas.height = canvas.clientHeight * ratio;
    context.setTransform(ratio, 0, 0, ratio, 0, 0);
  };
  const draw = (now: number) => {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = color;
    for (const [key, cell] of lit) {
      const alpha = cell.strength * (1 - (now - cell.time) / fade);
      if (alpha <= 0) {
        lit.delete(key);
        continue;
      }
      const [col = 0, row = 0] = key.split(",").map(Number);
      context.globalAlpha = Math.min(alpha, 1);
      context.beginPath();
      if (variant === "dot")
        context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
      else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
      context.fill();
    }
    frame = lit.size ? requestAnimationFrame(draw) : 0;
  };
  const light = (col: number, row: number, strength = 1) => {
    const key = `${col},${row}`;
    const time = performance.now();
    const current = lit.get(key);
    if (!current || current.strength * 0.8 <= strength)
      lit.set(key, { time, strength });
    if (frame) return;
    color = getComputedStyle(canvas).color;
    frame = requestAnimationFrame(draw);
  };
  const paint = (x: number, y: number) => {
    const col = Math.floor(x / size);
    const row = Math.floor(y / size);
    light(col, row);
    if (variant !== "brush") return;
    for (let dx = -2; dx <= 2; dx++)
      for (let dy = -2; dy <= 2; dy++) {
        const far = Math.max(Math.abs(dx), Math.abs(dy));
        if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
      }
  };
  /** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
  const trail = (x: number, y: number) => {
    const from = last ?? { x, y };
    const steps = Math.max(
      1,
      Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
    );
    for (let i = 1; i <= steps; i++)
      paint(
        from.x + ((x - from.x) * i) / steps,
        from.y + ((y - from.y) * i) / steps,
      );
    last = { x, y };
  };

  let inside = false;
  const move = (event: PointerEvent) => {
    inside = true;
    const rect = root.getBoundingClientRect();
    trail(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
  };
  const focus = (event: FocusEvent) => {
    const target = event.target as HTMLElement;
    if (target === root || !target.matches?.(":focus-visible")) return;
    const box = root.getBoundingClientRect();
    const rect = target.getBoundingClientRect();
    const left = Math.floor((rect.left - box.left) / size) - 1;
    const top = Math.floor((rect.top - box.top) / size) - 1;
    const right = Math.floor((rect.right - box.left) / size) + 1;
    const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
    for (let col = left; col <= right; col++)
      for (let row = top; row <= bottom; row++)
        if (col === left || col === right || row === top || row === bottom)
          light(col, row, 0.8);
  };

  resize();
  const observer =
    typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
  observer?.observe(canvas);
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  root.addEventListener("focusin", focus);
  const stopAuto =
    options.autoplay && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1000;
          trail(
            canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
            canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
          );
        })
      : null;

  return () => {
    observer?.disconnect();
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    root.removeEventListener("focusin", focus);
    stopAuto?.();
    cancelAnimationFrame(frame);
  };
}

export type PixelTrailColor = keyof typeof colors;

/** The host stays out of layout; the user's class lands on the area. */
@Component({
  selector: "markas-pixel-trail",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `
    <div #rootEl [class]="classes()" [style.--cell]="cellSize() + 'px'">
      <canvas #canvasEl aria-hidden="true" [class]="canvasClasses()"></canvas>
      <ng-content />
    </div>
  `,
})
export class PixelTrail {
  /** Side of one cell in px. */
  readonly cellSize = input(24, { transform: numberAttribute });
  /** How long a lit cell takes to fade out, in ms. */
  readonly fade = input(600, { transform: numberAttribute });
  /** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
  readonly variant = input<PixelTrailVariant>("pixel");
  /** Light color token. */
  readonly color = input<PixelTrailColor>("primary");
  /** Draws faint grid lines between the cells. */
  readonly showGrid = input(false, { transform: booleanAttribute });
  /** Draws a trail on its own while visible and the pointer is elsewhere. */
  readonly autoplay = input(false, { transform: booleanAttribute });
  readonly userClass = input("", { alias: "class" });

  protected readonly classes = computed(() => cx(base, this.userClass()));
  protected readonly canvasClasses = computed(() =>
    cx(canvasClass, colors[this.color()], this.showGrid() && gridClass),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");
  private readonly canvas =
    viewChild.required<ElementRef<HTMLCanvasElement>>("canvasEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const options = {
        size: this.cellSize(),
        fade: this.fade(),
        variant: this.variant(),
        autoplay: this.autoplay(),
      };
      onCleanup(
        createPixels(
          this.root().nativeElement,
          this.canvas().nativeElement,
          options,
        ),
      );
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { PixelTrail } from "./markas/pixel-trail.component";

@Component({
  selector: "app-hero",
  imports: [PixelTrail],
  template: `
    <markas-pixel-trail
      variant="dot"
      showGrid
      class="grid h-64 place-items-center rounded-xl"
    >
      <h2 class="text-2xl font-semibold">Move your mouse</h2>
    </markas-pixel-trail>
  `,
})
export class Hero {}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `variant` | `"pixel" \| "dot" \| "brush"` | "pixel" | pixel: sel persegi. dot: sel bulat seperti papan LED. brush: kuas lembut yang juga menyalakan sel di sekitar kursor. |
| `cellSize` | `number` | 24 | Sisi satu sel dalam px. |
| `fade` | `number` | 600 | Lama sel yang menyala memudar, dalam ms. |
| `color` | `"primary" \| "success" \| "warning" \| "danger" \| "ink"` | "primary" | Token warna cahaya, dibaca dari tema sehingga mengikuti mode terang dan gelap. |
| `showGrid` | `boolean` | false | Menggambar garis grid tipis di antara sel. |
| `autoplay` | `boolean` | false | Menggambar jejak sendiri selama area terlihat, tab aktif, dan kursor di tempat lain. |
| `children / slot` | `ReactNode / slot` | - | Konten di atas sel. Atur tata letaknya dengan class sendiri pada komponen. |

## Aksesibilitas

- Canvas bersifat aria-hidden dan tidak menangkap pointer; konten di atasnya tetap terbaca dan bisa diklik.
- Saat elemen di dalamnya mendapat fokus keyboard, sel di sekitarnya menyala sebagai penanda fokus tambahan di samping cincin fokus biasa.
- Dengan reduced motion tidak ada yang digambar; canvas hanya menggambar ulang selama masih ada sel yang menyala.

## Catatan

- Sel digambar di satu canvas di belakang konten, jadi ribuan sel pun tidak menambah node DOM. Canvas hanya menggambar ulang selama masih ada sel yang menyala.
- `variant`: persegi `pixel`, lingkaran `dot`, atau `brush` yang juga menyalakan sel di sekitarnya dengan lebih lembut. Gerakan cepat diisi, sehingga jejak tidak berlubang.
- Saat elemen di dalamnya mendapat fokus keyboard, sel di sekitarnya menyala. `autoplay` menggambar jejak sendiri selama area terlihat dan kursor di tempat lain.
- Warna dibaca dari token tema, sehingga mengikuti mode gelap. Dengan reduced motion tidak ada yang digambar. Atribut dan `class` jatuh ke area.
