Icon Swap
SaveCross-fades icons that share one box with a small scale and blur, plus a Copy Button whose two pages slide together into a check that draws itself.
- Category
- Core
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Icon Swap preview
npx @shakenui/cli add icon-swapInstallation
npx @shakenui/cli add icon-swapReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add icon-swap --dry-runUsage
icon-swap-example.tsx
"use client";
import { useState } from "react";
import { CopyButton, IconSwap } from "@/components/shaken/ui/icon-swap";
const iconButton =
"inline-flex size-9 items-center justify-center rounded-lg border border-zinc-950/12 bg-white text-zinc-700 transition-[background-color,color,scale] duration-150 ease-out hover:bg-zinc-950/[0.03] hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 motion-safe:active:scale-[0.96] dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:hover:bg-white/[0.06] dark:hover:text-white";
const menu = (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
<path d="M2.5 5h11M2.5 11h11" />
</svg>
);
const close = (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
<path d="m4 4 8 8M12 4l-8 8" />
</svg>
);
const play = (
<svg viewBox="0 0 16 16" fill="currentColor">
<path d="M5 3.4v9.2a.6.6 0 0 0 .9.5l7.3-4.6a.6.6 0 0 0 0-1L5.9 2.9a.6.6 0 0 0-.9.5Z" />
</svg>
);
const pause = (
<svg viewBox="0 0 16 16" fill="currentColor">
<rect x="3.5" y="3" width="3" height="10" rx="0.75" />
<rect x="9.5" y="3" width="3" height="10" rx="0.75" />
</svg>
);
export default function IconSwapExample() {
const [open, setOpen] = useState(false);
const [playing, setPlaying] = useState(false);
return (
<div className="grid w-full max-w-sm gap-5">
<div className="flex items-center gap-2">
<button
type="button"
aria-label="Navigation"
aria-expanded={open}
onClick={() => setOpen((value) => !value)}
className={iconButton}
>
<IconSwap value={open ? "close" : "menu"} icons={{ menu, close }} />
</button>
<button
type="button"
aria-label={playing ? "Pause preview" : "Play preview"}
onClick={() => setPlaying((value) => !value)}
className={iconButton}
>
<IconSwap value={playing ? "pause" : "play"} icons={{ play, pause }} />
</button>
<CopyButton
value="https://shakenui.com/r/run/8f3a2c"
label="Copy link"
copiedLabel="Link copied"
showLabel
variant="secondary"
className="ml-auto h-9"
/>
</div>
<div className="flex items-center gap-2 rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] py-1 pr-1 pl-3 dark:border-white/[0.08] dark:bg-transparent">
<code className="min-w-0 flex-1 truncate font-mono text-xs text-zinc-700 dark:text-zinc-300">npx @shakenui/cli add icon-swap</code>
<CopyButton value="npx @shakenui/cli add icon-swap" label="Copy command" size="sm" />
</div>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| value | string | — | IconSwap: key of the icon to show. |
| icons | Record<string, ReactNode> | — | IconSwap: every icon the box can show, by key. All stay mounted so swaps are interruptible. |
| CopyButton value | string | () => string | Promise<string> | — | CopyButton: the text to copy, or a function that returns it. |
| label / copiedLabel | string | "Copy" / "Copied" | CopyButton: the button's name, and the text announced and shown after copying. |
| showLabel | boolean | false | CopyButton: shows the label next to the icon; both labels share one width so the button never resizes. |
| variant | "ghost" | "secondary" | "ghost" | CopyButton: button style. |
| size | "sm" | "md" | "md" | CopyButton: 28px or 32px tall. |
| timeout | number | 1600 | CopyButton: milliseconds the check stays before the copy icon returns. |
| onCopy / onCopyError | (text) => void / (error) => void | — | CopyButton: called after a successful copy, or when the clipboard refuses. |
Accessibility
- IconSwap is aria-hidden; name the button that holds it, and pair state changes with aria-pressed, aria-expanded, or a changing aria-label.
- CopyButton is a native button. Icon-only, it is named by label; with showLabel, the inactive label is aria-hidden so the name is always the visible text.
- After copying, the copied label is announced once through a polite live region outside the button.
- Falls back to a hidden textarea and the copy command on insecure origins.
- With reduced motion preferred, icons and labels swap instantly and the check appears already drawn.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/icon-swap.tsxicon-swap- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/icon-swap/0.1.0.json.
ui/icon-swap.tsxShowHide
ui/icon-swap.tsx
"use client";
import { type ComponentProps, type ReactNode, useEffect, useRef, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
export interface IconSwapProps extends Omit<ComponentProps<"span">, "children"> {
/** Key of the icon to show. */
value: string;
/** Every icon the box can show, by key. All stay mounted, so swaps are interruptible. */
icons: Record<string, ReactNode>;
}
/**
* Cross-fades icons that share one box: the outgoing icon shrinks, blurs and fades while the
* incoming one grows into focus, both at once. Size the box with `className` (16px by default).
* Each icon's wrapper carries `data-state="active"` or `"inactive"` on a `group/icon-swap`, so an
* icon can style its own parts during the swap (see the check in CopyButton).
* Decorative: label the button that holds it.
*/
export function IconSwap({ value, icons, className, ...props }: IconSwapProps) {
return (
<span aria-hidden="true" className={cx("relative inline-grid size-4 shrink-0 place-items-center", className)} {...props}>
{Object.entries(icons).map(([key, icon]) => {
const active = key === value;
return (
<span
key={key}
data-state={active ? "active" : "inactive"}
className={cx(
"group/icon-swap flex size-full items-center justify-center [grid-area:1/1] [&>svg]:size-full",
"transition-[opacity,scale,filter] motion-reduce:transition-none",
// In: 220ms quint ease-out. Out: 140ms, so the two never read as a muddle.
active
? "scale-100 opacity-100 blur-none duration-220 ease-[cubic-bezier(0.23,1,0.32,1)]"
: "pointer-events-none scale-[0.55] opacity-0 blur-[2px] duration-140 ease-out",
)}
>
{icon}
</span>
);
})}
</span>
);
}
/** Two stacked pages. While the swap leaves it, the back page slides onto the front one. */
function CopyGlyph() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path
d="M10.5 3.25V3a1.5 1.5 0 0 0-1.5-1.5H3.25A1.75 1.75 0 0 0 1.5 3.25V9a1.5 1.5 0 0 0 1.5 1.5h.25"
className="transition-[translate,opacity] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] group-data-[state=inactive]/icon-swap:translate-x-[3px] group-data-[state=inactive]/icon-swap:translate-y-[3px] group-data-[state=inactive]/icon-swap:opacity-0 motion-reduce:transition-none"
/>
<rect x="5.5" y="5.5" width="9" height="9" rx="1.75" />
</svg>
);
}
/** A check that draws itself each time it becomes the active icon, and snaps back once hidden. */
function CheckGlyph() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
<path
d="M3 8.5 6.5 12 13 4.5"
pathLength={1}
className={cx(
"[stroke-dasharray:1] [stroke-dashoffset:1] transition-[stroke-dashoffset] delay-150 duration-0",
"group-data-[state=active]/icon-swap:[stroke-dashoffset:0] group-data-[state=active]/icon-swap:delay-60 group-data-[state=active]/icon-swap:duration-320 group-data-[state=active]/icon-swap:ease-[cubic-bezier(0.65,0,0.35,1)]",
"motion-reduce:transition-none",
)}
/>
</svg>
);
}
const copyVariants = {
ghost: cx(
"text-zinc-500 hover:bg-zinc-950/[0.04] hover:text-zinc-950",
"dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
),
secondary: cx(
"border border-zinc-950/12 bg-white text-zinc-700 shadow-[0_1px_2px_rgb(0_0_0/0.04)] hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] hover:text-zinc-950",
"dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:shadow-none dark:hover:border-white/25 dark:hover:bg-white/[0.06] dark:hover:text-white",
),
} as const;
export type CopyButtonVariant = keyof typeof copyVariants;
export interface CopyButtonProps extends Omit<ComponentProps<"button">, "value" | "children" | "onCopy"> {
/** The text to copy, or a function that returns it (it may be async). */
value: string | (() => string | Promise<string>);
/** Names the button, and is the visible text with `showLabel`. */
label?: string;
/** Replaces the label while the check shows, and is announced to screen readers. */
copiedLabel?: string;
/** Shows the label next to the icon. Both labels share one width, so the button never resizes. */
showLabel?: boolean;
variant?: CopyButtonVariant;
/** `sm` is 28px tall, `md` 32px. */
size?: "sm" | "md";
/** Milliseconds the check stays before the copy icon returns. */
timeout?: number;
/** Called with the copied text. */
onCopy?: (text: string) => void;
/** Called when the clipboard refuses the write. */
onCopyError?: (error: unknown) => void;
}
async function writeClipboard(text: string) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return;
}
// Fallback for insecure origins: a hidden textarea and the legacy copy command.
const area = document.createElement("textarea");
area.value = text;
area.setAttribute("readonly", "");
area.style.position = "fixed";
area.style.opacity = "0";
document.body.append(area);
area.select();
const ok = document.execCommand("copy");
area.remove();
if (!ok) throw new Error("Copy command was rejected");
}
/**
* Copies text to the clipboard. The two pages of the copy icon slide together and give way to a
* check that draws itself, in the same box, so nothing around the button moves.
*/
export function CopyButton({
value,
label = "Copy",
copiedLabel = "Copied",
showLabel = false,
variant = "ghost",
size = "md",
timeout = 1600,
onCopy,
onCopyError,
onClick,
className,
type = "button",
...props
}: CopyButtonProps) {
const [copied, setCopied] = useState(false);
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
async function copy() {
try {
const text = typeof value === "function" ? await value() : value;
await writeClipboard(text);
setCopied(true);
window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => setCopied(false), timeout);
onCopy?.(text);
} catch (error) {
onCopyError?.(error);
}
}
return (
<>
<button
type={type}
aria-label={showLabel ? undefined : label}
data-copied={copied || undefined}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) void copy();
}}
className={cx(
"inline-flex shrink-0 cursor-default items-center justify-center gap-1.5 rounded-lg font-medium whitespace-nowrap select-none",
"transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-reduce:transition-none motion-safe:active:scale-[0.96]",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
"disabled:pointer-events-none disabled:opacity-50",
copyVariants[variant],
showLabel ? (size === "sm" ? "h-7 px-2 text-xs" : "h-8 px-2.5 text-sm") : size === "sm" ? "size-7" : "size-8",
className,
)}
{...props}
>
<IconSwap
value={copied ? "check" : "copy"}
icons={{ copy: <CopyGlyph />, check: <CheckGlyph /> }}
className={cx(size === "sm" ? "size-3.5" : "size-4", copied && "text-zinc-950 dark:text-white")}
/>
{showLabel ? (
<span className="inline-grid">
{[label, copiedLabel].map((text, index) => {
const active = (index === 1) === copied;
return (
<span
key={index}
aria-hidden={!active || undefined}
className={cx(
"[grid-area:1/1] transition-[opacity,filter] motion-reduce:transition-none",
active
? "opacity-100 blur-none duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]"
: "opacity-0 blur-[2px] duration-120 ease-out",
)}
>
{text}
</span>
);
})}
</span>
) : null}
</button>
{/* Outside the button so the announcement never becomes part of its name. */}
<span className="sr-only" aria-live="polite">
{copied ? copiedLabel : ""}
</span>
</>
);
}