-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7f99270
commit 06f56ea
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import { | ||
ReactNode, | ||
createContext, | ||
useContext, | ||
useEffect, | ||
useState, | ||
} from 'react'; | ||
|
||
interface KeyModifiers { | ||
ctrlKey: boolean; | ||
shiftKey: boolean; | ||
altKey: boolean; | ||
} | ||
|
||
const defaultKeyModifiersState: KeyModifiers = { | ||
ctrlKey: false, | ||
shiftKey: false, | ||
altKey: false, | ||
}; | ||
|
||
export const KeyModifierContext = createContext<KeyModifiers>( | ||
defaultKeyModifiersState, | ||
); | ||
|
||
export function useKeyModifiers() { | ||
const context = useContext(KeyModifierContext); | ||
if (!context) { | ||
throw new Error('key modifiers context was not found'); | ||
} | ||
|
||
return context; | ||
} | ||
|
||
interface KeyModifierProviderProps { | ||
children: ReactNode; | ||
} | ||
|
||
const isMac = | ||
navigator !== undefined && navigator.userAgent.toLowerCase().includes('mac'); | ||
|
||
function getModifiers(event: KeyboardEvent) { | ||
const { shiftKey, altKey, metaKey } = event; | ||
const ctrlKey = isMac ? metaKey : event.ctrlKey; | ||
return { ctrlKey, shiftKey, altKey }; | ||
} | ||
|
||
export function KeyModifiersProvider({ children }: KeyModifierProviderProps) { | ||
const [modifiers, setModifiers] = useState<KeyModifiers>( | ||
defaultKeyModifiersState, | ||
); | ||
|
||
useEffect(() => { | ||
function handleKeyDown(event: KeyboardEvent) { | ||
setModifiers(getModifiers(event)); | ||
} | ||
|
||
function handleKeyUp(event: KeyboardEvent) { | ||
setModifiers(getModifiers(event)); | ||
} | ||
|
||
document.addEventListener('keydown', handleKeyDown); | ||
document.addEventListener('keyup', handleKeyUp); | ||
|
||
return () => { | ||
document.removeEventListener('keydown', handleKeyDown); | ||
document.removeEventListener('keyup', handleKeyUp); | ||
}; | ||
}, []); | ||
|
||
return ( | ||
<KeyModifierContext.Provider value={modifiers}> | ||
{children} | ||
</KeyModifierContext.Provider> | ||
); | ||
} |