# Ripple Button

Tombol yang memancarkan gelombang dari titik klik, atau dari tengah saat ditekan dengan keyboard.

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

## Kapan dipakai

Aksi yang terbantu umpan balik sentuhan, seperti tambah ke keranjang, berlangganan, atau tombol kirim.

- Pakai seperti Button, onClick dan type berperilaku sama
- Jangan campur ripple button dan tombol biasa dalam satu toolbar
- Gelombang memakai warna teks, jadi cocok di semua varian

## Kode

### Blade

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

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

@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',
    ];
    $layer = 'pointer-events-none absolute inset-0 -z-10';
    $wave = 'absolute rounded-full bg-current opacity-0';
@endphp

{{-- Each click adds one wave, from the pointer or from the center for keyboard clicks. --}}
<button
    x-data="{
        ripple(event) {
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const rect = this.$el.getBoundingClientRect();
            const fromPointer = event.detail > 0;
            const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
            const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
            const diameter = Math.hypot(rect.width, rect.height) * 2;
            const element = document.createElement('span');
            element.className = @js($wave);
            element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
            this.$refs.layer.append(element);
            if (typeof element.animate !== 'function') return element.remove();
            element.animate(
                [{ scale: '0', opacity: 0.25 }, { scale: '1', opacity: 0 }],
                { duration: 600, easing: 'ease-out' },
            ).onfinish = () => element.remove();
        },
    }"
    x-on:click="ripple($event)"
    {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size]]) }}
>
    <span x-ref="layer" class="{{ $layer }}" aria-hidden="true"></span>
    {{ $slot }}
</button>
```

```blade
<x-markas.ripple-button>Tambah ke keranjang</x-markas.ripple-button>
<x-markas.ripple-button variant="secondary" type="submit">Berlangganan</x-markas.ripple-button>
```

### React

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

```tsx
"use client";

import { useRef, type ComponentProps, type MouseEvent } 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 layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

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

/** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
function ripple(target: HTMLElement, event: MouseEvent<HTMLElement>) {
  const button = target.parentElement;
  if (!button || reducedMotion()) return;
  const rect = button.getBoundingClientRect();
  const fromPointer = event.detail > 0;
  const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
  const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
  const diameter = Math.hypot(rect.width, rect.height) * 2;
  const element = document.createElement("span");
  element.className = wave;
  element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
  target.append(element);
  if (typeof element.animate !== "function") return element.remove();
  element.animate(WAVE, {
    duration: WAVE_DURATION,
    easing: "ease-out",
  }).onfinish = () => element.remove();
}

export type RippleButtonProps = ComponentProps<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
};

export function RippleButton({
  variant = "primary",
  size = "md",
  type = "button",
  className,
  children,
  onClick,
  ...props
}: RippleButtonProps) {
  const layerRef = useRef<HTMLSpanElement>(null);

  const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
    if (layerRef.current) ripple(layerRef.current, event);
    onClick?.(event);
  };

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

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

<RippleButton onClick={addToCart}>Tambah ke keranjang</RippleButton>
<RippleButton variant="secondary" type="submit">Berlangganan</RippleButton>
```

### Vue

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

```vue
<script setup lang="ts">
import { 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 props = withDefaults(
  defineProps<{
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
  }>(),
  { variant: "primary", size: "md" },
);

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 layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

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

const layerRef = useTemplateRef<HTMLSpanElement>("layer");

/** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
function ripple(event: MouseEvent) {
  const target = layerRef.value;
  const button = target?.parentElement;
  if (!target || !button || reducedMotion()) return;
  const rect = button.getBoundingClientRect();
  const fromPointer = event.detail > 0;
  const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
  const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
  const diameter = Math.hypot(rect.width, rect.height) * 2;
  const element = document.createElement("span");
  element.className = wave;
  element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
  target.append(element);
  if (typeof element.animate !== "function") return element.remove();
  element.animate(WAVE, {
    duration: WAVE_DURATION,
    easing: "ease-out",
  }).onfinish = () => element.remove();
}
</script>

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

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

<template>
  <RippleButton @click="addToCart">Tambah ke keranjang</RippleButton>
  <RippleButton variant="secondary" type="submit">Berlangganan</RippleButton>
</template>
```

### Svelte

Simpan di `src/lib/components/markas/RippleButton.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 layer = "pointer-events-none absolute inset-0 -z-10";
  const wave = "absolute rounded-full bg-current opacity-0";

  const WAVE = [
    { scale: "0", opacity: 0.25 },
    { scale: "1", opacity: 0 },
  ];
  const WAVE_DURATION = 600;

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

  type Props = HTMLButtonAttributes & {
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    children?: Snippet;
  };

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

  let layerElement = $state<HTMLSpanElement>();

  /** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
  function ripple(
    event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
  ) {
    const target = layerElement;
    if (target && !reducedMotion()) {
      const rect = event.currentTarget.getBoundingClientRect();
      const fromPointer = event.detail > 0;
      const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
      const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
      const diameter = Math.hypot(rect.width, rect.height) * 2;
      const element = document.createElement("span");
      element.className = wave;
      element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
      target.append(element);
      if (typeof element.animate === "function")
        element.animate(WAVE, {
          duration: WAVE_DURATION,
          easing: "ease-out",
        }).onfinish = () => element.remove();
      else element.remove();
    }
    onclick?.(event);
  }
</script>

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

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

<RippleButton onclick={addToCart}>Tambah ke keranjang</RippleButton>
<RippleButton variant="secondary" type="submit">Berlangganan</RippleButton>
```

### Astro

Simpan di `src/components/markas/RippleButton.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 layer = "pointer-events-none absolute inset-0 -z-10";

type Props = HTMLAttributes<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
};

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

<button
  type={type}
  data-markas-ripple-button
  class:list={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  <span class={layer} aria-hidden="true"></span>
  <slot />
</button>

<script>
  const wave = "absolute rounded-full bg-current opacity-0";
  const WAVE = [
    { scale: "0", opacity: 0.25 },
    { scale: "1", opacity: 0 },
  ];
  const WAVE_DURATION = 600;

  // One listener per page serves every ripple button. Each click adds one wave, from the
  // pointer or from the center for keyboard clicks.
  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-markas-ripple-button]",
    );
    const target = button?.firstElementChild;
    if (!button || !target) return;
    if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
    const rect = button.getBoundingClientRect();
    const fromPointer = event.detail > 0;
    const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
    const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
    const diameter = Math.hypot(rect.width, rect.height) * 2;
    const element = document.createElement("span");
    element.className = wave;
    element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
    target.append(element);
    if (typeof element.animate !== "function") return element.remove();
    element.animate(WAVE, {
      duration: WAVE_DURATION,
      easing: "ease-out",
    }).onfinish = () => element.remove();
  });
</script>
```

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

<RippleButton>Tambah ke keranjang</RippleButton>
<RippleButton variant="secondary" type="submit">Berlangganan</RippleButton>
```

### Angular

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

```ts
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  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 layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

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

export type RippleButtonVariant = keyof typeof variants;
export type RippleButtonSize = keyof typeof sizes;

/**
 * Attribute selector on the native button: disabled, aria-*, name, value, and the user's
 * class stay on the button itself. Each click adds one wave.
 */
