# Tactile Button

A raised button whose surface gives when you press it while the label stays sharp and still, with a bars loader and a drawn check for loading and success. Black on a light page, white on a dark one.

Live demo: https://bearerop.in/craft/tactile-button

## Install

### 1. Install dependencies

It also uses the cn() helper from shadcn/ui (clsx and tailwind-merge) and the shadcn colour roles: primary, primary-foreground and ring.

```bash
npm install class-variance-authority lucide-react
```

### 2. Copy and paste the following code into your project.

One file. Every class means the same in Tailwind v3 and v4, so it needs no config changes in either.

#### Usage

```tsx
import { ArrowRight, Download } from "lucide-react";
import { TactileButton } from "@/components/craft/tactile-button";

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-4">
      <TactileButton>Continue</TactileButton>

      {/* Sizes: sm, md, lg (the default) */}
      <TactileButton size="md" iconStart={<Download />}>
        Download
      </TactileButton>

      {/* A pill, and the plain fill without the gradient or shadow */}
      <TactileButton rounded>Rounded</TactileButton>
      <TactileButton flat>Flat</TactileButton>

      {/* The label gives way to the bars loader, then to a drawn check */}
      <TactileButton loading>Save changes</TactileButton>
      <TactileButton success="Saved">Save changes</TactileButton>

      {/* Any element can take the button's look */}
      <TactileButton render={<a href="/docs" />} iconEnd={<ArrowRight />}>
        Read the docs
      </TactileButton>
    </div>
  );
}
```

#### Source

