feat(B07): 그립으로 고치고, 음수·극좌표를 받고, 편집분을 잃지 않는다

조사표 8~13절 검토에서 "기본 기능"으로 고른 것을 반영한다.

- 좌표 입력: 절대·상대 좌표가 양수만 받아 `@-100,50`을 거부했다. 부호를 허용하고
  극좌표 `@거리<각도`·`거리<각도`를 더했다. `-`·`+`가 확대·축소 단축키로 먼저
  잡혀 음수의 첫 글자를 먹고 있어 그 두 단축키를 뺐다(줌은 휠·뷰 막대·명령).
- 그립 편집: 선택 객체에 그립을 그리고 집어서 옮긴다. 선 끝점·중점, 폴리선 정점,
  사각형 모서리, 원 중심·반지름, 문자·점 기준점. 폴리선은 세그먼트 중점을 끌면
  정점이 늘고 정점 위 Ctrl+클릭이면 준다. 형상 필드가 private이라 공개 생성자로
  다시 만들어 바꿔 끼우고 id·도면층·색·그룹을 물려받는다.
- 자동 백업·복구: 5초 디바운스로 복구 전용 키에 저장하고, 시작할 때 백업이 있으면
  눌러서 되살리는 안내를 띄운다. 저장(QSAVE)에 성공하면 백업을 지운다.
- 선택 순환: 같은 자리를 다시 클릭하면 겹친 후보를 차례로 돌린다.
- 상태막대: `극좌표 추적` 버튼이 `직교`와 같은 onClick이라 같은 일을 하고 있었다.
  각각 45°·90°를 켜고 끄도록 고치고, 스냅 추적 토글과 F3·F7·F8·F10을 붙였다.
- 문자 굵게·기울임을 캔버스·SVG·JSON·스타일 패널에 연결했다.
- 조사표: 이미 되어 있던 5건의 표기를 정정하고, 출력·내보내기(9절)는 결재창 이후
  PDF·DXF·DWG로 반영할 것이라 보류(P)로 구분해 사유를 남겼다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-30 14:43:46 +09:00
