-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandPaletteContext.jsx
More file actions
52 lines (45 loc) · 1.42 KB
/
CommandPaletteContext.jsx
File metadata and controls
52 lines (45 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import React, { createContext, useState, useContext, useEffect } from 'react';
const CommandPaletteContext = createContext();
export const useCommandPalette = () => {
return useContext(CommandPaletteContext);
};
export const CommandPaletteProvider = ({ children }) => {
const [isPaletteOpen, setIsPaletteOpen] = useState(false);
const [triggerCommand, setTriggerCommand] = useState(
() => (id) => console.warn(`Command trigger not initialized for ${id}`),
);
const openPalette = () => setIsPaletteOpen(true);
const closePalette = () => setIsPaletteOpen(false);
const togglePalette = () => setIsPaletteOpen((prev) => !prev);
// Global keyboard shortcut
useEffect(() => {
const handleKeyDown = (event) => {
const isKPressed = event.key === 'k' || event.key === 'K';
if (
(event.altKey && isKPressed) ||
(event.ctrlKey && isKPressed) ||
(event.metaKey && isKPressed)
) {
event.preventDefault();
togglePalette();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
return (
<CommandPaletteContext.Provider
value={{
isPaletteOpen,
setIsPaletteOpen,
openPalette,
closePalette,
togglePalette,
triggerCommand,
setTriggerCommand,
}}
>
{children}
</CommandPaletteContext.Provider>
);
};