@Component({
  selector: "button[markas-ripple-button]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.type]": "type()",
    "[class]": "classes()",
    "(click)": "ripple($event)",
  },
  template: `<span #wave [class]="layer" aria-hidden="true"></span
    ><ng-content />`,
})
export class RippleButton {
  readonly variant = input<RippleButtonVariant>("primary");
  readonly size = input<RippleButtonSize>("md");
  readonly type = input<"button" | "submit" | "reset">("button");

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

  /** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
  protected ripple(event: MouseEvent) {
    const target = this.layerRef().nativeElement;
    const button = target.parentElement;
    if (!button || reducedMotion()) return;
    const rect = button.getBoundingClientRect();
    const fromPointer = event.detail > 0;
    const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
    const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
    const diameter = Math.hypot(rect.width, rect.height) * 2;
    const element = document.createElement("span");
    element.className = wave;
    element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
    target.append(element);
    if (typeof element.animate !== "function") return element.remove();
    element.animate(WAVE, {
      duration: WAVE_DURATION,
      easing: "ease-out",
    }).onfinish = () => element.remove();
  }
}
```

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

@Component({
  selector: "app-cart",
  imports: [RippleButton],
  template: `
    <button markas-ripple-button (click)="addToCart()">
      Tambah ke keranjang
    </button>
    <button markas-ripple-button variant="secondary" type="submit">
      Berlangganan
    </button>
  `,
})
export class Cart {
  addToCart() {}
}
```

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. |
| `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.
- Gelombang berada di lapisan aria-hidden dan dihapus setelah selesai.
- Dengan prefers-reduced-motion tidak ada gelombang, klik tetap berfungsi.

## Catatan

- Klik mouse atau sentuhan memulai gelombang di titik pointer. Enter dan Spasi memulainya dari tengah.
- Gelombang memakai warna teks dengan opasitas rendah, jadi setiap varian mendapat gelombang yang serasi.
- Blade butuh Alpine.js.
