Files
shadcn-ui/apps/v4/components/command-menu.tsx
shadcn 1aa35048a5 feat: v4 updates (#7499)
* feat(v4): update home page

* fix

* fix: cards

* feat(v4): charts page

* feat: update pages

* feat: colors

* fix

* feat: add docs

* feat: mdx work

* fix

* fix

* fix: sidebar

* fix: lint

* feat: updates

* feat: update components

* feat: fix docs

* fix: responsive

* feat: implement cmdk

* fix: update navigation menu demo

* fix: code style

* fix: themes

* feat: implement blocks page

* fix: docs config

* refactor

* fix: outputFileTracingIncludes

* fix

* fix: output

* fix

* fix: registry

* refactor: move docs

* debug: docs

* debug

* revert

* fix: mjs

* deps: pin fumadocs

* debug

* fix: downgrade next

* fix: index page

* refactor: move mdx components

* fix: remove copy button

* fix

* was it zod

* yes it was

* remove copy page

* fix: color page

* fix: colors page

* fix: meta colors

* fix: copy button

* feat: sync registry

* fix: registry build script

* feat: update port

* feat: clean up examples

* fix

* fix: mobile nav

* fix: blur for mobile

* fix: sidebar nav

* feat: update examples

* fix: build scripts

* feat: update components

* feat: restyle

* fix: types

* fix: styles

* fix: margins

* fix: screenshots

* fix

* feat: update theme

* fix: charts nav

* fix: image

* feat: optimize images

* fix: menu

* fix: card

* fix: border

* check

* feat: implement charts page

* fix: charts

* fix: og images

* feat: extend touch

* fix: static

* fix: sizing

* fix: mobile screenshots

* fix: page nav

* fix

* feat: update favicon

* fix: theme selector

* fix: feedback

* fix: sink

* docs: update

* fix: styles

* chore: update registry

* fix: command

* fix

* fix: minor updates

* fix: typography on smaller devices

* fix: format

* fix: remove unused icon

* feat: update favicon

* fix: typography

* docs: typography page

* fix: steps
2025-05-30 11:35:16 +04:00

307 lines
11 KiB
TypeScript

"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { type DialogProps } from "@radix-ui/react-dialog"
import { IconArrowRight } from "@tabler/icons-react"
import { CornerDownLeftIcon } from "lucide-react"
import { type Color, type ColorPalette } from "@/lib/colors"
import { source } from "@/lib/source"
import { cn } from "@/lib/utils"
import { useConfig } from "@/hooks/use-config"
import { useIsMac } from "@/hooks/use-is-mac"
import { useMutationObserver } from "@/hooks/use-mutation-observer"
import { copyToClipboardWithMeta } from "@/components/copy-button"
import { Button } from "@/registry/new-york-v4/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/registry/new-york-v4/ui/command"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/registry/new-york-v4/ui/dialog"
import { Separator } from "@/registry/new-york-v4/ui/separator"
export function CommandMenu({
tree,
colors,
...props
}: DialogProps & {
tree: typeof source.pageTree
colors: ColorPalette[]
}) {
const router = useRouter()
const isMac = useIsMac()
const [config] = useConfig()
const [open, setOpen] = React.useState(false)
const [selectedType, setSelectedType] = React.useState<
"color" | "page" | "component" | null
>(null)
const [copyPayload, setCopyPayload] = React.useState("")
const packageManager = config.packageManager || "pnpm"
const handlePageHighlight = React.useCallback(
(isComponent: boolean, item: { url: string; name?: React.ReactNode }) => {
if (isComponent) {
const componentName = item.url.split("/").pop()
setSelectedType("component")
setCopyPayload(
`${packageManager} dlx shadcn@latest add ${componentName}`
)
} else {
setSelectedType("page")
setCopyPayload("")
}
},
[packageManager, setSelectedType, setCopyPayload]
)
const handleColorHighlight = React.useCallback(
(color: Color) => {
setSelectedType("color")
setCopyPayload(color.className)
},
[setSelectedType, setCopyPayload]
)
const runCommand = React.useCallback((command: () => unknown) => {
setOpen(false)
command()
}, [])
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.key === "k" && (e.metaKey || e.ctrlKey)) || e.key === "/") {
if (
(e.target instanceof HTMLElement && e.target.isContentEditable) ||
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLSelectElement
) {
return
}
e.preventDefault()
setOpen((open) => !open)
}
if (e.key === "c" && (e.metaKey || e.ctrlKey)) {
runCommand(() => {
if (selectedType === "color") {
copyToClipboardWithMeta(copyPayload, {
name: "copy_color",
properties: { color: copyPayload },
})
}
if (selectedType === "page" || selectedType === "component") {
copyToClipboardWithMeta(copyPayload, {
name: "copy_npm_command",
properties: { command: copyPayload, pm: packageManager },
})
}
})
}
}
document.addEventListener("keydown", down)
return () => document.removeEventListener("keydown", down)
}, [copyPayload, runCommand, selectedType, packageManager])
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
variant="secondary"
className={cn(
"bg-surface text-surface-foreground/60 dark:bg-card relative h-8 w-full justify-start pl-2.5 font-normal shadow-none sm:pr-12 md:w-40 lg:w-56 xl:w-64"
)}
onClick={() => setOpen(true)}
{...props}
>
<span className="hidden lg:inline-flex">Search documentation...</span>
<span className="inline-flex lg:hidden">Search...</span>
<div className="absolute top-1.5 right-1.5 hidden gap-1 sm:flex">
<CommandMenuKbd>{isMac ? "⌘" : "Ctrl"}</CommandMenuKbd>
<CommandMenuKbd className="aspect-square">K</CommandMenuKbd>
</div>
</Button>
</DialogTrigger>
<DialogContent
showCloseButton={false}
className="rounded-xl border-none bg-clip-padding p-2 pb-11 shadow-2xl ring-4 ring-neutral-200/80 dark:bg-neutral-900 dark:ring-neutral-800"
>
<DialogHeader className="sr-only">
<DialogTitle>Search documentation...</DialogTitle>
<DialogDescription>Search for a command to run...</DialogDescription>
</DialogHeader>
<Command className="**:data-[slot=command-input-wrapper]:bg-input/50 **:data-[slot=command-input-wrapper]:border-input rounded-none bg-transparent **:data-[slot=command-input]:!h-9 **:data-[slot=command-input]:py-0 **:data-[slot=command-input-wrapper]:mb-0 **:data-[slot=command-input-wrapper]:!h-9 **:data-[slot=command-input-wrapper]:rounded-md **:data-[slot=command-input-wrapper]:border">
<CommandInput placeholder="Search documentation..." />
<CommandList className="no-scrollbar min-h-80 scroll-pt-2 scroll-pb-1.5">
<CommandEmpty className="text-muted-foreground py-12 text-center text-sm">
No results found.
</CommandEmpty>
{tree.children.map((group) => (
<CommandGroup
key={group.$id}
heading={group.name}
className="!p-0 [&_[cmdk-group-heading]]:scroll-mt-16 [&_[cmdk-group-heading]]:!p-3 [&_[cmdk-group-heading]]:!pb-1"
>
{group.type === "folder" &&
group.children.map((item) => {
if (item.type === "page") {
const isComponent = item.url.includes("/components/")
return (
<CommandMenuItem
key={item.url}
value={
item.name?.toString()
? `${group.name} ${item.name}`
: ""
}
keywords={isComponent ? ["component"] : undefined}
onHighlight={() =>
handlePageHighlight(isComponent, item)
}
onSelect={() => {
runCommand(() => router.push(item.url))
}}
>
{isComponent ? (
<div className="border-muted-foreground aspect-square size-4 rounded-full border border-dashed" />
) : (
<IconArrowRight />
)}
{item.name}
</CommandMenuItem>
)
}
return null
})}
</CommandGroup>
))}
{colors.map((colorPalette) => (
<CommandGroup
key={colorPalette.name}
heading={
colorPalette.name.charAt(0).toUpperCase() +
colorPalette.name.slice(1)
}
className="!p-0 [&_[cmdk-group-heading]]:!p-3"
>
{colorPalette.colors.map((color) => (
<CommandMenuItem
key={color.hex}
value={color.className}
keywords={["color", color.name, color.className]}
onHighlight={() => handleColorHighlight(color)}
onSelect={() => {
runCommand(() =>
copyToClipboardWithMeta(color.oklch, {
name: "copy_color",
properties: { color: color.oklch },
})
)
}}
>
<div
className="border-ghost aspect-square size-4 rounded-sm bg-(--color) after:rounded-sm"
style={{ "--color": color.oklch } as React.CSSProperties}
/>
{color.className}
<span className="text-muted-foreground ml-auto font-mono text-xs font-normal tabular-nums">
{color.oklch}
</span>
</CommandMenuItem>
))}
</CommandGroup>
))}
</CommandList>
</Command>
<div className="text-muted-foreground absolute inset-x-0 bottom-0 z-20 flex h-10 items-center gap-2 rounded-b-xl border-t border-t-neutral-100 bg-neutral-50 px-4 text-xs font-medium dark:border-t-neutral-700 dark:bg-neutral-800">
<div className="flex items-center gap-2">
<CommandMenuKbd>
<CornerDownLeftIcon />
</CommandMenuKbd>{" "}
{selectedType === "page" || selectedType === "component"
? "Go to Page"
: null}
{selectedType === "color" ? "Copy OKLCH" : null}
</div>
{copyPayload && (
<>
<Separator orientation="vertical" className="!h-4" />
<div className="flex items-center gap-1">
<CommandMenuKbd>{isMac ? "⌘" : "Ctrl"}</CommandMenuKbd>
<CommandMenuKbd>C</CommandMenuKbd>
{copyPayload}
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
)
}
function CommandMenuItem({
children,
className,
onHighlight,
...props
}: React.ComponentProps<typeof CommandItem> & {
onHighlight?: () => void
"data-selected"?: string
"aria-selected"?: string
}) {
const ref = React.useRef<HTMLDivElement>(null)
useMutationObserver(ref, (mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === "attributes" &&
mutation.attributeName === "aria-selected" &&
ref.current?.getAttribute("aria-selected") === "true"
) {
onHighlight?.()
}
})
})
return (
<CommandItem
ref={ref}
className={cn(
"data-[selected=true]:border-input data-[selected=true]:bg-input/50 h-9 rounded-md border border-transparent !px-3 font-medium",
className
)}
{...props}
>
{children}
</CommandItem>
)
}
function CommandMenuKbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
className={cn(
"bg-background text-muted-foreground pointer-events-none flex h-5 items-center justify-center gap-1 rounded border px-1 font-sans text-[0.7rem] font-medium select-none [&_svg:not([class*='size-'])]:size-3",
className
)}
{...props}
/>
)
}