리펙토링: 코드 최적화

This commit is contained in:
2026-05-27 18:15:27 +09:00
parent 326da377c9
commit 4d6fb49cba
5 changed files with 30 additions and 91 deletions
+7 -5
View File
@@ -92,13 +92,15 @@ prisma/
### 접근성 / 키보드 조작 ### 접근성 / 키보드 조작
- 문제 풀이 화면은 키보드만으로 진행할 수 있어야 한다. - 문제 풀이 화면은 키보드만으로 진행할 수 있어야 한다.
- 문제 풀이 화면은 모든 항을 하나의 공유 input group으로 입력한다. - 문제 풀이 화면은 모든 항을 하나의 공유 input으로 입력한다.
- input group 아래에는 각 항의 입력값 버튼을 버튼 그룹으로 표시한다. 현재 입력 중인 항은 `aria-pressed`로 표시하고, 비어 있는 항은 `?`로 표시한다. - input 아래에는 각 항의 입력값 버튼을 버튼 그룹으로 표시한다. 현재 입력 중인 항은 `aria-pressed`로 표시하고, 비어 있는 항은 `?`로 표시한다.
- 첫째 항에서 Enter를 누르면 같은 input group이 둘째 항 입력으로 전환된다. - 첫째 항에서 Enter를 누르면 같은 input이 둘째 항 입력으로 전환된다.
- 둘째 항에서 Enter를 누르면 제출 동작을 실행한다. 별도 제출 버튼이 없어도 form submit 흐름이 유지되어야 한다. - 둘째 항에서 Enter를 누르면 제출 동작을 실행한다. 별도 제출 버튼이 없어도 form submit 흐름이 유지되어야 한다.
- 모바일 화면에서는 input group에 `-/+` 버튼과 `↵` 버튼을 표시한다. `sm` 이상 화면에서는 물리 키보드 사용을 전제로 이 보조 버튼숨긴다. - 터치 기반 입력 환경에서는 input focus 시 커스텀 숫자 키패드를 표시한다. 키패드는 숫자, `+/-`, `.`, `⌫`, `↵` 버튼을 제공한다.
- 마우스/트랙패드처럼 hover 가능한 정밀 포인터가 있는 환경은 물리 키보드 사용 환경으로 간주하고 커스텀 숫자 키패드를 숨긴다. 웹 표준 API로 물리 키보드 연결 여부 자체를 안정적으로 판별할 수 없으므로 해상도 기준으로 분기하지 않는다.
- 입력 중에는 `-`, `1.` 같은 임시 값을 허용할 수 있지만 제출 시에는 정상적인 양의 실수 또는 음의 실수 표현만 통과시킨다.
- 문제 풀이 화면 최초 진입 시 모바일 키보드를 강제로 열지 않는다. 사용자가 input을 직접 focus하거나 피드백 후 다음 문제로 넘어갈 때 input에 focus를 둔다. - 문제 풀이 화면 최초 진입 시 모바일 키보드를 강제로 열지 않는다. 사용자가 input을 직접 focus하거나 피드백 후 다음 문제로 넘어갈 때 input에 focus를 둔다.
- 모바일 input focus 시 가상 키보드가 올라온 뒤 `span.katex` 상단이 브라우저 화면 상단에 오도록 조정한다. - 터치 기반 입력 환경에서 input focus 시 `span.katex` 상단이 브라우저 화면 상단에 오도록 조정한다.
- 정답·오답 피드백이 표시되면 다음 진행 버튼에 focus를 둔다. - 정답·오답 피드백이 표시되면 다음 진행 버튼에 focus를 둔다.
- 최종 결과 화면이 표시되면 다시 시작 버튼에 focus를 둔다. - 최종 결과 화면이 표시되면 다시 시작 버튼에 focus를 둔다.
- 아이콘이나 기호만으로 상태를 표시할 때는 `aria-label`, `sr-only` 텍스트 등으로 의미를 함께 제공한다. - 아이콘이나 기호만으로 상태를 표시할 때는 `aria-label`, `sr-only` 텍스트 등으로 의미를 함께 제공한다.
+8 -4
View File
@@ -57,14 +57,18 @@
- 오답 항목은 오답 색상 박스, 붉은색 입력값, `×`, 굵은 정답값을 함께 표시합니다. - 오답 항목은 오답 색상 박스, 붉은색 입력값, `×`, 굵은 정답값을 함께 표시합니다.
- 결과 화면은 지금까지 푼 문제를 `문제 = 내가 입력한 답` 형식으로 다시 보여주고, 정답·오답 표시 규칙을 피드백 화면과 공유합니다. - 결과 화면은 지금까지 푼 문제를 `문제 = 내가 입력한 답` 형식으로 다시 보여주고, 정답·오답 표시 규칙을 피드백 화면과 공유합니다.
- 키보드 흐름을 지원합니다. - 키보드 흐름을 지원합니다.
- 모든 항은 하나의 input group에서 순서대로 입력 - 모든 항은 하나의 input에서 순서대로 입력
- 첫째 항 Enter → 같은 input group이 둘째 항 입력으로 전환 - 첫째 항 Enter → 같은 input이 둘째 항 입력으로 전환
- 둘째 항 Enter → 제출 - 둘째 항 Enter → 제출
- 피드백 화면 → 다음 문제/결과 보기 버튼에 focus - 피드백 화면 → 다음 문제/결과 보기 버튼에 focus
- 다음 문제 이동 후 → input에 focus - 다음 문제 이동 후 → input에 focus
- 결과 화면 → 다시 시작 버튼에 focus - 결과 화면 → 다시 시작 버튼에 focus
- input group 아래에는 각 항의 입력값 버튼이 표시됩니다. 비어 있는 항은 `?`로 표시하고, 버튼을 누르면 해당 항을 초기화한 뒤 다시 입력합니다. - input 아래에는 각 항의 입력값 버튼이 표시됩니다. 비어 있는 항은 `?`로 표시하고, 버튼을 누르면 해당 항을 초기화한 뒤 다시 입력합니다.
- 모바일 화면에서는 `-/+``↵` 보조 버튼을 표시하고, input focus 후 가상 키보드가 올라오면 문제 수식이 화면 상단에 오도록 스크롤 위치를 조정합니다. - 터치 기반 입력 환경에서는 input focus 후 커스텀 숫자 키패드를 표시합니다.
- 키패드는 숫자, `+/-`, `.`, `⌫`, `↵` 버튼을 제공합니다.
- `↵`는 첫째 항에서 둘째 항으로 이동하고, 둘째 항에서 제출합니다.
- 마우스/트랙패드처럼 hover 가능한 정밀 포인터가 있는 환경은 물리 키보드 사용 환경으로 간주해 키패드를 숨깁니다.
- 입력 중에는 `-`, `1.` 같은 임시 값을 허용하지만, 제출 시에는 정상적인 양의 실수 또는 음의 실수 표현만 통과합니다.
--- ---
+2 -72
View File
@@ -12,12 +12,11 @@ import type {
import FeedbackPanel from "@/components/game/FeedbackPanel"; import FeedbackPanel from "@/components/game/FeedbackPanel";
import ScoreSummary from "@/components/game/ScoreSummary"; import ScoreSummary from "@/components/game/ScoreSummary";
import StageIndicator from "@/components/game/StageIndicator"; import StageIndicator from "@/components/game/StageIndicator";
import { DESKTOP_INPUT_DEVICE_QUERY } from "@/lib/input-device";
import KatexRenderer from "@/components/math/KatexRenderer"; import KatexRenderer from "@/components/math/KatexRenderer";
import { useGameStore } from "@/store/gameStore"; import { useGameStore } from "@/store/gameStore";
import type { ProblemCount } from "@/store/gameStore"; import type { ProblemCount } from "@/store/gameStore";
const DESKTOP_INPUT_DEVICE_QUERY = "(any-hover: hover) and (any-pointer: fine)";
const MOBILE_KEYBOARD_SPACER_OFFSET = 480;
const REAL_NUMBER_PATTERN = /^-?\d+(?:\.\d+)?$/; const REAL_NUMBER_PATTERN = /^-?\d+(?:\.\d+)?$/;
function parseAnswer(value: string) { function parseAnswer(value: string) {
@@ -44,14 +43,11 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
const resetSession = useGameStore((state) => state.resetSession); const resetSession = useGameStore((state) => state.resetSession);
const problemCardRef = useRef<HTMLDivElement>(null); const problemCardRef = useRef<HTMLDivElement>(null);
const scrollTimeoutsRef = useRef<number[]>([]);
const viewportResizeCleanupRef = useRef<(() => void) | null>(null);
const answerFormRef = useRef<AnswerFormHandle>(null); const answerFormRef = useRef<AnswerFormHandle>(null);
const [answerA, setAnswerA] = useState(""); const [answerA, setAnswerA] = useState("");
const [answerB, setAnswerB] = useState(""); const [answerB, setAnswerB] = useState("");
const [activeInput, setActiveInput] = useState<ActiveAnswerInput>(0); const [activeInput, setActiveInput] = useState<ActiveAnswerInput>(0);
const [mobileFocusSpacerHeight, setMobileFocusSpacerHeight] = useState(0);
const [inputError, setInputError] = useState(""); const [inputError, setInputError] = useState("");
const sessionProblemCount = session?.problems.length ?? null; const sessionProblemCount = session?.problems.length ?? null;
@@ -89,17 +85,6 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
setInputError(""); setInputError("");
}, [currentProblem?.key]); }, [currentProblem?.key]);
const clearViewportFocusCleanup = useCallback(() => {
scrollTimeoutsRef.current.forEach((timeoutId) => {
window.clearTimeout(timeoutId);
});
scrollTimeoutsRef.current = [];
viewportResizeCleanupRef.current?.();
viewportResizeCleanupRef.current = null;
}, []);
useEffect(() => clearViewportFocusCleanup, [clearViewportFocusCleanup]);
function handleSubmit(event: FormEvent<HTMLFormElement>) { function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
@@ -124,10 +109,6 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
answerFormRef.current?.focusInput(); answerFormRef.current?.focusInput();
} }
const handleInputBlur = useCallback(() => {
setMobileFocusSpacerHeight(0);
}, []);
const scrollKatexToViewportTop = useCallback(() => { const scrollKatexToViewportTop = useCallback(() => {
if (window.matchMedia(DESKTOP_INPUT_DEVICE_QUERY).matches) return; if (window.matchMedia(DESKTOP_INPUT_DEVICE_QUERY).matches) return;
@@ -157,53 +138,10 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
window.scrollTo(0, scrollTop); window.scrollTo(0, scrollTop);
} }
const visualViewport = window.visualViewport;
const keyboardHeight = Math.max(
0,
window.innerHeight -
(visualViewport?.height ?? window.innerHeight) -
(visualViewport?.offsetTop ?? 0),
);
setMobileFocusSpacerHeight(
Math.max(
window.innerHeight,
keyboardHeight + MOBILE_KEYBOARD_SPACER_OFFSET,
),
);
clearViewportFocusCleanup();
if (visualViewport) {
let settleTimeoutId: number | null = null;
const handleViewportResize = () => {
if (settleTimeoutId !== null) {
window.clearTimeout(settleTimeoutId);
}
settleTimeoutId = window.setTimeout(() => {
alignKatex();
}, 180);
};
visualViewport.addEventListener("resize", handleViewportResize);
viewportResizeCleanupRef.current = () => {
visualViewport.removeEventListener("resize", handleViewportResize);
if (settleTimeoutId !== null) {
window.clearTimeout(settleTimeoutId);
}
};
}
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
window.requestAnimationFrame(alignKatex); window.requestAnimationFrame(alignKatex);
}); });
[900, 1300].forEach((delay) => { }, []);
const timeoutId = window.setTimeout(alignKatex, delay);
scrollTimeoutsRef.current.push(timeoutId);
});
}, [clearViewportFocusCleanup]);
if (!session || sessionNeedsInit) { if (!session || sessionNeedsInit) {
return ( return (
@@ -284,7 +222,6 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
onActiveInputChange={setActiveInput} onActiveInputChange={setActiveInput}
onAnswerAChange={setAnswerA} onAnswerAChange={setAnswerA}
onAnswerBChange={setAnswerB} onAnswerBChange={setAnswerB}
onInputBlur={handleInputBlur}
onInputFocus={scrollKatexToViewportTop} onInputFocus={scrollKatexToViewportTop}
onSubmit={handleSubmit} onSubmit={handleSubmit}
/> />
@@ -298,13 +235,6 @@ export default function PlayClient({ problemCount }: PlayClientProps) {
onNext={handleNextProblem} onNext={handleNextProblem}
/> />
) : null} ) : null}
{!submitted && mobileFocusSpacerHeight > 0 ? (
<div
aria-hidden="true"
style={{ height: mobileFocusSpacerHeight }}
/>
) : null}
</section> </section>
</main> </main>
); );
+11 -10
View File
@@ -11,10 +11,11 @@ import {
} from "react"; } from "react";
import type { FocusEvent, FormEvent } from "react"; import type { FocusEvent, FormEvent } from "react";
import { DESKTOP_INPUT_DEVICE_QUERY } from "@/lib/input-device";
export type ActiveAnswerInput = 0 | 1; export type ActiveAnswerInput = 0 | 1;
const ANSWER_INPUT_PATTERN = /^-?\d*(?:\.\d*)?$/; const ANSWER_INPUT_PATTERN = /^-?\d*(?:\.\d*)?$/;
const DESKTOP_INPUT_DEVICE_QUERY = "(any-hover: hover) and (any-pointer: fine)";
const KEYPAD_KEYS = [ const KEYPAD_KEYS = [
"1", "1",
"2", "2",
@@ -290,15 +291,6 @@ const AnswerForm = forwardRef<AnswerFormHandle, AnswerFormProps>(function Answer
{key} {key}
</button> </button>
))} ))}
<button
type="button"
onPointerDown={(event) => event.preventDefault()}
onClick={deleteLastCharacter}
aria-label={`${activeLabel} 마지막 글자 삭제`}
className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 bg-white text-xl font-semibold text-slate-800 shadow-sm transition hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
>
</button>
<button <button
type="button" type="button"
onPointerDown={(event) => event.preventDefault()} onPointerDown={(event) => event.preventDefault()}
@@ -308,6 +300,15 @@ const AnswerForm = forwardRef<AnswerFormHandle, AnswerFormProps>(function Answer
> >
. .
</button> </button>
<button
type="button"
onPointerDown={(event) => event.preventDefault()}
onClick={deleteLastCharacter}
aria-label={`${activeLabel} 마지막 글자 삭제`}
className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 bg-white text-xl font-semibold text-slate-800 shadow-sm transition hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
>
</button>
<button <button
type="button" type="button"
onPointerDown={(event) => event.preventDefault()} onPointerDown={(event) => event.preventDefault()}
+2
View File
@@ -0,0 +1,2 @@
export const DESKTOP_INPUT_DEVICE_QUERY =
"(any-hover: hover) and (any-pointer: fine)";