Skip to content
Browse documentation

Merge a pull request and see it go in: the button carries a small branch graph, and pressing it draws what your merge strategy really does to main.

Used forPull request pagesAgents that open PRsDeploy dashboardsContent and docs tools

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/merge-button.json

Registered the namespace? Then it’s shadcn add @hairline/merge-button. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Pull request pages

    The merge action at the foot of a PR, with the strategy the repo uses.

  • Agents that open PRs

    Merging what a coding agent proposed, from the chat or the run summary.

  • Deploy dashboards

    Promoting a preview branch into main, with the result drawn on the button.

  • Content and docs tools

    Publishing a draft branch of a page or a dataset into the live one.

What it handles for you

A merge button that only changes colour doesn’t say what happened to main, and a failed merge usually leaves a toast somewhere else on the screen.

Instead of wiring upmerge pull request buttonmerging spinnermerged badgeconflict toastsquash and merge button
  1. Your merge call

    Pass onMerge; it owns pending, merged and failed, with no state of yours to track.

  2. Three strategies

    Merge, squash and rebase each draw what they really do to the history.

  3. Checks running

    A pulse runs along the branch for as long as your call is pending.

  4. Conflicts in place

    A throw crosses the lines under a red mark and puts the reason on the button.

  5. Retry

    Pressed again after a failure, it runs onMerge again from the start.

  6. Screen readers

    “Merged” or the failure is announced once; the graph is decoration and hidden.

Overview

Most merge buttons turn green, show a spinner, then say “Merged”, and the button looks the same whether the branch was merged, squashed or rebased. Merge button carries the branch on it: main along the bottom, your branch forking off with its commits. While your merge call runs, a pulse travels the branch the way checks run. When it’s in, the graph does what the strategy did: for a merge the branch bends down into main and a merge commit lands where they meet; for a squash the commits slide together into one and that one drops onto main; for a rebase each commit lifts off and lands on main in turn while the branch fades. The label morphs the whole way, Merge pull request → Merging → Merged. If the merge fails, the branch dips towards main, the lines cross under a red mark, the button shakes once and turns to “Resolve conflicts” (or the reason you threw); press it again to retry.

States

ready
Main along the bottom, the branch forking off it with 1 to 4 commits, beside the label for the strategy.
merging
While onMerge is pending the branch dims over 240ms, a bright dash runs along it from the fork every 1.3s and each commit lights as the dash passes it, the way checks run. The label morphs to Merging.
merged (merge)
The branch bends down into main over 440ms, a merge commit pops in where they meet with a slight overshoot, and main draws on past it.
merged (squash)
The commits slide into the head over 380ms and fade into it; that one commit arcs down onto main and settles with a small squash, and the branch draws back to the fork.
merged (rebase)
Each commit lifts off the branch and lands on main in turn, 150ms apart, while the branch fades.
conflict
If onMerge throws, the button turns outlined, the branch dips towards main, a red mark pops where the lines cross and the graph shakes once over 400ms. The label reads Resolve conflicts, or the error’s message.
reduced motion
Every state is drawn in its final position at once; only the label changes.

Usage

usage.tsx
import { MergeButton } from "@/components/merge-button";<MergeButton strategy="squash" onMerge={() => mergePullRequest(pr.number)} />

Works with

Merging a GitHub pull request

Call your own route, which merges with the GitHub API; a 405 or 409 there means the branch can’t be merged, so throw with the reason and the button shows it.

example.tsx
"use client";import { MergeButton } from "@/components/merge-button";export function MergePr({ pr }: { pr: { number: number; merged: boolean; commits: number } }) {  return (    <MergeButton      strategy="squash"      commits={pr.commits}      merged={pr.merged}      onMerge={async () => {        const res = await fetch(`/api/pulls/${pr.number}/merge`, { method: "PUT", body: JSON.stringify({ merge_method: "squash" }) });        if (res.status === 405 || res.status === 409) throw new Error("Resolve conflicts");        if (!res.ok) throw new Error("Couldn’t merge");      }}    />  );}

