Files
Aislo/B07_DesignDetail/openwebcad/src/helpers/grips.ts
T
eomsangdonandClaude Opus 5 e599884888 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>
2026-08-30 14:43:46 +09:00

200 lines
7.6 KiB
TypeScript

/**
* 그립 — 선택한 객체에 붙는 편집점. 집어서 다음 클릭 위치로 옮긴다.
* 형상 필드가 전부 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;
}