```tsx
"use client";

import { cva, type VariantProps } from "class-variance-authority";
import { Check } from "lucide-react";
import { cloneElement, type ComponentProps, type ReactElement, type ReactNode } from "react";
import { cn } from "@/lib/utils";

/**
 * A button whose fill, border and shadow live on `::before`, so pressing it
 * scales the surface and leaves the label sharp and still. It takes the
 * shadcn `primary` role: black on a light page, white on a dark one.
 * Every class here means the same in Tailwind v3 and v4.
 */
export const tactileButton = cva(
  [
    "relative isolate inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap font-sans font-medium outline-none",
    "before:absolute before:inset-0 before:-z-10 before:rounded-[inherit] before:transition-[scale,transform,background-color,border-color,box-shadow] before:duration-150 before:ease-out motion-reduce:before:transition-none",
    "focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none",
    "[&_svg]:pointer-events-none [&_svg]:shrink-0",
    // Pressed means :active or `data-pressed` (set below for Enter, which :active
    // ignores). A button that opens a popup stays still, so what it anchors does not
    // shift. A full-width button gives almost only in height: 1.5% of a wide button
    // is a visible jump at each end.
    "motion-safe:[&:is(:active,[data-pressed]):not([aria-haspopup])]:before:scale-x-[0.985]",
    "motion-safe:[&:is(:active,[data-pressed]):not([aria-haspopup])]:before:scale-y-[0.985]",
    "motion-safe:[&.w-full:is(:active,[data-pressed]):not([aria-haspopup])]:before:scale-x-[0.997]",
  ],
  {
    variants: {
      variant: {
        default: "text-primary-foreground before:bg-primary hover:before:bg-primary/90",
      },
      // Icons take the size's default unless they bring their own size class
      size: {
        sm: "h-8 gap-1.5 px-3 text-xs [&_svg:not([class*='size-'])]:size-3.5",
        md: "h-9 gap-2 px-4 text-sm [&_svg:not([class*='size-'])]:size-4",
        lg: "h-11 gap-2.5 px-6 text-base [&_svg:not([class*='size-'])]:size-5",
      },
      rounded: { true: "rounded-full", false: "rounded-xl" },
      flat: {
        true: "",
        // Raised: a gradient from light to dark over the fill, a border in the colour
        // the gradient ends on, a lit line just inside the top edge and a soft drop
        // shadow. The gradient stops at the border (`bg-no-repeat`), so only the flat
        // fill lies under it, and black at the gradient's final opacity over that fill
        // is exactly its last colour, in either theme.
        false: [
          "before:border before:border-solid before:border-black/20 before:bg-no-repeat",
          "before:bg-[linear-gradient(to_bottom,rgb(255_255_255/0.16),rgb(255_255_255/0)_45%,rgb(0_0_0/0.2))]",
          "before:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),0_1px_2px_rgb(0_0_0/0.3),0_3px_8px_-2px_rgb(0_0_0/0.25)]",
        ],
      },
    },
    defaultVariants: { variant: "default", size: "lg", rounded: false, flat: false },
  }
);

// The label, the loader and the success mark share one grid cell, so the
// button is as wide as the widest of them and never resizes between states
const face =
  "col-start-1 row-start-1 inline-flex items-center justify-center gap-[inherit] transition-[opacity,filter,transform,scale] duration-200 ease-out motion-reduce:transition-none";
const away = "pointer-events-none scale-95 opacity-0 blur-[2px]";

/** Twelve bars, each a little brighter than the last, turned one bar at a time. */
function Bars() {
  return (
    <svg
      viewBox="0 0 24 24"
      role="status"
      aria-label="Loading"
      fill="currentColor"
      className="animate-spin"
      style={{ animationTimingFunction: "steps(12)" }}
    >
      {Array.from({ length: 12 }, (_, bar) => (
        <rect key={bar} x="11" y="2" width="2" height="6" rx="1" opacity={(bar + 1) / 12} transform={`rotate(${bar * 30} 12 12)`} />
      ))}
    </svg>
  );
}

export type TactileButtonProps = ComponentProps<"button"> &
  VariantProps<typeof tactileButton> & {
    /** An icon before the label. It sits a little closer to the edge than text would. */
    iconStart?: ReactNode;
    /** An icon after the label. */
    iconEnd?: ReactNode;
    /** Swaps the label for the bars loader and ignores clicks. */
    loading?: boolean;
    /** Swaps the label for a check and this text, e.g. "Saved". Pass `true` for the check alone. */
    success?: ReactNode;
    /** Replaces the rendered tag, e.g. `render={<a href="/docs" />}`. */
    render?: ReactElement;
  };

export function TactileButton({
  className,
  variant,
  size,
  rounded,
  flat,
  type = "button",
  iconStart,
  iconEnd,
  loading = false,
  success,
  render,
  children,
  onClick,
  onKeyDown,
  onKeyUp,
  onBlur,
  ...props
}: TactileButtonProps) {
  const done = Boolean(success) && !loading;

  const shared = {
    ...props,
    "aria-busy": loading || undefined,
    "aria-disabled": loading || undefined,
    className: cn(tactileButton({ variant, size, rounded, flat }), className),
    onClick: loading ? undefined : onClick,
    onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => {
      if (event.key === "Enter") event.currentTarget.setAttribute("data-pressed", "");
      onKeyDown?.(event);
    },
    onKeyUp: (event: React.KeyboardEvent<HTMLButtonElement>) => {
      event.currentTarget.removeAttribute("data-pressed");
      onKeyUp?.(event);
    },
    onBlur: (event: React.FocusEvent<HTMLButtonElement>) => {
      event.currentTarget.removeAttribute("data-pressed");
      onBlur?.(event);
    },
  };

  const faces = (
    <span className="grid place-items-center gap-[inherit]">
      <span aria-hidden={loading || done || undefined} className={cn(face, (loading || done) && away)}>
        {iconStart && <span className="-ms-1 inline-flex">{iconStart}</span>}
        {children}
        {iconEnd && <span className="-me-1 inline-flex">{iconEnd}</span>}
      </span>
      <span aria-hidden={!loading || undefined} className={cn(face, !loading && away)}>
        <Bars />
      </span>
      <span aria-hidden={!done || undefined} className={cn(face, !done && away)}>
        {/* transitions.dev "success check": the wrapper fades, turns and settles while the path draws */}
        <span className="t-success-check tactile-check" data-state={done ? "in" : "out"}>
          <Check />
        </span>
        {success === true ? null : success}
      </span>
    </span>
  );

  if (render) return cloneElement(render, shared, faces);

  return (
    <button type={type} {...shared}>
      {faces}
    </button>
  );
}
```

### 3. Add the success check to your global stylesheet.

The drawn check is the success-check transition from transitions.dev, tuned down to suit an icon inside a button. Without it the check simply appears.

