Install Switcher
Package manager install command with a gliding segmented switch inside the pill: pick pnpm, npm, yarn or bun and the command rewrites, and the copy button copies the one showing. Add the dark class over art.
pnpm dlx shadcn add @01orbital/install-switcher"use client"
import * as React from "react"
import { CheckIcon, CopyIcon } from "@phosphor-icons/react"
import { cn } from "cn"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/components/toggle/segmented-control"
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
} from "@/components/ui/input-group"
// The runners a `shadcn add …` command can start with. Add one here to add a
// segment; the label is what the segment shows.
const MANAGERS = [
{ id: "pnpm", label: "pnpm", run: "pnpm dlx" },
{ id: "npm", label: "npm", run: "npx" },
{ id: "yarn", label: "yarn", run: "yarn dlx" },
{ id: "bun", label: "bun", run: "bunx" },
] as const
type Manager = (typeof MANAGERS)[number]["id"]
/**
* An install command with a package manager switch in the same pill, for a
* hero or docs page. Picking pnpm, npm, yarn or bun rewrites the command's
* runner, and the copy button copies the command as it shows.
*
* When the component is narrower than 32rem, the switch takes its own row
* above the command. After a copy, the button shows a check for two
* seconds; if copying fails, the command is selected and a message below
* asks the reader to press ⌘C or Ctrl+C. Over artwork, add
* `className="dark"`. `className` lands on the outer `div`.
*/
function InstallSwitcher({
command,
defaultManager = "pnpm",
className,
...props
}: Omit<React.ComponentProps<"div">, "children"> & {
/**
* Everything after the runner, such as `shadcn add @01orbital/stars`. The
* chosen manager's runner, such as `pnpm dlx` or `npx`, goes in front.
*/
command: string
/** The package manager shown first: `pnpm`, `npm`, `yarn` or `bun`. */
defaultManager?: Manager
}) {
const [manager, setManager] = React.useState<Manager>(defaultManager)
const { copied, failed, copyToClipboard } = useCopyToClipboard()
const snippetRef = React.useRef<HTMLElement>(null)
const run = MANAGERS.find((m) => m.id === manager)?.run ?? MANAGERS[0].run
// On failure the command is selected, so one keystroke copies it by hand.
const copy = async () => {
const code = snippetRef.current
if (!code) return
if (!(await copyToClipboard(code.textContent ?? ""))) {
window.getSelection()?.selectAllChildren(code)
}
}
return (
<div
data-slot="install-switcher"
className={cn("@container/install w-full min-w-0", className)}
{...props}
>
<InputGroup
data-copied={copied || undefined}
className="h-11 border-border bg-card font-mono text-card-foreground @max-lg/install:h-auto @max-lg/install:flex-wrap @max-lg/install:pt-1.5 @max-lg/install:pb-1"
>
<InputGroupAddon className="pl-1.5 @max-lg/install:w-full @max-lg/install:pb-1">
<SegmentedControl
aria-label="Package manager"
value={[manager]}
onValueChange={(next) => {
if (next[0]) setManager(next[0] as Manager)
}}
className="h-8 gap-0.5 p-0.5 font-sans"
>
{MANAGERS.map((m) => (
<SegmentedControlItem
key={m.id}
value={m.id}
className="h-7 px-2.5 text-xs"
>
{m.label}
</SegmentedControlItem>
))}
</SegmentedControl>
</InputGroupAddon>
<InputGroupAddon aria-hidden="true" className="pr-2 pl-2 font-normal">
$
</InputGroupAddon>
<InputGroupText className="min-w-0 flex-1 text-sm/7 text-current">
<code ref={snippetRef} className="truncate">
{run} {command}
</code>
</InputGroupText>
<InputGroupAddon align="inline-end">
<InputGroupButton
size="icon-sm"
onClick={copy}
aria-label={
copied ? "Copied" : failed ? "Copy failed" : "Copy command"
}
>
{copied ? (
<CheckIcon aria-hidden="true" />
) : (
<CopyIcon aria-hidden="true" />
)}
</InputGroupButton>
</InputGroupAddon>
<span
role="status"
className={
failed
? "absolute top-full left-0 mt-2 px-4 font-sans text-xs"
: "sr-only"
}
>
{copied
? "Copied"
: failed
? "Couldn't copy. It's selected: press ⌘C or Ctrl+C."
: ""}
</span>
</InputGroup>
</div>
)
}
export { InstallSwitcher, MANAGERS }
import { InstallSwitcher } from "@/components/code/install-switcher"
const COPY = {
command: "shadcn add @01orbital/moon-sphere",
} as const
export default function InstallSwitcherDemo() {
return (
<div className="grid min-h-full w-full max-w-2xl flex-1 content-center">
<InstallSwitcher command={COPY.command} />
</div>
)
}
"use client"
import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"
// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
/**
* Extra classes, as a string only: Base UI's function form is not
* accepted. On `SegmentedControl` they land on the track, and on
* `SegmentedControlItem` on the toggle button.
*/
className?: string
}
// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
pressed: Set<string>
group: string
multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })
/**
* A row of toggle buttons on a rounded track. The pressed one sits on a
* raised thumb that slides over from the last one pressed. Put
* `SegmentedControlItem` parts inside.
*
* It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
* `onValueChange` use arrays of item values. Without `multiple`, one item is
* always on: pressing the active item again does nothing, and
* `onValueChange` is not called with an empty array. With `multiple`, every
* item can be turned off. It is horizontal only, and `className` takes a
* string.
*/
function SegmentedControl({
className,
value,
defaultValue,
onValueChange,
multiple = false,
...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
const group = useId()
const [inner, setInner] = useState<string[]>(
(defaultValue as string[] | undefined) ?? []
)
const current = (value as string[] | undefined) ?? inner
const key = current.join("\u0000")
const context = useMemo(
() => ({
pressed: new Set(key ? key.split("\u0000") : []),
group,
multiple,
}),
[key, group, multiple]
)
return (
<PressedContext.Provider value={context}>
<LayoutGroup id={group}>
<ToggleGroupPrimitive
data-slot="segmented-control"
value={current}
multiple={multiple}
onValueChange={(next, event) => {
// One stays on: a press on the active item is ignored.
if (!multiple && next.length === 0) {
event.cancel()
return
}
// The consumer goes first: event.cancel() keeps the old value.
onValueChange?.(next, event)
if (!event.isCanceled) setInner(next as string[])
}}
className={cn(
// The track: a muted well; in dark a faint lit rim on its top edge.
"inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
"dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
className
)}
{...props}
/>
</LayoutGroup>
</PressedContext.Provider>
)
}
/**
* One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
* string `value`. It is square for one character or an icon and widens to
* fit a word.
*
* The pressed item sits on the thumb, a card-colored pill with a soft shadow
* (a light wash in dark mode) that glides over from the last item pressed;
* reduced motion moves it at once. The other items stay muted and come up
* to full ink on hover. When the control has `multiple`, each pressed item
* gets its own thumb, without the glide.
*/
function SegmentedControlItem({
className,
children,
value,
...props
}: Styled<TogglePrimitive.Props>) {
const { pressed, multiple } = useContext(PressedContext)
const reduce = useReducedMotion()
const on = typeof value === "string" && pressed.has(value)
return (
<TogglePrimitive
data-slot="segmented-control-item"
value={value}
className={cn(
"relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:text-foreground",
"focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pressed:text-foreground",
className
)}
{...props}
>
{/* The thumb: one shared element per group, so it glides to whichever
item is pressed instead of popping. With several pressed at once
each keeps its own, still. */}
{on && (
<motion.span
aria-hidden="true"
layoutId={multiple ? undefined : "thumb"}
transition={
reduce
? { duration: 0 }
: { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
}
className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
/>
)}
{children}
</TogglePrimitive>
)
}
export { SegmentedControl, SegmentedControlItem }
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
// timeout is the knob: how long `copied` stays true, in ms. `failed` holds
// until the next try, so the fallback instruction never times out. The
// returned promise says whether the write landed.
function useCopyToClipboard({ timeout = 2000 }: { timeout?: number } = {}) {
const [copied, setCopied] = useState(false)
const [failed, setFailed] = useState(false)
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
// Each try gets a number; only the latest one sets the feedback or the
// timer, so an earlier write finishing late never overrides a newer one.
const attempt = useRef(0)
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current)
},
[]
)
const copyToClipboard = useCallback(
async (text: string) => {
const current = ++attempt.current
let ok = true
try {
await navigator.clipboard.writeText(text)
} catch {
ok = false
}
if (current !== attempt.current) return ok
if (timer.current) clearTimeout(timer.current)
setCopied(ok)
setFailed(!ok)
timer.current = setTimeout(() => setCopied(false), timeout)
return ok
},
[timeout]
)
return { copied, failed, copyToClipboard }
}
export { useCopyToClipboard }
Usage
import { InstallSwitcher } from "@/components/code/install-switcher"
const COPY = {
command: "shadcn add @01orbital/moon-sphere",
} as const
export default function InstallSwitcherDemo() {
return (
<div className="grid min-h-full w-full max-w-2xl flex-1 content-center">
<InstallSwitcher command={COPY.command} />
</div>
)
}API reference
An install command with a package manager switch in the same pill, for a hero or docs page. Picking pnpm, npm, yarn or bun rewrites the command's runner, and the copy button copies the command as it shows.
When the component is narrower than 32rem, the switch takes its own row above the command. After a copy, the button shows a check for two seconds; if copying fails, the command is selected and a message below asks the reader to press ⌘C or Ctrl+C. Over artwork, add className="dark". className lands on the outer div.
Prop
Type
It also accepts the HTML attributes of the element it renders.
Dependencies
npm: @phosphor-icons/react, cn. The CLI installs them for you. cn merges Tailwind class names, in place of clsx and tailwind-merge.
Registry pieces it installs with it:
font-geist-mono- input-group
- segmented-control
use-copy-to-clipboard