Merge remote-tracking branch 'origin/sub_laptop_2' into main_laptop_1 — 337 가-1 옵션 틀 · 마-1 import 겹침 풂(안 쓰는 import 셋 뺌)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C6BNBFXFndbqYxu6sZuknK
This commit is contained in:
2026-10-15 23:58:14 +09:00
co-authored by Claude Opus 5.5
24 changed files with 2055 additions and 533 deletions
@@ -112,7 +112,7 @@ describe('Space = Enter(오토캐드)', () => {
expect(activeTool()).toBe(Tool.TEXT);
});
it('빈 Space · Enter = 마지막 명령 반복 · 빈 우클릭은 반복 안 함', () => {
it('빈 Space · Enter · 우클릭 = 마지막 명령 반복(337 · 쉴 때 우클릭도)', () => {
selectIdle();
const controller = new InputController();
press(controller, 'l');
@@ -135,6 +135,6 @@ describe('Space = Enter(오토캐드)', () => {
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
} as unknown as MouseEvent);
expect(activeTool()).toBe(Tool.SELECT);
expect(activeTool()).toBe(Tool.LINE);
});
});
@@ -9,33 +9,6 @@ import { getActiveToolActor } from '../state.ts';
export const isImeKey = (evt: KeyboardEvent): boolean =>
evt.isComposing || evt.keyCode === 229 || evt.key === 'Process';
/** 활성 도구의 지금 단계 설정(평평한 단계만) */
const activeStateConfig = () => {
const snapshot = getActiveToolActor()?.getSnapshot();
return snapshot?.machine?.states?.[snapshot?.value]?.config;
};
/** 활성 도구의 지금 단계가 TEXT_INPUT 을 받는가 */
export function activeToolAcceptsText(): boolean {
return !!activeStateConfig()?.on?.TEXT_INPUT;
}
/** 지금 단계가 점(`x,y`)을 받는가 — 한 번 스냅 이름 · 선택지 판정 */
export function activeToolWantsPoint(): boolean {
return !!activeStateConfig()?.on?.ABSOLUTE_POINT_INPUT;
}
/** 지금 단계가 이 글을 받는가 — 점 단계는 선택지 글자(meta.options · 선 C · U)만 · 나머지는 명령 이름으로 */
export function activeToolTakesText(text: string): boolean {
if (!activeToolAcceptsText()) return false;
if (!activeToolWantsPoint()) return true;
const options = (activeStateConfig()?.meta as { options?: string[] } | undefined)?.options;
return !!options?.includes(text);
}
/** 한글 받개에 초점을 줄 단계 — 글은 받되 점 단계 선택지(영문 C · U)는 아님 */
export const activeToolWantsIme = (): boolean => activeToolAcceptsText() && !activeToolWantsPoint();
/** 지금 단계가 자유 글(TEXT · MTEXT · 표 칸 · 이름 …)을 받는가 — Space 가 띄어쓰기(아니면 Enter) */
export function activeToolWantsFreeText(): boolean {
const meta = getActiveToolActor()?.getSnapshot()?.getMeta?.() as
@@ -44,6 +17,9 @@ export function activeToolWantsFreeText(): boolean {
return Object.values(meta ?? {}).some((stateMeta) => stateMeta?.kind === 'text');
}
/** 한글 받개에 초점을 줄 단계 = 글 물음(`kind: 'text'`)만 — 숫자 · 키워드 물음은 영문 자리 글자 */
export const activeToolWantsIme = (): boolean => activeToolWantsFreeText();
/** Enter 로 받을 Space — 수정키(Shift · Ctrl · Alt · Meta: 한/영 전환 등) · 길게 눌러 반복은 아님 */
export const isPlainSpace = (
evt: Pick<KeyboardEvent, 'key' | 'shiftKey' | 'ctrlKey' | 'altKey' | 'metaKey' | 'repeat'>
@@ -1,13 +1,8 @@
import { Point } from '@flatten-js/core';
import { compact, round } from 'es-toolkit';
import { Actor } from 'xstate';
import { MouseButton } from '../App.types.ts';
import {
describeCommand,
matchCommandPrefixes,
resolveCommandInput,
} from '../commands/registry.ts';
import { repeatLastCommand, runCommand } from '../commands/run-command.ts';
import { describeCommand, matchCommandPrefixes } from '../commands/registry.ts';
import { logLine, runCommandInput } from '../commands/run-command.ts';
import { requestHostSave } from '../integration/aislo-drawing-bridge.ts';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController.ts';
import { calculateAngleGuidesAndSnapPoints } from '../helpers/calculate-angle-guides-and-snap-points.ts';
@@ -21,68 +16,58 @@ import {
getHighlightedEntityIds,
getPickableEntities,
getGridEnabled,
getLastStateInstructions,
getPanStartLocation,
getScreenCanvasDrawController,
getSelectedEntities,
getSnapEnabled,
getSnapPoint,
getSnapPointOnAngleGuide,
isHostSave,
isViewOnly,
redo,
setActiveToolActor,
setAngleStep,
setGhostHelperEntities,
setGridEnabled,
setHighlightedEntityIds,
setPanStartLocation,
setSelectedEntityIds,
setShouldDrawCursor,
setSnapEnabled,
undo,
} from '../state.ts';
import { Tool } from '../tools.ts';
import { SelectState, selectToolStateMachine } from '../tools/select-tool.ts';
import { ActorEvent, type MouseClickEvent, type TextInputEvent } from '../tools/tool.types.ts';
import {
activeToolTakesText,
activeToolWantsFreeText,
activeToolWantsIme,
activeToolWantsPoint,
ImeSink,
isImeKey,
isPlainSpace,
} from './ime-sink.ts';
import { SelectState } from '../tools/select-tool.ts';
import { ActorEvent, type MouseClickEvent } from '../tools/tool.types.ts';
import { activeToolWantsFreeText, activeToolWantsIme, ImeSink, isImeKey, isPlainSpace } from './ime-sink.ts';
import { drawInputField, dynamicInputLine } from './input-field-draw.ts';
import { ctrlShortcut } from './input-shortcut.ts';
import { cadCtrlCommand, ctrlShortcut } from './input-shortcut.ts';
import { wheelZoom } from './input-wheel.ts';
import { isObjectSnap, noteShift, snapAt } from './ortho.ts';
import { isWaitingForSecondSelectPoint, selectingActor } from './selecting.ts';
import { isMiddleDouble, zoomExtents } from './zoom-prompt.ts';
import { attachTouch } from './input-touch.ts';
import {
ANGLE_LOCK_REGEXP,
NUMBER_REGEXP,
parsePointText,
type PointTextEvent,
} from './input-patterns.ts';
import { NUMBER_REGEXP, type PointTextEvent } from './input-patterns.ts';
import {
angleLockHint,
getAngleLock,
getDynamicField,
getLockedLength,
releaseOnePoint,
setAngleLock,
tabDynamicInput,
} from './input-angle-lock.ts';
import {
getSnapOverride,
isSnapName,
setSnapOverride,
snapOverrideHint,
snapOverridePoint,
} from './input-snap-override.ts';
import {
cancelActiveCommand,
closeSubPrompt,
currentNotice,
currentPrompt,
dynamicInputApplies,
isIdle,
notice,
redoCommand,
routeTyped,
sendPoint,
undoCommand,
} from './prompt-input.ts';
/** 이만큼 넘게 끌면 클릭이 아니라 드래그로 본다 (화면 픽셀) */
const DRAG_SELECT_MIN_PX = 4;
@@ -138,17 +123,20 @@ export class InputController {
public draw(drawController: ScreenCanvasDrawController) {
this.ime.sync(activeToolWantsIme());
const toolInstruction = getLastStateInstructions();
const toolInstruction = currentPrompt().line;
const texts: string[] = [];
if (toolInstruction) {
// Draw tool instruction
texts.push(toolInstruction);
}
texts.push(...compact([currentNotice()])); // 거절 · 안내 — 둘째 줄
if (toolInstruction) {
const roundedX = round(drawController.getWorldMouseLocation().x, 2);
const roundedY = round(drawController.getWorldMouseLocation().y, 2);
texts.push(`${roundedX},${roundedY}`);
}
const base = getAngleGuideOriginPoint();
if (base && this.dynamicInputApplies()) {
if (base && dynamicInputApplies()) {
texts.push(
dynamicInputLine(
base,
@@ -175,10 +163,10 @@ export class InputController {
public handleMouseUp(evt: MouseEvent) {
if (evt.button === MouseButton.Right) {
// Right click => confirm action (ENTER)
// 우클릭 = Enter(명령 중 확정 · 쉴 때 반복)
evt.preventDefault();
evt.stopPropagation();
this.handleEnterKey();
this.handleEnterKey(true);
}
// If ancestor parent exist with class .controls => ignore clicks, since a button was clicked instead of the canvas
@@ -379,8 +367,10 @@ export class InputController {
return;
}
const shortcut = ctrlShortcut(evt);
const cadCommand = cadCtrlCommand(evt);
// 한글 조합 중 — 단축키가 먹지 않게 IME 에 넘김(Ctrl 단축키는 조합 중에도 먹음)
if (isImeKey(evt) && !shortcut) return;
if (isImeKey(evt) && !shortcut && !cadCommand) return;
if (!['Shift', 'Control', 'Alt', 'Meta'].includes(evt.key)) notice(null); // 알림 줄은 다음 키까지
console.log(`key pressed: ${evt.key}`);
if (evt.key === 'F12') {
// F12 => open developer tools
@@ -419,7 +409,7 @@ export class InputController {
}
if (evt.key === 'Tab') {
// 점 단계(기준점 있음) = 동적 입력 칸 넘김 · 그 밖 = 브라우저 초점 이동
if (!this.dynamicInputApplies()) return;
if (!dynamicInputApplies()) return;
evt.preventDefault();
const isNumber = NUMBER_REGEXP.test(this.text);
if (this.text && !isNumber) return; // 숫자 아닌 글(@x,y 등)은 그대로 둠
@@ -427,6 +417,12 @@ export class InputController {
this.text = '';
return;
}
if (cadCommand) {
// Ctrl+C · X · Shift+C · Shift+V · 1 — 오토캐드 클립보드 · 특성
evt.preventDefault();
runCommandInput(cadCommand);
return;
}
if (evt.ctrlKey && evt.code === 'KeyV') {
// 막지 않음 — 브라우저가 `paste` 를 쏘고 `integration/dxf-clip-paste.ts` 가 받음(한글 자판도 code 로)
return;
@@ -480,163 +476,66 @@ export class InputController {
} else if (evt.key === 'ArrowRight') {
// Move the screen right
getScreenCanvasDrawController().setScreenOffset(this.getScreenPanStep('right', evt.shiftKey));
} else if (evt.key?.length === 1) {
} else if (evt.key?.length === 1 && !evt.ctrlKey && !evt.altKey && !evt.metaKey) {
// +·-는 확대·축소 단축키로 쓰지 않는다 — 음수 좌표(-100,-50)의 첫 글자를
// 먹어 버렸다. 줌은 휠·뷰 막대·ZOOMIN/ZOOMOUT 명령으로 한다.
// User entered a single character => add to input field text
// 글 단계(TEXT·MTEXT)는 친 그대로 — 명령 입력일 때만 대문자로 바꾼다.
// 글 단계(TEXT·MTEXT)는 친 그대로 — 명령 입력일 때만 대문자로 바꾼다(보이는 글만 · 맞추기는 prompt.ts).
// Ctrl · Alt · ⌘ 와 함께 누른 글자는 쌓지 않음(Ctrl+C → 원이 되던 것).
this.text += activeToolWantsFreeText() ? evt.key : evt.key.toUpperCase();
}
}
/** Esc 한 번 = 명령 끝(오토캐드) — 친 글 · 조합 · 각도 잠금 · 한 번 스냅 · 덧물음도 함께 풂 */
public handleEscapeKey() {
this.text = '';
this.ime.composing = '';
const boxing =
this.isSelectToolActive() &&
getActiveToolActor()?.getSnapshot()?.value === SelectState.WAITING_FOR_SECOND_SELECT_POINT;
if (boxing) {
getActiveToolActor()?.send({ type: ActorEvent.ESC }); // 상자 취소
} else if (isIdle()) {
setSelectedEntityIds([]); // 쉴 때 = 고름 풂
} else {
cancelActiveCommand();
}
releaseOnePoint();
setSnapOverride(null);
if (getSelectedEntities().length > 0) {
// Deselect entities
setSelectedEntityIds([]);
} else if (this.text === '') {
// Cancel tool action
getActiveToolActor()?.send({
type: ActorEvent.ESC,
});
} else {
// clear the input field
this.text = '';
}
closeSubPrompt();
logLine('*취소*');
}
/** 커서 옆에 띄울 명령 후보 (이름·별칭 접두사 일치) */
/** 커서 옆에 띄울 명령 후보 (이름·별칭 접두사 일치) — 쉴 때만 */
private getCommandSuggestions(): string[] {
if (this.text === '') {
if (this.text === '' || !isIdle()) {
return [];
}
return matchCommandPrefixes(this.text).slice(0, 6).map(describeCommand);
}
/** @param repeatIfIdle 키보드 Enter · Space — 빈 입력 + 선택 도구 대기면 마지막 명령 반복(우클릭은 확정만) */
public handleEnterKey(repeatIfIdle = false) {
// submit the text as input to the active tool and clear the input field
const lockedLength = getLockedLength();
if (this.text === '' && lockedLength !== null && this.dynamicInputApplies()) {
// 동적 입력 길이를 잠근 채 Enter — 그 길이(방향 = 각도 고정 · 아니면 커서)
this.sendPointEvent(this.distanceEvent(lockedLength));
} else if (this.text === '') {
console.log('ENTER: ', {
text: this.text,
activeTool: getActiveToolActor(),
});
const wasSelectTool = this.isSelectToolActive();
const selectIdle =
getActiveToolActor()?.getSnapshot()?.value === SelectState.WAITING_FOR_FIRST_SELECT_POINT;
if (repeatIfIdle && wasSelectTool && selectIdle && repeatLastCommand()) return;
// Send the ENTER event to the active tool
getActiveToolActor()?.send({
type: ActorEvent.ENTER,
});
// 선택 도구는 ENTER(우클릭)로 최종 상태에 들어가 **멈춘다**. 다른 도구가 선택을
// 자식으로 불러 쓸 때는 그 끝남이 필요하지만(move·copy·rotate의 onDone),
// 선택이 그 자체로 활성 도구일 때 멈추면 커서 옆 안내가 사라지고 이후 클릭도
// 안 먹는다(2026-08-30 사용자 지적). 그 경우에만 새로 세워 준다.
if (wasSelectTool && getActiveToolActor()?.getSnapshot()?.status === 'done') {
setActiveToolActor(new Actor(selectToolStateMachine));
}
} else if (activeToolWantsFreeText()) {
// 글 단계(TEXT · MTEXT · 표 칸 …)는 친 그대로 — 숫자 · 명령 이름도 글
this.sendText();
} else if (
getDynamicField() === 'angle' &&
NUMBER_REGEXP.test(this.text) &&
this.dynamicInputApplies()
) {
// 동적 입력 각도 칸 — 각도 고정 · 길이를 잠갔으면 바로 그 점
setAngleLock(Number.parseFloat(this.text));
this.text = '';
if (lockedLength !== null) this.sendPointEvent(this.distanceEvent(lockedLength));
} 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<a` · `d<a`
this.sendPointEvent(this.pointEventFromText() as PointTextEvent);
this.text = '';
} else if (isSnapName(this.text) && activeToolWantsPoint()) {
// 한 번 스냅 END · MID · … — 다음 한 점만
setSnapOverride(this.text);
this.text = '';
} else if (activeToolTakesText(this.text)) {
// 지금 단계의 선택지(선 C · U · 배열 L/R · 숫자 단계 글)
this.sendText();
} else if (resolveCommandInput(this.text)) {
// 명령 이름 또는 AutoCAD 별칭을 입력했다. 예: L, LINE, REC
const command = resolveCommandInput(this.text);
if (command) {
runCommand(command);
}
this.text = '';
} else {
this.sendText();
}
}
private sendText() {
console.log('TEXT_INPUT: ', { text: this.text, activeTool: getActiveToolActor() });
getActiveToolActor()?.send({
type: ActorEvent.TEXT_INPUT,
value: this.text,
} as TextInputEvent);
/**
* 친 글 제출(Enter · Space · 우클릭 · 명령행) — 해석은 `prompt-input.routeTyped` 한 곳.
* @param _repeatIfIdle 옛 꼴 — 빈 입력 + 쉼이면 늘 마지막 명령 반복(우클릭 포함)
*/
public handleEnterKey(_repeatIfIdle = false) {
const text = this.text;
this.text = '';
routeTyped(text);
}
/** 거리의 방향 = 스냅 · 가이드 · 커서 */
private distanceCursor() {
return (
getSnapPointOnAngleGuide()?.point ||
getSnapPoint()?.point ||
getScreenCanvasDrawController().getWorldMouseLocation()
);
}
private distanceEvent(value: number): PointTextEvent {
return { type: ActorEvent.NUMBER_INPUT, value, worldMouseLocation: this.distanceCursor() };
}
/** 친 글을 점 · 거리 사건으로 */
private pointEventFromText(): PointTextEvent | null {
return parsePointText(this.text, () => this.distanceCursor());
}
/** 동적 입력(길이 · 각도 칸 · Tab) — 기준점이 있는 점 단계에서만 */
private dynamicInputApplies(): boolean {
return activeToolWantsPoint() && !!getAngleGuideOriginPoint();
}
/** 점 하나를 도구에 보냄 — 각도 고정 · 한 번 스냅은 이 한 점으로 끝 */
/** 점 하나를 도구에 보냄(덧물음 먼저) — 각도 고정 · 한 번 스냅은 이 한 점으로 끝 */
private sendPointEvent(event: PointTextEvent | MouseClickEvent) {
getActiveToolActor()?.send(event);
releaseOnePoint();
setSnapOverride(null);
sendPoint(event);
}
public handleUndo(evt: KeyboardEvent) {
evt.preventDefault();
undo();
setGhostHelperEntities([]);
setSelectedEntityIds([]);
getActiveToolActor()?.send({
type: ActorEvent.ESC,
});
undoCommand();
}
public handleRedo(evt: KeyboardEvent) {
evt.preventDefault();
redo();
setGhostHelperEntities([]);
setSelectedEntityIds([]);
getActiveToolActor()?.send({
type: ActorEvent.ESC,
});
redoCommand();
}
}
@@ -2,9 +2,31 @@
* Ctrl 단축키 판정 — 공용 `A00_Common/key_shortcut.ts`(214-2)를 그대로 내보냄.
* 한글 자판은 `key` 가 「ㅋ」·「ㅛ」로 와 글자로는 안 맞아 자판 자리(`code`)로 본다.
*/
import { keyLetter } from '../../../../A00_Common/key_shortcut';
export {
ctrlShortcut,
isCtrlKey,
keyLetter,
type CtrlShortcut,
} from '../../../../A00_Common/key_shortcut';
/** CAD 만의 Ctrl 단축키 → 명령 이름(오토캐드) — Ctrl+V 는 브라우저 `paste` 사건 몫 */
export function cadCtrlCommand(
evt: Pick<KeyboardEvent, 'code' | 'ctrlKey' | 'altKey' | 'shiftKey'> &
Partial<Pick<KeyboardEvent, 'key' | 'metaKey'>>
): string | null {
if (!(evt.ctrlKey || evt.metaKey) || evt.altKey) return null;
switch (keyLetter(evt)) {
case 'c':
return evt.shiftKey ? 'COPYBASE' : 'COPYCLIP';
case 'x':
return evt.shiftKey ? null : 'CUTCLIP';
case 'v':
return evt.shiftKey ? 'PASTEBLOCK' : null;
case '1':
return evt.shiftKey ? null : 'PROPERTIES';
default:
return null;
}
}
@@ -0,0 +1,424 @@
/**
* 친 글 사다리 한 곳(337 설계 2-5 ~ 2-11) — 키보드 · 명령행 · 손가락 단추가 친 글을 지금 물음 꼴로 풂.
* 덧물음 → 빈 Enter → 글 물음 → 투명 `'` → 쉼(명령 이름) → 점 · 옵션 · 숫자 → 거절.
* 점 · 옵션 묻는 중 명령 이름은 거절(오토캐드) · 앞글자 실행 없음 · 대소문자 무관(맞추기는 `prompt.ts` 한 곳).
* 명령 끊기 · 되돌림도 여기 — 끊고(ESC) 뒤 실행(오토캐드 리본 `^C^C`).
*/
import { Point } from '@flatten-js/core';
import { Actor } from 'xstate';
import {
type PromptMeta,
type PromptSpec,
defaultValue,
matchOption,
normalizeKeyword,
renderPrompt,
resolvePrompt,
lastPoint,
} from '../commands/prompt';
import { resolveCommandInput } from '../commands/registry';
import { logLine, repeatLastCommand, runCommand } from '../commands/run-command';
import {
getActiveToolActor,
getAngleGuideOriginPoint,
getScreenCanvasDrawController,
getSnapPoint,
getSnapPointOnAngleGuide,
notifyWindow,
redo,
setActiveToolActor,
setAngleGuideOriginPoint,
setGhostHelperEntities,
setSelectedEntityIds,
setShouldDrawHelpers,
undo,
} from '../state';
import { HtmlEvent } from '../App.types';
import { Tool } from '../tools';
import { SelectState, selectToolStateMachine } from '../tools/select-tool';
import {
ActorEvent,
type MouseClickEvent,
type StepKind,
type TextInputEvent,
} from '../tools/tool.types';
import { getDynamicField, getLockedLength, releaseOnePoint, setAngleLock } from './input-angle-lock';
import {
ANGLE_LOCK_REGEXP,
NUMBER_REGEXP,
parsePointText,
type PointTextEvent,
} from './input-patterns';
import { isSnapName, setSnapOverride } from './input-snap-override';
// ---- 덧물음(설계 2-11) ----
export interface SubPrompt {
prompt: PromptSpec;
kind: StepKind;
onPoint?(p: Point): SubResult;
onNumber?(n: number): SubResult;
onOption?(key: string): SubResult;
onEnter?(): SubResult;
}
/** `{point}` = 닫고 그 점을 원래 물음에 ABSOLUTE_POINT_INPUT 로 */
export type SubResult = 'stay' | 'done' | { point: Point };
const subs: SubPrompt[] = [];
export const pushSubPrompt = (sub: SubPrompt): void => {
subs.push(sub);
notifyWindow(HtmlEvent.UPDATE_STATE);
};
export const subPrompt = (): SubPrompt | null => subs[subs.length - 1] ?? null;
/** 덧물음 모두 닫음(명령 끝 · Esc) */
export const closeSubPrompt = (): void => {
subs.length = 0;
};
function settle(result: SubResult | undefined) {
if (!result || result === 'stay') return;
subs.pop();
if (result !== 'done') sendPoint({ type: ActorEvent.ABSOLUTE_POINT_INPUT, value: result.point });
}
// ---- 알림 줄(설계 2-10) ----
const NOTICE_MS = 3000;
let noticeText: string | null = null;
let noticeAt = 0;
/** 커서 곁 둘째 줄(3 초 또는 다음 키까지) + 기록 줄 · null = 지움 */
export function notice(text: string | null): void {
noticeText = text;
noticeAt = Date.now();
if (text) logLine(text);
}
export const currentNotice = (): string | null =>
noticeText && Date.now() - noticeAt < NOTICE_MS ? noticeText : null;
// ---- 지금 물음 ----
const activeSnapshot = () => getActiveToolActor()?.getSnapshot();
/** 평평한 상태 설정 — 겹 상태는 읽지 않음 */
const flatConfig = () => {
const snapshot = activeSnapshot();
return typeof snapshot?.value === 'string'
? snapshot?.machine?.states?.[snapshot.value]?.config
: undefined;
};
const activeMeta = (): PromptMeta | undefined => {
const metas = Object.values((activeSnapshot()?.getMeta?.() ?? {}) as Record<string, PromptMeta>);
return metas.find((meta) => meta && (meta.kind || meta.prompt || meta.instructions));
};
/** 쉼 = 맨 위 도구가 선택 도구이고 첫 점 대기(상자 그리는 중은 아님) */
export function isIdle(): boolean {
const snapshot = activeSnapshot();
if (!snapshot || snapshot.status !== 'active') return !snapshot;
return (
snapshot.context?.type === Tool.SELECT &&
snapshot.value === SelectState.WAITING_FOR_FIRST_SELECT_POINT
);
}
/** 물음 종류 — meta.kind · 없으면 `on` 으로 짐작 */
function toolKind(): StepKind | null {
const meta = activeMeta();
if (meta?.kind) return meta.kind;
const on = (flatConfig()?.on ?? {}) as Record<string, unknown>;
if (on.ABSOLUTE_POINT_INPUT) return 'point';
if (on.NUMBER_INPUT) return 'number';
if (on.MOUSE_CLICK) return 'entity';
if (Object.keys(on).some((key) => key.startsWith('OPTION.'))) return 'keyword';
return null;
}
export interface CurrentPrompt {
kind: StepKind | 'idle' | null;
spec: PromptSpec | null;
/** 그린 한 줄(새 꼴) 또는 옛 instructions */
line: string | null;
/** 옛 꼴 — 점 물음이 받는 옵션 글자 */
legacyOptions: string[];
}
export function currentPrompt(): CurrentPrompt {
const sub = subPrompt();
if (sub) {
return { kind: sub.kind, spec: sub.prompt, line: renderPrompt(sub.prompt, sub.kind), legacyOptions: [] };
}
const meta = activeMeta();
const spec = resolvePrompt(meta?.prompt, activeSnapshot()?.context);
const kind = isIdle() ? 'idle' : toolKind();
return {
kind,
spec,
line: spec ? renderPrompt(spec, meta?.kind) : (meta?.instructions ?? null),
legacyOptions: meta?.options ?? [],
};
}
// ---- 보내기 ----
const send = (event: { type: string; [key: string]: unknown }) =>
getActiveToolActor()?.send(event as unknown as TextInputEvent);
/** 거리의 방향 = 스냅 · 가이드 · 커서 */
export const distanceCursor = (): Point =>
getSnapPointOnAngleGuide()?.point ||
getSnapPoint()?.point ||
getScreenCanvasDrawController().getWorldMouseLocation();
export const distanceEvent = (value: number): PointTextEvent => ({
type: ActorEvent.NUMBER_INPUT,
value,
worldMouseLocation: distanceCursor(),
});
/** 동적 입력(길이 · 각도 칸 · Tab) — 기준점이 있는 점 물음에서만 */
export const dynamicInputApplies = (): boolean =>
currentPrompt().kind === 'point' && !!getAngleGuideOriginPoint();
/** 점 하나 — 덧물음 먼저(마우스 누름도) · 각도 고정 · 한 번 스냅은 이 한 점으로 끝 */
export function sendPoint(event: PointTextEvent | MouseClickEvent): void {
const sub = subPrompt();
if (sub) {
if (event.type === ActorEvent.NUMBER_INPUT) {
if (sub.onNumber) settle(sub.onNumber(event.value));
else reject(currentPrompt());
} else if (event.type === ActorEvent.MOUSE_CLICK) {
settle(sub.onPoint?.(event.worldMouseLocation));
} else if (event.type === ActorEvent.RELATIVE_POINT_INPUT) {
const base = getAngleGuideOriginPoint() ?? lastPoint();
if (base) settle(sub.onPoint?.(new Point(base.x + event.value.x, base.y + event.value.y)));
else reject(currentPrompt());
} else {
settle(sub.onPoint?.(event.value));
}
} else {
getActiveToolActor()?.send(event);
}
releaseOnePoint();
setSnapOverride(null);
}
function sendOption(key: string) {
const sub = subPrompt();
if (sub) settle(sub.onOption?.(key));
else send({ type: `OPTION.${key}` });
}
function sendEnter() {
const sub = subPrompt();
if (sub) settle(sub.onEnter?.());
else send({ type: ActorEvent.ENTER });
}
// ---- 거절(설계 2-10) ----
const REJECT: Record<string, string> = {
point: '점 또는 옵션 키워드를 요구함.',
pointNumber: '숫자 거리, 두 번째 점 또는 옵션 키워드를 요구함.',
number: '숫자 값을 요구함.',
keyword: '옵션 키워드가 잘못됨.',
selection: '*선택이 잘못됨*',
};
function reject(prompt: CurrentPrompt, text?: string) {
const kind = prompt.kind;
const fallback =
kind === 'point'
? prompt.spec?.number
? REJECT.pointNumber
: REJECT.point
: kind === 'number'
? REJECT.number
: kind === 'selection' || kind === 'entity'
? REJECT.selection
: REJECT.keyword;
notice(text ?? prompt.spec?.reject ?? fallback);
}
/** 숫자 검사 — 맞으면 null · 틀리면 거절 글 */
function numberProblem(value: number, rule: PromptSpec['number']): string | null {
if (!rule) return null;
if (rule.int && !Number.isInteger(value)) return '정수 값을 요구함.';
const low = rule.min ?? Number.NEGATIVE_INFINITY;
const high = rule.max ?? Number.POSITIVE_INFINITY;
if (value < low || value > high) {
return rule.min !== undefined && rule.max !== undefined
? `${rule.min}에서 ${rule.max} 사이의 ${rule.int ? '정수' : '값'}를 요구함.`
: '값이 범위를 벗어남.';
}
if (rule.positive && value <= 0) return '값은 양수이고 0이 아니어야 함.';
return null;
}
// ---- 사다리(설계 2-5) ----
/** 옛 꼴 통과 — 새 물음이 없는 상태가 TEXT_INPUT 을 받고 숫자는 안 받음 */
const legacyTakesText = (): boolean => {
const on = (flatConfig()?.on ?? {}) as Record<string, unknown>;
return !!on.TEXT_INPUT && !on.NUMBER_INPUT;
};
/** ② 빈 Enter · Space · 우클릭 */
function routeEmpty(prompt: CurrentPrompt) {
const lockedLength = getLockedLength();
if (lockedLength !== null && dynamicInputApplies()) {
sendPoint(distanceEvent(lockedLength)); // 길이 잠근 채 Enter — 그 길이
return;
}
const fallback = prompt.spec?.default;
if (fallback?.kind === 'value') {
const value = defaultValue(fallback);
if (typeof value === 'number') {
if (subPrompt()?.onNumber) settle(subPrompt()?.onNumber?.(value));
else sendPoint(distanceEvent(value));
return;
}
if (value) {
sendPoint({ type: ActorEvent.ABSOLUTE_POINT_INPUT, value: new Point(value.x, value.y) });
return;
}
} else if (fallback?.kind === 'option') {
sendOption(fallback.key);
return;
}
if (prompt.kind === 'idle' && repeatLastCommand()) return;
sendEnter();
}
/** ⑧ `'이름` — 즉시형은 지금 도구 둔 채 · 도구형은 거절 */
function routeTransparent(name: string) {
const command = resolveCommandInput(name);
if (!command) {
notice(`알 수 없는 명령 「${normalizeKeyword(name)}」.`);
} else if (command.machine) {
notice(`「${command.id}」 명령은 투명하게 쓸 수 없음.`);
} else {
runCommand(command);
}
}
/** ④ 점 물음 보조 — 동적 각도 칸 · `<각도` · 한 번 스냅. 먹었으면 true */
function routePointAid(text: string): boolean {
if (getDynamicField() === 'angle' && NUMBER_REGEXP.test(text) && dynamicInputApplies()) {
setAngleLock(Number.parseFloat(text));
const lockedLength = getLockedLength();
if (lockedLength !== null) sendPoint(distanceEvent(lockedLength));
return true;
}
const lock = ANGLE_LOCK_REGEXP.exec(text);
if (lock) {
setAngleLock(Number.parseFloat(lock[1]));
return true;
}
const upper = normalizeKeyword(text);
if (isSnapName(upper)) {
setSnapOverride(upper);
return true;
}
return false;
}
/** ④ 좌표 · 거리 */
function routePointText(text: string, prompt: CurrentPrompt) {
const event = parsePointText(text, distanceCursor);
if (!event) return reject(prompt);
const hasBase = !!getAngleGuideOriginPoint() || !!subPrompt();
if (event.type !== ActorEvent.ABSOLUTE_POINT_INPUT && !hasBase) return reject(prompt);
if (event.type === ActorEvent.NUMBER_INPUT) {
const problem = numberProblem(event.value, prompt.spec?.number);
if (problem) return reject(prompt, problem);
}
sendPoint(event);
}
/** ⑥ 숫자 물음 — 글 전체가 수일 때만(`3.2*1.5` · `2m` 거절) */
function routeNumber(text: string, prompt: CurrentPrompt) {
if (!NUMBER_REGEXP.test(text)) return reject(prompt);
const value = Number.parseFloat(text);
const problem = numberProblem(value, prompt.spec?.number);
if (problem) return reject(prompt, problem);
const sub = subPrompt();
if (sub) settle(sub.onNumber?.(value));
else send({ type: ActorEvent.NUMBER_INPUT, value, worldMouseLocation: distanceCursor() });
}
/** 친 글 하나를 지금 물음으로 — 늘 다 먹음(거절이면 알림 줄) */
export function routeTyped(raw: string): void {
const prompt = currentPrompt();
const text = raw.trim();
if (!text) return routeEmpty(prompt);
if (prompt.kind === 'text') {
send({ type: ActorEvent.TEXT_INPUT, value: raw }); // ③ 원문 그대로
return;
}
if (text.startsWith("'")) return routeTransparent(text.slice(1));
if (prompt.kind === 'idle') {
// ⑨ 이름 > 내 별칭 > 기본 별칭 딱 맞음만
const command = resolveCommandInput(text);
if (command) runCommand(command);
else notice(`알 수 없는 명령 「${normalizeKeyword(text)}」.`);
return;
}
if (prompt.kind === 'point' && routePointAid(text)) return;
// ⑤ 옵션(숨김 포함) · 없는 옵션 안내
const hit = matchOption(text, prompt.spec);
if (hit && 'option' in hit) return sendOption(hit.option.key);
if (hit && 'absent' in hit) {
notice(`「${hit.absent.label}(${hit.absent.kw})」 옵션은 이 CAD 에 없음.`);
return;
}
const upper = normalizeKeyword(text);
if (!prompt.spec && prompt.legacyOptions.includes(upper)) {
send({ type: ActorEvent.TEXT_INPUT, value: upper }); // 옛 꼴 통과
return;
}
if (prompt.kind === 'point') return routePointText(text, prompt);
if (prompt.kind === 'number') return routeNumber(text, prompt);
if (!prompt.spec && legacyTakesText()) {
send({ type: ActorEvent.TEXT_INPUT, value: upper }); // 옛 꼴 통과
return;
}
reject(prompt); // ⑦ ⑩
}
// ---- 명령 끊기 · 되돌림(설계 2-8) ----
/** 쉬는 상태로 — 옛 도구가 ESC 뒤 처음 물음으로 돌아가도 한 번에 끝 */
function startIdle() {
setGhostHelperEntities([]);
setAngleGuideOriginPoint(null);
setShouldDrawHelpers(false);
setActiveToolActor(new Actor(selectToolStateMachine));
}
/** 진행 중 명령 끊기 — 쉼이면 아무 일 없음 */
export function cancelActiveCommand(): void {
closeSubPrompt();
releaseOnePoint();
setSnapOverride(null);
if (isIdle()) return;
const actor = getActiveToolActor();
actor?.send({ type: ActorEvent.ESC });
if (getActiveToolActor() === actor && !isIdle()) startIdle();
}
/** 되돌림 — 끊고 뒤 · 고름 풂(Ctrl+Z · ↶ · U) */
export function undoCommand(): void {
cancelActiveCommand();
undo();
setGhostHelperEntities([]);
setSelectedEntityIds([]);
}
export function redoCommand(): void {
cancelActiveCommand();
redo();
setGhostHelperEntities([]);
setSelectedEntityIds([]);
}