# Shimmer Button

Tombol dengan kilau lembut yang melintas berulang. Animasi berhenti saat di luar layar dan saat reduced motion aktif.

- Kategori: Tombol
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/shimmer-button.json
- CLI: `npx markasui@latest add shimmer-button`

## Kapan dipakai

Satu ajakan utama di hero, kartu harga, atau banner upgrade yang perlu menarik perhatian.

- Pakai paling banyak satu shimmer button per layar
- Buat label singkat, kilau melintasi seluruh tombol
- Pasangkan dengan Button ghost atau secondary biasa untuk aksi kedua

## Kode

### Blade

Simpan di `resources/views/components/markas/shimmer-button.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'variant' => 'primary',
    'size' => 'md',
    'duration' => 2400,
])

@php
    $base = 'relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $variants = [
        'primary' => 'bg-primary text-on-primary hover:bg-primary-strong',
        'secondary' => 'border border-line bg-surface text-ink hover:bg-subtle',
        'ghost' => 'text-ink hover:bg-subtle',
        'danger' => 'bg-danger text-on-primary hover:bg-danger/90',
    ];
    $sizes = [
        'sm' => 'h-8 rounded-md px-3 text-sm',
        'md' => 'h-10 rounded-lg px-4 text-sm',
        'lg' => 'h-12 rounded-lg px-6 text-base',
    ];
    $sheen = 'pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent';
    $sheenVariants = [
        'primary' => 'via-on-primary/30',
        'secondary' => 'via-primary/10',
        'ghost' => 'via-primary/10',
        'danger' => 'via-on-primary/30',
    ];
@endphp

{{-- The sheen sweeps across in the first 60% of each cycle, then rests off the button. It pauses off screen. --}}
<button
    x-data="{
        stop() {},
        init() {
            const sheen = this.$refs.sheen;
            if (typeof sheen.animate !== 'function') return;
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const animation = sheen.animate(
                [{ translate: '0 0' }, { translate: '300% 0', offset: 0.6 }, { translate: '300% 0' }],
                { duration: {{ (int) $duration }}, iterations: Infinity, easing: 'ease-in-out' },
            );
            if (typeof IntersectionObserver === 'undefined') {
                this.stop = () => animation.cancel();
                return;
            }
            const observer = new IntersectionObserver(([entry]) =>
                entry?.isIntersecting ? animation.play() : animation.pause(),
            );
            observer.observe(this.$el);
            this.stop = () => {
                observer.disconnect();
                animation.cancel();
            };
        },
        destroy() {
            this.stop();
        },
    }"
    {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size]]) }}
>
    {{ $slot }}
    <span x-ref="sheen" class="{{ $sheen }} {{ $sheenVariants[$variant] }}" aria-hidden="true"></span>
</button>
```

```blade
<x-markas.shimmer-button size="lg">Mulai gratis</x-markas.shimmer-button>
<x-markas.shimmer-button variant="secondary" :duration="3200">Jadwalkan demo</x-markas.shimmer-button>
```

### React

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

```tsx
"use client";

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

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const sheen =
  "pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent";
const sheenVariants = {
  primary: "via-on-primary/30",
  secondary: "via-primary/10",
  ghost: "via-primary/10",
  danger: "via-on-primary/30",
};

/** The sheen sweeps across in the first 60% of each cycle, then rests off the button. */
const SWEEP = [
  { translate: "0 0" },
  { translate: "300% 0", offset: 0.6 },
  { translate: "300% 0" },
];
const DEFAULT_DURATION = 2400;

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

export type ShimmerButtonProps = ComponentProps<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Length of one shimmer cycle in milliseconds. */
  duration?: number;
};

export function ShimmerButton({
  variant = "primary",
  size = "md",
  duration = DEFAULT_DURATION,
  type = "button",
  className,
  children,
  ...props
}: ShimmerButtonProps) {
  const sheenRef = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const element = sheenRef.current;
    const button = element?.parentElement;
    if (!element || !button || typeof element.animate !== "function") return;
    if (reducedMotion()) return;
    const animation = element.animate(SWEEP, {
      duration,
      iterations: Infinity,
      easing: "ease-in-out",
    });
    if (typeof IntersectionObserver === "undefined")
      return () => animation.cancel();
    // Pause while the button is off screen.
    const observer = new IntersectionObserver(([entry]) =>
      entry?.isIntersecting ? animation.play() : animation.pause(),
    );
    observer.observe(button);
    return () => {
      observer.disconnect();
      animation.cancel();
    };
  }, [duration]);

  return (
    <button
      type={type}
      className={cx(base, variants[variant], sizes[size], className)}
      {...props}
    >
      {children}
      <span
        ref={sheenRef}
        className={cx(sheen, sheenVariants[variant])}
        aria-hidden="true"
      />
    </button>
  );
}
```

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

