1 import { useEffect, useCallback } from "react"
2 import { DropdownMenu, IconButton, toast, Toaster } from "@medusajs/ui"
3 import { Keyboard } from "@medusajs/icons"
4
5 function getOsShortcut() {
6 const isMacOs =
7 typeof navigator !== "undefined"
8 ? navigator.userAgent.toLowerCase().indexOf("mac") !== 0
9 : true
10
11 return isMacOs ? "⌘" : "Ctrl"
12 }
13
14 export default function DropdownMenuWithShortcuts() {
15 const osShortcut = getOsShortcut()
16 const handleEdit = useCallback(() => {
17 toast.success("Success", {
18 description: "Edit shortcut triggered!",
19 })
20 }, [])
21
22 const handleDelete = useCallback(() => {
23 toast.success("Success", {
24 description: "Delete shortcut triggered!",
25 })
26 }, [])
27
28 useEffect(() => {
29 function handleKeydown(e: KeyboardEvent) {
30 if (e.metaKey && e.key.toLowerCase() === "e") {
31 e.preventDefault()
32 handleEdit()
33 }
34 if (e.metaKey && e.key.toLowerCase() === "d") {
35 e.preventDefault()
36 handleDelete()
37 }
38 }
39 window.addEventListener("keydown", handleKeydown)
40 return () => window.removeEventListener("keydown", handleKeydown)
41 }, [handleEdit, handleDelete])
42
43 return (
44 <>
45 <DropdownMenu>
46 <DropdownMenu.Trigger asChild>
47 <IconButton>
48 <Keyboard />
49 </IconButton>
50 </DropdownMenu.Trigger>
51 <DropdownMenu.Content>
52 <DropdownMenu.Item onSelect={handleEdit}>
53 Edit
54 <DropdownMenu.Shortcut>{osShortcut}E</DropdownMenu.Shortcut>
55 </DropdownMenu.Item>
56 <DropdownMenu.Item onSelect={handleDelete}>
57 Delete
58 <DropdownMenu.Shortcut>{osShortcut}D</DropdownMenu.Shortcut>
59 </DropdownMenu.Item>
60 </DropdownMenu.Content>
61 </DropdownMenu>
62 <Toaster />
63 </>
64 )
65 }