저장소 사고로 잃은 4개 커밋(38eb7cd4·b8a11756·281528bf·f60b488d)의 작업물을 하나로 다시 담았다. 내용은 동일하다. ■ 구조 - commands/: 명령 정의(id·AutoCAD 별칭·글리프·도구/즉시실행)를 단일 소스로 두고 리본·명령행·단축키가 모두 이 레지스트리를 읽는다. tools/tool.consts.ts 폐지. - ribbon/: 탭→패널→명령 데이터(ribbon.config.ts)와 범용 렌더러 분리. AutoCAD 배치(홈·삽입·주석·뷰·출력)와 패널 확장(▾)을 따른다. - tools/factories/sequence-tool.ts: 점·숫자·문자·객체·선택 단계를 선언하면 xstate 머신을 만들어 주는 공장. 명령당 170줄 보일러플레이트 제거. - helpers/geometry/: 3점 호·정다각형·타원·스플라인·구름형·평행이동·해치 스캔선· 점렬 샘플링 등 상태 없는 순수 함수. - Toolbar 483줄을 QuickAccessBar/Ribbon/InspectorPanel/StatusBar/CommandLine/ ViewControls/PropertiesEditor/QuickProperties로 분해. ■ 명령 (조사표 기준) - 1절 그리기 21건, 2절 수정 27건, 3절 도면층·특성·그룹·유틸리티 39건 전부 반영. - 5절 주석 34건 중 26건 반영(문자·치수 16종·지시선·표·구름형·주석 축척). - HatchEntity 추가(solid·pattern·cross·gradient) + JSON 왕복, Layer에 색·선가중치· 선종류·동결·투명도 필드 추가, 그리기 루프가 동결·숨김·투명도를 반영. ■ 화면 실측에서 고친 결함 - 명령행 포커스 상태에서 ENTER가 도구로 가지 않던 문제 - 명령행 문자 입력이 접두사가 같은 명령으로 실행되던 문제 - 명령이 끝나도 입력을 계속 먹던 문제(점 입력 명령만 반복, 나머지는 선택 도구 복귀) - 시퀀스 단계 인덱스 오사용 9건 + 단계 값 종류 검사 추가 - 해치 내부를 클릭해도 선택되지 않던 문제 미반영 8건(맞춤법 검사·꺾기 치수·치수 끊기/재연관/검사 치수·기하공차·지시선 수집· 축척 리스트 편집)은 조사표 `반영` 열과 PLAN.md에 사유를 적었다.
258 lines
7.2 KiB
TypeScript
258 lines
7.2 KiB
TypeScript
import type * as Flatten from '@flatten-js/core';
|
|
import { type Box, Point, Polygon, Relations, type Segment, Vector } from '@flatten-js/core';
|
|
import { type Shape, type SnapPoint, SnapPointType } from '../App.types';
|
|
import type { DrawController } from '../drawControllers/DrawController.ts';
|
|
import { twoPointBoxToPolygon } from '../helpers/box-to-polygon';
|
|
import { getExportColor } from '../helpers/get-export-color';
|
|
import { mirrorAngleOverAxis } from '../helpers/mirror-angle-over-axis.ts';
|
|
import { mirrorPointOverAxis } from '../helpers/mirror-point-over-axis.ts';
|
|
import { polygonToSegments } from '../helpers/polygon-to-segments';
|
|
import { scalePoint } from '../helpers/scale-point';
|
|
import { getActiveLayerId, isEntityHighlighted, isEntitySelected } from '../state.ts';
|
|
import { type Entity, EntityName, type JsonEntity } from './Entity';
|
|
import type { LineEntity } from './LineEntity.ts';
|
|
|
|
export class ImageEntity implements Entity {
|
|
public id: string = crypto.randomUUID();
|
|
public lineColor = '#fff';
|
|
public lineWidth = 1;
|
|
public lineDash: number[] | undefined = undefined;
|
|
public layerId: string;
|
|
/** 0~1 객체 투명도 (Entity 인터페이스의 선택 항목) */
|
|
public opacity?: number;
|
|
/** GROUP으로 묶인 객체가 공유하는 식별자 */
|
|
public groupId?: string;
|
|
|
|
private imageElement: HTMLImageElement;
|
|
private polygon: Polygon;
|
|
private angle: number;
|
|
|
|
constructor(
|
|
layerId: string,
|
|
imgData: HTMLImageElement,
|
|
startPointOrPolygon?: Point | Polygon,
|
|
endPointOrAngle?: Point | number,
|
|
angle = 0
|
|
) {
|
|
this.layerId = layerId;
|
|
this.imageElement = imgData;
|
|
if (startPointOrPolygon instanceof Polygon) {
|
|
this.polygon = startPointOrPolygon as Polygon;
|
|
} else {
|
|
this.polygon = twoPointBoxToPolygon(startPointOrPolygon as Point, endPointOrAngle as Point);
|
|
}
|
|
if (endPointOrAngle instanceof Point) {
|
|
this.angle = angle;
|
|
} else {
|
|
this.angle = endPointOrAngle as number;
|
|
}
|
|
}
|
|
|
|
public draw(
|
|
drawController: DrawController,
|
|
parentHighlighted?: boolean,
|
|
parentSelected?: boolean
|
|
): void {
|
|
drawController.setLineStyles(
|
|
parentHighlighted ?? isEntityHighlighted(this),
|
|
parentSelected ?? isEntitySelected(this),
|
|
this.lineColor,
|
|
this.lineWidth,
|
|
this.lineDash
|
|
);
|
|
for (const edge of polygonToSegments(this.polygon)) {
|
|
drawController.drawLine(edge.start, edge.end);
|
|
}
|
|
|
|
const width = this.polygon.box.width;
|
|
const height = this.polygon.box.height;
|
|
|
|
// Draw image
|
|
drawController.drawImage(
|
|
this.imageElement,
|
|
this.polygon.box.xmin,
|
|
this.polygon.box.ymin,
|
|
width,
|
|
height,
|
|
this.angle
|
|
);
|
|
}
|
|
|
|
public move(x: number, y: number) {
|
|
this.polygon = this.polygon.translate(new Vector(x, y));
|
|
}
|
|
|
|
public scale(scaleOrigin: Point, scaleFactor: number) {
|
|
const center = this.polygon.box.center;
|
|
const newCenter = scalePoint(center, scaleOrigin, scaleFactor);
|
|
this.polygon = this.polygon.translate(
|
|
new Vector(newCenter.x - center.x, newCenter.y - center.y)
|
|
);
|
|
}
|
|
|
|
public rotate(rotateOrigin: Point, angle: number) {
|
|
this.polygon = this.polygon.rotate(angle, rotateOrigin);
|
|
this.angle += angle; // Need to keep track of the angle for drawing the image
|
|
}
|
|
|
|
public mirror(mirrorAxis: LineEntity) {
|
|
const mirroredVertices = this.polygon.vertices.map((p) => mirrorPointOverAxis(p, mirrorAxis));
|
|
const mirroredAngle = mirrorAngleOverAxis(this.angle, mirrorAxis);
|
|
// TODO mirror image pixels
|
|
// this.imageElement = new HTMLImageElement(
|
|
// this.imageElement.
|
|
// )
|
|
this.polygon = new Polygon(mirroredVertices);
|
|
this.angle = mirroredAngle;
|
|
}
|
|
|
|
public clone(): ImageEntity {
|
|
const clonedImage = document.createElement('img');
|
|
clonedImage.src = this.imageElement.src;
|
|
return new ImageEntity(getActiveLayerId(), clonedImage, this.polygon.clone());
|
|
}
|
|
|
|
// TODO add destroy method to cleanup this.imageElement.src
|
|
|
|
public intersectsWithBox(selectionBox: Box): boolean {
|
|
return Relations.relate(this.polygon, selectionBox).B2B.length > 0;
|
|
}
|
|
|
|
public isContainedInBox(selectionBox: Box): boolean {
|
|
return selectionBox.contains(this.polygon);
|
|
}
|
|
|
|
public distanceTo(shape: Shape): [number, Segment] | null {
|
|
const distanceInfos: [number, Segment][] = polygonToSegments(this.polygon).map((segment) =>
|
|
segment.distanceTo(shape)
|
|
);
|
|
let shortestDistanceInfo: [number, Segment | null] = [Number.MAX_SAFE_INTEGER, null];
|
|
for (const distanceInfo of distanceInfos) {
|
|
if (distanceInfo[0] < shortestDistanceInfo[0]) {
|
|
shortestDistanceInfo = distanceInfo;
|
|
}
|
|
}
|
|
return shortestDistanceInfo as [number, Segment];
|
|
}
|
|
|
|
public getBoundingBox(): Box {
|
|
return this.polygon.box;
|
|
}
|
|
|
|
public getShape(): Shape | null {
|
|
return this.polygon;
|
|
}
|
|
|
|
public getSnapPoints(): SnapPoint[] {
|
|
const corners = this.polygon.vertices;
|
|
const edges = polygonToSegments(this.polygon);
|
|
return [
|
|
{
|
|
point: corners[0],
|
|
type: SnapPointType.LineEndPoint,
|
|
},
|
|
{
|
|
point: corners[1],
|
|
type: SnapPointType.LineEndPoint,
|
|
},
|
|
{
|
|
point: corners[2],
|
|
type: SnapPointType.LineEndPoint,
|
|
},
|
|
{
|
|
point: corners[3],
|
|
type: SnapPointType.LineEndPoint,
|
|
},
|
|
{
|
|
point: edges[0].middle(),
|
|
type: SnapPointType.LineMidPoint,
|
|
},
|
|
{
|
|
point: edges[1].middle(),
|
|
type: SnapPointType.LineMidPoint,
|
|
},
|
|
{
|
|
point: edges[2].middle(),
|
|
type: SnapPointType.LineMidPoint,
|
|
},
|
|
{
|
|
point: edges[3].middle(),
|
|
type: SnapPointType.LineMidPoint,
|
|
},
|
|
];
|
|
}
|
|
|
|
public getIntersections(entity: Entity): Point[] {
|
|
const otherShape = entity.getShape();
|
|
if (!otherShape) {
|
|
return [];
|
|
}
|
|
return polygonToSegments(this.polygon).flatMap((segment) => {
|
|
return segment.intersect(otherShape);
|
|
});
|
|
}
|
|
|
|
public getFirstPoint(): Point | null {
|
|
return this.polygon?.vertices[0] || null;
|
|
}
|
|
|
|
public getSvgString(): string | null {
|
|
return this.polygon.svg({
|
|
strokeWidth: this.lineWidth,
|
|
stroke: getExportColor(this.lineColor),
|
|
});
|
|
}
|
|
|
|
public getType(): EntityName {
|
|
return EntityName.Image;
|
|
}
|
|
|
|
public containsPointOnShape(point: Flatten.Point): boolean {
|
|
return polygonToSegments(this.polygon).some((segment) => segment.contains(point));
|
|
}
|
|
|
|
public async toJson(): Promise<JsonEntity<ImageJsonData> | null> {
|
|
return {
|
|
id: this.id,
|
|
type: EntityName.Image,
|
|
lineColor: this.lineColor,
|
|
lineWidth: this.lineWidth,
|
|
lineDash: this.lineDash,
|
|
layerId: this.layerId,
|
|
shapeData: {
|
|
points: this.polygon.vertices.map((vertex) => ({
|
|
x: vertex.x,
|
|
y: vertex.y,
|
|
})),
|
|
imageData: this.imageElement.currentSrc,
|
|
},
|
|
};
|
|
}
|
|
|
|
public static async fromJson(jsonEntity: JsonEntity<ImageJsonData>): Promise<ImageEntity> {
|
|
if (!jsonEntity.shapeData) {
|
|
throw new Error('Invalid JSON entity of type Image: missing shapeData');
|
|
}
|
|
const rectangle = new Polygon(
|
|
jsonEntity.shapeData.points.map((point) => new Point(point.x, point.y))
|
|
);
|
|
const image = new Image();
|
|
image.src = jsonEntity.shapeData.imageData;
|
|
const rectangleEntity = new ImageEntity(
|
|
jsonEntity.layerId || getActiveLayerId(),
|
|
image,
|
|
rectangle
|
|
);
|
|
rectangleEntity.id = jsonEntity.id;
|
|
rectangleEntity.lineColor = jsonEntity.lineColor;
|
|
rectangleEntity.lineWidth = jsonEntity.lineWidth;
|
|
rectangleEntity.lineDash = jsonEntity.lineDash;
|
|
return rectangleEntity;
|
|
}
|
|
}
|
|
|
|
export interface ImageJsonData {
|
|
points: { x: number; y: number }[];
|
|
imageData: string;
|
|
}
|