-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: when comand pressed, skip peek, fixed Innei/Shiro#436
Signed-off-by: Innei <[email protected]>
- Loading branch information
Showing
3 changed files
with
66 additions
and
2 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
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
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,57 @@ | ||
import { useEffect, useState } from 'react' | ||
|
||
let globalIsPressed = false | ||
let listeners = [] as ((isPressed: boolean) => void)[] | ||
|
||
function notifyListeners() { | ||
listeners.forEach((listener) => listener(globalIsPressed)) | ||
} | ||
|
||
function handleKeyDown(event: KeyboardEvent) { | ||
if ((event.metaKey || event.ctrlKey) && !globalIsPressed) { | ||
globalIsPressed = true | ||
notifyListeners() | ||
} | ||
} | ||
|
||
function handleKeyUp() { | ||
if (globalIsPressed) { | ||
globalIsPressed = false | ||
notifyListeners() | ||
} | ||
} | ||
|
||
function addListener(listener: (isPressed: boolean) => void) { | ||
listeners.push(listener) | ||
listener(globalIsPressed) | ||
} | ||
|
||
function removeListener(listener: (isPressed: boolean) => void) { | ||
listeners = listeners.filter((l) => l !== listener) | ||
} | ||
|
||
export function useIsCommandOrControlPressed() { | ||
const [isPressed, setIsPressed] = useState(globalIsPressed) | ||
|
||
useEffect(() => { | ||
addListener(setIsPressed) | ||
|
||
if (listeners.length === 1) { | ||
window.addEventListener('keydown', handleKeyDown) | ||
window.addEventListener('keyup', handleKeyUp) | ||
} | ||
|
||
return () => { | ||
removeListener(setIsPressed) | ||
|
||
if (listeners.length === 0) { | ||
window.removeEventListener('keydown', handleKeyDown) | ||
window.removeEventListener('keyup', handleKeyUp) | ||
} | ||
} | ||
}, []) | ||
|
||
return isPressed | ||
} | ||
|
||
export default useIsCommandOrControlPressed |