<ShimmerButton size="lg">Mulai gratis</ShimmerButton>
<ShimmerButton variant="secondary" duration={3200}>Jadwalkan demo</ShimmerButton>
```

### Vue

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

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

const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const sheenVariants = {
  primary: "via-on-primary/30",
  secondary: "via-primary/10",
  ghost: "via-primary/10",
  danger: "via-on-primary/30",
};

const props = withDefaults(
  defineProps<{
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Length of one shimmer cycle in milliseconds. */
    duration?: number;
  }>(),
  { variant: "primary", size: "md", duration: 2400 },
);

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const sheen =
  "pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent";

/** The sheen sweeps across in the first 60% of each cycle, then rests off the button. */
const SWEEP = [
  { translate: "0 0" },
  { translate: "300% 0", offset: 0.6 },
  { translate: "300% 0" },
];

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

const sheenRef = useTemplateRef<HTMLSpanElement>("sheen");
let stop = () => {};

onMounted(() => {
  const element = sheenRef.value;
  const button = element?.parentElement;
  if (!element || !button || typeof element.animate !== "function") return;
  if (reducedMotion()) return;
  const animation = element.animate(SWEEP, {
    duration: props.duration,
    iterations: Infinity,
    easing: "ease-in-out",
  });
  if (typeof IntersectionObserver === "undefined") {
    stop = () => animation.cancel();
    return;
  }
  // Pause while the button is off screen.
  const observer = new IntersectionObserver(([entry]) =>
    entry?.isIntersecting ? animation.play() : animation.pause(),
  );
  observer.observe(button);
  stop = () => {
    observer.disconnect();
    animation.cancel();
  };
});
onBeforeUnmount(() => stop());
</script>

<template>
  <button
    type="button"
    :class="[base, variants[props.variant], sizes[props.size]]"
  >
    <slot />
    <span
      ref="sheen"
      :class="[sheen, sheenVariants[props.variant]]"
      aria-hidden="true"
    />
  </button>
</template>
```

```vue
<script setup lang="ts">
import ShimmerButton from "@/components/markas/ShimmerButton.vue";
</script>

<template>
  <ShimmerButton size="lg">Mulai gratis</ShimmerButton>
  <ShimmerButton variant="secondary" :duration="3200"
    >Jadwalkan demo</ShimmerButton
  >
</template>
```