```bash
:root {
  --check-opacity-dur: 500ms;
  --check-rotate-dur: 500ms;
  --check-rotate-from: 80deg;
  --check-bob-dur: 500ms;
  --check-y-amount: 40px;
  --check-blur-dur: 500ms;
  --check-blur-from: 10px;
  --check-path-dur: 500ms;
  --check-path-delay: 80ms;
  --check-ease-out: cubic-bezier(0.22, 1, 0.36, 1);
  --check-ease-opacity: cubic-bezier(0.22, 1, 0.36, 1);
  --check-ease-rotate: cubic-bezier(0.22, 1, 0.36, 1);
  --check-ease-bob: cubic-bezier(0.34, 1.35, 0.64, 1);
  --check-ease-path: cubic-bezier(0.22, 1, 0.36, 1);
}
/* Inside a button the check is 14 to 20px, so it travels, turns and blurs far less */
.tactile-check {
  --check-y-amount: 6px;
  --check-rotate-from: 30deg;
  --check-blur-from: 3px;
}

.t-success-check {
  display: inline-block;
  transform-origin: center;
  opacity: 0;
  will-change: transform, opacity, filter;
}
.t-success-check svg { display: block; overflow: visible; }
.t-success-check svg path {
  stroke-dasharray: 23;
  stroke-dashoffset: 23;
}

.t-success-check[data-state="in"] {
  animation:
    t-check-fade   var(--check-opacity-dur) var(--check-ease-opacity) forwards,
    t-check-rotate var(--check-rotate-dur)  var(--check-ease-rotate)  forwards,
    t-check-blur   var(--check-blur-dur)    var(--check-ease-out)     forwards,
    t-check-bob    var(--check-bob-dur)     var(--check-ease-bob)     forwards;
}
.t-success-check[data-state="in"] svg path {
  animation: t-check-draw var(--check-path-dur) var(--check-ease-path) var(--check-path-delay, 0ms) forwards;
}

@keyframes t-check-fade { from { opacity: 0; } to { opacity: 1; } }
@keyframes t-check-rotate {
  from { transform: rotate(var(--check-rotate-from)); }
  to   { transform: rotate(0deg); }
}
@keyframes t-check-blur {
  from { filter: blur(var(--check-blur-from)); }
  to   { filter: blur(0); }
}
@keyframes t-check-bob {
  from { translate: 0 var(--check-y-amount); }
  to   { translate: 0 0; }
}
@keyframes t-check-draw { to { stroke-dashoffset: 0; } }

@media (prefers-reduced-motion: reduce) {
  .t-success-check { animation: none !important; opacity: 1; }
  .t-success-check svg path { animation: none !important; stroke-dashoffset: 0 !important; }
}
```

## Features

- **The surface presses, the label does not**: Fill, border and shadow live on a pseudo-element, and only that layer scales, so the text never blurs or shifts
- **A border that belongs to the gradient**: The edge is the exact colour the gradient ends on, worked out from the fill, so it holds in both themes
- **Loading and success without a resize**: Label, loader and success mark share one grid cell, so the button keeps the width of the widest
- **A classic bars loader**: Twelve bars turned one step at a time, drawn in the label's colour
- **Keyboard and menu aware**: Enter presses the surface like a click does, and a button that opens a popup stays still so the popup does not shift
- **Optical icon padding**: An icon sits a little closer to the edge than text would, so the content reads as centred
- **Any element**: Pass render to draw it as a link or any other tag
- **Respects reduced motion**: No press scale, no label blur, and the check appears already drawn

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | ReactNode | - | The label |
| className | string | - | Extra classes on the button |
| variant | "default" | default | The only look for now |
| size | "sm" \| "md" \| "lg" | lg | Height, padding, type and icon size |
| rounded | boolean | false | A pill instead of rounded corners |
| flat | boolean | false | Drops the gradient, lit edge and shadow |
| loading | boolean | false | Shows the bars loader and ignores clicks |
| success | ReactNode | - | Shows a drawn check and this text; true for the check alone |
| iconStart, iconEnd | ReactNode | - | An icon before or after the label |
| render | element | - | Replaces the rendered tag |

Every other prop of a button (disabled, onClick, type and so on) is passed through.
