Skip to content
45 changes: 45 additions & 0 deletions app/hooks/common/useShortcut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useEffect } from 'react';

const useShortcut = (
onShortcutAction: () => void,
keys: string[],
isGlobal: boolean
) => {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const isPressed = keys?.every((key) => {
if (key === 'Alt') {
return e.altKey;
} else if (key === 'Control' || key === 'Ctrl') {
return e.ctrlKey;
} else if (key === 'Shift') {
return e.shiftKey;
} else if (key === 'Meta') {
return e.metaKey;
}
return e.key.toLowerCase() === key.toLowerCase();
});
if (isPressed) {
onShortcutAction();
}
};
// 고민
// 다른 페이지로 먼저 접근하면 전역 이벤트가 설정되지 않는다.
// 생각나는 해결방법: layout.tsx 에서 useShortcut 훅을 사용하여 전역 이벤트를 설정한다.
// 이렇게 할 경우 어떤 페이지로 접근하든 전역 이벤트를 설정 할 수 있다.

if (isGlobal) {
window.addEventListener('keydown', handler);
} else if (window) {
document.addEventListener('keydown', handler);
}

return () => {
document.removeEventListener('keydown', handler);
};
}, [onShortcutAction, keys, isGlobal]);

return;
};

export default useShortcut;
16 changes: 16 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@ import useToast from '@/app/hooks/useToast';
import useDataFetch from '@/app/hooks/common/useDataFetch';
import { Post } from '@/app/types/Post';
import ErrorBox from '@/app/entities/common/Error/ErrorBox';
import { useRouter } from 'next/navigation';
import useShortcut from '@/app/hooks/common/useShortcut';

export default function Home() {
const { fingerprint } = useFingerprint();
const toast = useToast();
const router = useRouter();

const fetchConfig = {
method: 'GET' as const,
Expand All @@ -41,6 +44,19 @@ export default function Home() {
}
}, [fingerprint]);

const goToWritePage = () => {
toast.success('글쓰기 페이지로 이동합니다...');
router.push('/admin/write');
};

const goToPostsPage = () => {
toast.success('모든 글 목록 페이지로 이동합니다...');
router.push('/posts');
};

useShortcut(goToWritePage, ['Alt', 'N'], true);
useShortcut(goToPostsPage, ['Ctrl', ';'], true);

return (
<main className="w-full max-w-4xl mx-auto grid gap-16 p-4 md:p-8">
<section className="grid gap-6">
Expand Down