### Svelte

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

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

  const base =
    "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const variants = {
    primary: "bg-primary text-on-primary hover:bg-primary-strong",
    secondary: "border border-line bg-surface text-ink hover:bg-subtle",
    ghost: "text-ink hover:bg-subtle",
    danger: "bg-danger text-on-primary hover:bg-danger/90",
  };
  const sizes = {
    sm: "h-8 rounded-md px-3 text-sm",
    md: "h-10 rounded-lg px-4 text-sm",
    lg: "h-12 rounded-lg px-6 text-base",
  };
  const sheen =
    "pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent";
  const sheenVariants = {
    primary: "via-on-primary/30",
    secondary: "via-primary/10",
    ghost: "via-primary/10",
    danger: "via-on-primary/30",
  };

  /** The sheen sweeps across in the first 60% of each cycle, then rests off the button. */
  const SWEEP = [
    { translate: "0 0" },
    { translate: "300% 0", offset: 0.6 },
    { translate: "300% 0" },
  ];
  const DEFAULT_DURATION = 2400;

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

  type Props = HTMLButtonAttributes & {
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Length of one shimmer cycle in milliseconds. */
    duration?: number;
    children?: Snippet;
  };

  let {
    variant = "primary",
    size = "md",
    duration = DEFAULT_DURATION,
    type = "button",
    class: className,
    children,
    ...rest
  }: Props = $props();

  let sheenElement = $state<HTMLSpanElement>();

  $effect(() => {
    const element = sheenElement;
    const button = element?.parentElement;
    const cycle = duration;
    if (!element || !button || typeof element.animate !== "function") return;
    if (reducedMotion()) return;
    const animation = element.animate(SWEEP, {
      duration: cycle,
      iterations: Infinity,
      easing: "ease-in-out",
    });
    if (typeof IntersectionObserver === "undefined")
      return () => animation.cancel();
    // Pause while the button is off screen.
    const observer = new IntersectionObserver(([entry]) =>
      entry?.isIntersecting ? animation.play() : animation.pause(),
    );
    observer.observe(button);
    return () => {
      observer.disconnect();
      animation.cancel();
    };
  });
</script>

<button
  {type}
  class={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  {@render children?.()}
  <span
    bind:this={sheenElement}
    class={[sheen, sheenVariants[variant]]}
    aria-hidden="true"
  ></span>
</button>
```

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

<ShimmerButton size="lg">Mulai gratis</ShimmerButton>
<ShimmerButton variant="secondary" duration={3200}>Jadwalkan demo</ShimmerButton
>
```

### Astro

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

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

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const sheen =
  "pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent";
const sheenVariants = {
  primary: "via-on-primary/30",
  secondary: "via-primary/10",
  ghost: "via-primary/10",
  danger: "via-on-primary/30",
};

type Props = HTMLAttributes<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Length of one shimmer cycle in milliseconds. */
  duration?: number;
};

const {
  variant = "primary",
  size = "md",
  duration = 2400,
  type = "button",
  class: className,
  ...rest
} = Astro.props;
---

<markas-shimmer-button class="contents" data-duration={Number(duration)}>
  <button
    type={type}
    class:list={[base, variants[variant], sizes[size], className]}
    {...rest}
  >
    <slot />
    <span
      data-markas-sheen
      class:list={[sheen, sheenVariants[variant]]}
      aria-hidden="true"></span>
  </button>
</markas-shimmer-button>

<script>
  /** The sheen sweeps across in the first 60% of each cycle, then rests off the button. */
  const SWEEP = [
    { translate: "0 0" },
    { translate: "300% 0", offset: 0.6 },
    { translate: "300% 0" },
  ];

  // Per instance: the sweep pauses while its button is off screen.
  class ShimmerButton extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const element = this.querySelector<HTMLElement>("[data-markas-sheen]");
      const button = element?.parentElement;
      if (!element || !button || typeof element.animate !== "function") return;
      if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
      const animation = element.animate(SWEEP, {
        duration: Number(this.dataset.duration),
        iterations: Infinity,
        easing: "ease-in-out",
      });
      if (typeof IntersectionObserver === "undefined") {
        this.#stop = () => animation.cancel();
        return;
      }
      const observer = new IntersectionObserver(([entry]) =>
        entry?.isIntersecting ? animation.play() : animation.pause(),
      );
      observer.observe(button);
      this.#stop = () => {
        observer.disconnect();
        animation.cancel();
      };
    }

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

  if (!customElements.get("markas-shimmer-button"))
    customElements.define("markas-shimmer-button", ShimmerButton);
</script>
```

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

<ShimmerButton size="lg">Mulai gratis</ShimmerButton>
<ShimmerButton variant="secondary" duration={3200}>Jadwalkan demo</ShimmerButton>
```

### Angular

Simpan di `src/app/markas/shimmer-button.component.ts`. Tanpa dependensi tambahan.

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

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const sheen =
  "pointer-events-none absolute inset-y-0 -left-1/2 w-1/2 -skew-x-12 bg-linear-to-r from-transparent to-transparent";
