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
@@ -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;
}