co-authored by Claude Opus 5
parent 3fccf8278b
commit e599884888
22 changed files with 779 additions and 149 deletions
@@ -65,6 +65,9 @@ export const HIGHLIGHT_ENTITY_DISTANCE = 15;
* The size of the snap point indicator shapes that are shown on active snap points
*/
export const SNAP_POINT_SIZE = 15;
/** 그립 사각형의 화면 크기(px)와 색 — 선택 객체의 편집점 */
export const GRIP_SIZE = 8;
export const GRIP_COLOR = '#3aa0ff';
/**
* How long you need to hover over a snap point to make it a marked snap point that will show angle guides
@@ -1,11 +1,12 @@
/** 빠른 실행 도구막대 · 출력 탭 명령 (파일 수명주기) */
import { toast } from 'react-toastify';
import type { CadCommand } from './command.types';
import { clearRecovery, restoreRecovery } from '../helpers/autosave';
import { exportEntitiesToJsonFile } from '../helpers/import-export-handlers/export-entities-to-json';
import { exportEntitiesToLocalStorage } from '../helpers/import-export-handlers/export-entities-to-local-storage';
import { exportEntitiesToPngFile } from '../helpers/import-export-handlers/export-entities-to-png';
import { exportEntitiesToSvgFile } from '../helpers/import-export-handlers/export-entities-to-svg';
import { redo, undo } from '../state';
import type { CadCommand } from './command.types';
export const FILE_COMMANDS: CadCommand[] = [
{
@@ -15,10 +16,23 @@ export const FILE_COMMANDS: CadCommand[] = [
glyph: '💾',
hint: '현재 도면을 브라우저에 저장한다',
run: () => {
void exportEntitiesToLocalStorage().then(() => toast.success('도면을 저장했습니다.'));
void exportEntitiesToLocalStorage().then(() => {
clearRecovery();
toast.success('도면을 저장했습니다.');
});
return '도면 저장';
},
},
{
id: 'RECOVER',
label: '백업 복구',
glyph: '⟲',
hint: '자동 백업된 마지막 편집을 되살린다',
run: () => {
void restoreRecovery();
return '백업 복구';
},
},
{
id: 'EXPORT',
label: 'JSON 내보내기',
@@ -1,5 +1,6 @@
/** 리본 안에 들어가는 위젯 패널 — 특성(색·굵기·선종류), 도면층, 문자 스타일 */
import type { FC } from 'react';
import { runCommandInput } from '../commands/run-command';
import type { Entity } from '../entities/Entity';
import { EntityName } from '../entities/Entity';
import type { TextEntity } from '../entities/TextEntity';
@@ -19,7 +20,6 @@ import {
setActiveTextStyle,
setEntities,
} from '../state';
import { runCommandInput } from '../commands/run-command';
export const LINE_TYPES: { value: string; label: string; dash: number[] | undefined }[] = [
{ value: 'solid', label: '실선', dash: undefined },
@@ -178,6 +178,22 @@ export const TextStyleWidget: FC = () => {
}}
/>
</label>
<label className="cad-prop" title="굵게">
<span></span>
<input
type="checkbox"
checked={textStyle.bold}
onChange={(event) => handle({ bold: event.target.checked })}
/>
</label>
<label className="cad-prop" title="기울임">
<span></span>
<input
type="checkbox"
checked={textStyle.italic}
onChange={(event) => handle({ italic: event.target.checked })}
/>
</label>
<label className="cad-prop" title="문자 색상">
<span></span>
<input
@@ -4,9 +4,11 @@ import {
getAngleStep,
getGridEnabled,
getSnapEnabled,
getSnapTrackingEnabled,
setAngleStep,
setGridEnabled,
setSnapEnabled,
setSnapTrackingEnabled,
} from '../state';
interface StatusBarProps {
@@ -18,6 +20,8 @@ export const StatusBar: FC<StatusBarProps> = ({ commandLineVisible, onToggleComm
const snap = getSnapEnabled();
const grid = getGridEnabled();
const ortho = getAngleStep() === 90;
const polar = getAngleStep() === 45;
const snapTracking = getSnapTrackingEnabled();
return (
<footer className="cad-statusbar controls">
@@ -32,19 +36,27 @@ export const StatusBar: FC<StatusBarProps> = ({ commandLineVisible, onToggleComm
<button
type="button"
data-active={ortho}
title="직교 모드 — 켜면 90°, 끄면 45° 간격 각도 가이드"
onClick={() => setAngleStep(ortho ? 45 : 90)}
title="직교 모드 (F8) — 90° 간격 각도 가이드"
onClick={() => setAngleStep(ortho ? 0 : 90)}
>
</button>
<button
type="button"
data-active={!ortho}
title="극좌표 추적 — 45° 간격 각도 가이드"
onClick={() => setAngleStep(ortho ? 45 : 90)}
data-active={polar}
title="극좌표 추적 (F10) — 45° 간격 각도 가이드"
onClick={() => setAngleStep(polar ? 0 : 45)}
>
</button>
<button
type="button"
data-active={snapTracking}
title="객체 스냅 추적 — 스냅점에 잠시 머물면 그 점에서 정렬선이 뻗는다"
onClick={() => setSnapTrackingEnabled(!snapTracking)}
>
</button>
<button
type="button"
data-active={grid}
@@ -58,4 +58,6 @@ export const DEFAULT_TEXT_OPTIONS = {
textColor: '#FFF',
fontSize: CANVAS_INPUT_FIELD_FONT_SIZE,
fontFamily: 'sans-serif',
bold: false,
italic: false,
};
@@ -522,6 +522,8 @@ export class ScreenCanvasDrawController implements DrawController {
textColor: string;
fontSize: number;
fontFamily: string;
bold: boolean;
italic: boolean;
}> = {}
): void {
const screenBasePoint = this.worldToTarget(basePoint);
@@ -547,6 +549,8 @@ export class ScreenCanvasDrawController implements DrawController {
textColor: string;
fontSize: number;
fontFamily: string;
bold: boolean;
italic: boolean;
}> = {}
): void {
const opts = {
@@ -564,7 +568,7 @@ export class ScreenCanvasDrawController implements DrawController {
new Point(opts.textDirection.x, -opts.textDirection.y)
);
this.context.rotate(angle);
this.context.font = `${opts.fontSize}px ${opts.fontFamily}`;
this.context.font = `${opts.italic ? 'italic ' : ''}${opts.bold ? 'bold ' : ''}${opts.fontSize}px ${opts.fontFamily}`;
this.context.textAlign = opts.textAlign;
this.context.fillStyle = paintColor(opts.textColor);
this.context.textBaseline = 'middle';
@@ -239,7 +239,7 @@ export class SvgDrawController implements DrawController {
this.svgStrings.push(
// Use finalTextColor here
`<text x="${canvasBasePoint.x}" y="${canvasBasePoint.y}" fill="${finalTextColor}" font-size="${textOptions.fontSize}" font-family="${textOptions.fontFamily}" ${transformAttribute} ${textAnchorAttribute}>${label}</text>`
`<text x="${canvasBasePoint.x}" y="${canvasBasePoint.y}" fill="${finalTextColor}" font-size="${textOptions.fontSize}" font-family="${textOptions.fontFamily}"${textOptions.bold ? ' font-weight="bold"' : ''}${textOptions.italic ? ' font-style="italic"' : ''} ${transformAttribute} ${textAnchorAttribute}>${label}</text>`
);
}
@@ -14,6 +14,9 @@ export interface TextOptions {
textColor: string;
fontSize: number;
fontFamily: string;
/** 굵게·기울임 (문자 편집기 기본 서식). 밑줄은 캔버스에 없어 넣지 않았다 */
bold?: boolean;
italic?: boolean;
}
export class TextEntity implements Entity {
@@ -176,6 +179,8 @@ export class TextEntity implements Entity {
textColor: this.options.textColor,
fontSize: this.options.fontSize,
fontFamily: this.options.fontFamily,
bold: this.options.bold,
italic: this.options.italic,
},
},
};
@@ -198,6 +203,8 @@ export class TextEntity implements Entity {
textColor: jsonEntity.shapeData.options.textColor,
fontSize: jsonEntity.shapeData.options.fontSize,
fontFamily: jsonEntity.shapeData.options.fontFamily,
bold: jsonEntity.shapeData.options.bold,
italic: jsonEntity.shapeData.options.italic,
}
);
textEntity.id = jsonEntity.id;
@@ -217,5 +224,7 @@ export interface TextJsonData {
textColor: string;
fontSize: number;
fontFamily: string;
bold?: boolean;
italic?: boolean;
};
}
@@ -0,0 +1,83 @@
/**
* 자동 백업·복구 — 탭이 죽어도 마지막 편집을 잃지 않게 한다.
* 작업본(호스트 저장)과는 다른 층이다. 여기 쓰는 것은 복구 전용 사본이고,
* 되살리는 것은 사용자가 안내를 눌렀을 때뿐이다. 자동으로 도면을 갈아끼우지 않는다.
*/
import { toast } from 'react-toastify';
import { HtmlEvent } from '../App.types';
import type { Entity } from '../entities/Entity';
import { getEntities, setActiveLayerId, setEntities, setLayers } from '../state';
import { exportEntitiesAndLayersToJsonString } from './import-export-handlers/export-entities-to-json';
import { getEntitiesAndLayersFromJsonString } from './import-export-handlers/import-entities-from-json';
const RECOVERY_KEY = 'OPEN_WEB_CAD__RECOVERY';
const AUTOSAVE_DEBOUNCE_MS = 5000;
interface RecoveryFile {
savedAt: number;
json: string;
}
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
/** 마지막으로 백업한 객체 배열. setEntities가 매번 새 배열을 만들어 참조로 비교된다 */
let lastBackedUp: Entity[] | null = null;
function readRecovery(): RecoveryFile | null {
try {
const raw = localStorage.getItem(RECOVERY_KEY);
return raw ? (JSON.parse(raw) as RecoveryFile) : null;
} catch {
return null;
}
}
async function writeBackup(): Promise<void> {
const entities = getEntities();
if (entities === lastBackedUp || entities.length === 0) return;
try {
const file: RecoveryFile = {
savedAt: Date.now(),
json: await exportEntitiesAndLayersToJsonString(),
};
localStorage.setItem(RECOVERY_KEY, JSON.stringify(file));
lastBackedUp = entities;
} catch {
// 저장 공간이 없거나 막혀 있으면 조용히 넘어간다 — 편집을 막을 일은 아니다
}
}
export function clearRecovery(): void {
try {
localStorage.removeItem(RECOVERY_KEY);
} catch {
// 지우지 못해도 다음 백업이 덮어쓴다
}
}
export async function restoreRecovery(): Promise<void> {
const file = readRecovery();
if (!file) {
toast.info('복구할 백업이 없습니다.');
return;
}
const drawing = await getEntitiesAndLayersFromJsonString(file.json);
setEntities(drawing.entities, true);
setLayers(drawing.layers);
setActiveLayerId(drawing.layers[0].id);
toast.success(`백업을 되살렸습니다 (${new Date(file.savedAt).toLocaleString()}).`);
}
/** 시작할 때 한 번 부른다. 백업이 있으면 안내만 띄우고, 되살리기는 사용자가 누른다. */
export function registerAutoSave(): void {
window.addEventListener(HtmlEvent.UPDATE_STATE, () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => void writeBackup(), AUTOSAVE_DEBOUNCE_MS);
});
const file = readRecovery();
if (!file) return;
toast.info(
`이전 작업 백업이 있습니다 (${new Date(file.savedAt).toLocaleString()}). 눌러서 되살리기.`,
{ autoClose: false, onClick: () => void restoreRecovery() }
);
}
@@ -5,6 +5,7 @@ import {
getLayerById,
getScreenCanvasDrawController,
getShouldDrawHelpers,
getSnapTrackingEnabled,
setAngleGuideEntities,
setSnapPoint,
setSnapPointOnAngleGuide,
@@ -32,10 +33,13 @@ export function calculateAngleGuidesAndSnapPoints() {
).filter(entity => !getLayerById(entity.layerId)?.isLocked);
const hoveredSnapPoints = getHoveredSnapPoints();
const eligibleHoveredSnapPoints = hoveredSnapPoints.filter(
hoveredSnapPoint =>
hoveredSnapPoint.milliSecondsHovered > HOVERED_SNAP_POINT_TIME,
);
// 객체 스냅 추적(F11)을 끄면 머문 스냅점에서 정렬 가이드를 뻗지 않는다
const eligibleHoveredSnapPoints = getSnapTrackingEnabled()
? hoveredSnapPoints.filter(
hoveredSnapPoint =>
hoveredSnapPoint.milliSecondsHovered > HOVERED_SNAP_POINT_TIME,
)
: [];
const eligibleHoveredPoints = eligibleHoveredSnapPoints.map(
hoveredSnapPoint => hoveredSnapPoint.snapPoint.point,
@@ -1,12 +1,22 @@
import {Point} from '@flatten-js/core';
import {CURSOR_SIZE, GUIDE_LINE_COLOR, GUIDE_LINE_STYLE, GUIDE_LINE_WIDTH, SNAP_POINT_COLOR, SNAP_POINT_SIZE,} from '../App.consts';
import {type SnapPoint, SnapPointType} from '../App.types';
import type {DrawController} from '../drawControllers/DrawController';
import type {ScreenCanvasDrawController} from '../drawControllers/screenCanvas.drawController';
import type {Entity} from '../entities/Entity';
import {getLayerById, isEntityHighlighted, isEntitySelected} from '../state';
import {isEntityHidden} from './visibility';
import {toast} from 'react-toastify';
import { Point } from '@flatten-js/core';
import { toast } from 'react-toastify';
import {
CURSOR_SIZE,
GRIP_COLOR,
GRIP_SIZE,
GUIDE_LINE_COLOR,
GUIDE_LINE_STYLE,
GUIDE_LINE_WIDTH,
SNAP_POINT_COLOR,
SNAP_POINT_SIZE,
} from '../App.consts';
import { type SnapPoint, SnapPointType } from '../App.types';
import type { DrawController } from '../drawControllers/DrawController';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController';
import type { Entity } from '../entities/Entity';
import { getLayerById, isEntityHighlighted, isEntitySelected } from '../state';
import { getGrips } from './grips';
import { isEntityHidden } from './visibility';
export function drawEntities(drawController: DrawController, entities: Entity[]) {
for (const entity of entities) {
@@ -218,3 +228,19 @@ export function drawCursor(drawController: ScreenCanvasDrawController) {
new Point(screenMouseLocation.x + CURSOR_SIZE, screenMouseLocation.y)
);
}
/** 선택한 객체의 그립(편집점)을 화면 크기 고정 사각형으로 그린다 */
export function drawGrips(drawController: ScreenCanvasDrawController, entities: Entity[]) {
for (const entity of entities) {
for (const grip of getGrips(entity)) {
const screenPoint = drawController.worldToTarget(grip.point);
drawController.fillRectScreen(
screenPoint.x - GRIP_SIZE / 2,
screenPoint.y - GRIP_SIZE / 2,
GRIP_SIZE,
GRIP_SIZE,
GRIP_COLOR
);
}
}
}
+53 -50
View File
@@ -1,27 +1,29 @@
import { compact } from 'es-toolkit';
import { HOVERED_SNAP_POINT_TIME } from '../App.consts';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController';
import {
drawCursor,
drawDebugEntities,
drawEntities,
drawHelpers,
drawSnapPoint,
getAngleGuideEntities,
getDebugEntities,
getEntities,
getGhostHelperEntities,
getHighlightedEntityIds,
getHoveredSnapPoints,
getInputController,
getSelectedEntities,
getShouldDrawCursor,
getSnapPoint,
getSnapPointOnAngleGuide,
} from '../state';
import {
drawCursor,
drawDebugEntities,
drawEntities,
drawGrips,
drawHelpers,
drawSnapPoint,
} from './draw-functions';
import { getClosestSnapPoint } from './get-closest-snap-point';
import { isPointEqual } from './is-point-equal';
import { HOVERED_SNAP_POINT_TIME } from '../App.consts';
import { compact } from 'es-toolkit';
import {
getAngleGuideEntities,
getDebugEntities,
getEntities,
getGhostHelperEntities,
getHighlightedEntityIds,
getHoveredSnapPoints,
getInputController,
getShouldDrawCursor,
getSnapPoint,
getSnapPointOnAngleGuide,
} from '../state';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController';
import { drawScene } from './scene-cache';
/**
@@ -29,41 +31,42 @@ import { drawScene } from './scene-cache';
* mouse move) — re-draw the few highlighted entities on top of the blit.
*/
function drawHighlightedEntities(drawController: ScreenCanvasDrawController) {
const highlightedIds = getHighlightedEntityIds();
if (!highlightedIds.length) return;
const idSet = new Set(highlightedIds);
drawEntities(
drawController,
getEntities().filter(entity => idSet.has(entity.id)),
);
const highlightedIds = getHighlightedEntityIds();
if (!highlightedIds.length) return;
const idSet = new Set(highlightedIds);
drawEntities(
drawController,
getEntities().filter((entity) => idSet.has(entity.id))
);
}
export function draw(drawController: ScreenCanvasDrawController) {
drawController.clear();
drawController.clear();
// Static scene (all entities): cached bitmap blit, rebuilt only when needed.
drawScene(drawController, performance.now());
drawHighlightedEntities(drawController);
// Static scene (all entities): cached bitmap blit, rebuilt only when needed.
drawScene(drawController, performance.now());
drawHighlightedEntities(drawController);
drawHelpers(drawController, getAngleGuideEntities());
drawEntities(drawController, getGhostHelperEntities());
drawDebugEntities(drawController, getDebugEntities());
drawGrips(drawController, getSelectedEntities());
drawHelpers(drawController, getAngleGuideEntities());
drawEntities(drawController, getGhostHelperEntities());
drawDebugEntities(drawController, getDebugEntities());
const { snapPoint: closestSnapPoint } = getClosestSnapPoint(
compact([getSnapPoint(), getSnapPointOnAngleGuide()]),
drawController.getWorldMouseLocation(),
);
const isMarked =
!!closestSnapPoint &&
getHoveredSnapPoints().some(
hoveredSnapPoint =>
hoveredSnapPoint.milliSecondsHovered > HOVERED_SNAP_POINT_TIME &&
isPointEqual(hoveredSnapPoint.snapPoint.point, closestSnapPoint.point),
);
drawSnapPoint(drawController, closestSnapPoint, isMarked);
const { snapPoint: closestSnapPoint } = getClosestSnapPoint(
compact([getSnapPoint(), getSnapPointOnAngleGuide()]),
drawController.getWorldMouseLocation()
);
const isMarked =
!!closestSnapPoint &&
getHoveredSnapPoints().some(
(hoveredSnapPoint) =>
hoveredSnapPoint.milliSecondsHovered > HOVERED_SNAP_POINT_TIME &&
isPointEqual(hoveredSnapPoint.snapPoint.point, closestSnapPoint.point)
);
drawSnapPoint(drawController, closestSnapPoint, isMarked);
if (getShouldDrawCursor()) {
drawCursor(drawController);
getInputController().draw(drawController);
}
if (getShouldDrawCursor()) {
drawCursor(drawController);
getInputController().draw(drawController);
}
}
@@ -1,5 +1,5 @@
import type {Point, Segment} from '@flatten-js/core';
import type {Entity} from '../entities/Entity';
import type { Point, Segment } from '@flatten-js/core';
import type { Entity } from '../entities/Entity';
export function findClosestEntity<EntityType = Entity>(
worldPoint: Point,
@@ -22,3 +22,20 @@ export function findClosestEntity<EntityType = Entity>(
entity: closestEntity as EntityType,
};
}
/** 클릭 지점에서 maxDistance 안에 있는 객체를 가까운 순으로 (선택 순환에 쓴다) */
export function findEntitiesWithinDistance(
worldPoint: Point,
entities: Entity[],
maxDistance: number
): Entity[] {
const candidates: { entity: Entity; distance: number }[] = [];
for (const entity of entities) {
const distanceInfo = entity.distanceTo(worldPoint);
if (!distanceInfo) continue;
if (distanceInfo[0] < maxDistance) {
candidates.push({ entity, distance: distanceInfo[0] });
}
}
return candidates.sort((a, b) => a.distance - b.distance).map((candidate) => candidate.entity);
}
@@ -33,8 +33,8 @@ export function getDrawHelpers(
const nearestAngleSnapPoints: SnapPoint[] = [];
const angleGuides: LineEntity[] = [];
// draw angle guide
for (const anglePoint of anglePoints) {
// draw angle guide — angleStep 0은 직교·극좌표 추적을 모두 끈 상태다
for (const anglePoint of angleStep > 0 ? anglePoints : []) {
const angleGuideLines = getAngleGuideLines(anglePoint, angleStep);
const closestLineInfo = findClosestEntity<LineEntity>(worldMouseLocation, angleGuideLines);
@@ -0,0 +1,199 @@
/**
* 그립 — 선택한 객체에 붙는 편집점. 집어서 다음 클릭 위치로 옮긴다.
* 형상 필드가 전부 private이라 좌표를 고칠 때는 공개 생성자로 같은 객체를 다시 만들어
* 배열에서 바꿔 끼운다(id는 그대로 둬서 선택·그룹이 유지된다).
* ponytail: 호·해치·이미지·치수는 그립을 만들지 않는다 — 각각 각도·경계·비율·연관 규칙이
* 따로 있어 점 하나를 옮기는 것으로 정의되지 않는다. 필요해지면 그때 붙인다.
*/
import { type Circle, Point, type Polygon, type Segment } from '@flatten-js/core';
import { CircleEntity } from '../entities/CircleEntity';
import type { Entity } from '../entities/Entity';
import { LineEntity } from '../entities/LineEntity';
import { PointEntity } from '../entities/PointEntity';
import { PolyLineEntity } from '../entities/PolyLineEntity';
import { RectangleEntity } from '../entities/RectangleEntity';
import { TextEntity } from '../entities/TextEntity';
/** 두 점의 가운데 */
function midpoint(a: Point, b: Point): Point {
return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
export type GripKind = 'vertex' | 'midpoint' | 'center' | 'radius' | 'base';
export interface Grip {
point: Point;
kind: GripKind;
/** 같은 종류 안에서의 순번 (정점 번호, 세그먼트 번호) */
index: number;
}
/** 새로 만든 객체가 원본의 정체성과 표시 특성을 그대로 물려받게 한다 */
function inherit<T extends Entity>(source: Entity, target: T): T {
target.id = source.id;
target.layerId = source.layerId;
target.lineColor = source.lineColor;
target.lineWidth = source.lineWidth;
target.lineDash = source.lineDash;
target.opacity = source.opacity;
target.groupId = source.groupId;
return target;
}
/** 선으로만 이뤄진 폴리선의 정점 목록. 호가 섞여 있으면 null */
function polylineVertices(entity: PolyLineEntity): Point[] | null {
const children = entity.getEntities();
if (!children.length) return null;
const vertices: Point[] = [];
for (const child of children) {
if (!(child instanceof LineEntity)) return null;
const segment = child.getShape() as Segment;
if (!vertices.length) vertices.push(segment.start);
vertices.push(segment.end);
}
return vertices;
}
function polylineFromVertices(source: Entity, vertices: Point[]): PolyLineEntity | null {
if (vertices.length < 2) return null;
const segments: LineEntity[] = [];
for (let index = 0; index < vertices.length - 1; index += 1) {
const line = new LineEntity(source.layerId, vertices[index], vertices[index + 1]);
line.lineColor = source.lineColor;
line.lineWidth = source.lineWidth;
line.lineDash = source.lineDash;
segments.push(line);
}
return inherit(source, new PolyLineEntity(source.layerId, segments));
}
export function getGrips(entity: Entity): Grip[] {
if (entity instanceof LineEntity) {
const segment = entity.getShape() as Segment;
return [
{ point: segment.start, kind: 'vertex', index: 0 },
{ point: segment.end, kind: 'vertex', index: 1 },
{ point: midpoint(segment.start, segment.end), kind: 'midpoint', index: 0 },
];
}
if (entity instanceof RectangleEntity) {
const polygon = entity.getShape() as Polygon;
return polygon.vertices.map((vertex, index) => ({
point: vertex,
kind: 'vertex' as GripKind,
index,
}));
}
if (entity instanceof CircleEntity) {
const circle = entity.getShape() as Circle;
const { center, r } = circle;
return [
{ point: center, kind: 'center', index: 0 },
{ point: new Point(center.x + r, center.y), kind: 'radius', index: 0 },
{ point: new Point(center.x - r, center.y), kind: 'radius', index: 1 },
{ point: new Point(center.x, center.y + r), kind: 'radius', index: 2 },
{ point: new Point(center.x, center.y - r), kind: 'radius', index: 3 },
];
}
if (entity instanceof PolyLineEntity) {
const vertices = polylineVertices(entity);
if (!vertices) return [];
const grips: Grip[] = vertices.map((point, index) => ({ point, kind: 'vertex', index }));
for (let index = 0; index < vertices.length - 1; index += 1) {
grips.push({
point: midpoint(vertices[index], vertices[index + 1]),
kind: 'midpoint',
index,
});
}
return grips;
}
if (entity instanceof TextEntity || entity instanceof PointEntity) {
const point = entity.getFirstPoint();
return point ? [{ point, kind: 'base', index: 0 }] : [];
}
return [];
}
/** 그립을 target 위치로 옮긴 결과 객체. 원본은 건드리지 않는다 */
export function applyGrip(entity: Entity, grip: Grip, target: Point): Entity | null {
if (entity instanceof LineEntity) {
const segment = entity.getShape() as Segment;
if (grip.kind === 'midpoint') {
const center = midpoint(segment.start, segment.end);
return moveCopy(entity, target.x - center.x, target.y - center.y);
}
const start = grip.index === 0 ? target : segment.start;
const end = grip.index === 1 ? target : segment.end;
return inherit(entity, new LineEntity(entity.layerId, start, end));
}
if (entity instanceof RectangleEntity) {
const polygon = entity.getShape() as Polygon;
const vertices = polygon.vertices;
// 끈 모서리와 마주 보는 모서리로 새 사각형을 만든다 — 직사각형을 유지한다
const opposite = vertices[(grip.index + 2) % vertices.length];
return inherit(entity, new RectangleEntity(entity.layerId, target, opposite));
}
if (entity instanceof CircleEntity) {
const circle = entity.getShape() as Circle;
if (grip.kind === 'center') {
return moveCopy(entity, target.x - circle.center.x, target.y - circle.center.y);
}
const radius = circle.center.distanceTo(target)[0];
if (radius <= 0) return null;
return inherit(entity, new CircleEntity(entity.layerId, circle.center.clone(), radius));
}
if (entity instanceof PolyLineEntity) {
const vertices = polylineVertices(entity);
if (!vertices) return null;
if (grip.kind === 'midpoint') {
// 세그먼트 중점을 끌면 그 자리에 정점이 하나 생긴다 (다기능 그립)
const inserted = [...vertices];
inserted.splice(grip.index + 1, 0, target);
return polylineFromVertices(entity, inserted);
}
const moved = vertices.map((vertex, index) => (index === grip.index ? target : vertex));
return polylineFromVertices(entity, moved);
}
if (entity instanceof TextEntity || entity instanceof PointEntity) {
const base = entity.getFirstPoint();
if (!base) return null;
return moveCopy(entity, target.x - base.x, target.y - base.y);
}
return null;
}
/** 폴리선 정점 하나를 없앤다 (다기능 그립의 Ctrl+클릭) */
export function removePolylineVertex(entity: Entity, grip: Grip): Entity | null {
if (!(entity instanceof PolyLineEntity) || grip.kind !== 'vertex') return null;
const vertices = polylineVertices(entity);
if (!vertices || vertices.length <= 2) return null;
return polylineFromVertices(
entity,
vertices.filter((_, index) => index !== grip.index)
);
}
function moveCopy(entity: Entity, dx: number, dy: number): Entity {
const copy = inherit(entity, entity.clone());
copy.move(dx, dy);
return copy;
}
/** 클릭 지점에 가장 가까운 그립 (maxDistance는 월드 거리) */
export function findGripAt(
entities: Entity[],
worldPoint: Point,
maxDistance: number
): { entity: Entity; grip: Grip } | null {
let best: { entity: Entity; grip: Grip; distance: number } | null = null;
for (const entity of entities) {
for (const grip of getGrips(entity)) {
const distance = grip.point.distanceTo(worldPoint)[0];
if (distance < maxDistance && (!best || distance < best.distance)) {
best = { entity, grip, distance };
}
}
}
return best ? { entity: best.entity, grip: best.grip } : null;
}
@@ -15,35 +15,40 @@ import {
WHEEL_ZOOM_EXPONENT,
} from '../App.consts.ts';
import { MouseButton } from '../App.types.ts';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController.ts';
import { calculateAngleGuidesAndSnapPoints } from '../helpers/calculate-angle-guides-and-snap-points.ts';
import { findClosestEntity } from '../helpers/find-closest-entity.ts';
import { getClosestSnapPointWithinRadius } from '../helpers/get-closest-snap-point.ts';
import {
getActiveToolActor,
getCanvas,
getEntities,
getLastStateInstructions,
getPanStartLocation,
getSnapEnabled,
getScreenCanvasDrawController,
getSelectedEntities,
getSnapPoint,
getSnapPointOnAngleGuide,
redo,
setGhostHelperEntities,
setHighlightedEntityIds,
setPanStartLocation,
setSelectedEntityIds,
setShouldDrawCursor,
undo,
} from '../state.ts';
import {
describeCommand,
matchCommandPrefixes,
resolveCommandInput,
} from '../commands/registry.ts';
import { runCommand } from '../commands/run-command.ts';
import type { ScreenCanvasDrawController } from '../drawControllers/screenCanvas.drawController.ts';
import { calculateAngleGuidesAndSnapPoints } from '../helpers/calculate-angle-guides-and-snap-points.ts';
import { findClosestEntity } from '../helpers/find-closest-entity.ts';
import { getClosestSnapPointWithinRadius } from '../helpers/get-closest-snap-point.ts';
import {
getActiveToolActor,
getAngleStep,
getCanvas,
getEntities,
getGridEnabled,
getLastStateInstructions,
getPanStartLocation,
getScreenCanvasDrawController,
getSelectedEntities,
getSnapEnabled,
getSnapPoint,
getSnapPointOnAngleGuide,
redo,
setAngleStep,
setGhostHelperEntities,
setGridEnabled,
setHighlightedEntityIds,
setPanStartLocation,
setSelectedEntityIds,
setShouldDrawCursor,
setSnapEnabled,
undo,
} from '../state.ts';
import { Tool } from '../tools.ts';
import {
type AbsolutePointInputEvent,
@@ -55,8 +60,19 @@ import {
} from '../tools/tool.types.ts';
const NUMBER_REGEXP = /^[0-9]+([.][0-9]+)?$/;
const ABSOLUTE_POINT_REGEXP = /^([0-9]+([.][0-9]+)?)\s*,\s*([0-9]+([.][0-9]+)?)$/;
const RELATIVE_POINT_REGEXP = /^@([0-9]+([.][0-9]+)?)\s*,\s*([0-9]+([.][0-9]+)?)$/;
/** 부호 있는 실수 한 개 (좌표는 음수가 될 수 있다) */
const SIGNED = '(-?[0-9]+(?:[.][0-9]+)?)';
const ABSOLUTE_POINT_REGEXP = new RegExp(`^${SIGNED}[ ]*,[ ]*${SIGNED}$`);
const RELATIVE_POINT_REGEXP = new RegExp(`^@${SIGNED}[ ]*,[ ]*${SIGNED}$`);
/** 극좌표 — 거리<각도(도). `@`가 붙으면 직전 점 기준 */
const ABSOLUTE_POLAR_REGEXP = new RegExp(`^${SIGNED}[ ]*<[ ]*${SIGNED}$`);
const RELATIVE_POLAR_REGEXP = new RegExp(`^@${SIGNED}[ ]*<[ ]*${SIGNED}$`);
/** 거리·각도(도)를 x·y 변위로 바꾼다 */
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 class InputController {
private text = '';
@@ -320,6 +336,29 @@ export class InputController {
}
if (evt.key === 'F11') {
// F11 => toggle fullscreen
// ponytail: AutoCAD는 F11이 객체 스냅 추적이지만 브라우저 전체화면이 우선이다.
// 스냅 추적은 상태막대 버튼으로 켜고 끈다.
return;
}
// 제도 보조 토글 (AutoCAD 상태막대 기능키)
if (evt.key === 'F3') {
evt.preventDefault();
setSnapEnabled(!getSnapEnabled());
return;
}
if (evt.key === 'F7') {
evt.preventDefault();
setGridEnabled(!getGridEnabled());
return;
}
if (evt.key === 'F8') {
evt.preventDefault();
setAngleStep(getAngleStep() === 90 ? 0 : 90);
return;
}
if (evt.key === 'F10') {
evt.preventDefault();
setAngleStep(getAngleStep() === 45 ? 0 : 45);
return;
}
if (evt.key === 'Tab') {
@@ -370,19 +409,9 @@ export class InputController {
} else if (evt.key === 'ArrowRight') {
// Move the screen right
getScreenCanvasDrawController().setScreenOffset(this.getScreenPanStep('right', evt.shiftKey));
} else if (evt.key === '+') {
// Zoom in
// TODO keep the center of the screen centered during zoom
getScreenCanvasDrawController().setScreenScale(
getScreenCanvasDrawController().getScreenScale() * 1.1
);
} else if (evt.key === '-') {
// Zoom in
// TODO keep the center of the screen centered during zoom
getScreenCanvasDrawController().setScreenScale(
getScreenCanvasDrawController().getScreenScale() * 0.9
);
} else if (evt.key?.length === 1) {
// +·-는 확대·축소 단축키로 쓰지 않는다 — 음수 좌표(-100,-50)의 첫 글자를
// 먹어 버렸다. 줌은 휠·뷰 막대·ZOOMIN/ZOOMOUT 명령으로 한다.
// User entered a single character => add to input field text
this.text += evt.key.toUpperCase();
}
@@ -472,7 +501,7 @@ export class InputController {
return;
}
const x = Number.parseFloat(match[1]);
const y = Number.parseFloat(match[3]);
const y = Number.parseFloat(match[2]);
getActiveToolActor()?.send({
type: ActorEvent.ABSOLUTE_POINT_INPUT,
value: new Point(x, y),
@@ -489,12 +518,34 @@ export class InputController {
return;
}
const x = Number.parseFloat(match[1]);
const y = Number.parseFloat(match[3]);
const y = Number.parseFloat(match[2]);
getActiveToolActor()?.send({
type: ActorEvent.RELATIVE_POINT_INPUT,
value: new Point(x, y),
} as RelativePointInputEvent);
this.text = '';
} else if (RELATIVE_POLAR_REGEXP.test(this.text)) {
// 직전 점에서 거리·각도로 이동. 예: @100<45
const match = RELATIVE_POLAR_REGEXP.exec(this.text);
if (!match) {
return;
}
getActiveToolActor()?.send({
type: ActorEvent.RELATIVE_POINT_INPUT,
value: polarToPoint(Number.parseFloat(match[1]), Number.parseFloat(match[2])),
} as RelativePointInputEvent);
this.text = '';
} else if (ABSOLUTE_POLAR_REGEXP.test(this.text)) {
// 원점에서 거리·각도로 지정한 점. 예: 100<45
const match = ABSOLUTE_POLAR_REGEXP.exec(this.text);
if (!match) {
return;
}
getActiveToolActor()?.send({
type: ActorEvent.ABSOLUTE_POINT_INPUT,
value: polarToPoint(Number.parseFloat(match[1]), Number.parseFloat(match[2])),
} as AbsolutePointInputEvent);
this.text = '';
} else {
console.log('TEXT_INPUT: ', {
text: this.text,
+5 -3
View File
@@ -4,13 +4,15 @@ import ReactDOM from 'react-dom/client';
import { Actor, type MachineSnapshot } from 'xstate';
import { HIGHLIGHT_ENTITY_DISTANCE, SNAP_POINT_DISTANCE } from './App.consts';
import App from './App.tsx';
import { TOOL_STATE_MACHINES } from './commands/registry';
import { ScreenCanvasDrawController } from './drawControllers/screenCanvas.drawController';
import { registerAutoSave } from './helpers/autosave.ts';
import { registerCadDebugHook } from './helpers/debug-hook.ts';
import { draw } from './helpers/draw';
import { findClosestEntity } from './helpers/find-closest-entity';
import { getNewLayer } from './helpers/get-new-layer.ts';
import { scenePerf } from './helpers/scene-cache';
import { queryEntitiesNearPoint } from './helpers/spatial-index';
import { registerCadDebugHook } from './helpers/debug-hook.ts';
import { getNewLayer } from './helpers/get-new-layer.ts';
import { trackHoveredSnapPoint } from './helpers/track-hovered-snap-points';
import { InputController } from './inputController/input-controller.ts';
import { registerAisloDrawingBridge } from './integration/aislo-drawing-bridge.ts';
@@ -34,7 +36,6 @@ import {
} from './state';
import { syncThemeFromHost } from './theme.ts';
import { Tool } from './tools';
import { TOOL_STATE_MACHINES } from './commands/registry';
import { ActorEvent, type DrawEvent } from './tools/tool.types';
// 호스트 앱의 화이트/블랙 모드를 먼저 붙인 뒤 렌더한다.
@@ -155,6 +156,7 @@ function initApplication() {
setActiveLayerId(layers[0].id);
registerAisloDrawingBridge();
registerCadDebugHook();
registerAutoSave();
const screenCanvasDrawController = new ScreenCanvasDrawController(context);
setScreenCanvasDrawController(screenCanvasDrawController);
+13 -1
View File
@@ -13,7 +13,7 @@ import {
import type { ScreenCanvasDrawController } from './drawControllers/screenCanvas.drawController';
import type { Entity } from './entities/Entity';
import { bumpSceneVersion } from './helpers/scene-version';
import { createStack, StateVariable, type UndoState } from './helpers/undo-stack';
import { StateVariable, type UndoState, createStack } from './helpers/undo-stack';
import type { InputController } from './inputController/input-controller.ts'; // state variables
// state variables
@@ -146,6 +146,8 @@ let activeTextStyle = {
fontFamily: 'Noto Sans KR',
fontSize: 16,
textColor: '#ffffff',
bold: false,
italic: false,
};
/**
@@ -173,6 +175,8 @@ let layersById: Map<string, Layer> = new Map(layers.map((layer) => [layer.id, la
let snapEnabled = true;
let gridEnabled = false;
/** 객체 스냅 추적 — 스냅점에 머물면 그 점에서 정렬 가이드를 뻗는다 (AutoCAD F11) */
let snapTrackingEnabled = true;
/**
* 부모(B08 페이지)에서 넘어온 설계 컨텍스트. 수량 산출 패널이 이 값을 읽어
@@ -233,6 +237,7 @@ export const getActiveLayerId = (): string => {
};
export const getSnapEnabled = () => snapEnabled;
export const getGridEnabled = () => gridEnabled;
export const getSnapTrackingEnabled = () => snapTrackingEnabled;
export const getDesignMeta = (): DesignMeta | null => designMeta;
// setters
@@ -413,6 +418,13 @@ export const setSnapEnabled = (enabled: boolean) => {
}
window.dispatchEvent(new CustomEvent(HtmlEvent.UPDATE_STATE));
};
export const setSnapTrackingEnabled = (enabled: boolean) => {
snapTrackingEnabled = enabled;
if (!enabled) {
setHoveredSnapPoints([]);
}
window.dispatchEvent(new CustomEvent(HtmlEvent.UPDATE_STATE));
};
export const setGridEnabled = (enabled: boolean) => {
gridEnabled = enabled;
bumpSceneVersion();
+1
View File
@@ -9,6 +9,7 @@ export enum Tool {
ERASER = 'ERASER',
IMAGE_IMPORT = 'IMAGE_IMPORT',
INSERT_BLOCK = 'INSERT_BLOCK',
GRIP_EDIT = 'GRIP_EDIT',
ROTATE = 'ROTATE',
ALIGN_LEFT = 'ALIGN_LEFT',
ALIGN_RIGHT = 'ALIGN_RIGHT',
@@ -0,0 +1,115 @@
/**
* 그립 편집 도구 — 선택 도구에서 그립을 집으면 켜진다.
* 클릭 한 번으로 그 그립을 옮긴다 (AutoCAD처럼 끌지 않고 집어서 놓는 방식).
*/
import type { Point } from '@flatten-js/core';
import { Actor, assign, createMachine } from 'xstate';
import type { Entity } from '../entities/Entity';
import { getPointFromEvent } from '../helpers/get-point-from-event';
import { type Grip, applyGrip } from '../helpers/grips';
import {
getEntities,
setActiveToolActor,
setAngleGuideOriginPoint,
setEntities,
setGhostHelperEntities,
setShouldDrawHelpers,
} from '../state';
import { Tool } from '../tools';
import { selectToolStateMachine } from './select-tool';
import { ActorEvent, type PointInputEvent, type StateEvent, type ToolContext } from './tool.types';
let editedEntity: Entity | null = null;
let editedGrip: Grip | null = null;
/** 선택 도구가 그립을 집었을 때 부른다 */
export function startGripEdit(entity: Entity, grip: Grip): void {
editedEntity = entity;
editedGrip = grip;
setActiveToolActor(new Actor(gripEditToolStateMachine));
}
/** 편집 중인 객체 — 그립을 그릴 때 원본 대신 미리보기를 보여주려고 읽는다 */
export const getGripEditTargetId = (): string | null => editedEntity?.id ?? null;
function previewAt(point: Point): Entity | null {
if (!editedEntity || !editedGrip) return null;
return applyGrip(editedEntity, editedGrip, point);
}
export enum GripEditState {
INIT = 'INIT',
WAITING_FOR_TARGET_POINT = 'WAITING_FOR_TARGET_POINT',
}
export enum GripEditAction {
INIT_GRIP_EDIT_TOOL = 'INIT_GRIP_EDIT_TOOL',
DRAW_TEMP_GRIP_EDIT = 'DRAW_TEMP_GRIP_EDIT',
APPLY_GRIP_EDIT = 'APPLY_GRIP_EDIT',
SWITCH_TO_SELECT_TOOL = 'SWITCH_TO_SELECT_TOOL',
}
export const gripEditToolStateMachine = createMachine(
{
types: {} as { context: ToolContext; events: StateEvent },
context: { type: Tool.GRIP_EDIT },
initial: GripEditState.INIT,
states: {
[GripEditState.INIT]: {
always: {
actions: GripEditAction.INIT_GRIP_EDIT_TOOL,
target: GripEditState.WAITING_FOR_TARGET_POINT,
},
},
[GripEditState.WAITING_FOR_TARGET_POINT]: {
description: '그립을 옮길 위치를 지정한다',
meta: { instructions: '그립을 옮길 위치를 지정하십시오' },
on: {
[ActorEvent.DRAW]: { actions: GripEditAction.DRAW_TEMP_GRIP_EDIT },
[ActorEvent.MOUSE_CLICK]: {
actions: [GripEditAction.APPLY_GRIP_EDIT, GripEditAction.SWITCH_TO_SELECT_TOOL],
},
[ActorEvent.ABSOLUTE_POINT_INPUT]: {
actions: [GripEditAction.APPLY_GRIP_EDIT, GripEditAction.SWITCH_TO_SELECT_TOOL],
},
[ActorEvent.RELATIVE_POINT_INPUT]: {
actions: [GripEditAction.APPLY_GRIP_EDIT, GripEditAction.SWITCH_TO_SELECT_TOOL],
},
[ActorEvent.ESC]: { actions: GripEditAction.SWITCH_TO_SELECT_TOOL },
},
},
},
},
{
actions: {
[GripEditAction.INIT_GRIP_EDIT_TOOL]: assign(() => {
setShouldDrawHelpers(true);
setGhostHelperEntities([]);
setAngleGuideOriginPoint(editedGrip?.point ?? null);
return {};
}),
[GripEditAction.DRAW_TEMP_GRIP_EDIT]: ({ event }) => {
const point = getPointFromEvent(editedGrip?.point ?? null, event as PointInputEvent);
const preview = previewAt(point);
setGhostHelperEntities(preview ? [preview] : []);
},
[GripEditAction.APPLY_GRIP_EDIT]: ({ event }) => {
const point = getPointFromEvent(editedGrip?.point ?? null, event as PointInputEvent);
const edited = previewAt(point);
if (!edited || !editedEntity) return;
const targetId = editedEntity.id;
setEntities(
getEntities().map((entity) => (entity.id === targetId ? edited : entity)),
true
);
},
[GripEditAction.SWITCH_TO_SELECT_TOOL]: () => {
editedEntity = null;
editedGrip = null;
setGhostHelperEntities([]);
setAngleGuideOriginPoint(null);
setActiveToolActor(new Actor(selectToolStateMachine));
},
},
}
);
@@ -1,5 +1,6 @@
import type {Box, Point, Polygon} from '@flatten-js/core';
import {compact} from 'es-toolkit';
import type { Box, Point, Polygon } from '@flatten-js/core';
import { compact } from 'es-toolkit';
import { toast } from 'react-toastify';
import {
EPSILON,
HIGHLIGHT_ENTITY_DISTANCE,
@@ -8,32 +9,81 @@ import {
SELECTION_RECTANGLE_STYLE,
SELECTION_RECTANGLE_WIDTH,
} from '../App.consts';
import {RectangleEntity} from '../entities/RectangleEntity';
import {toast} from 'react-toastify';
import {findClosestEntity} from '../helpers/find-closest-entity';
import type { Entity } from '../entities/Entity';
import { RectangleEntity } from '../entities/RectangleEntity';
import { pointDistance } from '../helpers/distance-between-points';
import { expandSelectionWithGroups } from '../helpers/entity-groups';
import { findEntitiesWithinDistance } from '../helpers/find-closest-entity';
import { findGripAt, removePolylineVertex } from '../helpers/grips';
import {
getActiveLayerId,
getEntities,
getLayers,
getSelectedEntities,
getSelectedEntityIds,
isEntitySelected,
setEntities,
setGhostHelperEntities,
setSelectedEntityIds,
} from '../state';
import type {SelectContext} from './select-tool';
import type {MouseClickEvent} from './tool.types';
import {expandSelectionWithGroups} from '../helpers/entity-groups';
import { startGripEdit } from './grip-edit-tool';
import type { SelectContext } from './select-tool';
import type { MouseClickEvent } from './tool.types';
/** 선택 순환 — 같은 자리를 다시 클릭하면 겹친 후보를 차례로 돌린다 */
let lastPickPoint: Point | null = null;
let pickCycleIndex = 0;
function pickEntityAt(worldPoint: Point): Entity | null {
const candidates = findEntitiesWithinDistance(
worldPoint,
getEntities(),
HIGHLIGHT_ENTITY_DISTANCE
);
if (!candidates.length) {
lastPickPoint = null;
return null;
}
const samePlace =
!!lastPickPoint && pointDistance(lastPickPoint, worldPoint) < HIGHLIGHT_ENTITY_DISTANCE;
pickCycleIndex = samePlace ? (pickCycleIndex + 1) % candidates.length : 0;
lastPickPoint = worldPoint;
return candidates[pickCycleIndex];
}
export function handleFirstSelectionPoint(
context: SelectContext,
event: MouseClickEvent
): SelectContext {
const closestEntityInfo = findClosestEntity(event.worldMouseLocation, getEntities());
// 선택된 객체의 그립이 먼저다 — 집으면 그립 편집으로 넘어간다
const gripHit = findGripAt(
getSelectedEntities(),
event.worldMouseLocation,
HIGHLIGHT_ENTITY_DISTANCE
);
if (gripHit) {
if (event.holdingCtrl) {
// Ctrl+클릭 => 폴리선 정점 제거 (다기능 그립)
const trimmed = removePolylineVertex(gripHit.entity, gripHit.grip);
if (trimmed) {
setEntities(
getEntities().map((entity) => (entity.id === trimmed.id ? trimmed : entity)),
true
);
return { ...context, startPoint: null };
}
} else {
startGripEdit(gripHit.entity, gripHit.grip);
return { ...context, startPoint: null };
}
}
const pickedEntity = pickEntityAt(event.worldMouseLocation);
// Mouse is close to entity and is not dragging a rectangle
if (closestEntityInfo && closestEntityInfo.distance < HIGHLIGHT_ENTITY_DISTANCE) {
if (pickedEntity) {
// Select the entity close to the mouse
const closestEntity = closestEntityInfo.entity;
const closestEntity = pickedEntity;
if (!event.holdingCtrl && !event.holdingShift) {
// 그룹으로 묶인 객체는 하나만 집어도 함께 선택된다 (GROUP)
setSelectedEntityIds(expandSelectionWithGroups([closestEntity.id]));
@@ -7,8 +7,8 @@
- 기본 입력 기준: AutoCAD 2024의 명령 별칭(`acad.pgp`)과 키 조합·기능 키(CUIx)를 `단축키` 열에 함께 기록했다. `—`는 공식 기본 입력을 확인하지 못했거나 리본·상황별 조작만 있는 기능이다. 사용자 설정에 따라 값이 달라질 수 있다.
- 자료 성격: 아래 표는 기본 2D 제도 기능과 명령을 작업 기준으로 분류한 **기능 인벤토리**이며, 실제 리본에 표시되는 아이콘의 전수 목록이 아니다.
- 아이콘 주의: 리본은 제품·작업공간·화면 폭·CUI 사용자화에 따라 탭, 패널, 버튼, 드롭다운 및 슬라이드아웃 구성이 달라진다. 실제 아이콘 목록으로 사용하려면 AutoCAD 2024 기본 `제도 및 주석` 작업공간의 CUIx 또는 실행 화면을 기준으로 버튼 단위 검증이 추가로 필요하다.
- 반영 등급: `A` B07 웹 CAD 우선 구현 · `B` 후속·조건부(엔진·구조 확장이 선행되어야 함) · `C` 미반영(DWG·데스크톱·클라우드 종속이거나 임도 설계에 불필요)
- 반영: `☑` 반영 완료 · `◐` 부분 반영 · `☐` 미반영. `기존`은 이번 AutoCAD 대응 작업 이전부터 있던 기능이다. 구현할 때마다 이 열을 갱신한다.
- 반영 등급: `A` B07 웹 CAD 우선 구현 · `B` 후속·조건부(엔진·구조 확장이 선행되어야 함) · `C` 미반영(DWG·데스크톱·클라우드 종속이거나 임도 설계에 불필요) · `P` 보류(구현할 수 있으나 사업 판단으로 뒤로 미룬 것)
- 반영: `☑` 반영 완료 · `◐` 부분 반영 · `☐` 미반영 · `X` 반영하지 않기로 확정 · `보류` 나중에 다른 형태로 반영 예정. `기존`은 이번 AutoCAD 대응 작업 이전부터 있던 기능이다. 구현할 때마다 이 열을 갱신한다.
- 제외 범위: 3D 모델링, Architecture 등 전문화 도구 세트, Express Tools 및 타사 애드인. 같은 기능이 여러 위치에 나타나는 경우 최초 한 번만 기재했다.
## 1. 홈 탭 — 그리기
@@ -264,18 +264,25 @@
| 그룹(패널) | 기능/명령 | 단축키 | 짧은 설명 | 반영 등급 | 반영 |
| ---------- | ----------------------------------- | -------------- | ----------------------------------------------------------- | --------- | ------- |
| 플롯 | 플롯`PLOT` | PRINT / Ctrl+P | 프린터·용지·영역·축척·스타일을 설정해 출력한다. | A | |
| 플롯 | 미리보기`PREVIEW` | PRE | 실제 출력 전 용지 결과를 확인한다. | A | |
| 플롯 | 페이지 설정`PAGESETUP` | — | 배치별 출력 장치와 용지 설정을 저장한다. | B | |
| 플롯 | 플롯 스타일 | — | 색상·선가중치 등의 CTB/STB 출력 규칙을 관리한다. | C | |
| 플롯 | 플로터 관리자`PLOTTERMANAGER` | — | 플로터 구성 파일과 장치 설정을 관리한다. | C | |
| 플롯 | 플롯 스타일 관리자`STYLESMANAGER` | — | CTB·STB 플롯 스타일 테이블 파일을 관리한다. | C | |
| 게시 | 게시`PUBLISH` | — | 여러 도면·배치를 한 번에 DWF·PDF·프린터로 출력한다. | B | |
| 게시 | 배치 플롯 | — | 시트 목록을 구성해 일괄 출력한다. | B | |
| 내보내기 | PDF 내보내기`EXPORTPDF` | EPDF | 도면 또는 배치를 PDF 파일로 만든다. | A | |
| 내보내기 | DWF/DWFx 내보내기 | — | 검토·배포용 Autodesk 형식으로 내보낸다. | C | |
| 플롯 | 플롯`PLOT` | PRINT / Ctrl+P | 프린터·용지·영역·축척·스타일을 설정해 출력한다. | P | 보류 |
| 플롯 | 미리보기`PREVIEW` | PRE | 실제 출력 전 용지 결과를 확인한다. | P | 보류 |
| 플롯 | 페이지 설정`PAGESETUP` | — | 배치별 출력 장치와 용지 설정을 저장한다. | P | 보류 |
| 플롯 | 플롯 스타일 | — | 색상·선가중치 등의 CTB/STB 출력 규칙을 관리한다. | P | 보류 |
| 플롯 | 플로터 관리자`PLOTTERMANAGER` | — | 플로터 구성 파일과 장치 설정을 관리한다. | P | 보류 |
| 플롯 | 플롯 스타일 관리자`STYLESMANAGER` | — | CTB·STB 플롯 스타일 테이블 파일을 관리한다. | P | 보류 |
| 게시 | 게시`PUBLISH` | — | 여러 도면·배치를 한 번에 DWF·PDF·프린터로 출력한다. | P | 보류 |
| 게시 | 배치 플롯 | — | 시트 목록을 구성해 일괄 출력한다. | P | 보류 |
| 내보내기 | PDF 내보내기`EXPORTPDF` | EPDF | 도면 또는 배치를 PDF 파일로 만든다. | P | 보류 |
| 내보내기 | DWF/DWFx 내보내기 | — | 검토·배포용 Autodesk 형식으로 내보낸다. | P | 보류 |
| 내보내기 | 기타 형식`EXPORT` | EXP | 지원되는 다른 교환 파일 형식으로 저장한다. | A | ☑ 기존 |
| 전송 | 전자 전송`ETRANSMIT` | ZIP | 도면과 참조·글꼴·플롯 설정을 하나의 전달 패키지로 묶는다. | C | |
| 전송 | 전자 전송`ETRANSMIT` | ZIP | 도면과 참조·글꼴·플롯 설정을 하나의 전달 패키지로 묶는다. | P | 보류 |
**9절 결정(2026-08-30)**: 출력·내보내기는 **의도적 미구현**이다. 무료 구간에서 도면을 그대로
가져갈 수 있으면 사업성이 없어, 결재창이 붙은 뒤 **PDF·DXF·DWG 다운로드**로 한 번에 반영한다.
따라서 "안 함(X)"이 아니라 보류(P)로 적는다. 이미 있는 JSON·SVG·PNG 내보내기는 개발·검증용이다.
DXF·DWG는 SVG·PNG와 난이도가 다르다 — 지금 해치는 정적 선, 표는 선+TEXT 묶음, 치수는 선과
문자의 조합이라 DXF의 HATCH·TABLE·DIMENSION으로 그대로 나가지 못한다. 결재 연동 시점에
"무엇이 진짜 객체여야 하는가"를 먼저 정해야 한다.
## 10. 공동작업·검토
@@ -303,17 +310,17 @@
| 직접 편집 | 그립 편집 | — | 선택 객체의 정점·중간점·반지름 등을 직접 끌어 수정한다. | A | ☐ |
| 직접 편집 | 다기능 그립 | — | 폴리선 정점 추가·제거, 호 전환 등 상황별 작업을 제공한다. | B | ☐ |
| 정확도 | 객체 스냅`OSNAP` | OS / F3 | 끝점·중간점·중심·교차점·접점 등 정확한 점을 포착한다. | A | ☑ 기존 |
| 정확도 | 객체 스냅 추적`(F11)` | F11 | 포착한 점에서 임시 정렬 경로를 추적한다. | B | |
| 정확도 | 극좌표 추적`(F10)` | F10 | 지정 각도 증분을 따라 커서 이동을 안내한다. | B | |
| 정확도 | 객체 스냅 추적`(F11)` | F11 | 포착한 점에서 임시 정렬 경로를 추적한다. | A | ◐ 기존 |
| 정확도 | 극좌표 추적`(F10)` | F10 | 지정 각도 증분을 따라 커서 이동을 안내한다. | A | ☑ 기존 |
| 정확도 | 직교 모드`(F8)` | F8 | 커서 이동을 현재 UCS의 수평·수직 방향으로 제한한다. | A | ☑ 기존 |
| 정확도 | 그리드·스냅 | F7 / F9 | 화면 격자를 표시하고 커서 이동 간격을 제한한다. | A | ☑ 기존 |
| 정확도 | 동적 입력`(F12, DYNMODE 시스템 변수)` | F12 | 커서 근처에서 좌표·거리·각도 및 명령 옵션을 입력한다. | A | ☑ 기존 |
| 정확도 | 직접 거리 입력 | — | 방향을 지정한 뒤 키보드로 정확한 거리를 입력한다. | A | ☑ 기존 |
| 좌표 | 절대·상대·극좌표 | — | 전역 좌표, 이전 점 기준 좌표, 거리·각도로 점을 입력한다. | A | ◐ 기존 |
| 작업 흐름 | 명령 직접 입력 | — | 명령 이름, 별칭, 옵션, 숫자와 좌표를 명령행에 연속 입력한다. | A | ☑ 기존 |
| 작업 흐름 | 명령 자동완성 | — | 입력 중인 명령·시스템 변수·콘텐츠를 검색해 제안한다. | A | 기존 |
| 작업 흐름 | 명령 자동완성 | — | 입력 중인 명령·시스템 변수·콘텐츠를 검색해 제안한다. | A | 기존 |
| 작업 흐름 | 실행 취소·다시 실행 | Ctrl+Z / Ctrl+Y | 명령 단위로 작업 이력을 되돌리거나 복원한다. | A | ☑ 기존 |
| 작업 흐름 | 반복·최근 명령 | — | 직전 또는 최근 사용 명령을 다시 실행한다. | B | |
| 작업 흐름 | 반복·최근 명령 | — | 직전 또는 최근 사용 명령을 다시 실행한다. | A | ☑ 기존 |
| 표시 | 선가중치 표시 | — | 실제 출력 선 굵기의 화면 표시를 전환한다. | B | ☐ |
| 표시 | 투명도 표시 | — | 객체·도면층 투명도의 화면 표시를 전환한다. | C | ☐ |
| 표시 | 주석 가시성 | — | 현재 축척을 지원하지 않는 주석의 표시 여부를 전환한다. | C | ☐ |
@@ -346,7 +353,7 @@
| 배열 편집 | 원본 편집·재설정 | — | 원본 객체를 편집하고 배열 재지정을 초기화한다. | C | ☐ |
| 외부 참조·언더레이 | 페이드·대비 | — | 외부 참조와 PDF·DWF·DGN 언더레이의 화면 특성을 조정한다. | C | ☐ |
| 외부 참조 | 참조 도면층 | — | 참조에 포함된 도면층 표시를 관리한다. | C | ☐ |
| 이미지 | 페이드·대비·밝기 | — | 래스터 이미지의 화면 특성을 조정한다. | B | |
| 이미지 | 페이드·대비·밝기 | — | 래스터 이미지의 화면 특성을 조정한다. | B | |
| PDF/DWF/DGN 언더레이 | 단색·언더레이 도면층 | — | 단색 표시와 원본 도면층 가시성을 관리한다. | C | ☐ |
| 배치 | 명명된 뷰 삽입 | — | 저장된 모형 뷰를 배치 뷰포트로 배치한다. | C | ☐ |
| 테이블 셀 | 행·열 삽입·삭제 | — | 선택 셀 주변의 표 구조를 편집한다. | B | ☐ |