const sheenVariants = {
  primary: "via-on-primary/30",
  secondary: "via-primary/10",
  ghost: "via-primary/10",
  danger: "via-on-primary/30",
};

/** The sheen sweeps across in the first 60% of each cycle, then rests off the button. */
const SWEEP = [
  { translate: "0 0" },
  { translate: "300% 0", offset: 0.6 },
  { translate: "300% 0" },
];
const DEFAULT_DURATION = 2400;

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

export type ShimmerButtonVariant = keyof typeof variants;
export type ShimmerButtonSize = keyof typeof sizes;

/**
 * Attribute selector on the native button: disabled, aria-*, name, value, and the user's
 * class stay on the button itself. The sweep pauses while the button is off screen.
 */
@Component({
  selector: "button[markas-shimmer-button]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[attr.type]": "type()", "[class]": "classes()" },
  template: `<ng-content /><span
      #sheen
      [class]="sheenClasses()"
      aria-hidden="true"
    ></span>`,
})
export class ShimmerButton {
  readonly variant = input<ShimmerButtonVariant>("primary");
  readonly size = input<ShimmerButtonSize>("md");
  /** Length of one shimmer cycle in milliseconds. */
  readonly duration = input(DEFAULT_DURATION, { transform: numberAttribute });
  readonly type = input<"button" | "submit" | "reset">("button");

  protected readonly classes = computed(
    () => `${base} ${variants[this.variant()]} ${sizes[this.size()]}`,
  );
  protected readonly sheenClasses = computed(
    () => `${sheen} ${sheenVariants[this.variant()]}`,
  );
  private readonly sheen =
    viewChild.required<ElementRef<HTMLSpanElement>>("sheen");

  constructor() {
    let stop = () => {};
    afterNextRender(() => {
      const element = this.sheen().nativeElement;
      const button = element.parentElement;
      if (!button || typeof element.animate !== "function") return;
      if (reducedMotion()) return;
      const animation = element.animate(SWEEP, {
        duration: this.duration(),
        iterations: Infinity,
        easing: "ease-in-out",
      });
      stop = () => animation.cancel();
      if (typeof IntersectionObserver === "undefined") return;
      // Pause while the button is off screen.
      const observer = new IntersectionObserver(([entry]) =>
        entry?.isIntersecting ? animation.play() : animation.pause(),
      );
      observer.observe(button);
      stop = () => {
        observer.disconnect();
        animation.cancel();
      };
    });
    inject(DestroyRef).onDestroy(() => stop());
  }
}
```

```ts
import { Component } from "@angular/core";
import { ShimmerButton } from "./markas/shimmer-button.component";

@Component({
  selector: "app-hero",
  imports: [ShimmerButton],
  template: `
    <button markas-shimmer-button size="lg">Mulai gratis</button>
    <button markas-shimmer-button variant="secondary" [duration]="3200">
      Jadwalkan demo
    </button>
  `,
})
export class Hero {}
```

Angular memakai attribute selector pada button native, jadi `disabled`, `aria-*`, dan `class` tetap di button itu.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | primary | Gaya visual, sama seperti Button. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Tinggi 32, 40, atau 48px, sama seperti Button. |
| `duration` | `number` | 2400 | Lama satu siklus kilau dalam milidetik. |
| `type` | `'button' \| 'submit' \| 'reset'` | button | Atribut type native. |

## Aksesibilitas

- Elemen button native, jadi Enter dan Spasi berfungsi dan fokus tampil sebagai outline 2px warna primary.
- Kilau adalah span dekoratif aria-hidden, labelnya teks biasa.
- Dengan prefers-reduced-motion kilau tidak berjalan dan tombol tampak seperti Button biasa.

## Catatan

- Kilau berjalan dengan Web Animations API, jadi tidak perlu CSS atau keyframes tambahan.
- IntersectionObserver menjeda animasi saat tombol di luar layar. Dengan reduced motion animasi tidak pernah mulai.
- Blade butuh Alpine.js.