Props

onMerge
() => Promise<unknown> | void
Your merge call. Resolve when it’s in; throw or reject to show a failure, with the error’s message as the label.
strategy= "merge"
"merge" | "squash" | "rebase"
What the graph draws when it lands, and the labels it uses.
commits= 3
number
Commits drawn on the branch, 1 to 4.
merged= false
boolean
Already merged: shows the merged graph, still.
labels
Partial<Record<"idle" | "pending" | "done" | "error", string>>
Your own words for any state.
sound= false
boolean
A soft sound when it lands, and another on a failure.

Accessibility and motion

  • The graph is one small SVG moved by a frame loop that runs only while something is changing; it sleeps when the button is still.
  • The label changes through TextMorph, so the button’s width eases with it.
  • While merging or once merged the button is aria-disabled and ignores presses; after a failure it takes a press again to retry.
  • The result is announced once from a live region beside the button; the graph is hidden from screen readers.
  • Reduced motion draws each state in place with no pulse, bend or shake.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph.

Source

"use client";import * as React from "react";import { TextMorph } from "./text-morph";import { INTERACTION_FOCUS, INTERACTION_PRESS } from "./ui-interaction-motion";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * MERGE BUTTON: merge a pull request and see it go in * *   ready      the button carries a small graph: main along the *              bottom, your branch forking off it with its commits *   merging    while your onMerge runs, a pulse runs along the *              branch, the way checks run *   merged     each strategy draws what really happens: *                merge   the branch bends down into main and a *                        merge commit lands where they meet *                squash  the commits slide together into one, and *                        that one drops onto main *                rebase  each commit lifts off the branch and lands *                        on main in turn, the branch fades *   conflict   if onMerge throws, the branch dips towards main and *              the lines cross with a red mark and a shake; press *              again to retry * * One SVG, moved by a short frame loop that runs only while * something changes. * ───────────────────────────────────────────────────────── */export type MergeStrategy = "merge" | "squash" | "rebase";type Phase = "idle" | "pending" | "done" | "error";export interface MergeButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "children"> {  /** Your merge call. Throw or reject to show a conflict (or any failure) with the reason in the label. */  onMerge: () => Promise<unknown> | void;  strategy?: MergeStrategy;  /** How many commits to draw on the branch, 1 to 4. */  commits?: number;  /** Already merged: shows the merged state, still. */  merged?: boolean;  labels?: Partial<Record<Phase, string>>;  /** A soft click as it lands, off by default. */  sound?: boolean;}const LABELS: Record<MergeStrategy, Record<Phase, string>> = {  merge: { idle: "Merge pull request", pending: "Merging", done: "Merged", error: "Resolve conflicts" },  squash: { idle: "Squash and merge", pending: "Squashing", done: "Squashed and merged", error: "Resolve conflicts" },  rebase: { idle: "Rebase and merge", pending: "Rebasing", done: "Rebased and merged", error: "Resolve conflicts" },};// The graph, in its own units (viewBox 92 × 32).const MAIN_Y = 24;const BRANCH_Y = 9;const FORK = 9;const HEAD = 62;const JOIN = 78;const END = 90;const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => {  const query = window.matchMedia(reducedQuery);  query.addEventListener("change", onChange);  return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);const seg = (t: number, a: number, b: number) => clamp((t - a) / (b - a), 0, 1);const inOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);const out = (t: number) => 1 - (1 - t) ** 3;const back = (t: number) => 1 + 2.4 * (t - 1) ** 3 + 1.4 * (t - 1) ** 2;/** Where commit i of n sits on the branch. */const commitX = (i: number, n: number) => (n === 1 ? HEAD : 30 + ((HEAD - 30) * i) / (n - 1));/** Where rebased commit i of n lands on main. */const replayX = (i: number, n: number) => JOIN - 12 * (n - 1 - i) * (n > 3 ? 0.75 : 1);export function MergeButton({ onMerge, strategy = "merge", commits = 3, merged = false, labels, sound = false, className = "", disabled, ...props }: MergeButtonProps) {  const reduced = useReducedMotion();  const n = clamp(Math.round(commits), 1, 4);  const [phase, setPhase] = React.useState<Phase>(merged ? "done" : "idle");  const [message, setMessage] = React.useState<string | null>(null);  const text = { ...LABELS[strategy], ...labels };  const label = phase === "error" && message ? message : text[phase];  const svgRef = React.useRef<SVGSVGElement>(null);  const timeline = React.useRef({ phase: phase as Phase, t0: 0, frame: 0, from: phase as Phase });  /** Writes the graph for the current phase and time; returns whether it's still moving. */  const draw = React.useCallback(    (now: number) => {      const svg = svgRef.current;      if (!svg) return false;      const tl = timeline.current;      const t = reduced ? 1e6 : now - tl.t0;      const q = <T extends Element>(sel: string) => svg.querySelector<T>(sel);      const all = (sel: string) => Array.from(svg.querySelectorAll<SVGElement>(sel));      const branch = q<SVGPathElement>("[data-branch]")!;      const bend = q<SVGPathElement>("[data-bend]")!;      const join = q<SVGGElement>("[data-join]")!;      const extend = q<SVGPathElement>("[data-extend]")!;      const pulse = q<SVGPathElement>("[data-pulse]")!;      const cross = q<SVGGElement>("[data-cross]")!;      const dots = all("[data-commit]") as SVGGElement[];      let busy = false;      const show = (el: SVGElement, o: number) => el.setAttribute("opacity", String(clamp(o, 0, 1)));      const at = (el: SVGElement, x: number, y: number, s = 1) => el.setAttribute("transform", `translate(${x} ${y}) scale(${s})`);      // Defaults: the ready graph, brightening back from the dimmed checks if they just ended.      const lit = tl.from === "pending" && tl.phase !== "pending" ? out(seg(t, 0, 220)) : 1;      branch.style.strokeDashoffset = "0";      show(branch, 0.4 + 0.6 * lit);      show(bend, 0);      show(join, 0);      show(extend, 0);      show(pulse, 0);      show(cross, 0);      svg.style.translate = "";      dots.forEach((d, i) => {        show(d, 0.7 + 0.3 * lit);        at(d, commitX(i, n), BRANCH_Y);      });      if (tl.phase === "pending") {        // Checks running: the branch dims, a bright dash travels it from the fork, and each commit lights as it passes.        busy = true;        const ease = reduced ? 1 : out(seg(now - tl.t0, 0, 240));        show(branch, 1 - 0.6 * ease);        const k = ((now - tl.t0) % 1300) / 1300;        const p = -0.16 + 1.3 * k;        show(pulse, ease * (1 - seg(k, 0.85, 1)));        pulse.style.strokeDashoffset = String(-p);        const total = branch.getTotalLength();        const curve = total - (HEAD - FORK - 17);        dots.forEach((d, i) => {          const pos = (curve + commitX(i, n) - FORK - 17) / total;          show(d, 1 - ease * (p + 0.12 >= pos ? 0.1 : 0.5));        });      } else if (tl.phase === "error") {        // The branch dips towards main, the lines cross, a red mark, a shake.        const dip = out(seg(t, 0, 260)) * (1 - 0.6 * out(seg(t, 260, 520)));        show(bend, dip);        bend.style.strokeDashoffset = String(1 - dip * 0.55);        show(cross, back(seg(t, 160, 420)));        at(cross, JOIN - 6, (BRANCH_Y + MAIN_Y) / 2 + 1, Math.max(0.01, back(seg(t, 160, 420))));        const shake = seg(t, 160, 560);        svg.style.translate = shake > 0 && shake < 1 ? `${Math.sin(shake * Math.PI * 6) * 2.4 * (1 - shake)}px 0` : "";        busy = t < 600;      } else if (tl.phase === "done") {        busy = t < 1300;        if (strategy === "merge") {          // The branch bends down into main; the merge commit lands where they meet; main runs on.          const k = inOut(seg(t, 80, 520));          show(bend, 1);          bend.style.strokeDashoffset = String(1 - k);          const pop = seg(t, 440, 720);          show(join, pop > 0 ? 1 : 0);          at(join, JOIN, MAIN_Y, Math.max(0.01, back(pop)));          show(extend, 1);          extend.style.strokeDashoffset = String(1 - out(seg(t, 560, 900)));        } else if (strategy === "squash") {          // The commits slide together into the head, then that one commit drops onto main.          const gather = inOut(seg(t, 0, 380));          const drop = seg(t, 360, 820);          dots.forEach((d, i) => {            const x = commitX(i, n) + (HEAD - commitX(i, n)) * gather;            if (i < n - 1) {              show(d, (0.7 + 0.3 * lit) * (1 - seg(t, 260, 400)));              at(d, x, BRANCH_Y);            } else {              const e = inOut(drop);              const dx = HEAD + (JOIN - HEAD) * e;              const dy = BRANCH_Y + (MAIN_Y - BRANCH_Y) * e - Math.sin(Math.PI * e) * 5;              const squashed = 1 + 0.25 * gather * (1 - e) - (drop > 0.92 ? 0.12 * Math.sin(Math.PI * seg(t, 780, 900)) : 0);              at(d, dx, dy, squashed);            }          });          // The branch it leaves behind draws back to the fork.          branch.style.strokeDashoffset = String(-out(seg(t, 420, 900)));          show(branch, (0.4 + 0.6 * lit) * (1 - seg(t, 700, 950)));          show(extend, 1);          extend.style.strokeDashoffset = String(1 - out(seg(t, 760, 1100)));        } else {          // Rebase: each commit lifts off the branch and lands on main in turn; the branch fades.          dots.forEach((d, i) => {            const k = inOut(seg(t, 80 + i * 150, 480 + i * 150));            const x0 = commitX(i, n);            const x1 = replayX(i, n);            const x = x0 + (x1 - x0) * k;            const y = BRANCH_Y + (MAIN_Y - BRANCH_Y) * k - Math.sin(Math.PI * k) * 6;            at(d, x, y);          });          show(branch, (0.4 + 0.6 * lit) * (1 - seg(t, 300, 300 + n * 150 + 300)));          show(extend, 1);          extend.style.strokeDashoffset = String(1 - out(seg(t, 200, 520 + n * 150)));          busy = t < 700 + n * 150;        }      }      return busy;    },    [n, strategy, reduced],  );  const run = React.useCallback(() => {    const tl = timeline.current;    cancelAnimationFrame(tl.frame);    const tick = (now: number) => {      tl.frame = 0;      if (draw(now)) tl.frame = requestAnimationFrame(tick);    };    tl.frame = requestAnimationFrame(tick);  }, [draw]);  const go = React.useCallback(    (next: Phase) => {      const tl = timeline.current;      tl.from = tl.phase;      tl.phase = next;      tl.t0 = performance.now();      setPhase(next);      run();    },    [run],  );  React.useEffect(() => {    draw(performance.now());    const tl = timeline.current;    return () => {      cancelAnimationFrame(tl.frame);      tl.frame = 0;    };  }, [draw]);  const busy = phase === "pending";  const finished = phase === "done";  const click = async () => {    if (busy || finished || disabled) return;    setMessage(null);    go("pending");    try {      await onMerge();      go("done");      if (sound) playSound("success", 0.35);    } catch (err) {      setMessage(err instanceof Error && err.message ? err.message : null);      go("error");      if (sound) playSound("error", 0.35);    }  };  const bendPath = `M ${HEAD} ${BRANCH_Y} C ${HEAD + 9} ${BRANCH_Y}, ${JOIN - 4} ${MAIN_Y}, ${JOIN} ${MAIN_Y}`;  return (    <>    <button      type="button"      onClick={click}      aria-disabled={busy || finished || disabled || undefined}      aria-busy={busy || undefined}      className={`group inline-flex h-11 cursor-pointer items-center gap-2.5 rounded-full pl-2.5 pr-5 text-[13.5px] font-medium aria-disabled:cursor-default ${        phase === "error" ? "bg-background text-foreground shadow-[inset_0_0_0_1px_var(--border)]" : "bg-primary text-primary-foreground"      } transition-[background-color,color,box-shadow] duration-300 ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${className}`}      {...props}    >      <svg        ref={svgRef}        viewBox="0 0 92 32"        width={92}        height={32}        aria-hidden        className="shrink-0 overflow-visible"        fill="none"        strokeLinecap="round"        strokeLinejoin="round"      >        {/* main, and where it runs on to once something lands */}        <path d={`M 2 ${MAIN_Y} H ${JOIN - 6}`} stroke="currentColor" strokeOpacity={0.55} strokeWidth={2} />        <path data-extend d={`M ${JOIN - 14} ${MAIN_Y} H ${END}`} pathLength={1} strokeDasharray="1 1" stroke="currentColor" strokeWidth={2} opacity={0} />        {/* the branch, forking off main */}        <path          data-branch          d={`M ${FORK} ${MAIN_Y} C ${FORK + 9} ${MAIN_Y}, ${FORK + 8} ${BRANCH_Y}, ${FORK + 17} ${BRANCH_Y} H ${HEAD}`}          pathLength={1}          strokeDasharray="1 1"          stroke="currentColor"          strokeWidth={2}        />        <path data-bend d={bendPath} pathLength={1} strokeDasharray="1 1" stroke="currentColor" strokeWidth={2} opacity={0} />        {/* checks running along the branch */}        <path          data-pulse          d={`M ${FORK} ${MAIN_Y} C ${FORK + 9} ${MAIN_Y}, ${FORK + 8} ${BRANCH_Y}, ${FORK + 17} ${BRANCH_Y} H ${HEAD}`}          pathLength={1}          strokeDasharray="0.16 2"          stroke="currentColor"          strokeWidth={2.6}          opacity={0}        />        {/* the fork point on main */}        <circle cx={FORK} cy={MAIN_Y} r={2.4} fill="currentColor" fillOpacity={0.55} />        {/* commits: a ring with a filled centre */}        {Array.from({ length: n }, (_, i) => (          <g key={i} data-commit transform={`translate(${commitX(i, n)} ${BRANCH_Y})`}>            <circle r={3.6} fill="currentColor" />            <circle r={1.5} className={phase === "error" ? "fill-background" : "fill-primary"} />          </g>        ))}        {/* the merge commit */}        <g data-join opacity={0} transform={`translate(${JOIN} ${MAIN_Y})`}>          <circle r={5} fill="currentColor" />          <circle r={2.1} className="fill-primary" />        </g>        {/* a conflict */}        <g data-cross opacity={0} transform={`translate(${JOIN - 6} ${(BRANCH_Y + MAIN_Y) / 2})`}>          <circle r={5.4} className="fill-red-600 dark:fill-red-500" />          <path d="M -2 -2 L 2 2 M 2 -2 L -2 2" stroke="white" strokeWidth={1.6} />        </g>      </svg>      <span className={phase === "error" ? "text-red-600 dark:text-red-400" : undefined}>        <TextMorph>{label}</TextMorph>      </span>    </button>    <span className="sr-only" role="status" aria-live="polite">      {phase === "done" ? text.done : phase === "error" ? label : ""}    </span>    </>  );}

Registry item: /r/merge-button.json