diff --git a/B07_DesignDetail/openwebcad/src/commands/run-command.ts b/B07_DesignDetail/openwebcad/src/commands/run-command.ts index 3c905bb6b..0e405565e 100644 --- a/B07_DesignDetail/openwebcad/src/commands/run-command.ts +++ b/B07_DesignDetail/openwebcad/src/commands/run-command.ts @@ -2,6 +2,7 @@ import { toast } from 'react-toastify'; import { Actor } from 'xstate'; import { HtmlEvent } from '../App.types'; +import { setAngleLock } from '../inputController/input-angle-lock'; import { getSelectedEntities, isDrawingReadOnly, notifyWindow, setActiveToolActor } from '../state'; import type { CadCommand } from './command.types'; import { getCommandById, isViewOnlyCommand, resolveCommandInput } from './registry'; @@ -38,6 +39,7 @@ export function runCommand(command: CadCommand): string { } lastCommandId = command.id; + setAngleLock(null); // 앞 명령의 각도 고정은 새 명령에 넘기지 않음 if (command.machine) { setActiveToolActor(new Actor(command.machine)); diff --git a/B07_DesignDetail/openwebcad/src/helpers/get-point-from-event.ts b/B07_DesignDetail/openwebcad/src/helpers/get-point-from-event.ts index 76565a4e2..90a6693bf 100644 --- a/B07_DesignDetail/openwebcad/src/helpers/get-point-from-event.ts +++ b/B07_DesignDetail/openwebcad/src/helpers/get-point-from-event.ts @@ -1,4 +1,5 @@ import { type Point, Vector } from '@flatten-js/core'; +import { getAngleLock, pointAtLock, projectOnLock } from '../inputController/input-angle-lock.ts'; import { type AbsolutePointInputEvent, ActorEvent, @@ -12,21 +13,26 @@ import { /** * Various tools need to convert user input into a point * This function handles mouse click event, number events and in the future absoluteCoordinates and relativeCoordinate events + * 각도 고정(`<30`) 중이면 커서 · 클릭 · 숫자를 기준점에서 고정 방향으로. * @param startPoint * @param event */ export function getPointFromEvent(startPoint: Point | null, event: PointInputEvent): Point { + const locked = startPoint !== null && getAngleLock() !== null; if (event.type === ActorEvent.DRAW) { - return (event as DrawEvent).drawController.getWorldMouseLocation(); + const mouse = (event as DrawEvent).drawController.getWorldMouseLocation(); + return locked ? projectOnLock(startPoint, mouse) : mouse; } if (event.type === ActorEvent.MOUSE_CLICK) { - return (event as MouseClickEvent).worldMouseLocation; + const click = (event as MouseClickEvent).worldMouseLocation; + return locked ? projectOnLock(startPoint, click) : click; } if (event.type === ActorEvent.NUMBER_INPUT) { if (!startPoint) { throw new Error('Cannot get relative point by distance if no start point is provided'); } const distance = (event as NumberInputEvent).value; + if (locked) return pointAtLock(startPoint, distance); // Direction indicated by the startPoint and the mouse location const direction = new Vector( event.worldMouseLocation.x - startPoint.x, diff --git a/B07_DesignDetail/openwebcad/src/inputController/input-angle-lock.ts b/B07_DesignDetail/openwebcad/src/inputController/input-angle-lock.ts new file mode 100644 index 000000000..bee46aac9 --- /dev/null +++ b/B07_DesignDetail/openwebcad/src/inputController/input-angle-lock.ts @@ -0,0 +1,31 @@ +/** + * 각도 고정 `<각도` — 오토캐드 각도 재지정. 다음 한 점만 기준점에서 그 방향(동쪽 0° 반시계 +). + * 커서 · 클릭은 고정 방향 직선 위로 내리고 · 숫자는 그 방향 길이. 점 하나 쓰면 · Esc · 새 명령이면 풂. + */ +import { Point } from '@flatten-js/core'; +import { polarToPoint } from './input-patterns.ts'; + +let lockedDegrees: number | null = null; + +export const getAngleLock = (): number | null => lockedDegrees; + +export const setAngleLock = (degrees: number | null) => { + lockedDegrees = degrees; +}; + +/** 커서 옆 안내 줄 */ +export const angleLockHint = (): string | null => + lockedDegrees === null ? null : `각도 ${lockedDegrees}° 고정 — 길이 입력`; + +/** 기준점에서 고정 방향으로 거리만큼 간 점 */ +export function pointAtLock(base: Point, distance: number): Point { + const offset = polarToPoint(distance, lockedDegrees ?? 0); + return new Point(base.x + offset.x, base.y + offset.y); +} + +/** 점을 기준점 · 고정 방향 직선 위로 내림(커서 · 클릭) */ +export function projectOnLock(base: Point, point: Point): Point { + const unit = polarToPoint(1, lockedDegrees ?? 0); + const along = (point.x - base.x) * unit.x + (point.y - base.y) * unit.y; + return new Point(base.x + unit.x * along, base.y + unit.y * along); +} diff --git a/B07_DesignDetail/openwebcad/src/inputController/input-controller.ts b/B07_DesignDetail/openwebcad/src/inputController/input-controller.ts index b3a2e3e5b..768d6fec9 100644 --- a/B07_DesignDetail/openwebcad/src/inputController/input-controller.ts +++ b/B07_DesignDetail/openwebcad/src/inputController/input-controller.ts @@ -44,14 +44,7 @@ import { } from '../state.ts'; import { Tool } from '../tools.ts'; import { SelectState, selectToolStateMachine } from '../tools/select-tool.ts'; -import { - type AbsolutePointInputEvent, - ActorEvent, - type MouseClickEvent, - type NumberInputEvent, - type RelativePointInputEvent, - type TextInputEvent, -} from '../tools/tool.types.ts'; +import { ActorEvent, type MouseClickEvent, type TextInputEvent } from '../tools/tool.types.ts'; import { activeToolAcceptsText, activeToolWantsFreeText, @@ -63,14 +56,8 @@ import { drawInputField } from './input-field-draw.ts'; import { ctrlShortcut } from './input-shortcut.ts'; import { wheelZoom } from './input-wheel.ts'; import { attachTouch } from './input-touch.ts'; -import { - ABSOLUTE_POINT_REGEXP, - ABSOLUTE_POLAR_REGEXP, - NUMBER_REGEXP, - polarToPoint, - RELATIVE_POINT_REGEXP, - RELATIVE_POLAR_REGEXP, -} from './input-patterns.ts'; +import { ANGLE_LOCK_REGEXP, parsePointText, type PointTextEvent } from './input-patterns.ts'; +import { angleLockHint, setAngleLock } from './input-angle-lock.ts'; /** 이만큼 넘게 끌면 클릭이 아니라 드래그로 본다 (화면 픽셀) */ const DRAG_SELECT_MIN_PX = 4; @@ -135,6 +122,8 @@ export class InputController { const roundedY = round(drawController.getWorldMouseLocation().y, 2); texts.push(`${roundedX},${roundedY}`); } + const lockHint = angleLockHint(); + if (lockHint) texts.push(lockHint); // 입력 중인 문자로 시작하는 명령 후보. 예: C => CIRCLE (C), COPY (CO) texts.push(...this.getCommandSuggestions()); // 입력 글(조합 중인 한글도 함께) @@ -213,7 +202,7 @@ export class InputController { ); const worldMouseLocation = closestSnapPoint ? closestSnapPoint.point : worldMouseLocationTemp; - getActiveToolActor()?.send({ + this.sendPointEvent({ type: ActorEvent.MOUSE_CLICK, worldMouseLocation, screenMouseLocation: screenCanvasDrawController.worldToTarget(worldMouseLocation), @@ -448,6 +437,7 @@ export class InputController { } public handleEscapeKey() { + setAngleLock(null); if (getSelectedEntities().length > 0) { // Deselect entities setSelectedEntityIds([]); @@ -495,17 +485,20 @@ export class InputController { if (wasSelectTool && getActiveToolActor()?.getSnapshot()?.status === 'done') { setActiveToolActor(new Actor(selectToolStateMachine)); } - } else if (activeToolCanHandleTextInput) { - console.log('TEXT_INPUT: ', { - text: this.text, - activeTool: getActiveToolActor(), - }); - // Send the text to the active tool - getActiveToolActor()?.send({ - type: ActorEvent.TEXT_INPUT, - value: this.text, - } as TextInputEvent); + } else if (activeToolWantsFreeText()) { + // 글 단계(TEXT · MTEXT · 표 칸 …)는 친 그대로 — 숫자 · 명령 이름도 글 + this.sendText(); + } else if (ANGLE_LOCK_REGEXP.test(this.text)) { + // 각도 고정 `<30` — 다음 한 점만 그 방향 + setAngleLock(Number.parseFloat((ANGLE_LOCK_REGEXP.exec(this.text) as RegExpExecArray)[1])); this.text = ''; + } else if (this.pointEventFromText()) { + // 거리 `100` · `x,y` · `@x,y` · `@d + getSnapPointOnAngleGuide()?.point || + getSnapPoint()?.point || + getScreenCanvasDrawController().getWorldMouseLocation() + ); + } + + /** 점 하나를 도구에 보냄 — 각도 고정은 이 한 점으로 끝 */ + private sendPointEvent(event: PointTextEvent | MouseClickEvent) { + getActiveToolActor()?.send(event); + setAngleLock(null); + } + public handleUndo(evt: KeyboardEvent) { evt.preventDefault(); undo(); diff --git a/B07_DesignDetail/openwebcad/src/inputController/input-patterns.ts b/B07_DesignDetail/openwebcad/src/inputController/input-patterns.ts index d2483f459..0d92a49c9 100644 --- a/B07_DesignDetail/openwebcad/src/inputController/input-patterns.ts +++ b/B07_DesignDetail/openwebcad/src/inputController/input-patterns.ts @@ -1,17 +1,65 @@ -/** 명령 입력 해석 — 숫자 · 좌표 · 극좌표 꼴 */ +/** 명령 입력 해석 — 숫자 · 좌표 · 극좌표 · 각도 고정 꼴 */ import { Point } from '@flatten-js/core'; +import { + type AbsolutePointInputEvent, + ActorEvent, + type NumberInputEvent, + type RelativePointInputEvent, +} from '../tools/tool.types.ts'; -export const NUMBER_REGEXP = /^[0-9]+([.][0-9]+)?$/; -/** 부호 있는 실수 한 개 (좌표는 음수가 될 수 있다) */ -const SIGNED = '(-?[0-9]+(?:[.][0-9]+)?)'; +/** 부호 있는 실수 한 개 — `-5` · `.5` · `1.5` */ +const SIGNED = '(-?(?:[0-9]+(?:[.][0-9]+)?|[.][0-9]+))'; +export const NUMBER_REGEXP = new RegExp(`^${SIGNED}$`); export const ABSOLUTE_POINT_REGEXP = new RegExp(`^${SIGNED}[ ]*,[ ]*${SIGNED}$`); export const RELATIVE_POINT_REGEXP = new RegExp(`^@${SIGNED}[ ]*,[ ]*${SIGNED}$`); /** 극좌표 — 거리<각도(도). `@`가 붙으면 직전 점 기준 */ export const ABSOLUTE_POLAR_REGEXP = new RegExp(`^${SIGNED}[ ]*<[ ]*${SIGNED}$`); export const RELATIVE_POLAR_REGEXP = new RegExp(`^@${SIGNED}[ ]*<[ ]*${SIGNED}$`); +/** 각도 고정 — `<30` (다음 한 점만 그 방향) */ +export const ANGLE_LOCK_REGEXP = new RegExp(`^<[ ]*${SIGNED}$`); -/** 거리·각도(도)를 x·y 변위로 바꾼다 */ +/** 거리·각도(도)를 x·y 변위로 바꾼다 — 각도 = 동쪽 0° 반시계 + */ export function polarToPoint(distance: number, degrees: number): Point { const radians = (degrees * Math.PI) / 180; return new Point(distance * Math.cos(radians), distance * Math.sin(radians)); } + +export type PointTextEvent = NumberInputEvent | AbsolutePointInputEvent | RelativePointInputEvent; + +/** 친 글 → 점 · 거리 사건(숫자 · `x,y` · `@x,y` · `@d Point): PointTextEvent | null { + const num = (value: string) => Number.parseFloat(value); + let match = NUMBER_REGEXP.exec(text); + if (match) { + return { type: ActorEvent.NUMBER_INPUT, value: num(match[1]), worldMouseLocation: cursor() }; + } + match = ABSOLUTE_POINT_REGEXP.exec(text); + if (match) { + return { + type: ActorEvent.ABSOLUTE_POINT_INPUT, + value: new Point(num(match[1]), num(match[2])), + }; + } + match = RELATIVE_POINT_REGEXP.exec(text); + if (match) { + return { + type: ActorEvent.RELATIVE_POINT_INPUT, + value: new Point(num(match[1]), num(match[2])), + }; + } + match = RELATIVE_POLAR_REGEXP.exec(text); + if (match) { + return { + type: ActorEvent.RELATIVE_POINT_INPUT, + value: polarToPoint(num(match[1]), num(match[2])), + }; + } + match = ABSOLUTE_POLAR_REGEXP.exec(text); + if (match) { + return { + type: ActorEvent.ABSOLUTE_POINT_INPUT, + value: polarToPoint(num(match[1]), num(match[2])), + }; + } + return null; +} diff --git a/B07_DesignDetail/openwebcad/src/tools/factories/sequence-tool.ts b/B07_DesignDetail/openwebcad/src/tools/factories/sequence-tool.ts index c4c7859b6..78596b9e8 100644 --- a/B07_DesignDetail/openwebcad/src/tools/factories/sequence-tool.ts +++ b/B07_DesignDetail/openwebcad/src/tools/factories/sequence-tool.ts @@ -176,7 +176,9 @@ export function createSequenceTool(config: SequenceToolConfig) { const drawPreview = ({ context, event }: { context: SequenceContext; event: StateEvent }) => { if (!config.preview) return; - const ghosts = config.preview(makeInput(context.values, cursorPoint(event), context.picks)); + // 각도 고정(`<30`) 중이면 커서를 고정 방향 위로 + const cursor = getPointFromEvent(lastPoint(context.values), event as DrawEvent); + const ghosts = config.preview(makeInput(context.values, cursor, context.picks)); setGhostHelperEntities(ghosts); }; @@ -281,8 +283,10 @@ export function createSequenceTool(config: SequenceToolConfig) { on.DRAW = { actions: drawPreview }; on.MOUSE_CLICK = { actions: pushPoint, target }; on.ABSOLUTE_POINT_INPUT = { actions: pushPoint, target }; - on.RELATIVE_POINT_INPUT = { actions: pushPoint, target }; - on.NUMBER_INPUT = { actions: pushPoint, target }; + // 거리 · 상대 좌표는 기준점(앞 점)이 있을 때만 — 첫 점이면 무시(도구가 멈추지 않게) + const hasBase = ({ context }: { context: SequenceContext }) => !!lastPoint(context.values); + on.RELATIVE_POINT_INPUT = { guard: hasBase, actions: pushPoint, target }; + on.NUMBER_INPUT = { guard: hasBase, actions: pushPoint, target }; if (config.repeatLastStep && index === lastIndex) { on.ENTER = { target: COMMIT_STATE }; } diff --git a/B07_DesignDetail/openwebcad/src/tools/line-tool.ts b/B07_DesignDetail/openwebcad/src/tools/line-tool.ts index 42dc7dd3d..4ea1cb27a 100644 --- a/B07_DesignDetail/openwebcad/src/tools/line-tool.ts +++ b/B07_DesignDetail/openwebcad/src/tools/line-tool.ts @@ -131,7 +131,7 @@ export const lineToolStateMachine = createMachine( const activeLine = new LineEntity( getActiveLayerId(), context.startPoint as Point, - (event as DrawEvent).drawController.getWorldMouseLocation() + getPointFromEvent(context.startPoint, event as DrawEvent) ); activeLine.lineColor = getActiveLineColor(); activeLine.lineWidth = getActiveLineWidth(); diff --git a/resources/tester/cad/keyboard-chain.test.ts b/resources/tester/cad/keyboard-chain.test.ts new file mode 100644 index 000000000..be66f34d4 --- /dev/null +++ b/resources/tester/cad/keyboard-chain.test.ts @@ -0,0 +1,150 @@ +/** + * CAD 키보드 연속 명령(PLAN 331 · 요구 224-7) — 오토캐드 방식. + * 각도 고정 `<30` → 길이 · 시퀀스 첫 점 숫자 · 이동 · 복사 · 회전 키보드 값 · 선 중 C · U · 한 번 스냅 · 동적 입력 Tab. + * 시험 쪽 flatten-js 는 다른 사본(「Illegal Parameters」) — 점은 앱 코드로만 만들고 숫자로 판정. + * 실행: cd B07_DesignDetail/openwebcad && npx vitest run --dir ../../resources/tester/cad keyboard-chain + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("react-toastify", () => ({ + toast: Object.assign(vi.fn(), { error: vi.fn(), info: vi.fn(), warn: vi.fn(), success: vi.fn() }), +})); + +import { toast } from "react-toastify"; +import { InputController } from "../../../B07_DesignDetail/openwebcad/src/inputController/input-controller"; +import { getAngleLock } from "../../../B07_DesignDetail/openwebcad/src/inputController/input-angle-lock"; +import { + getActiveToolActor, + getEntities, + setEntities, + setSelectedEntityIds, +} from "../../../B07_DesignDetail/openwebcad/src/state"; +import { runCommandInput } from "../../../B07_DesignDetail/openwebcad/src/commands/run-command"; +import { initApplication } from "../../../B07_DesignDetail/openwebcad/test/helpers/init-application"; +import { CANVAS_HEIGHT } from "../../../B07_DesignDetail/openwebcad/test/helpers/tests.consts"; + +type Xy = { x: number; y: number }; +type Seg = { start: Xy; end: Xy }; + +const key = (controller: InputController, k: string) => + controller.handleKeyStroke({ + key: k, + code: "", + keyCode: 0, + isComposing: false, + shiftKey: false, + ctrlKey: false, + altKey: false, + metaKey: false, + repeat: false, + target: null, + preventDefault: vi.fn(), + stopPropagation: vi.fn(), + } as unknown as KeyboardEvent); + +/** 글자를 치고 Space(= Enter) */ +const type = (controller: InputController, text: string) => { + for (const ch of text) key(controller, ch); + key(controller, " "); +}; + +/** 세계 좌표 (x, y) 로 커서 이동 — 시험 캔버스는 축척 1 · y 위 + */ +const move = (controller: InputController, x: number, y: number) => + controller.handleMouseMove({ clientX: x, clientY: CANVAS_HEIGHT - y } as MouseEvent); + +const clickAt = (controller: InputController, x: number, y: number) => { + move(controller, x, y); + controller.handleMouseUp({ + button: 0, + clientX: x, + clientY: CANVAS_HEIGHT - y, + target: null, + preventDefault: () => {}, + stopPropagation: () => {}, + } as unknown as MouseEvent); +}; + +const lines = () => + getEntities() + .filter((entity) => entity.getType() === "Line") + .map((entity) => (entity as unknown as { segment: Seg }).segment); + +const expectXy = (point: Xy, x: number, y: number) => { + expect(point.x).toBeCloseTo(x, 3); + expect(point.y).toBeCloseTo(y, 3); +}; + +let controller: InputController; + +beforeEach(() => { + vi.mocked(toast.error).mockClear(); + controller = initApplication(); + setEntities([], true); + setSelectedEntityIds([]); +}); + +describe("331-1 각도 고정 → 길이", () => { + it("L · 0,0 · <30 · 100 → (86.603, 50) · <90 · 50 → (86.603, 100)", () => { + type(controller, "l"); + type(controller, "0,0"); + move(controller, 500, 500); // 커서 방향과 무관하게 고정 각도로 + type(controller, "<30"); + expect(getAngleLock()).toBe(30); + type(controller, "100"); + expect(getAngleLock()).toBeNull(); // 한 점만 + type(controller, "<90"); + type(controller, "50"); + const drawn = lines(); + expect(drawn).toHaveLength(2); + expectXy(drawn[0].start, 0, 0); + expectXy(drawn[0].end, 86.603, 50); + expectXy(drawn[1].end, 86.603, 100); + }); + + it("고정 없이 숫자 = 마우스 방향", () => { + type(controller, "l"); + type(controller, "0,0"); + move(controller, 0, 300); + type(controller, "100"); + expectXy(lines()[0].end, 0, 100); + }); + + it("고정 중 클릭 = 고정 방향 위로 내림 · Esc · 새 명령이면 풂", () => { + type(controller, "l"); + type(controller, "0,0"); + type(controller, "<0"); + clickAt(controller, 60, 25); // 가이드에서 먼 자리(스냅 안 붙게) + expectXy(lines()[0].end, 60, 0); + type(controller, "<45"); + key(controller, "Escape"); + expect(getAngleLock()).toBeNull(); + type(controller, "<45"); + runCommandInput("CIRCLE"); + expect(getAngleLock()).toBeNull(); + }); + + it("음수 · .5 숫자 · 음수 각도", () => { + type(controller, "l"); + type(controller, "0,0"); + type(controller, "<-90"); + type(controller, ".5"); + expectXy(lines()[0].end, 0, -0.5); + type(controller, "<0"); + type(controller, "-10"); + expectXy(lines()[1].end, -10, -0.5); + }); + + it("PLINE 첫 점에 숫자 · @x,y → 무시 · 도구 살아 있음 · 알림 0", () => { + type(controller, "pline"); + type(controller, "100"); + type(controller, "@10,0"); + const snapshot = getActiveToolActor()?.getSnapshot(); + expect(snapshot?.status).toBe("active"); + expect(snapshot?.value).toBe("STEP_0"); + expect(toast.error).not.toHaveBeenCalled(); + type(controller, "0,0"); + type(controller, "<0"); + type(controller, "100"); + expect(getActiveToolActor()?.getSnapshot()?.context.values).toHaveLength(2); + }); +});