@aivex/ui 1.2.0-dev.4 → 1.2.0-dev.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +68 -0
  2. package/dist/{Button-CzqDPqUT.js → Button-BrPqDGyO.js} +1502 -3115
  3. package/dist/Button-BrPqDGyO.js.map +1 -0
  4. package/dist/Button-EEErevS-.cjs +2 -0
  5. package/dist/Button-EEErevS-.cjs.map +1 -0
  6. package/dist/IconButton-CK4en7H6.js +209 -0
  7. package/dist/IconButton-CK4en7H6.js.map +1 -0
  8. package/dist/IconButton-DBlsEy3m.cjs +2 -0
  9. package/dist/IconButton-DBlsEy3m.cjs.map +1 -0
  10. package/dist/comment.cjs +3 -113
  11. package/dist/comment.cjs.map +1 -1
  12. package/dist/comment.js +153 -13491
  13. package/dist/comment.js.map +1 -1
  14. package/dist/components/Badge/Badge.d.ts +8 -1
  15. package/dist/components/Calendar/Calendar.d.ts +38 -0
  16. package/dist/components/Calendar/Calendar.test.d.ts +1 -0
  17. package/dist/components/{DatePicker → Calendar}/date.d.ts +4 -3
  18. package/dist/components/Calendar/date.test.d.ts +1 -0
  19. package/dist/components/Calendar/index.d.ts +2 -0
  20. package/dist/components/Comment/CommentInput.d.ts +6 -1
  21. package/dist/components/DataGrid/DataGrid.d.ts +38 -71
  22. package/dist/components/DataGrid/DataGridColumnSettings.d.ts +18 -0
  23. package/dist/components/DataGrid/DataGridPrimitives.d.ts +79 -0
  24. package/dist/components/DataGrid/DataGridRows.d.ts +66 -0
  25. package/dist/components/DataGrid/index.d.ts +6 -2
  26. package/dist/components/DraggableScroll/DraggableScroll.d.ts +6 -1
  27. package/dist/components/Drawer/Drawer.d.ts +35 -0
  28. package/dist/components/Drawer/index.d.ts +2 -0
  29. package/dist/components/Icon/index.d.ts +6 -1
  30. package/dist/components/InputBase/InputBase.d.ts +5 -7
  31. package/dist/components/Modal/Modal.d.ts +9 -2
  32. package/dist/components/Modal/ModalBase.d.ts +33 -0
  33. package/dist/components/Modal/index.d.ts +3 -1
  34. package/dist/components/ScrollArea/ScrollArea.d.ts +5 -1
  35. package/dist/components/SelectBox/SelectBox.d.ts +7 -4
  36. package/dist/components/SelectButton/SelectButton.d.ts +18 -0
  37. package/dist/components/SelectButton/index.d.ts +2 -0
  38. package/dist/components/ShapeEditor/ShapeEditor.d.ts +1 -1
  39. package/dist/components/ShapeEditor/ShapeViewer.d.ts +5 -5
  40. package/dist/components/ShapeEditor/_components/ImageStateOverlay.d.ts +8 -3
  41. package/dist/components/ShapeEditor/_components/Minimap.d.ts +13 -11
  42. package/dist/components/ShapeEditor/_components/MinimapShape.d.ts +2 -2
  43. package/dist/components/ShapeEditor/_components/SelectionInfo.d.ts +2 -0
  44. package/dist/components/ShapeEditor/_components/SettingsPanel.d.ts +18 -3
  45. package/dist/components/ShapeEditor/_constants.d.ts +7 -4
  46. package/dist/components/ShapeEditor/_model/clipboard.d.ts +22 -0
  47. package/dist/components/ShapeEditor/_model/clipboard.test.d.ts +1 -0
  48. package/dist/components/ShapeEditor/_model/cursors.d.ts +5 -0
  49. package/dist/components/ShapeEditor/_model/cursors.test.d.ts +1 -0
  50. package/dist/components/ShapeEditor/_model/geometry.d.ts +33 -1
  51. package/dist/components/ShapeEditor/_model/geometry.evenodd-audit.test.d.ts +1 -0
  52. package/dist/components/ShapeEditor/_model/geometry.test.d.ts +1 -0
  53. package/dist/components/ShapeEditor/_model/imageDiagnosis.d.ts +23 -0
  54. package/dist/components/ShapeEditor/_model/imageDiagnosis.test.d.ts +1 -0
  55. package/dist/components/ShapeEditor/_model/imageLoad.d.ts +13 -0
  56. package/dist/components/ShapeEditor/_model/imageLoad.test.d.ts +1 -0
  57. package/dist/components/ShapeEditor/_model/keymap.d.ts +1 -1
  58. package/dist/components/ShapeEditor/_model/overlays.d.ts +9 -19
  59. package/dist/components/ShapeEditor/_model/props.d.ts +100 -33
  60. package/dist/components/ShapeEditor/_model/strings.d.ts +7 -3
  61. package/dist/components/ShapeEditor/_model/viewSettings.d.ts +45 -1
  62. package/dist/components/ShapeEditor/_model/viewSettings.test.d.ts +1 -0
  63. package/dist/components/ShapeEditor/_renderers/KonvaRenderer.d.ts +23 -3
  64. package/dist/components/ShapeEditor/_renderers/PixiRenderer.d.ts +30 -5
  65. package/dist/components/ShapeEditor/_renderers/transformSession.d.ts +1 -1
  66. package/dist/components/ShapeEditor/_renderers/types.d.ts +52 -16
  67. package/dist/components/ShapeEditor/_state/createInteractionController.d.ts +8 -2
  68. package/dist/components/ShapeEditor/_state/createInteractionController.test.d.ts +1 -0
  69. package/dist/components/ShapeEditor/_state/useEditorHotkeys.d.ts +4 -4
  70. package/dist/components/ShapeEditor/_state/useEngineLifecycle.d.ts +52 -10
  71. package/dist/components/ShapeEditor/_state/useEngineLifecycle.test.d.ts +1 -0
  72. package/dist/components/ShapeEditor/_state/useSelectionActions.d.ts +7 -6
  73. package/dist/components/ShapeEditor/index.d.ts +3 -2
  74. package/dist/components/Spinner/Spinner.d.ts +15 -0
  75. package/dist/components/Spinner/index.d.ts +2 -0
  76. package/dist/components/Switch/Switch.d.ts +2 -1
  77. package/dist/components/Tagbox/Tagbox.d.ts +1 -4
  78. package/dist/components/Textarea/Textarea.d.ts +7 -4
  79. package/dist/components/Textbox/Textbox.d.ts +1 -5
  80. package/dist/components/Toast/Toast.d.ts +13 -3
  81. package/dist/components/Toast/index.d.ts +1 -1
  82. package/dist/index.cjs +1 -14
  83. package/dist/index.cjs.map +1 -1
  84. package/dist/index.d.ts +5 -1
  85. package/dist/index.js +2913 -7061
  86. package/dist/index.js.map +1 -1
  87. package/dist/keyboard-BMCakKCv.js +398 -0
  88. package/dist/keyboard-BMCakKCv.js.map +1 -0
  89. package/dist/keyboard-DCewgvMV.cjs +2 -0
  90. package/dist/keyboard-DCewgvMV.cjs.map +1 -0
  91. package/dist/shape-editor.cjs +1 -1
  92. package/dist/shape-editor.cjs.map +1 -1
  93. package/dist/shape-editor.js +3176 -2269
  94. package/dist/shape-editor.js.map +1 -1
  95. package/dist/styles.css +3 -2
  96. package/dist/tokens/tokens.css +613 -611
  97. package/dist/utils/keyboard.d.ts +3 -0
  98. package/dist/utils/useModalAutoFocus.d.ts +5 -0
  99. package/dist/utils.cjs +2 -0
  100. package/dist/utils.cjs.map +1 -0
  101. package/dist/utils.js +59 -0
  102. package/dist/utils.js.map +1 -0
  103. package/package.json +26 -14
  104. package/dist/Button-C_GP2mJ-.cjs +0 -2
  105. package/dist/Button-C_GP2mJ-.cjs.map +0 -1
  106. package/dist/Button-CzqDPqUT.js.map +0 -1
  107. package/dist/IconButton-B-MspnYP.cjs +0 -2
  108. package/dist/IconButton-B-MspnYP.cjs.map +0 -1
  109. package/dist/IconButton-DTGSfJme.js +0 -560
  110. package/dist/IconButton-DTGSfJme.js.map +0 -1
  111. package/dist/Switch-B2irM7Pp.js +0 -2656
  112. package/dist/Switch-B2irM7Pp.js.map +0 -1
  113. package/dist/Switch-CMKBdqkX.cjs +0 -42
  114. package/dist/Switch-CMKBdqkX.cjs.map +0 -1
  115. package/dist/components/DatePicker/Calendar.d.ts +0 -27
  116. package/dist/components/DatePicker/DatePicker.d.ts +0 -119
  117. package/dist/components/DatePicker/index.d.ts +0 -4
  118. package/dist/components/ShapeEditor/_model/imageFetch.d.ts +0 -9
@@ -1 +1 @@
1
- {"version":3,"file":"shape-editor.js","names":[],"sources":["../src/components/ShapeEditor/_model/geometry.ts","../src/components/ShapeEditor/_model/strings.ts","../src/components/ShapeEditor/_model/tools.ts","../src/components/ShapeEditor/_model/viewSettings.ts","../src/components/ShapeEditor/_components/AssistantOverlay.tsx","../src/components/ShapeEditor/_components/ContextMenu.tsx","../src/components/ShapeEditor/_components/CursorGuide.tsx","../src/components/ShapeEditor/_components/ImageStateOverlay.tsx","../src/components/ShapeEditor/_constants.ts","../src/components/ShapeEditor/_model/shapeRenderStyle.ts","../src/components/ShapeEditor/_components/MinimapShape.tsx","../src/components/ShapeEditor/_components/RegionOverlay.tsx","../src/components/ShapeEditor/_components/SettingsPanel.tsx","../src/components/ShapeEditor/_components/Minimap.tsx","../src/components/ShapeEditor/_components/SelectionInfo.tsx","../src/components/ShapeEditor/_model/cursors.ts","../src/components/ShapeEditor/_model/overlays.ts","../src/components/ShapeEditor/_model/viewport.ts","../src/components/ShapeEditor/_state/createInteractionController.ts","../src/components/ShapeEditor/_state/useAssistant.ts","../src/components/ShapeEditor/_model/brush.ts","../src/components/ShapeEditor/_model/scalarMask.ts","../src/components/ShapeEditor/_state/drawSessionState.ts","../src/components/ShapeEditor/_state/useDrawSession.ts","../src/components/ShapeEditor/_state/useEditorDocument.ts","../src/components/ShapeEditor/_model/keymap.ts","../src/components/ShapeEditor/_state/useEditorHotkeys.ts","../src/components/ShapeEditor/_model/imageFetch.ts","../src/components/ShapeEditor/_model/imageTiles.ts","../src/components/ShapeEditor/_model/konva.ts","../src/components/ShapeEditor/_model/pinIcon.ts","../src/components/ShapeEditor/_renderers/transformSession.ts","../src/components/ShapeEditor/_renderers/KonvaRenderer.ts","../src/components/ShapeEditor/_renderers/PixiRenderer.ts","../src/components/ShapeEditor/_state/useEngineLifecycle.ts","../src/components/ShapeEditor/_state/useMinimapNavigation.ts","../src/components/ShapeEditor/_state/useMinimapSync.ts","../src/components/ShapeEditor/_state/useSelectionActions.ts","../src/components/ShapeEditor/_state/useViewportControls.ts","../src/components/ShapeEditor/ShapeEditor.tsx","../src/components/ShapeEditor/ShapeViewer.tsx"],"sourcesContent":["/**\n * Editor의 도메인 무관 기하/도형 모델.\n *\n * 이 에디터는 \"색 입힌 도형을 그리고 편집\"할 뿐, 클래스/라벨/태스크 같은 라벨링 도메인\n * 개념을 모른다. 분류 정보(classId 등)는 호스트가 `meta`에 담아 넘기면 에디터는 건드리지\n * 않고 그대로 되돌려준다. 렌더에 필요한 색/채움은 `style`로 받는다.\n */\n\nexport interface Point {\n\tx: number;\n\ty: number;\n}\n\nexport const SHAPE_TYPE = {\n\tPOINT: \"POINT\",\n\tRECTANGLE: \"RECTANGLE\",\n\tROTATED_RECTANGLE: \"ROTATED_RECTANGLE\",\n\tPOLYGON: \"POLYGON\",\n\tELLIPSE: \"ELLIPSE\",\n\tLINE: \"LINE\",\n} as const;\n\nexport type ShapeType = (typeof SHAPE_TYPE)[keyof typeof SHAPE_TYPE];\n\n/** 도형 렌더 힌트. 호스트가 (예: 클래스→색) 계산해 주입한다. */\nexport interface ShapeStyle {\n\tcolor?: string;\n\t/** 점선의 빈 구간에 표시할 보조색. 지정하면 보조색 실선 위에 주색 점선을 그린다. */\n\talternateColor?: string;\n\tfilled?: boolean;\n\topacity?: number;\n\t/** 도형별 선 두께(화면 px). 없으면 에디터 기본값을 사용한다. */\n\tstrokeWidth?: number;\n\t/** 채움 투명도(0~1). 없으면 렌더러 기본값을 사용한다. */\n\tfillOpacity?: number;\n\t/** 점선 패턴(화면 px). */\n\tdash?: number[];\n\t/** POINT 도형 반경(화면 px). */\n\tpointRadius?: number;\n\t/** 렌더 순서. 없으면 문서 배열 순서를 따른다. */\n\tzIndex?: number;\n}\n\nexport interface ShapeInteraction {\n\t/** false면 렌더하지 않고 hit-test/선택/편집에서도 제외한다. */\n\tvisible?: boolean;\n\t/** false면 도형 클릭·마퀴·선택 API에서 선택 대상이 되지 않는다. */\n\tselectable?: boolean;\n\t/** false면 본체 드래그 이동을 막는다. */\n\tdraggable?: boolean;\n\t/** false면 트랜스포머/꼭짓점 편집/삭제 같은 문서 변경 편집을 막는다. */\n\teditable?: boolean;\n\t/** true면 렌더는 하되 포인터 hit-test 대상에서 제외한다. */\n\thitTestDisabled?: boolean;\n}\n\n/**\n * 에디터가 그리고 편집하는 단위.\n * - POINT: points 1개, RECTANGLE·ELLIPSE: 2개(대각 bbox), ROTATED_RECTANGLE: 4개,\n * POLYGON: N개(닫힘), LINE: N개(열린 폴리라인/자유곡선).\n * - id: **클라이언트 생성**(에디터가 도형 생성 시 부여). 서버 id는 에디터가 모른다 —\n * 호스트가 clientId↔serverId 매핑을 들거나 meta에 보관한다.\n * - meta: 호스트 전용 불투명 데이터(classId, serverId 등). 에디터는 읽지 않고 보존만 한다.\n * - style: 렌더 힌트(색/채움). 호스트가 클래스→색을 계산해 주입/시드한다.\n */\nexport interface EditorShape<TMeta = unknown> {\n\tid: string;\n\ttype: ShapeType;\n\tpoints: Point[];\n\trotation?: number;\n\t/**\n\t * 편집 불가(예: 모델 예측/평가 도형). 하위 호환 shorthand이며 selectable은 유지하고\n\t * draggable/editable만 false처럼 취급한다.\n\t */\n\treadOnly?: boolean;\n\tinteraction?: ShapeInteraction;\n\tstyle?: ShapeStyle;\n\tmeta?: TMeta;\n}\n\nexport interface Viewport {\n\tscale: number;\n\tposition: Point;\n}\n\nexport function isShapeVisible(shape: EditorShape): boolean {\n\treturn shape.interaction?.visible !== false;\n}\n\nexport function isShapeHitTestable(shape: EditorShape): boolean {\n\treturn isShapeVisible(shape) && shape.interaction?.hitTestDisabled !== true;\n}\n\nexport function isShapeSelectable(shape: EditorShape): boolean {\n\treturn isShapeHitTestable(shape) && shape.interaction?.selectable !== false;\n}\n\nexport function isShapeEditable(shape: EditorShape): boolean {\n\treturn isShapeSelectable(shape) && !shape.readOnly && shape.interaction?.editable !== false;\n}\n\nexport function isShapeDraggable(shape: EditorShape): boolean {\n\treturn isShapeEditable(shape) && shape.interaction?.draggable !== false;\n}\n\nexport function sortShapesForRender<TMeta>(shapes: EditorShape<TMeta>[]): EditorShape<TMeta>[] {\n\treturn shapes\n\t\t.map((shape, index) => ({ shape, index }))\n\t\t.sort((a, b) => {\n\t\t\tconst za = a.shape.style?.zIndex ?? 0;\n\t\t\tconst zb = b.shape.style?.zIndex ?? 0;\n\t\t\treturn za === zb ? a.index - b.index : za - zb;\n\t\t})\n\t\t.map((entry) => entry.shape);\n}\n\n// ── 순수 기하 헬퍼(트랜스포머/상호작용 공용, Konva 비의존) ──\nexport function clamp(value: number, min: number, max: number) {\n\treturn Math.max(min, Math.min(max, value));\n}\n\n// secure context가 아닌 환경(비-localhost http 등)에서도 안전한 클라이언트 id 생성.\nexport function generateId(): string {\n\tif (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n\t\treturn crypto.randomUUID();\n\t}\n\treturn `id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n// ── 자체 바운딩박스 트랜스포머용 기하 ──\nexport interface BBox {\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\nexport type Anchor = \"tl\" | \"t\" | \"tr\" | \"r\" | \"br\" | \"b\" | \"bl\" | \"l\";\nexport const ANCHORS: Anchor[] = [\"tl\", \"t\", \"tr\", \"r\", \"br\", \"b\", \"bl\", \"l\"];\n\nexport function getBBox(points: Point[]): BBox {\n\tconst xs = points.map((p) => p.x);\n\tconst ys = points.map((p) => p.y);\n\treturn {\n\t\tminX: Math.min(...xs),\n\t\tminY: Math.min(...ys),\n\t\tmaxX: Math.max(...xs),\n\t\tmaxY: Math.max(...ys),\n\t};\n}\n\nexport function anchorPoint(anchor: Anchor, b: BBox): Point {\n\tconst cx = (b.minX + b.maxX) / 2;\n\tconst cy = (b.minY + b.maxY) / 2;\n\tconst x = anchor.includes(\"l\") ? b.minX : anchor.includes(\"r\") ? b.maxX : cx;\n\tconst y = anchor.includes(\"t\") ? b.minY : anchor.includes(\"b\") ? b.maxY : cy;\n\treturn { x, y };\n}\n\n// 핸들을 (hx,hy)로 끌었을 때의 새 bbox(해당 모서리/변만 이동).\nexport function boxFromAnchor(anchor: Anchor, b: BBox, hx: number, hy: number): BBox {\n\tconst next = { ...b };\n\tif (anchor.includes(\"l\")) next.minX = hx;\n\tif (anchor.includes(\"r\")) next.maxX = hx;\n\tif (anchor.includes(\"t\")) next.minY = hy;\n\tif (anchor.includes(\"b\")) next.maxY = hy;\n\treturn next;\n}\n\n// Shift 제약: 박스를 정사각/정원으로(끝점을 큰 축에 맞춤).\nexport function squareEnd(start: Point, p: Point): Point {\n\tconst dx = p.x - start.x;\n\tconst dy = p.y - start.y;\n\tconst d = Math.max(Math.abs(dx), Math.abs(dy));\n\treturn {\n\t\tx: start.x + (dx < 0 ? -d : d),\n\t\ty: start.y + (dy < 0 ? -d : d),\n\t};\n}\n\n// 점을 pivot 기준 angle(rad) 회전.\nexport function rotatePoint(p: Point, pivot: Point, angle: number): Point {\n\tconst cos = Math.cos(angle);\n\tconst sin = Math.sin(angle);\n\tconst dx = p.x - pivot.x;\n\tconst dy = p.y - pivot.y;\n\treturn {\n\t\tx: pivot.x + dx * cos - dy * sin,\n\t\ty: pivot.y + dx * sin + dy * cos,\n\t};\n}\n\n// 축정렬 사각형(2점) → 4개 코너 점[tl,tr,br,bl]. 회전 시 ROTATED_RECTANGLE로 승격.\nexport function rectTo4(points: Point[]): Point[] {\n\tconst b = getBBox(points);\n\treturn [\n\t\t{ x: b.minX, y: b.minY },\n\t\t{ x: b.maxX, y: b.minY },\n\t\t{ x: b.maxX, y: b.maxY },\n\t\t{ x: b.minX, y: b.maxY },\n\t];\n}\n\n/**\n * 두 점(a,b)이 이루는 바운딩 박스에 **내접하는 타원**을 폴리곤으로 샘플링한다.\n * 그리기 미리보기(previewBox \"ellipse\": rx=w/2, ry=h/2)와 동일한 도형이어야 커밋 결과가\n * 드래그 중 보이던 것과 일치한다(정사각형 드래그면 원). 예전엔 대각선을 지름으로 한 원을\n * 만들어 미리보기(내접 타원)와 크기·모양이 달랐다.\n */\nexport function circleToPolygon(a: Point, b: Point, count = 32): Point[] {\n\tconst cx = (a.x + b.x) / 2;\n\tconst cy = (a.y + b.y) / 2;\n\tconst rx = Math.abs(b.x - a.x) / 2;\n\tconst ry = Math.abs(b.y - a.y) / 2;\n\treturn Array.from({ length: count }, (_, index) => {\n\t\tconst angle = (index / count) * 2 * Math.PI;\n\t\treturn {\n\t\t\tx: cx + rx * Math.cos(angle),\n\t\t\ty: cy + ry * Math.sin(angle),\n\t\t};\n\t});\n}\n\n/**\n * 볼록 껍질(Andrew monotone chain). 입력 점들의 볼록 다각형 코너를 반시계로 반환.\n * 3점 미만이면 입력을 그대로 돌려준다(최소사각형 계산의 전처리용).\n */\nexport function convexHull(points: Point[]): Point[] {\n\tconst pts = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n\tif (pts.length <= 2) return pts;\n\tconst cross = (o: Point, a: Point, b: Point) =>\n\t\t(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n\tconst lower: Point[] = [];\n\tfor (const p of pts) {\n\t\twhile (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0)\n\t\t\tlower.pop();\n\t\tlower.push(p);\n\t}\n\tconst upper: Point[] = [];\n\tfor (let i = pts.length - 1; i >= 0; i--) {\n\t\tconst p = pts[i];\n\t\twhile (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0)\n\t\t\tupper.pop();\n\t\tupper.push(p);\n\t}\n\tlower.pop();\n\tupper.pop();\n\treturn lower.concat(upper);\n}\n\n/**\n * 최소 넓이 회전 사각형(rotating calipers). 점들을 감싸는 넓이 최소의 (기울 수 있는)\n * 사각형 4개 코너를 둘레 순서로 반환한다. OBB(회전 바운딩박스) 어시스트 결과 변환용.\n * 최소사각형의 한 변은 반드시 볼록껍질의 한 변과 평행하다는 성질을 이용한다.\n */\nexport function minAreaRect(points: Point[]): Point[] {\n\tconst hull = convexHull(points);\n\tif (hull.length < 3) return rectTo4(points);\n\tlet bestArea = Number.POSITIVE_INFINITY;\n\tlet bestCorners = rectTo4(points);\n\tfor (let i = 0; i < hull.length; i++) {\n\t\tconst a = hull[i];\n\t\tconst b = hull[(i + 1) % hull.length];\n\t\tconst len = Math.hypot(b.x - a.x, b.y - a.y) || 1;\n\t\tconst ux = (b.x - a.x) / len;\n\t\tconst uy = (b.y - a.y) / len; // 에지 방향 단위벡터(법선은 (-uy, ux))\n\t\tlet minU = Number.POSITIVE_INFINITY;\n\t\tlet maxU = Number.NEGATIVE_INFINITY;\n\t\tlet minV = Number.POSITIVE_INFINITY;\n\t\tlet maxV = Number.NEGATIVE_INFINITY;\n\t\tfor (const p of hull) {\n\t\t\tconst u = p.x * ux + p.y * uy;\n\t\t\tconst v = -p.x * uy + p.y * ux;\n\t\t\tif (u < minU) minU = u;\n\t\t\tif (u > maxU) maxU = u;\n\t\t\tif (v < minV) minV = v;\n\t\t\tif (v > maxV) maxV = v;\n\t\t}\n\t\tconst area = (maxU - minU) * (maxV - minV);\n\t\tif (area < bestArea) {\n\t\t\tbestArea = area;\n\t\t\t// (u,v) 좌표 → 원좌표 역변환: p = u*(ux,uy) + v*(-uy,ux)\n\t\t\tconst toXY = (u: number, v: number): Point => ({\n\t\t\t\tx: u * ux - v * uy,\n\t\t\t\ty: u * uy + v * ux,\n\t\t\t});\n\t\t\tbestCorners = [toXY(minU, minV), toXY(maxU, minV), toXY(maxU, maxV), toXY(minU, maxV)];\n\t\t}\n\t}\n\treturn bestCorners;\n}\n\n// ── 기울어진(회전된) 사각형 트랜스포머용 벡터/기하 ──\nexport const vsub = (a: Point, b: Point): Point => ({\n\tx: a.x - b.x,\n\ty: a.y - b.y,\n});\nexport const vdot = (a: Point, b: Point): number => a.x * b.x + a.y * b.y;\nexport const vlen = (a: Point): number => Math.hypot(a.x, a.y);\nexport const vnorm = (a: Point): Point => {\n\tconst l = vlen(a) || 1;\n\treturn { x: a.x / l, y: a.y / l };\n};\nexport const mid = (a: Point, b: Point): Point => ({\n\tx: (a.x + b.x) / 2,\n\ty: (a.y + b.y) / 2,\n});\nexport const centerOf = (pts: Point[]): Point => {\n\tconst s = pts.reduce((acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y }), {\n\t\tx: 0,\n\t\ty: 0,\n\t});\n\treturn { x: s.x / pts.length, y: s.y / pts.length };\n};\n\n// 회전 사각형 코너[tl,tr,br,bl] → 8핸들 위치(ANCHORS 순서: tl,t,tr,r,br,b,bl,l).\nexport function orientedHandles(c: Point[]): Point[] {\n\treturn [\n\t\tc[0],\n\t\tmid(c[0], c[1]),\n\t\tc[1],\n\t\tmid(c[1], c[2]),\n\t\tc[2],\n\t\tmid(c[2], c[3]),\n\t\tc[3],\n\t\tmid(c[3], c[0]),\n\t];\n}\n\n// 위쪽 변 중앙에서 바깥(로컬 위) 방향으로 떨어진 회전 핸들 위치.\nexport function rotateHandlePos(c: Point[], gap: number): Point {\n\tconst top = mid(c[0], c[1]);\n\tconst up = vnorm(vsub(c[0], c[3])); // tl - bl = 로컬 위 방향\n\treturn { x: top.x + up.x * gap, y: top.y + up.y * gap };\n}\n\n/** 회전 사각형 위변(tl→tr) 각도(라디안). */\nexport function rotatedRectAngle(points: Point[]): number {\n\tif (points.length < 2) return 0;\n\treturn Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);\n}\n\n// 로컬 박스(원점 R + 정규직교축 u,v) → 월드 코너[tl,tr,br,bl].\nexport function localBoxToCorners(box: BBox, R: Point, u: Point, v: Point): Point[] {\n\tconst pt = (lx: number, ly: number): Point => ({\n\t\tx: R.x + lx * u.x + ly * v.x,\n\t\ty: R.y + lx * u.y + ly * v.y,\n\t});\n\treturn [\n\t\tpt(box.minX, box.minY),\n\t\tpt(box.maxX, box.minY),\n\t\tpt(box.maxX, box.maxY),\n\t\tpt(box.minX, box.maxY),\n\t];\n}\n\nexport function resizeRotatedRectFromAnchor(\n\tpoints: Point[],\n\tanchor: Anchor,\n\ttarget: Point,\n): Point[] {\n\tif (points.length < 4) return points;\n\tconst origin = points[0];\n\tconst u = vnorm(vsub(points[1], points[0]));\n\tconst v = vnorm(vsub(points[3], points[0]));\n\tconst width = vdot(vsub(points[1], origin), u);\n\tconst height = vdot(vsub(points[3], origin), v);\n\tconst localTarget = vsub(target, origin);\n\tconst box = boxFromAnchor(\n\t\tanchor,\n\t\t{ minX: 0, minY: 0, maxX: width, maxY: height },\n\t\tvdot(localTarget, u),\n\t\tvdot(localTarget, v),\n\t);\n\treturn localBoxToCorners(box, origin, u, v);\n}\n\n// old bbox 안의 점들을 new bbox에 맞춰 비례 재배치(사각형·폴리곤 공용, baking 없음).\nexport function rescalePoints(points: Point[], from: BBox, to: BBox): Point[] {\n\tconst fw = from.maxX - from.minX || 1;\n\tconst fh = from.maxY - from.minY || 1;\n\tconst tw = to.maxX - to.minX;\n\tconst th = to.maxY - to.minY;\n\treturn points.map((p) => ({\n\t\tx: to.minX + ((p.x - from.minX) / fw) * tw,\n\t\ty: to.minY + ((p.y - from.minY) / fh) * th,\n\t}));\n}\n","/**\n * 에디터 UI 문자열(도메인 무관). 기본값은 한국어이며, 호스트가 `strings` prop으로\n * 부분 재정의해 i18n/제품별 문구를 주입한다. next-intl 등 프레임워크에 비종속 —\n * 호스트가 자기 번역 시스템으로 값을 만들어 넘기면 된다.\n */\nexport interface EditorStrings {\n\tcontextMenu: {\n\t\tcopy: string;\n\t\tpaste: string;\n\t\tduplicate: string;\n\t\tdelete: string;\n\t\tbringToFront: string;\n\t\tsendToBack: string;\n\t\tflipHorizontal: string;\n\t\tflipVertical: string;\n\t\teditVertices: string;\n\t\tmerge: string;\n\t\tassistExpand: string;\n\t\tassistExclude: string;\n\t\tundo: string;\n\t\tredo: string;\n\t\tzoomToSelection: string;\n\t\tselectAll: string;\n\t\tclearSelection: string;\n\t};\n\tviewSettings: {\n\t\ttitle: string;\n\t\treset: string;\n\t\tbrightness: string;\n\t\tcontrast: string;\n\t\tstrokeSize: string;\n\t\tsimplifyStrength: string;\n\t\tpixelation: string;\n\t\tcursorGuide: string;\n\t\tguideMask: string;\n\t\tregionMask: string;\n\t\tkeepZoomOnImageChange: string;\n\t\twheelZoom: string;\n\t};\n\tminimap: {\n\t\tzoomIn: string;\n\t\tzoomOut: string;\n\t\tzoom100: string;\n\t\tviewSettings: string;\n\t\ttoggleMinimap: string;\n\t};\n\timageLoading: string;\n\timageLoadError: string;\n}\n\nexport const DEFAULT_EDITOR_STRINGS: EditorStrings = {\n\tcontextMenu: {\n\t\tcopy: \"복사\",\n\t\tpaste: \"붙여넣기\",\n\t\tduplicate: \"복제\",\n\t\tdelete: \"삭제\",\n\t\tbringToFront: \"맨 앞으로\",\n\t\tsendToBack: \"맨 뒤로\",\n\t\tflipHorizontal: \"좌우 반전\",\n\t\tflipVertical: \"상하 반전\",\n\t\teditVertices: \"정점 편집\",\n\t\tmerge: \"레이블 합치기\",\n\t\tassistExpand: \"이 지점 포함하기\",\n\t\tassistExclude: \"이 지점 제외하기\",\n\t\tundo: \"실행 취소\",\n\t\tredo: \"다시 실행\",\n\t\tzoomToSelection: \"선택 영역으로 확대\",\n\t\tselectAll: \"전체 선택\",\n\t\tclearSelection: \"선택 해제\",\n\t},\n\tviewSettings: {\n\t\ttitle: \"보기 설정\",\n\t\treset: \"보기설정 초기화\",\n\t\tbrightness: \"밝기\",\n\t\tcontrast: \"대비\",\n\t\tstrokeSize: \"선 두께\",\n\t\tsimplifyStrength: \"단순화 강도\",\n\t\tpixelation: \"이미지 픽셀화\",\n\t\tcursorGuide: \"커서 가이드라인\",\n\t\tguideMask: \"가이드 마스크\",\n\t\tregionMask: \"ROI 표시\",\n\t\tkeepZoomOnImageChange: \"이미지 변경 시 줌 유지\",\n\t\twheelZoom: \"스크롤로 확대·축소\",\n\t},\n\tminimap: {\n\t\tzoomIn: \"확대\",\n\t\tzoomOut: \"축소\",\n\t\tzoom100: \"100%로 초기화\",\n\t\tviewSettings: \"보기 설정\",\n\t\ttoggleMinimap: \"미니맵 접기/펼치기\",\n\t},\n\timageLoading: \"이미지를 불러오는 중…\",\n\timageLoadError: \"이미지를 불러올 수 없습니다\",\n};\n\n/** 그룹 단위 부분 재정의(그룹 안 키도 부분 지정 가능). */\nexport type EditorStringsOverride = {\n\t[K in keyof EditorStrings]?: EditorStrings[K] extends string ? string : Partial<EditorStrings[K]>;\n};\n\nexport function mergeEditorStrings(override?: EditorStringsOverride): EditorStrings {\n\tif (!override) return DEFAULT_EDITOR_STRINGS;\n\treturn {\n\t\tcontextMenu: {\n\t\t\t...DEFAULT_EDITOR_STRINGS.contextMenu,\n\t\t\t...override.contextMenu,\n\t\t},\n\t\tviewSettings: {\n\t\t\t...DEFAULT_EDITOR_STRINGS.viewSettings,\n\t\t\t...override.viewSettings,\n\t\t},\n\t\tminimap: { ...DEFAULT_EDITOR_STRINGS.minimap, ...override.minimap },\n\t\timageLoading: override.imageLoading ?? DEFAULT_EDITOR_STRINGS.imageLoading,\n\t\timageLoadError: override.imageLoadError ?? DEFAULT_EDITOR_STRINGS.imageLoadError,\n\t};\n}\n","/**\n * Editor 도구. 어떤 도구를 노출할지는 호스트가 `tools` prop으로 주입한다\n * (구버전처럼 TASK_TYPE에서 파생하지 않는다).\n */\nexport const TOOL = {\n\tSELECT: \"SELECT\",\n\tPOLYGON: \"POLYGON\",\n\tPATH: \"PATH\",\n\tBRUSH: \"BRUSH\",\n\tRECTANGLE: \"RECTANGLE\",\n\tROTATED_RECTANGLE: \"ROTATED_RECTANGLE\",\n\tCIRCLE: \"CIRCLE\",\n\tPOINT: \"POINT\",\n\t/** AI 어시스트: 박스 프롬프트(드래그 → 추론) → 폴리곤 커밋. assistant.infer 필요. */\n\tASSISTANT_POLYGON: \"ASSISTANT_POLYGON\",\n\t/**\n\t * AI 어시스트: 박스 프롬프트(드래그 → 추론) → 추론 폴리곤의 바운딩으로 사각형 커밋.\n\t * assistant.rectResult가 \"rotatedRect\"면 최소넓이 회전사각형(OBB), 아니면 축정렬 RECT.\n\t */\n\tASSISTANT_RECT: \"ASSISTANT_RECT\",\n\t/** AI 어시스트: 포인트 프롬프트(클릭 +, alt-클릭 −). 선택 폴리곤이 있으면 refine. */\n\tASSISTANT_POINT: \"ASSISTANT_POINT\",\n} as const;\n\nexport type BuiltInTool = (typeof TOOL)[keyof typeof TOOL];\nexport type Tool = BuiltInTool | (string & {});\n\n/** 붓(스칼라) 서브모드 — 그리기/지우기. */\nexport type BrushScalarMode = \"draw\" | \"erase\";\n","/** 에디터-로컬 보기/조작 환경설정(도메인 무관). props는 초기값(default)으로만 받는다. */\nexport interface ViewSettings {\n\tbrightness: number;\n\tcontrast: number;\n\tshowCursorGuide: boolean;\n\timageSmoothing: boolean;\n\tstrokeSize: number;\n\t/** 자유선/붓→폴리곤 단순화 강도(RDP epsilon, 이미지 px). 높을수록 점이 적어짐. */\n\tsimplifyStrength: number;\n\tshowGuide: boolean;\n\tshowRegionMask: boolean;\n\tkeepZoomOnImageChange: boolean;\n\twheelZoom: boolean;\n}\n\nexport const DEFAULT_VIEW_SETTINGS: ViewSettings = {\n\tbrightness: 1,\n\tcontrast: 1,\n\tshowCursorGuide: false,\n\timageSmoothing: true,\n\tstrokeSize: 2,\n\tsimplifyStrength: 1.5,\n\tshowGuide: true,\n\tshowRegionMask: true,\n\tkeepZoomOnImageChange: false,\n\twheelZoom: true,\n};\n","import type { CSSProperties } from \"react\";\nimport type { AssistantPromptPoint } from \"../_model/props\";\nimport type { AssistantStatus } from \"../_state/useAssistant\";\n\n/**\n * AI 어시스트 오버레이. 프롬프트 포인트(+/−) 마커와 진행 표시를 그린다.\n * 결과 폴리곤은 즉시 실제 도형으로 커밋되므로 여기선 그리지 않는다.\n * 캔버스 오버레이 레이어(이미지 좌표) 안에 놓여 뷰포트를 따라가고, 마커/배지는\n * inverse-scale로 화면 크기를 일정하게 유지한다. 렌더러 무관(순수 DOM).\n */\n\nconst INV = \"var(--editor-overlay-inverse-scale, 1)\";\n\nconst POS = \"#377be2\";\nconst NEG = \"#e23c3c\";\n\nfunction Marker({ point }: { point: AssistantPromptPoint }) {\n\tconst color = point.positive ? POS : NEG;\n\tconst badge: CSSProperties = {\n\t\tposition: \"absolute\",\n\t\tleft: point.x,\n\t\ttop: point.y,\n\t\twidth: 18,\n\t\theight: 18,\n\t\tmarginLeft: -9,\n\t\tmarginTop: -9,\n\t\tborderRadius: \"50%\",\n\t\tbackground: color,\n\t\tborder: \"2px solid #fff\",\n\t\tboxShadow: \"0 0 3px rgba(0,0,0,0.5)\",\n\t\tcolor: \"#fff\",\n\t\tfontSize: 13,\n\t\tfontWeight: 700,\n\t\tlineHeight: \"14px\",\n\t\tdisplay: \"flex\",\n\t\talignItems: \"center\",\n\t\tjustifyContent: \"center\",\n\t\ttransform: `scale(${INV})`,\n\t\ttransformOrigin: \"center\",\n\t};\n\treturn <div style={badge}>{point.positive ? \"+\" : \"−\"}</div>;\n}\n\nexport function AssistantOverlay({\n\timage,\n\tpoints,\n\tboxes,\n\tstatus,\n}: {\n\timage: { w: number; h: number };\n\tpoints: AssistantPromptPoint[];\n\t/** 진행 중인 박스 프롬프트들(병렬 요청 — 각각 shimmer 표시). */\n\tboxes: { x: number; y: number; width: number; height: number }[];\n\tstatus: AssistantStatus;\n}) {\n\treturn (\n\t\t<div\n\t\t\tstyle={{\n\t\t\t\tposition: \"absolute\",\n\t\t\t\tleft: 0,\n\t\t\t\ttop: 0,\n\t\t\t\twidth: image.w,\n\t\t\t\theight: image.h,\n\t\t\t\tpointerEvents: \"none\",\n\t\t\t}}\n\t\t>\n\t\t\t<style>{`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}</style>\n\t\t\t{boxes.map((box, i) => (\n\t\t\t\t// 추론 중 박스 영역마다 좌↔우 shimmer 스윕(옵스 LabelAssistantProgress 이식).\n\t\t\t\t<div\n\t\t\t\t\tkey={`box-${i}-${box.x}-${box.y}-${box.width}-${box.height}`}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\tleft: box.x,\n\t\t\t\t\t\ttop: box.y,\n\t\t\t\t\t\twidth: box.width,\n\t\t\t\t\t\theight: box.height,\n\t\t\t\t\t\tboxSizing: \"border-box\",\n\t\t\t\t\t\tborder:\n\t\t\t\t\t\t\t\"calc(2px * var(--editor-overlay-inverse-scale, 1)) solid rgba(255,255,255,0.9)\",\n\t\t\t\t\t\tbackgroundImage:\n\t\t\t\t\t\t\t\"linear-gradient(90deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0.10) 100%)\",\n\t\t\t\t\t\tbackgroundSize: \"200% 100%\",\n\t\t\t\t\t\tanimation: \"editorv2-assistant-shimmer 1.4s linear infinite\",\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t))}\n\t\t\t{/* +/− 마커는 포인트 추론 진행 중에만(박스 pending으로 오버레이가 떠 있을 때\n 이전 세션 점이 남아 보이지 않도록). 진행 표시는 shimmer와 하단 툴바 전환이\n 담당 — 별도 스피너 필은 두지 않는다. */}\n\t\t\t{status === \"loading\" &&\n\t\t\t\tpoints.map((pt, i) => <Marker key={`pt-${i}-${pt.x}-${pt.y}`} point={pt} />)}\n\t\t</div>\n\t);\n}\n","import { Menu } from \"../../Menu\";\nimport type { ContextMenuItem } from \"../_model/props\";\n\nexport type { ContextMenuItem };\n\n/**\n * 구분선 정규화 — 선두/말미 제거 + 연속 구분선 접기.\n * 호스트가 getContextMenuItems로 항목을 걸러내면 그룹 사이 구분선만 줄줄이 남을 수\n * 있어서, 렌더 직전에 방어적으로 정리한다(호스트 필터는 항목만 신경 쓰면 된다).\n */\nfunction normalizeItems(items: ContextMenuItem[]): ContextMenuItem[] {\n\tconst out: ContextMenuItem[] = [];\n\tfor (const item of items) {\n\t\tif (\"separator\" in item) {\n\t\t\tif (!out.length || \"separator\" in out[out.length - 1]) continue;\n\t\t\tout.push(item);\n\t\t} else {\n\t\t\tout.push(item);\n\t\t}\n\t}\n\twhile (out.length && \"separator\" in out[out.length - 1]) out.pop();\n\treturn out;\n}\n\n/**\n * 캔버스 우클릭 컨텍스트 메뉴(도메인 무관). 항목/위치는 호출부가 결정한다.\n * @aivex/ui Menu(Radix Dropdown)를 커서 위치의 0크기 트리거에 앵커해 띄운다.\n * 바깥 클릭·Escape·스크롤 닫힘은 Radix가 onOpenChange로 처리한다(비모달).\n */\nexport function ContextMenu({\n\tx,\n\ty,\n\titems: rawItems,\n\tonClose,\n}: {\n\tx: number;\n\ty: number;\n\titems: ContextMenuItem[];\n\tonClose: () => void;\n}) {\n\tconst items = normalizeItems(rawItems);\n\treturn (\n\t\t<Menu\n\t\t\topen\n\t\t\tmodal={false}\n\t\t\tonOpenChange={(open) => {\n\t\t\t\tif (!open) onClose();\n\t\t\t}}\n\t\t>\n\t\t\t<Menu.Trigger asChild>\n\t\t\t\t{/* 커서 위치의 0크기 앵커. Content가 이 지점 기준으로 뜬다. */}\n\t\t\t\t<span aria-hidden style={{ position: \"absolute\", left: x, top: y, width: 0, height: 0 }} />\n\t\t\t</Menu.Trigger>\n\t\t\t<Menu.Content\n\t\t\t\tside=\"bottom\"\n\t\t\t\talign=\"start\"\n\t\t\t\tsideOffset={2}\n\t\t\t\tcollisionPadding={8}\n\t\t\t\t// 메뉴가 위아래 어디에도 다 안 들어갈 만큼 길면 Radix flip/shift로는\n\t\t\t\t// 부족하다 — 가용 높이로 클램프하고 내부 스크롤로 넘긴다.\n\t\t\t\tstyle={{\n\t\t\t\t\tmaxHeight: \"var(--radix-dropdown-menu-content-available-height)\",\n\t\t\t\t\toverflowY: \"auto\",\n\t\t\t\t}}\n\t\t\t\tonContextMenu={(e) => e.preventDefault()}\n\t\t\t\tonCloseAutoFocus={(e) => e.preventDefault()}\n\t\t\t>\n\t\t\t\t{/* shrink-0: Content(flex-col)가 가용 높이로 클램프될 때 항목이\n 눌리는 대신 overflow 스크롤이 생기도록. */}\n\t\t\t\t{items.map((item, i) => {\n\t\t\t\t\tif (\"separator\" in item) {\n\t\t\t\t\t\treturn <Menu.Separator key={`sep-${i}`} className=\"aivex:shrink-0\" />;\n\t\t\t\t\t}\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<Menu.Item\n\t\t\t\t\t\t\tkey={item.label}\n\t\t\t\t\t\t\tdanger={item.danger}\n\t\t\t\t\t\t\tdisabled={item.disabled}\n\t\t\t\t\t\t\tclassName=\"aivex:shrink-0\"\n\t\t\t\t\t\t\tonSelect={() => item.onClick()}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className=\"aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6\">\n\t\t\t\t\t\t\t\t<span className=\"aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5\">\n\t\t\t\t\t\t\t\t\t{item.icon}\n\t\t\t\t\t\t\t\t\t<span className=\"aivex:truncate\">{item.label}</span>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t{item.shortcut && <Menu.Shortcut>{item.shortcut}</Menu.Shortcut>}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</Menu.Item>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t</Menu.Content>\n\t\t</Menu>\n\t);\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * 마우스 위치에 십자 가이드라인을 그리는 오버레이(도메인 무관).\n * 부모(컨테이너)를 채우고 pointer-events 없음 → 캔버스 상호작용 방해 안 함.\n * 고빈도(mousemove)라 React state 없이 line ref를 명령형 갱신.\n */\nexport function CursorGuide({ color = \"#1e88e5\" }: { color?: string }) {\n\tconst rootRef = useRef<HTMLDivElement>(null);\n\tconst vRef = useRef<HTMLDivElement>(null);\n\tconst hRef = useRef<HTMLDivElement>(null);\n\n\tuseEffect(() => {\n\t\tconst root = rootRef.current;\n\t\tconst v = vRef.current;\n\t\tconst h = hRef.current;\n\t\tif (!root || !v || !h) return;\n\n\t\tconst onMove = (e: MouseEvent) => {\n\t\t\tconst r = root.getBoundingClientRect();\n\t\t\tconst x = e.clientX - r.left;\n\t\t\tconst y = e.clientY - r.top;\n\t\t\tif (x < 0 || y < 0 || x > r.width || y > r.height) {\n\t\t\t\tv.style.display = \"none\";\n\t\t\t\th.style.display = \"none\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tv.style.display = \"block\";\n\t\t\th.style.display = \"block\";\n\t\t\tv.style.transform = `translateX(${x}px)`;\n\t\t\th.style.transform = `translateY(${y}px)`;\n\t\t};\n\t\tconst onLeave = () => {\n\t\t\tv.style.display = \"none\";\n\t\t\th.style.display = \"none\";\n\t\t};\n\n\t\twindow.addEventListener(\"mousemove\", onMove);\n\t\troot.parentElement?.addEventListener(\"mouseleave\", onLeave);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"mousemove\", onMove);\n\t\t\troot.parentElement?.removeEventListener(\"mouseleave\", onLeave);\n\t\t};\n\t}, []);\n\n\treturn (\n\t\t<div\n\t\t\tref={rootRef}\n\t\t\tclassName=\"aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden\"\n\t\t>\n\t\t\t<div\n\t\t\t\tref={vRef}\n\t\t\t\tstyle={{\n\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\ttop: 0,\n\t\t\t\t\tleft: 0,\n\t\t\t\t\twidth: 1,\n\t\t\t\t\theight: \"100%\",\n\t\t\t\t\tbackground: color,\n\t\t\t\t\topacity: 0.6,\n\t\t\t\t\tdisplay: \"none\",\n\t\t\t\t}}\n\t\t\t/>\n\t\t\t<div\n\t\t\t\tref={hRef}\n\t\t\t\tstyle={{\n\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\ttop: 0,\n\t\t\t\t\tleft: 0,\n\t\t\t\t\twidth: \"100%\",\n\t\t\t\t\theight: 1,\n\t\t\t\t\tbackground: color,\n\t\t\t\t\topacity: 0.6,\n\t\t\t\t\tdisplay: \"none\",\n\t\t\t\t}}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","import type { ReactNode } from \"react\";\nimport { DEFAULT_EDITOR_STRINGS } from \"../_model/strings\";\n\n/**\n * 이미지 로딩/에러 상태 오버레이. 에디터 영역 전체를 덮는다.\n * 호스트가 renderImageState로 커스텀하지 않으면 기본 스피너/에러 메시지를 그린다.\n */\nexport function ImageStateOverlay({\n\tstatus,\n\trender,\n\tloadingLabel = DEFAULT_EDITOR_STRINGS.imageLoading,\n\terrorLabel = DEFAULT_EDITOR_STRINGS.imageLoadError,\n}: {\n\tstatus: \"loading\" | \"error\";\n\trender?: (status: \"loading\" | \"error\") => ReactNode;\n\tloadingLabel?: string;\n\terrorLabel?: string;\n}) {\n\treturn (\n\t\t<div\n\t\t\t// e2e가 이미지 로딩 완료를 기다리는 앵커(로딩/에러 중에만 존재).\n\t\t\tdata-track-id={status === \"loading\" ? \"editor-image-loading-wrap\" : \"editor-image-error-wrap\"}\n\t\t\tstyle={{\n\t\t\t\tposition: \"absolute\",\n\t\t\t\tinset: 0,\n\t\t\t\tdisplay: \"flex\",\n\t\t\t\talignItems: \"center\",\n\t\t\t\tjustifyContent: \"center\",\n\t\t\t\tbackground: status === \"error\" ? \"rgba(13,13,18,1)\" : \"rgba(13,13,18,0.6)\",\n\t\t\t\tbackdropFilter: status === \"loading\" ? \"blur(2px)\" : undefined,\n\t\t\t\tcolor: \"#fff\",\n\t\t\t\tfontFamily: \"Pretendard, sans-serif\",\n\t\t\t\tpointerEvents: status === \"error\" ? \"auto\" : \"none\",\n\t\t\t}}\n\t\t>\n\t\t\t{render ? (\n\t\t\t\trender(status)\n\t\t\t) : status === \"loading\" ? (\n\t\t\t\t<div\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tdisplay: \"flex\",\n\t\t\t\t\t\talignItems: \"center\",\n\t\t\t\t\t\tgap: 10,\n\t\t\t\t\t\tfontSize: 13,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<span\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\twidth: 18,\n\t\t\t\t\t\t\theight: 18,\n\t\t\t\t\t\t\tborderRadius: \"50%\",\n\t\t\t\t\t\t\tborder: \"2px solid rgba(255,255,255,0.3)\",\n\t\t\t\t\t\t\tborderTopColor: \"#fff\",\n\t\t\t\t\t\t\tanimation: \"editorv2-image-spin 0.7s linear infinite\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n\t\t\t\t\t{loadingLabel}\n\t\t\t\t\t<style>{`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`}</style>\n\t\t\t\t</div>\n\t\t\t) : (\n\t\t\t\t<div style={{ textAlign: \"center\", opacity: 0.85 }}>\n\t\t\t\t\t<div style={{ fontSize: 28, marginBottom: 6 }}>⚠</div>\n\t\t\t\t\t<div style={{ fontSize: 13 }}>{errorLabel}</div>\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","// Editor 시각/상호작용 상수(화면 px 기준 다수). 컴포넌트·훅 공용.\n\nexport const MIN_SCALE = 0.1;\nexport const MAX_SCALE = 10;\nexport const ZOOM_FACTOR = 1.1;\nexport const POINT_RADIUS = 5; // 점 도형 화면상 반경(px).\nexport const HANDLE_RADIUS = 5; // 꼭짓점 핸들 화면상 반경(px).\nexport const HANDLE_SQUARE = 8; // 바운딩박스 핸들 화면상 한 변(px).\nexport const HANDLE_NAME = \"v2-handle\"; // 핸들 식별(선택 해제 가드용).\nexport const FIXED_NAME = \"v2-fixed\"; // 줌과 무관히 화면상 크기 고정(핸들+점). 줌 시 역-스케일.\nexport const HANDLE_COLOR = \"#1e88e5\";\nexport const POLY_CLOSE_PX = 12; // 폴리곤 첫 꼭짓점 근처(화면 px) 클릭 시 닫기.\nexport const ROTATE_GAP_PX = 28; // 회전 핸들이 bbox 위로 떨어진 거리(화면 px).\nexport const NUDGE_PX = 1; // 방향키 이동 거리(이미지 px).\nexport const NUDGE_BIG_PX = 10; // Shift+방향키 이동 거리.\nexport const DUPLICATE_OFFSET_PX = 12; // 복제 시 어긋나는 거리.\nexport const ROTATE_SNAP_RAD = Math.PI / 12; // Shift 회전 스냅(15°).\nexport const MINIMAP_SIZE = 180; // 미니맵 정사각 한 변(px). 이미지는 레터박스로 중앙 정렬.\nexport const MINIMAP_VP_STROKE = \"#00ff00\"; // 뷰포트 사각형 색(구버전과 동일).\nexport const MINIMAP_VP_FILL = \"rgba(0, 255, 0, 0.1)\";\nexport const DEFAULT_COLOR = \"#00e5ff\";\nexport const SELECTED_COLOR = \"#ffffff\";\nexport const STROKE_SIZE = 2; // 도형 선 두께(화면 px). 구버전 옵스 기본값과 동일.\nexport const SELECTION_BORDER_COLOR = \"#669DEF\"; // 선택 도형 테두리(구버전 TRANSFORMER.BORDER_COLOR).\nexport const SELECTION_BORDER_PAD = 3; // 선택 테두리를 도형 bbox 바깥으로 띄우는 거리(화면 px).\nexport const SELECTION_AREA_COLOR = \"#669DEF\";\nexport const SELECTION_AREA_FILL_ALPHA = 0.1;\nexport const FILL_ALPHA_HEX = \"20\"; // 채움 색 알파(구버전 `${color}20` = 약 12.5%).\nexport const FILL_ALPHA = 0x20 / 0xff;\nexport const ROI_BORDER_COLOR = \"#ffffff\"; // ROI/제외영역 점선 테두리 색.\nexport const ROI_BORDER_WIDTH = 2; // ROI 테두리 두께(화면 px — 줌과 무관하게 고정).\nexport const ROI_BORDER_DASH: [number, number] = [6, 6]; // ROI 점선 패턴(화면 px).\nexport const STRIPED_OPACITY = 0.7;\nexport const STRIPED_STROKE_SCALE = 2.5;\nexport const STRIPED_DASH_GAP_SCALE = 2;\n","import {\n\tDEFAULT_COLOR,\n\tFILL_ALPHA,\n\tPOINT_RADIUS,\n\tSTRIPED_DASH_GAP_SCALE,\n\tSTRIPED_OPACITY,\n\tSTRIPED_STROKE_SCALE,\n\tSTROKE_SIZE,\n} from \"../_constants\";\nimport type { EditorShape } from \"./geometry\";\n\nexport interface ResolvedShapeRenderStyle {\n\tcolor: string;\n\tstrokeWidth: number;\n\topacity: number;\n\tfillAlpha: number;\n\tfillVisible: boolean;\n\tdash?: number[];\n\tpointRadius: number;\n}\n\nexport interface ShapeRenderStyleDefaults {\n\tstrokeWidth?: number;\n\tpointRadius?: number;\n}\n\nexport function resolveShapeRenderStyle(\n\tshape: EditorShape,\n\tdefaults: ShapeRenderStyleDefaults = {},\n): ResolvedShapeRenderStyle {\n\tconst color = shape.style?.color ?? DEFAULT_COLOR;\n\tconst striped = !!shape.readOnly;\n\tconst baseStrokeWidth = shape.style?.strokeWidth ?? defaults.strokeWidth ?? STROKE_SIZE;\n\tconst strokeWidth = striped ? baseStrokeWidth * STRIPED_STROKE_SCALE : baseStrokeWidth;\n\tconst opacity = striped ? STRIPED_OPACITY : (shape.style?.opacity ?? 1);\n\tconst fillAlpha = shape.style?.fillOpacity ?? FILL_ALPHA;\n\tconst dash =\n\t\tshape.style?.dash ??\n\t\t(striped ? [strokeWidth, strokeWidth * STRIPED_DASH_GAP_SCALE] : undefined);\n\n\treturn {\n\t\tcolor,\n\t\tstrokeWidth,\n\t\topacity,\n\t\tfillAlpha,\n\t\tfillVisible: !!shape.style?.filled,\n\t\tdash,\n\t\tpointRadius: shape.style?.pointRadius ?? defaults.pointRadius ?? POINT_RADIUS,\n\t};\n}\n\nexport function colorWithAlpha(color: string, alpha: number): string {\n\tconst clampedAlpha = Math.max(0, Math.min(1, alpha));\n\tconst hex = color.trim().replace(\"#\", \"\");\n\tif (hex.length === 3 || hex.length === 6) {\n\t\tconst normalized = hex.length === 3 ? hex.replace(/./g, (char) => char + char) : hex;\n\t\tconst value = Number.parseInt(normalized, 16);\n\t\tif (!Number.isNaN(value)) {\n\t\t\tconst r = (value >> 16) & 255;\n\t\t\tconst g = (value >> 8) & 255;\n\t\t\tconst b = value & 255;\n\t\t\treturn `rgba(${r}, ${g}, ${b}, ${clampedAlpha})`;\n\t\t}\n\t}\n\treturn color;\n}\n","import type { EditorShape } from \"../_model/geometry\";\nimport { getBBox, SHAPE_TYPE } from \"../_model/geometry\";\nimport { resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\n\n// 미니맵용 도형 1개를 이미지 좌표 그대로 SVG로 렌더(부모 SVG viewBox가 축소 담당,\n// stroke는 non-scaling으로 화면 px 고정). 점 도형만 채움, 나머지는 외곽선.\nexport function MinimapShape<TMeta>({\n\tshape,\n\tstrokeSize,\n\tregister,\n}: {\n\tshape: EditorShape<TMeta>;\n\tstrokeSize?: number;\n\tregister?: (id: string, el: SVGElement | null) => void;\n}) {\n\tconst { type, points } = shape;\n\tconst style = resolveShapeRenderStyle(shape, { strokeWidth: strokeSize });\n\tconst ref = (el: SVGElement | null) => register?.(shape.id, el);\n\tconst common = {\n\t\tref,\n\t\tstroke: style.color,\n\t\tstrokeWidth: style.strokeWidth,\n\t\tstrokeDasharray: style.dash?.join(\" \"),\n\t\topacity: style.opacity,\n\t\tfill: style.fillVisible && type !== SHAPE_TYPE.LINE ? style.color : \"none\",\n\t\tfillOpacity: style.fillAlpha,\n\t\tvectorEffect: \"non-scaling-stroke\" as const,\n\t};\n\tif (type === SHAPE_TYPE.POINT) {\n\t\treturn (\n\t\t\t<circle\n\t\t\t\tref={ref}\n\t\t\t\tcx={points[0].x}\n\t\t\t\tcy={points[0].y}\n\t\t\t\tr={style.pointRadius}\n\t\t\t\tfill={style.color}\n\t\t\t\topacity={style.opacity}\n\t\t\t/>\n\t\t);\n\t}\n\tif (type === SHAPE_TYPE.RECTANGLE || type === SHAPE_TYPE.ELLIPSE) {\n\t\tconst b = getBBox(points);\n\t\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\t\treturn (\n\t\t\t\t<ellipse\n\t\t\t\t\tcx={(b.minX + b.maxX) / 2}\n\t\t\t\t\tcy={(b.minY + b.maxY) / 2}\n\t\t\t\t\trx={(b.maxX - b.minX) / 2}\n\t\t\t\t\try={(b.maxY - b.minY) / 2}\n\t\t\t\t\t{...common}\n\t\t\t\t/>\n\t\t\t);\n\t\t}\n\t\treturn (\n\t\t\t<rect x={b.minX} y={b.minY} width={b.maxX - b.minX} height={b.maxY - b.minY} {...common} />\n\t\t);\n\t}\n\tconst pts = points.map((p) => `${p.x},${p.y}`).join(\" \");\n\tif (type === SHAPE_TYPE.LINE) return <polyline points={pts} {...common} />;\n\treturn <polygon points={pts} {...common} />; // POLYGON, ROTATED_RECTANGLE\n}\n","import type { CSSProperties } from \"react\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\n\n/**\n * 영역 마스크 오버레이 SVG — 미니맵용.\n * 보이는 영역 밖을 딤으로 덮고, 가림 영역은 다시 덮으며, 경계선은 리졸브된\n * 윤곽 선분만 점선으로 그린다(미니맵 축소 특성상 색은 단일 흰색).\n * 좌표계는 이미지 좌표(viewBox=image), 화면 크기/선 두께는 호출부가 정한다.\n */\nexport function RegionOverlay({\n\timage,\n\tregion,\n\tmaskId,\n\twidth,\n\theight,\n\tstrokeWidth,\n\tstrokeDasharray,\n\tstyle,\n}: {\n\timage: { w: number; h: number };\n\tregion: RegionOverlayData;\n\tmaskId: string;\n\twidth: number;\n\theight: number;\n\tstrokeWidth: number | string;\n\tstrokeDasharray: string;\n\tstyle?: CSSProperties;\n}) {\n\tconst outlines = [...region.visibleOutline, ...region.occludedOutline];\n\treturn (\n\t\t<svg\n\t\t\twidth={width}\n\t\t\theight={height}\n\t\t\tviewBox={`0 0 ${image.w} ${image.h}`}\n\t\t\tstyle={style}\n\t\t\taria-hidden\n\t\t>\n\t\t\t<defs>\n\t\t\t\t<mask id={maskId}>\n\t\t\t\t\t<rect x={0} y={0} width={image.w} height={image.h} fill=\"white\" />\n\t\t\t\t\t{region.rects.map((r, i) => (\n\t\t\t\t\t\t<rect key={r.id ?? `area-${i}`} x={r.x} y={r.y} width={r.w} height={r.h} fill=\"black\" />\n\t\t\t\t\t))}\n\t\t\t\t\t{region.zones.map((z, i) => (\n\t\t\t\t\t\t<polygon\n\t\t\t\t\t\t\tkey={`occ-${i}`}\n\t\t\t\t\t\t\tpoints={z.points.map((p) => `${p.x},${p.y}`).join(\" \")}\n\t\t\t\t\t\t\tfill=\"white\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t</mask>\n\t\t\t</defs>\n\t\t\t<rect\n\t\t\t\tx={0}\n\t\t\t\ty={0}\n\t\t\t\twidth={image.w}\n\t\t\t\theight={image.h}\n\t\t\t\tfill={region.dim.color}\n\t\t\t\tfillOpacity={region.dim.opacity}\n\t\t\t\tmask={`url(#${maskId})`}\n\t\t\t/>\n\t\t\t{outlines.length > 0 && (\n\t\t\t\t<path\n\t\t\t\t\td={outlines.map(([a, b]) => `M${a.x} ${a.y}L${b.x} ${b.y}`).join(\"\")}\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"#fff\"\n\t\t\t\t\tstrokeWidth={strokeWidth}\n\t\t\t\t\tstrokeDasharray={strokeDasharray}\n\t\t\t\t\tvectorEffect=\"non-scaling-stroke\"\n\t\t\t\t/>\n\t\t\t)}\n\t\t</svg>\n\t);\n}\n","import { useEffect } from \"react\";\nimport { Button } from \"../../Button\";\nimport { Divider } from \"../../Divider\";\nimport { Slider } from \"../../Slider\";\nimport { Switch } from \"../../Switch\";\nimport { DEFAULT_EDITOR_STRINGS, type EditorStrings } from \"../_model/strings\";\nimport { DEFAULT_VIEW_SETTINGS, type ViewSettings } from \"../_model/viewSettings\";\n\nexport {\n\tDEFAULT_VIEW_SETTINGS,\n\ttype ViewSettings,\n} from \"../_model/viewSettings\";\n\n// 이 패널은 220px 폭의 좁은 팝오버라 Slider 기본 크기(썸 24px/트랙 8px)가 상대적으로\n// 커 보인다. 디자인시스템 Slider 자체는 그대로 두고 이 패널에서만 축소한다.\nconst COMPACT_SLIDER_PROPS = {\n\ttrackRootClassName: \"aivex:h-1.5\",\n\tthumbClassName: \"aivex:h-4 aivex:w-4 aivex:border\",\n};\n\n/**\n * 미니맵 기어 버튼에서 열리는 보기 설정 팝오버(도메인 무관).\n * 바깥 클릭/Esc로 닫힘. 값은 호출부가 소유하고 onChange로 부분 갱신.\n * 컨트롤은 @aivex/ui(Button/Slider/Switch/Divider)로 렌더한다.\n */\nexport function SettingsPanel({\n\tvalue,\n\tonChange,\n\tonClose,\n\tlabels = DEFAULT_EDITOR_STRINGS.viewSettings,\n}: {\n\tvalue: ViewSettings;\n\tonChange: (patch: Partial<ViewSettings>) => void;\n\tonClose: () => void;\n\t/** UI 문자열. 기본 한국어. */\n\tlabels?: EditorStrings[\"viewSettings\"];\n}) {\n\tuseEffect(() => {\n\t\tconst onKey = (e: KeyboardEvent) => {\n\t\t\tif (e.key === \"Escape\") onClose();\n\t\t};\n\t\t// 바깥 클릭 시 닫기 — 패널 자신은 루트 onPointerDown에서 전파를 막고,\n\t\t// 기어 토글 버튼도 전파를 막아(Minimap) 닫힘→재토글 이중 발화가 없다.\n\t\tconst onOutsidePointerDown = () => onClose();\n\t\twindow.addEventListener(\"keydown\", onKey);\n\t\twindow.addEventListener(\"pointerdown\", onOutsidePointerDown);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"keydown\", onKey);\n\t\t\twindow.removeEventListener(\"pointerdown\", onOutsidePointerDown);\n\t\t};\n\t}, [onClose]);\n\n\treturn (\n\t\t<div\n\t\t\tclassName=\"aivex:absolute aivex:bottom-full aivex:left-0 aivex:mb-1 aivex:w-[220px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-3 aivex:text-text-primary aivex:text-xs aivex:shadow-lg\"\n\t\t\tonPointerDown={(e) => e.stopPropagation()}\n\t\t>\n\t\t\t<div className=\"aivex:mb-2 aivex:flex aivex:items-center aivex:justify-between\">\n\t\t\t\t<span className=\"aivex:font-semibold aivex:text-text-secondary\">{labels.title}</span>\n\t\t\t\t<Button variant=\"ghost\" size=\"sm\" onClick={() => onChange({ ...DEFAULT_VIEW_SETTINGS })}>\n\t\t\t\t\t{labels.reset}\n\t\t\t\t</Button>\n\t\t\t</div>\n\n\t\t\t<Row label={`${labels.brightness} ${value.brightness.toFixed(2)}`}>\n\t\t\t\t<Slider\n\t\t\t\t\tmin={0}\n\t\t\t\t\tmax={3}\n\t\t\t\t\tstep={0.05}\n\t\t\t\t\tvalue={[value.brightness]}\n\t\t\t\t\tonValueChange={([v]) => onChange({ brightness: v })}\n\t\t\t\t\t{...COMPACT_SLIDER_PROPS}\n\t\t\t\t/>\n\t\t\t</Row>\n\t\t\t<Row label={`${labels.contrast} ${value.contrast.toFixed(2)}`}>\n\t\t\t\t<Slider\n\t\t\t\t\tmin={0}\n\t\t\t\t\tmax={3}\n\t\t\t\t\tstep={0.05}\n\t\t\t\t\tvalue={[value.contrast]}\n\t\t\t\t\tonValueChange={([v]) => onChange({ contrast: v })}\n\t\t\t\t\t{...COMPACT_SLIDER_PROPS}\n\t\t\t\t/>\n\t\t\t</Row>\n\t\t\t<Row label={`${labels.strokeSize} ${value.strokeSize}`}>\n\t\t\t\t<Slider\n\t\t\t\t\tmin={1}\n\t\t\t\t\tmax={10}\n\t\t\t\t\tstep={0.5}\n\t\t\t\t\tvalue={[value.strokeSize]}\n\t\t\t\t\tonValueChange={([v]) => onChange({ strokeSize: v })}\n\t\t\t\t\t{...COMPACT_SLIDER_PROPS}\n\t\t\t\t/>\n\t\t\t</Row>\n\t\t\t<Row label={`${labels.simplifyStrength} ${value.simplifyStrength}`}>\n\t\t\t\t<Slider\n\t\t\t\t\tmin={0.5}\n\t\t\t\t\tmax={5}\n\t\t\t\t\tstep={0.5}\n\t\t\t\t\tvalue={[value.simplifyStrength]}\n\t\t\t\t\tonValueChange={([v]) => onChange({ simplifyStrength: v })}\n\t\t\t\t\t{...COMPACT_SLIDER_PROPS}\n\t\t\t\t/>\n\t\t\t</Row>\n\n\t\t\t<div className=\"aivex:my-2\">\n\t\t\t\t<Divider />\n\t\t\t</div>\n\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.pixelation}\n\t\t\t\tchecked={!value.imageSmoothing}\n\t\t\t\tonChange={(v) => onChange({ imageSmoothing: !v })}\n\t\t\t/>\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.cursorGuide}\n\t\t\t\tchecked={value.showCursorGuide}\n\t\t\t\tonChange={(v) => onChange({ showCursorGuide: v })}\n\t\t\t/>\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.guideMask}\n\t\t\t\tchecked={value.showGuide}\n\t\t\t\tonChange={(v) => onChange({ showGuide: v })}\n\t\t\t/>\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.regionMask}\n\t\t\t\tchecked={value.showRegionMask}\n\t\t\t\tonChange={(v) => onChange({ showRegionMask: v })}\n\t\t\t/>\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.keepZoomOnImageChange}\n\t\t\t\tchecked={value.keepZoomOnImageChange}\n\t\t\t\tonChange={(v) => onChange({ keepZoomOnImageChange: v })}\n\t\t\t/>\n\t\t\t<Toggle\n\t\t\t\tlabel={labels.wheelZoom}\n\t\t\t\tchecked={value.wheelZoom}\n\t\t\t\tonChange={(v) => onChange({ wheelZoom: v })}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\nfunction Row({ label, children }: { label: string; children: React.ReactNode }) {\n\treturn (\n\t\t<div className=\"aivex:mb-2 aivex:block\">\n\t\t\t<span className=\"aivex:mb-1 aivex:block aivex:text-text-secondary\">{label}</span>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n\nfunction Toggle({\n\tlabel,\n\tchecked,\n\tonChange,\n}: {\n\tlabel: string;\n\tchecked: boolean;\n\tonChange: (v: boolean) => void;\n}) {\n\treturn (\n\t\t<div className=\"aivex:flex aivex:items-center aivex:justify-between aivex:py-1\">\n\t\t\t<span>{label}</span>\n\t\t\t<Switch size=\"sm\" checked={checked} onCheckedChange={onChange} />\n\t\t</div>\n\t);\n}\n","import type { RefObject } from \"react\";\nimport { Button } from \"../../Button\";\nimport { CaretLineDownIcon, CaretLineUpIcon, MinusIcon, PlusIcon, SettingIcon } from \"../../Icon\";\nimport { type EditorShape, isShapeVisible, sortShapesForRender } from \"../_model/geometry\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\nimport { DEFAULT_EDITOR_STRINGS, type EditorStrings } from \"../_model/strings\";\nimport type { ViewSettings } from \"../_model/viewSettings\";\nimport type { MinimapNavigation } from \"../_state/useMinimapNavigation\";\nimport { MinimapShape } from \"./MinimapShape\";\nimport { RegionOverlay } from \"./RegionOverlay\";\nimport { SettingsPanel } from \"./SettingsPanel\";\n\n/**\n * 미니맵 패널(좌하단) — 축소 이미지 + 가이드마스크/ROI 오버레이 + 도형 미리보기 +\n * 현재 뷰포트 사각형 + 줌 컨트롤 바 + 보기설정 팝오버.\n *\n * 내비게이션 로직(패닝/줌)은 useMinimapNavigation(nav)에, 뷰포트 사각형/줌라벨의 실시간\n * 갱신은 호스트의 syncMinimap이 rectRef/zoomLabelRef로 담당한다. 여긴 순수 표시.\n */\nexport function Minimap<TMeta>({\n\timage,\n\timageUrl,\n\timageVisible = true,\n\tmaskDataUrl,\n\tregion,\n\troiMaskId,\n\tshapes,\n\tview,\n\tonChangeView,\n\tnav,\n\tregisterShape,\n\trectRef,\n\tzoomLabelRef,\n\tonZoom100,\n\topen,\n\tonToggleOpen,\n\tshowSettings = true,\n\tsettingsOpen,\n\tonToggleSettings,\n\tonCloseSettings,\n\tlabels = DEFAULT_EDITOR_STRINGS.minimap,\n\tsettingsLabels,\n}: {\n\timage: { w: number; h: number };\n\timageUrl: string;\n\t/** 메인 캔버스와 동기화된 표시 여부 — 전환 시 즉시 숨기고 로드 후 페이드인. */\n\timageVisible?: boolean;\n\tmaskDataUrl: string | null;\n\t/** 리졸브된 영역 마스크 오버레이(딤·윤곽 벡터). */\n\tregion?: RegionOverlayData | null;\n\troiMaskId: string;\n\tshapes: EditorShape<TMeta>[];\n\tview: ViewSettings;\n\tonChangeView: (patch: Partial<ViewSettings>) => void;\n\tnav: MinimapNavigation;\n\tregisterShape: (id: string, el: SVGElement | null) => void;\n\trectRef: RefObject<HTMLDivElement | null>;\n\tzoomLabelRef: RefObject<HTMLSpanElement | null>;\n\tonZoom100: () => void;\n\topen: boolean;\n\tonToggleOpen: () => void;\n\t/** 보기설정(기어) 버튼 표시 여부(기본 true). */\n\tshowSettings?: boolean;\n\tsettingsOpen: boolean;\n\tonToggleSettings: () => void;\n\tonCloseSettings: () => void;\n\t/** UI 문자열(aria/버튼). 기본 한국어. */\n\tlabels?: EditorStrings[\"minimap\"];\n\t/** 설정 팝오버 문자열. 기본 한국어. */\n\tsettingsLabels?: EditorStrings[\"viewSettings\"];\n}) {\n\tconst { offX, offY, dispW, dispH, zoomCentered } = nav;\n\tconst imgStyle = {\n\t\tposition: \"absolute\" as const,\n\t\tleft: offX,\n\t\ttop: offY,\n\t\twidth: dispW,\n\t\theight: dispH,\n\t};\n\treturn (\n\t\t<div className=\"aivex:absolute aivex:bottom-2 aivex:left-2 aivex:w-[188px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-[4px] aivex:shadow-lg\">\n\t\t\t<div\n\t\t\t\tclassName={`aivex:overflow-hidden aivex:rounded-[4px] aivex:transition-all aivex:duration-200 aivex:ease-in-out ${open ? \"aivex:mb-1 aivex:max-h-[180px] aivex:opacity-100\" : \"aivex:max-h-0 aivex:opacity-0\"}`}\n\t\t\t>\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"aivex:relative aivex:h-[180px] aivex:w-[180px] aivex:cursor-grab aivex:touch-none aivex:overflow-hidden aivex:rounded-[4px] aivex:bg-black aivex:active:cursor-grabbing\"\n\t\t\t\t\tonPointerDown={nav.handleMinimapPointerDown}\n\t\t\t\t\tonPointerMove={nav.handleMinimapPointerMove}\n\t\t\t\t\tonPointerUp={nav.endMinimapDrag}\n\t\t\t\t\tonPointerCancel={nav.endMinimapDrag}\n\t\t\t\t\tonWheel={nav.handleMinimapWheel}\n\t\t\t\t>\n\t\t\t\t\t{/* 메인 캔버스와 동기 — 전환 시 즉시 숨기고, 로드 후 잔잔한 페이드인. */}\n\t\t\t\t\t<div\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\tinset: 0,\n\t\t\t\t\t\t\topacity: imageVisible ? 1 : 0,\n\t\t\t\t\t\t\ttransition: imageVisible ? \"opacity 0.3s ease\" : \"none\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{imageUrl && <img src={imageUrl} alt=\"\" draggable={false} style={imgStyle} />}\n\t\t\t\t\t\t{maskDataUrl && view.showGuide && (\n\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\tsrc={maskDataUrl}\n\t\t\t\t\t\t\t\talt=\"\"\n\t\t\t\t\t\t\t\tdraggable={false}\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t...imgStyle,\n\t\t\t\t\t\t\t\t\topacity: 0.55,\n\t\t\t\t\t\t\t\t\timageRendering: \"pixelated\",\n\t\t\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{view.showRegionMask && region && region.rects.length > 0 && (\n\t\t\t\t\t\t\t<RegionOverlay\n\t\t\t\t\t\t\t\timage={image}\n\t\t\t\t\t\t\t\tregion={region}\n\t\t\t\t\t\t\t\tmaskId={roiMaskId}\n\t\t\t\t\t\t\t\twidth={dispW}\n\t\t\t\t\t\t\t\theight={dispH}\n\t\t\t\t\t\t\t\tstrokeWidth={1}\n\t\t\t\t\t\t\t\tstrokeDasharray=\"4 4\"\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\t\tleft: offX,\n\t\t\t\t\t\t\t\t\ttop: offY,\n\t\t\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\tviewBox={`0 0 ${image.w} ${image.h}`}\n\t\t\t\t\t\t\twidth={dispW}\n\t\t\t\t\t\t\theight={dispH}\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\tleft: offX,\n\t\t\t\t\t\t\t\ttop: offY,\n\t\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\taria-hidden\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{sortShapesForRender(shapes)\n\t\t\t\t\t\t\t\t.filter(isShapeVisible)\n\t\t\t\t\t\t\t\t.map((s) => (\n\t\t\t\t\t\t\t\t\t<MinimapShape\n\t\t\t\t\t\t\t\t\t\tkey={s.id}\n\t\t\t\t\t\t\t\t\t\tshape={s}\n\t\t\t\t\t\t\t\t\t\tstrokeSize={view.strokeSize}\n\t\t\t\t\t\t\t\t\t\tregister={registerShape}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tref={rectRef}\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\tborder: \"1px solid #00ff00\",\n\t\t\t\t\t\t\t\tbackground: \"rgba(0,255,0,0.1)\",\n\t\t\t\t\t\t\t\tboxSizing: \"border-box\",\n\t\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div className=\"aivex:flex aivex:items-center aivex:justify-between\">\n\t\t\t\t<div className=\"aivex:flex aivex:items-center aivex:gap-0.5\">\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\tsize=\"icon-sm\"\n\t\t\t\t\t\taria-label={labels.zoomOut}\n\t\t\t\t\t\tonClick={() => zoomCentered(1 / 1.2)}\n\t\t\t\t\t>\n\t\t\t\t\t\t<MinusIcon size={16} />\n\t\t\t\t\t</Button>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\tsize=\"sm\"\n\t\t\t\t\t\taria-label={labels.zoom100}\n\t\t\t\t\t\tonClick={onZoom100}\n\t\t\t\t\t\tclassName=\"aivex:min-w-[44px] aivex:px-1 aivex:tabular-nums\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span ref={zoomLabelRef}>100%</span>\n\t\t\t\t\t</Button>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\tsize=\"icon-sm\"\n\t\t\t\t\t\taria-label={labels.zoomIn}\n\t\t\t\t\t\tonClick={() => zoomCentered(1.2)}\n\t\t\t\t\t>\n\t\t\t\t\t\t<PlusIcon size={16} />\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\n\t\t\t\t<div className=\"aivex:relative aivex:flex aivex:items-center aivex:gap-0.5\">\n\t\t\t\t\t{showSettings && (\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\t\tsize=\"icon-sm\"\n\t\t\t\t\t\t\taria-label={labels.viewSettings}\n\t\t\t\t\t\t\tonClick={onToggleSettings}\n\t\t\t\t\t\t\t// 팝오버의 바깥클릭 닫힘(window pointerdown)과 토글이 이중 발화하지 않게 전파 차단.\n\t\t\t\t\t\t\tonPointerDown={(e) => e.stopPropagation()}\n\t\t\t\t\t\t\tclassName={settingsOpen ? \"aivex:text-text-brand\" : undefined}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<SettingIcon size={16} />\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t)}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\tsize=\"icon-sm\"\n\t\t\t\t\t\taria-label={labels.toggleMinimap}\n\t\t\t\t\t\ttitle=\"(M)\"\n\t\t\t\t\t\tonClick={onToggleOpen}\n\t\t\t\t\t>\n\t\t\t\t\t\t{open ? <CaretLineDownIcon size={16} /> : <CaretLineUpIcon size={16} />}\n\t\t\t\t\t</Button>\n\t\t\t\t\t{showSettings && settingsOpen && (\n\t\t\t\t\t\t<SettingsPanel\n\t\t\t\t\t\t\tvalue={view}\n\t\t\t\t\t\t\tonChange={onChangeView}\n\t\t\t\t\t\t\tonClose={onCloseSettings}\n\t\t\t\t\t\t\tlabels={settingsLabels}\n\t\t\t\t\t\t/>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","import type { CSSProperties } from \"react\";\nimport { type EditorShape, getBBox, type Point, SHAPE_TYPE } from \"../_model/geometry\";\nimport type { EditorSelectionInfo } from \"../_model/props\";\n\n/**\n * 선택 도형 정보 오버레이. 각 선택 도형의 bbox 위/아래에 라벨 배지(색 점 + 텍스트)와\n * 정보 텍스트(기본 W × H px)를 표시한다. 캔버스 오버레이 레이어(이미지 좌표) 안에 놓여\n * 뷰포트를 따라가고, inverse-scale로 화면 크기를 일정하게 유지한다.\n *\n * 표시 **레이아웃/위치/실시간 추적은 에디터 소유**, **텍스트 내용은 호스트가 결정**한다:\n * 라벨은 getLabel, 정보 텍스트는 formatInfo(에디터가 계산한 픽셀 데이터 info를 받음).\n * 드래그/리사이즈 중에는 index가 formatInfo를 재계산해 ref로 즉시 갱신한다\n * (onTransformPreview 경로).\n */\n\nconst INV = \"var(--editor-overlay-inverse-scale, 1)\";\nconst GAP = 6; // bbox 모서리와의 화면 px 간격.\n\nconst TEXT: CSSProperties = {\n\tfontFamily: \"Pretendard, sans-serif\",\n\tfontSize: 12,\n\tfontWeight: 500,\n\tlineHeight: \"16px\",\n\tcolor: \"#fff\",\n\ttextShadow: \"0 0 4px #000, 0 0 4px #000\",\n\twhiteSpace: \"nowrap\",\n};\n\n/** shape + 실제 좌표(points)로 selection info 데이터를 만든다(에디터 계산분). */\nexport function buildSelectionInfo<TMeta>(\n\tshape: EditorShape<TMeta>,\n\tpoints: Point[],\n): EditorSelectionInfo<TMeta> {\n\tconst b = getBBox(points);\n\treturn {\n\t\tshape,\n\t\tx: b.minX,\n\t\ty: b.minY,\n\t\twidth: b.maxX - b.minX,\n\t\theight: b.maxY - b.minY,\n\t};\n}\n\n/** formatSelectionInfo 미지정 시 기본 텍스트. */\nexport function defaultSelectionInfoText<TMeta>(info: EditorSelectionInfo<TMeta>): string {\n\treturn `${Math.round(info.width)} x ${Math.round(info.height)} px`;\n}\n\nfunction Dot({ color, striped }: { color: string; striped: boolean }) {\n\treturn (\n\t\t<span\n\t\t\tstyle={{\n\t\t\t\tdisplay: \"inline-block\",\n\t\t\t\twidth: 12,\n\t\t\t\theight: 12,\n\t\t\t\tborderRadius: \"50%\",\n\t\t\t\t...(striped\n\t\t\t\t\t? { border: `2px dashed ${color}`, background: \"transparent\" }\n\t\t\t\t\t: { background: color }),\n\t\t\t}}\n\t\t/>\n\t);\n}\n\nexport function SelectionInfo<TMeta>({\n\tshapes,\n\tgetLabel,\n\thideDot,\n\tformatInfo,\n\tregister,\n}: {\n\tshapes: EditorShape<TMeta>[];\n\tgetLabel?: (shape: EditorShape<TMeta>) => string | undefined;\n\thideDot?: boolean;\n\tformatInfo?: (info: EditorSelectionInfo<TMeta>) => string;\n\tregister: (id: string, el: HTMLDivElement | null) => void;\n}) {\n\treturn (\n\t\t<>\n\t\t\t{shapes.map((shape) => {\n\t\t\t\tconst b = getBBox(shape.points);\n\t\t\t\tconst isPoint = shape.type === SHAPE_TYPE.POINT;\n\t\t\t\tconst label = getLabel?.(shape);\n\t\t\t\tconst color = shape.style?.color ?? \"#00e5ff\";\n\t\t\t\t// 점선 도형(예측/readOnly)은 배지의 클래스 원도 점선으로 — 실선 원은 GT.\n\t\t\t\tconst striped = !!shape.readOnly || !!shape.style?.dash;\n\t\t\t\tconst info = buildSelectionInfo(shape, shape.points);\n\t\t\t\tconst infoText = formatInfo ? formatInfo(info) : defaultSelectionInfoText(info);\n\t\t\t\treturn (\n\t\t\t\t\t<div\n\t\t\t\t\t\tkey={shape.id}\n\t\t\t\t\t\tref={(el) => register(shape.id, el)}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\tleft: b.minX,\n\t\t\t\t\t\t\ttop: b.minY,\n\t\t\t\t\t\t\twidth: b.maxX - b.minX,\n\t\t\t\t\t\t\theight: b.maxY - b.minY,\n\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{!!label && (\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\t\tleft: 0,\n\t\t\t\t\t\t\t\t\ttop: 0,\n\t\t\t\t\t\t\t\t\tdisplay: \"flex\",\n\t\t\t\t\t\t\t\t\talignItems: \"center\",\n\t\t\t\t\t\t\t\t\tgap: 4,\n\t\t\t\t\t\t\t\t\ttransform: `scale(${INV}) translateY(calc(-100% - ${GAP}px))`,\n\t\t\t\t\t\t\t\t\ttransformOrigin: \"left top\",\n\t\t\t\t\t\t\t\t\t...TEXT,\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{!hideDot && <Dot color={color} striped={striped} />}\n\t\t\t\t\t\t\t\t<span>{label}</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{!isPoint && !!infoText && (\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tdata-selinfo-dim\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\t\tright: 0,\n\t\t\t\t\t\t\t\t\ttop: \"100%\",\n\t\t\t\t\t\t\t\t\ttransform: `scale(${INV}) translateY(${GAP}px)`,\n\t\t\t\t\t\t\t\t\ttransformOrigin: \"right top\",\n\t\t\t\t\t\t\t\t\t...TEXT,\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{infoText}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t);\n\t\t\t})}\n\t\t</>\n\t);\n}\n","import type { Anchor } from \"./geometry\";\nimport { TOOL, type Tool } from \"./tools\";\n\nconst DRAW_TOOLS = new Set<Tool>([\n\tTOOL.RECTANGLE,\n\tTOOL.ROTATED_RECTANGLE,\n\tTOOL.CIRCLE,\n\tTOOL.POLYGON,\n\tTOOL.PATH,\n\tTOOL.BRUSH,\n\tTOOL.POINT,\n\tTOOL.ASSISTANT_POLYGON,\n\tTOOL.ASSISTANT_RECT,\n\tTOOL.ASSISTANT_POINT,\n]);\n\nconst ANCHOR_ANGLE: Record<Anchor, number> = {\n\ttl: -135,\n\tt: -90,\n\ttr: -45,\n\tr: 0,\n\tbr: 45,\n\tb: 90,\n\tbl: 135,\n\tl: 180,\n};\n\nconst RESIZE_CURSORS = [\"ew-resize\", \"nwse-resize\", \"ns-resize\", \"nesw-resize\"];\n\nexport function resizeCursorForAnchor(anchor: Anchor, angleRad = 0) {\n\tconst deg = ANCHOR_ANGLE[anchor] + (angleRad * 180) / Math.PI;\n\tconst normalized = ((deg % 180) + 180) % 180;\n\tconst bucket = Math.round(normalized / 45) % 4;\n\treturn RESIZE_CURSORS[bucket];\n}\n\nexport function cursorForTool({\n\ttool,\n\texternalToolCursor,\n\tisSpacePressed,\n\tisPolygonDrawing,\n}: {\n\ttool: Tool;\n\texternalToolCursor?: string;\n\tisSpacePressed: boolean;\n\tisPolygonDrawing: boolean;\n}) {\n\tif (isSpacePressed) return \"grab\";\n\tif (externalToolCursor) return externalToolCursor;\n\tif (tool === TOOL.SELECT) return \"default\";\n\tif (DRAW_TOOLS.has(tool)) return isPolygonDrawing ? \"default\" : \"crosshair\";\n\treturn \"default\";\n}\n\nexport type EditorInteractionMode =\n\t| \"idle\"\n\t| \"drawing\"\n\t| \"marquee\"\n\t| \"moving\"\n\t| \"panning\"\n\t| \"resizing\"\n\t| \"rotating\"\n\t| \"vertexDragging\";\n\nexport function resolveEditorCursor({\n\ttool,\n\texternalToolCursor,\n\tisSpacePressed,\n\tinteractionMode,\n\trendererCursorHint,\n\tisPolygonDrawing,\n}: {\n\ttool: Tool;\n\texternalToolCursor?: string;\n\tisSpacePressed: boolean;\n\tinteractionMode: EditorInteractionMode;\n\trendererCursorHint?: string | null;\n\tisPolygonDrawing: boolean;\n}) {\n\tif (interactionMode === \"marquee\") return \"default\";\n\tif (\n\t\tinteractionMode === \"moving\" ||\n\t\tinteractionMode === \"panning\" ||\n\t\tinteractionMode === \"vertexDragging\"\n\t) {\n\t\treturn \"grabbing\";\n\t}\n\tif (interactionMode === \"resizing\" || interactionMode === \"rotating\") {\n\t\treturn rendererCursorHint ?? \"grabbing\";\n\t}\n\tif (interactionMode === \"drawing\") return \"crosshair\";\n\tif (isSpacePressed) return \"grab\";\n\tif (externalToolCursor) return externalToolCursor;\n\tif (tool === TOOL.SELECT && rendererCursorHint) return rendererCursorHint;\n\treturn cursorForTool({\n\t\ttool,\n\t\texternalToolCursor,\n\t\tisSpacePressed,\n\t\tisPolygonDrawing,\n\t});\n}\n","import type { Point } from \"./geometry\";\n\n/**\n * 미니맵/캔버스에 그리는 **도메인 무관 보조 표시물**.\n *\n * 에디터는 이게 \"ROI\"인지 \"제외영역\"인지 의미를 모른다 — 순수 기하(사각형/다각형)와\n * 색(팔레트)만 안다. 호스트가 자기 도메인 데이터(클래스색·인덱스맵 등)에서 계산해\n * 주입하고, 에디터는 그대로 그리기만 한다. 비즈니스 로직 비종속.\n */\n\n/** 이미지 좌표 사각형 영역 — 가림 효과에서 \"보이는 창\"(예: 호스트의 관심영역). */\nexport interface RectArea {\n\tid?: string;\n\tx: number;\n\ty: number;\n\tw: number;\n\th: number;\n}\n\n/** 이미지 좌표 다각형 영역 — 보이는 창 안에서 다시 가리는 부분(예: 호스트의 마스킹). */\nexport interface PolygonArea {\n\tpoints: Point[];\n}\n\n/** @deprecated 도메인 중립화로 `RectArea`로 개명. 다음 릴리스에서 제거 예정. */\nexport type RoiRect = RectArea;\n/** @deprecated 도메인 중립화로 `PolygonArea`로 개명. 다음 릴리스에서 제거 예정. */\nexport type ExcludedZone = PolygonArea;\n\n/** 영역 윤곽 스트로크 — 화면 px 기준(줌과 무관하게 고정). */\nexport interface RegionOutlineStyle {\n\tcolor?: string;\n\topacity?: number;\n\t/** 두께(화면 px). */\n\twidth?: number;\n\t/** 점선 패턴(화면 px). */\n\tdash?: [number, number];\n\t/** 점선 빈 구간의 밑선 색(대비용). null이면 밑선 없음. 기본 검정. */\n\tunderlayColor?: string | null;\n}\n\n/**\n * 이미지 위 가림 효과를 위한 순수 시각 계약. 영역의 제품 의미(관심영역·마스킹 등)는\n * 호스트가 해석하고, 에디터는 \"보이는 영역과 가려지는 영역\"만 안다.\n * 표시 정책(딤 농도·윤곽 색)은 기본값일 뿐 호스트가 전부 재정의할 수 있다.\n */\nexport interface RegionMask {\n\tvisibleAreas: RectArea[];\n\toccludedAreas?: PolygonArea[];\n\t/** 가림 면 스타일. 기본 검정 50%. */\n\tdim?: { color?: string; opacity?: number };\n\t/**\n\t * 윤곽 표시. false면 면만 그리고 윤곽은 도형 레이어에 맡긴다. 미지정=기본 스타일.\n\t * mode \"merged\"(기본)=유효 영역(합집합 − 가림) 경계 하나를 visibleStyle로(보기 맥락),\n\t * \"separate\"=사각형·가림 윤곽을 각각 visibleStyle/occludedStyle로 통째 표시(편집 맥락).\n\t */\n\toutline?:\n\t\t| false\n\t\t| {\n\t\t\t\tmode?: \"merged\" | \"separate\";\n\t\t\t\tvisibleStyle?: RegionOutlineStyle;\n\t\t\t\toccludedStyle?: RegionOutlineStyle;\n\t\t };\n}\n\n/** 마스크 팔레트 — 픽셀 인덱스값 → 색(hex). 호스트가 클래스색에서 계산해 주입. */\nexport type MaskPalette = Record<number, string>;\n\n// ── 가이드 마스크(도메인 무관) ─────────────────────────────────────────────\n\n/**\n * 디코딩된 가이드 마스크 래스터. `indices`는 width*height 픽셀 인덱스이고\n * 인덱스→색은 palette로 결정한다. transparent 인덱스는 그리지 않는다.\n * 서버/도메인별 와이어 포맷(바이너리 헤더 등) 디코딩은 호스트 책임 —\n * 에디터는 순수 래스터만 받는다(LabelEditor/guideMask.ts 참고).\n */\nexport interface GuideMaskRaster {\n\twidth: number;\n\theight: number;\n\tindices: Uint8Array;\n\ttransparent?: number;\n}\n\nconst clampChannel = (value: number) => Math.min(255, Math.max(0, value));\n\nconst hexToRgba = (hex: string): [number, number, number, number] | null => {\n\tconst normalized = hex.replace(\"#\", \"\").trim();\n\tif (![3, 4, 6, 8].includes(normalized.length)) return null;\n\n\tconst expand = (value: string) => (value.length === 1 ? `${value}${value}` : value);\n\tconst short = normalized.length <= 4;\n\n\tconst r = expand(normalized.slice(0, short ? 1 : 2));\n\tconst g = expand(normalized.slice(short ? 1 : 2, short ? 2 : 4));\n\tconst b = expand(normalized.slice(short ? 2 : 4, short ? 3 : 6));\n\tconst a =\n\t\tnormalized.length === 4\n\t\t\t? expand(normalized.slice(3, 4))\n\t\t\t: normalized.length === 8\n\t\t\t\t? expand(normalized.slice(6, 8))\n\t\t\t\t: \"ff\";\n\n\tconst parse = (value: string) => Number.parseInt(value, 16);\n\tconst rgba: [number, number, number, number] = [parse(r), parse(g), parse(b), parse(a)];\n\tif (rgba.some((value) => Number.isNaN(value))) return null;\n\treturn rgba.map(clampChannel) as [number, number, number, number];\n};\n\n/**\n * 가이드 마스크 래스터 + 팔레트(인덱스→색)를 컬러 캔버스로 그린다.\n * 실패하면 null. 결과 캔버스는 이미지 원본 해상도(width×height).\n */\nexport const buildMaskCanvas = (\n\traster: GuideMaskRaster,\n\tpalette: MaskPalette,\n): HTMLCanvasElement | null => {\n\tconst { width, height, indices, transparent } = raster;\n\tif (!width || !height || indices.length < width * height) return null;\n\n\tconst rgbaPalette: Record<number, [number, number, number, number]> = {};\n\tfor (const [key, hex] of Object.entries(palette)) {\n\t\tconst rgba = hexToRgba(hex);\n\t\tif (rgba) rgbaPalette[Number(key)] = rgba;\n\t}\n\tif (!Object.keys(rgbaPalette).length) return null;\n\n\tconst canvas = document.createElement(\"canvas\");\n\tcanvas.width = width;\n\tcanvas.height = height;\n\tconst context = canvas.getContext(\"2d\");\n\tif (!context) return null;\n\n\tconst data = new Uint8ClampedArray(width * height * 4);\n\tconst pixels = width * height;\n\tfor (let i = 0; i < pixels; i += 1) {\n\t\tconst value = indices[i];\n\t\tif (value === transparent) continue;\n\t\tconst color = rgbaPalette[value];\n\t\tif (!color) continue;\n\t\tconst offset = i * 4;\n\t\tdata[offset] = color[0];\n\t\tdata[offset + 1] = color[1];\n\t\tdata[offset + 2] = color[2];\n\t\tdata[offset + 3] = color[3];\n\t}\n\n\tcontext.putImageData(new ImageData(data, width, height), 0, 0);\n\treturn canvas;\n};\n\nfunction traceZone(ctx: CanvasRenderingContext2D, points: { x: number; y: number }[]) {\n\tctx.beginPath();\n\tctx.moveTo(points[0].x, points[0].y);\n\tfor (let i = 1; i < points.length; i += 1) ctx.lineTo(points[i].x, points[i].y);\n\tctx.closePath();\n}\n\n// ── 유효 ROI 경계(사각형 합집합 − 제외영역) 선분 클리핑 ──\n\n/** 이미지 좌표 선분. 렌더러가 화면고정(줌 무관) 점선 스트로크로 그린다. */\nexport type OutlineSegment = [Point, Point];\n\nconst rectToPoly = (r: RectArea): Point[] => [\n\t{ x: r.x, y: r.y },\n\t{ x: r.x + r.w, y: r.y },\n\t{ x: r.x + r.w, y: r.y + r.h },\n\t{ x: r.x, y: r.y + r.h },\n];\n\nfunction pointInPoly(p: Point, poly: Point[]): boolean {\n\tlet inside = false;\n\tfor (let i = 0, j = poly.length - 1; i < poly.length; j = i, i += 1) {\n\t\tconst a = poly[i];\n\t\tconst b = poly[j];\n\t\tif (a.y > p.y !== b.y > p.y) {\n\t\t\tconst t = (p.y - a.y) / (b.y - a.y);\n\t\t\tif (p.x < a.x + t * (b.x - a.x)) inside = !inside;\n\t\t}\n\t}\n\treturn inside;\n}\n\n/** 선분 [a,b]와 다각형 변들의 교차 파라미터 t들(양 끝 제외). */\nfunction segPolyIntersectionTs(a: Point, b: Point, poly: Point[]): number[] {\n\tconst ts: number[] = [];\n\tconst dx = b.x - a.x;\n\tconst dy = b.y - a.y;\n\tfor (let i = 0; i < poly.length; i += 1) {\n\t\tconst c = poly[i];\n\t\tconst d = poly[(i + 1) % poly.length];\n\t\tconst ex = d.x - c.x;\n\t\tconst ey = d.y - c.y;\n\t\tconst denom = dx * ey - dy * ex;\n\t\tif (!denom) continue;\n\t\tconst t = ((c.x - a.x) * ey - (c.y - a.y) * ex) / denom;\n\t\tconst u = ((c.x - a.x) * dy - (c.y - a.y) * dx) / denom;\n\t\tif (t > 0 && t < 1 && u >= 0 && u <= 1) ts.push(t);\n\t}\n\treturn ts;\n}\n\n/**\n * 다각형 변들을 교차점에서 쪼개 보이는 조각만 남긴다. 판정은 조각 중점이 아니라\n * **변 법선 방향으로 살짝 벗어난 양쪽 표본**으로 한다 — 중점 자체는 경계 위라\n * 포함판정이 비일관해서, 타일처럼 맞닿은 사각형의 공유 변이 한쪽만 숨겨지는\n * seam이 생겼다. \"자기 내부 반대쪽(outward) 표본이 다른 다각형에 덮이면 합집합\n * 내부 경계\"라는 규칙은 맞닿음·부분중첩은 숨기고 완전중복(동일 사각형 2개)의\n * 진짜 외곽은 남긴다.\n * hideInside: outward 표본이 이들 중 하나(자기 제외) 안이면 숨김.\n * keepInsideAny: 지정 시 inward 표본이 이들 중 하나 안일 때만 유지.\n */\nfunction clipEdges(\n\tpolys: Point[][],\n\thideInside: Point[][],\n\tkeepInsideAny: Point[][] | null,\n): OutlineSegment[] {\n\t// 표본 오프셋(이미지 px) — 시각적으로 무의미하게 작되 경계 부동소수 오차보다 크게.\n\tconst SAMPLE_OFFSET = 1e-3;\n\tconst out: OutlineSegment[] = [];\n\tconst lerp = (a: Point, b: Point, t: number): Point => ({\n\t\tx: a.x + (b.x - a.x) * t,\n\t\ty: a.y + (b.y - a.y) * t,\n\t});\n\tfor (const poly of polys) {\n\t\tif (poly.length < 2) continue;\n\t\tfor (let i = 0; i < poly.length; i += 1) {\n\t\t\tconst a = poly[i];\n\t\t\tconst b = poly[(i + 1) % poly.length];\n\t\t\tconst cuts = [0, 1];\n\t\t\tfor (const other of hideInside) {\n\t\t\t\tif (other !== poly) cuts.push(...segPolyIntersectionTs(a, b, other));\n\t\t\t}\n\t\t\tif (keepInsideAny) {\n\t\t\t\tfor (const other of keepInsideAny) cuts.push(...segPolyIntersectionTs(a, b, other));\n\t\t\t}\n\t\t\tconst len = Math.hypot(b.x - a.x, b.y - a.y);\n\t\t\tif (!len) continue;\n\t\t\tconst nx = (-(b.y - a.y) / len) * SAMPLE_OFFSET;\n\t\t\tconst ny = ((b.x - a.x) / len) * SAMPLE_OFFSET;\n\t\t\tcuts.sort((x, y) => x - y);\n\t\t\tfor (let k = 0; k + 1 < cuts.length; k += 1) {\n\t\t\t\tconst t0 = cuts[k];\n\t\t\t\tconst t1 = cuts[k + 1];\n\t\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\t\tconst m = lerp(a, b, (t0 + t1) / 2);\n\t\t\t\tconst p1 = { x: m.x + nx, y: m.y + ny };\n\t\t\t\tconst p2 = { x: m.x - nx, y: m.y - ny };\n\t\t\t\t// 자기 다각형 내부 쪽이 inward(호스트 다각형 winding 불문).\n\t\t\t\tconst inward = pointInPoly(p1, poly) ? p1 : p2;\n\t\t\t\tconst outward = inward === p1 ? p2 : p1;\n\t\t\t\tif (hideInside.some((other) => other !== poly && pointInPoly(outward, other))) continue;\n\t\t\t\tif (keepInsideAny && !keepInsideAny.some((other) => pointInPoly(inward, other))) continue;\n\t\t\t\tout.push([lerp(a, b, t0), lerp(a, b, t1)]);\n\t\t\t}\n\t\t}\n\t}\n\treturn out;\n}\n\n/** 사각형들의 합집합을 서로 겹치지 않는 사각형들로 분해한다(x-슬랩 스윕). */\nfunction decomposeUnionRects(rects: RectArea[]): RectArea[] {\n\tconst xs = [...new Set(rects.flatMap((r) => [r.x, r.x + r.w]))].sort((a, b) => a - b);\n\tconst out: RectArea[] = [];\n\tfor (let i = 0; i + 1 < xs.length; i += 1) {\n\t\tconst x0 = xs[i];\n\t\tconst x1 = xs[i + 1];\n\t\tif (x1 <= x0) continue;\n\t\tconst intervals = rects\n\t\t\t.filter((r) => r.x <= x0 && r.x + r.w >= x1)\n\t\t\t.map((r) => [r.y, r.y + r.h] as [number, number])\n\t\t\t.sort((a, b) => a[0] - b[0]);\n\t\tlet cur: [number, number] | null = null;\n\t\tfor (const [y0, y1] of intervals) {\n\t\t\tif (!cur || y0 > cur[1]) {\n\t\t\t\tif (cur) out.push({ x: x0, y: cur[0], w: x1 - x0, h: cur[1] - cur[0] });\n\t\t\t\tcur = [y0, y1];\n\t\t\t} else {\n\t\t\t\tcur[1] = Math.max(cur[1], y1);\n\t\t\t}\n\t\t}\n\t\tif (cur) out.push({ x: x0, y: cur[0], w: x1 - x0, h: cur[1] - cur[0] });\n\t}\n\treturn out;\n}\n\n/**\n * Canvas2D에 벡터 딤을 그린다 — 이미지 전체를 딤 색으로 덮되 보이는 영역 합집합을\n * 구멍(dimHoles, 무겹침이라 nonzero에서 안전)으로 뚫고, 가림 영역은 합집합 안쪽만\n * 다시 덮는다. Konva 렌더러와 ShapeViewer가 공유한다(전체 경로 커버리지 채움이라\n * 인접 구멍 경계에 이음선이 생기지 않는다).\n */\nexport function drawRegionDim(\n\tctx: CanvasRenderingContext2D,\n\tregion: Pick<RegionOverlayData, \"rects\" | \"zones\" | \"dimHoles\" | \"dim\">,\n\twidth: number,\n\theight: number,\n) {\n\tctx.save();\n\tctx.globalAlpha *= region.dim.opacity;\n\tctx.fillStyle = region.dim.color;\n\tctx.beginPath();\n\tctx.rect(0, 0, width, height);\n\tfor (const r of region.dimHoles) {\n\t\t// 반시계 서브패스 → nonzero 규칙에서 구멍.\n\t\tctx.moveTo(r.x, r.y);\n\t\tctx.lineTo(r.x, r.y + r.h);\n\t\tctx.lineTo(r.x + r.w, r.y + r.h);\n\t\tctx.lineTo(r.x + r.w, r.y);\n\t\tctx.closePath();\n\t}\n\tctx.fill();\n\tif (region.zones.length) {\n\t\tctx.beginPath();\n\t\tfor (const r of region.rects) ctx.rect(r.x, r.y, r.w, r.h);\n\t\tctx.clip();\n\t\tfor (const z of region.zones) {\n\t\t\ttraceZone(ctx, z.points);\n\t\t\tctx.fill();\n\t\t}\n\t}\n\tctx.restore();\n}\n\n/** 다각형 변들을 그대로 선분으로 편다(클리핑 없음 — separate 윤곽용). */\nfunction polysToSegments(polys: Point[][]): OutlineSegment[] {\n\tconst out: OutlineSegment[] = [];\n\tfor (const poly of polys) {\n\t\tif (poly.length < 2) continue;\n\t\tfor (let i = 0; i < poly.length; i += 1) {\n\t\t\tout.push([poly[i], poly[(i + 1) % poly.length]]);\n\t\t}\n\t}\n\treturn out;\n}\n\n/** 기본 표시 정책 — 호스트가 RegionMask.dim/outline으로 전부 재정의 가능. */\nconst DEFAULT_DIM = { color: \"#000000\", opacity: 0.5 };\nconst DEFAULT_VISIBLE_OUTLINE: ResolvedRegionOutlineStyle = {\n\tcolor: \"#ffffff\",\n\topacity: 1,\n\twidth: 2,\n\tdash: [6, 6],\n\tunderlayColor: \"#000000\",\n};\nconst DEFAULT_OCCLUDED_OUTLINE: ResolvedRegionOutlineStyle = {\n\tcolor: \"#dc2626\",\n\topacity: 0.8,\n\twidth: 2,\n\tdash: [6, 6],\n\tunderlayColor: \"#000000\",\n};\n\n/** 기본값이 채워진 윤곽 스트로크 — 렌더러가 그대로 그린다. */\nexport type ResolvedRegionOutlineStyle = Required<RegionOutlineStyle>;\n\n/**\n * 렌더러 오버레이용 영역 데이터. 딤(면)·윤곽 모두 벡터로 넘긴다 —\n * 래스터(캔버스 굽기 + 텍스처 업로드)가 없어 드래그 중 프레임마다 재계산해도 싸다.\n * 딤은 rects/zones로 각 렌더러가 직접 그리고(이미지 전체 − 사각형 합집합, 가림은\n * 합집합 안쪽만 다시 덮음), 윤곽은 선분 목록을 화면고정(줌 무관) 스트로크로 그린다.\n */\nexport interface RegionOverlayData {\n\t/** 딤 계산용 보이는 창들. visibleAreas가 비어 있으면 전체 이미지 사각형 1개. */\n\trects: RectArea[];\n\tzones: PolygonArea[];\n\t/** 사각형 합집합의 무겹침 분해 — 캔버스 딤 경로의 구멍용(겹치는 영역 안전). */\n\tdimHoles: RectArea[];\n\tdim: { color: string; opacity: number };\n\t/** visibleStyle로 그릴 경계 조각. merged면 유효 영역 경계 전체가 여기 담긴다. */\n\tvisibleOutline: OutlineSegment[];\n\t/** occludedStyle로 그릴 가림 윤곽 조각(separate 모드에서만 비어있지 않음). */\n\toccludedOutline: OutlineSegment[];\n\t/** null이면 윤곽 생략(outline: false). */\n\toutlineStyles: {\n\t\tvisible: ResolvedRegionOutlineStyle;\n\t\toccluded: ResolvedRegionOutlineStyle;\n\t} | null;\n}\n\n/**\n * RegionMask를 렌더러가 그릴 벡터 데이터로 리졸브한다(기본 표시 정책 주입 포함).\n * outline.mode \"merged\"(기본)면 유효 영역(합집합 − 가림) 경계 하나를,\n * \"separate\"면 사각형·가림 윤곽을 각각 통째로 넘긴다.\n * 렌더러 오버레이 레이어(이미지↔도형 사이)에 그려 도형이 그 위에 보이게 한다.\n */\nexport const buildRegionOverlayData = (\n\tmask: RegionMask,\n\twidth: number,\n\theight: number,\n): RegionOverlayData | null => {\n\tconst zones = mask.occludedAreas?.filter((z) => z.points.length >= 3) ?? [];\n\tif (!width || !height || (!mask.visibleAreas.length && !zones.length)) return null;\n\tconst rects = mask.visibleAreas;\n\t// 보이는 창이 없으면 전체 이미지를 창으로 본다(가림만 먼저 그리는 편집 초기 상태) —\n\t// 바깥 딤 없이 가림 영역만 딤·윤곽으로 표시되고, 전체 이미지 테두리는 윤곽에서 제외한다.\n\tconst universe: RectArea[] = rects.length ? rects : [{ x: 0, y: 0, w: width, h: height }];\n\tconst dimHoles = decomposeUnionRects(universe);\n\tconst dim = { ...DEFAULT_DIM, ...mask.dim };\n\tconst outline = mask.outline;\n\tif (outline === false) {\n\t\treturn {\n\t\t\trects: universe,\n\t\t\tzones,\n\t\t\tdimHoles,\n\t\t\tdim,\n\t\t\tvisibleOutline: [],\n\t\t\toccludedOutline: [],\n\t\t\toutlineStyles: null,\n\t\t};\n\t}\n\tconst outlineStyles = {\n\t\tvisible: { ...DEFAULT_VISIBLE_OUTLINE, ...outline?.visibleStyle },\n\t\toccluded: { ...DEFAULT_OCCLUDED_OUTLINE, ...outline?.occludedStyle },\n\t};\n\tconst rectPolys = rects.map(rectToPoly);\n\tconst universePolys = universe.map(rectToPoly);\n\tconst zonePolys = zones.map((z) => z.points);\n\tif (outline?.mode === \"separate\") {\n\t\t// 편집 맥락 — 사각형·가림 윤곽을 각각 통째로.\n\t\treturn {\n\t\t\trects: universe,\n\t\t\tzones,\n\t\t\tdimHoles,\n\t\t\tdim,\n\t\t\tvisibleOutline: polysToSegments(rectPolys),\n\t\t\toccludedOutline: polysToSegments(zonePolys),\n\t\t\toutlineStyles,\n\t\t};\n\t}\n\t// 보기 맥락(기본) — 유효 영역 경계 하나를 visibleStyle로.\n\treturn {\n\t\trects: universe,\n\t\tzones,\n\t\tdimHoles,\n\t\tdim,\n\t\tvisibleOutline: [\n\t\t\t// 사각형 변: 다른 사각형·가림 안쪽은 숨김(합집합 − 가림 경계만 남음).\n\t\t\t...clipEdges(rectPolys, [...rectPolys, ...zonePolys], null),\n\t\t\t// 가림 변: 보이는 창(없으면 전체 이미지) 안쪽이면서 다른 가림 밖인 조각만.\n\t\t\t...clipEdges(zonePolys, zonePolys, universePolys),\n\t\t],\n\t\toccludedOutline: [],\n\t\toutlineStyles,\n\t};\n};\n","import type { Viewport } from \"../_renderers/types\";\nimport type { BBox, EditorShape, Point, ShapeType } from \"./geometry\";\nimport { getBBox, SHAPE_TYPE } from \"./geometry\";\n\n/** 기존 Editor `TARGET_CONTAINER_RATIO` — 레이블 줌 시 화면 대비 목표 비율. */\nexport const TARGET_CONTAINER_RATIO = 0.3;\nexport const DEFAULT_ZOOM_ANIMATION_MS = 300;\nexport const MIN_VIEWPORT_SCALE = 0.05;\nexport const MAX_VIEWPORT_SCALE = 20;\n\nexport interface ZoomBounds {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\nexport function easeOutCubic(t: number) {\n\treturn 1 - (1 - t) ** 3;\n}\n\nexport function bboxToZoomBounds(b: BBox): ZoomBounds {\n\treturn {\n\t\tx: b.minX,\n\t\ty: b.minY,\n\t\twidth: Math.max(0, b.maxX - b.minX),\n\t\theight: Math.max(0, b.maxY - b.minY),\n\t};\n}\n\nexport function zoomBoundsFromPoints(type: ShapeType, points: Point[]): ZoomBounds | null {\n\tif (!points.length) return null;\n\tif (type === SHAPE_TYPE.POINT) {\n\t\tconst p = points[0];\n\t\tconst r = 8;\n\t\treturn { x: p.x - r, y: p.y - r, width: r * 2, height: r * 2 };\n\t}\n\tconst b = getBBox(points);\n\tconst width = Math.max(1, b.maxX - b.minX);\n\tconst height = Math.max(1, b.maxY - b.minY);\n\treturn { x: b.minX, y: b.minY, width, height };\n}\n\nexport function zoomBoundsFromShapes(shapes: EditorShape[]): ZoomBounds | null {\n\tif (!shapes.length) return null;\n\tconst boxes = shapes\n\t\t.map((shape) => zoomBoundsFromPoints(shape.type, shape.points))\n\t\t.filter((box): box is ZoomBounds => box !== null);\n\tif (!boxes.length) return null;\n\tconst b = getBBox(\n\t\tboxes.flatMap((box) => [\n\t\t\t{ x: box.x, y: box.y },\n\t\t\t{ x: box.x + box.width, y: box.y + box.height },\n\t\t]),\n\t);\n\treturn bboxToZoomBounds(b);\n}\n\nexport interface ViewportZoomOptions {\n\tpad?: number;\n\tcontainerRatio?: number;\n\tminScale?: number;\n\tmaxScale?: number;\n}\n\n/** 레이블 리스트 클릭 등 — 기존 Editor `animateToBounds`와 동일한 스케일 계산. */\nexport function viewportForZoomBounds(\n\tbounds: ZoomBounds,\n\tscreenW: number,\n\tscreenH: number,\n\toptions: ViewportZoomOptions = {},\n): Viewport | null {\n\tconst {\n\t\tcontainerRatio = TARGET_CONTAINER_RATIO,\n\t\tminScale = MIN_VIEWPORT_SCALE,\n\t\tmaxScale = MAX_VIEWPORT_SCALE,\n\t} = options;\n\tif (!screenW || !screenH || bounds.width <= 0 || bounds.height <= 0) return null;\n\n\tconst targetScaleByContainer = Math.min(\n\t\t(screenW * containerRatio) / bounds.width,\n\t\t(screenH * containerRatio) / bounds.height,\n\t);\n\tconst scale = Math.max(minScale, Math.min(maxScale, targetScaleByContainer));\n\tconst cx = bounds.x + bounds.width / 2;\n\tconst cy = bounds.y + bounds.height / 2;\n\treturn {\n\t\tscale,\n\t\tx: screenW / 2 - cx * scale,\n\t\ty: screenH / 2 - cy * scale,\n\t};\n}\n\n/** 선택 영역 맞춤 — 화면에 bbox가 최대한 들어오도록. */\nexport function viewportForBBox(\n\tb: BBox,\n\tscreenW: number,\n\tscreenH: number,\n\tpad = 80,\n): Viewport | null {\n\tif (!screenW || !screenH) return null;\n\tconst bw = Math.max(1, b.maxX - b.minX);\n\tconst bh = Math.max(1, b.maxY - b.minY);\n\tconst scale = Math.max(\n\t\tMIN_VIEWPORT_SCALE,\n\t\tMath.min(MAX_VIEWPORT_SCALE, Math.min((screenW - pad) / bw, (screenH - pad) / bh)),\n\t);\n\tconst cx = (b.minX + b.maxX) / 2;\n\tconst cy = (b.minY + b.maxY) / 2;\n\treturn {\n\t\tscale,\n\t\tx: screenW / 2 - cx * scale,\n\t\ty: screenH / 2 - cy * scale,\n\t};\n}\n\nexport function animateViewport(\n\tfrom: Viewport,\n\tto: Viewport,\n\tapply: (viewport: Viewport) => void,\n\tduration = DEFAULT_ZOOM_ANIMATION_MS,\n): () => void {\n\tconst startTime = Date.now();\n\tlet frame = 0;\n\n\tconst tick = () => {\n\t\tconst elapsed = Date.now() - startTime;\n\t\tconst progress = Math.min(elapsed / duration, 1);\n\t\tconst eased = easeOutCubic(progress);\n\t\tapply({\n\t\t\tscale: from.scale + (to.scale - from.scale) * eased,\n\t\t\tx: from.x + (to.x - from.x) * eased,\n\t\t\ty: from.y + (to.y - from.y) * eased,\n\t\t});\n\t\tif (progress < 1) frame = requestAnimationFrame(tick);\n\t};\n\n\tframe = requestAnimationFrame(tick);\n\treturn () => cancelAnimationFrame(frame);\n}\n","import type { RefObject } from \"react\";\nimport type { EditorInteractionMode } from \"../_model/cursors\";\nimport {\n\tcircleToPolygon,\n\ttype EditorShape,\n\tgetBBox,\n\tisShapeDraggable,\n\tisShapeSelectable,\n\ttype Point,\n\trectTo4,\n\tSHAPE_TYPE,\n\ttype ShapeStyle,\n\tsortShapesForRender,\n\tsquareEnd,\n} from \"../_model/geometry\";\nimport type { EditorExternalTool, EditorExternalToolContext } from \"../_model/props\";\nimport { TOOL, type Tool } from \"../_model/tools\";\nimport type { EditorRenderer, EditorRendererCallbacks } from \"../_renderers/types\";\nimport type { AssistantSession } from \"./useAssistant\";\nimport type { DrawSession } from \"./useDrawSession\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\n/**\n * 캔버스 포인터 상호작용 상태머신. 렌더러가 올려주는 포인터 이벤트를 받아\n * 팬/그리기/마퀴/꼭짓점드래그/외부도구를 조율하고, 문서·선택·그리기세션에 위임한다.\n *\n * 엔진 인스턴스마다 1회 생성한다(그때의 상호작용 임시 상태를 클로저로 보관). 최신 상태는\n * 전부 ref/drawSession으로 읽으므로 재생성 없이 최신 값을 반영한다.\n */\nexport interface InteractionControllerCtx<TMeta> {\n\tengineRef: RefObject<EditorRenderer | null>;\n\ttoolRef: RefObject<Tool>;\n\texternalToolMapRef: RefObject<Map<string, EditorExternalTool>>;\n\tspaceRef: RefObject<boolean>;\n\tshiftRef: RefObject<boolean>;\n\tdocRef: RefObject<EditorDocument<TMeta>>;\n\tselRef: RefObject<string[]>;\n\tdraftRef: RefObject<ShapeStyle | undefined>;\n\treadOnlyRef: RefObject<boolean | undefined>;\n\t/** true면 SELECT 도구 마퀴(범위 선택) 비활성 — 클릭 단건 선택만. */\n\tdisableMarqueeRef?: RefObject<boolean | undefined>;\n\t/** 편집 잠금(완료 등). true면 편집 시도를 막고 onLockedInteraction 호출. */\n\tlockedRef: RefObject<boolean | undefined>;\n\tonLockedInteraction: () => void;\n\tcreateRef: RefObject<(type: EditorShape<TMeta>[\"type\"], points: Point[]) => void>;\n\tselectRef: RefObject<(ids: string[]) => void>;\n\t/** 폴리곤 정점 편집모드 진입(더블클릭). */\n\tenterEditRef: RefObject<(id: string) => void>;\n\tdrawSessionRef: RefObject<DrawSession<TMeta>>;\n\tassistantRef: RefObject<AssistantSession<TMeta>>;\n\tsetCursorHint: (cursor: string | null) => void;\n\tsetInteractionMode: (mode: EditorInteractionMode) => void;\n\tsyncMinimap: () => void;\n\tonTransformPreview: (updates: { id: string; points: Point[] }[]) => void;\n\t/**\n\t * 박스 드래그 그리는 중 미리보기 지오메트리 통지 — 좌상단 클래스 배지 + 우하단\n\t * 크기(W×H) 정보 오버레이용. 그리는 중엔 bbox 두 꼭짓점, 종료 시 null.\n\t */\n\tonDrawPreview: (info: { type: EditorShape<TMeta>[\"type\"]; points: Point[] } | null) => void;\n}\n\nexport function createInteractionController<TMeta>(\n\tctx: InteractionControllerCtx<TMeta>,\n): EditorRendererCallbacks {\n\tconst {\n\t\tengineRef,\n\t\ttoolRef,\n\t\texternalToolMapRef,\n\t\tspaceRef,\n\t\tshiftRef,\n\t\tdocRef,\n\t\tselRef,\n\t\tdraftRef,\n\t\treadOnlyRef,\n\t\tdisableMarqueeRef,\n\t\tlockedRef,\n\t\tonLockedInteraction,\n\t\tcreateRef,\n\t\tselectRef,\n\t\tenterEditRef,\n\t\tdrawSessionRef,\n\t\tassistantRef,\n\t\tsetCursorHint,\n\t\tsetInteractionMode,\n\t\tsyncMinimap,\n\t\tonTransformPreview,\n\t\tonDrawPreview,\n\t} = ctx;\n\tconst ds = () => drawSessionRef.current;\n\tconst assist = () => assistantRef.current;\n\n\t// 상호작용 일시 상태(엔진 인스턴스 수명과 동일).\n\tlet pan: { x: number; y: number; px: number; py: number } | null = null;\n\tlet drawStart: Point | null = null;\n\t// 자유선(PATH)/붓(BRUSH)은 동일한 스트로크 파이프라인 — 종류만 구분.\n\tlet strokeKind: \"path\" | \"scalar\" | null = null;\n\tlet draftPointDrag: {\n\t\tstart: Point;\n\t\tbase: Point[];\n\t\tindices: number[];\n\t\tmoved: boolean;\n\t} | null = null;\n\tlet marquee: Point | null = null;\n\tlet lastHit = \"\";\n\t// 폴리곤 더블클릭→편집모드 감지용(같은 도형을 짧은 간격으로 두 번 클릭).\n\tlet lastClick: { id: string; t: number } | null = null;\n\n\tconst isBox = (t: Tool) =>\n\t\tt === TOOL.RECTANGLE || t === TOOL.ROTATED_RECTANGLE || t === TOOL.CIRCLE;\n\t// 어시스트 박스 드래그 도구(폴리곤 결과 ASSISTANT_POLYGON + 사각형 결과 ASSISTANT_RECT).\n\tconst isAssistantBox = (t: Tool) => t === TOOL.ASSISTANT_POLYGON || t === TOOL.ASSISTANT_RECT;\n\tconst isClickPath = (t: Tool) => t === TOOL.POLYGON;\n\tconst getExternalTool = () => externalToolMapRef.current.get(toolRef.current);\n\tconst makeExternalContext = (\n\t\teng: EditorRenderer,\n\t\tpoint: Point,\n\t\tevent: EditorExternalToolContext[\"event\"],\n\t\ttargetId?: string | null,\n\t): EditorExternalToolContext => ({\n\t\tpoint,\n\t\ttargetId,\n\t\tevent,\n\t\treadOnly: readOnlyRef.current,\n\t\tviewport: eng.viewport,\n\t});\n\n\treturn {\n\t\tonCursorHint: setCursorHint,\n\t\tonInteractionModeChange: setInteractionMode,\n\t\tonPointerDown: (p, targetId, e) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tconst tool = toolRef.current;\n\t\t\t// 팬: 중간버튼 또는 Space.\n\t\t\tif (e.button === 1 || spaceRef.current) {\n\t\t\t\tsetInteractionMode(\"panning\");\n\t\t\t\tsetCursorHint(null);\n\t\t\t\tpan = {\n\t\t\t\t\tx: eng.viewport.x,\n\t\t\t\t\ty: eng.viewport.y,\n\t\t\t\t\tpx: e.global.x,\n\t\t\t\t\tpy: e.global.y,\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// 우클릭=메뉴. 단, 마법봉(ASSISTANT_POINT)의 Alt+우클릭은 음성 정제로 쓴다.\n\t\t\tif (e.button === 2 && !(tool === TOOL.ASSISTANT_POINT && e.altKey)) return;\n\n\t\t\tconst externalTool = getExternalTool();\n\t\t\tif (externalTool) {\n\t\t\t\tds().reset();\n\t\t\t\tselectRef.current([]);\n\t\t\t\texternalTool.onPointerDown?.(makeExternalContext(eng, p, e, targetId));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// 편집 잠금(완료 등): 코멘트(외부도구)·팬·우클릭메뉴 외 편집 시도를 막고\n\t\t\t// 호스트에 알린다(옵스식 완료 편집 확인 모달). 위 external-tool 블록을 지난\n\t\t\t// 뒤이므로 코멘트는 통과, 여기서 나머지 편집 상호작용을 전부 차단한다.\n\t\t\tif (lockedRef.current) {\n\t\t\t\tonLockedInteraction();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// AI 어시스트(마법봉): 옵스식.\n\t\t\t// - 그냥 클릭 → 그 점 기반 새 폴리곤 생성(이전 세션은 확정).\n\t\t\t// - Alt+좌클릭 → 현재 폴리곤을 넓힘(+ 정제), Alt+우클릭 → 좁힘(− 정제).\n\t\t\tif (tool === TOOL.ASSISTANT_POINT) {\n\t\t\t\tif (e.altKey) assist().addPoint(p, e.button !== 2);\n\t\t\t\telse assist().newPolygon(p);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// AI 어시스트: 박스 프롬프트(드래그). 폴리곤/사각형 결과 모두 동일 드래그.\n\t\t\tif (isAssistantBox(tool) && draftRef.current) {\n\t\t\t\tdrawStart = p;\n\t\t\t\tsetInteractionMode(\"drawing\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Alt-클릭: 포인터 아래 겹친 도형들을 위→아래로 순환 선택.\n\t\t\tif (tool === TOOL.SELECT && e.altKey) {\n\t\t\t\tconst under = sortShapesForRender(docRef.current.getShapes()).filter((s) => {\n\t\t\t\t\tif (!isShapeSelectable(s)) return false;\n\t\t\t\t\tconst b = getBBox(s.points);\n\t\t\t\t\treturn p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY;\n\t\t\t\t});\n\t\t\t\tif (under.length) {\n\t\t\t\t\tconst ordered = [...under].reverse();\n\t\t\t\t\tconst cur = ordered.findIndex((s) => selRef.current.includes(s.id));\n\t\t\t\t\tconst next = [ordered[(cur + 1) % ordered.length].id];\n\t\t\t\t\tselectRef.current(next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 도형 위 클릭.\n\t\t\tif (targetId && tool === TOOL.SELECT) {\n\t\t\t\tconst targetShape = docRef.current.getShapes().find((shape) => shape.id === targetId);\n\t\t\t\tif (!targetShape || !isShapeSelectable(targetShape)) return;\n\t\t\t\t// 폴리곤/라인 더블클릭 → 정점 편집모드 진입(옵스식).\n\t\t\t\tconst now = typeof performance !== \"undefined\" ? performance.now() : 0;\n\t\t\t\tconst isDouble = !!lastClick && lastClick.id === targetId && now - lastClick.t < 300;\n\t\t\t\tlastClick = { id: targetId, t: now };\n\t\t\t\tconst editable =\n\t\t\t\t\t(targetShape.type === SHAPE_TYPE.POLYGON || targetShape.type === SHAPE_TYPE.LINE) &&\n\t\t\t\t\t!readOnlyRef.current &&\n\t\t\t\t\ttargetShape.interaction?.editable !== false &&\n\t\t\t\t\t!targetShape.readOnly;\n\t\t\t\tif (isDouble && editable) {\n\t\t\t\t\tselectRef.current([targetId]);\n\t\t\t\t\tenterEditRef.current(targetId);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet next = selRef.current;\n\t\t\t\tif (shiftRef.current) {\n\t\t\t\t\tconst set = new Set(next);\n\t\t\t\t\tset.has(targetId) ? set.delete(targetId) : set.add(targetId);\n\t\t\t\t\tnext = [...set];\n\t\t\t\t} else if (!next.includes(targetId)) {\n\t\t\t\t\tnext = [targetId];\n\t\t\t\t}\n\t\t\t\tselectRef.current(next);\n\t\t\t\t// 이동 시작은 엔진이 관리(핸들도 함께 따라감).\n\t\t\t\tif (!readOnlyRef.current && isShapeDraggable(targetShape)) {\n\t\t\t\t\teng.beginMove(p, next);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// 그리기 도구.\n\t\t\tif (isBox(tool) && draftRef.current) {\n\t\t\t\tdrawStart = p;\n\t\t\t\tsetInteractionMode(\"drawing\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isClickPath(tool) && draftRef.current) {\n\t\t\t\tconst draftPoints = ds().getDraftPointsSnapshot();\n\t\t\t\tif (!draftPoints.length && selRef.current.length) {\n\t\t\t\t\tselectRef.current([]);\n\t\t\t\t}\n\t\t\t\tif (ds().tryClosePolygon(p, 12 / eng.viewport.scale)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst hitIndex = ds().hitDraftPoint(p);\n\t\t\t\tif (hitIndex >= 0) {\n\t\t\t\t\tif (e.altKey) {\n\t\t\t\t\t\tds().removeDraftPoint(hitIndex);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst drag = ds().selectDraftPointForDrag(hitIndex, e.shiftKey || e.ctrlKey || e.metaKey);\n\t\t\t\t\tif (!drag) return;\n\t\t\t\t\tdraftPointDrag = {\n\t\t\t\t\t\tstart: p,\n\t\t\t\t\t\tbase: drag.base,\n\t\t\t\t\t\tindices: drag.indices,\n\t\t\t\t\t\tmoved: false,\n\t\t\t\t\t};\n\t\t\t\t\tsetInteractionMode(\"vertexDragging\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tds().appendPolygonPoint(p);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (tool === TOOL.PATH && draftRef.current) {\n\t\t\t\tif (selRef.current.length) selectRef.current([]);\n\t\t\t\tstrokeKind = \"path\";\n\t\t\t\tsetInteractionMode(\"drawing\");\n\t\t\t\tds().beginStroke(p);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (tool === TOOL.BRUSH && draftRef.current && !readOnlyRef.current) {\n\t\t\t\tstrokeKind = \"scalar\";\n\t\t\t\tsetInteractionMode(\"drawing\");\n\t\t\t\tds().beginStroke(p);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// 빈 공간 SELECT = 마퀴. 단, 다중선택 bbox 안의 빈 공간(레이블 사이 틈,\n\t\t\t// 채움 없는 도형 근처)은 그룹 이동으로 처리한다 — 다중선택을 \"잡아서 옮기는\"\n\t\t\t// 도중 히트가 빗나가 마퀴로 바뀌는 문제 방지(Shift는 마퀴 추가선택 우선).\n\t\t\tif (tool === TOOL.SELECT) {\n\t\t\t\tif (!shiftRef.current && !readOnlyRef.current && selRef.current.length >= 2) {\n\t\t\t\t\tconst selShapes = docRef.current\n\t\t\t\t\t\t.getShapes()\n\t\t\t\t\t\t.filter((s) => selRef.current.includes(s.id) && isShapeDraggable(s));\n\t\t\t\t\tif (selShapes.length) {\n\t\t\t\t\t\tconst b = getBBox(selShapes.flatMap((s) => s.points));\n\t\t\t\t\t\tif (p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY) {\n\t\t\t\t\t\t\teng.beginMove(p, selRef.current);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmarquee = p;\n\t\t\t\tlastHit = \"\";\n\t\t\t\tsetInteractionMode(\"marquee\");\n\t\t\t\tsetCursorHint(null);\n\t\t\t}\n\t\t},\n\t\tonPointerMove: (p, e) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tif (pan) {\n\t\t\t\teng.applyViewport({\n\t\t\t\t\tscale: eng.viewport.scale,\n\t\t\t\t\tx: pan.x + (e.global.x - pan.px),\n\t\t\t\t\ty: pan.y + (e.global.y - pan.py),\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst tool = toolRef.current;\n\t\t\tconst externalTool = getExternalTool();\n\t\t\tif (externalTool) {\n\t\t\t\texternalTool.onPointerMove?.(makeExternalContext(eng, p, e));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (draftPointDrag) {\n\t\t\t\tconst dx = p.x - draftPointDrag.start.x;\n\t\t\t\tconst dy = p.y - draftPointDrag.start.y;\n\t\t\t\tdraftPointDrag.moved = draftPointDrag.moved || Math.hypot(dx, dy) > 0.5;\n\t\t\t\tds().moveDraftPoints(draftPointDrag.base, draftPointDrag.indices, dx, dy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (drawStart && (isBox(tool) || isAssistantBox(tool))) {\n\t\t\t\tconst end = shiftRef.current ? squareEnd(drawStart, p) : p;\n\t\t\t\teng.previewBox(tool === TOOL.CIRCLE ? \"ellipse\" : \"rect\", drawStart, end, {\n\t\t\t\t\t...draftRef.current,\n\t\t\t\t\tcolor: draftRef.current?.color ?? \"#00e5ff\",\n\t\t\t\t});\n\t\t\t\t// 어시스트 박스(프롬프트)는 라벨 대상이 아니므로 실제 그리기 도구에서만 정보 배지.\n\t\t\t\tif (isBox(tool)) {\n\t\t\t\t\tonDrawPreview({\n\t\t\t\t\t\ttype: tool === TOOL.CIRCLE ? SHAPE_TYPE.ELLIPSE : SHAPE_TYPE.RECTANGLE,\n\t\t\t\t\t\tpoints: [drawStart, end],\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (strokeKind) {\n\t\t\t\tds().appendStrokePoint(p, 2 / eng.viewport.scale);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isClickPath(tool) && ds().hasDraftPoints()) {\n\t\t\t\tds().setDraftCursor(p);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (marquee) {\n\t\t\t\t// 마퀴 비활성 시 드래그해도 박스/범위선택 없음(빈 공간 클릭 해제는 유지).\n\t\t\t\tif (disableMarqueeRef?.current) return;\n\t\t\t\tconst box = {\n\t\t\t\t\tminX: Math.min(marquee.x, p.x),\n\t\t\t\t\tminY: Math.min(marquee.y, p.y),\n\t\t\t\t\tmaxX: Math.max(marquee.x, p.x),\n\t\t\t\t\tmaxY: Math.max(marquee.y, p.y),\n\t\t\t\t};\n\t\t\t\teng.previewMarquee(marquee, p);\n\t\t\t\tconst hit = eng.shapesIntersecting(box);\n\t\t\t\tconst key = hit.join(\",\");\n\t\t\t\tif (key !== lastHit) {\n\t\t\t\t\tlastHit = key;\n\t\t\t\t\tselectRef.current(hit);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tonPointerUp: (p) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tif (pan) {\n\t\t\t\tpan = null;\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (draftPointDrag) {\n\t\t\t\tds().commitDraftPointDrag(draftPointDrag.moved);\n\t\t\t\tdraftPointDrag = null;\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst tool = toolRef.current;\n\t\t\tconst externalTool = getExternalTool();\n\t\t\tif (externalTool) {\n\t\t\t\texternalTool.onPointerUp?.(makeExternalContext(eng, p, {}));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (tool === TOOL.POINT && draftRef.current) {\n\t\t\t\tcreateRef.current(SHAPE_TYPE.POINT, [p]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (strokeKind) {\n\t\t\t\tconst kind = strokeKind;\n\t\t\t\tstrokeKind = null;\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\tif (kind === \"path\") ds().completeFreehandStroke();\n\t\t\t\telse ds().finishScalarStroke();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (drawStart && isAssistantBox(tool)) {\n\t\t\t\tconst s = drawStart;\n\t\t\t\tdrawStart = null;\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\teng.clearPreview();\n\t\t\t\tconst box = {\n\t\t\t\t\tx: Math.min(s.x, p.x),\n\t\t\t\t\ty: Math.min(s.y, p.y),\n\t\t\t\t\twidth: Math.abs(p.x - s.x),\n\t\t\t\t\theight: Math.abs(p.y - s.y),\n\t\t\t\t};\n\t\t\t\t// ASSISTANT_RECT는 결과를 사각형으로, ASSISTANT_POLYGON는 폴리곤으로 커밋.\n\t\t\t\tif (box.width > 2 && box.height > 2)\n\t\t\t\t\tassist().beginBox(box, tool === TOOL.ASSISTANT_RECT ? \"rect\" : \"polygon\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (drawStart && isBox(tool)) {\n\t\t\t\tconst end = shiftRef.current ? squareEnd(drawStart, p) : p;\n\t\t\t\tconst s = drawStart;\n\t\t\t\tdrawStart = null;\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\teng.clearPreview();\n\t\t\t\tonDrawPreview(null);\n\t\t\t\tif (Math.abs(end.x - s.x) > 2 && Math.abs(end.y - s.y) > 2) {\n\t\t\t\t\tif (tool === TOOL.ROTATED_RECTANGLE)\n\t\t\t\t\t\tcreateRef.current(SHAPE_TYPE.ROTATED_RECTANGLE, rectTo4([s, end]));\n\t\t\t\t\telse if (tool === TOOL.CIRCLE)\n\t\t\t\t\t\tcreateRef.current(SHAPE_TYPE.POLYGON, circleToPolygon(s, end));\n\t\t\t\t\telse createRef.current(SHAPE_TYPE.RECTANGLE, [s, end]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (marquee) {\n\t\t\t\tconst moved = Math.abs(p.x - marquee.x) > 3 || Math.abs(p.y - marquee.y) > 3;\n\t\t\t\tmarquee = null;\n\t\t\t\teng.clearMarquee();\n\t\t\t\tsetInteractionMode(\"idle\");\n\t\t\t\tif (!moved && selRef.current.length) selectRef.current([]);\n\t\t\t}\n\t\t},\n\t\tonViewportChange: syncMinimap,\n\t\tonTransformPreview,\n\t\tonTransformCommit: (updates) => {\n\t\t\tconst shapes = docRef.current.getShapes();\n\t\t\tconst next = updates\n\t\t\t\t.map((u) => {\n\t\t\t\t\tconst s = shapes.find((x) => x.id === u.id);\n\t\t\t\t\treturn s ? { ...s, points: u.points } : null;\n\t\t\t\t})\n\t\t\t\t.filter((s): s is EditorShape<TMeta> => !!s);\n\t\t\tif (next.length) docRef.current.update(next);\n\t\t},\n\t};\n}\n","import { type RefObject, useCallback, useRef, useState } from \"react\";\nimport {\n\ttype EditorShape,\n\tgenerateId,\n\tgetBBox,\n\tminAreaRect,\n\ttype Point,\n\tSHAPE_TYPE,\n\ttype ShapeStyle,\n} from \"../_model/geometry\";\nimport type { AssistantPrompt, EditorAssistant } from \"../_model/props\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nexport type AssistantStatus = \"idle\" | \"loading\" | \"ready\";\n\ninterface UseAssistantParams<TMeta> {\n\tdocRef: RefObject<EditorDocument<TMeta>>;\n\tdraftRef: RefObject<ShapeStyle | undefined>;\n\tdraftMeta: TMeta | undefined;\n\tchangeSelection: (ids: string[]) => void;\n\tassistantRef: RefObject<EditorAssistant | undefined>;\n}\n\ntype Box = { x: number; y: number; width: number; height: number };\n\n/**\n * AI 어시스트 세션(SAM 식). 프롬프트 수집(박스/포인트)·호스트 infer 호출·**즉시 커밋**.\n * 옵스 에디터와 동일하게 추론 결과를 프리뷰 없이 바로 도형으로 만든다.\n *\n * 두 갈래의 수명 주기(옵스 파리티):\n * - **박스 프롬프트(ASSISTANT_POLYGON/RECT)**: 드래그마다 **병렬 독립 요청** —\n * 앞 요청이 진행 중이어도 새 드래그가 그것을 취소하지 않고 각자 완료 시 커밋된다.\n * 커밋된 결과는 확정(Esc로 지워지지 않음 — 일반 undo/삭제로 다룬다).\n * - **포인트 프롬프트(마법봉)**: 단일 세션. 클릭=이전 세션 확정+새 세션, Alt+클릭=\n * 같은 도형 제자리 refine. Esc=세션 취소(이번 세션 생성분 제거 + 진행 중 응답 폐기).\n */\nexport function useAssistant<TMeta>({\n\tdocRef,\n\tdraftRef,\n\tdraftMeta,\n\tchangeSelection,\n\tassistantRef,\n}: UseAssistantParams<TMeta>) {\n\tconst [status, setStatus] = useState<AssistantStatus>(\"idle\");\n\tconst [points, setPoints] = useState<{ x: number; y: number; positive: boolean }[]>([]);\n\t// 진행 중인 박스 프롬프트들(병렬). shimmer 표시 + isActive 판단용.\n\tconst [pendingBoxes, setPendingBoxes] = useState<Box[]>([]);\n\tconst pendingBoxesRef = useRef<Box[]>([]);\n\n\tconst pointsRef = useRef<{ x: number; y: number; positive: boolean }[]>([]);\n\tconst committedRef = useRef<string[]>([]); // 포인트 세션이 만든 도형 id.\n\tconst statusRef = useRef<AssistantStatus>(\"idle\");\n\tconst tokenRef = useRef(0); // 포인트 세션 최신 요청 토큰(stale 폐기).\n\t// 기존 도형 refine 세션: base(원본 좌표)를 프롬프트에 실어 보내고, Esc 시 원복한다.\n\tconst baseRef = useRef<Point[] | null>(null);\n\tconst originalShapeRef = useRef<EditorShape<TMeta> | null>(null);\n\tconst boxEpochRef = useRef(0); // 박스 요청 세대 — cancel 시 증가, 이후 응답 폐기.\n\n\tconst mutatePending = useCallback((updater: (list: Box[]) => Box[]) => {\n\t\tpendingBoxesRef.current = updater(pendingBoxesRef.current);\n\t\tsetPendingBoxes(pendingBoxesRef.current);\n\t}, []);\n\n\tconst setStatusBoth = useCallback((s: AssistantStatus) => {\n\t\tstatusRef.current = s;\n\t\tsetStatus(s);\n\t}, []);\n\n\t/**\n\t * 결과 폴리곤(들) → 커밋 도형. rect면 바운딩(축정렬 / rotatedRect면 최소회전) 사각형.\n\t * style은 호출부가 스냅샷해 넘긴다 — 박스 요청은 드래그 시점 클래스 스타일을\n\t * 캡처해서, 추론 중 클래스를 바꿔도 결과가 어긋나지 않게 한다(레거시 파리티).\n\t */\n\tconst buildShapes = useCallback(\n\t\t(\n\t\t\tpolys: Point[][],\n\t\t\tresultShape: \"polygon\" | \"rect\",\n\t\t\tstyle: ShapeStyle,\n\t\t): EditorShape<TMeta>[] | null => {\n\t\t\tconst rotated = assistantRef.current?.rectResult === \"rotatedRect\";\n\t\t\treturn polys.map((pts) => {\n\t\t\t\tif (resultShape === \"rect\" && rotated)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: generateId(),\n\t\t\t\t\t\ttype: SHAPE_TYPE.ROTATED_RECTANGLE,\n\t\t\t\t\t\tpoints: minAreaRect(pts),\n\t\t\t\t\t\tstyle,\n\t\t\t\t\t\tmeta: draftMeta,\n\t\t\t\t\t};\n\t\t\t\tif (resultShape === \"rect\") {\n\t\t\t\t\tconst b = getBBox(pts);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: generateId(),\n\t\t\t\t\t\ttype: SHAPE_TYPE.RECTANGLE,\n\t\t\t\t\t\tpoints: [\n\t\t\t\t\t\t\t{ x: b.minX, y: b.minY },\n\t\t\t\t\t\t\t{ x: b.maxX, y: b.maxY },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tstyle,\n\t\t\t\t\t\tmeta: draftMeta,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tid: generateId(),\n\t\t\t\t\ttype: SHAPE_TYPE.POLYGON,\n\t\t\t\t\tpoints: pts,\n\t\t\t\t\tstyle,\n\t\t\t\t\tmeta: draftMeta,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\t[draftMeta, assistantRef],\n\t);\n\n\t// 확정: 포인트 세션이 만든 도형은 문서에 남기고 세션만 정리. 박스 요청엔 영향 없음.\n\tconst finalize = useCallback(() => {\n\t\ttokenRef.current++;\n\t\tpointsRef.current = [];\n\t\tcommittedRef.current = [];\n\t\tbaseRef.current = null;\n\t\toriginalShapeRef.current = null;\n\t\tsetPoints([]);\n\t\tsetStatusBoth(\"idle\");\n\t}, [setStatusBoth]);\n\n\t/**\n\t * 취소(Esc): 포인트 세션 생성분 제거 + 진행 중인 박스/포인트 응답 폐기.\n\t * 이미 커밋된 박스 결과는 유지한다(옵스와 동일 — 일반 삭제/undo로 다룬다).\n\t */\n\tconst cancel = useCallback(() => {\n\t\tboxEpochRef.current++;\n\t\tmutatePending(() => []);\n\t\tconst original = originalShapeRef.current;\n\t\tif (original) {\n\t\t\t// 기존 도형 refine 세션 — 생성분 삭제가 아니라 원본 좌표 복원.\n\t\t\tdocRef.current.update([original]);\n\t\t} else if (committedRef.current.length) {\n\t\t\tdocRef.current.remove(committedRef.current);\n\t\t}\n\t\tfinalize();\n\t}, [docRef, finalize, mutatePending]);\n\n\t// ── 포인트 세션(마법봉) — 단일 세션, 제자리 refine ──\n\n\tconst applyResult = useCallback(\n\t\t(polys: Point[][]) => {\n\t\t\tconst ids = committedRef.current;\n\t\t\tif (!polys.length) {\n\t\t\t\tif (ids.length) {\n\t\t\t\t\tdocRef.current.remove(ids);\n\t\t\t\t\tcommittedRef.current = [];\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (ids.length === polys.length) {\n\t\t\t\t// 같은 개수 → 제자리 갱신(refine).\n\t\t\t\tconst shapes = docRef.current.getShapes();\n\t\t\t\tconst updates = polys\n\t\t\t\t\t.map((pts, i) => {\n\t\t\t\t\t\tconst prev = shapes.find((s) => s.id === ids[i]);\n\t\t\t\t\t\treturn prev ? { ...prev, points: pts } : null;\n\t\t\t\t\t})\n\t\t\t\t\t.filter((s): s is EditorShape<TMeta> => !!s);\n\t\t\t\tif (updates.length) docRef.current.update(updates);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// 개수가 달라짐 → 이전 것 제거 후 새로 생성(포인트 세션 결과는 항상 폴리곤).\n\t\t\t// refine 대상이 대체되므로 원복 스냅샷은 무효화한다.\n\t\t\tbaseRef.current = null;\n\t\t\toriginalShapeRef.current = null;\n\t\t\tif (ids.length) docRef.current.remove(ids);\n\t\t\tconst style = draftRef.current;\n\t\t\tif (!style) return;\n\t\t\tconst created = buildShapes(polys, \"polygon\", style);\n\t\t\tif (!created?.length) return;\n\t\t\tdocRef.current.create(created);\n\t\t\tcommittedRef.current = created.map((s) => s.id);\n\t\t\tchangeSelection(committedRef.current);\n\t\t},\n\t\t[docRef, draftRef, changeSelection, buildShapes],\n\t);\n\n\tconst runInfer = useCallback(async () => {\n\t\tconst infer = assistantRef.current?.infer;\n\t\tif (!infer) return;\n\t\tconst prompt: AssistantPrompt = {\n\t\t\tkind: \"points\",\n\t\t\tpoints: pointsRef.current,\n\t\t\tbase: baseRef.current ?? undefined,\n\t\t};\n\t\tconst token = ++tokenRef.current;\n\t\tsetStatusBoth(\"loading\");\n\t\tlet polys: Point[][] = [];\n\t\ttry {\n\t\t\tconst result = await infer(prompt);\n\t\t\tpolys = (result ?? []).filter((p) => p.length >= 3);\n\t\t} catch {\n\t\t\tpolys = [];\n\t\t}\n\t\tif (token !== tokenRef.current) return; // stale — 더 최신 요청/취소.\n\t\tapplyResult(polys);\n\t\tsetStatusBoth(\"ready\");\n\t}, [assistantRef, applyResult, setStatusBoth]);\n\n\tconst addPoint = useCallback(\n\t\t(p: Point, positive: boolean) => {\n\t\t\t// 누적 포인트(pointsRef)는 추론 프롬프트용으로 전부 유지하되, 화면 마커(setPoints)는\n\t\t\t// 이번에 찍은 점만 표시한다(옵스식 — 진행 중인 그 점만 보이고 끝나면 사라짐).\n\t\t\tpointsRef.current = [...pointsRef.current, { x: p.x, y: p.y, positive }];\n\t\t\tsetPoints([{ x: p.x, y: p.y, positive }]);\n\t\t\trunInfer();\n\t\t},\n\t\t[runInfer],\n\t);\n\n\t// 옵스식 마법봉: 그냥 클릭 → 이전 세션 확정 후 그 점 기반 새 폴리곤 생성.\n\tconst newPolygon = useCallback(\n\t\t(p: Point) => {\n\t\t\tfinalize();\n\t\t\tconst next = [{ x: p.x, y: p.y, positive: true }];\n\t\t\tpointsRef.current = next;\n\t\t\tsetPoints(next);\n\t\t\trunInfer();\n\t\t},\n\t\t[finalize, runInfer],\n\t);\n\n\t/**\n\t * 기존 도형을 지정 지점으로 refine(우클릭 메뉴 \"이 지점 포함/제외\").\n\t * 같은 도형이면 세션을 이어 포인트를 누적하고, 다른 도형이면 새 refine 세션을\n\t * 시작한다(원본 좌표를 base로 프롬프트에 실어 제자리 갱신, Esc=원복).\n\t */\n\tconst refineShape = useCallback(\n\t\t(shape: EditorShape<TMeta>, p: Point, positive: boolean) => {\n\t\t\tif (committedRef.current.length !== 1 || committedRef.current[0] !== shape.id) {\n\t\t\t\tfinalize();\n\t\t\t\tcommittedRef.current = [shape.id];\n\t\t\t\tbaseRef.current = shape.points;\n\t\t\t\toriginalShapeRef.current = shape;\n\t\t\t}\n\t\t\tpointsRef.current = [...pointsRef.current, { x: p.x, y: p.y, positive }];\n\t\t\tsetPoints([{ x: p.x, y: p.y, positive }]);\n\t\t\trunInfer();\n\t\t},\n\t\t[finalize, runInfer],\n\t);\n\n\t// ── 박스 프롬프트 — 병렬 독립 요청(옵스식: 연속 드래그가 서로를 취소하지 않음) ──\n\n\tconst beginBox = useCallback(\n\t\t(b: Box, resultShape: \"polygon\" | \"rect\" = \"polygon\") => {\n\t\t\tconst infer = assistantRef.current?.infer;\n\t\t\tconst style = draftRef.current; // 드래그 시점 클래스 스타일 스냅샷.\n\t\t\tif (!infer || !style) return;\n\t\t\tconst epoch = boxEpochRef.current;\n\t\t\tmutatePending((list) => [...list, b]);\n\t\t\tvoid (async () => {\n\t\t\t\tlet polys: Point[][] = [];\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await infer({ kind: \"box\", box: b });\n\t\t\t\t\tpolys = (result ?? []).filter((p) => p.length >= 3);\n\t\t\t\t} catch {\n\t\t\t\t\tpolys = [];\n\t\t\t\t}\n\t\t\t\tmutatePending((list) => list.filter((x) => x !== b));\n\t\t\t\tif (epoch !== boxEpochRef.current) return; // 취소됨 — 결과 폐기.\n\t\t\t\tconst created = buildShapes(polys, resultShape, style);\n\t\t\t\tif (!created?.length) return;\n\t\t\t\tdocRef.current.create(created);\n\t\t\t\tchangeSelection(created.map((s) => s.id));\n\t\t\t})();\n\t\t},\n\t\t[assistantRef, draftRef, buildShapes, changeSelection, docRef, mutatePending],\n\t);\n\n\tconst isActive = useCallback(\n\t\t() =>\n\t\t\tstatusRef.current === \"loading\" ||\n\t\t\tpointsRef.current.length > 0 ||\n\t\t\tpendingBoxesRef.current.length > 0 ||\n\t\t\tcommittedRef.current.length > 0,\n\t\t[],\n\t);\n\n\treturn {\n\t\tstatus,\n\t\tpoints,\n\t\t/** 진행 중인 박스 프롬프트들(병렬). 오버레이 shimmer 표시용. */\n\t\tboxes: pendingBoxes,\n\t\tbeginBox,\n\t\taddPoint,\n\t\tnewPolygon,\n\t\trefineShape,\n\t\tfinalize,\n\t\tcancel,\n\t\tisActive,\n\t};\n}\n\nexport type AssistantSession<TMeta> = ReturnType<typeof useAssistant<TMeta>>;\n","import type { Point } from \"./geometry\";\n\nfunction perpendicularDistance(point: Point, lineStart: Point, lineEnd: Point) {\n\tconst area = Math.abs(\n\t\t0.5 *\n\t\t\t(lineStart.x * lineEnd.y +\n\t\t\t\tlineEnd.x * point.y +\n\t\t\t\tpoint.x * lineStart.y -\n\t\t\t\tlineEnd.x * lineStart.y -\n\t\t\t\tpoint.x * lineEnd.y -\n\t\t\t\tlineStart.x * point.y),\n\t);\n\tconst bottom = Math.hypot(lineStart.x - lineEnd.x, lineStart.y - lineEnd.y);\n\treturn bottom === 0 ? 0 : (area * 2) / bottom;\n}\n\n/** RDP 경로 단순화(이미지 좌표). */\nexport function simplifyPath(points: Point[], epsilon = 1.5): Point[] {\n\tif (points.length <= 2) return points;\n\n\tconst rdp = (pts: Point[], eps: number): Point[] => {\n\t\tif (pts.length < 3) return pts;\n\t\tlet dmax = 0;\n\t\tlet index = 0;\n\t\tconst end = pts.length - 1;\n\t\tfor (let i = 1; i < end; i++) {\n\t\t\tconst d = perpendicularDistance(pts[i], pts[0], pts[end]);\n\t\t\tif (d > dmax) {\n\t\t\t\tindex = i;\n\t\t\t\tdmax = d;\n\t\t\t}\n\t\t}\n\t\tif (dmax > eps) {\n\t\t\tconst left = rdp(pts.slice(0, index + 1), eps);\n\t\t\tconst right = rdp(pts.slice(index), eps);\n\t\t\treturn left.slice(0, -1).concat(right);\n\t\t}\n\t\treturn [pts[0], pts[end]];\n\t};\n\n\tconst simplified = rdp(points, epsilon);\n\tconst last = points[points.length - 1];\n\tconst tail = simplified[simplified.length - 1];\n\tif (last.x !== tail.x || last.y !== tail.y) simplified.push(last);\n\treturn simplified;\n}\n","import { simplifyPath } from \"./brush\";\nimport {\n\tcircleToPolygon,\n\ttype EditorShape,\n\tgetBBox,\n\ttype Point,\n\trectTo4,\n\tSHAPE_TYPE,\n} from \"./geometry\";\n\nconst MAX_CANVAS_DIM = 4096;\nconst MIN_POLYGON_AREA = 4;\n\nfunction polygonArea(points: Point[]): number {\n\tlet sum = 0;\n\tfor (let i = 0; i < points.length; i++) {\n\t\tconst a = points[i];\n\t\tconst b = points[(i + 1) % points.length];\n\t\tsum += a.x * b.y - b.x * a.y;\n\t}\n\treturn Math.abs(sum / 2);\n}\n\nfunction extractAlpha(data: Uint8ClampedArray, width: number, height: number): Uint8Array {\n\tconst alpha = new Uint8Array(width * height);\n\tfor (let i = 0; i < width * height; i++) {\n\t\talpha[i] = data[i * 4 + 3] > 128 ? 255 : 0;\n\t}\n\treturn alpha;\n}\n\nfunction alphaToRgba(alpha: Uint8Array): Uint8ClampedArray {\n\tconst data = new Uint8ClampedArray(alpha.length * 4);\n\tfor (let i = 0; i < alpha.length; i++) {\n\t\tif (alpha[i] > 128) data[i * 4 + 3] = 255;\n\t}\n\treturn data;\n}\n\nfunction floodFillComponent(\n\twork: Uint8Array,\n\twidth: number,\n\theight: number,\n\tsx: number,\n\tsy: number,\n): Uint8Array {\n\tconst component = new Uint8Array(width * height);\n\tconst stack: [number, number][] = [[sx, sy]];\n\twhile (stack.length) {\n\t\tconst [x, y] = stack.pop()!;\n\t\tconst idx = y * width + x;\n\t\tif (x < 0 || y < 0 || x >= width || y >= height) continue;\n\t\tif (work[idx] <= 128) continue;\n\t\twork[idx] = 0;\n\t\tcomponent[idx] = 255;\n\t\tstack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);\n\t}\n\treturn component;\n}\n\n/** 마스크에서 분리된 모든 외곽선을 추출. */\nfunction traceAllOuterContours(data: Uint8ClampedArray, width: number, height: number): Point[][] {\n\tconst work = extractAlpha(data, width, height);\n\tconst contours: Point[][] = [];\n\n\twhile (true) {\n\t\tlet sx = -1;\n\t\tlet sy = -1;\n\t\touter: for (let y = 0; y < height; y++) {\n\t\t\tfor (let x = 0; x < width; x++) {\n\t\t\t\tif (work[y * width + x] > 128) {\n\t\t\t\t\tsx = x;\n\t\t\t\t\tsy = y;\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (sx < 0) break;\n\n\t\tconst component = floodFillComponent(work, width, height, sx, sy);\n\t\tconst contour = traceOuterContour(alphaToRgba(component), width, height);\n\t\tif (contour.length >= 3) contours.push(contour);\n\t}\n\n\treturn contours;\n}\n\nexport type ScalarStrokeMode = \"add\" | \"erase\";\n\nexport interface ScalarStroke {\n\tpoints: Point[];\n\tmode: ScalarStrokeMode;\n}\n\nexport interface ScalarMaskRaster {\n\tcanvas: HTMLCanvasElement;\n\tox: number;\n\toy: number;\n\tscale: number;\n}\n\nfunction isFilled(data: Uint8ClampedArray, width: number, height: number, x: number, y: number) {\n\tif (x < 0 || y < 0 || x >= width || y >= height) return false;\n\treturn data[(y * width + x) * 4 + 3] > 128;\n}\n\n/** 채워진 영역의 외곽선을 Moore-neighbor로 추적. */\nfunction traceOuterContour(data: Uint8ClampedArray, width: number, height: number): Point[] {\n\tlet sx = -1;\n\tlet sy = -1;\n\touter: for (let y = 0; y < height; y++) {\n\t\tfor (let x = 0; x < width; x++) {\n\t\t\tif (isFilled(data, width, height, x, y)) {\n\t\t\t\tsx = x;\n\t\t\t\tsy = y;\n\t\t\t\tbreak outer;\n\t\t\t}\n\t\t}\n\t}\n\tif (sx < 0) return [];\n\n\tconst dx = [1, 1, 0, -1, -1, -1, 0, 1];\n\tconst dy = [0, 1, 1, 1, 0, -1, -1, -1];\n\tconst contour: Point[] = [];\n\tlet x = sx;\n\tlet y = sy;\n\tlet dir = 7;\n\tconst start = { x, y };\n\tlet guard = 0;\n\n\tdo {\n\t\tcontour.push({ x, y });\n\t\tlet found = false;\n\t\tfor (let i = 0; i < 8; i++) {\n\t\t\tconst nd = (dir + i) % 8;\n\t\t\tconst nx = x + dx[nd];\n\t\t\tconst ny = y + dy[nd];\n\t\t\tif (isFilled(data, width, height, nx, ny)) {\n\t\t\t\tx = nx;\n\t\t\t\ty = ny;\n\t\t\t\tdir = (nd + 6) % 8;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!found) break;\n\t\tguard += 1;\n\t\tif (guard > width * height * 4) break;\n\t} while (x !== start.x || y !== start.y || contour.length === 1);\n\n\treturn contour;\n}\n\nfunction collectPoints(strokes: ScalarStroke[], basePolygons: Point[][]): Point[] {\n\tconst all: Point[] = [];\n\tfor (const stroke of strokes) {\n\t\tfor (const p of stroke.points) all.push(p);\n\t}\n\tfor (const poly of basePolygons) {\n\t\tfor (const p of poly) all.push(p);\n\t}\n\treturn all;\n}\n\n/** 면적 편집 가능한 도형 → 채움 폴리곤 꼭짓점. */\nfunction shapeToFilledPolygon(shape: EditorShape): Point[] | null {\n\tswitch (shape.type) {\n\t\tcase SHAPE_TYPE.RECTANGLE:\n\t\t\tif (shape.points.length < 2) return null;\n\t\t\treturn rectTo4(shape.points);\n\t\tcase SHAPE_TYPE.POLYGON:\n\t\tcase SHAPE_TYPE.ROTATED_RECTANGLE:\n\t\tcase SHAPE_TYPE.ELLIPSE:\n\t\t\treturn shape.points.length >= 3 ? shape.points : null;\n\t\tcase SHAPE_TYPE.POINT: {\n\t\t\tconst p = shape.points[0];\n\t\t\tif (!p) return null;\n\t\t\tconst r = 6;\n\t\t\treturn circleToPolygon({ x: p.x - r, y: p.y - r }, { x: p.x + r, y: p.y + r });\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nexport function shapesToFilledPolygons(shapes: EditorShape[]): Point[][] {\n\treturn shapes\n\t\t.map(shapeToFilledPolygon)\n\t\t.filter((points): points is Point[] => !!points && points.length >= 3);\n}\n\n/** 붓/지우개 스트로크(+ 선택 도형 베이스)를 이진 마스크 캔버스로 래스터화. */\nexport function buildScalarMaskRaster(\n\tstrokes: ScalarStroke[],\n\tradius: number,\n\tbasePolygons: Point[][] = [],\n): ScalarMaskRaster | null {\n\tif (radius <= 0) return null;\n\tif (!strokes.length && !basePolygons.length) return null;\n\n\tconst allPoints = collectPoints(strokes, basePolygons);\n\tif (!allPoints.length) return null;\n\n\tconst padding = radius + 4;\n\tconst bbox = getBBox(allPoints);\n\tlet width = Math.ceil(bbox.maxX - bbox.minX + padding * 2);\n\tlet height = Math.ceil(bbox.maxY - bbox.minY + padding * 2);\n\tconst scale = Math.min(1, MAX_CANVAS_DIM / Math.max(width, height, 1));\n\twidth = Math.max(1, Math.ceil(width * scale));\n\theight = Math.max(1, Math.ceil(height * scale));\n\n\tconst ox = bbox.minX - padding;\n\tconst oy = bbox.minY - padding;\n\tconst toLocal = (p: Point) => ({\n\t\tx: (p.x - ox) * scale,\n\t\ty: (p.y - oy) * scale,\n\t});\n\n\tconst canvas = document.createElement(\"canvas\");\n\tcanvas.width = width;\n\tcanvas.height = height;\n\tconst ctx = canvas.getContext(\"2d\");\n\tif (!ctx) return null;\n\n\tctx.lineCap = \"round\";\n\tctx.lineJoin = \"round\";\n\tctx.lineWidth = radius * 2 * scale;\n\n\tctx.fillStyle = \"#000\";\n\tfor (const poly of basePolygons) {\n\t\tif (poly.length < 3) continue;\n\t\tctx.beginPath();\n\t\tconst start = toLocal(poly[0]);\n\t\tctx.moveTo(start.x, start.y);\n\t\tfor (let i = 1; i < poly.length; i++) {\n\t\t\tconst p = toLocal(poly[i]);\n\t\t\tctx.lineTo(p.x, p.y);\n\t\t}\n\t\tctx.closePath();\n\t\tctx.fill();\n\t}\n\n\tfor (const stroke of strokes) {\n\t\tif (!stroke.points.length) continue;\n\t\tctx.globalCompositeOperation = stroke.mode === \"erase\" ? \"destination-out\" : \"source-over\";\n\t\tctx.strokeStyle = stroke.mode === \"erase\" ? \"rgba(0,0,0,1)\" : \"#000\";\n\t\tctx.beginPath();\n\t\tconst first = toLocal(stroke.points[0]);\n\t\tctx.moveTo(first.x, first.y);\n\t\tfor (let i = 1; i < stroke.points.length; i++) {\n\t\t\tconst p = toLocal(stroke.points[i]);\n\t\t\tctx.lineTo(p.x, p.y);\n\t\t}\n\t\tif (stroke.points.length === 1) {\n\t\t\tctx.lineTo(first.x + 0.01, first.y);\n\t\t}\n\t\tctx.stroke();\n\t}\n\n\treturn { canvas, ox, oy, scale };\n}\n\n/** 스칼라 마스크를 분리된 폴리곤 외곽선들로 변환. */\nexport function scalarMaskToPolygons(raster: ScalarMaskRaster, simplifyEpsilon = 1.5): Point[][] {\n\tconst { canvas, ox, oy, scale } = raster;\n\tconst contours = traceAllOuterContours(\n\t\tcanvas.getContext(\"2d\")!.getImageData(0, 0, canvas.width, canvas.height).data,\n\t\tcanvas.width,\n\t\tcanvas.height,\n\t);\n\tif (!contours.length) return [];\n\n\tconst toWorld = (p: Point) => ({\n\t\tx: p.x / scale + ox,\n\t\ty: p.y / scale + oy,\n\t});\n\n\tconst polys: Point[][] = [];\n\tfor (const contour of contours) {\n\t\tconst world = contour.map(toWorld);\n\t\tconst simplified = simplifyPath(world, simplifyEpsilon);\n\t\tconst points = simplified.length >= 3 ? simplified : world;\n\t\tif (points.length >= 3 && polygonArea(points) >= MIN_POLYGON_AREA) {\n\t\t\tpolys.push(points);\n\t\t}\n\t}\n\treturn polys;\n}\n\nexport { polygonArea };\n\n/** 미리보기용 색상 오버레이 캔버스. */\nexport function buildScalarMaskPreviewCanvas(\n\traster: ScalarMaskRaster,\n\tcolor: string,\n): HTMLCanvasElement {\n\tconst { canvas } = raster;\n\tconst preview = document.createElement(\"canvas\");\n\tpreview.width = canvas.width;\n\tpreview.height = canvas.height;\n\tconst ctx = preview.getContext(\"2d\");\n\tif (!ctx) return canvas;\n\n\tctx.drawImage(canvas, 0, 0);\n\tctx.globalCompositeOperation = \"source-in\";\n\tctx.fillStyle = color;\n\tctx.fillRect(0, 0, preview.width, preview.height);\n\treturn preview;\n}\n","import type { Point } from \"../_model/geometry\";\nimport type { ScalarStroke } from \"../_model/scalarMask\";\n\nexport function cloneScalarStrokes(strokes: ScalarStroke[]): ScalarStroke[] {\n\treturn strokes.map((stroke) => ({\n\t\tmode: stroke.mode,\n\t\tpoints: stroke.points.map((point) => ({ ...point })),\n\t}));\n}\n\nexport function scalarStrokesEqual(a: ScalarStroke[], b: ScalarStroke[]) {\n\treturn (\n\t\ta.length === b.length &&\n\t\ta.every(\n\t\t\t(stroke, i) =>\n\t\t\t\tstroke.mode === b[i].mode &&\n\t\t\t\tstroke.points.length === b[i].points.length &&\n\t\t\t\tstroke.points.every((p, j) => p.x === b[i].points[j].x && p.y === b[i].points[j].y),\n\t\t)\n\t);\n}\n\nexport function clonePoints(points: Point[]): Point[] {\n\treturn points.map((p) => ({ ...p }));\n}\n\nexport function pointsEqual(a: Point[], b: Point[]) {\n\treturn a.length === b.length && a.every((p, i) => p.x === b[i].x && p.y === b[i].y);\n}\n","import { type RefObject, useCallback, useRef } from \"react\";\nimport { simplifyPath } from \"../_model/brush\";\nimport {\n\ttype EditorShape,\n\tgenerateId,\n\tisShapeEditable,\n\ttype Point,\n\tSHAPE_TYPE,\n\ttype ShapeStyle,\n} from \"../_model/geometry\";\nimport type { DrawSessionChange, DrawSessionKind } from \"../_model/props\";\nimport {\n\tbuildScalarMaskRaster,\n\tpolygonArea,\n\ttype ScalarStroke,\n\tscalarMaskToPolygons,\n\tshapesToFilledPolygons,\n} from \"../_model/scalarMask\";\nimport { type BrushScalarMode, TOOL, type Tool } from \"../_model/tools\";\nimport type { EditorRenderer } from \"../_renderers/types\";\nimport {\n\tclonePoints,\n\tcloneScalarStrokes,\n\tpointsEqual,\n\tscalarStrokesEqual,\n} from \"./drawSessionState\";\nimport type { useEditorDocument } from \"./useEditorDocument\";\n\nconst DRAFT_POINT_HIT_RADIUS = 10;\n\ntype DocApi<TMeta> = ReturnType<typeof useEditorDocument<TMeta>>;\n\n/** useDrawSession가 반환하는 그리기 세션 핸들. */\nexport type DrawSession<TMeta> = ReturnType<typeof useDrawSession<TMeta>>;\n\ninterface UseDrawSessionParams<TMeta> {\n\ttoolRef: RefObject<Tool>;\n\tselRef: RefObject<string[]>;\n\tdocRef: RefObject<DocApi<TMeta>>;\n\treadOnlyRef: RefObject<boolean | undefined>;\n\tdraftRef: RefObject<ShapeStyle | undefined>;\n\tbrushSizeRef: RefObject<number>;\n\t/** 자유선/붓→폴리곤 단순화 강도(RDP epsilon). */\n\tsimplifyEpsilonRef: RefObject<number>;\n\tdraftMeta: TMeta | undefined;\n\tengineRef: RefObject<EditorRenderer | null>;\n\tonDrawSessionChange?: (session: DrawSessionChange) => void;\n\tonDraftShapeChange?: (shape: Pick<EditorShape<TMeta>, \"type\" | \"points\" | \"meta\"> | null) => void;\n\tchangeSelection: (ids: string[]) => void;\n\tcreateShape: (type: EditorShape<TMeta>[\"type\"], points: Point[]) => void;\n}\n\nexport function useDrawSession<TMeta>({\n\ttoolRef,\n\tselRef,\n\tdocRef,\n\treadOnlyRef,\n\tdraftRef,\n\tbrushSizeRef,\n\tsimplifyEpsilonRef,\n\tdraftMeta,\n\tengineRef,\n\tonDrawSessionChange,\n\tonDraftShapeChange,\n\tchangeSelection,\n\tcreateShape,\n}: UseDrawSessionParams<TMeta>) {\n\tconst onDrawSessionChangeRef = useRef(onDrawSessionChange);\n\tonDrawSessionChangeRef.current = onDrawSessionChange;\n\tconst onDraftShapeChangeRef = useRef(onDraftShapeChange);\n\tonDraftShapeChangeRef.current = onDraftShapeChange;\n\tconst draftMetaRef = useRef(draftMeta);\n\tdraftMetaRef.current = draftMeta;\n\tconst createShapeRef = useRef(createShape);\n\tcreateShapeRef.current = createShape;\n\n\tconst draftPathRef = useRef<Point[]>([]);\n\tconst draftCursorRef = useRef<Point | null>(null);\n\tconst draftSelectedPointIndicesRef = useRef<Set<number>>(new Set());\n\tconst draftHistoryRef = useRef<Point[][]>([[]]);\n\tconst draftHistoryIndexRef = useRef(0);\n\tconst draftPreviewSignatureRef = useRef(\"\");\n\n\tconst scalarStrokesRef = useRef<ScalarStroke[]>([]);\n\tconst scalarBasePolygonsRef = useRef<Point[][]>([]);\n\tconst scalarEditTargetIdsRef = useRef<string[]>([]);\n\tconst scalarHistoryRef = useRef<ScalarStroke[][]>([[]]);\n\tconst scalarHistoryIndexRef = useRef(0);\n\tconst brushScalarModeRef = useRef<BrushScalarMode>(\"draw\");\n\n\tconst brushStrokeMode = (): ScalarStroke[\"mode\"] =>\n\t\tbrushScalarModeRef.current === \"erase\" ? \"erase\" : \"add\";\n\n\tconst getBrushSessionActive = () =>\n\t\tscalarEditTargetIdsRef.current.length > 0 ||\n\t\tscalarStrokesRef.current.length > 0 ||\n\t\t(toolRef.current === TOOL.BRUSH && draftPathRef.current.length > 0);\n\n\tconst getDrawSessionKind = (): DrawSessionKind => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH && getBrushSessionActive()) return \"brush\";\n\t\tif (tool === TOOL.POLYGON && draftPathRef.current.length > 0) {\n\t\t\treturn \"polygon\";\n\t\t}\n\t\tif (tool === TOOL.PATH && draftPathRef.current.length > 0) return \"path\";\n\t\treturn \"none\";\n\t};\n\n\tconst canUndoBrushSession = () =>\n\t\tdraftPathRef.current.length > 0 || scalarHistoryIndexRef.current > 0;\n\n\tconst canRedoBrushSession = () =>\n\t\tdraftPathRef.current.length === 0 &&\n\t\tscalarHistoryIndexRef.current < scalarHistoryRef.current.length - 1;\n\n\tconst canUndoPolygonSession = () => draftHistoryIndexRef.current > 0;\n\n\tconst canRedoPolygonSession = () =>\n\t\tdraftHistoryIndexRef.current < draftHistoryRef.current.length - 1;\n\n\tconst canUndoSession = () => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) return canUndoBrushSession();\n\t\tif (tool === TOOL.POLYGON || tool === TOOL.PATH) {\n\t\t\treturn canUndoPolygonSession();\n\t\t}\n\t\treturn false;\n\t};\n\n\tconst canRedoSession = () => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) return canRedoBrushSession();\n\t\tif (tool === TOOL.POLYGON || tool === TOOL.PATH) {\n\t\t\treturn canRedoPolygonSession();\n\t\t}\n\t\treturn false;\n\t};\n\n\tconst hasDraftSession = () => getDrawSessionKind() !== \"none\";\n\n\tconst notifyDrawSession = useCallback(() => {\n\t\tconst kind = getDrawSessionKind();\n\t\tonDrawSessionChangeRef.current?.({\n\t\t\tactive: kind !== \"none\",\n\t\t\tkind,\n\t\t\tcanUndo: canUndoSession(),\n\t\t\tcanRedo: canRedoSession(),\n\t\t\tbrush:\n\t\t\t\tkind === \"brush\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tmode: brushScalarModeRef.current,\n\t\t\t\t\t\t\tediting: scalarEditTargetIdsRef.current.length > 0,\n\t\t\t\t\t\t\teditTargetIds: [...scalarEditTargetIdsRef.current],\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t});\n\t}, []);\n\n\tconst resetScalarHistory = useCallback(() => {\n\t\tscalarHistoryRef.current = [[]];\n\t\tscalarHistoryIndexRef.current = 0;\n\t}, []);\n\n\tconst renderPreview = useCallback(() => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return;\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) {\n\t\t\tconst strokes: ScalarStroke[] = [...scalarStrokesRef.current];\n\t\t\tif (draftPathRef.current.length) {\n\t\t\t\tstrokes.push({\n\t\t\t\t\tpoints: draftPathRef.current,\n\t\t\t\t\tmode: brushStrokeMode(),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!strokes.length && !scalarBasePolygonsRef.current.length) {\n\t\t\t\teng.clearPreview();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst raster = buildScalarMaskRaster(\n\t\t\t\tstrokes,\n\t\t\t\tbrushSizeRef.current,\n\t\t\t\tscalarBasePolygonsRef.current,\n\t\t\t);\n\t\t\tif (!raster) {\n\t\t\t\teng.clearPreview();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst color = draftRef.current?.color ?? \"#00e5ff\";\n\t\t\teng.previewScalarMask(raster, color);\n\t\t\treturn;\n\t\t}\n\t\tconst points = draftPathRef.current;\n\t\tif (!points.length) {\n\t\t\teng.clearPreview();\n\t\t\tif (tool === TOOL.POLYGON && draftPreviewSignatureRef.current) {\n\t\t\t\tdraftPreviewSignatureRef.current = \"\";\n\t\t\t\tonDraftShapeChangeRef.current?.(null);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst style = {\n\t\t\t...draftRef.current,\n\t\t\tcolor: draftRef.current?.color ?? \"#00e5ff\",\n\t\t};\n\t\tconst selected = Array.from(draftSelectedPointIndicesRef.current);\n\t\t// PATH(자유선/펜)은 정점을 찍는 방식이 아니므로 그리는 중 점을 숨기고 선만 보여준다.\n\t\tconst showVertices = tool !== TOOL.PATH;\n\t\teng.previewPoly(points, draftCursorRef.current, style, false, selected, showVertices);\n\t\tif (tool === TOOL.POLYGON) {\n\t\t\tconst signature = points.map((point) => `${point.x},${point.y}`).join(\";\");\n\t\t\tif (signature !== draftPreviewSignatureRef.current) {\n\t\t\t\tdraftPreviewSignatureRef.current = signature;\n\t\t\t\tonDraftShapeChangeRef.current?.({\n\t\t\t\t\ttype: SHAPE_TYPE.POLYGON,\n\t\t\t\t\tpoints: clonePoints(points),\n\t\t\t\t\tmeta: draftMetaRef.current,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}, [brushSizeRef, draftRef, engineRef, toolRef]);\n\n\tconst pushScalarHistory = useCallback(\n\t\t(strokes: ScalarStroke[]) => {\n\t\t\tconst snapshot = cloneScalarStrokes(strokes);\n\t\t\tconst history = scalarHistoryRef.current;\n\t\t\tconst index = scalarHistoryIndexRef.current;\n\t\t\tconst last = history[index];\n\t\t\tif (last && scalarStrokesEqual(last, snapshot)) return;\n\t\t\tscalarHistoryRef.current = [...history.slice(0, index + 1), snapshot];\n\t\t\tscalarHistoryIndexRef.current += 1;\n\t\t\tnotifyDrawSession();\n\t\t},\n\t\t[notifyDrawSession],\n\t);\n\n\tconst pushDraftHistory = useCallback((points: Point[]) => {\n\t\tconst history = draftHistoryRef.current;\n\t\tconst index = draftHistoryIndexRef.current;\n\t\tconst last = history[index];\n\t\tif (last && pointsEqual(last, points)) return;\n\t\tdraftHistoryRef.current = [...history.slice(0, index + 1), clonePoints(points)];\n\t\tdraftHistoryIndexRef.current += 1;\n\t}, []);\n\n\tconst reset = useCallback(() => {\n\t\tdraftPathRef.current = [];\n\t\tscalarStrokesRef.current = [];\n\t\tscalarBasePolygonsRef.current = [];\n\t\tscalarEditTargetIdsRef.current = [];\n\t\tdraftCursorRef.current = null;\n\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\tdraftHistoryRef.current = [[]];\n\t\tdraftHistoryIndexRef.current = 0;\n\t\tdraftPreviewSignatureRef.current = \"\";\n\t\tresetScalarHistory();\n\t\tengineRef.current?.clearPreview();\n\t\tonDraftShapeChangeRef.current?.(null);\n\t\tnotifyDrawSession();\n\t}, [engineRef, notifyDrawSession, resetScalarHistory]);\n\n\tconst setDraftPath = useCallback(\n\t\t(points: Point[], commitHistory: boolean) => {\n\t\t\tdraftPathRef.current = points;\n\t\t\tconst validIndices = new Set(\n\t\t\t\tArray.from(draftSelectedPointIndicesRef.current).filter(\n\t\t\t\t\t(index) => index >= 0 && index < points.length,\n\t\t\t\t),\n\t\t\t);\n\t\t\tdraftSelectedPointIndicesRef.current = validIndices;\n\t\t\tif (commitHistory) pushDraftHistory(points);\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t},\n\t\t[notifyDrawSession, pushDraftHistory, renderPreview],\n\t);\n\n\tconst getDraftPointsSnapshot = useCallback(() => clonePoints(draftPathRef.current), []);\n\n\tconst hasDraftPoints = useCallback(() => draftPathRef.current.length > 0, []);\n\n\tconst tryClosePolygon = useCallback(\n\t\t(p: Point, closeRadius: number) => {\n\t\t\tif (toolRef.current !== TOOL.POLYGON) return false;\n\t\t\tconst points = draftPathRef.current;\n\t\t\tif (points.length < 3) return false;\n\t\t\tconst first = points[0];\n\t\t\tif (Math.hypot(p.x - first.x, p.y - first.y) > closeRadius) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcreateShapeRef.current(SHAPE_TYPE.POLYGON, points);\n\t\t\treset();\n\t\t\treturn true;\n\t\t},\n\t\t[reset, toolRef],\n\t);\n\n\tconst removeDraftPoint = useCallback(\n\t\t(index: number) => {\n\t\t\tconst points = draftPathRef.current;\n\t\t\tif (index < 0 || index >= points.length) return false;\n\t\t\tsetDraftPath(\n\t\t\t\tpoints.filter((_, pointIndex) => pointIndex !== index),\n\t\t\t\ttrue,\n\t\t\t);\n\t\t\treturn true;\n\t\t},\n\t\t[setDraftPath],\n\t);\n\n\tconst selectDraftPointForDrag = useCallback(\n\t\t(index: number, additive: boolean) => {\n\t\t\tconst points = draftPathRef.current;\n\t\t\tif (index < 0 || index >= points.length) return null;\n\t\t\tconst selected = new Set(draftSelectedPointIndicesRef.current);\n\t\t\tif (additive) {\n\t\t\t\tif (selected.has(index)) selected.delete(index);\n\t\t\t\telse selected.add(index);\n\t\t\t} else if (!selected.has(index)) {\n\t\t\t\tselected.clear();\n\t\t\t\tselected.add(index);\n\t\t\t}\n\t\t\tdraftSelectedPointIndicesRef.current = selected;\n\t\t\tdraftCursorRef.current = null;\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t\treturn {\n\t\t\t\tbase: clonePoints(points),\n\t\t\t\tindices: Array.from(selected),\n\t\t\t};\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst appendPolygonPoint = useCallback(\n\t\t(p: Point) => {\n\t\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\t\tdraftCursorRef.current = p;\n\t\t\tsetDraftPath([...draftPathRef.current, p], true);\n\t\t},\n\t\t[setDraftPath],\n\t);\n\n\tconst beginStroke = useCallback(\n\t\t(p: Point) => {\n\t\t\tdraftCursorRef.current = null;\n\t\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\t\tdraftPathRef.current = [{ ...p }];\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst appendStrokePoint = useCallback(\n\t\t(p: Point, step: number) => {\n\t\t\tconst last = draftPathRef.current[draftPathRef.current.length - 1];\n\t\t\tif (last && Math.hypot(p.x - last.x, p.y - last.y) < step) return false;\n\t\t\tdraftPathRef.current = [...draftPathRef.current, { ...p }];\n\t\t\tdraftCursorRef.current = null;\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t\treturn true;\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst moveDraftPoints = useCallback(\n\t\t(base: Point[], indices: number[], dx: number, dy: number) => {\n\t\t\tconst moving = new Set(indices);\n\t\t\tdraftPathRef.current = base.map((point, index) =>\n\t\t\t\tmoving.has(index) ? { x: point.x + dx, y: point.y + dy } : { ...point },\n\t\t\t);\n\t\t\tdraftCursorRef.current = null;\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst commitDraftPointDrag = useCallback(\n\t\t(moved: boolean) => {\n\t\t\tif (moved) {\n\t\t\t\tpushDraftHistory(draftPathRef.current);\n\t\t\t\trenderPreview();\n\t\t\t\tnotifyDrawSession();\n\t\t\t}\n\t\t},\n\t\t[notifyDrawSession, pushDraftHistory, renderPreview],\n\t);\n\n\tconst setDraftCursor = useCallback(\n\t\t(p: Point | null) => {\n\t\t\tdraftCursorRef.current = p ? { ...p } : null;\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst undoBrush = useCallback(() => {\n\t\tif (draftPathRef.current.length > 0) {\n\t\t\tdraftPathRef.current = [];\n\t\t\trenderPreview();\n\t\t\tnotifyDrawSession();\n\t\t\treturn true;\n\t\t}\n\t\tif (scalarHistoryIndexRef.current <= 0) return false;\n\t\tscalarHistoryIndexRef.current -= 1;\n\t\tscalarStrokesRef.current = cloneScalarStrokes(\n\t\t\tscalarHistoryRef.current[scalarHistoryIndexRef.current],\n\t\t);\n\t\trenderPreview();\n\t\tnotifyDrawSession();\n\t\treturn true;\n\t}, [notifyDrawSession, renderPreview]);\n\n\tconst redoBrush = useCallback(() => {\n\t\tif (draftPathRef.current.length > 0) return false;\n\t\tif (scalarHistoryIndexRef.current >= scalarHistoryRef.current.length - 1) {\n\t\t\treturn false;\n\t\t}\n\t\tscalarHistoryIndexRef.current += 1;\n\t\tscalarStrokesRef.current = cloneScalarStrokes(\n\t\t\tscalarHistoryRef.current[scalarHistoryIndexRef.current],\n\t\t);\n\t\trenderPreview();\n\t\tnotifyDrawSession();\n\t\treturn true;\n\t}, [notifyDrawSession, renderPreview]);\n\n\tconst undoPolygon = useCallback(() => {\n\t\tif (draftHistoryIndexRef.current <= 0) return false;\n\t\tdraftHistoryIndexRef.current -= 1;\n\t\tdraftPathRef.current = clonePoints(draftHistoryRef.current[draftHistoryIndexRef.current]);\n\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\trenderPreview();\n\t\tnotifyDrawSession();\n\t\treturn true;\n\t}, [notifyDrawSession, renderPreview]);\n\n\tconst redoPolygon = useCallback(() => {\n\t\tif (draftHistoryIndexRef.current >= draftHistoryRef.current.length - 1) {\n\t\t\treturn false;\n\t\t}\n\t\tdraftHistoryIndexRef.current += 1;\n\t\tdraftPathRef.current = clonePoints(draftHistoryRef.current[draftHistoryIndexRef.current]);\n\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\trenderPreview();\n\t\tnotifyDrawSession();\n\t\treturn true;\n\t}, [notifyDrawSession, renderPreview]);\n\n\tconst undoSession = useCallback(() => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) return undoBrush();\n\t\tif (tool === TOOL.POLYGON || tool === TOOL.PATH) return undoPolygon();\n\t\treturn false;\n\t}, [toolRef, undoBrush, undoPolygon]);\n\n\tconst redoSession = useCallback(() => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) return redoBrush();\n\t\tif (tool === TOOL.POLYGON || tool === TOOL.PATH) return redoPolygon();\n\t\treturn false;\n\t}, [redoBrush, redoPolygon, toolRef]);\n\n\tconst seedBrushEditFromSelection = useCallback(() => {\n\t\tconst ids = selRef.current;\n\t\tif (!ids.length) {\n\t\t\treturn scalarEditTargetIdsRef.current.length > 0;\n\t\t}\n\t\tconst shapes = docRef.current\n\t\t\t.getShapes()\n\t\t\t.filter((shape) => ids.includes(shape.id) && isShapeEditable(shape));\n\t\tconst polygons = shapesToFilledPolygons(shapes);\n\t\tif (!polygons.length) {\n\t\t\tscalarEditTargetIdsRef.current = [];\n\t\t\tscalarBasePolygonsRef.current = [];\n\t\t\treturn false;\n\t\t}\n\t\tscalarEditTargetIdsRef.current = shapes.map((shape) => shape.id);\n\t\tscalarBasePolygonsRef.current = polygons;\n\t\treturn true;\n\t}, [docRef, selRef]);\n\n\tconst commitBrush = useCallback(() => {\n\t\tif (readOnlyRef.current) return false;\n\t\tconst strokes: ScalarStroke[] = [...scalarStrokesRef.current];\n\t\tif (draftPathRef.current.length) {\n\t\t\tstrokes.push({\n\t\t\t\tpoints: clonePoints(draftPathRef.current),\n\t\t\t\tmode: brushStrokeMode(),\n\t\t\t});\n\t\t}\n\t\tconst basePolygons = scalarBasePolygonsRef.current;\n\t\tconst editTargetIds = [...scalarEditTargetIdsRef.current];\n\t\tif (!strokes.length && !basePolygons.length) return false;\n\n\t\tconst raster = buildScalarMaskRaster(strokes, brushSizeRef.current, basePolygons);\n\t\tif (!raster) {\n\t\t\treset();\n\t\t\treturn false;\n\t\t}\n\t\tconst polygons = scalarMaskToPolygons(raster, simplifyEpsilonRef.current);\n\n\t\tif (editTargetIds.length) {\n\t\t\tconst targets = docRef.current\n\t\t\t\t.getShapes()\n\t\t\t\t.filter((shape) => editTargetIds.includes(shape.id));\n\t\t\tif (!polygons.length) {\n\t\t\t\tdocRef.current.remove(editTargetIds);\n\t\t\t\treset();\n\t\t\t\tchangeSelection([]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpolygons.sort((a, b) => polygonArea(b) - polygonArea(a));\n\t\t\tconst updates: EditorShape<TMeta>[] = [];\n\t\t\tconst creates: EditorShape<TMeta>[] = [];\n\t\t\tconst nextSelection: string[] = [];\n\t\t\tfor (let i = 0; i < polygons.length; i++) {\n\t\t\t\tconst points = polygons[i];\n\t\t\t\tif (i < targets.length) {\n\t\t\t\t\tconst shape = targets[i];\n\t\t\t\t\tupdates.push({ ...shape, type: SHAPE_TYPE.POLYGON, points });\n\t\t\t\t\tnextSelection.push(shape.id);\n\t\t\t\t} else {\n\t\t\t\t\tconst template = targets[0];\n\t\t\t\t\tconst id = generateId();\n\t\t\t\t\tcreates.push({\n\t\t\t\t\t\t...template,\n\t\t\t\t\t\tid,\n\t\t\t\t\t\ttype: SHAPE_TYPE.POLYGON,\n\t\t\t\t\t\tpoints,\n\t\t\t\t\t});\n\t\t\t\t\tnextSelection.push(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst deleteIds = targets.slice(polygons.length).map((shape) => shape.id);\n\t\t\tif (updates.length) docRef.current.update(updates);\n\t\t\tif (creates.length) docRef.current.create(creates);\n\t\t\tif (deleteIds.length) docRef.current.remove(deleteIds);\n\t\t\treset();\n\t\t\tchangeSelection(nextSelection);\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!polygons.length) {\n\t\t\treset();\n\t\t\treturn false;\n\t\t}\n\t\tconst style = draftRef.current;\n\t\tif (!style) return false;\n\t\tconst shapes: EditorShape<TMeta>[] = polygons.map((points) => ({\n\t\t\tid: generateId(),\n\t\t\ttype: SHAPE_TYPE.POLYGON,\n\t\t\tpoints,\n\t\t\tstyle,\n\t\t\tmeta: draftMeta,\n\t\t}));\n\t\tdocRef.current.create(shapes);\n\t\tchangeSelection(shapes.map((shape) => shape.id));\n\t\treset();\n\t\treturn true;\n\t}, [brushSizeRef, changeSelection, docRef, draftMeta, draftRef, readOnlyRef, reset]);\n\n\tconst commitDraftSession = useCallback(() => {\n\t\tconst tool = toolRef.current;\n\t\tif (tool === TOOL.BRUSH) return commitBrush();\n\t\tconst points = draftPathRef.current;\n\t\tif (tool === TOOL.POLYGON && points.length >= 3) {\n\t\t\tcreateShapeRef.current(SHAPE_TYPE.POLYGON, points);\n\t\t\treset();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}, [commitBrush, reset, toolRef]);\n\n\tconst completeFreehandStroke = useCallback(() => {\n\t\tconst points = draftPathRef.current;\n\t\tif (toolRef.current === TOOL.PATH && points.length >= 3) {\n\t\t\tconst simplified = simplifyPath(points, simplifyEpsilonRef.current);\n\t\t\tif (simplified.length >= 3) {\n\t\t\t\tcreateShapeRef.current(SHAPE_TYPE.POLYGON, simplified);\n\t\t\t}\n\t\t}\n\t\treset();\n\t}, [reset, toolRef]);\n\n\tconst setBrushScalarMode = useCallback(\n\t\t(mode: BrushScalarMode) => {\n\t\t\tbrushScalarModeRef.current = mode;\n\t\t\tnotifyDrawSession();\n\t\t\trenderPreview();\n\t\t},\n\t\t[notifyDrawSession, renderPreview],\n\t);\n\n\tconst beginBrushEditFromSelection = useCallback(() => {\n\t\tif (readOnlyRef.current || toolRef.current !== TOOL.BRUSH) return false;\n\t\tscalarStrokesRef.current = [];\n\t\tdraftPathRef.current = [];\n\t\tresetScalarHistory();\n\t\tconst ok = seedBrushEditFromSelection();\n\t\tnotifyDrawSession();\n\t\trenderPreview();\n\t\treturn ok;\n\t}, [\n\t\tnotifyDrawSession,\n\t\treadOnlyRef,\n\t\trenderPreview,\n\t\tresetScalarHistory,\n\t\tseedBrushEditFromSelection,\n\t\ttoolRef,\n\t]);\n\n\tconst deleteDraftSelectedPoints = useCallback(() => {\n\t\tconst selected = draftSelectedPointIndicesRef.current;\n\t\tif (!selected.size) return false;\n\t\tconst next = draftPathRef.current.filter((_, i) => !selected.has(i));\n\t\tdraftSelectedPointIndicesRef.current = new Set();\n\t\tsetDraftPath(next, true);\n\t\treturn true;\n\t}, [setDraftPath]);\n\n\tconst hitDraftPoint = useCallback(\n\t\t(p: Point) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tconst points = draftPathRef.current;\n\t\t\tif (!eng || !points.length) return -1;\n\t\t\tconst hitRadius = DRAFT_POINT_HIT_RADIUS / (eng.viewport.scale || 1);\n\t\t\tfor (let i = points.length - 1; i >= 0; i--) {\n\t\t\t\tconst point = points[i];\n\t\t\t\tif (Math.hypot(p.x - point.x, p.y - point.y) <= hitRadius) return i;\n\t\t\t}\n\t\t\treturn -1;\n\t\t},\n\t\t[engineRef],\n\t);\n\n\tconst finishScalarStroke = useCallback(() => {\n\t\tif (draftPathRef.current.length >= 1) {\n\t\t\tscalarStrokesRef.current.push({\n\t\t\t\tpoints: clonePoints(draftPathRef.current),\n\t\t\t\tmode: brushStrokeMode(),\n\t\t\t});\n\t\t\tdraftPathRef.current = [];\n\t\t\tpushScalarHistory(scalarStrokesRef.current);\n\t\t}\n\t\trenderPreview();\n\t\tnotifyDrawSession();\n\t}, [notifyDrawSession, pushScalarHistory, renderPreview]);\n\n\tconst cancelBrush = useCallback(() => {\n\t\tif (toolRef.current !== TOOL.BRUSH) return;\n\t\treset();\n\t}, [reset, toolRef]);\n\n\tconst handleToolChange = useCallback(\n\t\t(tool: Tool, isExternalTool: boolean) => {\n\t\t\tif (isExternalTool) {\n\t\t\t\treset();\n\t\t\t\tbrushScalarModeRef.current = \"draw\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (tool !== TOOL.BRUSH) {\n\t\t\t\treset();\n\t\t\t\tbrushScalarModeRef.current = \"draw\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbrushScalarModeRef.current = \"draw\";\n\t\t\tscalarStrokesRef.current = [];\n\t\t\tdraftPathRef.current = [];\n\t\t\tresetScalarHistory();\n\t\t\tseedBrushEditFromSelection();\n\t\t\tnotifyDrawSession();\n\t\t\trenderPreview();\n\t\t},\n\t\t[notifyDrawSession, renderPreview, reset, resetScalarHistory, seedBrushEditFromSelection],\n\t);\n\n\tconst handleBrushSelectionChange = useCallback(\n\t\t(selectedIds: string[], readOnly: boolean | undefined) => {\n\t\t\tif (toolRef.current !== TOOL.BRUSH || readOnly) return;\n\t\t\tif (!selectedIds.length) {\n\t\t\t\tnotifyDrawSession();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nextKey = [...selectedIds].sort().join(\",\");\n\t\t\tconst editKey = [...scalarEditTargetIdsRef.current].sort().join(\",\");\n\t\t\tif (nextKey === editKey) return;\n\t\t\tif (scalarStrokesRef.current.length || draftPathRef.current.length) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscalarStrokesRef.current = [];\n\t\t\tdraftPathRef.current = [];\n\t\t\tresetScalarHistory();\n\t\t\tseedBrushEditFromSelection();\n\t\t\tnotifyDrawSession();\n\t\t\trenderPreview();\n\t\t},\n\t\t[notifyDrawSession, renderPreview, resetScalarHistory, seedBrushEditFromSelection, toolRef],\n\t);\n\n\treturn {\n\t\treset,\n\t\tundoSession,\n\t\tredoSession,\n\t\tcanUndoSession,\n\t\tcanRedoSession,\n\t\thasDraftSession,\n\t\thasDraftPoints,\n\t\tcommitDraftSession,\n\t\tcompleteFreehandStroke,\n\t\tsetBrushScalarMode,\n\t\tgetBrushScalarMode: () => brushScalarModeRef.current,\n\t\thasBrushSession: getBrushSessionActive,\n\t\tcommitBrush,\n\t\tcancelBrush,\n\t\tbeginBrushEditFromSelection,\n\t\tdeleteDraftSelectedPoints,\n\t\thitDraftPoint,\n\t\tgetDraftPointsSnapshot,\n\t\ttryClosePolygon,\n\t\tremoveDraftPoint,\n\t\tselectDraftPointForDrag,\n\t\tappendPolygonPoint,\n\t\tbeginStroke,\n\t\tappendStrokePoint,\n\t\tmoveDraftPoints,\n\t\tcommitDraftPointDrag,\n\t\tsetDraftCursor,\n\t\tfinishScalarStroke,\n\t\thandleToolChange,\n\t\thandleBrushSelectionChange,\n\t};\n}\n","import { useCallback, useReducer, useRef } from \"react\";\nimport type { EditorShape } from \"../_model/geometry\";\n\n/**\n * 에디터가 소유하는 도형 문서 + undo/redo 히스토리.\n *\n * 전역 zustand가 아니라 컴포넌트 로컬 useReducer라 멀티 인스턴스 안전.\n * 히스토리는 스냅샷 방식(MVP). 변경이 문서에 커밋된 뒤 호스트 이벤트를 방출하며,\n * undo/redo는 이전↔현재 도형을 diff해 역연산 이벤트를 낸다.\n */\ninterface DocState<TMeta> {\n\tshapes: EditorShape<TMeta>[];\n\tpast: EditorShape<TMeta>[][];\n\tfuture: EditorShape<TMeta>[][];\n}\n\ntype DocAction<TMeta> =\n\t| { type: \"CREATE\"; shapes: EditorShape<TMeta>[] }\n\t| { type: \"UPDATE\"; shapes: EditorShape<TMeta>[] }\n\t| { type: \"DELETE\"; ids: string[] }\n\t| { type: \"REPLACE\"; removeIds: string[]; shapes: EditorShape<TMeta>[] }\n\t| { type: \"REORDER\"; ids: string[]; edge: \"front\" | \"back\" }\n\t| { type: \"RESET\"; shapes: EditorShape<TMeta>[] }\n\t| { type: \"UNDO\" }\n\t| { type: \"REDO\" };\n\nfunction withHistory<TMeta>(state: DocState<TMeta>, next: EditorShape<TMeta>[]): DocState<TMeta> {\n\treturn { shapes: next, past: [...state.past, state.shapes], future: [] };\n}\n\nfunction reducer<TMeta>(state: DocState<TMeta>, action: DocAction<TMeta>): DocState<TMeta> {\n\tswitch (action.type) {\n\t\tcase \"CREATE\":\n\t\t\treturn withHistory(state, [...state.shapes, ...action.shapes]);\n\t\tcase \"UPDATE\": {\n\t\t\tconst patch = new Map(action.shapes.map((a) => [a.id, a]));\n\t\t\treturn withHistory(\n\t\t\t\tstate,\n\t\t\t\tstate.shapes.map((a) => patch.get(a.id) ?? a),\n\t\t\t);\n\t\t}\n\t\tcase \"DELETE\": {\n\t\t\tconst ids = new Set(action.ids);\n\t\t\treturn withHistory(\n\t\t\t\tstate,\n\t\t\t\tstate.shapes.filter((a) => !ids.has(a.id)),\n\t\t\t);\n\t\t}\n\t\tcase \"REPLACE\": {\n\t\t\tconst removeIds = new Set(action.removeIds);\n\t\t\treturn withHistory(state, [\n\t\t\t\t...state.shapes.filter((a) => !removeIds.has(a.id)),\n\t\t\t\t...action.shapes,\n\t\t\t]);\n\t\t}\n\t\tcase \"REORDER\": {\n\t\t\tconst ids = new Set(action.ids);\n\t\t\tconst picked = state.shapes.filter((a) => ids.has(a.id));\n\t\t\tconst rest = state.shapes.filter((a) => !ids.has(a.id));\n\t\t\tif (picked.length === 0) return state;\n\t\t\tconst next = action.edge === \"front\" ? [...rest, ...picked] : [...picked, ...rest];\n\t\t\treturn withHistory(state, next);\n\t\t}\n\t\tcase \"RESET\":\n\t\t\treturn { shapes: action.shapes, past: [], future: [] };\n\t\tcase \"UNDO\": {\n\t\t\tif (state.past.length === 0) return state;\n\t\t\tconst prev = state.past[state.past.length - 1];\n\t\t\treturn {\n\t\t\t\tshapes: prev,\n\t\t\t\tpast: state.past.slice(0, -1),\n\t\t\t\tfuture: [state.shapes, ...state.future],\n\t\t\t};\n\t\t}\n\t\tcase \"REDO\": {\n\t\t\tif (state.future.length === 0) return state;\n\t\t\tconst next = state.future[0];\n\t\t\treturn {\n\t\t\t\tshapes: next,\n\t\t\t\tpast: [...state.past, state.shapes],\n\t\t\t\tfuture: state.future.slice(1),\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\ninterface DocCallbacks<TMeta> {\n\tonShapesCreated?: (shapes: EditorShape<TMeta>[]) => void;\n\tonShapesUpdated?: (shapes: EditorShape<TMeta>[]) => void;\n\tonShapesDeleted?: (ids: string[]) => void;\n}\n\n/** useEditorDocument가 반환하는 문서 핸들(에디터 도형+히스토리 제어). */\nexport type EditorDocument<TMeta> = ReturnType<typeof useEditorDocument<TMeta>>;\n\nexport function useEditorDocument<TMeta>(callbacks: DocCallbacks<TMeta>) {\n\tconst { onShapesCreated, onShapesUpdated, onShapesDeleted } = callbacks;\n\tconst [state, dispatch] = useReducer(reducer<TMeta>, {\n\t\tshapes: [],\n\t\tpast: [],\n\t\tfuture: [],\n\t});\n\t// 핸들/동기 읽기용 미러(클로저 stale 방지).\n\tconst stateRef = useRef(state);\n\tstateRef.current = state;\n\n\t// dispatch(useReducer)는 다음 렌더에야 반영되므로, 동기 읽기 미러(stateRef)를 즉시 함께\n\t// 갱신한다. 그래야 create 직후 getShapes()가 새 도형을 반영해 \"생성 후 자동 선택\" 같은\n\t// read-after-write가 정상 동작한다(예전엔 normalizeSelection이 stale 미러를 읽어 새 도형\n\t// id를 걸러내 선택이 비었다).\n\tconst dispatchSync = useCallback((action: DocAction<TMeta>) => {\n\t\tstateRef.current = reducer(stateRef.current, action);\n\t\tdispatch(action);\n\t}, []);\n\n\tconst emitDiff = useCallback(\n\t\t(prev: EditorShape<TMeta>[], next: EditorShape<TMeta>[]) => {\n\t\t\tconst prevMap = new Map(prev.map((a) => [a.id, a]));\n\t\t\tconst nextMap = new Map(next.map((a) => [a.id, a]));\n\t\t\tconst created = next.filter((a) => !prevMap.has(a.id));\n\t\t\tif (created.length) onShapesCreated?.(created);\n\t\t\tconst deletedIds = prev.filter((a) => !nextMap.has(a.id)).map((a) => a.id);\n\t\t\tif (deletedIds.length) onShapesDeleted?.(deletedIds);\n\t\t\tconst updated = next.filter((a) => prevMap.has(a.id) && prevMap.get(a.id) !== a);\n\t\t\tif (updated.length) onShapesUpdated?.(updated);\n\t\t},\n\t\t[onShapesCreated, onShapesUpdated, onShapesDeleted],\n\t);\n\n\tconst create = useCallback(\n\t\t(shapes: EditorShape<TMeta> | EditorShape<TMeta>[]) => {\n\t\t\tconst next = Array.isArray(shapes) ? shapes : [shapes];\n\t\t\tif (!next.length) return;\n\t\t\tdispatchSync({ type: \"CREATE\", shapes: next });\n\t\t\tonShapesCreated?.(next);\n\t\t},\n\t\t[onShapesCreated],\n\t);\n\n\tconst update = useCallback(\n\t\t(shapes: EditorShape<TMeta>[]) => {\n\t\t\tdispatchSync({ type: \"UPDATE\", shapes });\n\t\t\tonShapesUpdated?.(shapes);\n\t\t},\n\t\t[onShapesUpdated],\n\t);\n\n\tconst remove = useCallback(\n\t\t(ids: string[]) => {\n\t\t\tif (ids.length === 0) return;\n\t\t\tdispatchSync({ type: \"DELETE\", ids });\n\t\t\tonShapesDeleted?.(ids);\n\t\t},\n\t\t[onShapesDeleted],\n\t);\n\n\t/** 원자적 교체(합치기 등) — 삭제+생성을 히스토리 한 칸으로. 이벤트는 각각 방출. */\n\tconst replace = useCallback(\n\t\t(removeIds: string[], shapes: EditorShape<TMeta>[]) => {\n\t\t\tif (!removeIds.length && !shapes.length) return;\n\t\t\tdispatchSync({ type: \"REPLACE\", removeIds, shapes });\n\t\t\tif (removeIds.length) onShapesDeleted?.(removeIds);\n\t\t\tif (shapes.length) onShapesCreated?.(shapes);\n\t\t},\n\t\t[onShapesCreated, onShapesDeleted],\n\t);\n\n\t/** z-순서 변경(맨 앞/뒤). 점 변경이 아니라 배열 순서만 — create/update/delete 이벤트 없음. */\n\tconst reorder = useCallback((ids: string[], edge: \"front\" | \"back\") => {\n\t\tif (ids.length === 0) return;\n\t\tdispatchSync({ type: \"REORDER\", ids, edge });\n\t}, []);\n\n\t/** 호스트가 새 문서를 시드(이미지 전환 등). 히스토리 초기화, 이벤트 없음. */\n\tconst reset = useCallback((shapes: EditorShape<TMeta>[]) => {\n\t\tdispatchSync({ type: \"RESET\", shapes });\n\t}, []);\n\n\tconst undo = useCallback(() => {\n\t\tconst s = stateRef.current;\n\t\tif (s.past.length === 0) return;\n\t\temitDiff(s.shapes, s.past[s.past.length - 1]);\n\t\tdispatchSync({ type: \"UNDO\" });\n\t}, [emitDiff]);\n\n\tconst redo = useCallback(() => {\n\t\tconst s = stateRef.current;\n\t\tif (s.future.length === 0) return;\n\t\temitDiff(s.shapes, s.future[0]);\n\t\tdispatchSync({ type: \"REDO\" });\n\t}, [emitDiff]);\n\n\tconst canUndo = useCallback(() => stateRef.current.past.length > 0, []);\n\tconst canRedo = useCallback(() => stateRef.current.future.length > 0, []);\n\tconst getShapes = useCallback(() => stateRef.current.shapes, []);\n\n\treturn {\n\t\tshapes: state.shapes,\n\t\tcreate,\n\t\tupdate,\n\t\tremove,\n\t\treplace,\n\t\treorder,\n\t\treset,\n\t\tundo,\n\t\tredo,\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tgetShapes,\n\t};\n}\n","/**\n * 에디터 단축키 매핑. 조합키 문자열(예: \"mod+shift+z\")을 액션으로 잇는다.\n * 호스트는 keymap prop으로 재정의(문자열/배열)하거나 비활성(null)할 수 있다.\n *\n * 조합키 규칙: 수식어는 `mod`(⌘/Ctrl)·`shift`·`alt` 순, 그 뒤에 키 토큰.\n * 키 토큰은 e.code 기반(레이아웃/IME 무관): 글자 a–z, 숫자 0–9,\n * 기호(= - [ ] ; . , / `), 이름키(escape/enter/backspace/delete/arrow*).\n */\n\nexport type EditorAction =\n\t| \"undo\"\n\t| \"redo\"\n\t| \"selectAll\"\n\t| \"copy\"\n\t| \"cut\"\n\t| \"paste\"\n\t| \"duplicate\"\n\t| \"delete\"\n\t| \"cancel\"\n\t| \"commitDraft\"\n\t| \"bringToFront\"\n\t| \"sendToBack\"\n\t| \"flipHorizontal\"\n\t| \"flipVertical\"\n\t| \"zoomIn\"\n\t| \"zoomOut\"\n\t| \"zoom100\"\n\t| \"zoomFit\"\n\t| \"toggleMinimap\"\n\t| \"toggleCursorGuide\"\n\t| \"togglePixelation\"\n\t| \"selectTool\"\n\t| \"rectangleTool\"\n\t| \"rotatedRectangleTool\"\n\t| \"circleTool\"\n\t| \"polygonTool\"\n\t| \"pathTool\"\n\t| \"brushTool\"\n\t| \"pointTool\";\n\nexport const DEFAULT_KEYMAP: Record<EditorAction, string[]> = {\n\tundo: [\"mod+z\"],\n\tredo: [\"mod+shift+z\"],\n\tselectAll: [\"mod+a\"],\n\tcopy: [\"mod+c\"],\n\tcut: [\"mod+x\"],\n\tpaste: [\"mod+v\"],\n\tduplicate: [\"mod+d\"],\n\tdelete: [\"delete\", \"backspace\"],\n\tcancel: [\"escape\"],\n\tcommitDraft: [\"enter\"],\n\tbringToFront: [\"mod+]\"],\n\tsendToBack: [\"mod+[\"],\n\tflipHorizontal: [\"shift+h\"],\n\tflipVertical: [\"shift+v\"],\n\tzoomIn: [\"mod+=\", \"mod+shift+=\"],\n\tzoomOut: [\"mod+-\"],\n\tzoom100: [\"shift+1\"],\n\tzoomFit: [\"shift+2\"],\n\ttoggleMinimap: [\"m\"],\n\ttoggleCursorGuide: [\";\"],\n\ttogglePixelation: [\".\"],\n\tselectTool: [\"s\"],\n\trectangleTool: [\"r\"],\n\trotatedRectangleTool: [\"shift+r\"],\n\tcircleTool: [\"o\"],\n\tpolygonTool: [\"p\"],\n\tpathTool: [\"g\"],\n\tbrushTool: [\"b\"],\n\tpointTool: [\"i\"],\n};\n\nconst CODE_TOKEN: Record<string, string> = {\n\tEqual: \"=\",\n\tMinus: \"-\",\n\tBracketLeft: \"[\",\n\tBracketRight: \"]\",\n\tSemicolon: \";\",\n\tPeriod: \".\",\n\tComma: \",\",\n\tSlash: \"/\",\n\tBackquote: \"`\",\n};\n\nconst KEY_TOKEN: Record<string, string> = {\n\tEscape: \"escape\",\n\tEnter: \"enter\",\n\tBackspace: \"backspace\",\n\tDelete: \"delete\",\n\tTab: \"tab\",\n\tArrowUp: \"arrowup\",\n\tArrowDown: \"arrowdown\",\n\tArrowLeft: \"arrowleft\",\n\tArrowRight: \"arrowright\",\n};\n\n/** KeyboardEvent → 정규화된 키 토큰. 수식어 단독/Space/미매핑은 null. */\nfunction keyToken(e: KeyboardEvent): string | null {\n\tconst code = e.code;\n\tconst letter = /^Key([A-Z])$/.exec(code);\n\tif (letter) return letter[1].toLowerCase();\n\tconst digit = /^Digit([0-9])$/.exec(code);\n\tif (digit) return digit[1];\n\tif (CODE_TOKEN[code]) return CODE_TOKEN[code];\n\tif (KEY_TOKEN[e.key]) return KEY_TOKEN[e.key];\n\treturn null;\n}\n\n/** KeyboardEvent → 조합키 문자열(예: \"mod+shift+z\"). 매핑 불가 시 null. */\nexport function eventToCombo(e: KeyboardEvent): string | null {\n\tconst token = keyToken(e);\n\tif (!token) return null;\n\tconst parts: string[] = [];\n\tif (e.metaKey || e.ctrlKey) parts.push(\"mod\");\n\tif (e.shiftKey) parts.push(\"shift\");\n\tif (e.altKey) parts.push(\"alt\");\n\tparts.push(token);\n\treturn parts.join(\"+\");\n}\n\nexport type KeymapOverrides = Partial<Record<EditorAction, string | string[] | null>>;\n\n/** 기본 keymap에 호스트 재정의를 병합해 조합키→액션 조회 맵을 만든다. */\nexport function resolveKeymap(overrides?: KeymapOverrides): Map<string, EditorAction> {\n\tconst lookup = new Map<string, EditorAction>();\n\tfor (const action of Object.keys(DEFAULT_KEYMAP) as EditorAction[]) {\n\t\tconst override = overrides?.[action];\n\t\tconst combos =\n\t\t\toverride === undefined\n\t\t\t\t? DEFAULT_KEYMAP[action]\n\t\t\t\t: override === null\n\t\t\t\t\t? []\n\t\t\t\t\t: Array.isArray(override)\n\t\t\t\t\t\t? override\n\t\t\t\t\t\t: [override];\n\t\tfor (const combo of combos) lookup.set(combo.toLowerCase(), action);\n\t}\n\treturn lookup;\n}\n","import { type RefObject, useEffect, useMemo, useRef } from \"react\";\nimport {\n\ttype EditorAction,\n\teventToCombo,\n\ttype KeymapOverrides,\n\tresolveKeymap,\n} from \"../_model/keymap\";\n\n/** 액션 핸들러. false 반환 시 \"미처리\"로 보고 preventDefault를 건너뛴다. */\nexport type EditorActionHandlers = Partial<Record<EditorAction, () => boolean | void>>;\n\ninterface EditorHotkeysCtx {\n\t/** 호스트 재정의(문자열/배열=재매핑, null=비활성). 미지정 키는 기본값. */\n\tkeymap?: KeymapOverrides;\n\t/** 에디터 루트 요소. 에디터를 포함하지 않는 모달 위에서는 액션을 무시하는 데 쓴다. */\n\thostRef: RefObject<HTMLElement | null>;\n\tactions: EditorActionHandlers;\n\tspaceRef: RefObject<boolean>;\n\tshiftRef: RefObject<boolean>;\n\t/** Space 눌림/뗌 시 커서 갱신 등(index 소유). */\n\tonSpaceDown: () => void;\n\tonSpaceUp: () => void;\n\t/** 방향키 넛지(화면 px, shift면 큰 폭). 선택/readOnly 가드는 호스트가. */\n\tnudge: (dx: number, dy: number) => void;\n}\n\nconst ARROW_DELTA: Record<string, [number, number]> = {\n\tArrowUp: [0, -1],\n\tArrowDown: [0, 1],\n\tArrowLeft: [-1, 0],\n\tArrowRight: [1, 0],\n};\n\nfunction isTypingTarget(): boolean {\n\tconst el = document.activeElement as HTMLElement | null;\n\treturn !!el && (el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\" || el.isContentEditable);\n}\n\n/**\n * 이벤트가 에디터를 포함하지 않는 모달/다이얼로그 안에서 발생했는지.\n * capture 리스너는 stopPropagation의 영향을 받지 않으므로, 에디터 위에 뜬\n * 확인창·팝오버에서 Delete/Ctrl+Z 등이 에디터로 새는 것을 여기서 막는다.\n */\nfunction isInsideForeignModal(target: EventTarget | null, host: HTMLElement | null): boolean {\n\tif (!host || !(target instanceof Element)) return false;\n\tconst modal = target.closest('[role=\"dialog\"],[aria-modal=\"true\"]');\n\treturn !!modal && !modal.contains(host);\n}\n\n/**\n * 에디터 키보드 단축키. 기본 keymap을 내장하되 호스트가 재정의/비활성할 수 있다.\n * Space/Shift 추적과 방향키 넛지는 고정(재매핑 불가), 그 외 액션은 keymap 기반.\n * 최신 keymap/액션을 ref로 읽어 리스너는 1회만 바인딩한다.\n */\nexport function useEditorHotkeys(ctx: EditorHotkeysCtx) {\n\tconst { spaceRef, shiftRef } = ctx;\n\tconst lookup = useMemo(() => resolveKeymap(ctx.keymap), [ctx.keymap]);\n\n\tconst ref = useRef(ctx);\n\tref.current = ctx;\n\tconst lookupRef = useRef(lookup);\n\tlookupRef.current = lookup;\n\n\tuseEffect(() => {\n\t\tconst down = (e: KeyboardEvent) => {\n\t\t\tif (e.code === \"Space\") {\n\t\t\t\tspaceRef.current = true;\n\t\t\t\tref.current.onSpaceDown();\n\t\t\t}\n\t\t\tif (e.key === \"Shift\") shiftRef.current = true;\n\t\t\tif (isTypingTarget()) return;\n\t\t\tif (isInsideForeignModal(e.target, ref.current.hostRef.current)) return;\n\n\t\t\tconst arrow = ARROW_DELTA[e.key];\n\t\t\tif (arrow) {\n\t\t\t\te.preventDefault();\n\t\t\t\tconst step = e.shiftKey ? 10 : 1;\n\t\t\t\tref.current.nudge(arrow[0] * step, arrow[1] * step);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst combo = eventToCombo(e);\n\t\t\tif (!combo) return;\n\t\t\tconst action = lookupRef.current.get(combo);\n\t\t\tif (!action) return;\n\t\t\tconst handled = ref.current.actions[action]?.();\n\t\t\tif (handled !== false) e.preventDefault();\n\t\t};\n\t\tconst up = (e: KeyboardEvent) => {\n\t\t\tif (e.code === \"Space\") {\n\t\t\t\tspaceRef.current = false;\n\t\t\t\tref.current.onSpaceUp();\n\t\t\t}\n\t\t\tif (e.key === \"Shift\") shiftRef.current = false;\n\t\t};\n\t\t// 모달·팝오버가 내부 keydown 버블링을 중단하더라도 에디터 단축키는 동작해야 한다.\n\t\t// 입력 요소 예외는 down 내부의 isTypingTarget()에서 그대로 보장한다.\n\t\twindow.addEventListener(\"keydown\", down, { capture: true });\n\t\twindow.addEventListener(\"keyup\", up, { capture: true });\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"keydown\", down, { capture: true });\n\t\t\twindow.removeEventListener(\"keyup\", up, { capture: true });\n\t\t};\n\t}, [spaceRef, shiftRef]);\n}\n","/**\n * CORS 안전 이미지 blob URL 로드 — HTTP 캐시를 우선 사용한다(재방문·페이지 전환·\n * 화질 스왑 시 재다운로드 없음). 앱 다른 곳의 crossOrigin 없는 `<img>`가 캐시를\n * CORS 헤더 없는 응답으로 채웠으면 cors fetch가 실패하므로, 그때만 cache:\"reload\"로\n * 캐시 항목을 정상 CORS 응답으로 갈아끼우며 한 번 더 시도한다.\n * 둘 다 실패하면 null — 호출부가 crossOrigin=\"anonymous\" `<img>`로 폴백한다.\n * Konva/Pixi 렌더러와 ShapeViewer가 공유한다.\n */\nexport async function fetchImageObjectUrl(url: string): Promise<string | null> {\n\tfor (const cache of [\"default\", \"reload\"] as const) {\n\t\ttry {\n\t\t\tconst response = await fetch(url, { mode: \"cors\", credentials: \"omit\", cache });\n\t\t\tif (response.ok) return URL.createObjectURL(await response.blob());\n\t\t} catch {\n\t\t\t// 다음 cache 모드로 재시도.\n\t\t}\n\t}\n\treturn null;\n}\n","export const IMAGE_TILE_SIZE = 4000;\n\nexport interface ImageTile {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tsrcX: number;\n\tsrcY: number;\n}\n\nexport function getImageTiles(\n\twidth: number,\n\theight: number,\n\ttileSize = IMAGE_TILE_SIZE,\n): ImageTile[] {\n\tif (width <= 0 || height <= 0) return [];\n\tconst cols = Math.ceil(width / tileSize);\n\tconst rows = Math.ceil(height / tileSize);\n\treturn Array.from({ length: rows }, (_, row) =>\n\t\tArray.from({ length: cols }, (_, col) => {\n\t\t\tconst x = col * tileSize;\n\t\t\tconst y = row * tileSize;\n\t\t\tconst isLastCol = col === cols - 1;\n\t\t\tconst isLastRow = row === rows - 1;\n\t\t\treturn {\n\t\t\t\tx,\n\t\t\t\ty,\n\t\t\t\twidth: isLastCol ? width - x : tileSize + 1,\n\t\t\t\theight: isLastRow ? height - y : tileSize + 1,\n\t\t\t\tsrcX: x,\n\t\t\t\tsrcY: y,\n\t\t\t};\n\t\t}),\n\t).flat();\n}\n\nexport function createImageTileCanvas(image: HTMLImageElement, tile: ImageTile): HTMLCanvasElement {\n\tconst canvas = document.createElement(\"canvas\");\n\tcanvas.width = tile.width;\n\tcanvas.height = tile.height;\n\tconst context = canvas.getContext(\"2d\");\n\tif (!context) return canvas;\n\tcontext.drawImage(\n\t\timage,\n\t\ttile.srcX,\n\t\ttile.srcY,\n\t\ttile.width,\n\t\ttile.height,\n\t\t0,\n\t\t0,\n\t\ttile.width,\n\t\ttile.height,\n\t);\n\treturn canvas;\n}\n","import type Konva from \"konva\";\nimport type { EditorShape, Point, ShapeType } from \"./geometry\";\nimport { getBBox, SHAPE_TYPE } from \"./geometry\";\n\n// 드래그로 옮겨진 노드의 새 절대 좌표(이미지 좌표)를 도형 타입별로 계산.\nexport function movedPoints<TMeta>(shape: EditorShape<TMeta>, node: Konva.Node): Point[] {\n\tconst { type, points } = shape;\n\tif (type === SHAPE_TYPE.POINT) {\n\t\treturn [{ x: node.x(), y: node.y() }];\n\t}\n\tif (type === SHAPE_TYPE.RECTANGLE) {\n\t\tconst [a, b] = points;\n\t\tconst dx = node.x() - Math.min(a.x, b.x);\n\t\tconst dy = node.y() - Math.min(a.y, b.y);\n\t\treturn [\n\t\t\t{ x: a.x + dx, y: a.y + dy },\n\t\t\t{ x: b.x + dx, y: b.y + dy },\n\t\t];\n\t}\n\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\t// Ellipse는 중심(node.x/y) 기준 — old 중심과의 delta를 점에 적용.\n\t\tconst b = getBBox(points);\n\t\tconst dx = node.x() - (b.minX + b.maxX) / 2;\n\t\tconst dy = node.y() - (b.minY + b.maxY) / 2;\n\t\treturn points.map((p) => ({ x: p.x + dx, y: p.y + dy }));\n\t}\n\t// POLYGON / ROTATED_RECTANGLE / LINE: Line은 x/y=0 기준이라 node 위치가 곧 delta.\n\treturn points.map((p) => ({ x: p.x + node.x(), y: p.y + node.y() }));\n}\n\n// Konva 노드를 주어진 점 좌표가 렌더된 모습과 동일하게 맞춘다(이동 커밋 + 리사이즈\n// 미리보기에 공용). 깜빡임 방지 + 명령형 미리보기.\nexport function applyPointsToNode(node: Konva.Node, type: ShapeType, points: Point[]) {\n\tif (type === SHAPE_TYPE.POINT) {\n\t\tnode.setAttrs({ x: points[0].x, y: points[0].y });\n\t\treturn;\n\t}\n\tif (type === SHAPE_TYPE.RECTANGLE) {\n\t\tconst [a, b] = points;\n\t\tnode.setAttrs({\n\t\t\tx: Math.min(a.x, b.x),\n\t\t\ty: Math.min(a.y, b.y),\n\t\t\twidth: Math.abs(b.x - a.x),\n\t\t\theight: Math.abs(b.y - a.y),\n\t\t});\n\t\treturn;\n\t}\n\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\tconst b = getBBox(points);\n\t\tnode.setAttrs({\n\t\t\tx: (b.minX + b.maxX) / 2,\n\t\t\ty: (b.minY + b.maxY) / 2,\n\t\t\tradiusX: (b.maxX - b.minX) / 2,\n\t\t\tradiusY: (b.maxY - b.minY) / 2,\n\t\t});\n\t\treturn;\n\t}\n\t// POLYGON / ROTATED_RECTANGLE / LINE\n\tnode.setAttrs({ x: 0, y: 0, points: points.flatMap((p) => [p.x, p.y]) });\n}\n","/**\n * 지도 핀(물방울) 마커 — 기존 옵스 에디터의 pin.svg를 그대로 가져온 것.\n * POINT 도형을 점(dot) 대신 핀 아이콘으로 렌더할 때 쓴다. 팁은 하단중앙 (8,22).\n * 렌더러는 이 경로를 그리고 하단중앙을 도형 좌표에 맞춘 뒤, 뷰포트 반비례 스케일로\n * 화면 크기를 일정하게 유지한다.\n */\nexport const PIN_PATH =\n\t\"M8 0C12.4183 0 16 3.58172 16 8C16 11.5323 13.71 14.5277 10.5342 15.5879L10.166 20.0068C10.0721 21.1334 9.13046 22 8 22C6.86954 22 5.92786 21.1334 5.83398 20.0068L5.46484 15.5879C2.28949 14.5275 0 11.532 0 8C0 3.58172 3.58172 0 8 0Z\";\n\nexport const PIN_WIDTH = 16;\nexport const PIN_HEIGHT = 22;\nexport const PIN_STROKE = \"#ffffff\";\nexport const PIN_STROKE_WIDTH = 1.5;\n\n/** pixi Graphics.svg()용 최소 SVG 문자열(색 입힘). */\nexport function pinSvg(fill: string): string {\n\treturn `<svg width=\"${PIN_WIDTH}\" height=\"${PIN_HEIGHT}\" viewBox=\"0 0 ${PIN_WIDTH} ${PIN_HEIGHT}\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"${PIN_PATH}\" fill=\"${fill}\" stroke=\"${PIN_STROKE}\" stroke-width=\"${PIN_STROKE_WIDTH}\"/></svg>`;\n}\n","import { POINT_RADIUS } from \"../_constants\";\nimport {\n\tANCHORS,\n\ttype Anchor,\n\tanchorPoint,\n\ttype BBox,\n\tboxFromAnchor,\n\ttype EditorShape,\n\tgetBBox,\n\tisShapeDraggable,\n\tisShapeEditable,\n\tisShapeSelectable,\n\torientedHandles,\n\ttype Point,\n\trectTo4,\n\trescalePoints,\n\tresizeRotatedRectFromAnchor,\n\trotatePoint,\n\tSHAPE_TYPE,\n} from \"../_model/geometry\";\nimport { resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\n\n/**\n * 트랜스포머 드래그(이동/리사이즈/회전/정점) 상태와 지오메트리 계산 — 렌더러 공용.\n * Konva/Pixi 렌더러는 여기서 계산된 updates/box로 각자 프리뷰(노드 갱신·핸들 재배치)만\n * 수행한다. 수학이 한 곳에 있어 버그 수정이 양 백엔드에 동시에 적용된다.\n */\n\nexport const ROT_SNAP = Math.PI / 12; // Shift 회전 15° 스냅.\n\nexport interface ShapeUpdate {\n\tid: string;\n\tpoints: Point[];\n}\n\nexport type ActiveDrag =\n\t| {\n\t\t\tkind: \"resize\";\n\t\t\tanchor: Anchor;\n\t\t\tbox: BBox;\n\t\t\tshapes: ShapeUpdate[];\n\t }\n\t| {\n\t\t\tkind: \"move\";\n\t\t\tstart: Point;\n\t\t\tbox: BBox;\n\t\t\tshapes: ShapeUpdate[];\n\t }\n\t| {\n\t\t\tkind: \"vertex\";\n\t\t\tid: string;\n\t\t\tindices: number[];\n\t\t\tbase: Point[];\n\t\t\tstart: Point;\n\t }\n\t| {\n\t\t\tkind: \"rotate\";\n\t\t\tid: string;\n\t\t\tcenter: Point;\n\t\t\tstartAngle: number;\n\t\t\tpoints: Point[];\n\t\t\tshiftKey: boolean;\n\t };\n\n/** 드래그 대상이 단일 회전사각형인지(리사이즈/이동 핸들 분기용). */\nexport function dragTargetIsRotatedRect(shapes: EditorShape[], d: ActiveDrag): boolean {\n\tif (d.kind !== \"resize\" && d.kind !== \"move\") return false;\n\tif (d.shapes.length !== 1) return false;\n\tconst shape = shapes.find((s) => s.id === d.shapes[0].id);\n\treturn shape?.type === SHAPE_TYPE.ROTATED_RECTANGLE;\n}\n\n/**\n * 드래그 진행/확정 공용 지오메트리 — 현재 포인터(img) 기준 도형별 새 points와\n * 축정렬 핸들 박스(box, 회전 케이스는 null)를 계산한다.\n */\nexport function computeDragUpdates(\n\td: ActiveDrag,\n\timg: Point,\n\tisRotatedRect: boolean,\n): { updates: ShapeUpdate[]; box: BBox | null } {\n\tif (d.kind === \"resize\") {\n\t\tconst nb = isRotatedRect ? d.box : boxFromAnchor(d.anchor, d.box, img.x, img.y);\n\t\treturn {\n\t\t\tupdates: d.shapes.map((s) => ({\n\t\t\t\tid: s.id,\n\t\t\t\tpoints: isRotatedRect\n\t\t\t\t\t? resizeRotatedRectFromAnchor(s.points, d.anchor, img)\n\t\t\t\t\t: rescalePoints(s.points, d.box, nb),\n\t\t\t})),\n\t\t\tbox: nb,\n\t\t};\n\t}\n\tif (d.kind === \"move\") {\n\t\tconst dx = img.x - d.start.x;\n\t\tconst dy = img.y - d.start.y;\n\t\treturn {\n\t\t\tupdates: d.shapes.map((s) => ({\n\t\t\t\tid: s.id,\n\t\t\t\tpoints: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })),\n\t\t\t})),\n\t\t\tbox: {\n\t\t\t\tminX: d.box.minX + dx,\n\t\t\t\tminY: d.box.minY + dy,\n\t\t\t\tmaxX: d.box.maxX + dx,\n\t\t\t\tmaxY: d.box.maxY + dy,\n\t\t\t},\n\t\t};\n\t}\n\tif (d.kind === \"rotate\") {\n\t\tlet a = Math.atan2(img.y - d.center.y, img.x - d.center.x) - d.startAngle;\n\t\tif (d.shiftKey) a = Math.round(a / ROT_SNAP) * ROT_SNAP;\n\t\treturn {\n\t\t\tupdates: [{ id: d.id, points: d.points.map((p) => rotatePoint(p, d.center, a)) }],\n\t\t\tbox: null,\n\t\t};\n\t}\n\tconst dx = img.x - d.start.x;\n\tconst dy = img.y - d.start.y;\n\tconst next = d.base.map((p, i) => (d.indices.includes(i) ? { x: p.x + dx, y: p.y + dy } : p));\n\treturn { updates: [{ id: d.id, points: next }], box: getBBox(next) };\n}\n\n/**\n * 포인터 이동 전(클릭 유지 상태) 드래그 지오메트리를 바꾸지 않는 포인터 이미지 좌표.\n * 뷰포트 변경(줌/팬) 중 드래그 상태를 건드리지 않고 핸들·프리뷰만 재배치할 때 쓴다.\n */\nexport function dragIdentityImage(shapes: EditorShape[], d: ActiveDrag): Point {\n\tif (d.kind === \"move\" || d.kind === \"vertex\") return d.start;\n\tif (d.kind === \"rotate\") {\n\t\treturn {\n\t\t\tx: d.center.x + Math.cos(d.startAngle),\n\t\t\ty: d.center.y + Math.sin(d.startAngle),\n\t\t};\n\t}\n\tif (dragTargetIsRotatedRect(shapes, d)) {\n\t\treturn orientedHandles(d.shapes[0].points)[ANCHORS.indexOf(d.anchor)];\n\t}\n\treturn anchorPoint(d.anchor, d.box);\n}\n\n/** 이동 드래그 시작 상태 — 드래그 가능한 대상만 추려 스냅샷과 합집합 박스를 만든다. */\nexport function makeMoveDrag(\n\tshapes: EditorShape[],\n\tids: string[],\n\tstart: Point,\n): Extract<ActiveDrag, { kind: \"move\" }> | null {\n\tconst targets = shapes\n\t\t.filter((s) => ids.includes(s.id) && isShapeDraggable(s))\n\t\t.map((s) => ({ id: s.id, points: s.points }));\n\tif (!targets.length) return null;\n\treturn { kind: \"move\", start, box: getBBox(targets.flatMap((s) => s.points)), shapes: targets };\n}\n\n// ── 렌더러 공용 순수 헬퍼 ──\n\nexport function cloneShapes<TMeta>(shapes: EditorShape<TMeta>[]): EditorShape<TMeta>[] {\n\treturn shapes.map((shape) => ({\n\t\t...shape,\n\t\tpoints: shape.points.map((point) => ({ ...point })),\n\t}));\n}\n\n/** 선택 중 편집 가능한 도형. */\nexport function selectEditable(shapes: EditorShape[], selected: string[]): EditorShape[] {\n\tconst selectedSet = new Set(selected);\n\treturn shapes.filter((s) => selectedSet.has(s.id) && isShapeEditable(s));\n}\n\n/** 박스와 bbox가 겹치는 선택 가능 도형 id(마퀴 선택). */\nexport function intersectingShapeIds(shapes: EditorShape[], box: BBox): string[] {\n\treturn shapes\n\t\t.filter((s) => {\n\t\t\tif (!isShapeSelectable(s)) return false;\n\t\t\tconst b = getBBox(s.points);\n\t\t\treturn b.minX <= box.maxX && b.maxX >= box.minX && b.minY <= box.maxY && b.maxY >= box.minY;\n\t\t})\n\t\t.map((s) => s.id);\n}\n\n/** 점 도형 화면고정 반경(이미지 좌표) — 도형별 스타일 반영. */\nexport function pointRadiusFor(\n\tshape: EditorShape | undefined,\n\tstrokeSize: number,\n\tscale: number,\n): number {\n\tconst radius = shape\n\t\t? resolveShapeRenderStyle(shape, { strokeWidth: strokeSize }).pointRadius\n\t\t: POINT_RADIUS;\n\treturn radius / (scale || 1);\n}\n\nexport function pointSelectionBoxAt(p: Point, radius: number): BBox {\n\treturn { minX: p.x - radius, minY: p.y - radius, maxX: p.x + radius, maxY: p.y + radius };\n}\n\n/** 선택 아웃라인 4점 — 회전사각형은 원 점, 점은 반경 박스, 나머지는 bbox. */\nexport function outlinePointsFor(\n\tshape: EditorShape,\n\tpoints: Point[],\n\tpointRadius: number,\n): Point[] {\n\tif (shape.type === SHAPE_TYPE.ROTATED_RECTANGLE) return points;\n\tconst b =\n\t\tshape.type === SHAPE_TYPE.POINT ? pointSelectionBoxAt(points[0], pointRadius) : getBBox(points);\n\treturn rectTo4([\n\t\t{ x: b.minX, y: b.minY },\n\t\t{ x: b.maxX, y: b.maxY },\n\t]);\n}\n\n/** 회전 핸들과 박스 사이 간격(이미지 좌표, 화면 24px 고정). */\nexport function rotationHandleGapFor(scale: number): number {\n\treturn 24 / (scale || 1);\n}\n\n/** 회전사각형 핸들 각도(화면 좌표 상단 변 기준). */\nexport function orientedAngleFromScreenPoints(tl: Point, tr: Point): number {\n\treturn Math.atan2(tr.y - tl.y, tr.x - tl.x);\n}\n","import Konva from \"konva\";\nimport { SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA } from \"../_constants\";\nimport { resizeCursorForAnchor } from \"../_model/cursors\";\nimport {\n\tANCHORS,\n\tanchorPoint,\n\ttype BBox,\n\tcenterOf,\n\ttype EditorShape,\n\tgetBBox,\n\tisShapeDraggable,\n\tisShapeSelectable,\n\tisShapeVisible,\n\tmid,\n\torientedHandles,\n\ttype Point,\n\trectTo4,\n\trotateHandlePos,\n\tSHAPE_TYPE,\n\ttype ShapeStyle,\n\tsortShapesForRender,\n} from \"../_model/geometry\";\nimport { fetchImageObjectUrl } from \"../_model/imageFetch\";\nimport { getImageTiles } from \"../_model/imageTiles\";\nimport { applyPointsToNode } from \"../_model/konva\";\nimport {\n\tdrawRegionDim,\n\ttype RegionOverlayData,\n\ttype ResolvedRegionOutlineStyle,\n} from \"../_model/overlays\";\nimport { PIN_HEIGHT, PIN_PATH, PIN_STROKE, PIN_STROKE_WIDTH, PIN_WIDTH } from \"../_model/pinIcon\";\nimport type { ScalarMaskRaster } from \"../_model/scalarMask\";\nimport { buildScalarMaskPreviewCanvas } from \"../_model/scalarMask\";\nimport { colorWithAlpha, resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\nimport {\n\ttype ActiveDrag,\n\tcloneShapes,\n\tcomputeDragUpdates,\n\tdragIdentityImage,\n\tdragTargetIsRotatedRect,\n\tintersectingShapeIds,\n\tmakeMoveDrag,\n\torientedAngleFromScreenPoints,\n\toutlinePointsFor,\n\tpointRadiusFor,\n\trotationHandleGapFor,\n\tselectEditable,\n} from \"./transformSession\";\nimport type { EditorRenderer, EditorRendererCallbacks, PreviewKind, Viewport } from \"./types\";\n\nconst STROKE = 2;\nconst _POINT_RADIUS = 5;\nconst HANDLE_HEX = \"#1e88e5\";\nconst SEL_HEX = \"#669def\";\n\n/**\n * KonvaRenderer — EditorRenderer의 Konva(canvas2D) 구현(명령형, react-konva 아님).\n * 좌표계: world 그룹이 이미지 좌표를 담고 scale/position으로 줌/팬. 선두께는\n * strokeScaleEnabled:false로 네이티브 화면고정. 핸들은 화면좌표 그룹(비-scaled).\n */\nexport class KonvaRenderer implements EditorRenderer {\n\tprivate stage: Konva.Stage;\n\tprivate layer = new Konva.Layer();\n\tprivate world = new Konva.Group();\n\tprivate bgGroup = new Konva.Group();\n\tprivate overlayGroup = new Konva.Group({ listening: false });\n\tprivate shapeGroup = new Konva.Group();\n\tprivate selGroup = new Konva.Group();\n\tprivate previewGroup = new Konva.Group();\n\tprivate handleGroup = new Konva.Group();\n\tprivate cb: EditorRendererCallbacks;\n\tprivate host: HTMLElement;\n\tprivate baseCursor = \"default\";\n\tprivate strokeSize = STROKE;\n\tprivate imageSmoothing = true;\n\timageWidth = 0;\n\timageHeight = 0;\n\n\tprivate shapes: EditorShape[] = [];\n\tprivate selected: string[] = [];\n\tprivate nodes = new Map<string, Konva.Shape>();\n\t// 점선 도형의 보조색(alternateColor) 밑선 노드 — 본 노드 아래에 실선으로 깔린다.\n\tprivate altNodes = new Map<string, Konva.Shape>();\n\t// 마지막으로 적용한 뷰포트 스케일. 판(스케일 불변) 시 스케일 의존 갱신을 건너뛰기 위함.\n\tprivate lastAppliedScale = -1;\n\t// 연속 setImage 레이스 가드 — 마지막 요청만 타일을 교체한다.\n\tprivate imageLoadToken = 0;\n\tprivate transformEnabled = false;\n\tprivate handleNodes: Konva.Rect[] = [];\n\tprivate vertexNodes: Konva.Circle[] = [];\n\tprivate lastImg: Point = { x: 0, y: 0 };\n\tprivate lastDragImg: Point | null = null;\n\tprivate ro: ResizeObserver | null = null;\n\tprivate activeDrag: ActiveDrag | null = null;\n\tprivate midNodes: Konva.Circle[] = [];\n\t// 다중 선택된 정점 인덱스(현재 편집 폴리곤 기준). 함께 이동.\n\tprivate selectedVertices = new Set<number>();\n\tprivate vertexPolygonId: string | null = null;\n\t// 폴리곤 정점 편집모드 대상 id(옵스식). 이 값이 선택된 단일 폴리곤과 같을 때만 정점 표시.\n\tprivate editingId: string | null = null;\n\tprivate rotNode: Konva.Circle | null = null;\n\tprivate rotLineNode: Konva.Line | null = null;\n\tprivate transformerOutline: Konva.Line | null = null;\n\tprivate selectionBorders: Konva.Line[] = [];\n\n\tconstructor(host: HTMLElement, cb: EditorRendererCallbacks) {\n\t\tthis.host = host;\n\t\tthis.cb = cb;\n\t\tthis.stage = new Konva.Stage({\n\t\t\tcontainer: host as HTMLDivElement,\n\t\t\twidth: host.clientWidth || 1,\n\t\t\theight: host.clientHeight || 1,\n\t\t});\n\t\tthis.world.add(\n\t\t\tthis.bgGroup,\n\t\t\tthis.overlayGroup,\n\t\t\tthis.shapeGroup,\n\t\t\tthis.selGroup,\n\t\t\tthis.previewGroup,\n\t\t);\n\t\tthis.layer.add(this.world, this.handleGroup);\n\t\t// 뷰포트(fit)가 정해지기 전엔 콘텐츠를 숨긴다(초기 unfit 프레임 방지). 첫 applyViewport\n\t\t// 에서 노출한다.\n\t\tthis.world.visible(false);\n\t\tthis.stage.add(this.layer);\n\t}\n\n\tasync init() {\n\t\tconst ev = (e: Konva.KonvaEventObject<MouseEvent>) => ({\n\t\t\tbutton: e.evt.button,\n\t\t\tshiftKey: e.evt.shiftKey,\n\t\t\taltKey: e.evt.altKey,\n\t\t\tctrlKey: e.evt.ctrlKey,\n\t\t\tmetaKey: e.evt.metaKey,\n\t\t\tglobal: this.stage.getPointerPosition() ?? { x: 0, y: 0 },\n\t\t});\n\t\tthis.stage.on(\"mousedown\", (e) => {\n\t\t\tconst id = e.target === this.stage ? null : (e.target.id() as string) || null;\n\t\t\tthis.cb.onPointerDown(this.toImage(), id, ev(e));\n\t\t});\n\t\tthis.stage.on(\"mousemove\", () => {\n\t\t\tthis.lastImg = this.toImage();\n\t\t\tif (this.activeDrag) {\n\t\t\t\tthis.lastDragImg = this.lastImg;\n\t\t\t\tthis.dragTransform(this.lastImg);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cb.onPointerMove(this.lastImg, {\n\t\t\t\tglobal: this.stage.getPointerPosition() ?? { x: 0, y: 0 },\n\t\t\t});\n\t\t});\n\t\tconst up = () => {\n\t\t\tif (this.activeDrag) {\n\t\t\t\tthis.endTransform();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cb.onPointerUp(this.lastImg);\n\t\t};\n\t\tthis.stage.on(\"mouseup\", up);\n\t\twindow.addEventListener(\"mouseup\", up);\n\t\tthis.upCleanup = () => window.removeEventListener(\"mouseup\", up);\n\n\t\tthis.ro = new ResizeObserver(() => {\n\t\t\tthis.stage.size({\n\t\t\t\twidth: this.host.clientWidth || 1,\n\t\t\t\theight: this.host.clientHeight || 1,\n\t\t\t});\n\t\t\tthis.layer.batchDraw();\n\t\t});\n\t\tthis.ro.observe(this.host);\n\t}\n\n\tprivate upCleanup: (() => void) | null = null;\n\n\tdestroy() {\n\t\tthis.ro?.disconnect();\n\t\tthis.upCleanup?.();\n\t\tthis.stage.destroy();\n\t}\n\n\tget dom(): HTMLElement {\n\t\treturn this.stage.container();\n\t}\n\n\tget screenSize() {\n\t\treturn { w: this.stage.width(), h: this.stage.height() };\n\t}\n\n\tsetCursor(cursor: string) {\n\t\tthis.baseCursor = cursor;\n\t\tthis.applyCursor();\n\t}\n\n\tprivate emitCursorHint(cursor: string | null) {\n\t\tthis.cb.onCursorHint?.(cursor);\n\t}\n\n\tprivate emitInteractionMode(\n\t\tmode: \"idle\" | \"moving\" | \"resizing\" | \"rotating\" | \"vertexDragging\",\n\t) {\n\t\tthis.cb.onInteractionModeChange?.(mode);\n\t}\n\n\tprivate applyCursor() {\n\t\tthis.stage.container().style.cursor = this.baseCursor;\n\t\tfor (const canvas of this.stage.container().querySelectorAll(\"canvas\")) {\n\t\t\tcanvas.style.cursor = this.baseCursor;\n\t\t}\n\t}\n\n\tprivate bindCursor(node: Konva.Node, cursor: string) {\n\t\tconst enter = () => {\n\t\t\tif (this.activeDrag) return;\n\t\t\tif (cursor === \"pointer\" && !this.transformEnabled) return;\n\t\t\tthis.emitCursorHint(cursor);\n\t\t};\n\t\tconst leave = () => {\n\t\t\tif (!this.activeDrag) this.emitCursorHint(null);\n\t\t};\n\t\tnode.on(\"mouseenter\", enter);\n\t\tnode.on(\"mouseover\", enter);\n\t\tnode.on(\"mouseleave\", leave);\n\t\tnode.on(\"mouseout\", leave);\n\t}\n\n\tprivate toImage(): Point {\n\t\tconst p = this.world.getRelativePointerPosition();\n\t\treturn p ? { x: p.x, y: p.y } : this.lastImg;\n\t}\n\n\tprivate imgToScreen(p: Point): Point {\n\t\treturn this.world.getAbsoluteTransform().point(p);\n\t}\n\n\tasync setImage(url: string) {\n\t\tconst loadToken = ++this.imageLoadToken;\n\t\t// HTTP 캐시 우선 + 오염 캐시(CORS 헤더 없는 응답)일 때만 reload 재시도 —\n\t\t// 페이지 전환/화질 스왑/재방문 시 재다운로드를 피한다(imageFetch.ts 참고).\n\t\tconst objectUrl = await fetchImageObjectUrl(url);\n\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst img = new Image();\n\t\t\tif (!objectUrl) img.crossOrigin = \"anonymous\";\n\t\t\timg.onload = () => {\n\t\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\t\tif (loadToken !== this.imageLoadToken) return resolve(); // 더 최신 요청 있음.\n\t\t\t\tthis.imageWidth = img.naturalWidth;\n\t\t\t\tthis.imageHeight = img.naturalHeight;\n\t\t\t\tthis.bgGroup.destroyChildren();\n\t\t\t\tfor (const tile of getImageTiles(this.imageWidth, this.imageHeight)) {\n\t\t\t\t\tthis.bgGroup.add(\n\t\t\t\t\t\tnew Konva.Image({\n\t\t\t\t\t\t\timage: img,\n\t\t\t\t\t\t\tx: tile.x,\n\t\t\t\t\t\t\ty: tile.y,\n\t\t\t\t\t\t\twidth: tile.width,\n\t\t\t\t\t\t\theight: tile.height,\n\t\t\t\t\t\t\tcrop: {\n\t\t\t\t\t\t\t\tx: tile.srcX,\n\t\t\t\t\t\t\t\ty: tile.srcY,\n\t\t\t\t\t\t\t\twidth: tile.width,\n\t\t\t\t\t\t\t\theight: tile.height,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tlistening: false,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis.layer.batchDraw();\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\timg.onerror = () => {\n\t\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\t\tthis.imageWidth ||= 800;\n\t\t\t\tthis.imageHeight ||= 600;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\timg.src = objectUrl ?? url;\n\t\t});\n\t}\n\n\tclearImage() {\n\t\t// 이후 도착하는 이전 setImage 응답이 타일을 되살리지 않게 토큰도 올린다.\n\t\tthis.imageLoadToken++;\n\t\tthis.bgGroup.destroyChildren();\n\t\tthis.layer.batchDraw();\n\t}\n\n\tsetFilter(brightness: number, contrast: number) {\n\t\t// 이미지 노드에만 CSS filter는 불가 → 컨테이너 캔버스에 적용(옵스와 동일, 전체 캔버스).\n\t\tconst f =\n\t\t\tbrightness !== 1 || contrast !== 1 ? `brightness(${brightness}) contrast(${contrast})` : \"\";\n\t\tconst canvas = this.stage.container().querySelector(\"canvas\");\n\t\tif (canvas) (canvas as HTMLCanvasElement).style.filter = f;\n\t}\n\n\tsetStrokeSize(strokeSize: number) {\n\t\tif (this.strokeSize === strokeSize) return;\n\t\tthis.strokeSize = strokeSize;\n\t\tthis.setShapes(this.shapes, this.selected);\n\t}\n\n\tsetImageSmoothing(smooth: boolean) {\n\t\tif (this.imageSmoothing === smooth) return;\n\t\tthis.imageSmoothing = smooth;\n\t\t// imageSmoothingEnabled는 레이어 캔버스 컨텍스트에 적용된다(drawImage 스케일링에만 영향,\n\t\t// 벡터 도형 안티에일리어싱과는 무관).\n\t\tthis.layer.imageSmoothingEnabled(smooth);\n\t\tthis.layer.batchDraw();\n\t}\n\n\tsetOverlays(\n\t\tmaskCanvas: HTMLCanvasElement | null,\n\t\tregion: RegionOverlayData | null,\n\t\tdimmed: boolean,\n\t) {\n\t\tthis.overlayGroup.destroyChildren();\n\t\tif (maskCanvas) {\n\t\t\tthis.overlayGroup.add(\n\t\t\t\tnew Konva.Image({\n\t\t\t\t\timage: maskCanvas,\n\t\t\t\t\topacity: 0.55,\n\t\t\t\t\timageSmoothingEnabled: false,\n\t\t\t\t\tlistening: false,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tif (region) {\n\t\t\t// 벡터 딤 — 래스터(캔버스 굽기) 없이 매 프레임 재계산해도 싸서 드래그 중\n\t\t\t// 오버레이가 트랜스포머와 같은 박자로 따라온다.\n\t\t\tconst { imageWidth, imageHeight } = this;\n\t\t\tthis.overlayGroup.add(\n\t\t\t\tnew Konva.Shape({\n\t\t\t\t\tlistening: false,\n\t\t\t\t\tsceneFunc: (konvaCtx) => {\n\t\t\t\t\t\tdrawRegionDim(konvaCtx._context, region, imageWidth, imageHeight);\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (region.outlineStyles) {\n\t\t\t\t// 경계 선분 — strokeScaleEnabled:false로 두께·점선 패턴이 화면 px 고정(줌 무관).\n\t\t\t\tconst addSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n\t\t\t\t\tconst fixedStroke = {\n\t\t\t\t\t\tstrokeWidth: style.width,\n\t\t\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\t\t\tlistening: false,\n\t\t\t\t\t};\n\t\t\t\t\tfor (const [a, b] of segments) {\n\t\t\t\t\t\tif (style.underlayColor) {\n\t\t\t\t\t\t\tthis.overlayGroup.add(\n\t\t\t\t\t\t\t\tnew Konva.Line({\n\t\t\t\t\t\t\t\t\tpoints: [a.x, a.y, b.x, b.y],\n\t\t\t\t\t\t\t\t\tstroke: style.underlayColor,\n\t\t\t\t\t\t\t\t\t...fixedStroke,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.overlayGroup.add(\n\t\t\t\t\t\t\tnew Konva.Line({\n\t\t\t\t\t\t\t\tpoints: [a.x, a.y, b.x, b.y],\n\t\t\t\t\t\t\t\tstroke: style.color,\n\t\t\t\t\t\t\t\topacity: style.opacity,\n\t\t\t\t\t\t\t\tdash: style.dash,\n\t\t\t\t\t\t\t\t...fixedStroke,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\taddSegments(region.visibleOutline, region.outlineStyles.visible);\n\t\t\t\taddSegments(region.occludedOutline, region.outlineStyles.occluded);\n\t\t\t}\n\t\t}\n\t\tif (dimmed && this.imageWidth) {\n\t\t\tthis.overlayGroup.add(\n\t\t\t\tnew Konva.Rect({\n\t\t\t\t\tx: 0,\n\t\t\t\t\ty: 0,\n\t\t\t\t\twidth: this.imageWidth,\n\t\t\t\t\theight: this.imageHeight,\n\t\t\t\t\tfill: \"#0d0d12\",\n\t\t\t\t\topacity: 0.3,\n\t\t\t\t\tlistening: false,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tthis.layer.batchDraw();\n\t}\n\n\tget viewport(): Viewport {\n\t\treturn { scale: this.world.scaleX(), x: this.world.x(), y: this.world.y() };\n\t}\n\n\tapplyViewport(v: Viewport) {\n\t\t// 판(translate만)은 스케일 불변이라 스케일 의존 갱신(화면고정 도형·선택테두리·핸들)이\n\t\t// 불필요하다 — 줌 때만 갱신해 도형 많을 때 판 렉을 방지. batchDraw는 위치 반영을 위해 유지.\n\t\tconst scaleChanged = v.scale !== this.lastAppliedScale;\n\t\tthis.lastAppliedScale = v.scale;\n\t\tthis.world.scale({ x: v.scale, y: v.scale });\n\t\tthis.world.position({ x: v.x, y: v.y });\n\t\tthis.world.visible(true); // 뷰포트 확정 → 콘텐츠 노출(초기 unfit 프레임 방지)\n\t\tif (scaleChanged) {\n\t\t\tthis.syncScreenFixedShapes();\n\t\t\tthis.updateSelectionBordersLive((shape) => shape.points);\n\t\t\t// 그리는 중 폴리곤 초안의 정점 원 크기를 새 스케일로 재계산.\n\t\t\tconst p = this.lastPreviewPoly;\n\t\t\tif (p) {\n\t\t\t\tthis.previewPoly(\n\t\t\t\t\tp.points,\n\t\t\t\t\tp.cursor,\n\t\t\t\t\tp.style,\n\t\t\t\t\tp.closed,\n\t\t\t\t\tp.selectedPointIndices,\n\t\t\t\t\tp.showVertices,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// 트랜스포머 핸들은 화면 고정 그룹(layer 직속)에 화면 좌표로 그려지므로\n\t\t// 판(이동)에서도 매번 위치를 재계산해야 한다. 선택분만 그려서 가볍다.\n\t\t// 드래그(클릭 유지 포함) 중에는 drawTransformer가 조기 종료하므로\n\t\t// 마지막(또는 identity) 포인터 좌표로 라이브 재배치한다.\n\t\tif (this.activeDrag) {\n\t\t\tthis.dragTransform(this.lastDragImg ?? dragIdentityImage(this.shapes, this.activeDrag));\n\t\t} else {\n\t\t\tthis.drawTransformer();\n\t\t}\n\t\tthis.layer.batchDraw();\n\t\tthis.cb.onViewportChange?.();\n\t}\n\n\tfit() {\n\t\tif (!this.imageWidth || !this.imageHeight) return;\n\t\tconst { w, h } = this.screenSize;\n\t\tconst scale = Math.min(w / this.imageWidth, h / this.imageHeight);\n\t\tthis.applyViewport({\n\t\t\tscale,\n\t\t\tx: (w - this.imageWidth * scale) / 2,\n\t\t\ty: (h - this.imageHeight * scale) / 2,\n\t\t});\n\t}\n\n\tzoom100() {\n\t\tif (!this.imageWidth || !this.imageHeight) return;\n\t\tconst { w, h } = this.screenSize;\n\t\tthis.applyViewport({\n\t\t\tscale: 1,\n\t\t\tx: (w - this.imageWidth) / 2,\n\t\t\ty: (h - this.imageHeight) / 2,\n\t\t});\n\t}\n\n\tzoomAt(cx: number, cy: number, factor: number) {\n\t\tconst s = this.world.scaleX();\n\t\tconst ns = Math.min(20, Math.max(0.05, s * factor));\n\t\tconst wx = (cx - this.world.x()) / s;\n\t\tconst wy = (cy - this.world.y()) / s;\n\t\tthis.applyViewport({ scale: ns, x: cx - wx * ns, y: cy - wy * ns });\n\t}\n\n\t// ── 도형 렌더 ──\n\tsetShapes(shapes: EditorShape[], selected: string[]) {\n\t\tthis.shapes = cloneShapes(shapes);\n\t\tthis.selected = selected;\n\t\tif (this.activeDrag) return;\n\t\tthis.shapeGroup.destroyChildren();\n\t\tthis.nodes.clear();\n\t\tthis.altNodes.clear();\n\t\tfor (const shape of sortShapesForRender(shapes).filter(isShapeVisible)) {\n\t\t\tconst node = this.makeNode(shape);\n\t\t\t// 점선의 빈 구간 보조색 — 보조색 실선 밑선 위에 주색 점선(프리뷰·뷰어와 동일 계약).\n\t\t\tconst style = resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize });\n\t\t\tif (shape.style?.alternateColor && style.dash?.length && shape.type !== SHAPE_TYPE.POINT) {\n\t\t\t\tconst alt = node.clone({\n\t\t\t\t\tid: `${shape.id}__alt`,\n\t\t\t\t\tstroke: shape.style.alternateColor,\n\t\t\t\t\tdash: [],\n\t\t\t\t\tfillEnabled: false,\n\t\t\t\t\tlistening: false,\n\t\t\t\t}) as Konva.Shape;\n\t\t\t\tthis.altNodes.set(shape.id, alt);\n\t\t\t\tthis.shapeGroup.add(alt);\n\t\t\t}\n\t\t\tthis.nodes.set(shape.id, node);\n\t\t\tthis.shapeGroup.add(node);\n\t\t}\n\t\tthis.drawSelectionBorders();\n\t\tthis.drawTransformer();\n\t\tthis.layer.batchDraw();\n\t}\n\n\tsetSelection(selected: string[]) {\n\t\tthis.selected = selected;\n\t\t// 편집 대상 폴리곤이 아니게 되면 정점 다중선택 초기화.\n\t\tif (selected.length !== 1 || selected[0] !== this.vertexPolygonId) {\n\t\t\tthis.vertexPolygonId = null;\n\t\t\tthis.selectedVertices.clear();\n\t\t}\n\t\tif (this.editingId && (selected.length !== 1 || selected[0] !== this.editingId)) {\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tif (this.activeDrag) return;\n\t\tthis.drawSelectionBorders();\n\t\tthis.drawTransformer();\n\t\tthis.layer.batchDraw();\n\t}\n\n\t/** 폴리곤 정점 편집모드 진입/해제(null이면 해제). */\n\tsetEditing(id: string | null) {\n\t\tif (this.editingId === id) return;\n\t\tthis.editingId = id;\n\t\tthis.selectedVertices.clear();\n\t\tif (!this.activeDrag) {\n\t\t\tthis.drawTransformer();\n\t\t\tthis.layer.batchDraw();\n\t\t}\n\t}\n\n\tprivate makeNode(shape: EditorShape): Konva.Shape {\n\t\tconst { type, points } = shape;\n\t\tconst style = resolveShapeRenderStyle(shape, {\n\t\t\tstrokeWidth: this.strokeSize,\n\t\t});\n\t\tconst listening = isShapeSelectable(shape);\n\t\tconst common = {\n\t\t\tid: shape.id,\n\t\t\tstroke: style.color,\n\t\t\tstrokeWidth: style.strokeWidth,\n\t\t\tdash: this.scaledDash(style.dash),\n\t\t\topacity: style.opacity,\n\t\t\tstrokeScaleEnabled: false,\n\t\t\tlistening,\n\t\t};\n\t\tconst fill = style.fillVisible ? colorWithAlpha(style.color, style.fillAlpha) : undefined;\n\t\tif (type === SHAPE_TYPE.POINT) {\n\t\t\tconst inv = 1 / (this.world.scaleX() || 1);\n\t\t\tconst node = new Konva.Path({\n\t\t\t\tid: shape.id,\n\t\t\t\tdata: PIN_PATH,\n\t\t\t\tx: points[0].x,\n\t\t\t\ty: points[0].y,\n\t\t\t\toffsetX: PIN_WIDTH / 2,\n\t\t\t\toffsetY: PIN_HEIGHT,\n\t\t\t\tscaleX: inv,\n\t\t\t\tscaleY: inv,\n\t\t\t\tfill: style.color,\n\t\t\t\tstroke: PIN_STROKE,\n\t\t\t\tstrokeWidth: PIN_STROKE_WIDTH,\n\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\tshadowColor: \"#000\",\n\t\t\t\tshadowBlur: 2,\n\t\t\t\tshadowOpacity: 0.3,\n\t\t\t\tshadowForStrokeEnabled: false,\n\t\t\t\topacity: style.opacity,\n\t\t\t\tlistening,\n\t\t\t});\n\t\t\tthis.bindCursor(node, isShapeDraggable(shape) ? \"grab\" : \"default\");\n\t\t\treturn node;\n\t\t}\n\t\tif (type === SHAPE_TYPE.RECTANGLE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tconst node = new Konva.Rect({\n\t\t\t\tx: b.minX,\n\t\t\t\ty: b.minY,\n\t\t\t\twidth: b.maxX - b.minX,\n\t\t\t\theight: b.maxY - b.minY,\n\t\t\t\tfill,\n\t\t\t\t...common,\n\t\t\t});\n\t\t\tthis.bindCursor(node, isShapeDraggable(shape) ? \"grab\" : \"default\");\n\t\t\treturn node;\n\t\t}\n\t\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tconst node = new Konva.Ellipse({\n\t\t\t\tx: (b.minX + b.maxX) / 2,\n\t\t\t\ty: (b.minY + b.maxY) / 2,\n\t\t\t\tradiusX: (b.maxX - b.minX) / 2,\n\t\t\t\tradiusY: (b.maxY - b.minY) / 2,\n\t\t\t\tfill,\n\t\t\t\t...common,\n\t\t\t});\n\t\t\tthis.bindCursor(node, isShapeDraggable(shape) ? \"grab\" : \"default\");\n\t\t\treturn node;\n\t\t}\n\t\tconst flat = points.flatMap((p) => [p.x, p.y]);\n\t\tconst closed = type !== SHAPE_TYPE.LINE;\n\t\tconst node = new Konva.Line({\n\t\t\tpoints: flat,\n\t\t\tclosed,\n\t\t\tfill: closed ? fill : undefined,\n\t\t\tlineJoin: \"round\",\n\t\t\t...common,\n\t\t});\n\t\tthis.bindCursor(node, isShapeDraggable(shape) ? \"grab\" : \"default\");\n\t\treturn node;\n\t}\n\n\tliveUpdateShape(id: string, points: Point[]) {\n\t\tconst node = this.nodes.get(id);\n\t\tconst shape = this.shapes.find((s) => s.id === id);\n\t\tif (node && shape) {\n\t\t\tapplyPointsToNode(node, shape.type, points);\n\t\t\tconst alt = this.altNodes.get(id);\n\t\t\tif (alt) applyPointsToNode(alt, shape.type, points);\n\t\t\tif (shape.type === SHAPE_TYPE.POINT && node instanceof Konva.Circle) {\n\t\t\t\tnode.radius(this.pointRadius(shape));\n\t\t\t}\n\t\t\tthis.layer.batchDraw();\n\t\t}\n\t}\n\n\tprivate pointRadius(shape?: EditorShape) {\n\t\treturn pointRadiusFor(shape, this.strokeSize, this.world.scaleX() || 1);\n\t}\n\n\tprivate scaledDash(dash?: number[]) {\n\t\treturn dash;\n\t}\n\n\tprivate syncScreenFixedShapes() {\n\t\tconst inv = 1 / (this.world.scaleX() || 1);\n\t\tfor (const shape of this.shapes) {\n\t\t\tconst node = this.nodes.get(shape.id);\n\t\t\tif (shape.type === SHAPE_TYPE.POINT) {\n\t\t\t\t// 핀은 뷰포트 반비례 스케일로 화면 크기 고정.\n\t\t\t\tnode?.scale({ x: inv, y: inv });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnode?.dash(\n\t\t\t\tthis.scaledDash(resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize }).dash),\n\t\t\t);\n\t\t}\n\t}\n\n\tshapesIntersecting(box: BBox): string[] {\n\t\treturn intersectingShapeIds(this.shapes, box);\n\t}\n\n\tprivate drawSelectionBorders() {\n\t\t// Set 멤버십 + 노드 재사용(개수 변화 때만 재생성). 전체선택 후 줌/판마다\n\t\t// N개 노드를 destroy/생성하고 includes로 O(N²) 검사하던 렉 방지.\n\t\tconst selectedSet = new Set(this.selected);\n\t\tconst targets = this.selected.length\n\t\t\t? this.shapes.filter((s) => selectedSet.has(s.id) && isShapeSelectable(s))\n\t\t\t: [];\n\t\tif (this.selectionBorders.length !== targets.length) {\n\t\t\tfor (const rect of this.selectionBorders) rect.destroy();\n\t\t\tthis.selectionBorders = targets.map(() => {\n\t\t\t\tconst rect = new Konva.Line({\n\t\t\t\t\tclosed: true,\n\t\t\t\t\tstroke: SEL_HEX,\n\t\t\t\t\tstrokeWidth: 1.5,\n\t\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\t\tlistening: false,\n\t\t\t\t});\n\t\t\t\tthis.selGroup.add(rect);\n\t\t\t\treturn rect;\n\t\t\t});\n\t\t}\n\t\ttargets.forEach((shape, i) => {\n\t\t\tthis.selectionBorders[i].points(\n\t\t\t\tthis.selectionOutlinePoints(shape, shape.points).flatMap((p) => [p.x, p.y]),\n\t\t\t);\n\t\t});\n\t}\n\n\t/** 드래그 중 선택 테두리를 라이브 좌표로 동기화. */\n\tprivate updateSelectionBordersLive(getPoints: (shape: EditorShape) => Point[]) {\n\t\tconst selectedSet = new Set(this.selected);\n\t\tlet i = 0;\n\t\tfor (const shape of this.shapes) {\n\t\t\tif (!selectedSet.has(shape.id)) continue;\n\t\t\tif (!isShapeSelectable(shape)) continue;\n\t\t\tconst points = this.selectionOutlinePoints(shape, getPoints(shape));\n\t\t\tconst rect = this.selectionBorders[i++];\n\t\t\tif (rect) {\n\t\t\t\trect.points(points.flatMap((p) => [p.x, p.y]));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate selectionOutlinePoints(shape: EditorShape, points: Point[]) {\n\t\treturn outlinePointsFor(shape, points, this.pointRadius(shape));\n\t}\n\n\t// ── 미리보기 ──\n\t/** 그리는 중 폴리곤 초안 마지막 파라미터 — 줌 시 정점 원 크기 재계산용\n\t * (선은 strokeScaleEnabled=false로 화면 고정이라 재도색 불필요). */\n\tprivate lastPreviewPoly: {\n\t\tpoints: Point[];\n\t\tcursor: Point | null;\n\t\tstyle: ShapeStyle;\n\t\tclosed: boolean;\n\t\tselectedPointIndices: number[];\n\t\tshowVertices: boolean;\n\t} | null = null;\n\tclearPreview() {\n\t\tthis.lastPreviewPoly = null;\n\t\tthis.previewGroup.destroyChildren();\n\t\tthis.layer.batchDraw();\n\t}\n\tclearMarquee() {\n\t\tthis.marquee?.destroy();\n\t\tthis.marquee = null;\n\t\tthis.layer.batchDraw();\n\t}\n\tprivate preview: Konva.Shape | null = null;\n\tprivate marquee: Konva.Rect | null = null;\n\n\tpreviewBox(kind: PreviewKind, a: Point, b: Point, style: ShapeStyle) {\n\t\tthis.lastPreviewPoly = null;\n\t\tthis.previewGroup.destroyChildren();\n\t\tconst x = Math.min(a.x, b.x);\n\t\tconst y = Math.min(a.y, b.y);\n\t\tconst w = Math.abs(b.x - a.x);\n\t\tconst h = Math.abs(b.y - a.y);\n\t\tconst makePreview = (stroke: string, dash?: number[]) =>\n\t\t\tkind === \"ellipse\"\n\t\t\t\t? new Konva.Ellipse({\n\t\t\t\t\t\tx: x + w / 2,\n\t\t\t\t\t\ty: y + h / 2,\n\t\t\t\t\t\tradiusX: w / 2,\n\t\t\t\t\t\tradiusY: h / 2,\n\t\t\t\t\t\tstroke,\n\t\t\t\t\t\tstrokeWidth: style.strokeWidth ?? this.strokeSize,\n\t\t\t\t\t\tdash: this.scaledDash(dash),\n\t\t\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\t\t})\n\t\t\t\t: new Konva.Rect({\n\t\t\t\t\t\tx,\n\t\t\t\t\t\ty,\n\t\t\t\t\t\twidth: w,\n\t\t\t\t\t\theight: h,\n\t\t\t\t\t\tstroke,\n\t\t\t\t\t\tstrokeWidth: style.strokeWidth ?? this.strokeSize,\n\t\t\t\t\t\tdash: this.scaledDash(dash),\n\t\t\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\t\t});\n\t\tif (style.alternateColor) {\n\t\t\tthis.previewGroup.add(makePreview(style.alternateColor));\n\t\t}\n\t\tthis.preview = makePreview(style.color ?? \"#00e5ff\", style.dash);\n\t\tthis.previewGroup.add(this.preview);\n\t\tthis.layer.batchDraw();\n\t}\n\n\tpreviewPoly(\n\t\tpoints: Point[],\n\t\tcursor: Point | null,\n\t\tstyle: ShapeStyle,\n\t\tclosed: boolean,\n\t\tselectedPointIndices: number[] = [],\n\t\tshowVertices = true,\n\t) {\n\t\tthis.lastPreviewPoly = {\n\t\t\tpoints,\n\t\t\tcursor,\n\t\t\tstyle,\n\t\t\tclosed,\n\t\t\tselectedPointIndices,\n\t\t\tshowVertices,\n\t\t};\n\t\tthis.previewGroup.destroyChildren();\n\t\tif (!points.length) return;\n\t\tconst flat = points.flatMap((p) => [p.x, p.y]);\n\t\tif (cursor) flat.push(cursor.x, cursor.y);\n\t\tconst makePreview = (stroke: string, dash?: number[]) =>\n\t\t\tnew Konva.Line({\n\t\t\t\tpoints: flat,\n\t\t\t\tclosed,\n\t\t\t\tstroke,\n\t\t\t\tstrokeWidth: style.strokeWidth ?? this.strokeSize,\n\t\t\t\tdash: this.scaledDash(dash),\n\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\tlineCap: \"round\",\n\t\t\t\tlineJoin: \"round\",\n\t\t\t});\n\t\tif (style.alternateColor) {\n\t\t\tthis.previewGroup.add(makePreview(style.alternateColor));\n\t\t}\n\t\tthis.previewGroup.add(makePreview(style.color ?? \"#00e5ff\", style.dash));\n\t\t// PATH(자유선)처럼 점을 안 찍는 도구는 정점 점을 숨기고 선만 보여준다.\n\t\tif (!showVertices) {\n\t\t\tthis.layer.batchDraw();\n\t\t\treturn;\n\t\t}\n\t\tconst selected = new Set(selectedPointIndices);\n\t\tconst scale = this.world.scaleX() || 1;\n\t\tfor (let i = 0; i < points.length; i++) {\n\t\t\tconst point = points[i];\n\t\t\tconst isSelected = selected.has(i);\n\t\t\tthis.previewGroup.add(\n\t\t\t\tnew Konva.Circle({\n\t\t\t\t\tx: point.x,\n\t\t\t\t\ty: point.y,\n\t\t\t\t\tradius: (isSelected ? 6 : 5) / scale,\n\t\t\t\t\tfill: isSelected ? HANDLE_HEX : \"#ffffff\",\n\t\t\t\t\tstroke: isSelected ? \"#ffffff\" : HANDLE_HEX,\n\t\t\t\t\tstrokeWidth: 1.5,\n\t\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\t\tlistening: false,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tthis.layer.batchDraw();\n\t}\n\n\tpreviewScalarMask(raster: ScalarMaskRaster, color: string) {\n\t\tthis.previewGroup.destroyChildren();\n\t\tconst tint = color.length === 7 ? `${color}99` : color;\n\t\tconst previewCanvas = buildScalarMaskPreviewCanvas(raster, tint);\n\t\tthis.previewGroup.add(\n\t\t\tnew Konva.Image({\n\t\t\t\timage: previewCanvas,\n\t\t\t\tx: raster.ox,\n\t\t\t\ty: raster.oy,\n\t\t\t\tscaleX: 1 / raster.scale,\n\t\t\t\tscaleY: 1 / raster.scale,\n\t\t\t\tlistening: false,\n\t\t\t}),\n\t\t);\n\t\tthis.layer.batchDraw();\n\t}\n\n\tpreviewMarquee(a: Point, b: Point) {\n\t\tif (!this.marquee) {\n\t\t\tthis.marquee = new Konva.Rect({\n\t\t\t\tfill: colorWithAlpha(SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA),\n\t\t\t\tstroke: SELECTION_AREA_COLOR,\n\t\t\t\tstrokeWidth: 1,\n\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\tlistening: false,\n\t\t\t\tperfectDrawEnabled: false,\n\t\t\t});\n\t\t\tthis.previewGroup.add(this.marquee);\n\t\t}\n\t\tthis.marquee.setAttrs({\n\t\t\tx: Math.min(a.x, b.x),\n\t\t\ty: Math.min(a.y, b.y),\n\t\t\twidth: Math.abs(b.x - a.x),\n\t\t\theight: Math.abs(b.y - a.y),\n\t\t});\n\t\tthis.layer.batchDraw();\n\t}\n\n\t// ── 트랜스포머 ──\n\tsetTransformEnabled(enabled: boolean) {\n\t\tthis.transformEnabled = enabled;\n\t\tthis.drawTransformer();\n\t\tthis.layer.batchDraw();\n\t}\n\n\t// 팬 모드: 핸들 그룹 전체의 이벤트 수신만 끈다(핸들은 계속 보이되 클릭은 통과).\n\t// 그룹 속성이라 이후 drawTransformer 재생성에도 유지되고, 히트 그래프는 재도색해 반영.\n\tsetPanMode(active: boolean) {\n\t\tthis.handleGroup.listening(!active);\n\t\tthis.layer.batchDraw();\n\t}\n\n\tprivate setTransformerOutline(box: BBox) {\n\t\tconst w = Math.max(0, box.maxX - box.minX);\n\t\tconst h = Math.max(0, box.maxY - box.minY);\n\t\tif (!w && !h) return;\n\t\tthis.setTransformerOutlinePoints(\n\t\t\trectTo4([\n\t\t\t\t{ x: box.minX, y: box.minY },\n\t\t\t\t{ x: box.maxX, y: box.maxY },\n\t\t\t]),\n\t\t);\n\t}\n\n\tprivate setTransformerOutlinePoints(points: Point[]) {\n\t\tif (points.length < 2) return;\n\t\tif (!this.transformerOutline) {\n\t\t\tthis.transformerOutline = new Konva.Line({\n\t\t\t\tclosed: true,\n\t\t\t\tstroke: HANDLE_HEX,\n\t\t\t\tstrokeWidth: 1,\n\t\t\t\tstrokeScaleEnabled: false,\n\t\t\t\tlistening: false,\n\t\t\t});\n\t\t\tthis.selGroup.add(this.transformerOutline);\n\t\t}\n\t\tthis.transformerOutline.points(points.flatMap((p) => [p.x, p.y]));\n\t}\n\n\tprivate rotationHandleGap() {\n\t\treturn rotationHandleGapFor(this.viewport.scale);\n\t}\n\n\tprivate rotationHandleScreenPoint(points: Point[]) {\n\t\treturn this.imgToScreen(rotateHandlePos(points, this.rotationHandleGap()));\n\t}\n\n\tprivate setRotationConnector(points: Point[]) {\n\t\tconst from = this.imgToScreen(mid(points[0], points[1]));\n\t\tconst to = this.rotationHandleScreenPoint(points);\n\t\tif (!this.rotLineNode) {\n\t\t\tthis.rotLineNode = new Konva.Line({\n\t\t\t\tpoints: [from.x, from.y, to.x, to.y],\n\t\t\t\tstroke: HANDLE_HEX,\n\t\t\t\tstrokeWidth: 1,\n\t\t\t\tlistening: false,\n\t\t\t});\n\t\t\tthis.handleGroup.add(this.rotLineNode);\n\t\t} else {\n\t\t\tthis.rotLineNode.points([from.x, from.y, to.x, to.y]);\n\t\t}\n\t}\n\n\tprivate layoutResizeHandle(node: Konva.Rect, sp: Point, angleRad: number) {\n\t\tnode.position({ x: sp.x, y: sp.y });\n\t\tnode.offset({ x: 4, y: 4 });\n\t\tnode.rotation((angleRad * 180) / Math.PI);\n\t}\n\n\tprivate orientedHandleAngle(points: Point[]): number {\n\t\treturn orientedAngleFromScreenPoints(this.imgToScreen(points[0]), this.imgToScreen(points[1]));\n\t}\n\n\tprivate repositionOrientedHandles(points: Point[]) {\n\t\tconst angleRad = this.orientedHandleAngle(points);\n\t\torientedHandles(points).forEach((point, i) => {\n\t\t\tconst sp = this.imgToScreen(point);\n\t\t\tconst node = this.handleNodes[i];\n\t\t\tif (node) this.layoutResizeHandle(node, sp, angleRad);\n\t\t});\n\t\tthis.setTransformerOutlinePoints(points);\n\t\tif (this.rotNode) {\n\t\t\tconst sp = this.rotationHandleScreenPoint(points);\n\t\t\tthis.rotNode.position({ x: sp.x, y: sp.y });\n\t\t}\n\t\tif (this.rotLineNode) this.setRotationConnector(points);\n\t}\n\n\tdrawTransformer() {\n\t\tif (this.activeDrag) return;\n\t\tfor (const h of this.handleNodes) h.destroy();\n\t\tfor (const v of this.vertexNodes) v.destroy();\n\t\tfor (const m of this.midNodes) m.destroy();\n\t\tthis.rotNode?.destroy();\n\t\tthis.rotNode = null;\n\t\tthis.rotLineNode?.destroy();\n\t\tthis.rotLineNode = null;\n\t\tthis.transformerOutline?.destroy();\n\t\tthis.transformerOutline = null;\n\t\tthis.handleNodes = [];\n\t\tthis.vertexNodes = [];\n\t\tthis.midNodes = [];\n\t\tif (!this.transformEnabled) return;\n\t\tconst sel = selectEditable(this.shapes, this.selected);\n\t\tif (!sel.length) return;\n\t\tif (sel.length === 1 && sel[0].type === SHAPE_TYPE.POINT) return;\n\n\t\tconst editingPoly =\n\t\t\tsel.length === 1 &&\n\t\t\t(sel[0].type === SHAPE_TYPE.POLYGON || sel[0].type === SHAPE_TYPE.LINE) &&\n\t\t\tthis.editingId === sel[0].id\n\t\t\t\t? sel[0]\n\t\t\t\t: null;\n\n\t\tconst box = getBBox(sel.flatMap((s) => s.points));\n\t\tconst rotatedRect =\n\t\t\tsel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE ? sel[0] : null;\n\t\tconst transformerHandles = rotatedRect\n\t\t\t? orientedHandles(rotatedRect.points)\n\t\t\t: ANCHORS.map((a) => anchorPoint(a, box));\n\t\trotatedRect\n\t\t\t? this.setTransformerOutlinePoints(rotatedRect.points)\n\t\t\t: this.setTransformerOutline(box);\n\t\tif (rotatedRect) this.setRotationConnector(rotatedRect.points);\n\t\tconst handleAngleRad = rotatedRect ? this.orientedHandleAngle(rotatedRect.points) : 0;\n\t\t// 편집모드(정점 편집) 중엔 bbox 리사이즈 핸들을 숨긴다.\n\t\tfor (const a of editingPoly ? [] : ANCHORS) {\n\t\t\tconst sp = this.imgToScreen(transformerHandles[ANCHORS.indexOf(a)]);\n\t\t\tconst g = new Konva.Rect({\n\t\t\t\tx: sp.x,\n\t\t\t\ty: sp.y,\n\t\t\t\twidth: 8,\n\t\t\t\theight: 8,\n\t\t\t\toffsetX: 4,\n\t\t\t\toffsetY: 4,\n\t\t\t\trotation: (handleAngleRad * 180) / Math.PI,\n\t\t\t\tfill: \"#ffffff\",\n\t\t\t\tstroke: HANDLE_HEX,\n\t\t\t\tstrokeWidth: 1,\n\t\t\t});\n\t\t\tconst cursor = resizeCursorForAnchor(a, handleAngleRad);\n\t\t\tthis.bindCursor(g, cursor);\n\t\t\tg.on(\"mousedown\", (e) => {\n\t\t\t\te.cancelBubble = true;\n\t\t\t\tthis.emitCursorHint(cursor);\n\t\t\t\tthis.emitInteractionMode(\"resizing\");\n\t\t\t\tconst cur = selectEditable(this.shapes, this.selected);\n\t\t\t\tthis.activeDrag = {\n\t\t\t\t\tkind: \"resize\",\n\t\t\t\t\tanchor: a,\n\t\t\t\t\tbox: getBBox(cur.flatMap((s) => s.points)),\n\t\t\t\t\tshapes: cur.map((s) => ({ id: s.id, points: s.points })),\n\t\t\t\t};\n\t\t\t\tthis.lastDragImg = null;\n\t\t\t});\n\t\t\tthis.handleGroup.add(g);\n\t\t\tthis.handleNodes.push(g);\n\t\t}\n\t\tif (editingPoly) {\n\t\t\tconst shape = editingPoly;\n\t\t\tconst pts = shape.points;\n\t\t\tconst isPoly = shape.type === SHAPE_TYPE.POLYGON;\n\t\t\tconst edges = isPoly ? pts.length : pts.length - 1;\n\t\t\tfor (let i = 0; i < edges; i++) {\n\t\t\t\tconst a = pts[i];\n\t\t\t\tconst b = pts[(i + 1) % pts.length];\n\t\t\t\tconst m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n\t\t\t\tconst sp = this.imgToScreen(m);\n\t\t\t\tconst g = new Konva.Circle({\n\t\t\t\t\tx: sp.x,\n\t\t\t\t\ty: sp.y,\n\t\t\t\t\tradius: 4,\n\t\t\t\t\tfill: \"#ffffff\",\n\t\t\t\t\topacity: 0.6,\n\t\t\t\t\tstroke: HANDLE_HEX,\n\t\t\t\t\tstrokeWidth: 1,\n\t\t\t\t});\n\t\t\t\tthis.bindCursor(g, \"copy\");\n\t\t\t\tg.on(\"mousedown\", (e) => {\n\t\t\t\t\te.cancelBubble = true;\n\t\t\t\t\tconst next = [...pts.slice(0, i + 1), m, ...pts.slice(i + 1)];\n\t\t\t\t\tthis.cb.onTransformCommit?.([{ id: shape.id, points: next }]);\n\t\t\t\t});\n\t\t\t\tthis.handleGroup.add(g);\n\t\t\t\tthis.midNodes.push(g);\n\t\t\t}\n\t\t\t// 편집 대상 폴리곤이 바뀌면 정점 다중선택 초기화.\n\t\t\tif (this.vertexPolygonId !== shape.id) {\n\t\t\t\tthis.vertexPolygonId = shape.id;\n\t\t\t\tthis.selectedVertices.clear();\n\t\t\t}\n\t\t\tpts.forEach((pt, i) => {\n\t\t\t\tconst sp = this.imgToScreen(pt);\n\t\t\t\tconst isSel = this.selectedVertices.has(i);\n\t\t\t\tconst g = new Konva.Circle({\n\t\t\t\t\tx: sp.x,\n\t\t\t\t\ty: sp.y,\n\t\t\t\t\tradius: 5,\n\t\t\t\t\tfill: isSel ? HANDLE_HEX : \"#ffffff\",\n\t\t\t\t\tstroke: isSel ? \"#ffffff\" : HANDLE_HEX,\n\t\t\t\t\tstrokeWidth: 1.5,\n\t\t\t\t});\n\t\t\t\tthis.bindCursor(g, \"pointer\");\n\t\t\t\tg.on(\"mousedown\", (e) => {\n\t\t\t\t\te.cancelBubble = true;\n\t\t\t\t\t// Shift/Ctrl/Cmd: 정점 다중선택 토글(드래그 안 함).\n\t\t\t\t\tif (e.evt.shiftKey || e.evt.ctrlKey || e.evt.metaKey) {\n\t\t\t\t\t\tif (this.selectedVertices.has(i)) this.selectedVertices.delete(i);\n\t\t\t\t\t\telse this.selectedVertices.add(i);\n\t\t\t\t\t\tthis.drawTransformer();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// 선택된 정점 위를 그냥 클릭하면 선택 세트 전체를 함께 이동, 아니면 그 정점만.\n\t\t\t\t\tconst indices =\n\t\t\t\t\t\tthis.selectedVertices.has(i) && this.selectedVertices.size > 1\n\t\t\t\t\t\t\t? [...this.selectedVertices]\n\t\t\t\t\t\t\t: [i];\n\t\t\t\t\tif (indices.length === 1) {\n\t\t\t\t\t\tthis.selectedVertices.clear();\n\t\t\t\t\t\tthis.selectedVertices.add(i);\n\t\t\t\t\t}\n\t\t\t\t\tthis.activeDrag = {\n\t\t\t\t\t\tkind: \"vertex\",\n\t\t\t\t\t\tid: shape.id,\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tbase: pts,\n\t\t\t\t\t\tstart: this.toImage(),\n\t\t\t\t\t};\n\t\t\t\t\tthis.lastDragImg = null;\n\t\t\t\t\tthis.emitCursorHint(\"grabbing\");\n\t\t\t\t\tthis.emitInteractionMode(\"vertexDragging\");\n\t\t\t\t});\n\t\t\t\tthis.handleGroup.add(g);\n\t\t\t\tthis.vertexNodes.push(g);\n\t\t\t});\n\t\t}\n\n\t\tif (sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n\t\t\tconst shape = sel[0];\n\t\t\tconst center = centerOf(shape.points);\n\t\t\tconst sp = this.rotationHandleScreenPoint(shape.points);\n\t\t\tconst g = new Konva.Circle({\n\t\t\t\tx: sp.x,\n\t\t\t\ty: sp.y,\n\t\t\t\tradius: 6,\n\t\t\t\tfill: \"#ffffff\",\n\t\t\t\tstroke: HANDLE_HEX,\n\t\t\t\tstrokeWidth: 1.5,\n\t\t\t});\n\t\t\tthis.bindCursor(g, \"grab\");\n\t\t\tg.on(\"mousedown\", (e) => {\n\t\t\t\te.cancelBubble = true;\n\t\t\t\tconst ip = this.toImage();\n\t\t\t\tthis.activeDrag = {\n\t\t\t\t\tkind: \"rotate\",\n\t\t\t\t\tid: shape.id,\n\t\t\t\t\tcenter,\n\t\t\t\t\tstartAngle: Math.atan2(ip.y - center.y, ip.x - center.x),\n\t\t\t\t\tpoints: shape.points,\n\t\t\t\t\tshiftKey: e.evt.shiftKey,\n\t\t\t\t};\n\t\t\t\tthis.lastDragImg = null;\n\t\t\t\tthis.emitCursorHint(\"grabbing\");\n\t\t\t\tthis.emitInteractionMode(\"rotating\");\n\t\t\t});\n\t\t\tthis.handleGroup.add(g);\n\t\t\tthis.rotNode = g;\n\t\t}\n\t\tthis.layer.batchDraw();\n\t}\n\n\tbeginMove(start: Point, ids: string[]) {\n\t\tconst drag = makeMoveDrag(this.shapes, ids, start);\n\t\tif (!drag) return;\n\t\tif (this.transformEnabled && !this.handleNodes.length) this.drawTransformer();\n\t\tthis.activeDrag = drag;\n\t\tthis.lastDragImg = null;\n\t\tthis.emitCursorHint(\"grabbing\");\n\t\tthis.emitInteractionMode(\"moving\");\n\t\tconst selectedShape =\n\t\t\tdrag.shapes.length === 1 ? this.shapes.find((s) => s.id === drag.shapes[0].id) : null;\n\t\tif (selectedShape?.type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n\t\t\tthis.setTransformerOutlinePoints(drag.shapes[0].points);\n\t\t} else {\n\t\t\tthis.setTransformerOutline(drag.box);\n\t\t}\n\t\tthis.updateSelectionBordersLive((shape) => shape.points);\n\t}\n\n\tprivate repositionHandles(box: BBox) {\n\t\tANCHORS.forEach((a, i) => {\n\t\t\tconst sp = this.imgToScreen(anchorPoint(a, box));\n\t\t\tconst node = this.handleNodes[i];\n\t\t\tif (node) this.layoutResizeHandle(node, sp, 0);\n\t\t});\n\t\tthis.setTransformerOutline(box);\n\t}\n\n\t/** 폴리곤/라인 꼭짓점·변 중점 핸들을 이미지 좌표 기준으로 재배치. */\n\tprivate repositionPolygonHandles(pts: Point[], isPolygon: boolean) {\n\t\tif (!this.vertexNodes.length) return;\n\t\tpts.forEach((pt, i) => {\n\t\t\tconst sp = this.imgToScreen(pt);\n\t\t\tthis.vertexNodes[i]?.position({ x: sp.x, y: sp.y });\n\t\t});\n\t\tconst edges = isPolygon ? pts.length : pts.length - 1;\n\t\tfor (let i = 0; i < edges; i++) {\n\t\t\tconst a = pts[i];\n\t\t\tconst b = pts[(i + 1) % pts.length];\n\t\t\tconst sp = this.imgToScreen({\n\t\t\t\tx: (a.x + b.x) / 2,\n\t\t\t\ty: (a.y + b.y) / 2,\n\t\t\t});\n\t\t\tthis.midNodes[i]?.position({ x: sp.x, y: sp.y });\n\t\t}\n\t}\n\n\tprivate commitTransformUpdates(updates: { id: string; points: Point[] }[]) {\n\t\tif (!updates.length) return;\n\t\tfor (const update of updates) {\n\t\t\tconst shape = this.shapes.find((s) => s.id === update.id);\n\t\t\tif (!shape) continue;\n\t\t\tshape.points = update.points;\n\t\t\tthis.liveUpdateShape(update.id, update.points);\n\t\t}\n\t\tthis.cb.onTransformCommit?.(updates);\n\t\tthis.drawTransformer();\n\t\tthis.layer.batchDraw();\n\t}\n\n\t// lastDragImg 기록은 mousemove 콜러 소유 — 뷰포트 변경(줌/팬) 중 재호출해도\n\t// endTransform의 \"이동 없음 → 커밋 생략\" 판정이 유지된다.\n\tprivate dragTransform(img: Point) {\n\t\tconst d = this.activeDrag;\n\t\tif (!d) return;\n\t\tthis.applyCursor();\n\t\tconst isRotatedRect = dragTargetIsRotatedRect(this.shapes, d);\n\t\tconst { updates, box } = computeDragUpdates(d, img, isRotatedRect);\n\t\tfor (const u of updates) this.liveUpdateShape(u.id, u.points);\n\t\tthis.cb.onTransformPreview?.(updates);\n\t\tthis.updateSelectionBordersLive(\n\t\t\t(shape) => updates.find((item) => item.id === shape.id)?.points ?? shape.points,\n\t\t);\n\t\tif (d.kind === \"resize\" || d.kind === \"move\") {\n\t\t\tif (isRotatedRect) this.repositionOrientedHandles(updates[0].points);\n\t\t\telse if (box) this.repositionHandles(box);\n\t\t\tconst single =\n\t\t\t\td.shapes.length === 1 ? this.shapes.find((s) => s.id === d.shapes[0].id) : null;\n\t\t\tconst isPolyLike = single?.type === SHAPE_TYPE.POLYGON || single?.type === SHAPE_TYPE.LINE;\n\t\t\tconst showPolyHandles =\n\t\t\t\td.kind === \"resize\" ? isPolyLike : this.vertexNodes.length > 0 && d.shapes.length === 1;\n\t\t\tif (showPolyHandles) {\n\t\t\t\tthis.repositionPolygonHandles(updates[0].points, single?.type === SHAPE_TYPE.POLYGON);\n\t\t\t}\n\t\t} else if (d.kind === \"rotate\") {\n\t\t\tthis.repositionOrientedHandles(updates[0].points);\n\t\t\tconst shape = this.shapes.find((s) => s.id === d.id);\n\t\t\tif (shape && (shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE)) {\n\t\t\t\tthis.repositionPolygonHandles(updates[0].points, shape.type === SHAPE_TYPE.POLYGON);\n\t\t\t}\n\t\t} else {\n\t\t\tif (box) this.repositionHandles(box);\n\t\t\tconst shape = this.shapes.find((s) => s.id === d.id);\n\t\t\tthis.repositionPolygonHandles(updates[0].points, shape?.type === SHAPE_TYPE.POLYGON);\n\t\t}\n\t\tthis.layer.batchDraw();\n\t}\n\n\tprivate endTransform() {\n\t\tconst d = this.activeDrag;\n\t\tconst img = this.lastDragImg;\n\t\tthis.activeDrag = null;\n\t\tthis.emitInteractionMode(\"idle\");\n\t\tthis.emitCursorHint(d?.kind === \"move\" ? \"grab\" : null);\n\t\tif (!d || !img) {\n\t\t\tthis.cb.onTransformPreview?.([]);\n\t\t\tthis.drawTransformer();\n\t\t\treturn;\n\t\t}\n\t\tif (d.kind === \"move\" && img.x === d.start.x && img.y === d.start.y) {\n\t\t\tthis.cb.onTransformPreview?.([]);\n\t\t\tthis.drawTransformer();\n\t\t\treturn;\n\t\t}\n\t\tconst { updates } = computeDragUpdates(d, img, dragTargetIsRotatedRect(this.shapes, d));\n\t\tthis.commitTransformUpdates(updates);\n\t}\n}\n","import {\n\tApplication,\n\tColorMatrixFilter,\n\tContainer,\n\ttype FederatedPointerEvent,\n\tGraphics,\n\tRectangle,\n\tSprite,\n\tTexture,\n} from \"pixi.js\";\nimport { SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA } from \"../_constants\";\nimport { resizeCursorForAnchor } from \"../_model/cursors\";\nimport {\n\tANCHORS,\n\tanchorPoint,\n\ttype BBox,\n\tcenterOf,\n\ttype EditorShape,\n\tgetBBox,\n\tisShapeDraggable,\n\tisShapeSelectable,\n\tisShapeVisible,\n\tmid,\n\torientedHandles,\n\ttype Point,\n\trectTo4,\n\trotateHandlePos,\n\tSHAPE_TYPE,\n\ttype ShapeStyle,\n\tsortShapesForRender,\n} from \"../_model/geometry\";\nimport { fetchImageObjectUrl } from \"../_model/imageFetch\";\nimport { createImageTileCanvas, getImageTiles } from \"../_model/imageTiles\";\nimport type { RegionOverlayData, ResolvedRegionOutlineStyle } from \"../_model/overlays\";\nimport { PIN_HEIGHT, PIN_WIDTH, pinSvg } from \"../_model/pinIcon\";\nimport { buildScalarMaskPreviewCanvas, type ScalarMaskRaster } from \"../_model/scalarMask\";\nimport { resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\nimport {\n\ttype ActiveDrag,\n\tcloneShapes,\n\tcomputeDragUpdates,\n\tdragIdentityImage,\n\tdragTargetIsRotatedRect,\n\tintersectingShapeIds,\n\tmakeMoveDrag,\n\torientedAngleFromScreenPoints,\n\toutlinePointsFor,\n\tpointRadiusFor,\n\trotationHandleGapFor,\n\tselectEditable,\n} from \"./transformSession\";\nimport type { EditorRendererCallbacks, Viewport } from \"./types\";\n\nexport type { Viewport };\n\nconst STROKE = 2;\nconst _POINT_RADIUS = 5;\nconst DEFAULT_COLOR = 0x00e5ff;\nconst SELECTION_BORDER = 0x669def;\n\nfunction hexToNum(hex?: string): number {\n\tif (!hex) return DEFAULT_COLOR;\n\tconst h = hex.replace(\"#\", \"\");\n\treturn Number.parseInt(h.length === 3 ? h.replace(/./g, \"$&$&\") : h, 16);\n}\n\n/**\n * Pixi renderer backend(WebGL). React 비의존.\n * 좌표계: world 컨테이너가 이미지 좌표를 담고, scale/position으로 줌/팬.\n */\nexport class PixiRenderer {\n\tapp = new Application();\n\tworld = new Container();\n\tbgLayer = new Container(); // 이미지 + 색보정\n\toverlayLayer = new Container(); // 마스크/ROI(후속)\n\tshapeLayer = new Container();\n\tselLayer = new Container(); // 선택 테두리\n\tpreviewLayer = new Container(); // 그리기 미리보기\n\thandleLayer = new Container(); // 트랜스포머/핸들(화면고정)\n\n\tfilter = new ColorMatrixFilter();\n\timageWidth = 0;\n\timageHeight = 0;\n\tprivate imageTileTextures: Texture[] = [];\n\t// 연속 setImage 레이스 가드 — 마지막 요청만 타일을 교체한다.\n\tprivate imageLoadToken = 0;\n\tprivate overlayTextures: Texture[] = [];\n\t// 영역 윤곽 점선 — 줌 시 화면고정 두께로 재도색해야 해서 벡터 데이터를 보관.\n\tprivate region: RegionOverlayData | null = null;\n\tprivate regionOutlineG: Graphics | null = null;\n\n\tprivate cb: EditorRendererCallbacks;\n\tprivate host: HTMLElement;\n\tprivate baseCursor = \"default\";\n\tprivate strokeSize = STROKE;\n\tprivate shapes: EditorShape[] = [];\n\tprivate selected: string[] = [];\n\tprivate nodes = new Map<string, Graphics>();\n\t// 마지막으로 적용한 뷰포트 스케일. 판(스케일 불변) 시 재도색을 건너뛰기 위한 비교용.\n\tprivate lastAppliedScale = -1;\n\tprivate brightness = 1;\n\tprivate contrast = 1;\n\tprivate imageSmoothing = true;\n\tprivate destroyed = false;\n\tprivate transformEnabled = false;\n\tprivate handleNodes: Graphics[] = [];\n\tprivate vertexNodes: Graphics[] = [];\n\tprivate lastDragImg: Point | null = null;\n\tprivate activeDrag: ActiveDrag | null = null;\n\tprivate midNodes: Graphics[] = [];\n\t// 다중 선택된 정점 인덱스(현재 편집 폴리곤 기준). 함께 이동.\n\tprivate selectedVertices = new Set<number>();\n\tprivate vertexPolygonId: string | null = null;\n\t// 폴리곤 정점 편집모드 대상 id. 이 값이 선택된 단일 폴리곤과 같을 때만 정점/변중점\n\t// 핸들을 보여준다(단순 선택으로는 정점을 안 보이게 — 옵스식 편집모드).\n\tprivate editingId: string | null = null;\n\tprivate rotNode: Graphics | null = null;\n\tprivate rotLineNode: Graphics | null = null;\n\tprivate transformerOutline: Graphics | null = null;\n\tprivate selectionBorderGfx: Graphics[] = [];\n\n\tconstructor(host: HTMLElement, cb: EditorRendererCallbacks) {\n\t\tthis.host = host;\n\t\tthis.cb = cb;\n\t}\n\n\t/** Pixi 이벤트 → 렌더러 추상화 이벤트. */\n\tprivate ev(e: FederatedPointerEvent) {\n\t\treturn {\n\t\t\tbutton: e.button,\n\t\t\tshiftKey: e.shiftKey,\n\t\t\taltKey: e.altKey,\n\t\t\tctrlKey: e.ctrlKey,\n\t\t\tmetaKey: e.metaKey,\n\t\t\tglobal: { x: e.global.x, y: e.global.y },\n\t\t};\n\t}\n\n\tasync init() {\n\t\tawait this.app.init({\n\t\t\tresizeTo: this.host,\n\t\t\tbackground: \"#111111\",\n\t\t\tantialias: true,\n\t\t\tautoDensity: true,\n\t\t\tresolution: window.devicePixelRatio || 1,\n\t\t\tpreference: \"webgl\",\n\t\t});\n\t\tif (this.destroyed) {\n\t\t\tthis.app.destroy(true);\n\t\t\treturn;\n\t\t}\n\t\tthis.host.appendChild(this.app.canvas);\n\t\tthis.applyCursor();\n\n\t\tthis.world.addChild(\n\t\t\tthis.bgLayer,\n\t\t\tthis.overlayLayer,\n\t\t\tthis.shapeLayer,\n\t\t\tthis.selLayer,\n\t\t\tthis.previewLayer,\n\t\t);\n\t\tthis.app.stage.addChild(this.world, this.handleLayer);\n\t\t// 뷰포트(fit)가 정해지기 전엔 콘텐츠를 숨긴다. 안 그러면 이미지가 fit 전 기본\n\t\t// 뷰포트로 한 프레임 그려졌다가 fit되면서 위치/크기가 튀어 보인다. 첫 applyViewport\n\t\t// (fit 포함)에서 노출한다.\n\t\tthis.world.visible = false;\n\n\t\t// 스테이지 전체 포인터 입력(팬/마퀴/그리기용).\n\t\tthis.app.stage.eventMode = \"static\";\n\t\tthis.syncHitArea();\n\t\tthis.app.stage.on(\"pointerdown\", (e) => {\n\t\t\t// 도형이 먼저 처리(stopPropagation)하지 않은 경우만 = 빈 공간.\n\t\t\tthis.cb.onPointerDown(this.toImage(e), null, this.ev(e));\n\t\t});\n\t\tthis.app.stage.on(\"pointermove\", (e) => {\n\t\t\tif (this.activeDrag) {\n\t\t\t\tthis.lastDragImg = this.toImage(e);\n\t\t\t\tthis.dragTransform(this.lastDragImg);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cb.onPointerMove(this.toImage(e), this.ev(e));\n\t\t});\n\t\tconst up = (e: FederatedPointerEvent) => {\n\t\t\tif (this.activeDrag) {\n\t\t\t\tthis.endTransform();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cb.onPointerUp(this.toImage(e));\n\t\t};\n\t\tthis.app.stage.on(\"pointerup\", up);\n\t\tthis.app.stage.on(\"pointerupoutside\", up);\n\n\t\tthis.app.renderer.on(\"resize\", () => this.syncHitArea());\n\t}\n\n\tprivate syncHitArea() {\n\t\t// screenSize(CSS px)와 동일 기준을 써야 한다. 예전엔 renderer.width를 resolution으로\n\t\t// 다시 나눠 retina에서 hitArea가 절반이 됐고, 마퀴/빈공간 클릭이 좌상단에서만 됐다.\n\t\tconst { w, h } = this.screenSize;\n\t\tthis.app.stage.hitArea = new Rectangle(0, 0, w, h);\n\t}\n\n\tdestroy() {\n\t\tthis.destroyed = true;\n\t\tthis.clearImageTiles();\n\t\tfor (const texture of this.overlayTextures) texture.destroy(true);\n\t\tthis.overlayTextures = [];\n\t\tif (this.app.renderer) this.app.destroy(true, { children: true });\n\t}\n\n\tget screenSize() {\n\t\t// renderer.screen은 CSS 픽셀 기준 화면 크기다. renderer.width/height도 v8에서 CSS\n\t\t// 픽셀이라 resolution으로 다시 나누면 retina(dpr>1)에서 절반이 되는 버그가 있었다.\n\t\treturn {\n\t\t\tw: this.app.renderer.screen.width,\n\t\t\th: this.app.renderer.screen.height,\n\t\t};\n\t}\n\n\tsetCursor(cursor: string) {\n\t\tthis.baseCursor = cursor;\n\t\tthis.syncShapeCursors();\n\t\tthis.applyCursor();\n\t}\n\n\tprivate emitCursorHint(cursor: string | null) {\n\t\tthis.cb.onCursorHint?.(cursor);\n\t}\n\n\tprivate emitInteractionMode(\n\t\tmode: \"idle\" | \"moving\" | \"resizing\" | \"rotating\" | \"vertexDragging\",\n\t) {\n\t\tthis.cb.onInteractionModeChange?.(mode);\n\t}\n\n\tprivate applyCursor() {\n\t\tif (this.destroyed || !this.app.renderer) return;\n\t\tconst canvas = this.app.canvas;\n\t\tif (!canvas) return;\n\t\tcanvas.style.cursor = this.baseCursor;\n\t}\n\n\tprivate syncShapeCursors() {\n\t\tfor (const node of this.nodes.values()) {\n\t\t\tnode.cursor = undefined;\n\t\t}\n\t}\n\n\tprivate bindCursor(node: Graphics, cursor: string) {\n\t\tnode.cursor = undefined;\n\t\tnode.on(\"pointerover\", () => {\n\t\t\tif (this.activeDrag) return;\n\t\t\tthis.emitCursorHint(cursor);\n\t\t});\n\t\tnode.on(\"pointerout\", () => {\n\t\t\tif (!this.activeDrag) this.emitCursorHint(null);\n\t\t});\n\t}\n\n\t/** 휠/컨텍스트메뉴 리스너 부착용 DOM 요소(렌더러 추상화). */\n\tget dom(): HTMLElement {\n\t\treturn this.app.canvas;\n\t}\n\n\t/** 화면 좌표(global) → 이미지 좌표(world local). */\n\ttoImage(e: FederatedPointerEvent): Point {\n\t\tconst p = this.world.toLocal(e.global);\n\t\treturn { x: p.x, y: p.y };\n\t}\n\n\tasync setImage(url: string) {\n\t\tconst loadToken = ++this.imageLoadToken;\n\t\t// WebGL 텍스처는 CORS-clean 이미지만 허용한다. HTTP 캐시 우선 + 오염 캐시(CORS\n\t\t// 헤더 없는 응답)일 때만 reload 재시도 — 페이지 전환/화질 스왑/재방문 시\n\t\t// 재다운로드를 피한다(imageFetch.ts 참고). fetch가 막히면 crossOrigin img로 폴백.\n\t\tconst objectUrl = await fetchImageObjectUrl(url);\n\t\tif (this.destroyed) {\n\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\treturn;\n\t\t}\n\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst img = new Image();\n\t\t\t// blob URL은 same-origin이라 crossOrigin 불필요. 폴백(원본 URL)일 때만 지정.\n\t\t\tif (!objectUrl) img.crossOrigin = \"anonymous\";\n\t\t\timg.onload = () => {\n\t\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\t\tif (this.destroyed) return resolve();\n\t\t\t\tif (loadToken !== this.imageLoadToken) return resolve(); // 더 최신 요청 있음.\n\t\t\t\tthis.imageWidth = img.naturalWidth;\n\t\t\t\tthis.imageHeight = img.naturalHeight;\n\t\t\t\tthis.clearImageTiles();\n\t\t\t\tfor (const tile of getImageTiles(this.imageWidth, this.imageHeight)) {\n\t\t\t\t\tconst texture = Texture.from(createImageTileCanvas(img, tile));\n\t\t\t\t\ttexture.source.scaleMode = this.imageSmoothing ? \"linear\" : \"nearest\";\n\t\t\t\t\tthis.imageTileTextures.push(texture);\n\t\t\t\t\tconst sprite = new Sprite(texture);\n\t\t\t\t\tsprite.x = tile.x;\n\t\t\t\t\tsprite.y = tile.y;\n\t\t\t\t\tsprite.width = tile.width;\n\t\t\t\t\tsprite.height = tile.height;\n\t\t\t\t\tthis.bgLayer.addChild(sprite);\n\t\t\t\t}\n\t\t\t\tthis.applySpriteFilter();\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\timg.onerror = () => {\n\t\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\t\tthis.imageWidth ||= 800;\n\t\t\t\tthis.imageHeight ||= 600;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\timg.src = objectUrl ?? url;\n\t\t});\n\t}\n\n\tsetFilter(brightness: number, contrast: number) {\n\t\tthis.brightness = brightness;\n\t\tthis.contrast = contrast;\n\t\tthis.applySpriteFilter();\n\t}\n\n\tsetStrokeSize(strokeSize: number) {\n\t\tif (this.strokeSize === strokeSize) return;\n\t\tthis.strokeSize = strokeSize;\n\t\tthis.setShapes(this.shapes, this.selected);\n\t}\n\n\tprivate applySpriteFilter() {\n\t\tif (this.destroyed || !this.app.renderer) return;\n\t\tconst hasFilter = this.brightness !== 1 || this.contrast !== 1;\n\t\tif (!hasFilter) {\n\t\t\tthis.filter.reset();\n\t\t\tthis.bgLayer.filters = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.filter.brightness(this.brightness, false);\n\t\t// Pixi contrast uses 0 as identity, while Editor view settings use the\n\t\t// CSS convention where 1 is identity.\n\t\tthis.filter.contrast(this.contrast - 1, true);\n\t\tthis.bgLayer.filters = [this.filter];\n\t}\n\n\tclearImage() {\n\t\tif (this.destroyed) return;\n\t\t// 이후 도착하는 이전 setImage 응답이 타일을 되살리지 않게 토큰도 올린다.\n\t\tthis.imageLoadToken++;\n\t\tthis.clearImageTiles();\n\t}\n\n\tprivate clearImageTiles() {\n\t\tfor (const child of this.bgLayer.removeChildren()) {\n\t\t\tchild.destroy();\n\t\t}\n\t\tfor (const texture of this.imageTileTextures) {\n\t\t\ttexture.destroy(true);\n\t\t}\n\t\tthis.imageTileTextures = [];\n\t}\n\n\tsetImageSmoothing(smooth: boolean) {\n\t\tif (this.imageSmoothing === smooth) return;\n\t\tthis.imageSmoothing = smooth;\n\t\tconst mode = smooth ? \"linear\" : \"nearest\";\n\t\tfor (const texture of this.imageTileTextures) {\n\t\t\ttexture.source.scaleMode = mode;\n\t\t\t// scaleMode 세터는 필터만 대입하고 change를 안 쏨 → GPU 샘플러가 캐시된 채 유지된다.\n\t\t\t// style.update()로 리소스 무효화를 트리거해야 실제로 반영된다.\n\t\t\ttexture.source.style.update();\n\t\t}\n\t\tif (!this.destroyed && this.app.renderer) this.app.render();\n\t}\n\n\tsetOverlays(\n\t\tmaskCanvas: HTMLCanvasElement | null,\n\t\tregion: RegionOverlayData | null,\n\t\tdimmed: boolean,\n\t) {\n\t\tfor (const child of this.overlayLayer.removeChildren()) child.destroy();\n\t\tthis.regionOutlineG = null;\n\t\tthis.region = region;\n\t\tfor (const texture of this.overlayTextures) texture.destroy(true);\n\t\tthis.overlayTextures = [];\n\t\tif (maskCanvas) {\n\t\t\tconst texture = Texture.from(maskCanvas);\n\t\t\ttexture.source.scaleMode = \"nearest\";\n\t\t\tthis.overlayTextures.push(texture);\n\t\t\tconst sprite = new Sprite(texture);\n\t\t\tsprite.alpha = 0.55;\n\t\t\tthis.overlayLayer.addChild(sprite);\n\t\t}\n\t\tif (region) {\n\t\t\t// 벡터 딤 — 래스터(캔버스 굽기 + 텍스처 업로드) 없이 매 프레임 재계산해도 싸서\n\t\t\t// 드래그 중 오버레이가 트랜스포머와 같은 박자로 따라온다.\n\t\t\t// 스텐실 마스크는 겹치는 영역도 합집합으로 처리한다. 마스크의 계단 현상은\n\t\t\t// 경계 위에 그려지는 점선 윤곽이 덮는다.\n\t\t\t// 마스크는 각자 컨텍스트를 소유해야 destroy 시 함께 정리된다(공유 컨텍스트는 누수).\n\t\t\tconst dimColor = hexToNum(region.dim.color);\n\t\t\tconst buildUnionMask = () => {\n\t\t\t\tconst mask = new Graphics();\n\t\t\t\tfor (const r of region.rects) mask.rect(r.x, r.y, r.w, r.h).fill(0xffffff);\n\t\t\t\treturn mask;\n\t\t\t};\n\t\t\tconst dimG = new Graphics()\n\t\t\t\t.rect(0, 0, this.imageWidth, this.imageHeight)\n\t\t\t\t.fill({ color: dimColor, alpha: region.dim.opacity });\n\t\t\tconst dimMask = buildUnionMask();\n\t\t\tthis.overlayLayer.addChild(dimMask, dimG);\n\t\t\tdimG.setMask({ mask: dimMask, inverse: true });\n\t\t\tif (region.zones.length) {\n\t\t\t\tconst zoneG = new Graphics();\n\t\t\t\tfor (const z of region.zones) {\n\t\t\t\t\tzoneG\n\t\t\t\t\t\t.poly(\n\t\t\t\t\t\t\tz.points.flatMap((point) => [point.x, point.y]),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.fill({ color: dimColor, alpha: region.dim.opacity });\n\t\t\t\t}\n\t\t\t\tconst zoneMask = buildUnionMask();\n\t\t\t\tthis.overlayLayer.addChild(zoneMask, zoneG);\n\t\t\t\tzoneG.setMask({ mask: zoneMask });\n\t\t\t}\n\t\t\tif (region.outlineStyles) {\n\t\t\t\tthis.regionOutlineG = this.overlayLayer.addChild(new Graphics());\n\t\t\t\tthis.redrawRegionOutline();\n\t\t\t}\n\t\t}\n\t\tif (dimmed && this.imageWidth) {\n\t\t\tthis.overlayLayer.addChild(\n\t\t\t\tnew Graphics()\n\t\t\t\t\t.rect(0, 0, this.imageWidth, this.imageHeight)\n\t\t\t\t\t.fill({ color: 0x0d0d12, alpha: 0.3 }),\n\t\t\t);\n\t\t}\n\t\tif (!this.destroyed && this.app.renderer) this.app.render();\n\t}\n\n\t// ── 뷰포트 ──\n\tget viewport(): Viewport {\n\t\treturn { scale: this.world.scale.x, x: this.world.x, y: this.world.y };\n\t}\n\n\tapplyViewport(v: Viewport) {\n\t\t// 판(translate만)은 스케일이 안 바뀌므로 재도색/핸들 재생성이 불필요하다\n\t\t// (월드 하위 노드가 함께 이동). 스트로크 폭·핸들 크기를 화면px로 유지하기 위한\n\t\t// 재도색은 줌(스케일 변경) 때만 한다 — 도형 많을 때 판이 매 프레임 전체 재그리기로\n\t\t// 렉 걸리던 것을 방지.\n\t\tconst scaleChanged = v.scale !== this.lastAppliedScale;\n\t\tthis.lastAppliedScale = v.scale;\n\t\tthis.world.scale.set(v.scale);\n\t\tthis.world.position.set(v.x, v.y);\n\t\tthis.world.visible = true; // 뷰포트 확정 → 콘텐츠 노출(초기 unfit 프레임 방지)\n\t\tif (scaleChanged) this.restrokeShapes();\n\t\t// 트랜스포머 핸들은 화면 고정 레이어(stage 직속)에 화면 좌표로 그려지므로\n\t\t// 판(이동)에서도 매번 위치를 재계산해야 한다. 선택분만 그려서 가볍다.\n\t\t// 드래그(클릭 유지 포함) 중에는 drawTransformer가 조기 종료하므로\n\t\t// 마지막(또는 identity) 포인터 좌표로 라이브 재배치한다.\n\t\tif (this.activeDrag) {\n\t\t\tthis.dragTransform(this.lastDragImg ?? dragIdentityImage(this.shapes, this.activeDrag));\n\t\t} else {\n\t\t\tthis.drawTransformer();\n\t\t}\n\t\tthis.cb.onViewportChange?.();\n\t}\n\n\tfit() {\n\t\tif (!this.imageWidth || !this.imageHeight) return;\n\t\tconst { w, h } = this.screenSize;\n\t\tconst scale = Math.min(w / this.imageWidth, h / this.imageHeight);\n\t\tthis.applyViewport({\n\t\t\tscale,\n\t\t\tx: (w - this.imageWidth * scale) / 2,\n\t\t\ty: (h - this.imageHeight * scale) / 2,\n\t\t});\n\t}\n\n\tzoom100() {\n\t\tif (!this.imageWidth || !this.imageHeight) return;\n\t\tconst { w, h } = this.screenSize;\n\t\tthis.applyViewport({\n\t\t\tscale: 1,\n\t\t\tx: (w - this.imageWidth) / 2,\n\t\t\ty: (h - this.imageHeight) / 2,\n\t\t});\n\t}\n\n\tzoomAt(cx: number, cy: number, factor: number, min = 0.05, max = 20) {\n\t\tconst s = this.world.scale.x;\n\t\tconst ns = Math.min(max, Math.max(min, s * factor));\n\t\tconst wx = (cx - this.world.x) / s;\n\t\tconst wy = (cy - this.world.y) / s;\n\t\tthis.applyViewport({ scale: ns, x: cx - wx * ns, y: cy - wy * ns });\n\t}\n\n\tpanBy(dx: number, dy: number) {\n\t\tthis.applyViewport({\n\t\t\tscale: this.world.scale.x,\n\t\t\tx: this.world.x + dx,\n\t\t\ty: this.world.y + dy,\n\t\t});\n\t}\n\n\t// ── 도형 렌더 ──\n\tsetShapes(shapes: EditorShape[], selected: string[]) {\n\t\tthis.shapes = cloneShapes(shapes);\n\t\tthis.selected = selected;\n\t\tif (this.activeDrag) return;\n\t\tthis.drawShapes();\n\t\tthis.drawSelectionBorders();\n\t\tthis.drawTransformer();\n\t}\n\n\tsetSelection(selected: string[]) {\n\t\tthis.selected = selected;\n\t\tif (selected.length !== 1 || selected[0] !== this.vertexPolygonId) {\n\t\t\tthis.vertexPolygonId = null;\n\t\t\tthis.selectedVertices.clear();\n\t\t}\n\t\t// 편집 대상이 더 이상 유일 선택이 아니면 편집모드 해제.\n\t\tif (this.editingId && (selected.length !== 1 || selected[0] !== this.editingId)) {\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tif (this.activeDrag) return;\n\t\tthis.drawSelectionBorders();\n\t\tthis.drawTransformer();\n\t}\n\n\t/** 폴리곤 정점 편집모드 진입/해제(null이면 해제). */\n\tsetEditing(id: string | null) {\n\t\tif (this.editingId === id) return;\n\t\tthis.editingId = id;\n\t\tthis.selectedVertices.clear();\n\t\tif (!this.activeDrag) this.drawTransformer();\n\t}\n\n\t/** SELECT 모드 + 비-readOnly일 때만 핸들 표시(호스트가 설정). */\n\tsetTransformEnabled(enabled: boolean) {\n\t\tthis.transformEnabled = enabled;\n\t\tthis.syncShapeCursors();\n\t\tthis.drawTransformer();\n\t}\n\n\t// 팬 모드: 핸들 레이어 자식의 히트테스트만 끈다(핸들은 계속 보이되 클릭은 통과).\n\t// interactiveChildren는 컨테이너 속성이라 이후 drawTransformer 재생성에도 유지된다.\n\tsetPanMode(active: boolean) {\n\t\tthis.handleLayer.interactiveChildren = !active;\n\t}\n\n\tprivate strokeW(shape?: EditorShape) {\n\t\tconst strokeWidth = shape\n\t\t\t? resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize }).strokeWidth\n\t\t\t: STROKE;\n\t\treturn strokeWidth / this.world.scale.x;\n\t}\n\n\tprivate pointRadius(shape?: EditorShape) {\n\t\treturn pointRadiusFor(shape, this.strokeSize, this.world.scale.x);\n\t}\n\n\tprivate dashForShape(shape: EditorShape): [number, number] | null {\n\t\tconst dash = resolveShapeRenderStyle(shape, {\n\t\t\tstrokeWidth: this.strokeSize,\n\t\t}).dash;\n\t\tif (!dash?.length) return null;\n\t\tconst scale = this.world.scale.x || 1;\n\t\treturn [dash[0] / scale, (dash[1] ?? dash[0]) / scale];\n\t}\n\n\tprivate drawShapes() {\n\t\tthis.shapeLayer.removeChildren();\n\t\tfor (const n of this.nodes.values()) n.destroy();\n\t\tthis.nodes.clear();\n\t\tfor (const shape of sortShapesForRender(this.shapes).filter(isShapeVisible)) {\n\t\t\tconst g = new Graphics();\n\t\t\tthis.paintShape(g, shape);\n\t\t\tg.eventMode = isShapeSelectable(shape) ? \"static\" : \"none\";\n\t\t\tg.cursor = undefined;\n\t\t\tif (isShapeSelectable(shape) && isShapeDraggable(shape)) {\n\t\t\t\tg.on(\"pointerover\", () => {\n\t\t\t\t\tif (!this.activeDrag && this.transformEnabled) this.emitCursorHint(\"grab\");\n\t\t\t\t});\n\t\t\t\tg.on(\"pointerout\", () => {\n\t\t\t\t\tif (!this.activeDrag) this.emitCursorHint(null);\n\t\t\t\t});\n\t\t\t}\n\t\t\tg.on(\"pointerdown\", (e) => {\n\t\t\t\te.stopPropagation();\n\t\t\t\tthis.cb.onPointerDown(this.toImage(e), shape.id, this.ev(e));\n\t\t\t});\n\t\t\tthis.shapeLayer.addChild(g);\n\t\t\tthis.nodes.set(shape.id, g);\n\t\t}\n\t}\n\n\t/** 도형 하나를 Graphics에 그린다(생성/라이브갱신 공용). */\n\tprivate paintShape(g: Graphics, shape: EditorShape) {\n\t\tg.clear();\n\t\tconst style = resolveShapeRenderStyle(shape, {\n\t\t\tstrokeWidth: this.strokeSize,\n\t\t});\n\t\tconst color = hexToNum(style.color);\n\t\tconst width = this.strokeW(shape);\n\t\tconst alpha = style.opacity;\n\t\tconst dash = this.dashForShape(shape);\n\t\tif (shape.type === SHAPE_TYPE.POINT) {\n\t\t\t// 핀 아이콘(하단중앙 앵커, 뷰포트 반비례 스케일로 화면 크기 고정).\n\t\t\tg.svg(pinSvg(style.color));\n\t\t\tg.position.set(shape.points[0].x, shape.points[0].y);\n\t\t\tg.pivot.set(PIN_WIDTH / 2, PIN_HEIGHT);\n\t\t\tconst inv = 1 / (this.world.scale.x || 1);\n\t\t\tg.scale.set(inv, inv);\n\t\t\tg.alpha = alpha;\n\t\t\treturn;\n\t\t}\n\t\tif (style.fillVisible && shape.type !== SHAPE_TYPE.LINE) {\n\t\t\tthis.path(g, shape);\n\t\t\tg.fill({ color, alpha: style.fillAlpha * alpha });\n\t\t} else if (shape.type !== SHAPE_TYPE.LINE) {\n\t\t\t// 외곽선만 그리는 닫힌 도형(예: OBB 박스)도 내부를 클릭해 선택할 수 있도록\n\t\t\t// 투명 fill로 hit 영역을 확보한다(렌더에는 영향 없음). LINE(열린 패스)은 제외.\n\t\t\tthis.path(g, shape);\n\t\t\tg.fill({ color, alpha: 0 });\n\t\t}\n\t\tif (dash) {\n\t\t\t// 점선의 빈 구간 보조색(alternateColor) — 보조색 실선 위에 주색 점선(프리뷰와 동일 계약).\n\t\t\tif (shape.style?.alternateColor) {\n\t\t\t\tthis.path(g, shape);\n\t\t\t\tg.stroke({ width, color: hexToNum(shape.style.alternateColor), alpha });\n\t\t\t}\n\t\t\tthis.dashedStrokeShape(g, shape, width, color, alpha, dash);\n\t\t\treturn;\n\t\t}\n\t\tthis.path(g, shape);\n\t\tg.stroke({ width, color, alpha });\n\t}\n\n\t/** 드래그 중 도형 노드를 새 점으로 즉시 다시 그림(리렌더 없음). */\n\tliveUpdateShape(id: string, points: Point[]) {\n\t\tconst g = this.nodes.get(id);\n\t\tconst shape = this.shapes.find((s) => s.id === id);\n\t\tif (g && shape) this.paintShape(g, { ...shape, points });\n\t}\n\n\t/** bbox가 박스와 교차하는 도형 id들(마퀴 선택). */\n\tshapesIntersecting(box: { minX: number; minY: number; maxX: number; maxY: number }): string[] {\n\t\treturn intersectingShapeIds(this.shapes, box);\n\t}\n\n\t/** 점을 포함하는 도형들(위→아래 순서, Alt 순환용). */\n\tshapesAt(p: Point): string[] {\n\t\treturn this.shapes\n\t\t\t.filter((s) => {\n\t\t\t\tconst b = getBBox(s.points);\n\t\t\t\treturn p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY;\n\t\t\t})\n\t\t\t.map((s) => s.id);\n\t}\n\n\t// ── 그리기 미리보기 ──\n\tprivate previewG = new Graphics();\n\tprivate marqueeG = new Graphics();\n\tprivate previewMaskSprite: Sprite | null = null;\n\tprivate previewMaskTexture: Texture | null = null;\n\tprivate previewReady = false;\n\t/** 그리는 중 초안(폴리곤/박스) 마지막 파라미터 — 줌 시 화면고정 두께로 재도색용. */\n\tprivate lastPreview:\n\t\t| {\n\t\t\t\tkind: \"poly\";\n\t\t\t\tpoints: Point[];\n\t\t\t\tcursor: Point | null;\n\t\t\t\tstyle: ShapeStyle;\n\t\t\t\tclosed: boolean;\n\t\t\t\tselectedPointIndices: number[];\n\t\t\t\tshowVertices: boolean;\n\t\t }\n\t\t| { kind: \"box\"; boxKind: \"rect\" | \"ellipse\"; a: Point; b: Point; style: ShapeStyle }\n\t\t| null = null;\n\t/** 줌 후 초안을 현재 스케일 기준 두께/정점 크기로 다시 그린다. */\n\tprivate repaintPreview() {\n\t\tconst p = this.lastPreview;\n\t\tif (!p) return;\n\t\tif (p.kind === \"poly\") {\n\t\t\tthis.previewPoly(\n\t\t\t\tp.points,\n\t\t\t\tp.cursor,\n\t\t\t\tp.style,\n\t\t\t\tp.closed,\n\t\t\t\tp.selectedPointIndices,\n\t\t\t\tp.showVertices,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.previewBox(p.boxKind, p.a, p.b, p.style);\n\t\t}\n\t}\n\tprivate ensurePreview() {\n\t\tif (this.previewReady) return;\n\t\tthis.previewLayer.addChild(this.previewG, this.marqueeG);\n\t\tthis.previewReady = true;\n\t}\n\tclearPreview() {\n\t\tthis.lastPreview = null;\n\t\tthis.previewG.clear();\n\t\tif (this.previewMaskSprite) this.previewMaskSprite.visible = false;\n\t}\n\tclearMarquee() {\n\t\tthis.marqueeG.clear();\n\t}\n\tpreviewBox(kind: \"rect\" | \"ellipse\", a: Point, b: Point, style: ShapeStyle) {\n\t\tthis.lastPreview = { kind: \"box\", boxKind: kind, a, b, style };\n\t\tthis.ensurePreview();\n\t\tthis.previewG.clear();\n\t\tconst shape: EditorShape = {\n\t\t\tid: \"__preview__\",\n\t\t\ttype: kind === \"ellipse\" ? SHAPE_TYPE.ELLIPSE : SHAPE_TYPE.RECTANGLE,\n\t\t\tpoints: [a, b],\n\t\t\tstyle,\n\t\t};\n\t\tconst width = this.strokeW(shape);\n\t\tif (style.alternateColor) {\n\t\t\tthis.path(this.previewG, shape);\n\t\t\tthis.previewG.stroke({ width, color: hexToNum(style.alternateColor) });\n\t\t}\n\t\tconst dash = this.dashForShape(shape);\n\t\tif (dash) {\n\t\t\tthis.dashedStrokeShape(\n\t\t\t\tthis.previewG,\n\t\t\t\tshape,\n\t\t\t\twidth,\n\t\t\t\thexToNum(style.color ?? \"#00e5ff\"),\n\t\t\t\tstyle.opacity ?? 1,\n\t\t\t\tdash,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis.path(this.previewG, shape);\n\t\tthis.previewG.stroke({\n\t\t\twidth,\n\t\t\tcolor: hexToNum(style.color ?? \"#00e5ff\"),\n\t\t\talpha: style.opacity ?? 1,\n\t\t});\n\t}\n\tpreviewPoly(\n\t\tpoints: Point[],\n\t\tcursor: Point | null,\n\t\tstyle: ShapeStyle,\n\t\tclosed: boolean,\n\t\tselectedPointIndices: number[] = [],\n\t\tshowVertices = true,\n\t) {\n\t\tthis.lastPreview = {\n\t\t\tkind: \"poly\",\n\t\t\tpoints,\n\t\t\tcursor,\n\t\t\tstyle,\n\t\t\tclosed,\n\t\t\tselectedPointIndices,\n\t\t\tshowVertices,\n\t\t};\n\t\tthis.ensurePreview();\n\t\tthis.previewG.clear();\n\t\tif (!points.length) return;\n\t\tconst previewPoints = cursor ? [...points, cursor] : points;\n\t\tconst shape: EditorShape = {\n\t\t\tid: \"__preview__\",\n\t\t\ttype: closed ? SHAPE_TYPE.POLYGON : SHAPE_TYPE.LINE,\n\t\t\tpoints: previewPoints,\n\t\t\tstyle,\n\t\t};\n\t\tconst width = this.strokeW(shape);\n\t\tif (style.alternateColor) {\n\t\t\tthis.path(this.previewG, shape);\n\t\t\tthis.previewG.stroke({ width, color: hexToNum(style.alternateColor) });\n\t\t}\n\t\tconst dash = this.dashForShape(shape);\n\t\tif (dash) {\n\t\t\tthis.dashedStrokeShape(\n\t\t\t\tthis.previewG,\n\t\t\t\tshape,\n\t\t\t\twidth,\n\t\t\t\thexToNum(style.color ?? \"#00e5ff\"),\n\t\t\t\tstyle.opacity ?? 1,\n\t\t\t\tdash,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.path(this.previewG, shape);\n\t\t\tthis.previewG.stroke({\n\t\t\t\twidth,\n\t\t\t\tcolor: hexToNum(style.color ?? \"#00e5ff\"),\n\t\t\t\talpha: style.opacity ?? 1,\n\t\t\t});\n\t\t}\n\t\t// PATH(자유선)처럼 점을 안 찍는 도구는 정점 점을 숨기고 선만 보여준다.\n\t\tif (!showVertices) return;\n\t\tconst selected = new Set(selectedPointIndices);\n\t\tconst radius = 5 / this.world.scale.x;\n\t\tconst selectedRadius = 6 / this.world.scale.x;\n\t\tfor (let i = 0; i < points.length; i++) {\n\t\t\tconst point = points[i];\n\t\t\tconst isSelected = selected.has(i);\n\t\t\tthis.previewG\n\t\t\t\t.circle(point.x, point.y, isSelected ? selectedRadius : radius)\n\t\t\t\t.fill({ color: isSelected ? 0x1e88e5 : 0xffffff })\n\t\t\t\t.stroke({\n\t\t\t\t\twidth: 1.5 / this.world.scale.x,\n\t\t\t\t\tcolor: isSelected ? 0xffffff : 0x1e88e5,\n\t\t\t\t});\n\t\t}\n\t}\n\tpreviewScalarMask(raster: ScalarMaskRaster, color: string) {\n\t\t// 래스터 스프라이트는 스케일 재도색이 필요 없다 — 초안 재도색 대상에서 제외.\n\t\tthis.lastPreview = null;\n\t\tthis.ensurePreview();\n\t\tthis.previewG.clear();\n\t\tconst tint = color.length === 7 ? `${color}99` : color;\n\t\tconst previewCanvas = buildScalarMaskPreviewCanvas(raster, tint);\n\t\tif (this.previewMaskTexture) this.previewMaskTexture.destroy(true);\n\t\tthis.previewMaskTexture = Texture.from(previewCanvas);\n\t\tif (!this.previewMaskSprite) {\n\t\t\tthis.previewMaskSprite = new Sprite(this.previewMaskTexture);\n\t\t\tthis.previewLayer.addChildAt(this.previewMaskSprite, 0);\n\t\t} else {\n\t\t\tthis.previewMaskSprite.texture = this.previewMaskTexture;\n\t\t\tthis.previewMaskSprite.visible = true;\n\t\t}\n\t\tthis.previewMaskSprite.x = raster.ox;\n\t\tthis.previewMaskSprite.y = raster.oy;\n\t\tthis.previewMaskSprite.width = previewCanvas.width / raster.scale;\n\t\tthis.previewMaskSprite.height = previewCanvas.height / raster.scale;\n\t}\n\tpreviewMarquee(a: Point, b: Point) {\n\t\tthis.ensurePreview();\n\t\tthis.marqueeG.clear();\n\t\tconst x = Math.min(a.x, b.x);\n\t\tconst y = Math.min(a.y, b.y);\n\t\tconst w = Math.abs(b.x - a.x);\n\t\tconst h = Math.abs(b.y - a.y);\n\t\tconst color = hexToNum(SELECTION_AREA_COLOR);\n\t\tthis.marqueeG\n\t\t\t.rect(x, y, w, h)\n\t\t\t.fill({ color, alpha: SELECTION_AREA_FILL_ALPHA })\n\t\t\t.stroke({ width: 1 / this.world.scale.x, color });\n\t}\n\n\t/** 줌 시 화면고정 선두께 유지 위해 다시 그림(도형 수 많으면 비용 — 후속 최적화). */\n\t/**\n\t * 뷰포트 스케일 변경(줌) 시 스트로크 폭을 화면px 기준으로 다시 맞춘다.\n\t * 노드를 destroy/재생성하지 않고 기존 Graphics를 재도색(paintShape가 clear로 시작)해\n\t * 도형이 많아도 줌이 무겁지 않게 한다. 노드가 아직 없으면 최초 1회만 전체 생성.\n\t */\n\tprivate restrokeShapes() {\n\t\tif (!this.nodes.size) {\n\t\t\tif (this.shapes.length) this.drawShapes();\n\t\t} else {\n\t\t\tconst byId = new Map(this.shapes.map((s) => [s.id, s]));\n\t\t\tfor (const [id, g] of this.nodes) {\n\t\t\t\tconst shape = byId.get(id);\n\t\t\t\tif (shape) this.paintShape(g, shape);\n\t\t\t}\n\t\t}\n\t\tthis.drawSelectionBorders();\n\t\tthis.redrawRegionOutline();\n\t\tthis.repaintPreview();\n\t}\n\n\t/** 영역 윤곽 점선 — 두께·점선을 화면 px로 유지(줌 시 재도색). */\n\tprivate redrawRegionOutline() {\n\t\tconst g = this.regionOutlineG;\n\t\tif (!g) return;\n\t\tg.clear();\n\t\tconst styles = this.region?.outlineStyles;\n\t\tif (!this.region || !styles) return;\n\t\tconst scale = this.world.scale.x || 1;\n\t\tconst drawSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n\t\t\tconst width = style.width / scale;\n\t\t\tconst dash: [number, number] = [style.dash[0] / scale, style.dash[1] / scale];\n\t\t\tfor (const [a, b] of segments) {\n\t\t\t\tif (style.underlayColor) {\n\t\t\t\t\tg.poly([a.x, a.y, b.x, b.y], false).stroke({\n\t\t\t\t\t\twidth,\n\t\t\t\t\t\tcolor: hexToNum(style.underlayColor),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthis.strokeDashedPolyline(\n\t\t\t\t\tg,\n\t\t\t\t\t[a, b],\n\t\t\t\t\tfalse,\n\t\t\t\t\twidth,\n\t\t\t\t\thexToNum(style.color),\n\t\t\t\t\tstyle.opacity,\n\t\t\t\t\tdash,\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t\tdrawSegments(this.region.visibleOutline, styles.visible);\n\t\tdrawSegments(this.region.occludedOutline, styles.occluded);\n\t}\n\n\tprivate path(g: Graphics, shape: EditorShape) {\n\t\tconst { type, points } = shape;\n\t\tif (type === SHAPE_TYPE.POINT) {\n\t\t\tg.circle(points[0].x, points[0].y, this.pointRadius(shape));\n\t\t\treturn;\n\t\t}\n\t\tif (type === SHAPE_TYPE.RECTANGLE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tg.rect(b.minX, b.minY, b.maxX - b.minX, b.maxY - b.minY);\n\t\t\treturn;\n\t\t}\n\t\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tg.ellipse(\n\t\t\t\t(b.minX + b.maxX) / 2,\n\t\t\t\t(b.minY + b.maxY) / 2,\n\t\t\t\t(b.maxX - b.minX) / 2,\n\t\t\t\t(b.maxY - b.minY) / 2,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst flat = points.flatMap((p) => [p.x, p.y]);\n\t\tg.poly(flat, type !== SHAPE_TYPE.LINE);\n\t}\n\n\tprivate dashedStrokeShape(\n\t\tg: Graphics,\n\t\tshape: EditorShape,\n\t\twidth: number,\n\t\tcolor: number,\n\t\talpha: number,\n\t\tdashPattern: [number, number],\n\t) {\n\t\tconst { type, points } = shape;\n\t\tif (type === SHAPE_TYPE.RECTANGLE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tthis.strokeDashedPolyline(\n\t\t\t\tg,\n\t\t\t\t[\n\t\t\t\t\t{ x: b.minX, y: b.minY },\n\t\t\t\t\t{ x: b.maxX, y: b.minY },\n\t\t\t\t\t{ x: b.maxX, y: b.maxY },\n\t\t\t\t\t{ x: b.minX, y: b.maxY },\n\t\t\t\t],\n\t\t\t\ttrue,\n\t\t\t\twidth,\n\t\t\t\tcolor,\n\t\t\t\talpha,\n\t\t\t\tdashPattern,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (type === SHAPE_TYPE.ELLIPSE) {\n\t\t\tconst b = getBBox(points);\n\t\t\tconst cx = (b.minX + b.maxX) / 2;\n\t\t\tconst cy = (b.minY + b.maxY) / 2;\n\t\t\tconst rx = (b.maxX - b.minX) / 2;\n\t\t\tconst ry = (b.maxY - b.minY) / 2;\n\t\t\tconst samples = 96;\n\t\t\tconst ellipsePoints = Array.from({ length: samples }, (_, i) => {\n\t\t\t\tconst a = (i / samples) * Math.PI * 2;\n\t\t\t\treturn { x: cx + Math.cos(a) * rx, y: cy + Math.sin(a) * ry };\n\t\t\t});\n\t\t\tthis.strokeDashedPolyline(g, ellipsePoints, true, width, color, alpha, dashPattern);\n\t\t\treturn;\n\t\t}\n\t\tthis.strokeDashedPolyline(\n\t\t\tg,\n\t\t\tpoints,\n\t\t\ttype !== SHAPE_TYPE.LINE,\n\t\t\twidth,\n\t\t\tcolor,\n\t\t\talpha,\n\t\t\tdashPattern,\n\t\t);\n\t}\n\n\tprivate strokeDashedPolyline(\n\t\tg: Graphics,\n\t\tpoints: Point[],\n\t\tclosed: boolean,\n\t\twidth: number,\n\t\tcolor: number,\n\t\talpha: number,\n\t\tdashPattern: [number, number],\n\t) {\n\t\tif (points.length < 2) return;\n\t\tconst [dash, gap] = dashPattern;\n\t\tlet drawing = true;\n\t\tlet phase = 0;\n\t\tconst segmentCount = closed ? points.length : points.length - 1;\n\t\tfor (let i = 0; i < segmentCount; i++) {\n\t\t\tconst a = points[i];\n\t\t\tconst b = points[(i + 1) % points.length];\n\t\t\tconst dx = b.x - a.x;\n\t\t\tconst dy = b.y - a.y;\n\t\t\tconst length = Math.hypot(dx, dy);\n\t\t\tif (!length) continue;\n\t\t\tlet consumed = 0;\n\t\t\twhile (consumed < length) {\n\t\t\t\tconst patternLength = drawing ? dash : gap;\n\t\t\t\tconst step = Math.min(patternLength - phase, length - consumed);\n\t\t\t\tif (drawing) {\n\t\t\t\t\tconst t0 = consumed / length;\n\t\t\t\t\tconst t1 = (consumed + step) / length;\n\t\t\t\t\tg.moveTo(a.x + dx * t0, a.y + dy * t0)\n\t\t\t\t\t\t.lineTo(a.x + dx * t1, a.y + dy * t1)\n\t\t\t\t\t\t.stroke({ width, color, alpha });\n\t\t\t\t}\n\t\t\t\tconsumed += step;\n\t\t\t\tphase += step;\n\t\t\t\tif (phase >= patternLength - 0.0001) {\n\t\t\t\t\tphase = 0;\n\t\t\t\t\tdrawing = !drawing;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate drawSelectionBorders() {\n\t\tthis.selLayer.position.set(0, 0);\n\t\t// Set 멤버십 + 노드 재사용(개수 변화 때만 재생성). 전체선택 후 줌/판마다\n\t\t// N개 Graphics를 destroy/생성하고 includes로 O(N²) 검사하던 렉 방지.\n\t\tconst selectedSet = new Set(this.selected);\n\t\tconst targets = this.selected.length\n\t\t\t? this.shapes.filter((s) => selectedSet.has(s.id) && isShapeSelectable(s))\n\t\t\t: [];\n\t\tif (this.selectionBorderGfx.length !== targets.length) {\n\t\t\tfor (const g of this.selectionBorderGfx) g.destroy();\n\t\t\tthis.selectionBorderGfx = targets.map(() => {\n\t\t\t\tconst g = new Graphics();\n\t\t\t\tthis.selLayer.addChild(g);\n\t\t\t\treturn g;\n\t\t\t});\n\t\t}\n\t\tconst w = 1.5 / this.world.scale.x;\n\t\ttargets.forEach((shape, i) => {\n\t\t\tconst g = this.selectionBorderGfx[i];\n\t\t\tg.clear();\n\t\t\tg.poly(\n\t\t\t\tthis.selectionOutlinePoints(shape, shape.points).flatMap((point) => [point.x, point.y]),\n\t\t\t\ttrue,\n\t\t\t).stroke({ width: w, color: SELECTION_BORDER });\n\t\t});\n\t}\n\n\t/** 드래그 중 선택 테두리를 라이브 좌표로 동기화. */\n\tprivate updateSelectionBordersLive(getPoints: (shape: EditorShape) => Point[]) {\n\t\tconst selectedSet = new Set(this.selected);\n\t\tconst w = 1.5 / this.world.scale.x;\n\t\tlet i = 0;\n\t\tfor (const shape of this.shapes) {\n\t\t\tif (!selectedSet.has(shape.id)) continue;\n\t\t\tif (!isShapeSelectable(shape)) continue;\n\t\t\tconst g = this.selectionBorderGfx[i++];\n\t\t\tif (!g) continue;\n\t\t\tg.clear();\n\t\t\tg.poly(\n\t\t\t\tthis.selectionOutlinePoints(shape, getPoints(shape)).flatMap((point) => [point.x, point.y]),\n\t\t\t\ttrue,\n\t\t\t).stroke({ width: w, color: SELECTION_BORDER });\n\t\t}\n\t}\n\n\tprivate selectionOutlinePoints(shape: EditorShape, points: Point[]) {\n\t\treturn outlinePointsFor(shape, points, this.pointRadius(shape));\n\t}\n\n\t// ── 트랜스포머(바운딩박스 리사이즈 + 꼭짓점 편집) ──\n\n\tprivate imgToScreen(p: Point): Point {\n\t\tconst g = this.world.toGlobal({ x: p.x, y: p.y });\n\t\treturn { x: g.x, y: g.y };\n\t}\n\n\tprivate setTransformerOutline(box: BBox) {\n\t\tconst bw = box.maxX - box.minX;\n\t\tconst bh = box.maxY - box.minY;\n\t\tif (bw <= 0 && bh <= 0) return;\n\t\tthis.setTransformerOutlinePoints(\n\t\t\trectTo4([\n\t\t\t\t{ x: box.minX, y: box.minY },\n\t\t\t\t{ x: box.maxX, y: box.maxY },\n\t\t\t]),\n\t\t);\n\t}\n\n\tprivate setTransformerOutlinePoints(points: Point[]) {\n\t\tif (points.length < 2) return;\n\t\tif (!this.transformerOutline) {\n\t\t\tthis.transformerOutline = new Graphics();\n\t\t\tthis.selLayer.addChild(this.transformerOutline);\n\t\t}\n\t\tthis.transformerOutline.clear();\n\t\tthis.transformerOutline\n\t\t\t.poly(\n\t\t\t\tpoints.flatMap((point) => [point.x, point.y]),\n\t\t\t\ttrue,\n\t\t\t)\n\t\t\t.stroke({ width: 1 / this.world.scale.x, color: 0x1e88e5 });\n\t}\n\n\tprivate rotationHandleGap() {\n\t\treturn rotationHandleGapFor(this.viewport.scale);\n\t}\n\n\tprivate rotationHandleScreenPoint(points: Point[]) {\n\t\treturn this.imgToScreen(rotateHandlePos(points, this.rotationHandleGap()));\n\t}\n\n\tprivate setRotationConnector(points: Point[]) {\n\t\tconst from = this.imgToScreen(mid(points[0], points[1]));\n\t\tconst to = this.rotationHandleScreenPoint(points);\n\t\tif (!this.rotLineNode) {\n\t\t\tthis.rotLineNode = new Graphics();\n\t\t\tthis.rotLineNode.eventMode = \"none\";\n\t\t\tthis.handleLayer.addChild(this.rotLineNode);\n\t\t}\n\t\tthis.rotLineNode.clear();\n\t\tthis.rotLineNode\n\t\t\t.moveTo(from.x, from.y)\n\t\t\t.lineTo(to.x, to.y)\n\t\t\t.stroke({ width: 1, color: 0x1e88e5 });\n\t}\n\n\tprivate layoutResizeHandle(g: Graphics, sp: Point, angleRad: number) {\n\t\tg.position.set(sp.x, sp.y);\n\t\tg.rotation = angleRad;\n\t}\n\n\tprivate orientedHandleAngle(points: Point[]): number {\n\t\treturn orientedAngleFromScreenPoints(this.imgToScreen(points[0]), this.imgToScreen(points[1]));\n\t}\n\n\t/** 핸들(8개 bbox + 단일 폴리곤/라인 꼭짓점)을 화면좌표로 그림. */\n\tdrawTransformer() {\n\t\tif (this.activeDrag) return; // 드래그 중엔 repositionHandlesLive가 담당\n\t\tfor (const h of this.handleNodes) h.destroy();\n\t\tfor (const v of this.vertexNodes) v.destroy();\n\t\tfor (const m of this.midNodes) m.destroy();\n\t\tthis.rotNode?.destroy();\n\t\tthis.rotNode = null;\n\t\tthis.rotLineNode?.destroy();\n\t\tthis.rotLineNode = null;\n\t\tthis.transformerOutline?.destroy();\n\t\tthis.transformerOutline = null;\n\t\tthis.handleNodes = [];\n\t\tthis.vertexNodes = [];\n\t\tthis.midNodes = [];\n\t\tif (!this.transformEnabled) return;\n\t\tconst sel = selectEditable(this.shapes, this.selected);\n\t\tif (sel.length === 0) return;\n\t\tif (sel.length === 1 && sel[0].type === SHAPE_TYPE.POINT) return;\n\n\t\t// 폴리곤/라인이 편집모드일 때만 정점 편집 UI를 보여준다.\n\t\tconst editingPoly =\n\t\t\tsel.length === 1 &&\n\t\t\t(sel[0].type === SHAPE_TYPE.POLYGON || sel[0].type === SHAPE_TYPE.LINE) &&\n\t\t\tthis.editingId === sel[0].id\n\t\t\t\t? sel[0]\n\t\t\t\t: null;\n\n\t\tconst box = getBBox(sel.flatMap((s) => s.points));\n\t\tconst rotatedRect =\n\t\t\tsel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE ? sel[0] : null;\n\t\tconst transformerHandles = rotatedRect\n\t\t\t? orientedHandles(rotatedRect.points)\n\t\t\t: ANCHORS.map((a) => anchorPoint(a, box));\n\t\trotatedRect\n\t\t\t? this.setTransformerOutlinePoints(rotatedRect.points)\n\t\t\t: this.setTransformerOutline(box);\n\t\tif (rotatedRect) this.setRotationConnector(rotatedRect.points);\n\t\tconst handleAngleRad = rotatedRect ? this.orientedHandleAngle(rotatedRect.points) : 0;\n\t\t// 편집모드(정점 편집) 중엔 bbox 리사이즈 핸들을 숨겨 정점 편집만 보이게 한다.\n\t\tfor (const a of editingPoly ? [] : ANCHORS) {\n\t\t\tconst sp = this.imgToScreen(transformerHandles[ANCHORS.indexOf(a)]);\n\t\t\tconst g = new Graphics();\n\t\t\tg.rect(-4, -4, 8, 8).fill({ color: 0xffffff }).stroke({ width: 1, color: 0x1e88e5 });\n\t\t\tthis.layoutResizeHandle(g, sp, handleAngleRad);\n\t\t\tg.eventMode = \"static\";\n\t\t\tconst cursor = resizeCursorForAnchor(a, handleAngleRad);\n\t\t\tthis.bindCursor(g, cursor);\n\t\t\tg.on(\"pointerdown\", (e) => {\n\t\t\t\te.stopPropagation();\n\t\t\t\tthis.emitCursorHint(cursor);\n\t\t\t\tthis.emitInteractionMode(\"resizing\");\n\t\t\t\tconst cur = selectEditable(this.shapes, this.selected);\n\t\t\t\tthis.activeDrag = {\n\t\t\t\t\tkind: \"resize\",\n\t\t\t\t\tanchor: a,\n\t\t\t\t\tbox: getBBox(cur.flatMap((s) => s.points)),\n\t\t\t\t\tshapes: cur.map((s) => ({ id: s.id, points: s.points })),\n\t\t\t\t};\n\t\t\t\tthis.lastDragImg = null;\n\t\t\t});\n\t\t\tthis.handleLayer.addChild(g);\n\t\t\tthis.handleNodes.push(g);\n\t\t}\n\n\t\tif (editingPoly) {\n\t\t\tconst shape = editingPoly;\n\t\t\tconst pts = shape.points;\n\t\t\tconst isPoly = shape.type === SHAPE_TYPE.POLYGON;\n\t\t\t// 변 중점 추가 핸들(클릭=꼭짓점 삽입).\n\t\t\tconst edges = isPoly ? pts.length : pts.length - 1;\n\t\t\tfor (let i = 0; i < edges; i++) {\n\t\t\t\tconst a = pts[i];\n\t\t\t\tconst b = pts[(i + 1) % pts.length];\n\t\t\t\tconst m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n\t\t\t\tconst sp = this.imgToScreen(m);\n\t\t\t\tconst g = new Graphics();\n\t\t\t\tg.circle(0, 0, 4)\n\t\t\t\t\t.fill({ color: 0xffffff, alpha: 0.6 })\n\t\t\t\t\t.stroke({ width: 1, color: 0x1e88e5 });\n\t\t\t\tg.position.set(sp.x, sp.y);\n\t\t\t\tg.eventMode = \"static\";\n\t\t\t\tthis.bindCursor(g, \"copy\");\n\t\t\t\tg.on(\"pointerdown\", (e) => {\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\tconst next = [...pts.slice(0, i + 1), m, ...pts.slice(i + 1)];\n\t\t\t\t\tthis.cb.onTransformCommit?.([{ id: shape.id, points: next }]);\n\t\t\t\t});\n\t\t\t\tthis.handleLayer.addChild(g);\n\t\t\t\tthis.midNodes.push(g);\n\t\t\t}\n\t\t\t// 편집 대상 폴리곤이 바뀌면 정점 다중선택 초기화.\n\t\t\tif (this.vertexPolygonId !== shape.id) {\n\t\t\t\tthis.vertexPolygonId = shape.id;\n\t\t\t\tthis.selectedVertices.clear();\n\t\t\t}\n\t\t\t// 꼭짓점 핸들(드래그=이동, Shift/Ctrl/Cmd=다중선택).\n\t\t\tpts.forEach((pt, i) => {\n\t\t\t\tconst sp = this.imgToScreen(pt);\n\t\t\t\tconst isSel = this.selectedVertices.has(i);\n\t\t\t\tconst g = new Graphics();\n\t\t\t\tg.circle(0, 0, 5)\n\t\t\t\t\t.fill({ color: isSel ? 0x1e88e5 : 0xffffff })\n\t\t\t\t\t.stroke({ width: 1.5, color: isSel ? 0xffffff : 0x1e88e5 });\n\t\t\t\tg.position.set(sp.x, sp.y);\n\t\t\t\tg.eventMode = \"static\";\n\t\t\t\tthis.bindCursor(g, \"pointer\");\n\t\t\t\tg.on(\"pointerdown\", (e) => {\n\t\t\t\t\te.stopPropagation();\n\t\t\t\t\tif (e.shiftKey || e.ctrlKey || e.metaKey) {\n\t\t\t\t\t\tif (this.selectedVertices.has(i)) this.selectedVertices.delete(i);\n\t\t\t\t\t\telse this.selectedVertices.add(i);\n\t\t\t\t\t\tthis.drawTransformer();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst indices =\n\t\t\t\t\t\tthis.selectedVertices.has(i) && this.selectedVertices.size > 1\n\t\t\t\t\t\t\t? [...this.selectedVertices]\n\t\t\t\t\t\t\t: [i];\n\t\t\t\t\tif (indices.length === 1) {\n\t\t\t\t\t\tthis.selectedVertices.clear();\n\t\t\t\t\t\tthis.selectedVertices.add(i);\n\t\t\t\t\t}\n\t\t\t\t\tthis.activeDrag = {\n\t\t\t\t\t\tkind: \"vertex\",\n\t\t\t\t\t\tid: shape.id,\n\t\t\t\t\t\tindices,\n\t\t\t\t\t\tbase: pts,\n\t\t\t\t\t\tstart: this.toImage(e),\n\t\t\t\t\t};\n\t\t\t\t\tthis.lastDragImg = null;\n\t\t\t\t\tthis.emitCursorHint(\"grabbing\");\n\t\t\t\t\tthis.emitInteractionMode(\"vertexDragging\");\n\t\t\t\t});\n\t\t\t\tthis.handleLayer.addChild(g);\n\t\t\t\tthis.vertexNodes.push(g);\n\t\t\t});\n\t\t}\n\n\t\t// 회전 핸들(회전사각형 단일 선택). bbox 위 중앙 바깥.\n\t\tif (sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n\t\t\tconst shape = sel[0];\n\t\t\tconst center = centerOf(shape.points);\n\t\t\tconst sp = this.rotationHandleScreenPoint(shape.points);\n\t\t\tconst g = new Graphics();\n\t\t\tg.circle(0, 0, 6).fill({ color: 0xffffff }).stroke({ width: 1.5, color: 0x1e88e5 });\n\t\t\tg.position.set(sp.x, sp.y);\n\t\t\tg.eventMode = \"static\";\n\t\t\tthis.bindCursor(g, \"grab\");\n\t\t\tg.on(\"pointerdown\", (e) => {\n\t\t\t\te.stopPropagation();\n\t\t\t\tconst ip = this.toImage(e);\n\t\t\t\tthis.activeDrag = {\n\t\t\t\t\tkind: \"rotate\",\n\t\t\t\t\tid: shape.id,\n\t\t\t\t\tcenter,\n\t\t\t\t\tstartAngle: Math.atan2(ip.y - center.y, ip.x - center.x),\n\t\t\t\t\tpoints: shape.points,\n\t\t\t\t\tshiftKey: e.shiftKey,\n\t\t\t\t};\n\t\t\t\tthis.lastDragImg = null;\n\t\t\t\tthis.emitCursorHint(\"grabbing\");\n\t\t\t\tthis.emitInteractionMode(\"rotating\");\n\t\t\t});\n\t\t\tthis.handleLayer.addChild(g);\n\t\t\tthis.rotNode = g;\n\t\t}\n\t}\n\n\t/** 도형 본체 드래그 이동 시작(호스트가 도형 위 포인터다운 시 호출). */\n\tbeginMove(start: Point, ids: string[]) {\n\t\tconst drag = makeMoveDrag(this.shapes, ids, start);\n\t\tif (!drag) return;\n\t\tif (this.transformEnabled && !this.handleNodes.length) this.drawTransformer();\n\t\tthis.activeDrag = drag;\n\t\tthis.lastDragImg = null;\n\t\tthis.emitCursorHint(\"grabbing\");\n\t\tthis.emitInteractionMode(\"moving\");\n\t\tconst selectedShape =\n\t\t\tdrag.shapes.length === 1 ? this.shapes.find((s) => s.id === drag.shapes[0].id) : null;\n\t\tif (selectedShape?.type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n\t\t\tthis.setTransformerOutlinePoints(drag.shapes[0].points);\n\t\t} else {\n\t\t\tthis.setTransformerOutline(drag.box);\n\t\t}\n\t\tthis.updateSelectionBordersLive((shape) => shape.points);\n\t}\n\n\tprivate repositionHandlesForBox(box: BBox) {\n\t\tANCHORS.forEach((a, i) => {\n\t\t\tconst sp = this.imgToScreen(anchorPoint(a, box));\n\t\t\tconst node = this.handleNodes[i];\n\t\t\tif (node) this.layoutResizeHandle(node, sp, 0);\n\t\t});\n\t\tthis.setTransformerOutline(box);\n\t}\n\n\tprivate repositionOrientedHandles(points: Point[]) {\n\t\tconst angleRad = this.orientedHandleAngle(points);\n\t\torientedHandles(points).forEach((point, i) => {\n\t\t\tconst sp = this.imgToScreen(point);\n\t\t\tconst node = this.handleNodes[i];\n\t\t\tif (node) this.layoutResizeHandle(node, sp, angleRad);\n\t\t});\n\t\tthis.setTransformerOutlinePoints(points);\n\t\tif (this.rotNode) {\n\t\t\tconst sp = this.rotationHandleScreenPoint(points);\n\t\t\tthis.rotNode.position.set(sp.x, sp.y);\n\t\t}\n\t\tif (this.rotLineNode) this.setRotationConnector(points);\n\t}\n\n\t/** 폴리곤/라인 꼭짓점·변 중점 핸들을 이미지 좌표 기준으로 재배치. */\n\tprivate repositionPolygonHandles(pts: Point[], isPolygon: boolean) {\n\t\tif (!this.vertexNodes.length) return;\n\t\tpts.forEach((pt, i) => {\n\t\t\tconst sp = this.imgToScreen(pt);\n\t\t\tthis.vertexNodes[i]?.position.set(sp.x, sp.y);\n\t\t});\n\t\tconst edges = isPolygon ? pts.length : pts.length - 1;\n\t\tfor (let i = 0; i < edges; i++) {\n\t\t\tconst a = pts[i];\n\t\t\tconst b = pts[(i + 1) % pts.length];\n\t\t\tconst sp = this.imgToScreen({\n\t\t\t\tx: (a.x + b.x) / 2,\n\t\t\t\ty: (a.y + b.y) / 2,\n\t\t\t});\n\t\t\tthis.midNodes[i]?.position.set(sp.x, sp.y);\n\t\t}\n\t}\n\n\tprivate resetMoveOffsets() {\n\t\tfor (const [id, g] of this.nodes) {\n\t\t\t// POINT 핀은 position이 절대 앵커(paintShape가 설정) — 0으로 리셋하면\n\t\t\t// 원점으로 튄다. 커밋 시 paintShape가 새 앵커로 다시 세팅하므로 건너뛴다.\n\t\t\tif (this.shapes.find((s) => s.id === id)?.type === SHAPE_TYPE.POINT) continue;\n\t\t\tg.position.set(0, 0);\n\t\t}\n\t\tthis.selLayer.position.set(0, 0);\n\t}\n\n\tprivate commitTransformUpdates(updates: { id: string; points: Point[] }[]) {\n\t\tif (!updates.length) return;\n\t\tfor (const update of updates) {\n\t\t\tconst shape = this.shapes.find((s) => s.id === update.id);\n\t\t\tif (!shape) continue;\n\t\t\tshape.points = update.points;\n\t\t\tconst g = this.nodes.get(update.id);\n\t\t\tif (g) this.paintShape(g, { ...shape, points: update.points });\n\t\t}\n\t\tthis.cb.onTransformCommit?.(updates);\n\t\tthis.drawTransformer();\n\t}\n\n\t// lastDragImg 기록은 pointermove 콜러 소유 — 뷰포트 변경(줌/팬) 중 재호출해도\n\t// endTransform의 \"이동 없음 → 커밋 생략\" 판정이 유지된다.\n\tprivate dragTransform(img: Point) {\n\t\tconst d = this.activeDrag;\n\t\tif (!d) return;\n\t\tthis.applyCursor();\n\t\tconst isRotatedRect = dragTargetIsRotatedRect(this.shapes, d);\n\t\tconst { updates, box } = computeDragUpdates(d, img, isRotatedRect);\n\t\tif (d.kind === \"move\") {\n\t\t\t// 순수 이동은 지오메트리 재생성 없이 노드 transform만 이동(마우스와 1:1, 즉각).\n\t\t\t// 단 POINT 핀은 paintShape가 position을 절대 앵커(points[0])로 쓰므로,\n\t\t\t// 델타를 덮어쓰면 원점 근처로 튄다 — 절대 좌표로 이동시킨다.\n\t\t\tconst dx = img.x - d.start.x;\n\t\t\tconst dy = img.y - d.start.y;\n\t\t\tfor (const s of d.shapes) {\n\t\t\t\tconst g = this.nodes.get(s.id);\n\t\t\t\tif (!g) continue;\n\t\t\t\tconst type = this.shapes.find((x) => x.id === s.id)?.type;\n\t\t\t\tif (type === SHAPE_TYPE.POINT) g.position.set(s.points[0].x + dx, s.points[0].y + dy);\n\t\t\t\telse g.position.set(dx, dy);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const u of updates) this.liveUpdateShape(u.id, u.points);\n\t\t}\n\t\tthis.cb.onTransformPreview?.(updates);\n\t\tthis.updateSelectionBordersLive(\n\t\t\t(shape) => updates.find((item) => item.id === shape.id)?.points ?? shape.points,\n\t\t);\n\t\tif (d.kind === \"resize\" || d.kind === \"move\") {\n\t\t\tif (isRotatedRect) this.repositionOrientedHandles(updates[0].points);\n\t\t\telse if (box) this.repositionHandlesForBox(box);\n\t\t\tconst single =\n\t\t\t\td.shapes.length === 1 ? this.shapes.find((s) => s.id === d.shapes[0].id) : null;\n\t\t\tconst isPolyLike = single?.type === SHAPE_TYPE.POLYGON || single?.type === SHAPE_TYPE.LINE;\n\t\t\tconst showPolyHandles =\n\t\t\t\td.kind === \"resize\" ? isPolyLike : this.vertexNodes.length > 0 && d.shapes.length === 1;\n\t\t\tif (showPolyHandles) {\n\t\t\t\tthis.repositionPolygonHandles(updates[0].points, single?.type === SHAPE_TYPE.POLYGON);\n\t\t\t}\n\t\t} else if (d.kind === \"rotate\") {\n\t\t\tthis.repositionOrientedHandles(updates[0].points);\n\t\t\tconst shape = this.shapes.find((s) => s.id === d.id);\n\t\t\tif (shape && (shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE)) {\n\t\t\t\tthis.repositionPolygonHandles(updates[0].points, shape.type === SHAPE_TYPE.POLYGON);\n\t\t\t}\n\t\t} else {\n\t\t\tif (box) this.repositionHandlesForBox(box);\n\t\t\tconst shape = this.shapes.find((s) => s.id === d.id);\n\t\t\tthis.repositionPolygonHandles(updates[0].points, shape?.type === SHAPE_TYPE.POLYGON);\n\t\t}\n\t}\n\n\tprivate endTransform() {\n\t\tconst d = this.activeDrag;\n\t\tconst img = this.lastDragImg;\n\t\tthis.activeDrag = null;\n\t\tthis.emitInteractionMode(\"idle\");\n\t\tthis.emitCursorHint(d?.kind === \"move\" ? \"grab\" : null);\n\t\tif (!d || !img) {\n\t\t\tthis.cb.onTransformPreview?.([]);\n\t\t\tthis.drawTransformer();\n\t\t\treturn;\n\t\t}\n\t\tif (d.kind === \"move\" && img.x === d.start.x && img.y === d.start.y) {\n\t\t\tthis.cb.onTransformPreview?.([]);\n\t\t\tthis.drawTransformer();\n\t\t\treturn;\n\t\t}\n\t\tconst { updates } = computeDragUpdates(d, img, dragTargetIsRotatedRect(this.shapes, d));\n\t\tif (d.kind === \"move\") this.resetMoveOffsets();\n\t\tthis.commitTransformUpdates(updates);\n\t}\n}\n","import { type RefObject, useEffect, useRef } from \"react\";\nimport type { EditorShape, Point } from \"../_model/geometry\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\nimport { TOOL, type Tool } from \"../_model/tools\";\nimport type { ViewSettings } from \"../_model/viewSettings\";\nimport { KonvaRenderer } from \"../_renderers/KonvaRenderer\";\nimport { PixiRenderer } from \"../_renderers/PixiRenderer\";\nimport type { EditorRenderer, EditorRendererCallbacks, Viewport } from \"../_renderers/types\";\n\nexport type EditorImageStatus = \"loading\" | \"ready\" | \"error\";\n\n/**\n * 렌더러 엔진 생명주기 — backend당 1회 생성/파괴, 이미지 전환(문서 전환 vs 화질 스왑),\n * 휠 줌/팬·우클릭 메뉴 네이티브 리스너, 이미지 로딩 상태 프리로드를 소유한다.\n *\n * 이미지 변경은 엔진을 재사용해 setImage로 스왑한다(렌더러가 새 이미지 준비 후 타일을\n * 교체하므로 전환 중 이전 이미지가 유지됨). imageUrl마다 엔진을 파괴/재생성하면 캔버스가\n * DOM에서 사라졌다 붙는 사이 배경이 번쩍인다.\n */\nexport function useEngineLifecycle<TMeta>({\n\tbackend,\n\thostRef,\n\tengineRef,\n\timageUrl,\n\trenderedImageUrl,\n\tmakeCallbacks,\n\tviewRef,\n\treadOnlyRef,\n\ttoolRef,\n\trenderShapesRef,\n\tselRef,\n\tmaskCanvasRef,\n\tregionOverlayRef,\n\tdimmedRef,\n\tsyncMinimap,\n\tsetImage,\n\tsetImageVisible,\n\tsetReady,\n\tsetImageStatus,\n\tonContextMenuRequest,\n}: {\n\tbackend: \"konva\" | \"pixi\";\n\thostRef: RefObject<HTMLDivElement | null>;\n\tengineRef: RefObject<EditorRenderer | null>;\n\t/** 문서(시드) 기준 이미지 URL — 문서 전환 vs 화질 스왑 구분용. */\n\timageUrl: string;\n\t/** 실제 렌더 URL(화질 스왑 반영). */\n\trenderedImageUrl: string;\n\t/** 상호작용 컨트롤러(콜백) 팩토리 — 엔진 생성 직전에 1회 호출. */\n\tmakeCallbacks: () => EditorRendererCallbacks;\n\tviewRef: RefObject<ViewSettings>;\n\treadOnlyRef: RefObject<boolean>;\n\ttoolRef: RefObject<Tool>;\n\t/** 렌더 도형(문서 + 오버라이드 + 장식) — 이미지 전환 시 엔진 재시드용. */\n\trenderShapesRef: RefObject<EditorShape<TMeta>[]>;\n\tselRef: RefObject<string[]>;\n\tmaskCanvasRef: RefObject<HTMLCanvasElement | null>;\n\tregionOverlayRef: RefObject<RegionOverlayData | null>;\n\tdimmedRef: RefObject<boolean>;\n\tsyncMinimap: () => void;\n\tsetImage: (size: { w: number; h: number } | null) => void;\n\tsetImageVisible: (visible: boolean) => void;\n\tsetReady: (ready: boolean) => void;\n\tsetImageStatus: (status: EditorImageStatus) => void;\n\tonContextMenuRequest: (menu: { x: number; y: number; img: Point }) => void;\n}) {\n\t// 실제 렌더 URL(화질 스왑). imageUrl은 시드/좌표계 identity, displayImageUrl은 텍스처만.\n\tconst displayUrlRef = useRef(renderedImageUrl);\n\tdisplayUrlRef.current = renderedImageUrl;\n\tconst docImageUrlRef = useRef(imageUrl);\n\tdocImageUrlRef.current = imageUrl;\n\tconst loadedUrlRef = useRef<string | null>(null);\n\t// 현재 엔진에 반영된 문서(시드) 기준 imageUrl — 문서 전환 vs 화질 스왑 구분용.\n\tconst lastDocUrlRef = useRef<string | null>(null);\n\tconst engineInitedRef = useRef(false);\n\tconst previousEngineStateRef = useRef<{ imageUrl: string; viewport: Viewport } | null>(null);\n\tconst makeCallbacksRef = useRef(makeCallbacks);\n\tmakeCallbacksRef.current = makeCallbacks;\n\tconst onContextMenuRequestRef = useRef(onContextMenuRequest);\n\tonContextMenuRequestRef.current = onContextMenuRequest;\n\n\t// 엔진 초기화 + 상호작용 상태머신 — **backend당 1회 생성**.\n\tuseEffect(() => {\n\t\tconst host = hostRef.current;\n\t\tif (!host) return;\n\t\tlet cancelled = false;\n\t\tlet onWheel: ((e: WheelEvent) => void) | null = null;\n\t\tlet onContextMenu: ((e: MouseEvent) => void) | null = null;\n\n\t\tconst cb = makeCallbacksRef.current();\n\t\tconst eng = backend === \"konva\" ? new KonvaRenderer(host, cb) : new PixiRenderer(host, cb);\n\t\tengineRef.current = eng;\n\n\t\t(async () => {\n\t\t\tawait eng.init();\n\t\t\tif (cancelled) return;\n\t\t\t// 엔진 레벨 설정은 이미지와 무관하게 항상 적용.\n\t\t\teng.setFilter(viewRef.current.brightness, viewRef.current.contrast);\n\t\t\teng.setStrokeSize(viewRef.current.strokeSize);\n\t\t\teng.setImageSmoothing(viewRef.current.imageSmoothing);\n\t\t\teng.setTransformEnabled(!readOnlyRef.current);\n\t\t\tengineInitedRef.current = true;\n\n\t\t\t// 초기 마운트/백엔드 스왑 시 현재 이미지 로드(있을 때만 — 빈 URL이면\n\t\t\t// 아래 이미지 전환 이펙트가 URL 도착 시 로드한다).\n\t\t\tif (displayUrlRef.current) {\n\t\t\t\tawait eng.setImage(displayUrlRef.current);\n\t\t\t\tif (cancelled) return;\n\t\t\t\tloadedUrlRef.current = displayUrlRef.current;\n\t\t\t\tlastDocUrlRef.current = docImageUrlRef.current;\n\t\t\t\tsetImage({ w: eng.imageWidth, h: eng.imageHeight });\n\t\t\t\tsetImageVisible(true);\n\t\t\t\teng.setShapes(renderShapesRef.current, selRef.current);\n\t\t\t\teng.setOverlays(\n\t\t\t\t\tviewRef.current.showGuide ? maskCanvasRef.current : null,\n\t\t\t\t\tviewRef.current.showRegionMask ? regionOverlayRef.current : null,\n\t\t\t\t\tdimmedRef.current,\n\t\t\t\t);\n\t\t\t\t// 백엔드 스왑(같은 이미지)·줌 유지 설정이면 이전 뷰포트 복원, 아니면 fit.\n\t\t\t\tconst previousEngineState = previousEngineStateRef.current;\n\t\t\t\tif (\n\t\t\t\t\tpreviousEngineState?.viewport &&\n\t\t\t\t\t(previousEngineState.imageUrl === loadedUrlRef.current ||\n\t\t\t\t\t\tviewRef.current.keepZoomOnImageChange)\n\t\t\t\t) {\n\t\t\t\t\teng.applyViewport(previousEngineState.viewport);\n\t\t\t\t} else {\n\t\t\t\t\teng.fit();\n\t\t\t\t}\n\t\t\t\tsyncMinimap();\n\t\t\t\tsetReady(true);\n\t\t\t}\n\n\t\t\tonWheel = (ev: WheelEvent) => {\n\t\t\t\tev.preventDefault();\n\t\t\t\tconst r = eng.dom.getBoundingClientRect();\n\t\t\t\t// 트랙패드 핀치는 브라우저가 ctrlKey=true 휠로 전달한다. ⌘/Ctrl+휠 포함\n\t\t\t\t// 커서 기준 부드러운 줌(지수 배율 — 핀치의 연속적인 delta에 맞춤).\n\t\t\t\tif (ev.ctrlKey || ev.metaKey) {\n\t\t\t\t\teng.zoomAt(ev.clientX - r.left, ev.clientY - r.top, Math.exp(-ev.deltaY * 0.01));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// 휠/두손가락 스크롤 동작은 \"휠 줌\" 설정이 결정한다(장치 자동 감지는\n\t\t\t\t// macOS 마우스 휠 가속 때문에 트랙패드와 구분이 불가능해 포기).\n\t\t\t\t// 켬(기본) = 줌(기존 옵스 동작), 끔 = 팬(트랙패드 사용자용).\n\t\t\t\t// 핀치·⌘/Ctrl+휠 줌은 위에서 설정과 무관하게 항상 동작.\n\t\t\t\tif (!viewRef.current.wheelZoom) {\n\t\t\t\t\tconst v = eng.viewport;\n\t\t\t\t\teng.applyViewport({\n\t\t\t\t\t\tscale: v.scale,\n\t\t\t\t\t\tx: v.x - ev.deltaX,\n\t\t\t\t\t\ty: v.y - ev.deltaY,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\teng.zoomAt(ev.clientX - r.left, ev.clientY - r.top, ev.deltaY < 0 ? 1.1 : 1 / 1.1);\n\t\t\t};\n\t\t\teng.dom.addEventListener(\"wheel\", onWheel, { passive: false });\n\t\t\tonContextMenu = (ev: MouseEvent) => {\n\t\t\t\tev.preventDefault();\n\t\t\t\t// 마법봉 Alt+우클릭은 음성(−) 정제이므로 컨텍스트 메뉴를 띄우지 않는다.\n\t\t\t\tif (toolRef.current === TOOL.ASSISTANT_POINT && ev.altKey) return;\n\t\t\t\tconst r = host.getBoundingClientRect();\n\t\t\t\tconst hostX = ev.clientX - r.left;\n\t\t\t\tconst hostY = ev.clientY - r.top;\n\t\t\t\tconst v = eng.viewport;\n\t\t\t\t// 우클릭 도형 선택은 생략(빈/도형 무관 메뉴). 위치 + 이미지 좌표.\n\t\t\t\tonContextMenuRequestRef.current({\n\t\t\t\t\tx: hostX,\n\t\t\t\t\ty: hostY,\n\t\t\t\t\timg: { x: (hostX - v.x) / v.scale, y: (hostY - v.y) / v.scale },\n\t\t\t\t});\n\t\t\t};\n\t\t\teng.dom.addEventListener(\"contextmenu\", onContextMenu);\n\t\t})();\n\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\tengineInitedRef.current = false;\n\t\t\tpreviousEngineStateRef.current = {\n\t\t\t\timageUrl: loadedUrlRef.current ?? \"\",\n\t\t\t\tviewport: eng.viewport,\n\t\t\t};\n\t\t\tengineRef.current = null;\n\t\t\tif (onWheel && eng.dom) eng.dom.removeEventListener(\"wheel\", onWheel);\n\t\t\tif (onContextMenu && eng.dom) {\n\t\t\t\teng.dom.removeEventListener(\"contextmenu\", onContextMenu);\n\t\t\t}\n\t\t\teng.destroy();\n\t\t};\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [backend]);\n\n\t// 렌더 이미지 전환 — 엔진 재사용(파괴/재생성 없음). imageUrl 변경(문서 전환)과\n\t// displayImageUrl 스왑(고화질 토글)을 공용 처리한다. 렌더러가 새 이미지 로드\n\t// 완료 후 타일을 교체하므로 전환 중 이전 이미지가 그대로 보이고 로딩 딤만\n\t// 얹힌다(배경 번쩍임 제거). 문서 전환일 때만 도형/오버레이/fit을 갱신하고,\n\t// 화질 스왑은 문서·뷰포트를 유지한다.\n\tuseEffect(() => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng || !engineInitedRef.current) return; // 초기/백엔드 스왑 로드는 엔진 이펙트 담당\n\t\tif (!renderedImageUrl) return;\n\t\tif (loadedUrlRef.current === renderedImageUrl) return;\n\t\tconst target = renderedImageUrl;\n\t\tconst isDocImageChange = lastDocUrlRef.current !== imageUrl;\n\t\t// 문서 전환은 이전 이미지·도형을 즉시 비운다(잔상 없이 어두운 캔버스+로딩 딤만).\n\t\t// 화질 스왑은 같은 이미지라 유지 — 로드 완료 시 텍스처만 교체.\n\t\tif (isDocImageChange) {\n\t\t\teng.clearImage();\n\t\t\teng.setShapes([], []);\n\t\t\teng.setOverlays(null, null, false);\n\t\t\tsetImageVisible(false);\n\t\t}\n\t\tlet cancelled = false;\n\t\t(async () => {\n\t\t\tawait eng.setImage(target);\n\t\t\tif (cancelled || engineRef.current !== eng) return;\n\t\t\tloadedUrlRef.current = target;\n\t\t\tif (!isDocImageChange) return; // 화질 스왑 — 텍스처만 교체.\n\t\t\tlastDocUrlRef.current = imageUrl;\n\t\t\tsetImage({ w: eng.imageWidth, h: eng.imageHeight });\n\t\t\tsetImageVisible(true);\n\t\t\teng.setShapes(renderShapesRef.current, selRef.current);\n\t\t\teng.setOverlays(\n\t\t\t\tviewRef.current.showGuide ? maskCanvasRef.current : null,\n\t\t\t\tviewRef.current.showRegionMask ? regionOverlayRef.current : null,\n\t\t\t\tdimmedRef.current,\n\t\t\t);\n\t\t\tif (!viewRef.current.keepZoomOnImageChange) eng.fit();\n\t\t\tsyncMinimap();\n\t\t\tsetReady(true);\n\t\t})();\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [renderedImageUrl]);\n\n\t// 이미지 로딩/에러 상태(오버레이용) — 렌더 URL을 프리로드해 추적.\n\tuseEffect(() => {\n\t\tlet cancelled = false;\n\t\t// 이미지 전환 중 URL이 잠깐 빈 값이 될 수 있다. 이때 img.src=\"\"는 즉시 onerror를\n\t\t// 발생시켜 \"이미지를 불러올 수 없습니다\"가 반짝인다. 빈 URL은 에러가 아니라\n\t\t// 아직 이미지가 없는 상태이므로 loading으로 둔다.\n\t\tif (!renderedImageUrl) {\n\t\t\tsetImageStatus(\"loading\");\n\t\t\treturn;\n\t\t}\n\t\tsetImageStatus(\"loading\");\n\t\tconst img = new Image();\n\t\timg.onload = () => {\n\t\t\tif (!cancelled) setImageStatus(\"ready\");\n\t\t};\n\t\timg.onerror = () => {\n\t\t\tif (!cancelled) setImageStatus(\"error\");\n\t\t};\n\t\timg.src = renderedImageUrl;\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [renderedImageUrl]);\n}\n","import {\n\ttype PointerEvent as ReactPointerEvent,\n\ttype WheelEvent as ReactWheelEvent,\n\ttype RefObject,\n\tuseRef,\n} from \"react\";\nimport type { EditorRenderer } from \"../_renderers/types\";\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 20;\n\n/** deltaMode/정수 여부로 트랙패드 휠을 추정(마우스 휠 대비 감도 보정용). */\nfunction isTrackpadWheel(event: WheelEvent): boolean {\n\tconst { deltaY, deltaX, deltaMode } = event;\n\n\tif (deltaMode === 0) {\n\t\tconst absDeltaY = Math.abs(deltaY);\n\t\tconst absDeltaX = Math.abs(deltaX);\n\t\treturn (\n\t\t\tabsDeltaY < 10 || absDeltaX < 10 || !Number.isInteger(deltaY) || !Number.isInteger(deltaX)\n\t\t);\n\t}\n\n\tif (deltaMode === 1) return false;\n\n\treturn !Number.isInteger(deltaY) || !Number.isInteger(deltaX);\n}\n\n/**\n * 미니맵 내비게이션(패닝/줌) 훅. 미니맵 위 포인터·휠 조작을 캔버스 뷰포트로 변환한다.\n * 미니맵 사각형 갱신(syncMinimap)은 뷰포트 동기화 쪽 책임이라 여기서 다루지 않는다.\n */\nexport function useMinimapNavigation({\n\tengineRef,\n\timage,\n\twheelZoom,\n\tminimapSize,\n}: {\n\tengineRef: RefObject<EditorRenderer | null>;\n\timage: { w: number; h: number } | null;\n\twheelZoom: boolean;\n\tminimapSize: number;\n}) {\n\tconst dragRef = useRef<{\n\t\tpointerId: number;\n\t\toffsetX: number;\n\t\toffsetY: number;\n\t} | null>(null);\n\n\t// 이미지 로드 전/전환 중엔 {w:0,h:0}가 올 수 있다 — 0 나눗셈이면\n\t// mm=Infinity, dispW=0*Infinity=NaN으로 스타일에 NaN이 흘러간다.\n\tconst hasImage = !!image && image.w > 0 && image.h > 0;\n\tconst mm = hasImage ? Math.min(minimapSize / image.w, minimapSize / image.h) : 1;\n\tconst dispW = hasImage ? image.w * mm : 0;\n\tconst dispH = hasImage ? image.h * mm : 0;\n\tconst offX = hasImage ? (minimapSize - dispW) / 2 : 0;\n\tconst offY = hasImage ? (minimapSize - dispH) / 2 : 0;\n\n\tconst getMinimapPointer = (\n\t\te: ReactPointerEvent<HTMLDivElement> | ReactWheelEvent<HTMLDivElement>,\n\t) => {\n\t\tconst rect = e.currentTarget.getBoundingClientRect();\n\t\treturn { x: e.clientX - rect.left, y: e.clientY - rect.top };\n\t};\n\n\tconst getMinimapViewportRect = () => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return null;\n\t\tconst v = eng.viewport;\n\t\treturn {\n\t\t\tx: (-v.x / v.scale) * mm + offX,\n\t\t\ty: (-v.y / v.scale) * mm + offY,\n\t\t\twidth: (eng.screenSize.w / v.scale) * mm,\n\t\t\theight: (eng.screenSize.h / v.scale) * mm,\n\t\t};\n\t};\n\n\tconst applyMinimapPointerView = (\n\t\tpointer: { x: number; y: number },\n\t\ttargetScale: number,\n\t\tdragOffset?: { offsetX: number; offsetY: number },\n\t) => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng || !image) return;\n\t\tconst viewport = getMinimapViewportRect();\n\t\tif (!viewport) return;\n\n\t\tconst offsetX = dragOffset?.offsetX ?? viewport.width / 2;\n\t\tconst offsetY = dragOffset?.offsetY ?? viewport.height / 2;\n\t\tconst targetX = pointer.x - offsetX + viewport.width / 2;\n\t\tconst targetY = pointer.y - offsetY + viewport.height / 2;\n\t\tconst imageX = (targetX - offX) / mm;\n\t\tconst imageY = (targetY - offY) / mm;\n\n\t\teng.applyViewport({\n\t\t\tscale: targetScale,\n\t\t\tx: eng.screenSize.w / 2 - imageX * targetScale,\n\t\t\ty: eng.screenSize.h / 2 - imageY * targetScale,\n\t\t});\n\t};\n\n\tconst handleMinimapPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {\n\t\tconst eng = engineRef.current;\n\t\tconst viewport = getMinimapViewportRect();\n\t\tif (!eng || !viewport) return;\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\n\t\tconst pointer = getMinimapPointer(e);\n\t\tconst insideViewport =\n\t\t\tpointer.x >= viewport.x &&\n\t\t\tpointer.x <= viewport.x + viewport.width &&\n\t\t\tpointer.y >= viewport.y &&\n\t\t\tpointer.y <= viewport.y + viewport.height;\n\t\tconst dragOffset = insideViewport\n\t\t\t? { offsetX: pointer.x - viewport.x, offsetY: pointer.y - viewport.y }\n\t\t\t: { offsetX: viewport.width / 2, offsetY: viewport.height / 2 };\n\n\t\tdragRef.current = { pointerId: e.pointerId, ...dragOffset };\n\t\te.currentTarget.setPointerCapture(e.pointerId);\n\t\tapplyMinimapPointerView(pointer, eng.viewport.scale, dragOffset);\n\t};\n\n\tconst handleMinimapPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n\t\tconst drag = dragRef.current;\n\t\tconst eng = engineRef.current;\n\t\tif (!drag || !eng || drag.pointerId !== e.pointerId) return;\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tapplyMinimapPointerView(getMinimapPointer(e), eng.viewport.scale, drag);\n\t};\n\n\tconst endMinimapDrag = (e: ReactPointerEvent<HTMLDivElement>) => {\n\t\tconst drag = dragRef.current;\n\t\tif (!drag || drag.pointerId !== e.pointerId) return;\n\t\tdragRef.current = null;\n\t\tif (e.currentTarget.hasPointerCapture(e.pointerId)) {\n\t\t\te.currentTarget.releasePointerCapture(e.pointerId);\n\t\t}\n\t};\n\n\tconst handleMinimapWheel = (e: ReactWheelEvent<HTMLDivElement>) => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng || !wheelZoom) return;\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\n\t\tconst trackpadMultiplier = isTrackpadWheel(e.nativeEvent) ? 2.5 : 1;\n\t\tconst adjustedDeltaY = e.deltaY * trackpadMultiplier;\n\t\tconst scaleBy = 1.05;\n\t\tconst nextScale =\n\t\t\tadjustedDeltaY > 0 ? eng.viewport.scale / scaleBy : eng.viewport.scale * scaleBy;\n\t\tconst clampedScale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));\n\t\tapplyMinimapPointerView(getMinimapPointer(e), clampedScale);\n\t};\n\n\tconst zoomCentered = (factor: number) => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return;\n\t\tconst { w, h } = eng.screenSize;\n\t\teng.zoomAt(w / 2, h / 2, factor);\n\t};\n\n\treturn {\n\t\tmm,\n\t\toffX,\n\t\toffY,\n\t\tdispW,\n\t\tdispH,\n\t\thandleMinimapPointerDown,\n\t\thandleMinimapPointerMove,\n\t\tendMinimapDrag,\n\t\thandleMinimapWheel,\n\t\tzoomCentered,\n\t};\n}\n\nexport type MinimapNavigation = ReturnType<typeof useMinimapNavigation>;\n","import { type RefObject, useCallback, useRef } from \"react\";\nimport { type EditorShape, getBBox, type Point, SHAPE_TYPE } from \"../_model/geometry\";\nimport type { EditorRenderer, Viewport } from \"../_renderers/types\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nfunction updateMinimapShapeEl<TMeta>(\n\tel: SVGElement | undefined,\n\tshape: EditorShape<TMeta>,\n\tpoints: Point[],\n) {\n\tif (!el || !points.length) return;\n\tif (shape.type === SHAPE_TYPE.POINT) {\n\t\tel.setAttribute(\"cx\", String(points[0].x));\n\t\tel.setAttribute(\"cy\", String(points[0].y));\n\t\treturn;\n\t}\n\tif (shape.type === SHAPE_TYPE.RECTANGLE || shape.type === SHAPE_TYPE.ELLIPSE) {\n\t\tconst b = getBBox(points);\n\t\tif (shape.type === SHAPE_TYPE.ELLIPSE) {\n\t\t\tel.setAttribute(\"cx\", String((b.minX + b.maxX) / 2));\n\t\t\tel.setAttribute(\"cy\", String((b.minY + b.maxY) / 2));\n\t\t\tel.setAttribute(\"rx\", String((b.maxX - b.minX) / 2));\n\t\t\tel.setAttribute(\"ry\", String((b.maxY - b.minY) / 2));\n\t\t\treturn;\n\t\t}\n\t\tel.setAttribute(\"x\", String(b.minX));\n\t\tel.setAttribute(\"y\", String(b.minY));\n\t\tel.setAttribute(\"width\", String(b.maxX - b.minX));\n\t\tel.setAttribute(\"height\", String(b.maxY - b.minY));\n\t\treturn;\n\t}\n\tel.setAttribute(\"points\", points.map((p) => `${p.x},${p.y}`).join(\" \"));\n}\n\n/**\n * 뷰포트 → 미니맵 사각형·줌 % 라벨·캔버스 위 DOM 오버레이(transform) 동기화와\n * 미니맵 SVG 도형의 명령형 갱신(드래그/변형 미리보기). 전부 리렌더 0 경로.\n */\nexport function useMinimapSync<TMeta>({\n\tengineRef,\n\tdocRef,\n\toverlayRef,\n\tzoomLabelRef,\n\tminimapRectRef,\n\tminimapSize,\n\tonViewportChangeRef,\n}: {\n\tengineRef: RefObject<EditorRenderer | null>;\n\tdocRef: RefObject<EditorDocument<TMeta>>;\n\toverlayRef: RefObject<HTMLDivElement | null>;\n\tzoomLabelRef: RefObject<HTMLSpanElement | null>;\n\tminimapRectRef: RefObject<HTMLDivElement | null>;\n\tminimapSize: number;\n\tonViewportChangeRef: RefObject<((viewport: Viewport) => void) | undefined>;\n}) {\n\tconst minimapShapeRefs = useRef(new Map<string, SVGElement>());\n\n\tconst registerMinimapShape = useCallback((id: string, el: SVGElement | null) => {\n\t\tif (el) minimapShapeRefs.current.set(id, el);\n\t\telse minimapShapeRefs.current.delete(id);\n\t}, []);\n\n\tconst applyMinimapPreview = useCallback(\n\t\t(updates: { id: string; points: Point[] }[]) => {\n\t\t\tconst shapes = docRef.current.getShapes();\n\t\t\tif (!updates.length) {\n\t\t\t\tfor (const shape of shapes) {\n\t\t\t\t\tupdateMinimapShapeEl(minimapShapeRefs.current.get(shape.id), shape, shape.points);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst shapeMap = new Map(shapes.map((shape) => [shape.id, shape]));\n\t\t\tfor (const update of updates) {\n\t\t\t\tconst shape = shapeMap.get(update.id);\n\t\t\t\tif (shape) {\n\t\t\t\t\tupdateMinimapShapeEl(minimapShapeRefs.current.get(shape.id), shape, update.points);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[docRef],\n\t);\n\n\t// 뷰포트 변경 시 미니맵 사각형 + 줌 % 라벨 + 캔버스 위 ROI/마스크 오버레이 동기화.\n\tconst syncMinimap = useCallback(() => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng?.imageWidth) return;\n\t\tconst v = eng.viewport;\n\t\tonViewportChangeRef.current?.(v);\n\t\t// 오버레이(이미지 좌표 콘텐츠)를 뷰포트 변환으로 캔버스에 정렬.\n\t\tif (overlayRef.current) {\n\t\t\toverlayRef.current.style.transform = `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;\n\t\t\tconst inverseScale = 1 / (v.scale || 1);\n\t\t\toverlayRef.current.style.setProperty(\"--editor-overlay-stroke\", `${inverseScale}`);\n\t\t\toverlayRef.current.style.setProperty(\"--editor-overlay-dash\", `${4 * inverseScale}`);\n\t\t\toverlayRef.current.style.setProperty(\"--editor-overlay-inverse-scale\", `${inverseScale}`);\n\t\t}\n\t\tif (zoomLabelRef.current) {\n\t\t\tzoomLabelRef.current.textContent = `${Math.round(v.scale * 100)}%`;\n\t\t}\n\t\tconst rect = minimapRectRef.current;\n\t\tif (!rect) return;\n\t\tconst mm = Math.min(minimapSize / eng.imageWidth, minimapSize / eng.imageHeight);\n\t\tconst offX = (minimapSize - eng.imageWidth * mm) / 2;\n\t\tconst offY = (minimapSize - eng.imageHeight * mm) / 2;\n\t\tconst { w, h } = eng.screenSize;\n\t\trect.style.left = `${(-v.x / v.scale) * mm + offX}px`;\n\t\trect.style.top = `${(-v.y / v.scale) * mm + offY}px`;\n\t\trect.style.width = `${(w / v.scale) * mm}px`;\n\t\trect.style.height = `${(h / v.scale) * mm}px`;\n\t}, [engineRef, overlayRef, zoomLabelRef, minimapRectRef, minimapSize, onViewportChangeRef]);\n\n\treturn { registerMinimapShape, applyMinimapPreview, syncMinimap };\n}\n","import { type RefObject, useCallback, useRef } from \"react\";\nimport {\n\ttype EditorShape,\n\tgenerateId,\n\tgetBBox,\n\tisShapeEditable,\n\tisShapeSelectable,\n\tSHAPE_TYPE,\n} from \"../_model/geometry\";\nimport {\n\tbuildScalarMaskRaster,\n\tscalarMaskToPolygons,\n\tshapesToFilledPolygons,\n} from \"../_model/scalarMask\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nconst DUP_OFFSET = 12;\n\n/**\n * 선택 기반 문서 액션(키보드·컨텍스트메뉴·명령형 핸들 공용) — 복사/붙여넣기/복제/삭제/\n * z순서/반전/합치기/넛지. 클립보드(clipRef)와 붙여넣기 오프셋 카운터를 소유한다.\n */\nexport function useSelectionActions<TMeta>({\n\tdoc,\n\tselRef,\n\teffectiveReadOnly,\n\tchangeSelection,\n\tcanMergeSelection,\n}: {\n\tdoc: EditorDocument<TMeta>;\n\tselRef: RefObject<string[]>;\n\teffectiveReadOnly: boolean;\n\tchangeSelection: (ids: string[]) => void;\n\tcanMergeSelection?: (shapes: EditorShape<TMeta>[]) => boolean;\n}) {\n\tconst clipRef = useRef<EditorShape<TMeta>[]>([]);\n\tconst pasteN = useRef(0);\n\n\tconst selectAll = useCallback(\n\t\t() =>\n\t\t\tchangeSelection(\n\t\t\t\tdoc\n\t\t\t\t\t.getShapes()\n\t\t\t\t\t.filter((shape) => isShapeSelectable(shape))\n\t\t\t\t\t.map((shape) => shape.id),\n\t\t\t),\n\t\t[doc, changeSelection],\n\t);\n\tconst clearSelection = useCallback(() => changeSelection([]), [changeSelection]);\n\t// 현재 선택 중 편집 가능한 도형(선택 기반 액션 공용).\n\tconst getEditableSelection = useCallback(\n\t\t() => doc.getShapes().filter((s) => selRef.current.includes(s.id) && isShapeEditable(s)),\n\t\t[doc, selRef],\n\t);\n\tconst deleteSelection = useCallback(() => {\n\t\tif (effectiveReadOnly || !selRef.current.length) return;\n\t\tconst ids = getEditableSelection().map((s) => s.id);\n\t\tif (!ids.length) return;\n\t\tdoc.remove(ids);\n\t\tchangeSelection([]);\n\t}, [doc, effectiveReadOnly, changeSelection, getEditableSelection, selRef]);\n\tconst copySelection = useCallback(() => {\n\t\tclipRef.current = getEditableSelection();\n\t\tpasteN.current = 0;\n\t}, [getEditableSelection]);\n\tconst canPaste = useCallback(() => clipRef.current.length > 0, []);\n\tconst paste = useCallback(() => {\n\t\tif (effectiveReadOnly || !clipRef.current.length) return;\n\t\tpasteN.current += 1;\n\t\tconst off = DUP_OFFSET * pasteN.current;\n\t\tconst pasted = clipRef.current.map((s) => ({\n\t\t\t...s,\n\t\t\tid: generateId(),\n\t\t\tpoints: s.points.map((p) => ({ x: p.x + off, y: p.y + off })),\n\t\t}));\n\t\tdoc.create(pasted);\n\t\tchangeSelection(pasted.map((s) => s.id));\n\t}, [doc, effectiveReadOnly, changeSelection]);\n\tconst duplicate = useCallback(() => {\n\t\tif (effectiveReadOnly || !selRef.current.length) return;\n\t\tconst dup = getEditableSelection().map((s) => ({\n\t\t\t...s,\n\t\t\tid: generateId(),\n\t\t\tpoints: s.points.map((p) => ({\n\t\t\t\tx: p.x + DUP_OFFSET,\n\t\t\t\ty: p.y + DUP_OFFSET,\n\t\t\t})),\n\t\t}));\n\t\tif (!dup.length) return;\n\t\tdoc.create(dup);\n\t\tchangeSelection(dup.map((s) => s.id));\n\t}, [doc, effectiveReadOnly, changeSelection, getEditableSelection, selRef]);\n\tconst bringToFront = useCallback(() => {\n\t\tif (effectiveReadOnly) return;\n\t\tconst ids = getEditableSelection().map((s) => s.id);\n\t\tif (ids.length) doc.reorder(ids, \"front\");\n\t}, [doc, effectiveReadOnly, getEditableSelection]);\n\tconst sendToBack = useCallback(() => {\n\t\tif (effectiveReadOnly) return;\n\t\tconst ids = getEditableSelection().map((s) => s.id);\n\t\tif (ids.length) doc.reorder(ids, \"back\");\n\t}, [doc, effectiveReadOnly, getEditableSelection]);\n\tconst flip = useCallback(\n\t\t(horizontal: boolean) => {\n\t\t\tif (effectiveReadOnly || !selRef.current.length) return;\n\t\t\tconst sel = getEditableSelection();\n\t\t\tif (!sel.length) return;\n\t\t\tconst b = getBBox(sel.flatMap((s) => s.points));\n\t\t\tconst cx = (b.minX + b.maxX) / 2;\n\t\t\tconst cy = (b.minY + b.maxY) / 2;\n\t\t\tdoc.update(\n\t\t\t\tsel.map((s) => ({\n\t\t\t\t\t...s,\n\t\t\t\t\tpoints: s.points.map((p) => ({\n\t\t\t\t\t\tx: horizontal ? 2 * cx - p.x : p.x,\n\t\t\t\t\t\ty: horizontal ? p.y : 2 * cy - p.y,\n\t\t\t\t\t})),\n\t\t\t\t})),\n\t\t\t);\n\t\t},\n\t\t[doc, effectiveReadOnly, getEditableSelection, selRef],\n\t);\n\tconst nudgeSelection = useCallback(\n\t\t(dx: number, dy: number) => {\n\t\t\tif (effectiveReadOnly || !selRef.current.length) return;\n\t\t\t// readOnly·편집불가 도형은 방향키 이동에서도 제외한다(다른 편집 경로와 동일 규칙).\n\t\t\tconst sel = doc\n\t\t\t\t.getShapes()\n\t\t\t\t.filter((s) => selRef.current.includes(s.id) && isShapeEditable(s));\n\t\t\tif (!sel.length) return;\n\t\t\tdoc.update(\n\t\t\t\tsel.map((s) => ({\n\t\t\t\t\t...s,\n\t\t\t\t\tpoints: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })),\n\t\t\t\t})),\n\t\t\t);\n\t\t},\n\t\t[doc, effectiveReadOnly, selRef],\n\t);\n\n\t/** 합치기 대상: 선택된 편집 가능 '닫힌' 도형들(2개 이상일 때 유효). */\n\tconst getMergeTargets = useCallback(\n\t\t() =>\n\t\t\tgetEditableSelection().filter(\n\t\t\t\t(shape) =>\n\t\t\t\t\tshape.type === SHAPE_TYPE.POLYGON ||\n\t\t\t\t\tshape.type === SHAPE_TYPE.RECTANGLE ||\n\t\t\t\t\tshape.type === SHAPE_TYPE.ROTATED_RECTANGLE ||\n\t\t\t\t\tshape.type === SHAPE_TYPE.ELLIPSE,\n\t\t\t),\n\t\t[getEditableSelection],\n\t);\n\t/**\n\t * 선택 도형 합치기(래스터 유니온) — 붓 커밋과 같은 파이프라인으로 채운 마스크를\n\t * 만들어 외곽선을 다시 딴다. 결과 style/meta는 첫 도형을 따르고, 서로 떨어져\n\t * 있으면 조각 수만큼 폴리곤이 남는다. 원자적 replace라 undo 한 번에 복원된다.\n\t */\n\tconst mergeSelection = useCallback(() => {\n\t\tif (effectiveReadOnly) return;\n\t\tconst targets = getMergeTargets();\n\t\tif (targets.length < 2) return;\n\t\tif (canMergeSelection && !canMergeSelection(targets)) return;\n\t\tconst raster = buildScalarMaskRaster([], 1, shapesToFilledPolygons(targets));\n\t\tif (!raster) return;\n\t\tconst merged = scalarMaskToPolygons(raster, 1);\n\t\tif (!merged.length) return;\n\t\tconst first = targets[0];\n\t\tconst created = merged.map((points) => ({\n\t\t\tid: generateId(),\n\t\t\ttype: SHAPE_TYPE.POLYGON,\n\t\t\tpoints,\n\t\t\tstyle: first.style,\n\t\t\tmeta: first.meta,\n\t\t}));\n\t\tdoc.replace(\n\t\t\ttargets.map((shape) => shape.id),\n\t\t\tcreated,\n\t\t);\n\t\tchangeSelection(created.map((shape) => shape.id));\n\t}, [doc, effectiveReadOnly, getMergeTargets, canMergeSelection, changeSelection]);\n\n\treturn {\n\t\tselectAll,\n\t\tclearSelection,\n\t\tgetEditableSelection,\n\t\tdeleteSelection,\n\t\tcopySelection,\n\t\tcanPaste,\n\t\tpaste,\n\t\tduplicate,\n\t\tbringToFront,\n\t\tsendToBack,\n\t\tflip,\n\t\tnudgeSelection,\n\t\tgetMergeTargets,\n\t\tmergeSelection,\n\t};\n}\n","import { type RefObject, useCallback, useEffect, useRef } from \"react\";\nimport { getBBox } from \"../_model/geometry\";\nimport {\n\tanimateViewport,\n\tviewportForBBox,\n\tviewportForZoomBounds,\n\ttype ZoomBounds,\n\tzoomBoundsFromShapes,\n} from \"../_model/viewport\";\nimport type { EditorRenderer, Viewport } from \"../_renderers/types\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\n/**\n * 뷰포트 줌 액션(애니메이션 줌·선택/도형/영역 맞춤·중앙 줌) + zoomBound prop 반영.\n * 진행 중 애니메이션 취소 핸들을 소유하고 언마운트 시 정리한다.\n */\nexport function useViewportControls<TMeta>({\n\tengineRef,\n\tdoc,\n\tselRef,\n\tzoomAnimationDuration,\n\tzoomBound,\n\tready,\n}: {\n\tengineRef: RefObject<EditorRenderer | null>;\n\tdoc: EditorDocument<TMeta>;\n\tselRef: RefObject<string[]>;\n\tzoomAnimationDuration: number;\n\tzoomBound: ZoomBounds | undefined;\n\tready: boolean;\n}) {\n\tconst cancelZoomAnimationRef = useRef<(() => void) | null>(null);\n\tconst previousZoomBoundRef = useRef<string | null>(null);\n\n\tconst cancelZoomAnimation = useCallback(() => {\n\t\tcancelZoomAnimationRef.current?.();\n\t\tcancelZoomAnimationRef.current = null;\n\t}, []);\n\n\tconst runViewportAnimation = useCallback(\n\t\t(target: Viewport, duration = zoomAnimationDuration) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tcancelZoomAnimation();\n\t\t\tcancelZoomAnimationRef.current = animateViewport(\n\t\t\t\teng.viewport,\n\t\t\t\ttarget,\n\t\t\t\t(viewport) => eng.applyViewport(viewport),\n\t\t\t\tduration,\n\t\t\t);\n\t\t},\n\t\t[cancelZoomAnimation, zoomAnimationDuration, engineRef],\n\t);\n\n\tconst zoomToBounds = useCallback(\n\t\t(bounds: ZoomBounds, duration = zoomAnimationDuration) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tconst target = viewportForZoomBounds(bounds, eng.screenSize.w, eng.screenSize.h);\n\t\t\tif (target) runViewportAnimation(target, duration);\n\t\t},\n\t\t[runViewportAnimation, zoomAnimationDuration, engineRef],\n\t);\n\n\tconst zoomToShapes = useCallback(\n\t\t(ids: string[], duration = zoomAnimationDuration) => {\n\t\t\tconst shapes = doc.getShapes().filter((shape) => ids.includes(shape.id));\n\t\t\tconst bounds = zoomBoundsFromShapes(shapes);\n\t\t\tif (bounds) zoomToBounds(bounds, duration);\n\t\t},\n\t\t[doc, zoomToBounds, zoomAnimationDuration],\n\t);\n\n\tconst zoomToSelection = useCallback(() => {\n\t\tconst sel = doc.getShapes().filter((s) => selRef.current.includes(s.id));\n\t\tif (!sel.length) return;\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return;\n\t\tconst target = viewportForBBox(\n\t\t\tgetBBox(sel.flatMap((s) => s.points)),\n\t\t\teng.screenSize.w,\n\t\t\teng.screenSize.h,\n\t\t\t80,\n\t\t);\n\t\tif (target) runViewportAnimation(target);\n\t}, [doc, runViewportAnimation, engineRef, selRef]);\n\n\tconst zoomAtCenter = useCallback(\n\t\t(factor: number) => {\n\t\t\tconst eng = engineRef.current;\n\t\t\tif (!eng) return;\n\t\t\tconst { w, h } = eng.screenSize;\n\t\t\teng.zoomAt(w / 2, h / 2, factor);\n\t\t},\n\t\t[engineRef],\n\t);\n\n\tuseEffect(() => () => cancelZoomAnimation(), [cancelZoomAnimation]);\n\n\tuseEffect(() => {\n\t\tif (!zoomBound) {\n\t\t\tpreviousZoomBoundRef.current = null;\n\t\t\treturn;\n\t\t}\n\t\tif (!ready) return;\n\t\tconst eng = engineRef.current;\n\t\tif (!eng?.imageWidth) return;\n\t\tconst { w, h } = eng.screenSize;\n\t\tif (!w || !h) return;\n\t\tconst key = JSON.stringify(zoomBound);\n\t\tif (previousZoomBoundRef.current === key) return;\n\t\tzoomToBounds(zoomBound);\n\t\tpreviousZoomBoundRef.current = key;\n\t}, [zoomBound, ready, zoomToBounds, engineRef]);\n\n\treturn {\n\t\tcancelZoomAnimation,\n\t\trunViewportAnimation,\n\t\tzoomToBounds,\n\t\tzoomToShapes,\n\t\tzoomToSelection,\n\t\tzoomAtCenter,\n\t};\n}\n","\"use client\";\n\nimport {\n\tuseCallback,\n\tuseEffect,\n\tuseId,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from \"react\";\nimport { MagicWandIcon } from \"../Icon\";\nimport { AssistantOverlay } from \"./_components/AssistantOverlay\";\nimport { ContextMenu, type ContextMenuItem } from \"./_components/ContextMenu\";\nimport { CursorGuide } from \"./_components/CursorGuide\";\nimport { ImageStateOverlay } from \"./_components/ImageStateOverlay\";\nimport { Minimap } from \"./_components/Minimap\";\nimport {\n\tbuildSelectionInfo,\n\tdefaultSelectionInfoText,\n\tSelectionInfo,\n} from \"./_components/SelectionInfo\";\nimport { type EditorInteractionMode, resolveEditorCursor } from \"./_model/cursors\";\nimport {\n\ttype EditorShape,\n\tgenerateId,\n\tgetBBox,\n\tisShapeEditable,\n\tisShapeSelectable,\n\tisShapeVisible,\n\ttype Point,\n\tSHAPE_TYPE,\n} from \"./_model/geometry\";\nimport { buildMaskCanvas, buildRegionOverlayData } from \"./_model/overlays\";\nimport type { DrawSessionChange, ShapeEditorProps } from \"./_model/props\";\nimport { mergeEditorStrings } from \"./_model/strings\";\nimport { TOOL } from \"./_model/tools\";\nimport { DEFAULT_ZOOM_ANIMATION_MS } from \"./_model/viewport\";\nimport { DEFAULT_VIEW_SETTINGS, type ViewSettings } from \"./_model/viewSettings\";\nimport type { EditorRenderer } from \"./_renderers/types\";\nimport { createInteractionController } from \"./_state/createInteractionController\";\nimport { useAssistant } from \"./_state/useAssistant\";\nimport { useDrawSession } from \"./_state/useDrawSession\";\nimport { useEditorDocument } from \"./_state/useEditorDocument\";\nimport { type EditorActionHandlers, useEditorHotkeys } from \"./_state/useEditorHotkeys\";\nimport { type EditorImageStatus, useEngineLifecycle } from \"./_state/useEngineLifecycle\";\nimport { useMinimapNavigation } from \"./_state/useMinimapNavigation\";\nimport { useMinimapSync } from \"./_state/useMinimapSync\";\nimport { useSelectionActions } from \"./_state/useSelectionActions\";\nimport { useViewportControls } from \"./_state/useViewportControls\";\n\nconst MINIMAP_SIZE = 180;\n// 그리는 중 정보 배지용 합성 도형 id(선택 배지와 같은 오버레이를 재사용).\nconst DRAFT_PREVIEW_ID = \"__draft_preview__\";\n\nfunction sameSelection(a: string[], b: string[]) {\n\treturn a.length === b.length && a.every((id, i) => id === b[i]);\n}\n\n/**\n * ShapeEditor — renderer backend 기반 도형 에디터. 상호작용/문서/키보드/메뉴는 여기서 소유하고,\n * 그리기·히트테스트·뷰포트는 `EditorRenderer`(Konva/Pixi)에 위임한다. `backend`로 교체.\n * 갭(회전/꼭짓점추가 등)은 여기서 한 번 구현하면 양쪽 렌더러에 적용된다.\n */\nexport default function ShapeEditor<TMeta, TMarkerMeta = unknown>({\n\timageUrl,\n\tdisplayImageUrl,\n\trenderImageState,\n\tdimmed = false,\n\tinitialShapes,\n\tselectedIds: controlledSelectedIds,\n\tactiveTool,\n\tdraftStyle,\n\tdraftMeta,\n\treadOnly,\n\tdisableMarquee,\n\tlocked,\n\tonLockedInteraction,\n\tonIdleEscape,\n\toverrideShapeInteraction,\n\tdefaultViewSettings,\n\tviewSettings,\n\tonViewSettingsChange,\n\tshowMinimap = true,\n\tshowViewSettings = true,\n\tgetContextMenuItems,\n\tstrings,\n\tcanMergeSelection,\n\tbrushSize = 20,\n\tzoomBound,\n\tzoomAnimationDuration = DEFAULT_ZOOM_ANIMATION_MS,\n\tdecorationShapes,\n\tregionMask,\n\tguideMask,\n\tmaskPalette,\n\toverlayMarkers,\n\trenderOverlayMarker,\n\tonOverlayMarkerClick,\n\trenderImageOverlay,\n\tgetSelectionLabel,\n\thideSelectionLabelDot,\n\tformatSelectionInfo,\n\texternalTools,\n\tassistant,\n\tkeymap,\n\thandleRef,\n\tbackend = \"pixi\",\n\tonActiveToolChange,\n\tonSelectionChange,\n\tonEditingChange,\n\tonShapesCreated,\n\tonShapesUpdated,\n\tonShapesDeleted,\n\tonDrawSessionChange,\n\tonDraftShapeChange,\n\tonViewportChange,\n\tonShapesTransformPreview,\n}: ShapeEditorProps<TMeta, TMarkerMeta> & { backend?: \"konva\" | \"pixi\" }) {\n\tconst hostRef = useRef<HTMLDivElement>(null);\n\tconst engineRef = useRef<EditorRenderer | null>(null);\n\tconst minimapRectRef = useRef<HTMLDivElement>(null);\n\tconst overlayRef = useRef<HTMLDivElement>(null);\n\tconst zoomLabelRef = useRef<HTMLSpanElement>(null);\n\tconst roiMaskId = useId();\n\tconst minimapRoiMaskId = `${roiMaskId}-minimap`;\n\tconst [image, setImage] = useState<{ w: number; h: number } | null>(null);\n\t// 이미지 표시 페이드인 — 전환 시 즉시 숨겼다가(transition 없음) 로드 완료 후\n\t// 잔잔하게 나타난다. 화질 스왑은 건드리지 않는다(같은 이미지 유지).\n\tconst [imageVisible, setImageVisible] = useState(false);\n\tconst [ready, setReady] = useState(false);\n\tconst [menu, setMenu] = useState<{\n\t\tx: number;\n\t\ty: number;\n\t\t/** 우클릭 지점(이미지 좌표) — 어시스트 지점 확장/제외용. */\n\t\timg: Point;\n\t} | null>(null);\n\tconst [drawSessionState, setDrawSessionState] = useState<DrawSessionChange>({\n\t\tactive: false,\n\t\tkind: \"none\",\n\t\tcanUndo: false,\n\t\tcanRedo: false,\n\t});\n\tconst [minimapOpen, setMinimapOpen] = useState(true);\n\tconst [settingsOpen, setSettingsOpen] = useState(false);\n\n\t// 실제 렌더 URL(화질 스왑). imageUrl은 시드/좌표계 identity, displayImageUrl은 텍스처만.\n\tconst renderedImageUrl = displayImageUrl ?? imageUrl;\n\tconst [imageStatus, setImageStatus] = useState<EditorImageStatus>(\"loading\");\n\n\tconst doc = useEditorDocument<TMeta>({\n\t\tonShapesCreated,\n\t\tonShapesUpdated,\n\t\tonShapesDeleted,\n\t});\n\tconst [uncontrolledSelectedIds, setUncontrolledSelectedIds] = useState<string[]>([]);\n\tconst selectedIds = controlledSelectedIds ?? uncontrolledSelectedIds;\n\tconst selectionControlled = controlledSelectedIds !== undefined;\n\tconst externalToolMap = useMemo(\n\t\t() => new Map((externalTools ?? []).map((tool) => [tool.id, tool])),\n\t\t[externalTools],\n\t);\n\tconst externalToolMapRef = useRef(externalToolMap);\n\texternalToolMapRef.current = externalToolMap;\n\tconst drawSessionStateRef = useRef(drawSessionState);\n\tdrawSessionStateRef.current = drawSessionState;\n\n\t// 보기 설정(에디터-로컬). defaultViewSettings는 초기값(seed)일 뿐, 이후 설정 팝오버가 소유.\n\t// undefined 값은 기본값을 덮어쓰지 않는다(부분 지정 seed가 brightness 등을 NaN화하는 것 방지).\n\tconst [view, setView] = useState<ViewSettings>(() => {\n\t\tconst defined = Object.fromEntries(\n\t\t\tObject.entries(defaultViewSettings ?? {}).filter(([, v]) => v !== undefined),\n\t\t) as Partial<ViewSettings>;\n\t\treturn { ...DEFAULT_VIEW_SETTINGS, ...defined };\n\t});\n\tconst updateView = useCallback(\n\t\t(patch: Partial<ViewSettings>) => setView((v) => ({ ...v, ...patch })),\n\t\t[],\n\t);\n\n\t// UI 문자열(기본 한국어 + 호스트 부분 재정의).\n\tconst S = useMemo(() => mergeEditorStrings(strings), [strings]);\n\n\t// 외부 → 에디터 동기화(viewSettings prop). 값이 실제로 다를 때만 반영해\n\t// 동기화 루프(에디터 변경 → 호스트 스토어 → prop → 에디터)를 끊는다.\n\tuseEffect(() => {\n\t\tif (!viewSettings) return;\n\t\tsetView((v) => {\n\t\t\tconst entries = Object.entries(viewSettings).filter(\n\t\t\t\t([key, value]) => value !== undefined && v[key as keyof ViewSettings] !== value,\n\t\t\t);\n\t\t\tif (!entries.length) return v;\n\t\t\treturn { ...v, ...Object.fromEntries(entries) };\n\t\t});\n\t}, [viewSettings]);\n\n\t// 에디터 → 외부 통지(onViewSettingsChange). 마운트 시드는 변경이 아니므로 건너뛴다.\n\tconst onViewSettingsChangeRef = useRef(onViewSettingsChange);\n\tonViewSettingsChangeRef.current = onViewSettingsChange;\n\tconst viewNotifiedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (!viewNotifiedRef.current) {\n\t\t\tviewNotifiedRef.current = true;\n\t\t\treturn;\n\t\t}\n\t\tonViewSettingsChangeRef.current?.(view);\n\t}, [view]);\n\n\t// 가이드 마스크 → 컬러 캔버스(렌더러 오버레이 + 미니맵 dataURL).\n\tconst maskCanvas = useMemo(() => {\n\t\tif (!guideMask || !maskPalette) return null;\n\t\treturn buildMaskCanvas(guideMask, maskPalette);\n\t}, [guideMask, maskPalette]);\n\tconst maskDataUrl = useMemo(() => maskCanvas?.toDataURL() ?? null, [maskCanvas]);\n\t// 영역 마스크 → 딤·윤곽 벡터(렌더러 오버레이용, 이미지↔도형 사이. 윤곽은 화면고정).\n\tconst regionOverlay = useMemo(() => {\n\t\t// 빈 마스크(창·가림 모두 없음) 판정은 buildRegionOverlayData가 담당한다.\n\t\tif (!image || !regionMask) return null;\n\t\treturn buildRegionOverlayData(regionMask, image.w, image.h);\n\t}, [image, regionMask]);\n\tconst maskCanvasRef = useRef(maskCanvas);\n\tmaskCanvasRef.current = maskCanvas;\n\tconst regionOverlayRef = useRef(regionOverlay);\n\tregionOverlayRef.current = regionOverlay;\n\tconst dimmedRef = useRef(dimmed);\n\tdimmedRef.current = dimmed;\n\tconst imageSizeRef = useRef(image);\n\timageSizeRef.current = image;\n\n\t// 콜백이 최신값을 읽도록 ref 미러(엔진 콜백은 init 때 1회 캡처).\n\tconst selRef = useRef<string[]>([]);\n\tselRef.current = selectedIds;\n\tconst toolRef = useRef(activeTool);\n\ttoolRef.current = activeTool;\n\tconst draftRef = useRef(draftStyle);\n\tdraftRef.current = draftStyle;\n\tconst draftMetaRef = useRef(draftMeta);\n\tdraftMetaRef.current = draftMeta;\n\tconst brushSizeRef = useRef(brushSize);\n\tbrushSizeRef.current = brushSize;\n\tconst simplifyEpsilonRef = useRef(view.simplifyStrength);\n\tsimplifyEpsilonRef.current = view.simplifyStrength;\n\t// 완료(locked) 상태는 편집 관점에서 읽기전용과 동일하다 — 포인터 편집 시도는\n\t// 컨트롤러의 locked 분기가 확인 모달로 안내하고, 단축키·우클릭 메뉴·트랜스포머 등\n\t// 나머지 변이 경로는 effectiveReadOnly로 막는다(조회·코멘트·툴바는 유지).\n\tconst effectiveReadOnly = !!readOnly || !!locked;\n\tconst readOnlyRef = useRef(effectiveReadOnly);\n\treadOnlyRef.current = effectiveReadOnly;\n\tconst disableMarqueeRef = useRef(disableMarquee);\n\tdisableMarqueeRef.current = disableMarquee;\n\tconst lockedRef = useRef(locked);\n\tlockedRef.current = locked;\n\tconst onLockedInteractionRef = useRef(onLockedInteraction);\n\tonLockedInteractionRef.current = onLockedInteraction;\n\tconst overrideInteractionRef = useRef(overrideShapeInteraction);\n\toverrideInteractionRef.current = overrideShapeInteraction;\n\tconst docRef = useRef(doc);\n\tdocRef.current = doc;\n\tconst spaceRef = useRef(false);\n\tconst shiftRef = useRef(false);\n\tconst interactionModeRef = useRef<EditorInteractionMode>(\"idle\");\n\tconst rendererCursorHintRef = useRef<string | null>(null);\n\tconst applyEditorCursor = useCallback(() => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return;\n\t\tconst tool = toolRef.current;\n\t\tconst externalTool = externalToolMapRef.current.get(tool);\n\t\tconst session = drawSessionStateRef.current;\n\t\teng.setCursor(\n\t\t\tresolveEditorCursor({\n\t\t\t\ttool,\n\t\t\t\texternalToolCursor: externalTool?.cursor,\n\t\t\t\tisSpacePressed: spaceRef.current,\n\t\t\t\tinteractionMode: interactionModeRef.current,\n\t\t\t\trendererCursorHint: rendererCursorHintRef.current,\n\t\t\t\tisPolygonDrawing: session.kind === \"polygon\" && session.active,\n\t\t\t}),\n\t\t);\n\t}, []);\n\tconst setEditorInteractionMode = useCallback(\n\t\t(mode: EditorInteractionMode) => {\n\t\t\tif (interactionModeRef.current === mode) return;\n\t\t\tinteractionModeRef.current = mode;\n\t\t\tapplyEditorCursor();\n\t\t},\n\t\t[applyEditorCursor],\n\t);\n\tconst setEditorCursorHint = useCallback(\n\t\t(cursor: string | null) => {\n\t\t\tif (rendererCursorHintRef.current === cursor) return;\n\t\t\trendererCursorHintRef.current = cursor;\n\t\t\tapplyEditorCursor();\n\t\t},\n\t\t[applyEditorCursor],\n\t);\n\tconst normalizeSelection = useCallback((ids: string[]) => {\n\t\tconst seen = new Set<string>();\n\t\tconst shapes = new Map(docRef.current.getShapes().map((s) => [s.id, s]));\n\t\treturn ids.filter((id) => {\n\t\t\tif (seen.has(id)) return false;\n\t\t\tseen.add(id);\n\t\t\tconst shape = shapes.get(id);\n\t\t\tif (!shape) return false;\n\t\t\t// 호스트 상호작용 오버라이드(숨김/비활성) 반영 — 숨겨진 도형은 선택 불가.\n\t\t\tconst ov = overrideInteractionRef.current?.(shape);\n\t\t\tconst effective = ov ? { ...shape, interaction: { ...shape.interaction, ...ov } } : shape;\n\t\t\treturn isShapeSelectable(effective);\n\t\t});\n\t}, []);\n\tconst changeSelection = useCallback(\n\t\t(ids: string[]) => {\n\t\t\tconst next = normalizeSelection(ids);\n\t\t\tif (sameSelection(selRef.current, next)) return;\n\t\t\tif (!selectionControlled) setUncontrolledSelectedIds(next);\n\t\t\tengineRef.current?.setSelection(next);\n\t\t\tonSelectionChange?.(next);\n\t\t},\n\t\t[normalizeSelection, onSelectionChange, selectionControlled],\n\t);\n\tconst selectRef = useRef(changeSelection);\n\tselectRef.current = changeSelection;\n\n\t// 폴리곤 정점 편집모드(옵스식). 더블클릭으로 진입, 툴 변경/선택 해제/Esc로 종료.\n\tconst [editingId, setEditingId] = useState<string | null>(null);\n\tconst enterEdit = useCallback((id: string) => setEditingId(id), []);\n\tconst enterEditRef = useRef(enterEdit);\n\tenterEditRef.current = enterEdit;\n\n\tuseEffect(() => {\n\t\tif (!selectionControlled) return;\n\t\tconst next = normalizeSelection(controlledSelectedIds);\n\t\tif (!sameSelection(controlledSelectedIds, next)) onSelectionChange?.(next);\n\t}, [\n\t\tcontrolledSelectedIds,\n\t\tdoc.shapes,\n\t\tnormalizeSelection,\n\t\tonSelectionChange,\n\t\tselectionControlled,\n\t]);\n\n\tconst onViewportChangeRef = useRef(onViewportChange);\n\tonViewportChangeRef.current = onViewportChange;\n\tconst { registerMinimapShape, applyMinimapPreview, syncMinimap } = useMinimapSync<TMeta>({\n\t\tengineRef,\n\t\tdocRef,\n\t\toverlayRef,\n\t\tzoomLabelRef,\n\t\tminimapRectRef,\n\t\tminimapSize: MINIMAP_SIZE,\n\t\tonViewportChangeRef,\n\t});\n\n\t// 선택 정보 배지 — 드래그/변형 중 bbox 위치·정보텍스트를 ref로 즉시 갱신(문서 커밋 전).\n\tconst selectionInfoRefs = useRef(new Map<string, HTMLDivElement>());\n\tconst formatSelectionInfoRef = useRef(formatSelectionInfo);\n\tformatSelectionInfoRef.current = formatSelectionInfo;\n\tconst registerSelectionInfo = useCallback((id: string, el: HTMLDivElement | null) => {\n\t\tif (el) selectionInfoRefs.current.set(id, el);\n\t\telse selectionInfoRefs.current.delete(id);\n\t}, []);\n\t// 그리는 중 정보 배지의 합성 도형(문서에 없음) — preview 갱신 시 lookup에 섞는다.\n\tconst drawPreviewRef = useRef<EditorShape<TMeta> | null>(null);\n\tconst [drawPreviewShape, setDrawPreviewShape] = useState<EditorShape<TMeta> | null>(null);\n\tconst applySelectionInfoPreview = useCallback((updates: { id: string; points: Point[] }[]) => {\n\t\tif (!updates.length) return;\n\t\tconst shapeMap = new Map(docRef.current.getShapes().map((s) => [s.id, s]));\n\t\tif (drawPreviewRef.current) {\n\t\t\tshapeMap.set(drawPreviewRef.current.id, drawPreviewRef.current);\n\t\t}\n\t\tfor (const { id, points } of updates) {\n\t\t\tconst el = selectionInfoRefs.current.get(id);\n\t\t\tconst shape = shapeMap.get(id);\n\t\t\tif (!el || !shape) continue;\n\t\t\tconst b = getBBox(points);\n\t\t\tel.style.left = `${b.minX}px`;\n\t\t\tel.style.top = `${b.minY}px`;\n\t\t\tel.style.width = `${b.maxX - b.minX}px`;\n\t\t\tel.style.height = `${b.maxY - b.minY}px`;\n\t\t\tconst dim = el.querySelector<HTMLElement>(\"[data-selinfo-dim]\");\n\t\t\tif (dim) {\n\t\t\t\tconst info = buildSelectionInfo(shape, points);\n\t\t\t\tdim.textContent = formatSelectionInfoRef.current?.(info) ?? defaultSelectionInfoText(info);\n\t\t\t}\n\t\t}\n\t}, []);\n\tconst handleTransformPreview = useCallback(\n\t\t(updates: { id: string; points: Point[] }[]) => {\n\t\t\tapplyMinimapPreview(updates);\n\t\t\tapplySelectionInfoPreview(updates);\n\t\t\tonShapesTransformPreview?.(updates);\n\t\t},\n\t\t[applyMinimapPreview, applySelectionInfoPreview, onShapesTransformPreview],\n\t);\n\n\t// 박스 드래그 그리는 중 정보 배지(좌상단 클래스 + 우하단 W×H). 선택 배지 오버레이를\n\t// 재사용한다: 시작/종료 때만 합성 도형을 React에 마운트/언마운트하고, 이동 중에는\n\t// 선택 배지와 동일한 ref 기반 DOM 갱신으로 위치·크기 텍스트만 즉시 반영한다.\n\tconst handleDrawPreview = useCallback(\n\t\t(info: { type: EditorShape<TMeta>[\"type\"]; points: Point[] } | null) => {\n\t\t\tonDraftShapeChange?.(info ? { ...info, meta: draftMetaRef.current } : null);\n\t\t\tif (!info || !draftRef.current) {\n\t\t\t\tif (drawPreviewRef.current) {\n\t\t\t\t\tdrawPreviewRef.current = null;\n\t\t\t\t\tsetDrawPreviewShape(null);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst shape = {\n\t\t\t\tid: DRAFT_PREVIEW_ID,\n\t\t\t\ttype: info.type,\n\t\t\t\tpoints: info.points,\n\t\t\t\tstyle: draftRef.current,\n\t\t\t\tmeta: draftMetaRef.current,\n\t\t\t} as EditorShape<TMeta>;\n\t\t\tconst wasActive = drawPreviewRef.current !== null;\n\t\t\tdrawPreviewRef.current = shape;\n\t\t\tif (wasActive) {\n\t\t\t\tapplySelectionInfoPreview([{ id: DRAFT_PREVIEW_ID, points: info.points }]);\n\t\t\t} else {\n\t\t\t\tsetDrawPreviewShape(shape);\n\t\t\t}\n\t\t},\n\t\t[applySelectionInfoPreview, onDraftShapeChange],\n\t);\n\n\tconst createShape = useCallback(\n\t\t(type: EditorShape<TMeta>[\"type\"], points: Point[]) => {\n\t\t\tconst style = draftRef.current;\n\t\t\tif (!style || readOnlyRef.current) return;\n\t\t\tconst id = generateId();\n\t\t\tdocRef.current.create({ id, type, points, style, meta: draftMeta });\n\t\t\tselectRef.current([id]);\n\t\t},\n\t\t[draftMeta],\n\t);\n\tconst createRef = useRef(createShape);\n\tcreateRef.current = createShape;\n\tconst handleDrawSessionChange = useCallback(\n\t\t(session: DrawSessionChange) => {\n\t\t\tsetDrawSessionState(session);\n\t\t\tonDrawSessionChange?.(session);\n\t\t},\n\t\t[onDrawSessionChange],\n\t);\n\n\tconst drawSession = useDrawSession<TMeta>({\n\t\ttoolRef,\n\t\tselRef,\n\t\tdocRef,\n\t\treadOnlyRef,\n\t\tdraftRef,\n\t\tbrushSizeRef,\n\t\tsimplifyEpsilonRef,\n\t\tdraftMeta,\n\t\tengineRef,\n\t\tonDrawSessionChange: handleDrawSessionChange,\n\t\tonDraftShapeChange,\n\t\tchangeSelection,\n\t\tcreateShape,\n\t});\n\t// cb(상호작용 컨트롤러)에서 쓰는 그리기 세션 메서드는 drawSessionRef로 최신값을 읽는다.\n\tconst drawSessionRef = useRef(drawSession);\n\tdrawSessionRef.current = drawSession;\n\tconst {\n\t\treset: resetDraftPath,\n\t\tundoSession,\n\t\tredoSession,\n\t\tcanUndoSession,\n\t\tcanRedoSession,\n\t\thasDraftSession,\n\t\thasDraftPoints,\n\t\tcommitDraftSession: completeDraftPath,\n\t\tsetBrushScalarMode,\n\t\tgetBrushScalarMode,\n\t\thasBrushSession: getBrushSessionActive,\n\t\tcommitBrush,\n\t\tcancelBrush,\n\t\tbeginBrushEditFromSelection,\n\t\tdeleteDraftSelectedPoints,\n\t\thandleToolChange,\n\t\thandleBrushSelectionChange,\n\t} = drawSession;\n\n\t// ── AI 어시스트 세션(호스트 assistant.infer 위임) ──\n\tconst assistantRef = useRef(assistant);\n\tassistantRef.current = assistant;\n\tconst assistantSession = useAssistant<TMeta>({\n\t\tdocRef,\n\t\tdraftRef,\n\t\tdraftMeta,\n\t\tchangeSelection,\n\t\tassistantRef,\n\t});\n\tconst assistantSessionRef = useRef(assistantSession);\n\tassistantSessionRef.current = assistantSession;\n\n\t// ── 선택 기반 액션(키보드·컨텍스트메뉴·명령형 핸들 공용) ──\n\tconst {\n\t\tselectAll,\n\t\tclearSelection,\n\t\tdeleteSelection,\n\t\tcopySelection,\n\t\tcanPaste,\n\t\tpaste,\n\t\tduplicate,\n\t\tbringToFront,\n\t\tsendToBack,\n\t\tflip,\n\t\tnudgeSelection,\n\t\tgetMergeTargets,\n\t\tmergeSelection,\n\t} = useSelectionActions<TMeta>({\n\t\tdoc,\n\t\tselRef,\n\t\teffectiveReadOnly,\n\t\tchangeSelection,\n\t\tcanMergeSelection,\n\t});\n\tconst { zoomToBounds, zoomToShapes, zoomToSelection, zoomAtCenter } = useViewportControls<TMeta>({\n\t\tengineRef,\n\t\tdoc,\n\t\tselRef,\n\t\tzoomAnimationDuration,\n\t\tzoomBound,\n\t\tready,\n\t});\n\n\t// 명령형 핸들(ShapeEditorHandle과 동일) — 데모 엔진 교체 시 그대로 동작.\n\tuseImperativeHandle(\n\t\thandleRef,\n\t\t() => ({\n\t\t\t// 드래그·드로잉 중 고빈도 프리뷰 — React 상태를 우회해 렌더러에 즉시 반영한다.\n\t\t\t// ref만 읽으므로 핸들 재생성 없이 항상 최신 컨텍스트로 동작한다.\n\t\t\tpreviewRegionMask: (mask) => {\n\t\t\t\tconst img = imageSizeRef.current;\n\t\t\t\tif (!img) return;\n\t\t\t\t// mask가 있으면 빈 판정 포함 build에 위임, null이면 prop 오버레이로 복귀.\n\t\t\t\tconst overlay = mask\n\t\t\t\t\t? buildRegionOverlayData(mask, img.w, img.h)\n\t\t\t\t\t: regionOverlayRef.current;\n\t\t\t\tengineRef.current?.setOverlays(\n\t\t\t\t\tviewRef.current.showGuide ? maskCanvasRef.current : null,\n\t\t\t\t\tviewRef.current.showRegionMask ? overlay : null,\n\t\t\t\t\tdimmedRef.current,\n\t\t\t\t);\n\t\t\t},\n\t\t\tundo: () => {\n\t\t\t\tif (!undoSession()) doc.undo();\n\t\t\t},\n\t\t\tredo: () => {\n\t\t\t\tif (!redoSession()) doc.redo();\n\t\t\t},\n\t\t\tcanUndo: () => canUndoSession() || doc.canUndo(),\n\t\t\tcanRedo: () => canRedoSession() || doc.canRedo(),\n\t\t\tundoSession,\n\t\t\tredoSession,\n\t\t\tcanUndoSession,\n\t\t\tcanRedoSession,\n\t\t\thasDraftSession,\n\t\t\tcancelDraftSession: resetDraftPath,\n\t\t\tcommitDraftSession: completeDraftPath,\n\t\t\tsetSelection: changeSelection,\n\t\t\tcreateShapes: (shapes) => {\n\t\t\t\tif (!shapes.length) return;\n\t\t\t\tdoc.create(shapes);\n\t\t\t\tchangeSelection(shapes.map((s) => s.id));\n\t\t\t},\n\t\t\tupdateShapes: doc.update,\n\t\t\tdeleteShapes: doc.remove,\n\t\t\tgetShapes: doc.getShapes,\n\t\t\tselectAll,\n\t\t\tclearSelection,\n\t\t\tdeleteSelection,\n\t\t\tcopySelection,\n\t\t\tpaste,\n\t\t\tduplicate,\n\t\t\tbringToFront,\n\t\t\tsendToBack,\n\t\t\tflipHorizontal: () => flip(true),\n\t\t\tflipVertical: () => flip(false),\n\t\t\tzoomFit: () => engineRef.current?.fit(),\n\t\t\tzoom100: () => engineRef.current?.zoom100(),\n\t\t\tzoomIn: () => {\n\t\t\t\tconst eng = engineRef.current;\n\t\t\t\tif (!eng) return;\n\t\t\t\tconst { w, h } = eng.screenSize;\n\t\t\t\teng.zoomAt(w / 2, h / 2, 1.2);\n\t\t\t},\n\t\t\tzoomOut: () => {\n\t\t\t\tconst eng = engineRef.current;\n\t\t\t\tif (!eng) return;\n\t\t\t\tconst { w, h } = eng.screenSize;\n\t\t\t\teng.zoomAt(w / 2, h / 2, 1 / 1.2);\n\t\t\t},\n\t\t\tzoomToSelection,\n\t\t\tzoomToShapes,\n\t\t\tzoomToBounds,\n\t\t\tbrush: {\n\t\t\t\tsetScalarMode: setBrushScalarMode,\n\t\t\t\tgetScalarMode: getBrushScalarMode,\n\t\t\t\thasSession: getBrushSessionActive,\n\t\t\t\tcommit: commitBrush,\n\t\t\t\tcancel: cancelBrush,\n\t\t\t\tbeginEditFromSelection: beginBrushEditFromSelection,\n\t\t\t},\n\t\t}),\n\t\t[\n\t\t\tdoc,\n\t\t\tchangeSelection,\n\t\t\tundoSession,\n\t\t\tredoSession,\n\t\t\tcompleteDraftPath,\n\t\t\tresetDraftPath,\n\t\t\tcommitBrush,\n\t\t\tcancelBrush,\n\t\t\tselectAll,\n\t\t\tclearSelection,\n\t\t\tdeleteSelection,\n\t\t\tcopySelection,\n\t\t\tpaste,\n\t\t\tduplicate,\n\t\t\tbringToFront,\n\t\t\tsendToBack,\n\t\t\tflip,\n\t\t\tzoomToSelection,\n\t\t\tzoomToShapes,\n\t\t\tzoomToBounds,\n\t\t\tsetBrushScalarMode,\n\t\t\tgetBrushScalarMode,\n\t\t\tgetBrushSessionActive,\n\t\t\tbeginBrushEditFromSelection,\n\t\t],\n\t);\n\n\tconst viewRef = useRef(view);\n\tviewRef.current = view;\n\n\t// 엔진 생명주기 — backend당 1회 생성, 이미지 전환/화질 스왑, 휠 줌·우클릭 리스너,\n\t// 이미지 로딩 상태 프리로드. 상호작용 컨트롤러는 엔진 생성 직전 팩토리로 만든다.\n\tconst makeRendererCallbacks = useCallback(\n\t\t() =>\n\t\t\tcreateInteractionController<TMeta>({\n\t\t\t\tengineRef,\n\t\t\t\ttoolRef,\n\t\t\t\texternalToolMapRef,\n\t\t\t\tspaceRef,\n\t\t\t\tshiftRef,\n\t\t\t\tdocRef,\n\t\t\t\tselRef,\n\t\t\t\tdraftRef,\n\t\t\t\treadOnlyRef,\n\t\t\t\tdisableMarqueeRef,\n\t\t\t\tlockedRef,\n\t\t\t\tonLockedInteraction: () => onLockedInteractionRef.current?.(),\n\t\t\t\tcreateRef,\n\t\t\t\tselectRef,\n\t\t\t\tenterEditRef,\n\t\t\t\tdrawSessionRef,\n\t\t\t\tassistantRef: assistantSessionRef,\n\t\t\t\tsetCursorHint: setEditorCursorHint,\n\t\t\t\tsetInteractionMode: setEditorInteractionMode,\n\t\t\t\tsyncMinimap,\n\t\t\t\tonTransformPreview: handleTransformPreview,\n\t\t\t\tonDrawPreview: handleDrawPreview,\n\t\t\t}),\n\t\t[\n\t\t\tsetEditorCursorHint,\n\t\t\tsetEditorInteractionMode,\n\t\t\tsyncMinimap,\n\t\t\thandleTransformPreview,\n\t\t\thandleDrawPreview,\n\t\t],\n\t);\n\t// renderShapes 메모(아래)보다 먼저 선언 — 라이프사이클 훅이 ref 객체만 캡처하고\n\t// .current는 이펙트 시점에 읽으므로 렌더 후반 대입으로 충분하다.\n\tconst renderShapesRef = useRef<EditorShape<TMeta>[]>([]);\n\tuseEngineLifecycle<TMeta>({\n\t\tbackend,\n\t\thostRef,\n\t\tengineRef,\n\t\timageUrl,\n\t\trenderedImageUrl,\n\t\tmakeCallbacks: makeRendererCallbacks,\n\t\tviewRef,\n\t\treadOnlyRef,\n\t\ttoolRef,\n\t\trenderShapesRef,\n\t\tselRef,\n\t\tmaskCanvasRef,\n\t\tregionOverlayRef,\n\t\tdimmedRef,\n\t\tsyncMinimap,\n\t\tsetImage,\n\t\tsetImageVisible,\n\t\tsetReady,\n\t\tsetImageStatus,\n\t\tonContextMenuRequest: setMenu,\n\t});\n\n\t// 렌더 시점 상호작용 오버라이드 적용본. 문서(undo 히스토리)는 불변으로 두고\n\t// 엔진/미니맵/선택배지에만 반영한다 — 가시성 토글이 undo에 안 섞이게.\n\t// 장식 도형(decorationShapes)도 여기서만 합류한다 — 문서 밖이라 히스토리·선택·\n\t// getShapes에 안 섞이고, 상호작용은 강제로 잠근다.\n\tconst renderShapes = useMemo(() => {\n\t\tconst docShapes = !overrideShapeInteraction\n\t\t\t? doc.shapes\n\t\t\t: doc.shapes.map((s) => {\n\t\t\t\t\tconst ov = overrideShapeInteraction(s);\n\t\t\t\t\treturn ov ? { ...s, interaction: { ...s.interaction, ...ov } } : s;\n\t\t\t\t});\n\t\tif (!decorationShapes?.length) return docShapes;\n\t\tconst decorations = decorationShapes.map((s) => ({\n\t\t\t...s,\n\t\t\tinteraction: {\n\t\t\t\t...s.interaction,\n\t\t\t\tselectable: false,\n\t\t\t\tdraggable: false,\n\t\t\t\teditable: false,\n\t\t\t\thitTestDisabled: true,\n\t\t\t},\n\t\t}));\n\t\treturn [...decorations, ...docShapes];\n\t}, [doc.shapes, overrideShapeInteraction, decorationShapes]);\n\trenderShapesRef.current = renderShapes;\n\n\t// 문서/선택 변경 → 엔진 재렌더.\n\tuseEffect(() => {\n\t\tengineRef.current?.setShapes(renderShapes, selectedIds);\n\t\tsyncMinimap();\n\t}, [renderShapes, selectedIds, syncMinimap]);\n\n\t// 폴리곤 편집모드 → 엔진 반영.\n\tuseEffect(() => {\n\t\tengineRef.current?.setEditing(editingId);\n\t}, [editingId, ready]);\n\n\t// 편집모드 진입/해제 통지(호스트 안내 툴바용).\n\tconst onEditingChangeRef = useRef(onEditingChange);\n\tonEditingChangeRef.current = onEditingChange;\n\tuseEffect(() => {\n\t\tonEditingChangeRef.current?.(editingId);\n\t}, [editingId]);\n\n\t// 툴이 바뀌면 편집모드 해제.\n\tuseEffect(() => {\n\t\tsetEditingId(null);\n\t}, [activeTool]);\n\n\t// 선택이 편집 대상 단일 폴리곤이 아니게 되면 편집모드 해제.\n\tuseEffect(() => {\n\t\tif (editingId && (selectedIds.length !== 1 || selectedIds[0] !== editingId)) {\n\t\t\tsetEditingId(null);\n\t\t}\n\t}, [selectedIds, editingId]);\n\n\t// 보기 설정(밝기·대비·선두께·픽셀화)을 엔진에 동기. 각 setter는 값이 같으면 no-op.\n\tuseEffect(() => {\n\t\tconst eng = engineRef.current;\n\t\tif (!eng) return;\n\t\teng.setFilter(view.brightness, view.contrast);\n\t\teng.setStrokeSize(view.strokeSize);\n\t\teng.setImageSmoothing(view.imageSmoothing);\n\t\tsyncMinimap();\n\t}, [view.brightness, view.contrast, view.strokeSize, view.imageSmoothing, syncMinimap]);\n\n\t// ROI 딤·가이드 마스크를 렌더러 오버레이(이미지↔도형 사이)에 반영.\n\t// useLayoutEffect — 드래그 중 regionMask가 호스트 왕복으로 프레임마다 갱신되는데,\n\t// useEffect(페인트 후)면 도형·핸들보다 오버레이가 한 프레임 늦게 따라온다.\n\t// 페인트 전에 렌더러에 반영해 같은 프레임의 렌더 틱에 함께 태운다.\n\tuseLayoutEffect(() => {\n\t\tif (!ready) return;\n\t\tengineRef.current?.setOverlays(\n\t\t\tview.showGuide ? maskCanvas : null,\n\t\t\tview.showRegionMask ? regionOverlay : null,\n\t\t\tdimmed,\n\t\t);\n\t}, [ready, maskCanvas, regionOverlay, view.showGuide, view.showRegionMask, dimmed]);\n\n\tuseEffect(() => {\n\t\tif (!ready || !image) return;\n\t\tsyncMinimap();\n\t}, [ready, image, maskDataUrl, view.showGuide, view.showRegionMask, regionMask, syncMinimap]);\n\n\tuseEffect(() => {\n\t\tif (!ready) return;\n\t\tengineRef.current?.setTransformEnabled(!effectiveReadOnly && activeTool !== TOOL.BRUSH);\n\t}, [effectiveReadOnly, ready, activeTool]);\n\n\tuseEffect(() => {\n\t\thandleToolChange(activeTool, externalToolMap.has(activeTool));\n\t}, [activeTool, externalToolMap, handleToolChange]);\n\n\t// 도구가 바뀌면 어시스트 세션을 확정(만든 도형은 유지, 프롬프트 마커만 정리).\n\t// 어시스트 도구 사이(박스↔포인트) 전환도 새 세션으로 시작하도록 매번 확정한다.\n\tconst finalizeAssistant = assistantSession.finalize;\n\tuseEffect(() => {\n\t\tfinalizeAssistant();\n\t}, [activeTool, finalizeAssistant]);\n\n\tuseEffect(() => {\n\t\tinteractionModeRef.current = \"idle\";\n\t\trendererCursorHintRef.current = null;\n\t\tapplyEditorCursor();\n\t}, [activeTool, backend, applyEditorCursor]);\n\n\tuseEffect(() => {\n\t\thandleBrushSelectionChange(selectedIds, effectiveReadOnly);\n\t}, [selectedIds, activeTool, effectiveReadOnly, handleBrushSelectionChange]);\n\n\tuseEffect(() => {\n\t\tif (!ready) return;\n\t\tapplyEditorCursor();\n\t}, [activeTool, drawSessionState, externalToolMap, ready, applyEditorCursor]);\n\n\t// 초기 시드.\n\tconst seedRef = useRef<string | null>(null);\n\tuseEffect(() => {\n\t\tif (seedRef.current === imageUrl) return;\n\t\tseedRef.current = imageUrl;\n\t\tdoc.reset(initialShapes ?? []);\n\t\tchangeSelection([]);\n\t\tresetDraftPath();\n\t\tfinalizeAssistant();\n\t}, [imageUrl, initialShapes, doc.reset, changeSelection, resetDraftPath, finalizeAssistant]);\n\n\t// ── 키보드 단축키(기본 내장 + keymap prop으로 재정의/비활성) ──\n\tconst hotkeyActions: EditorActionHandlers = {\n\t\tundo: () => {\n\t\t\tif (effectiveReadOnly) return;\n\t\t\tif (!undoSession()) doc.undo();\n\t\t},\n\t\tredo: () => {\n\t\t\tif (effectiveReadOnly) return;\n\t\t\tif (!redoSession()) doc.redo();\n\t\t},\n\t\tselectAll,\n\t\tcopy: copySelection,\n\t\tcut: () => {\n\t\t\tcopySelection();\n\t\t\tdeleteSelection();\n\t\t},\n\t\tpaste,\n\t\tduplicate,\n\t\tdelete: () => {\n\t\t\tif (hasDraftPoints() && deleteDraftSelectedPoints()) return;\n\t\t\tdeleteSelection();\n\t\t},\n\t\tcancel: () => {\n\t\t\t// 외부 툴이 소비하면 종료, false(취소할 것 없음)면 아래 사슬로 계속.\n\t\t\tconst externalTool = externalToolMapRef.current.get(toolRef.current);\n\t\t\tif (externalTool?.onCancel && externalTool.onCancel() !== false) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (assistantSession.isActive()) {\n\t\t\t\tassistantSession.cancel();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (hasDraftSession()) {\n\t\t\t\tresetDraftPath();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (editingId) {\n\t\t\t\tsetEditingId(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (selRef.current.length) {\n\t\t\t\tclearSelection();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// 취소할 것이 없음 — 호스트 후속 동작(툴 복귀/에디터 닫기, 옵스 Esc 사슬 꼬리).\n\t\t\tonIdleEscape?.();\n\t\t},\n\t\tcommitDraft: () => {\n\t\t\tif (assistantSession.isActive()) {\n\t\t\t\tassistantSession.finalize();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (hasDraftSession()) {\n\t\t\t\tcompleteDraftPath();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// 옵스식 Enter: 그리기 중이 아니면 폴리곤 편집모드 완료/시작 토글.\n\t\t\tif (effectiveReadOnly) return;\n\t\t\tif (editingId) {\n\t\t\t\tsetEditingId(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sel = selRef.current;\n\t\t\tif (sel.length !== 1) return;\n\t\t\tconst shape = docRef.current.getShapes().find((s) => s.id === sel[0]);\n\t\t\tconst editable =\n\t\t\t\tshape &&\n\t\t\t\t(shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE) &&\n\t\t\t\tshape.interaction?.editable !== false &&\n\t\t\t\t!shape.readOnly;\n\t\t\tif (editable) setEditingId(sel[0]);\n\t\t},\n\t\tbringToFront,\n\t\tsendToBack,\n\t\tflipHorizontal: () => flip(true),\n\t\tflipVertical: () => flip(false),\n\t\tzoomIn: () => zoomAtCenter(1.2),\n\t\tzoomOut: () => zoomAtCenter(1 / 1.2),\n\t\tzoom100: () => engineRef.current?.zoom100(),\n\t\tzoomFit: () => engineRef.current?.fit(),\n\t\ttoggleMinimap: () => setMinimapOpen((o) => !o),\n\t\ttoggleCursorGuide: () => setView((v) => ({ ...v, showCursorGuide: !v.showCursorGuide })),\n\t\ttogglePixelation: () => setView((v) => ({ ...v, imageSmoothing: !v.imageSmoothing })),\n\t\tselectTool: () => onActiveToolChange?.(TOOL.SELECT),\n\t\trectangleTool: () => onActiveToolChange?.(TOOL.RECTANGLE),\n\t\trotatedRectangleTool: () => onActiveToolChange?.(TOOL.ROTATED_RECTANGLE),\n\t\tcircleTool: () => onActiveToolChange?.(TOOL.CIRCLE),\n\t\tpolygonTool: () => onActiveToolChange?.(TOOL.POLYGON),\n\t\tpathTool: () => onActiveToolChange?.(TOOL.PATH),\n\t\tbrushTool: () => onActiveToolChange?.(TOOL.BRUSH),\n\t\tpointTool: () => onActiveToolChange?.(TOOL.POINT),\n\t};\n\tuseEditorHotkeys({\n\t\tkeymap,\n\t\thostRef,\n\t\tactions: hotkeyActions,\n\t\tspaceRef,\n\t\tshiftRef,\n\t\tonSpaceDown: () => {\n\t\t\t// 스페이스=무조건 팬: 핸들 히트테스트를 꺼 트랜스포머 위 클릭도 팬으로 흐르게.\n\t\t\tengineRef.current?.setPanMode(true);\n\t\t\tapplyEditorCursor();\n\t\t},\n\t\tonSpaceUp: () => {\n\t\t\tengineRef.current?.setPanMode(false);\n\t\t\tif (interactionModeRef.current === \"panning\") {\n\t\t\t\tsetEditorInteractionMode(\"idle\");\n\t\t\t} else {\n\t\t\t\tapplyEditorCursor();\n\t\t\t}\n\t\t},\n\t\tnudge: nudgeSelection,\n\t});\n\n\t// 선택 정보 배지 대상(선택 && 표시 중인 도형 — 오버라이드 반영).\n\tconst selectedShapes = useMemo(\n\t\t() => renderShapes.filter((s) => selectedIds.includes(s.id) && isShapeVisible(s)),\n\t\t[renderShapes, selectedIds],\n\t);\n\t// 선택 배지 + 그리는 중 미리보기 배지(합성 도형)를 같은 오버레이로 렌더.\n\tconst selectionInfoShapes = useMemo(\n\t\t() => (drawPreviewShape ? [...selectedShapes, drawPreviewShape] : selectedShapes),\n\t\t[selectedShapes, drawPreviewShape],\n\t);\n\n\t// 컨텍스트 메뉴 항목.\n\tconst hasSel = selectedIds.length > 0;\n\tconst hasEditableSel = doc.shapes.some(\n\t\t(shape) => selectedIds.includes(shape.id) && isShapeEditable(shape),\n\t);\n\t// 정점 편집 진입 가능 여부(단일 폴리곤/라인 선택, 편집 가능).\n\tconst editableSinglePoly =\n\t\t!effectiveReadOnly &&\n\t\tselectedIds.length === 1 &&\n\t\t(() => {\n\t\t\tconst s = doc.shapes.find((shape) => shape.id === selectedIds[0]);\n\t\t\treturn (\n\t\t\t\t!!s &&\n\t\t\t\t(s.type === SHAPE_TYPE.POLYGON || s.type === SHAPE_TYPE.LINE) &&\n\t\t\t\ts.interaction?.editable !== false &&\n\t\t\t\t!s.readOnly\n\t\t\t);\n\t\t})();\n\t// 합치기/어시스트 refine 가용성(메뉴 열릴 때 평가).\n\tconst mergeTargets = getMergeTargets();\n\tconst mergeDisabled =\n\t\teffectiveReadOnly ||\n\t\tmergeTargets.length < 2 ||\n\t\t(canMergeSelection ? !canMergeSelection(mergeTargets) : false);\n\tconst assistRefineTarget =\n\t\tassistant && !effectiveReadOnly && selectedIds.length === 1\n\t\t\t? (() => {\n\t\t\t\t\tconst s = doc.shapes.find((shape) => shape.id === selectedIds[0]);\n\t\t\t\t\treturn s &&\n\t\t\t\t\t\ts.type === SHAPE_TYPE.POLYGON &&\n\t\t\t\t\t\ts.interaction?.editable !== false &&\n\t\t\t\t\t\t!s.readOnly\n\t\t\t\t\t\t? s\n\t\t\t\t\t\t: null;\n\t\t\t\t})()\n\t\t\t: null;\n\tconst defaultMenuItems: ContextMenuItem[] = [\n\t\t{\n\t\t\tid: \"copy\",\n\t\t\tlabel: S.contextMenu.copy,\n\t\t\tshortcut: \"⌘C\",\n\t\t\tdisabled: !hasSel,\n\t\t\tonClick: copySelection,\n\t\t},\n\t\t{\n\t\t\tid: \"paste\",\n\t\t\tlabel: S.contextMenu.paste,\n\t\t\tshortcut: \"⌘V\",\n\t\t\tdisabled: effectiveReadOnly || !canPaste(),\n\t\t\tonClick: paste,\n\t\t},\n\t\t{\n\t\t\tid: \"duplicate\",\n\t\t\tlabel: S.contextMenu.duplicate,\n\t\t\tshortcut: \"⌘D\",\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: duplicate,\n\t\t},\n\t\t{\n\t\t\tid: \"delete\",\n\t\t\tlabel: S.contextMenu.delete,\n\t\t\tshortcut: \"Del\",\n\t\t\tdanger: true,\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: deleteSelection,\n\t\t},\n\t\t{ separator: true },\n\t\t{\n\t\t\tid: \"editVertices\",\n\t\t\tlabel: S.contextMenu.editVertices,\n\t\t\tshortcut: \"Enter\",\n\t\t\tdisabled: !editableSinglePoly,\n\t\t\tonClick: () => setEditingId(selectedIds[0]),\n\t\t},\n\t\t{\n\t\t\tid: \"merge\",\n\t\t\tlabel: S.contextMenu.merge,\n\t\t\tdisabled: mergeDisabled,\n\t\t\tonClick: mergeSelection,\n\t\t},\n\t\t{\n\t\t\tid: \"assistExpand\",\n\t\t\tlabel: S.contextMenu.assistExpand,\n\t\t\ticon: <MagicWandIcon size={14} />,\n\t\t\tdisabled: !assistRefineTarget,\n\t\t\tonClick: () => {\n\t\t\t\tif (menu && assistRefineTarget)\n\t\t\t\t\tassistantSession.refineShape(assistRefineTarget, menu.img, true);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"assistExclude\",\n\t\t\tlabel: S.contextMenu.assistExclude,\n\t\t\ticon: <MagicWandIcon size={14} />,\n\t\t\tdisabled: !assistRefineTarget,\n\t\t\tonClick: () => {\n\t\t\t\tif (menu && assistRefineTarget)\n\t\t\t\t\tassistantSession.refineShape(assistRefineTarget, menu.img, false);\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"bringToFront\",\n\t\t\tlabel: S.contextMenu.bringToFront,\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: bringToFront,\n\t\t},\n\t\t{\n\t\t\tid: \"sendToBack\",\n\t\t\tlabel: S.contextMenu.sendToBack,\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: sendToBack,\n\t\t},\n\t\t{\n\t\t\tid: \"flipHorizontal\",\n\t\t\tlabel: S.contextMenu.flipHorizontal,\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: () => flip(true),\n\t\t},\n\t\t{\n\t\t\tid: \"flipVertical\",\n\t\t\tlabel: S.contextMenu.flipVertical,\n\t\t\tdisabled: !hasEditableSel || effectiveReadOnly,\n\t\t\tonClick: () => flip(false),\n\t\t},\n\t\t{ separator: true },\n\t\t{\n\t\t\tid: \"undo\",\n\t\t\tlabel: S.contextMenu.undo,\n\t\t\tshortcut: \"⌘Z\",\n\t\t\tdisabled: effectiveReadOnly || (!canUndoSession() && !doc.canUndo()),\n\t\t\tonClick: () => {\n\t\t\t\tif (!undoSession()) doc.undo();\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: \"redo\",\n\t\t\tlabel: S.contextMenu.redo,\n\t\t\tshortcut: \"⇧⌘Z\",\n\t\t\tdisabled: effectiveReadOnly || (!canRedoSession() && !doc.canRedo()),\n\t\t\tonClick: () => {\n\t\t\t\tif (!redoSession()) doc.redo();\n\t\t\t},\n\t\t},\n\t\t{ separator: true },\n\t\t{ id: \"selectAll\", label: S.contextMenu.selectAll, shortcut: \"⌘A\", onClick: selectAll },\n\t\t{\n\t\t\tid: \"clearSelection\",\n\t\t\tlabel: S.contextMenu.clearSelection,\n\t\t\tdisabled: !hasSel,\n\t\t\tonClick: clearSelection,\n\t\t},\n\t\t{\n\t\t\tid: \"zoomToSelection\",\n\t\t\tlabel: S.contextMenu.zoomToSelection,\n\t\t\tdisabled: !hasSel,\n\t\t\tonClick: zoomToSelection,\n\t\t},\n\t];\n\t// 호스트가 도메인 액션(예: 클래스 변경)을 추가/제거할 수 있는 확장 지점.\n\tconst menuItems = getContextMenuItems\n\t\t? getContextMenuItems(defaultMenuItems, {\n\t\t\t\tselectedIds,\n\t\t\t\treadOnly: effectiveReadOnly,\n\t\t\t})\n\t\t: defaultMenuItems;\n\n\tconst minimapNav = useMinimapNavigation({\n\t\tengineRef,\n\t\timage,\n\t\twheelZoom: view.wheelZoom,\n\t\tminimapSize: MINIMAP_SIZE,\n\t});\n\n\treturn (\n\t\t<div className=\"aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black\">\n\t\t\t{/* 숨길 땐 즉시(transition 없음), 나타날 땐 잔잔한 페이드인. */}\n\t\t\t<div\n\t\t\t\tref={hostRef}\n\t\t\t\tclassName=\"aivex:h-full aivex:w-full\"\n\t\t\t\tstyle={{\n\t\t\t\t\topacity: imageVisible ? 1 : 0,\n\t\t\t\t\ttransition: imageVisible ? \"opacity 0.3s ease\" : \"none\",\n\t\t\t\t}}\n\t\t\t/>\n\n\t\t\t{/* 이미지 로딩/에러 상태 오버레이. */}\n\t\t\t{imageStatus !== \"ready\" && (\n\t\t\t\t<ImageStateOverlay\n\t\t\t\t\tstatus={imageStatus}\n\t\t\t\t\trender={renderImageState}\n\t\t\t\t\tloadingLabel={S.imageLoading}\n\t\t\t\t\terrorLabel={S.imageLoadError}\n\t\t\t\t/>\n\t\t\t)}\n\n\t\t\t{/* 캔버스 위 ROI/제외영역/가이드마스크 오버레이(뷰포트 동기, 렌더러 무관). */}\n\t\t\t{ready && image && (\n\t\t\t\t<div className=\"aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tref={overlayRef}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\ttop: 0,\n\t\t\t\t\t\t\tleft: 0,\n\t\t\t\t\t\t\twidth: image.w,\n\t\t\t\t\t\t\theight: image.h,\n\t\t\t\t\t\t\ttransformOrigin: \"0 0\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{/* ROI 딤·가이드 마스크는 렌더러 오버레이(이미지↔도형 사이)에서 그린다.\n 여기(도형 위 DOM)에는 마커/선택정보/어시스트만 둔다. */}\n\t\t\t\t\t\t{!!overlayMarkers?.length && renderOverlayMarker && (\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\t\tleft: 0,\n\t\t\t\t\t\t\t\t\ttop: 0,\n\t\t\t\t\t\t\t\t\twidth: image.w,\n\t\t\t\t\t\t\t\t\theight: image.h,\n\t\t\t\t\t\t\t\t\tpointerEvents: \"none\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{overlayMarkers.map((marker) => (\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tkey={marker.id}\n\t\t\t\t\t\t\t\t\t\trole={marker.disabled ? undefined : \"button\"}\n\t\t\t\t\t\t\t\t\t\ttabIndex={marker.disabled ? undefined : 0}\n\t\t\t\t\t\t\t\t\t\taria-pressed={marker.selected || undefined}\n\t\t\t\t\t\t\t\t\t\tonPointerDown={(e) => e.stopPropagation()}\n\t\t\t\t\t\t\t\t\t\tonClick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\tif (!marker.disabled) onOverlayMarkerClick?.(marker);\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tonKeyDown={(e) => {\n\t\t\t\t\t\t\t\t\t\t\tif (marker.disabled) return;\n\t\t\t\t\t\t\t\t\t\t\tif (e.key !== \"Enter\" && e.key !== \" \") return;\n\t\t\t\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\tonOverlayMarkerClick?.(marker);\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t\t\tposition: \"absolute\",\n\t\t\t\t\t\t\t\t\t\t\tleft: marker.point.x,\n\t\t\t\t\t\t\t\t\t\t\ttop: marker.point.y,\n\t\t\t\t\t\t\t\t\t\t\t// topLeft: 앵커점을 콘텐츠 원점(0,0)에 두고 그 점 기준으로 스케일.\n\t\t\t\t\t\t\t\t\t\t\t// center(기본): 콘텐츠 중앙을 앵커점에 맞춘다.\n\t\t\t\t\t\t\t\t\t\t\ttransform:\n\t\t\t\t\t\t\t\t\t\t\t\tmarker.anchor === \"topLeft\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t? \"scale(var(--editor-overlay-inverse-scale, 1))\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t: \"translate(-50%, -50%) scale(var(--editor-overlay-inverse-scale, 1))\",\n\t\t\t\t\t\t\t\t\t\t\ttransformOrigin: marker.anchor === \"topLeft\" ? \"0 0\" : \"center\",\n\t\t\t\t\t\t\t\t\t\t\t// 선택된 마커(열린 패널 포함)는 다른 마커 위에 — DOM 순서상\n\t\t\t\t\t\t\t\t\t\t\t// 뒤 마커가 앞 마커의 패널을 덮는 것을 방지.\n\t\t\t\t\t\t\t\t\t\t\tzIndex: marker.selected ? 1 : undefined,\n\t\t\t\t\t\t\t\t\t\t\tpointerEvents: marker.disabled ? \"none\" : \"auto\",\n\t\t\t\t\t\t\t\t\t\t\tcursor: marker.disabled ? \"default\" : \"pointer\",\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{renderOverlayMarker(marker)}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{renderImageOverlay?.({\n\t\t\t\t\t\t\timage,\n\t\t\t\t\t\t\tviewport: engineRef.current?.viewport ?? { scale: 1, x: 0, y: 0 },\n\t\t\t\t\t\t})}\n\t\t\t\t\t\t{selectionInfoShapes.length > 0 && (\n\t\t\t\t\t\t\t<SelectionInfo\n\t\t\t\t\t\t\t\tshapes={selectionInfoShapes}\n\t\t\t\t\t\t\t\tgetLabel={getSelectionLabel}\n\t\t\t\t\t\t\t\thideDot={hideSelectionLabelDot}\n\t\t\t\t\t\t\t\tformatInfo={formatSelectionInfo}\n\t\t\t\t\t\t\t\tregister={registerSelectionInfo}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{/* 어시스트 오버레이(+/− 마커·박스 shimmer·스피너)는 추론 진행 중에만\n 표시한다(포인트 세션 loading 또는 병렬 박스 요청 pending). 옵스는\n processingBoundingBoxes(진행 중에만 채워짐)로 그렸으므로, 추론이\n 끝나면 마커/shimmer가 남지 않아야 한다. */}\n\t\t\t\t\t\t{assistant &&\n\t\t\t\t\t\t\t(assistantSession.status === \"loading\" || assistantSession.boxes.length > 0) && (\n\t\t\t\t\t\t\t\t<AssistantOverlay\n\t\t\t\t\t\t\t\t\timage={image}\n\t\t\t\t\t\t\t\t\tpoints={assistantSession.points}\n\t\t\t\t\t\t\t\t\tboxes={assistantSession.boxes}\n\t\t\t\t\t\t\t\t\tstatus={assistantSession.status}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{/* 커서 가이드라인. */}\n\t\t\t{ready && view.showCursorGuide && <CursorGuide color=\"#1e88e5\" />}\n\n\t\t\t{/* 미니맵(좌하단) + 줌 컨트롤 바 + 설정 팝오버. */}\n\t\t\t{ready && image && showMinimap && (\n\t\t\t\t<Minimap\n\t\t\t\t\timage={image}\n\t\t\t\t\timageUrl={renderedImageUrl}\n\t\t\t\t\timageVisible={imageVisible}\n\t\t\t\t\tmaskDataUrl={maskDataUrl}\n\t\t\t\t\tregion={regionOverlay}\n\t\t\t\t\troiMaskId={minimapRoiMaskId}\n\t\t\t\t\tshapes={renderShapes}\n\t\t\t\t\tview={view}\n\t\t\t\t\tonChangeView={updateView}\n\t\t\t\t\tnav={minimapNav}\n\t\t\t\t\tregisterShape={registerMinimapShape}\n\t\t\t\t\trectRef={minimapRectRef}\n\t\t\t\t\tzoomLabelRef={zoomLabelRef}\n\t\t\t\t\tonZoom100={() => engineRef.current?.zoom100()}\n\t\t\t\t\topen={minimapOpen}\n\t\t\t\t\tonToggleOpen={() => setMinimapOpen((o) => !o)}\n\t\t\t\t\tlabels={S.minimap}\n\t\t\t\t\tsettingsLabels={S.viewSettings}\n\t\t\t\t\tshowSettings={showViewSettings}\n\t\t\t\t\tsettingsOpen={settingsOpen}\n\t\t\t\t\tonToggleSettings={() => setSettingsOpen((o) => !o)}\n\t\t\t\t\tonCloseSettings={() => setSettingsOpen(false)}\n\t\t\t\t/>\n\t\t\t)}\n\n\t\t\t{menu && (\n\t\t\t\t<ContextMenu x={menu.x} y={menu.y} items={menuItems} onClose={() => setMenu(null)} />\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","\"use client\";\n\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n\ttype EditorShape,\n\tgetBBox,\n\ttype Point,\n\tSHAPE_TYPE,\n\tsortShapesForRender,\n} from \"./_model/geometry\";\nimport { fetchImageObjectUrl } from \"./_model/imageFetch\";\nimport {\n\tbuildMaskCanvas,\n\tbuildRegionOverlayData,\n\tdrawRegionDim,\n\ttype GuideMaskRaster,\n\ttype MaskPalette,\n\ttype RegionMask,\n\ttype ResolvedRegionOutlineStyle,\n} from \"./_model/overlays\";\nimport { resolveShapeRenderStyle } from \"./_model/shapeRenderStyle\";\n\n/**\n * ShapeViewer가 지원하는 EditorShape **표시 서브셋 계약**:\n * - 도형: POINT / RECTANGLE / ELLIPSE / POLYGON / LINE / ROTATED_RECTANGLE(꼭짓점 배열)\n * - 스타일: color·alternateColor·strokeWidth·dash·opacity·filled·fillOpacity·\n * pointRadius·zIndex, readOnly 줄무늬 — 에디터 렌더러와 같은 의미\n * (resolveShapeRenderStyle 공유)로 그린다.\n * - 상호작용·선택·핸들·마커 등 편집 표현은 렌더링하지 않는다(interaction.visible만 존중).\n */\nexport interface ShapeViewerProps<TMeta = unknown> {\n\timageUrl: string;\n\talt?: string;\n\t/** 도형 좌표계 크기. 썸네일 이미지의 실제 픽셀 크기와 다를 때 지정한다. */\n\tcoordinateSize?: { width: number; height: number };\n\tshapes?: EditorShape<TMeta>[];\n\tregionMask?: RegionMask;\n\tguideMask?: GuideMaskRaster | null;\n\tmaskPalette?: MaskPalette;\n\t/** 지정한 도형이 화면을 채우도록 확대한다. */\n\tfocusedShapeId?: string;\n\t/**\n\t * 포커스 줌 시 이미지 밖 여백 처리. \"cover\"면 이미지가 항상 컨테이너를\n\t * 가득 채우도록 배율을 올리고 오프셋을 이미지 안쪽으로 클램프한다(썸네일용).\n\t */\n\tfocusFit?: \"contain\" | \"cover\";\n\tzoomPadding?: number;\n\tstrokeSize?: number;\n\tbrightness?: number;\n\tcontrast?: number;\n\timageSmoothing?: boolean;\n\tlazy?: boolean;\n\tclassName?: string;\n\tstyle?: CSSProperties;\n\trenderImageState?: (status: \"loading\" | \"error\") => ReactNode;\n}\n\ntype LoadedImage = {\n\timage: HTMLImageElement;\n\trevoke: (() => void) | null;\n};\n\nasync function loadImage(url: string): Promise<LoadedImage> {\n\tconst objectUrl = await fetchImageObjectUrl(url);\n\n\treturn await new Promise<LoadedImage>((resolve, reject) => {\n\t\tconst image = new Image();\n\t\tif (!objectUrl) image.crossOrigin = \"anonymous\";\n\t\timage.onload = () =>\n\t\t\tresolve({\n\t\t\t\timage,\n\t\t\t\trevoke: objectUrl ? () => URL.revokeObjectURL(objectUrl) : null,\n\t\t\t});\n\t\timage.onerror = () => {\n\t\t\tif (objectUrl) URL.revokeObjectURL(objectUrl);\n\t\t\treject(new Error(\"Failed to load image\"));\n\t\t};\n\t\timage.src = objectUrl ?? url;\n\t});\n}\n\nfunction tracePoints(\n\tctx: CanvasRenderingContext2D,\n\tpoints: { x: number; y: number }[],\n\tclosed: boolean,\n) {\n\tif (points.length === 0) return;\n\tctx.beginPath();\n\tctx.moveTo(points[0].x, points[0].y);\n\tfor (let index = 1; index < points.length; index += 1) {\n\t\tctx.lineTo(points[index].x, points[index].y);\n\t}\n\tif (closed) ctx.closePath();\n}\n\n// 스타일 해석은 에디터 렌더러(Konva/Pixi)와 공유(resolveShapeRenderStyle) —\n// 썸네일과 편집기의 표현이 어긋나지 않게 한다. 도형 경로만 이 파일 소유.\nfunction drawShape(\n\tctx: CanvasRenderingContext2D,\n\tshape: EditorShape,\n\tviewportScale: number,\n\tdefaultStrokeSize: number,\n) {\n\tif (shape.interaction?.visible === false) return;\n\tconst style = resolveShapeRenderStyle(shape, {\n\t\tstrokeWidth: defaultStrokeSize,\n\t\tpointRadius: 2,\n\t});\n\tctx.save();\n\tctx.globalAlpha = style.opacity;\n\tctx.lineWidth = style.strokeWidth / viewportScale;\n\tctx.lineJoin = \"round\";\n\tctx.lineCap = \"round\";\n\n\tif (shape.type === SHAPE_TYPE.POINT) {\n\t\tconst point = shape.points[0];\n\t\tif (point) {\n\t\t\tctx.fillStyle = style.color;\n\t\t\tctx.beginPath();\n\t\t\tctx.arc(point.x, point.y, style.pointRadius / viewportScale, 0, Math.PI * 2);\n\t\t\tctx.fill();\n\t\t}\n\t\tctx.restore();\n\t\treturn;\n\t}\n\n\tif (shape.type === SHAPE_TYPE.RECTANGLE || shape.type === SHAPE_TYPE.ELLIPSE) {\n\t\tconst [start, end] = shape.points;\n\t\tif (start && end) {\n\t\t\tconst x = Math.min(start.x, end.x);\n\t\t\tconst y = Math.min(start.y, end.y);\n\t\t\tconst width = Math.abs(end.x - start.x);\n\t\t\tconst height = Math.abs(end.y - start.y);\n\t\t\tctx.beginPath();\n\t\t\tif (shape.type === SHAPE_TYPE.ELLIPSE) {\n\t\t\t\tctx.ellipse(x + width / 2, y + height / 2, width / 2, height / 2, 0, 0, Math.PI * 2);\n\t\t\t} else {\n\t\t\t\tctx.rect(x, y, width, height);\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttracePoints(ctx, shape.points, shape.type !== SHAPE_TYPE.LINE);\n\t}\n\n\tif (style.fillVisible) {\n\t\tctx.save();\n\t\tctx.fillStyle = style.color;\n\t\tctx.globalAlpha *= style.fillAlpha;\n\t\tctx.fill();\n\t\tctx.restore();\n\t}\n\t// 점선의 빈 구간 보조색 — 에디터 렌더러와 동일 의미(보조색 실선 위에 주색 점선).\n\tif (shape.style?.alternateColor && style.dash?.length) {\n\t\tctx.setLineDash([]);\n\t\tctx.strokeStyle = shape.style.alternateColor;\n\t\tctx.stroke();\n\t}\n\tctx.setLineDash((style.dash ?? []).map((value) => value / viewportScale));\n\tctx.strokeStyle = style.color;\n\tctx.stroke();\n\tctx.restore();\n}\n\n/** 목록·카드 미리보기를 위한 상호작용 없는 Canvas2D 도형 뷰어. */\nexport default function ShapeViewer<TMeta = unknown>({\n\timageUrl,\n\talt = \"Shape preview\",\n\tcoordinateSize,\n\tshapes = [],\n\tregionMask,\n\tguideMask,\n\tmaskPalette,\n\tfocusedShapeId,\n\tfocusFit = \"contain\",\n\tzoomPadding = 0.3,\n\tstrokeSize = 1,\n\tbrightness = 1,\n\tcontrast = 1,\n\timageSmoothing = true,\n\tlazy = true,\n\tclassName,\n\tstyle,\n\trenderImageState,\n}: ShapeViewerProps<TMeta>) {\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\tconst canvasRef = useRef<HTMLCanvasElement>(null);\n\tconst imageRef = useRef<LoadedImage | null>(null);\n\tconst [visible, setVisible] = useState(!lazy);\n\tconst [status, setStatus] = useState<\"loading\" | \"ready\" | \"error\">(\"loading\");\n\tconst [sizeRevision, setSizeRevision] = useState(0);\n\n\tuseEffect(() => {\n\t\tif (!lazy || visible) return;\n\t\tconst element = containerRef.current;\n\t\tif (!element) return;\n\t\tconst observer = new IntersectionObserver(([entry]) => {\n\t\t\tif (!entry.isIntersecting) return;\n\t\t\tsetVisible(true);\n\t\t\tobserver.disconnect();\n\t\t});\n\t\tobserver.observe(element);\n\t\treturn () => observer.disconnect();\n\t}, [lazy, visible]);\n\n\tuseEffect(() => {\n\t\tconst element = containerRef.current;\n\t\tif (!element) return;\n\t\tconst observer = new ResizeObserver(() => setSizeRevision((value) => value + 1));\n\t\tobserver.observe(element);\n\t\treturn () => observer.disconnect();\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!visible || !imageUrl) {\n\t\t\tsetStatus(imageUrl ? \"loading\" : \"error\");\n\t\t\treturn;\n\t\t}\n\t\tlet active = true;\n\t\tsetStatus(\"loading\");\n\t\tvoid loadImage(imageUrl)\n\t\t\t.then((loaded) => {\n\t\t\t\tif (!active) {\n\t\t\t\t\tloaded.revoke?.();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\timageRef.current?.revoke?.();\n\t\t\t\timageRef.current = loaded;\n\t\t\t\tsetStatus(\"ready\");\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!active) return;\n\t\t\t\t// URL 교체 실패 시 이전 항목의 이미지가 에러 상태 뒤에 남지 않게 해제.\n\t\t\t\timageRef.current?.revoke?.();\n\t\t\t\timageRef.current = null;\n\t\t\t\tsetStatus(\"error\");\n\t\t\t});\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t};\n\t}, [imageUrl, visible]);\n\n\tuseEffect(\n\t\t() => () => {\n\t\t\timageRef.current?.revoke?.();\n\t\t\timageRef.current = null;\n\t\t},\n\t\t[],\n\t);\n\n\tconst focusedShape = useMemo(\n\t\t() => shapes.find((shape) => shape.id === focusedShapeId),\n\t\t[focusedShapeId, shapes],\n\t);\n\tconst maskCanvas = useMemo(\n\t\t() => (guideMask && maskPalette ? buildMaskCanvas(guideMask, maskPalette) : null),\n\t\t[guideMask, maskPalette],\n\t);\n\n\tuseEffect(() => {\n\t\tif (status === \"error\") {\n\t\t\t// 실패한 항목이 직전 그림을 계속 보여주지 않도록 캔버스를 비운다.\n\t\t\t// (loading 중에는 비우지 않는다 — 목록 페이징 시 깜빡임 방지.)\n\t\t\tconst canvas = canvasRef.current;\n\t\t\tcanvas?.getContext(\"2d\")?.clearRect(0, 0, canvas.width, canvas.height);\n\t\t}\n\t\tif (status !== \"ready\") return;\n\t\tconst container = containerRef.current;\n\t\tconst canvas = canvasRef.current;\n\t\tconst loaded = imageRef.current;\n\t\tif (!container || !canvas || !loaded) return;\n\n\t\tconst { width: cssWidth, height: cssHeight } = container.getBoundingClientRect();\n\t\tif (!cssWidth || !cssHeight) return;\n\t\tconst dpr = window.devicePixelRatio || 1;\n\t\tcanvas.width = Math.max(1, Math.round(cssWidth * dpr));\n\t\tcanvas.height = Math.max(1, Math.round(cssHeight * dpr));\n\t\tcanvas.style.width = `${cssWidth}px`;\n\t\tcanvas.style.height = `${cssHeight}px`;\n\t\tconst ctx = canvas.getContext(\"2d\");\n\t\tif (!ctx) return;\n\n\t\tconst imageWidth = coordinateSize?.width ?? loaded.image.naturalWidth;\n\t\tconst imageHeight = coordinateSize?.height ?? loaded.image.naturalHeight;\n\t\t// 좌표계 크기 0(호스트가 서버 메타 수신 전 전달 등)이면 scale이 Infinity가 된다.\n\t\tif (!imageWidth || !imageHeight) return;\n\t\tlet scale = Math.min(cssWidth / imageWidth, cssHeight / imageHeight);\n\t\tlet offsetX = (cssWidth - imageWidth * scale) / 2;\n\t\tlet offsetY = (cssHeight - imageHeight * scale) / 2;\n\n\t\tif (focusedShape && focusedShape.points.length > 0) {\n\t\t\tconst bounds = getBBox(focusedShape.points);\n\t\t\tconst width = Math.max(bounds.maxX - bounds.minX, 50);\n\t\t\tconst height = Math.max(bounds.maxY - bounds.minY, 50);\n\t\t\tconst padding = Math.min(width, height) * zoomPadding;\n\t\t\tscale = Math.min(cssWidth / (width + padding * 2), cssHeight / (height + padding * 2));\n\t\t\tif (focusFit === \"cover\") {\n\t\t\t\tscale = Math.max(scale, Math.max(cssWidth / imageWidth, cssHeight / imageHeight));\n\t\t\t}\n\t\t\toffsetX = cssWidth / 2 - ((bounds.minX + bounds.maxX) / 2) * scale;\n\t\t\toffsetY = cssHeight / 2 - ((bounds.minY + bounds.maxY) / 2) * scale;\n\t\t\tif (focusFit === \"cover\") {\n\t\t\t\toffsetX = Math.min(0, Math.max(offsetX, cssWidth - imageWidth * scale));\n\t\t\t\toffsetY = Math.min(0, Math.max(offsetY, cssHeight - imageHeight * scale));\n\t\t\t}\n\t\t}\n\n\t\tctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n\t\tctx.clearRect(0, 0, cssWidth, cssHeight);\n\t\tctx.save();\n\t\tctx.translate(offsetX, offsetY);\n\t\tctx.scale(scale, scale);\n\t\tctx.imageSmoothingEnabled = imageSmoothing;\n\t\tctx.filter = `brightness(${brightness}) contrast(${contrast})`;\n\t\tctx.drawImage(loaded.image, 0, 0, imageWidth, imageHeight);\n\t\tctx.filter = \"none\";\n\t\tif (maskCanvas) {\n\t\t\tctx.save();\n\t\t\tctx.globalAlpha = 0.55;\n\t\t\tctx.drawImage(maskCanvas, 0, 0, imageWidth, imageHeight);\n\t\t\tctx.restore();\n\t\t}\n\n\t\tconst regionOverlay = regionMask\n\t\t\t? buildRegionOverlayData(regionMask, imageWidth, imageHeight)\n\t\t\t: null;\n\t\tif (regionOverlay) {\n\t\t\tdrawRegionDim(ctx, regionOverlay, imageWidth, imageHeight);\n\t\t\tif (regionOverlay.outlineStyles) {\n\t\t\t\t// 경계 선분 — 스타일은 에디터와 동일하게 RegionMask에서 리졸브된 값을 쓴다.\n\t\t\t\tconst strokeSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n\t\t\t\t\tctx.lineWidth = style.width / scale;\n\t\t\t\t\tif (style.underlayColor) {\n\t\t\t\t\t\tctx.setLineDash([]);\n\t\t\t\t\t\tctx.strokeStyle = style.underlayColor;\n\t\t\t\t\t\tfor (const [a, b] of segments) {\n\t\t\t\t\t\t\ttracePoints(ctx, [a, b], false);\n\t\t\t\t\t\t\tctx.stroke();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tctx.save();\n\t\t\t\t\tctx.globalAlpha *= style.opacity;\n\t\t\t\t\tctx.setLineDash(style.dash.map((value) => value / scale));\n\t\t\t\t\tctx.strokeStyle = style.color;\n\t\t\t\t\tfor (const [a, b] of segments) {\n\t\t\t\t\t\ttracePoints(ctx, [a, b], false);\n\t\t\t\t\t\tctx.stroke();\n\t\t\t\t\t}\n\t\t\t\t\tctx.restore();\n\t\t\t\t};\n\t\t\t\tstrokeSegments(regionOverlay.visibleOutline, regionOverlay.outlineStyles.visible);\n\t\t\t\tstrokeSegments(regionOverlay.occludedOutline, regionOverlay.outlineStyles.occluded);\n\t\t\t}\n\t\t}\n\n\t\tfor (const shape of sortShapesForRender(shapes)) {\n\t\t\tdrawShape(ctx, shape, scale, strokeSize);\n\t\t}\n\t\tctx.restore();\n\t}, [\n\t\tbrightness,\n\t\tcontrast,\n\t\tcoordinateSize,\n\t\tfocusedShape,\n\t\tfocusFit,\n\t\timageSmoothing,\n\t\tmaskCanvas,\n\t\tregionMask,\n\t\tshapes,\n\t\tsizeRevision,\n\t\tstatus,\n\t\tstrokeSize,\n\t\tzoomPadding,\n\t]);\n\n\treturn (\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tclassName={className}\n\t\t\tstyle={{ position: \"relative\", width: \"100%\", height: \"100%\", ...style }}\n\t\t>\n\t\t\t<canvas ref={canvasRef} role=\"img\" aria-label={alt} style={{ display: \"block\" }} />\n\t\t\t{status !== \"ready\" && renderImageState && (\n\t\t\t\t<div style={{ position: \"absolute\", inset: 0 }}>\n\t\t\t\t\t{renderImageState(status === \"error\" ? \"error\" : \"loading\")}\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n"],"mappings":";;;;;;;;;IAeC,IAAW;CACX,OAAA;CACA,WAAS;CACT,mBAAS;CACT,SAAM;CACN,SAAA;CAiED,MAAA;CACC;;AAGD,QAAA,EAAgB,aAAA,YAAgD;;;AAIhE,QAAA,EAAgB,EAAkB,IAAA,EA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A,EAAA,YAAI,EAAe,QAAA,GACnB,EAAI,eAAoB;AAEvB,KADD,EAAA,YAAe,EAAA,CAAA,EACd,EAAA,cAAiB,EAAM;AACvB,UAAI,IAAA,CAAA,GAAQ,MAAA;;AAQb,IAHD,EAAI,MAAA,EACJ,EAAI,eAAc,EAAM,SACxB,EAAA,YAAe,EAAM,KAAA,KAAU,MAAA,IAAA,EAAA,CAAA,EAC9B,EAAA,cAAiB,EAAM;AACvB,SAAI,IAAA,CAAA,GAAQ,MAAA,EAEb,oBAAA,EAAI,QAAS;AAEd,MAAA,SAAA;;;;OASA,IAAA,KAAA,GAAA,EAAA,CAAA,IAAA,GAAA,GAAA,GAAA,EAAA;AACF,IAAA,SAAA;IACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAED;EAEE,CAAA,EACW,kBAAA,OAAA;EACX,KAAA;;SAA+B;GAAe,UAAQ;GAAQ,OAAG;GAAO,QAAA;;GAEhE;YAAqB,CAAA,kBAAA,UAAA;GAAM,KAAA;GAAiB,MAAA;GAA+B,cACvE;GACN,OAAO,EAAA,SAAA,SAAA;IAAE,EAAA,MAAU,WAAA,KAAA,kBAAA,OAAA;UAAY;IAAU,UAAA;;IAExC"}
1
+ {"version":3,"file":"shape-editor.js","names":[],"sources":["../src/components/ShapeEditor/_model/geometry.ts","../src/components/ShapeEditor/_model/strings.ts","../src/components/ShapeEditor/_model/tools.ts","../src/components/ShapeEditor/_model/viewSettings.ts","../src/components/ShapeEditor/_components/AssistantOverlay.tsx","../src/components/ShapeEditor/_components/ContextMenu.tsx","../src/components/ShapeEditor/_components/CursorGuide.tsx","../src/components/ShapeEditor/_components/ImageStateOverlay.tsx","../src/components/ShapeEditor/_constants.ts","../src/components/ShapeEditor/_model/shapeRenderStyle.ts","../src/components/ShapeEditor/_components/MinimapShape.tsx","../src/components/ShapeEditor/_components/RegionOverlay.tsx","../src/components/ShapeEditor/_components/SettingsPanel.tsx","../src/components/ShapeEditor/_components/Minimap.tsx","../src/components/ShapeEditor/_components/SelectionInfo.tsx","../src/components/ShapeEditor/_model/clipboard.ts","../src/components/ShapeEditor/_model/cursors.ts","../src/components/ShapeEditor/_model/overlays.ts","../src/components/ShapeEditor/_model/viewport.ts","../src/components/ShapeEditor/_state/createInteractionController.ts","../src/components/ShapeEditor/_state/useAssistant.ts","../src/components/ShapeEditor/_model/brush.ts","../src/components/ShapeEditor/_model/scalarMask.ts","../src/components/ShapeEditor/_state/drawSessionState.ts","../src/components/ShapeEditor/_state/useDrawSession.ts","../src/components/ShapeEditor/_state/useEditorDocument.ts","../src/components/ShapeEditor/_model/keymap.ts","../src/components/ShapeEditor/_state/useEditorHotkeys.ts","../src/components/ShapeEditor/_model/imageLoad.ts","../src/components/ShapeEditor/_model/imageDiagnosis.ts","../src/components/ShapeEditor/_model/imageTiles.ts","../src/components/ShapeEditor/_model/konva.ts","../src/components/ShapeEditor/_model/pinIcon.ts","../src/components/ShapeEditor/_renderers/transformSession.ts","../src/components/ShapeEditor/_renderers/KonvaRenderer.ts","../src/components/ShapeEditor/_renderers/PixiRenderer.ts","../src/components/ShapeEditor/_state/useEngineLifecycle.ts","../src/components/ShapeEditor/_state/useMinimapNavigation.ts","../src/components/ShapeEditor/_state/useMinimapSync.ts","../src/components/ShapeEditor/_state/useSelectionActions.ts","../src/components/ShapeEditor/_state/useViewportControls.ts","../src/components/ShapeEditor/ShapeEditor.tsx","../src/components/ShapeEditor/ShapeViewer.tsx"],"sourcesContent":["/**\n * Editor의 도메인 무관 기하/도형 모델.\n *\n * 이 에디터는 \"색 입힌 도형을 그리고 편집\"할 뿐, 클래스/라벨/태스크 같은 라벨링 도메인\n * 개념을 모른다. 분류 정보(classId 등)는 호스트가 `meta`에 담아 넘기면 에디터는 건드리지\n * 않고 그대로 되돌려준다. 렌더에 필요한 색/채움은 `style`로 받는다.\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport const SHAPE_TYPE = {\n POINT: \"POINT\",\n RECTANGLE: \"RECTANGLE\",\n ROTATED_RECTANGLE: \"ROTATED_RECTANGLE\",\n POLYGON: \"POLYGON\",\n ELLIPSE: \"ELLIPSE\",\n LINE: \"LINE\",\n} as const;\n\nexport type ShapeType = (typeof SHAPE_TYPE)[keyof typeof SHAPE_TYPE];\n\n/** 도형 렌더 힌트. 호스트가 (예: 클래스→색) 계산해 주입한다. */\nexport interface ShapeStyle {\n color?: string;\n /** 점선의 빈 구간에 표시할 보조색. 지정하면 보조색 실선 위에 주색 점선을 그린다. */\n alternateColor?: string;\n filled?: boolean;\n opacity?: number;\n /** 도형별 선 두께(화면 px). 없으면 에디터 기본값을 사용한다. */\n strokeWidth?: number;\n /** 채움 투명도(0~1). 없으면 렌더러 기본값을 사용한다. */\n fillOpacity?: number;\n /** 점선 패턴(화면 px). 고정값이라 선 두께가 바뀌어도 따라오지 않는다. */\n dash?: number[];\n /**\n * 점선으로 그린다. 패턴은 에디터가 선 두께에 맞춰 정하므로 소비처는 의도만 밝힌다.\n * dash로 직접 지정하면 그쪽이 우선한다.\n */\n dashed?: boolean;\n /** POINT 도형 반경(화면 px). */\n pointRadius?: number;\n /** 렌더 순서. 없으면 문서 배열 순서를 따른다. */\n zIndex?: number;\n}\n\nexport interface ShapeInteraction {\n /** false면 렌더하지 않고 hit-test/선택/편집에서도 제외한다. */\n visible?: boolean;\n /** false면 도형 클릭·마퀴·선택 API에서 선택 대상이 되지 않는다. */\n selectable?: boolean;\n /** false면 본체 드래그 이동을 막는다. */\n draggable?: boolean;\n /** false면 트랜스포머/꼭짓점 편집/삭제 같은 문서 변경 편집을 막는다. */\n editable?: boolean;\n /** true면 렌더는 하되 포인터 hit-test 대상에서 제외한다. */\n hitTestDisabled?: boolean;\n}\n\n/**\n * 에디터가 그리고 편집하는 단위.\n * - POINT: points 1개, RECTANGLE·ELLIPSE: 2개(대각 bbox), ROTATED_RECTANGLE: 4개,\n * POLYGON: N개(닫힘), LINE: N개(열린 폴리라인/자유곡선).\n * - id: **클라이언트 생성**(에디터가 도형 생성 시 부여). 서버 id는 에디터가 모른다 —\n * 호스트가 clientId↔serverId 매핑을 들거나 meta에 보관한다.\n * - meta: 호스트 전용 불투명 데이터(classId, serverId 등). 에디터는 읽지 않고 보존만 한다.\n * - style: 렌더 힌트(색/채움). 호스트가 클래스→색을 계산해 주입/시드한다.\n */\nexport interface EditorShape<TMeta = unknown> {\n id: string;\n type: ShapeType;\n points: Point[];\n rotation?: number;\n /**\n * 편집 불가(예: 모델 예측/평가 도형). 하위 호환 shorthand이며 selectable은 유지하고\n * draggable/editable만 false처럼 취급한다.\n */\n readOnly?: boolean;\n interaction?: ShapeInteraction;\n style?: ShapeStyle;\n meta?: TMeta;\n}\n\nexport interface Viewport {\n scale: number;\n position: Point;\n}\n\nexport function isShapeVisible(shape: EditorShape): boolean {\n return shape.interaction?.visible !== false;\n}\n\nexport function isShapeHitTestable(shape: EditorShape): boolean {\n return isShapeVisible(shape) && shape.interaction?.hitTestDisabled !== true;\n}\n\nexport function isShapeSelectable(shape: EditorShape): boolean {\n return isShapeHitTestable(shape) && shape.interaction?.selectable !== false;\n}\n\nexport function isShapeEditable(shape: EditorShape): boolean {\n return isShapeSelectable(shape) && !shape.readOnly && shape.interaction?.editable !== false;\n}\n\nexport function isShapeDraggable(shape: EditorShape): boolean {\n return isShapeEditable(shape) && shape.interaction?.draggable !== false;\n}\n\nexport function sortShapesForRender<TMeta>(shapes: EditorShape<TMeta>[]): EditorShape<TMeta>[] {\n return shapes\n .map((shape, index) => ({ shape, index }))\n .sort((a, b) => {\n const za = a.shape.style?.zIndex ?? 0;\n const zb = b.shape.style?.zIndex ?? 0;\n return za === zb ? a.index - b.index : za - zb;\n })\n .map((entry) => entry.shape);\n}\n\n// ── 순수 기하 헬퍼(트랜스포머/상호작용 공용, Konva 비의존) ──\nexport function clamp(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n// secure context가 아닌 환경(비-localhost http 등)에서도 안전한 클라이언트 id 생성.\nexport function generateId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n// ── 자체 바운딩박스 트랜스포머용 기하 ──\nexport interface BBox {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\nexport type Anchor = \"tl\" | \"t\" | \"tr\" | \"r\" | \"br\" | \"b\" | \"bl\" | \"l\";\nexport const ANCHORS: Anchor[] = [\"tl\", \"t\", \"tr\", \"r\", \"br\", \"b\", \"bl\", \"l\"];\n\nexport function getBBox(points: Point[]): BBox {\n const xs = points.map((p) => p.x);\n const ys = points.map((p) => p.y);\n return {\n minX: Math.min(...xs),\n minY: Math.min(...ys),\n maxX: Math.max(...xs),\n maxY: Math.max(...ys),\n };\n}\n\nexport function anchorPoint(anchor: Anchor, b: BBox): Point {\n const cx = (b.minX + b.maxX) / 2;\n const cy = (b.minY + b.maxY) / 2;\n const x = anchor.includes(\"l\") ? b.minX : anchor.includes(\"r\") ? b.maxX : cx;\n const y = anchor.includes(\"t\") ? b.minY : anchor.includes(\"b\") ? b.maxY : cy;\n return { x, y };\n}\n\n// 핸들을 (hx,hy)로 끌었을 때의 새 bbox(해당 모서리/변만 이동).\nexport function boxFromAnchor(anchor: Anchor, b: BBox, hx: number, hy: number): BBox {\n const next = { ...b };\n if (anchor.includes(\"l\")) next.minX = hx;\n if (anchor.includes(\"r\")) next.maxX = hx;\n if (anchor.includes(\"t\")) next.minY = hy;\n if (anchor.includes(\"b\")) next.maxY = hy;\n return next;\n}\n\n// Shift 제약: 박스를 정사각/정원으로(끝점을 큰 축에 맞춤).\nexport function squareEnd(start: Point, p: Point): Point {\n const dx = p.x - start.x;\n const dy = p.y - start.y;\n const d = Math.max(Math.abs(dx), Math.abs(dy));\n return {\n x: start.x + (dx < 0 ? -d : d),\n y: start.y + (dy < 0 ? -d : d),\n };\n}\n\n// 점을 pivot 기준 angle(rad) 회전.\nexport function rotatePoint(p: Point, pivot: Point, angle: number): Point {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const dx = p.x - pivot.x;\n const dy = p.y - pivot.y;\n return {\n x: pivot.x + dx * cos - dy * sin,\n y: pivot.y + dx * sin + dy * cos,\n };\n}\n\n// 축정렬 사각형(2점) → 4개 코너 점[tl,tr,br,bl]. 회전 시 ROTATED_RECTANGLE로 승격.\nexport function rectTo4(points: Point[]): Point[] {\n const b = getBBox(points);\n return [\n { x: b.minX, y: b.minY },\n { x: b.maxX, y: b.minY },\n { x: b.maxX, y: b.maxY },\n { x: b.minX, y: b.maxY },\n ];\n}\n\n/**\n * 두 점(a,b)이 이루는 바운딩 박스에 **내접하는 타원**을 폴리곤으로 샘플링한다.\n * 그리기 미리보기(previewBox \"ellipse\": rx=w/2, ry=h/2)와 동일한 도형이어야 커밋 결과가\n * 드래그 중 보이던 것과 일치한다(정사각형 드래그면 원). 예전엔 대각선을 지름으로 한 원을\n * 만들어 미리보기(내접 타원)와 크기·모양이 달랐다.\n */\nexport function circleToPolygon(a: Point, b: Point, count = 32): Point[] {\n const cx = (a.x + b.x) / 2;\n const cy = (a.y + b.y) / 2;\n const rx = Math.abs(b.x - a.x) / 2;\n const ry = Math.abs(b.y - a.y) / 2;\n return Array.from({ length: count }, (_, index) => {\n const angle = (index / count) * 2 * Math.PI;\n return {\n x: cx + rx * Math.cos(angle),\n y: cy + ry * Math.sin(angle),\n };\n });\n}\n\n/**\n * 볼록 껍질(Andrew monotone chain). 입력 점들의 볼록 다각형 코너를 반시계로 반환.\n * 3점 미만이면 입력을 그대로 돌려준다(최소사각형 계산의 전처리용).\n */\nexport function convexHull(points: Point[]): Point[] {\n const pts = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n if (pts.length <= 2) return pts;\n const cross = (o: Point, a: Point, b: Point) =>\n (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n const lower: Point[] = [];\n for (const p of pts) {\n while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0)\n lower.pop();\n lower.push(p);\n }\n const upper: Point[] = [];\n for (let i = pts.length - 1; i >= 0; i--) {\n const p = pts[i];\n while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0)\n upper.pop();\n upper.push(p);\n }\n lower.pop();\n upper.pop();\n return lower.concat(upper);\n}\n\n/**\n * 최소 넓이 회전 사각형(rotating calipers). 점들을 감싸는 넓이 최소의 (기울 수 있는)\n * 사각형 4개 코너를 둘레 순서로 반환한다. OBB(회전 바운딩박스) 어시스트 결과 변환용.\n * 최소사각형의 한 변은 반드시 볼록껍질의 한 변과 평행하다는 성질을 이용한다.\n */\nexport function minAreaRect(points: Point[]): Point[] {\n const hull = convexHull(points);\n if (hull.length < 3) return rectTo4(points);\n let bestArea = Number.POSITIVE_INFINITY;\n let bestCorners = rectTo4(points);\n for (let i = 0; i < hull.length; i++) {\n const a = hull[i];\n const b = hull[(i + 1) % hull.length];\n const len = Math.hypot(b.x - a.x, b.y - a.y) || 1;\n const ux = (b.x - a.x) / len;\n const uy = (b.y - a.y) / len; // 에지 방향 단위벡터(법선은 (-uy, ux))\n let minU = Number.POSITIVE_INFINITY;\n let maxU = Number.NEGATIVE_INFINITY;\n let minV = Number.POSITIVE_INFINITY;\n let maxV = Number.NEGATIVE_INFINITY;\n for (const p of hull) {\n const u = p.x * ux + p.y * uy;\n const v = -p.x * uy + p.y * ux;\n if (u < minU) minU = u;\n if (u > maxU) maxU = u;\n if (v < minV) minV = v;\n if (v > maxV) maxV = v;\n }\n const area = (maxU - minU) * (maxV - minV);\n if (area < bestArea) {\n bestArea = area;\n // (u,v) 좌표 → 원좌표 역변환: p = u*(ux,uy) + v*(-uy,ux)\n const toXY = (u: number, v: number): Point => ({\n x: u * ux - v * uy,\n y: u * uy + v * ux,\n });\n bestCorners = [toXY(minU, minV), toXY(maxU, minV), toXY(maxU, maxV), toXY(minU, maxV)];\n }\n }\n return bestCorners;\n}\n\n// ── 기울어진(회전된) 사각형 트랜스포머용 벡터/기하 ──\nexport const vsub = (a: Point, b: Point): Point => ({\n x: a.x - b.x,\n y: a.y - b.y,\n});\nexport const vdot = (a: Point, b: Point): number => a.x * b.x + a.y * b.y;\nexport const vlen = (a: Point): number => Math.hypot(a.x, a.y);\nexport const vnorm = (a: Point): Point => {\n const l = vlen(a) || 1;\n return { x: a.x / l, y: a.y / l };\n};\nexport const mid = (a: Point, b: Point): Point => ({\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n});\nexport const centerOf = (pts: Point[]): Point => {\n const s = pts.reduce((acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y }), {\n x: 0,\n y: 0,\n });\n return { x: s.x / pts.length, y: s.y / pts.length };\n};\n\n// 회전 사각형 코너[tl,tr,br,bl] → 8핸들 위치(ANCHORS 순서: tl,t,tr,r,br,b,bl,l).\nexport function orientedHandles(c: Point[]): Point[] {\n return [\n c[0],\n mid(c[0], c[1]),\n c[1],\n mid(c[1], c[2]),\n c[2],\n mid(c[2], c[3]),\n c[3],\n mid(c[3], c[0]),\n ];\n}\n\n// 위쪽 변 중앙에서 바깥(로컬 위) 방향으로 떨어진 회전 핸들 위치.\nexport function rotateHandlePos(c: Point[], gap: number): Point {\n const top = mid(c[0], c[1]);\n const up = vnorm(vsub(c[0], c[3])); // tl - bl = 로컬 위 방향\n return { x: top.x + up.x * gap, y: top.y + up.y * gap };\n}\n\n/** 회전 사각형 위변(tl→tr) 각도(라디안). */\nexport function rotatedRectAngle(points: Point[]): number {\n if (points.length < 2) return 0;\n return Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);\n}\n\n// 로컬 박스(원점 R + 정규직교축 u,v) → 월드 코너[tl,tr,br,bl].\nexport function localBoxToCorners(box: BBox, R: Point, u: Point, v: Point): Point[] {\n const pt = (lx: number, ly: number): Point => ({\n x: R.x + lx * u.x + ly * v.x,\n y: R.y + lx * u.y + ly * v.y,\n });\n return [\n pt(box.minX, box.minY),\n pt(box.maxX, box.minY),\n pt(box.maxX, box.maxY),\n pt(box.minX, box.maxY),\n ];\n}\n\nexport function resizeRotatedRectFromAnchor(\n points: Point[],\n anchor: Anchor,\n target: Point,\n): Point[] {\n if (points.length < 4) return points;\n const origin = points[0];\n const u = vnorm(vsub(points[1], points[0]));\n const v = vnorm(vsub(points[3], points[0]));\n const width = vdot(vsub(points[1], origin), u);\n const height = vdot(vsub(points[3], origin), v);\n const localTarget = vsub(target, origin);\n const box = boxFromAnchor(\n anchor,\n { minX: 0, minY: 0, maxX: width, maxY: height },\n vdot(localTarget, u),\n vdot(localTarget, v),\n );\n return localBoxToCorners(box, origin, u, v);\n}\n\n// old bbox 안의 점들을 new bbox에 맞춰 비례 재배치(사각형·폴리곤 공용, baking 없음).\nexport function rescalePoints(points: Point[], from: BBox, to: BBox): Point[] {\n const fw = from.maxX - from.minX || 1;\n const fh = from.maxY - from.minY || 1;\n const tw = to.maxX - to.minX;\n const th = to.maxY - to.minY;\n return points.map((p) => ({\n x: to.minX + ((p.x - from.minX) / fw) * tw,\n y: to.minY + ((p.y - from.minY) / fh) * th,\n }));\n}\n\n// 인접하지 않은 변 쌍의 교차 전수 수집 — minX 정렬 스윕 + bbox 컷이라 손으로 그린\n// 조밀 폴리곤(변이 짧고 국소적)에서 근사 선형. 끝점 접촉·평행은 교차로 치지 않는다.\nfunction collectSelfIntersections(\n points: Point[],\n): { i: number; j: number; ti: number; tj: number }[] {\n const n = points.length;\n const segs = Array.from({ length: n }, (_, i) => {\n const a = points[i];\n const b = points[(i + 1) % n];\n return {\n i,\n minX: Math.min(a.x, b.x),\n maxX: Math.max(a.x, b.x),\n minY: Math.min(a.y, b.y),\n maxY: Math.max(a.y, b.y),\n };\n }).sort((s, t) => s.minX - t.minX);\n const hits: { i: number; j: number; ti: number; tj: number }[] = [];\n for (let u = 0; u < n; u++) {\n const s = segs[u];\n for (let v = u + 1; v < n && segs[v].minX <= s.maxX; v++) {\n const t = segs[v];\n if (t.minY > s.maxY || t.maxY < s.minY) continue;\n const i = Math.min(s.i, t.i);\n const j = Math.max(s.i, t.i);\n if (j === i + 1 || (i === 0 && j === n - 1)) continue;\n const hit = segmentCrossParams(\n points[i],\n points[(i + 1) % n],\n points[j],\n points[(j + 1) % n],\n );\n if (hit) hits.push({ i, j, ti: hit.ti, tj: hit.tj });\n }\n }\n return hits;\n}\n\n// 두 선분의 순수 교차점 파라미터(각 선분 위 0~1, 끝점 접촉 제외). 평행/접촉이면 null.\nfunction segmentCrossParams(\n a: Point,\n b: Point,\n c: Point,\n d: Point,\n): { ti: number; tj: number } | null {\n const rx = b.x - a.x;\n const ry = b.y - a.y;\n const sx = d.x - c.x;\n const sy = d.y - c.y;\n const denom = rx * sy - ry * sx;\n if (!denom) return null;\n const ti = ((c.x - a.x) * sy - (c.y - a.y) * sx) / denom;\n const tj = ((c.x - a.x) * ry - (c.y - a.y) * rx) / denom;\n const EPS = 1e-9;\n if (ti <= EPS || ti >= 1 - EPS || tj <= EPS || tj >= 1 - EPS) return null;\n return { ti, tj };\n}\n\n// ── 마퀴(축정렬 박스) 대 도형 실제 기하 충돌 판정 ──\n\nconst pointInBox = (p: Point, b: BBox): boolean =>\n p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY;\n\n/** 부호 있는 외적 — 세 점의 방향(좌회전 양수). */\nconst orient = (a: Point, b: Point, c: Point): number =>\n (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\n\nconst onSegment = (p: Point, q: Point, r: Point): boolean =>\n orient(p, q, r) === 0 &&\n Math.min(p.x, q.x) <= r.x &&\n r.x <= Math.max(p.x, q.x) &&\n Math.min(p.y, q.y) <= r.y &&\n r.y <= Math.max(p.y, q.y);\n\nfunction segmentsIntersect(a: Point, b: Point, c: Point, d: Point): boolean {\n const d1 = orient(c, d, a);\n const d2 = orient(c, d, b);\n const d3 = orient(a, b, c);\n const d4 = orient(a, b, d);\n if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) {\n return true;\n }\n return onSegment(c, d, a) || onSegment(c, d, b) || onSegment(a, b, c) || onSegment(a, b, d);\n}\n\nfunction segmentIntersectsBox(a: Point, b: Point, box: BBox): boolean {\n if (pointInBox(a, box) || pointInBox(b, box)) return true;\n const tl = { x: box.minX, y: box.minY };\n const tr = { x: box.maxX, y: box.minY };\n const br = { x: box.maxX, y: box.maxY };\n const bl = { x: box.minX, y: box.maxY };\n return (\n segmentsIntersect(a, b, tl, tr) ||\n segmentsIntersect(a, b, tr, br) ||\n segmentsIntersect(a, b, br, bl) ||\n segmentsIntersect(a, b, bl, tl)\n );\n}\n\n/** 점이 닫힌 다각형 내부인가(ray casting, even-odd). */\nexport function pointInPolygon(p: Point, polygon: Point[]): boolean {\n let inside = false;\n for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n const a = polygon[i];\n const b = polygon[j];\n const crosses =\n a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x;\n if (crosses) inside = !inside;\n }\n return inside;\n}\n\n/** 정점이 박스 안이거나 어느 변이 박스와 교차하는가. closed면 마지막→첫 변도 검사. */\nfunction outlineIntersectsBox(points: Point[], box: BBox, closed: boolean): boolean {\n if (points.some((p) => pointInBox(p, box))) return true;\n const last = closed ? points.length : points.length - 1;\n for (let i = 0; i < last; i += 1) {\n if (segmentIntersectsBox(points[i], points[(i + 1) % points.length], box)) return true;\n }\n return false;\n}\n\n/**\n * 도형과 축정렬 박스의 실제 기하 충돌 — 마퀴 선택 판정. bbox 근사와 달리\n * 오목 폴리곤의 빈 구석·타원 모서리·회전 사각형 바깥을 잡지 않는다.\n * 닫힌 도형은 면(영역)으로 본다: 박스가 도형 내부에 완전히 들어간 경우도 충돌.\n */\nexport function shapeIntersectsBox(shape: EditorShape, box: BBox): boolean {\n const points = shape.points;\n if (!points.length) return false;\n // 싼 bbox 선별 — 실패면 정밀 판정 불필요.\n const b = getBBox(points);\n if (b.minX > box.maxX || b.maxX < box.minX || b.minY > box.maxY || b.maxY < box.minY) {\n return false;\n }\n switch (shape.type) {\n case SHAPE_TYPE.POINT:\n return pointInBox(points[0], box);\n case SHAPE_TYPE.RECTANGLE:\n // 축정렬 사각형은 bbox가 곧 실제 기하.\n return true;\n case SHAPE_TYPE.ELLIPSE: {\n const rx = (b.maxX - b.minX) / 2;\n const ry = (b.maxY - b.minY) / 2;\n if (rx <= 0 || ry <= 0) return true; // 퇴화(선/점) — bbox 통과로 충분.\n const cx = (b.minX + b.maxX) / 2;\n const cy = (b.minY + b.maxY) / 2;\n // 박스에서 타원 중심에 가장 가까운 점이 타원 안이면 충돌.\n const nx = clamp(cx, box.minX, box.maxX);\n const ny = clamp(cy, box.minY, box.maxY);\n return ((nx - cx) / rx) ** 2 + ((ny - cy) / ry) ** 2 <= 1;\n }\n case SHAPE_TYPE.LINE:\n return outlineIntersectsBox(points, box, false);\n case SHAPE_TYPE.POLYGON:\n case SHAPE_TYPE.ROTATED_RECTANGLE:\n return (\n outlineIntersectsBox(points, box, true) ||\n // 윤곽 교차 없이 겹치는 유일한 경우 = 박스가 다각형 내부에 완전 포함.\n (points.length >= 3 && pointInPolygon({ x: box.minX, y: box.minY }, points))\n );\n default:\n return true; // 미지의 타입은 bbox 판정 유지(과소선택보다 과대선택이 안전).\n }\n}\n\nconst signedArea = (loop: Point[]): number => {\n let sum = 0;\n for (let i = 0, j = loop.length - 1; i < loop.length; j = i++) {\n sum += (loop[j].x - loop[i].x) * (loop[j].y + loop[i].y);\n }\n return sum / 2;\n};\n\n/**\n * 점 m에서 방향 d(단위벡터)로 쏜 레이가 폴리곤 경계를 가로지르는 부호 합 —\n * m의 감김수(winding). |값|이 그 지점을 덮는 경계 겹수, 홀짝이 evenodd 패리티.\n * 시작점이 경계 변 위에 있어도 되도록 레이 진행거리 EPS 이하 교차(시작점이\n * 얹힌 변 자신)를 제외한다 — 얇은 슬리버 면에도 안쪽 오프셋 없이 정확하다.\n */\nfunction windingAt(m: Point, d: Point, points: Point[], eps: number): number {\n let winding = 0;\n const n = points.length;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const p = points[j];\n const q = points[i];\n // 레이 수직 좌표(u) 부호가 갈리는 선분만 후보 — 반개구간(u>0)으로 꼭짓점 중복 방지.\n const up = (p.x - m.x) * d.y - (p.y - m.y) * d.x;\n const uq = (q.x - m.x) * d.y - (q.y - m.y) * d.x;\n if (up > 0 === uq > 0) continue;\n const vp = (p.x - m.x) * d.x + (p.y - m.y) * d.y;\n const vq = (q.x - m.x) * d.x + (q.y - m.y) * d.y;\n const v = vp + ((vq - vp) * up) / (up - uq);\n if (v > eps) winding += up > 0 ? -1 : 1;\n }\n return winding;\n}\n\n// 면(orbit) 첫 변 중점에서 면 안쪽으로 향하는 단위 노멀 — windingAt의 레이 방향.\nfunction inwardNormal(face: Point[]): Point | null {\n const a = face[0];\n const b = face[1];\n let dx = -(b.y - a.y);\n let dy = b.x - a.x;\n if (signedArea(face) < 0) {\n dx = -dx;\n dy = -dy;\n }\n const len = Math.hypot(dx, dy);\n if (!len) return null;\n return { x: dx / len, y: dy / len };\n}\n\nexport interface FillGroup {\n outline: Point[];\n holes: Point[][];\n /** 채움 겹수 — 2 이상이면 반투명 채움이 겹쳐 진해진다(겹침 영역 표현). */\n layers: number;\n}\n\n/**\n * 자기교차 폴리곤의 채움 그룹 계산 — 교차점을 정점으로 하는 평면 배치(arrangement)의\n * 면(face)들을 반변(half-edge) 궤도로 추출한 뒤, 면별 감김수로 채움을 정한다:\n * - 유계 면은 기본적으로 max(1, |감김수|)겹으로 칠한다 — 관통 웨지처럼 감김수가\n * 상쇄(0)된 닫힌 포켓도 눈에는 도형의 일부이므로 비우지 않고, 같은 방향으로\n * 두 번 감은 겹침(≥2)은 겹수만큼 포개 칠해 진해진다.\n * - 예외: 홀수 면 안에 중첩된 감김수 짝수(≥2) 면 = 한붓 도넛의 구멍 — 비운다.\n * - 무계(바깥) 면과 면의 안쪽 경계(구멍 궤도)는 칠하지 않고, 안쪽 경계는 그 면의\n * cut 구멍으로 붙여 면들이 서로 겹치지 않게 한다(겹수 계산이 정확해지는 조건).\n * 순수 evenodd/nonzero 어느 쪽도 아닌 의도적 선택 — \"반투명 도형을 포개 그린\"\n * 직관(구멍만 비고, 겹치면 진해지고, 나머지는 전부 칠해짐)을 재현한다.\n */\nexport function computePolygonFillGroups(points: Point[], maxPoints = 4096): FillGroup[] {\n const single: FillGroup[] = [{ outline: points, holes: [], layers: 1 }];\n const n = points.length;\n if (n < 4 || n > maxPoints) return single;\n const hits = collectSelfIntersections(points);\n if (!hits.length) return single;\n\n // 경계 순회 정점열 — 교차점은 쌍둥이가 같은 Point 객체를 공유해 그래프 정점이 된다.\n const cuts: { t: number; p: Point }[][] = Array.from({ length: n }, () => []);\n for (const hit of hits) {\n const a = points[hit.i];\n const b = points[(hit.i + 1) % n];\n const p = { x: a.x + (b.x - a.x) * hit.ti, y: a.y + (b.y - a.y) * hit.ti };\n cuts[hit.i].push({ t: hit.ti, p });\n cuts[hit.j].push({ t: hit.tj, p });\n }\n const seq: Point[] = [];\n for (let i = 0; i < n; i++) {\n seq.push(points[i]);\n for (const c of cuts[i].sort((x, y) => x.t - y.t)) seq.push(c.p);\n }\n\n // 반변 그래프: 무향 변마다 방향 반변 2개, 정점별 나가는 반변을 각도순 정렬.\n const vertexId = new Map<Point, number>();\n const coords: Point[] = [];\n const idOf = (p: Point) => {\n let id = vertexId.get(p);\n if (id === undefined) {\n id = coords.length;\n vertexId.set(p, id);\n coords.push(p);\n }\n return id;\n };\n const m = seq.length;\n // he: [from, to] 반변 배열. i번째 무향 변의 반변 = 2i(정방향), 2i+1(역방향).\n const heFrom: number[] = [];\n const heTo: number[] = [];\n for (let k = 0; k < m; k++) {\n const u = idOf(seq[k]);\n const v = idOf(seq[(k + 1) % m]);\n if (u === v) continue; // 퇴화 변\n heFrom.push(u, v);\n heTo.push(v, u);\n }\n const heCount = heFrom.length;\n if (!heCount) return single;\n const outgoing: number[][] = Array.from({ length: coords.length }, () => []);\n for (let h = 0; h < heCount; h++) outgoing[heFrom[h]].push(h);\n for (const list of outgoing) {\n list.sort((h1, h2) => {\n const a1 = Math.atan2(\n coords[heTo[h1]].y - coords[heFrom[h1]].y,\n coords[heTo[h1]].x - coords[heFrom[h1]].x,\n );\n const a2 = Math.atan2(\n coords[heTo[h2]].y - coords[heFrom[h2]].y,\n coords[heTo[h2]].x - coords[heFrom[h2]].x,\n );\n return a1 - a2;\n });\n }\n // next(h) = h의 쌍둥이(to→from)에서 to 정점 나가는 반변 중 각도순 바로 이전 —\n // 한쪽 면을 일관되게 왼쪽/오른쪽에 두고 궤도(face 경계)를 돈다.\n const twin = (h: number) => (h % 2 === 0 ? h + 1 : h - 1);\n const next = (h: number): number => {\n const list = outgoing[heTo[h]];\n const idx = list.indexOf(twin(h));\n return list[(idx - 1 + list.length) % list.length];\n };\n const visited = new Array<boolean>(heCount).fill(false);\n const orbits: Point[][] = [];\n for (let start = 0; start < heCount; start++) {\n if (visited[start]) continue;\n const face: Point[] = [];\n let cur = start;\n let guard = 0;\n do {\n visited[cur] = true;\n face.push(coords[heFrom[cur]]);\n cur = next(cur);\n } while (cur !== start && !visited[cur] && guard++ <= heCount);\n if (face.length >= 3) orbits.push(face);\n }\n\n // 유계 면(채움 후보)을 면적 부호로 가른다 — 가장 큰 궤도는 무계 바깥 껍질이고,\n // 그 부호의 반대가 유계 면의 부호다. 한붓 폴리곤의 경계 그래프는 연결이라\n // 모든 면이 단순 연결(면 자체의 구멍 없음)이므로 안쪽 경계 배정은 불필요하다.\n const areas = orbits.map(signedArea);\n const faceSign = Math.sign(\n areas.reduce((best, a) => (Math.abs(a) > Math.abs(best) ? a : best), 0),\n );\n const faces = orbits.map((_, i) => i).filter((i) => Math.sign(areas[i]) === -faceSign);\n\n // 한붓 도넛 구멍의 서명 — 구멍 면의 경계는 한 점(교차점)에서 꼬집힌 단일\n // 가닥이라 경계 위 교차점이 정확히 1개다. 겹침 웨지·닫힌 포켓은 서로 다른\n // 가닥들이 만나 생기므로 경계 교차점이 2개 이상이다.\n const crossingPoints = new Set<Point>();\n for (const row of cuts) for (const c of row) crossingPoints.add(c.p);\n const boundaryCrossings = (face: Point[]): number => {\n let count = 0;\n const seen = new Set<Point>();\n for (const p of face) {\n if (crossingPoints.has(p) && !seen.has(p)) {\n seen.add(p);\n count++;\n }\n }\n return count;\n };\n\n const groups: FillGroup[] = [];\n for (const f of faces) {\n const d = inwardNormal(orbits[f]);\n if (!d) continue;\n const a = orbits[f][0];\n const b = orbits[f][1];\n const eps = 1e-9 * (Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + 1);\n const w = Math.abs(windingAt(mid(a, b), d, points, eps));\n if (w % 2 === 0 && boundaryCrossings(orbits[f]) === 1) continue; // 도넛 구멍\n groups.push({ outline: orbits[f], holes: [], layers: Math.max(1, w) });\n }\n return groups.length ? groups : single;\n}\n","import type { EditorImageErrorKind } from \"./imageDiagnosis\";\n\n/**\n * 에디터 UI 문자열(도메인 무관). 기본값은 한국어이며, 호스트가 `strings` prop으로\n * 부분 재정의해 i18n/제품별 문구를 주입한다. next-intl 등 프레임워크에 비종속 —\n * 호스트가 자기 번역 시스템으로 값을 만들어 넘기면 된다.\n */\nexport interface EditorStrings {\n contextMenu: {\n copy: string;\n paste: string;\n duplicate: string;\n delete: string;\n bringToFront: string;\n sendToBack: string;\n editVertices: string;\n merge: string;\n assistExpand: string;\n assistExclude: string;\n undo: string;\n redo: string;\n zoomToSelection: string;\n selectAll: string;\n clearSelection: string;\n };\n viewSettings: {\n title: string;\n reset: string;\n brightness: string;\n contrast: string;\n strokeSize: string;\n simplifyStrength: string;\n pixelation: string;\n cursorGuide: string;\n regionMask: string;\n keepZoomOnImageChange: string;\n wheelZoom: string;\n zoomSensitivity: string;\n };\n minimap: {\n zoomIn: string;\n zoomOut: string;\n zoom100: string;\n viewSettings: string;\n toggleMinimap: string;\n };\n canvasLabel: string;\n imageLoading: string;\n /** 문서에 이미지가 없을 때(원본 미수신 등) 오버레이 문구. */\n imageMissing: string;\n imageLoadError: string;\n /** 이미지 로드 실패 분류별 안내문(진단 오버레이). */\n imageErrorHints: Record<EditorImageErrorKind, string>;\n}\n\nexport const DEFAULT_EDITOR_STRINGS: EditorStrings = {\n contextMenu: {\n copy: \"복사\",\n paste: \"붙여넣기\",\n duplicate: \"복제\",\n delete: \"삭제\",\n bringToFront: \"맨 앞으로\",\n sendToBack: \"맨 뒤로\",\n editVertices: \"정점 편집\",\n merge: \"라벨 합치기\",\n assistExpand: \"이 지점 포함하기\",\n assistExclude: \"이 지점 제외하기\",\n undo: \"실행 취소\",\n redo: \"다시 실행\",\n zoomToSelection: \"선택 영역으로 확대\",\n selectAll: \"전체 선택\",\n clearSelection: \"선택 해제\",\n },\n // 디자인 시안에 문구가 명시된 항목은 시안 표기를 그대로 쓴다.\n viewSettings: {\n title: \"보기 설정\",\n reset: \"초기화\",\n brightness: \"밝기\",\n contrast: \"대비\",\n strokeSize: \"선 굵기\",\n simplifyStrength: \"단순화 강도\",\n pixelation: \"이미지 픽셀화\",\n cursorGuide: \"마우스 가이드라인 표시\",\n regionMask: \"ROI 표시\",\n keepZoomOnImageChange: \"이미지 변경시 확대 유지\",\n wheelZoom: \"스크롤만 사용하여 확대 축소\",\n zoomSensitivity: \"확대 축소 민감도\",\n },\n minimap: {\n zoomIn: \"확대\",\n zoomOut: \"축소\",\n zoom100: \"100%로 초기화\",\n viewSettings: \"보기 설정\",\n toggleMinimap: \"미니맵 접기/펼치기\",\n },\n canvasLabel: \"이미지 편집 영역\",\n imageLoading: \"이미지를 불러오는 중…\",\n imageMissing: \"표시할 이미지가 없습니다\",\n imageLoadError: \"이미지를 불러올 수 없습니다\",\n imageErrorHints: {\n \"mixed-content\":\n \"HTTPS 페이지에서 HTTP 이미지 요청은 혼합 콘텐츠 정책에 따라 차단됩니다. 이미지 스토리지의 HTTPS 전환이 필요합니다.\",\n cors: \"이미지 스토리지 응답에 Access-Control-Allow-Origin 헤더가 없습니다. 스토리지 또는 프록시의 CORS 설정이 필요합니다.\",\n auth: \"이미지 서버가 세션 인증(쿠키)을 요구합니다. 에디터의 이미지 요청은 자격 증명 없이 전송되므로 스토리지 인증 방식 검토가 필요합니다.\",\n forbidden:\n \"이미지 접근이 거부되었습니다. 서명 URL(presigned) 만료 또는 접근 권한 설정 점검이 필요합니다.\",\n \"not-found\": \"요청한 이미지가 서버에 존재하지 않습니다. 파일 삭제·이동 여부 확인이 필요합니다.\",\n \"server-error\": \"이미지 서버가 내부 오류를 반환했습니다. 스토리지 서버 상태 점검이 필요합니다.\",\n http: \"이미지 서버가 오류 상태 코드를 반환했습니다.\",\n offline: \"네트워크 연결이 감지되지 않습니다. 클라이언트 네트워크 상태 확인이 필요합니다.\",\n network: \"이미지 서버에 도달할 수 없습니다. 네트워크 경로·방화벽·DNS 구성 점검이 필요합니다.\",\n \"unexpected-content\":\n \"이미지 대신 다른 형식의 응답이 수신되었습니다. 게이트웨이의 인증 리다이렉트 여부 확인이 필요합니다.\",\n decode:\n \"전송은 정상이나 이미지 디코딩에 실패했습니다. 파일 손상 또는 미지원 형식일 수 있습니다.\",\n \"csp-img\":\n \"콘텐츠 보안 정책(CSP)의 img-src 지시어가 이미지 표시를 차단하고 있습니다. 정책에 이미지 스토리지 출처 추가가 필요합니다.\",\n \"csp-eval\":\n \"콘텐츠 보안 정책(CSP)이 동적 스크립트 실행(unsafe-eval)을 차단하여 렌더러 초기화에 실패했습니다.\",\n webgl:\n \"WebGL 컨텍스트를 생성할 수 없습니다. 하드웨어 가속 설정 또는 브라우저 보안 정책(Edge 보안 강화 모드 등) 점검이 필요합니다.\",\n \"renderer-init\": \"캔버스 렌더러 초기화 또는 렌더링 중 오류가 발생했습니다.\",\n unknown:\n \"원인이 특정되지 않은 오류입니다. 아래 상세 정보와 함께 기술 지원에 문의하시기 바랍니다.\",\n },\n};\n\n/** 그룹 단위 부분 재정의(그룹 안 키도 부분 지정 가능). */\nexport type EditorStringsOverride = {\n [K in keyof EditorStrings]?: EditorStrings[K] extends string ? string : Partial<EditorStrings[K]>;\n};\n\nexport function mergeEditorStrings(override?: EditorStringsOverride): EditorStrings {\n if (!override) return DEFAULT_EDITOR_STRINGS;\n return {\n contextMenu: {\n ...DEFAULT_EDITOR_STRINGS.contextMenu,\n ...override.contextMenu,\n },\n viewSettings: {\n ...DEFAULT_EDITOR_STRINGS.viewSettings,\n ...override.viewSettings,\n },\n minimap: { ...DEFAULT_EDITOR_STRINGS.minimap, ...override.minimap },\n canvasLabel: override.canvasLabel ?? DEFAULT_EDITOR_STRINGS.canvasLabel,\n imageLoading: override.imageLoading ?? DEFAULT_EDITOR_STRINGS.imageLoading,\n imageMissing: override.imageMissing ?? DEFAULT_EDITOR_STRINGS.imageMissing,\n imageLoadError: override.imageLoadError ?? DEFAULT_EDITOR_STRINGS.imageLoadError,\n imageErrorHints: {\n ...DEFAULT_EDITOR_STRINGS.imageErrorHints,\n ...override.imageErrorHints,\n },\n };\n}\n","/**\n * Editor 도구. 어떤 도구를 노출할지는 호스트가 `tools` prop으로 주입한다\n * (구버전처럼 TASK_TYPE에서 파생하지 않는다).\n */\nexport const TOOL = {\n SELECT: \"SELECT\",\n POLYGON: \"POLYGON\",\n PATH: \"PATH\",\n BRUSH: \"BRUSH\",\n RECTANGLE: \"RECTANGLE\",\n ROTATED_RECTANGLE: \"ROTATED_RECTANGLE\",\n CIRCLE: \"CIRCLE\",\n POINT: \"POINT\",\n /** AI 어시스트: 박스 프롬프트(드래그 → 추론) → 폴리곤 커밋. assistant.infer 필요. */\n ASSISTANT_POLYGON: \"ASSISTANT_POLYGON\",\n /**\n * AI 어시스트: 박스 프롬프트(드래그 → 추론) → 추론 폴리곤의 바운딩으로 사각형 커밋.\n * assistant.rectResult가 \"rotatedRect\"면 최소넓이 회전사각형(OBB), 아니면 축정렬 RECT.\n */\n ASSISTANT_RECT: \"ASSISTANT_RECT\",\n /** AI 어시스트: 포인트 프롬프트(클릭 +, alt-클릭 −). 선택 폴리곤이 있으면 refine. */\n ASSISTANT_POINT: \"ASSISTANT_POINT\",\n} as const;\n\nexport type BuiltInTool = (typeof TOOL)[keyof typeof TOOL];\nexport type Tool = BuiltInTool | (string & {});\n\n/** 붓(스칼라) 서브모드 — 그리기/지우기. */\nexport type BrushScalarMode = \"draw\" | \"erase\";\n","/** 에디터-로컬 보기/조작 환경설정(도메인 무관). props는 초기값(default)으로만 받는다. */\nexport interface ViewSettings {\n brightness: number;\n contrast: number;\n showCursorGuide: boolean;\n imageSmoothing: boolean;\n strokeSize: number;\n /** 자유선/붓→폴리곤 단순화 강도(RDP epsilon, 이미지 px). 높을수록 점이 적어짐. */\n simplifyStrength: number;\n showRegionMask: boolean;\n keepZoomOnImageChange: boolean;\n wheelZoom: boolean;\n /** 휠/핀치 확대·축소 민감도 배율(1 = 기본). 마우스별 휠 이벤트 밀도 차이 보정용. */\n zoomSensitivity: number;\n}\n\nexport const DEFAULT_VIEW_SETTINGS: ViewSettings = {\n brightness: 1,\n contrast: 1,\n showCursorGuide: false,\n imageSmoothing: true,\n strokeSize: 2,\n simplifyStrength: 1.5,\n showRegionMask: true,\n keepZoomOnImageChange: false,\n wheelZoom: true,\n zoomSensitivity: 1,\n};\n\n/** 숫자형 보기 설정의 허용 범위 — 슬라이더와 클램프가 공유하는 단일 출처. */\nexport interface ViewSettingRange {\n min: number;\n max: number;\n step: number;\n}\n\n/**\n * 밝기/대비는 0에 가까우면 완전 검정·평면 회색이 되어 이미지가 사라지고,\n * 너무 높으면 화이트아웃된다. 사진을 계속 식별할 수 있는 구간으로 묶는다.\n */\nexport const VIEW_SETTING_RANGES = {\n brightness: { min: 0.5, max: 1.5, step: 0.05 },\n contrast: { min: 0.5, max: 1.5, step: 0.05 },\n strokeSize: { min: 1, max: 10, step: 0.5 },\n simplifyStrength: { min: 0.5, max: 5, step: 0.5 },\n zoomSensitivity: { min: 0.2, max: 3, step: 0.1 },\n} as const satisfies Partial<Record<keyof ViewSettings, ViewSettingRange>>;\n\ntype RangedKey = keyof typeof VIEW_SETTING_RANGES;\n\nconst RANGED_KEYS = Object.keys(VIEW_SETTING_RANGES) as RangedKey[];\n\n/**\n * 범위 밖 값을 허용 구간 안으로 되돌린다(구버전 저장값 마이그레이션 겸용).\n * NaN/Infinity는 기본값으로 되살린다. 지정되지 않은(undefined) 키는 만들어내지 않으므로\n * 부분 패치에도 그대로 쓸 수 있다. 고칠 게 없으면 새 객체를 만들지 않고 입력을 그대로 반환한다.\n */\nexport function clampViewSettings<T extends Partial<ViewSettings>>(settings: T): T {\n const fixes: Partial<Record<RangedKey, number>> = {};\n for (const key of RANGED_KEYS) {\n const value = settings[key];\n if (value === undefined) continue;\n const { min, max } = VIEW_SETTING_RANGES[key];\n const fixed = Number.isFinite(value)\n ? Math.min(max, Math.max(min, value as number))\n : DEFAULT_VIEW_SETTINGS[key];\n if (fixed !== value) fixes[key] = fixed;\n }\n return Object.keys(fixes).length ? { ...settings, ...fixes } : settings;\n}\n","import type { CSSProperties } from \"react\";\nimport type { AssistantPromptPoint } from \"../_model/props\";\nimport type { AssistantStatus } from \"../_state/useAssistant\";\n\n/**\n * AI 어시스트 오버레이. 프롬프트 포인트(+/−) 마커와 진행 표시를 그린다.\n * 결과 폴리곤은 즉시 실제 도형으로 커밋되므로 여기선 그리지 않는다.\n * 캔버스 오버레이 레이어(이미지 좌표) 안에 놓여 뷰포트를 따라가고, 마커/배지는\n * inverse-scale로 화면 크기를 일정하게 유지한다. 렌더러 무관(순수 DOM).\n */\n\nconst INV = \"var(--editor-overlay-inverse-scale, 1)\";\n\nconst POS = \"#377be2\";\nconst NEG = \"#e23c3c\";\n\nfunction Marker({ point }: { point: AssistantPromptPoint }) {\n const color = point.positive ? POS : NEG;\n const badge: CSSProperties = {\n position: \"absolute\",\n left: point.x,\n top: point.y,\n width: 18,\n height: 18,\n marginLeft: -9,\n marginTop: -9,\n borderRadius: \"50%\",\n background: color,\n border: \"2px solid #fff\",\n boxShadow: \"0 0 3px rgba(0,0,0,0.5)\",\n color: \"#fff\",\n fontSize: 13,\n fontWeight: 700,\n lineHeight: \"14px\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n transform: `scale(${INV})`,\n transformOrigin: \"center\",\n };\n return <div style={badge}>{point.positive ? \"+\" : \"−\"}</div>;\n}\n\nexport function AssistantOverlay({\n image,\n points,\n boxes,\n status,\n}: {\n image: { w: number; h: number };\n points: AssistantPromptPoint[];\n /** 진행 중인 박스 프롬프트들(병렬 요청 — 각각 shimmer 표시). */\n boxes: { x: number; y: number; width: number; height: number }[];\n status: AssistantStatus;\n}) {\n return (\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n width: image.w,\n height: image.h,\n pointerEvents: \"none\",\n }}\n >\n <style>{`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}</style>\n {boxes.map((box, i) => (\n // 추론 중 박스 영역마다 좌↔우 shimmer 스윕(옵스 LabelAssistantProgress 이식).\n <div\n key={`box-${i}-${box.x}-${box.y}-${box.width}-${box.height}`}\n style={{\n position: \"absolute\",\n left: box.x,\n top: box.y,\n width: box.width,\n height: box.height,\n boxSizing: \"border-box\",\n border:\n \"calc(2px * var(--editor-overlay-inverse-scale, 1)) solid rgba(255,255,255,0.9)\",\n backgroundImage:\n \"linear-gradient(90deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0.10) 100%)\",\n backgroundSize: \"200% 100%\",\n animation: \"editorv2-assistant-shimmer 1.4s linear infinite\",\n }}\n />\n ))}\n {/* +/− 마커는 포인트 추론 진행 중에만(박스 pending으로 오버레이가 떠 있을 때\n 이전 세션 점이 남아 보이지 않도록). 진행 표시는 shimmer와 하단 툴바 전환이\n 담당 — 별도 스피너 필은 두지 않는다. */}\n {status === \"loading\" &&\n points.map((pt, i) => <Marker key={`pt-${i}-${pt.x}-${pt.y}`} point={pt} />)}\n </div>\n );\n}\n","import { Menu } from \"../../Menu\";\nimport type { ContextMenuItem } from \"../_model/props\";\n\nexport type { ContextMenuItem };\n\n/**\n * 구분선 정규화 — 선두/말미 제거 + 연속 구분선 접기.\n * 호스트가 getContextMenuItems로 항목을 걸러내면 그룹 사이 구분선만 줄줄이 남을 수\n * 있어서, 렌더 직전에 방어적으로 정리한다(호스트 필터는 항목만 신경 쓰면 된다).\n */\nfunction normalizeItems(items: ContextMenuItem[]): ContextMenuItem[] {\n const out: ContextMenuItem[] = [];\n for (const item of items) {\n if (\"separator\" in item) {\n if (!out.length || \"separator\" in out[out.length - 1]) continue;\n out.push(item);\n } else {\n out.push(item);\n }\n }\n while (out.length && \"separator\" in out[out.length - 1]) out.pop();\n return out;\n}\n\n/**\n * 캔버스 우클릭 컨텍스트 메뉴(도메인 무관). 항목/위치는 호출부가 결정한다.\n * @aivex/ui Menu(Radix Dropdown)를 커서 위치의 0크기 트리거에 앵커해 띄운다.\n * 바깥 클릭·Escape·스크롤 닫힘은 Radix가 onOpenChange로 처리한다(비모달).\n */\nexport function ContextMenu({\n x,\n y,\n items: rawItems,\n onClose,\n}: {\n x: number;\n y: number;\n items: ContextMenuItem[];\n onClose: () => void;\n}) {\n const items = normalizeItems(rawItems);\n return (\n <Menu\n open\n modal={false}\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n >\n <Menu.Trigger asChild>\n {/* 커서 위치의 0크기 앵커. Content가 이 지점 기준으로 뜬다. */}\n <span aria-hidden style={{ position: \"absolute\", left: x, top: y, width: 0, height: 0 }} />\n </Menu.Trigger>\n <Menu.Content\n side=\"bottom\"\n align=\"start\"\n sideOffset={2}\n collisionPadding={8}\n // 메뉴가 위아래 어디에도 다 안 들어갈 만큼 길면 Radix flip/shift로는\n // 부족하다 — 가용 높이로 클램프하고 내부 스크롤로 넘긴다.\n style={{\n maxHeight: \"var(--radix-dropdown-menu-content-available-height)\",\n overflowY: \"auto\",\n }}\n onContextMenu={(e) => e.preventDefault()}\n onCloseAutoFocus={(e) => e.preventDefault()}\n >\n {/* shrink-0: Content(flex-col)가 가용 높이로 클램프될 때 항목이\n 눌리는 대신 overflow 스크롤이 생기도록. */}\n {items.map((item, i) => {\n if (\"separator\" in item) {\n return <Menu.Separator key={`sep-${i}`} className=\"aivex:shrink-0\" />;\n }\n return (\n <Menu.Item\n key={item.label}\n danger={item.danger}\n disabled={item.disabled}\n className=\"aivex:shrink-0\"\n onSelect={() => item.onClick()}\n >\n <span className=\"aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6\">\n <span className=\"aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5\">\n {item.icon}\n <span className=\"aivex:truncate\">{item.label}</span>\n </span>\n {item.shortcut && <Menu.Shortcut>{item.shortcut}</Menu.Shortcut>}\n </span>\n </Menu.Item>\n );\n })}\n </Menu.Content>\n </Menu>\n );\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * 마우스 위치에 십자 가이드라인을 그리는 오버레이(도메인 무관).\n * 부모(컨테이너)를 채우고 pointer-events 없음 → 캔버스 상호작용 방해 안 함.\n * 고빈도(mousemove)라 React state 없이 line ref를 명령형 갱신.\n */\nexport function CursorGuide({ color = \"#1e88e5\" }: { color?: string }) {\n const rootRef = useRef<HTMLDivElement>(null);\n const vRef = useRef<HTMLDivElement>(null);\n const hRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const root = rootRef.current;\n const v = vRef.current;\n const h = hRef.current;\n if (!root || !v || !h) return;\n\n const onMove = (e: MouseEvent) => {\n const r = root.getBoundingClientRect();\n const x = e.clientX - r.left;\n const y = e.clientY - r.top;\n if (x < 0 || y < 0 || x > r.width || y > r.height) {\n v.style.display = \"none\";\n h.style.display = \"none\";\n return;\n }\n v.style.display = \"block\";\n h.style.display = \"block\";\n v.style.transform = `translateX(${x}px)`;\n h.style.transform = `translateY(${y}px)`;\n };\n const onLeave = () => {\n v.style.display = \"none\";\n h.style.display = \"none\";\n };\n\n window.addEventListener(\"mousemove\", onMove);\n root.parentElement?.addEventListener(\"mouseleave\", onLeave);\n return () => {\n window.removeEventListener(\"mousemove\", onMove);\n root.parentElement?.removeEventListener(\"mouseleave\", onLeave);\n };\n }, []);\n\n return (\n <div\n ref={rootRef}\n className=\"aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden\"\n >\n <div\n ref={vRef}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: 1,\n height: \"100%\",\n background: color,\n opacity: 0.6,\n display: \"none\",\n }}\n />\n <div\n ref={hRef}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: 1,\n background: color,\n opacity: 0.6,\n display: \"none\",\n }}\n />\n </div>\n );\n}\n","import type { ReactNode } from \"react\";\nimport type { EditorImageDiagnosis, EditorImageErrorKind } from \"../_model/imageDiagnosis\";\nimport { DEFAULT_EDITOR_STRINGS } from \"../_model/strings\";\n\n/**\n * 이미지 로딩/에러 상태 오버레이. 에디터 영역 전체를 덮는다.\n * 호스트가 renderImageState로 커스텀하지 않으면 기본 스피너/에러 메시지를 그린다.\n * 에러에 진단(diagnosis)이 있으면 원인 안내문과 기술 근거를 함께 표시한다.\n */\nexport function ImageStateOverlay({\n status,\n error,\n render,\n loadingLabel = DEFAULT_EDITOR_STRINGS.imageLoading,\n missingLabel = DEFAULT_EDITOR_STRINGS.imageMissing,\n errorLabel = DEFAULT_EDITOR_STRINGS.imageLoadError,\n errorHints = DEFAULT_EDITOR_STRINGS.imageErrorHints,\n}: {\n status: \"loading\" | \"error\" | \"missing\";\n error?: EditorImageDiagnosis | null;\n render?: (\n status: \"loading\" | \"error\" | \"missing\",\n diagnosis?: EditorImageDiagnosis | null,\n ) => ReactNode;\n loadingLabel?: string;\n missingLabel?: string;\n errorLabel?: string;\n errorHints?: Record<EditorImageErrorKind, string>;\n}) {\n // 커스텀 렌더가 null/undefined를 주면 기본 표시로 폴백한다 — 어떤 조합에서도\n // \"메시지 없는 회색 화면\"이 만들어질 수 없게 하는 불변식.\n const custom = render?.(status, error) ?? null;\n return (\n <div\n // e2e가 이미지 로딩 완료를 기다리는 앵커(로딩/에러 중에만 존재).\n data-track-id={\n status === \"loading\"\n ? \"editor-image-loading-wrap\"\n : status === \"missing\"\n ? \"editor-image-missing-wrap\"\n : \"editor-image-error-wrap\"\n }\n style={{\n position: \"absolute\",\n inset: 0,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: status === \"error\" ? \"rgba(13,13,18,1)\" : \"rgba(13,13,18,0.6)\",\n backdropFilter: status === \"loading\" ? \"blur(2px)\" : undefined,\n color: \"#fff\",\n fontFamily: \"Pretendard, sans-serif\",\n pointerEvents: status === \"error\" ? \"auto\" : \"none\",\n }}\n >\n {custom !== null ? (\n custom\n ) : status === \"missing\" ? (\n <div style={{ fontSize: 13, opacity: 0.75 }}>{missingLabel}</div>\n ) : status === \"loading\" ? (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n fontSize: 13,\n }}\n >\n <span\n style={{\n width: 18,\n height: 18,\n borderRadius: \"50%\",\n border: \"2px solid rgba(255,255,255,0.3)\",\n borderTopColor: \"#fff\",\n animation: \"editorv2-image-spin 0.7s linear infinite\",\n }}\n />\n {loadingLabel}\n <style>{`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`}</style>\n </div>\n ) : (\n <div style={{ textAlign: \"center\", opacity: 0.85, maxWidth: 420, padding: \"0 16px\" }}>\n <div style={{ fontSize: 28, marginBottom: 6 }}>⚠</div>\n <div style={{ fontSize: 13 }}>{errorLabel}</div>\n {error && (\n <>\n <div style={{ fontSize: 12, marginTop: 8, opacity: 0.8, lineHeight: 1.5 }}>\n {errorHints[error.kind]}\n </div>\n <div\n style={{\n fontSize: 11,\n marginTop: 6,\n opacity: 0.55,\n fontFamily: \"ui-monospace, monospace\",\n wordBreak: \"break-all\",\n }}\n >\n {error.detail}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n );\n}\n","// Editor 시각/상호작용 상수(화면 px 기준 다수). 컴포넌트·훅 공용.\n\nexport const MIN_SCALE = 0.1;\nexport const MAX_SCALE = 10;\nexport const ZOOM_FACTOR = 1.1;\nexport const POINT_RADIUS = 5; // 점 도형 화면상 반경(px).\nexport const HANDLE_RADIUS = 5; // 꼭짓점 핸들 화면상 반경(px).\nexport const HANDLE_SQUARE = 8; // 바운딩박스 핸들 화면상 한 변(px).\nexport const HANDLE_NAME = \"v2-handle\"; // 핸들 식별(선택 해제 가드용).\nexport const FIXED_NAME = \"v2-fixed\"; // 줌과 무관히 화면상 크기 고정(핸들+점). 줌 시 역-스케일.\nexport const HANDLE_COLOR = \"#1e88e5\";\nexport const POLY_CLOSE_PX = 12; // 폴리곤 첫 꼭짓점 근처(화면 px) 클릭 시 닫기.\nexport const ROTATE_GAP_PX = 28; // 회전 핸들이 bbox 위로 떨어진 거리(화면 px).\nexport const NUDGE_PX = 1; // 방향키 이동 거리(이미지 px).\nexport const NUDGE_BIG_PX = 10; // Shift+방향키 이동 거리.\nexport const DUPLICATE_OFFSET_PX = 12; // 복제 시 어긋나는 거리.\nexport const ROTATE_SNAP_RAD = Math.PI / 12; // Shift 회전 스냅(15°).\n// 미니맵 정사각 한 변(px). 패널 폭(220) - 좌우 패딩(8×2). 이미지는 레터박스로 중앙 정렬.\nexport const MINIMAP_SIZE = 204;\nexport const MINIMAP_VP_STROKE = \"#00ff00\"; // 뷰포트 사각형 색(구버전과 동일).\nexport const MINIMAP_VP_FILL = \"rgba(0, 255, 0, 0.1)\";\nexport const DEFAULT_COLOR = \"#00e5ff\";\nexport const SELECTED_COLOR = \"#ffffff\";\nexport const STROKE_SIZE = 2; // 도형 선 두께(화면 px). 구버전 옵스 기본값과 동일.\nexport const SELECTION_BORDER_COLOR = \"#669DEF\"; // 선택 도형 테두리(구버전 TRANSFORMER.BORDER_COLOR).\nexport const SELECTION_BORDER_PAD = 3; // 선택 테두리를 도형 bbox 바깥으로 띄우는 거리(화면 px).\nexport const SELECTION_AREA_COLOR = \"#669DEF\";\nexport const SELECTION_AREA_FILL_ALPHA = 0.1;\nexport const FILL_ALPHA_HEX = \"20\"; // 채움 색 알파(구버전 `${color}20` = 약 12.5%).\nexport const FILL_ALPHA = 0x20 / 0xff;\nexport const ROI_BORDER_COLOR = \"#ffffff\"; // ROI/제외영역 점선 테두리 색.\nexport const ROI_BORDER_WIDTH = 2; // ROI 테두리 두께(화면 px — 줌과 무관하게 고정).\nexport const ROI_BORDER_DASH: [number, number] = [6, 6]; // ROI 점선 패턴(화면 px).\n/**\n * style.dashed 도형 점선 — [칸 배수, 간격 배수].\n * 칸이 선 두께의 2배 미만이면 점처럼 자글거리고 6배 이상이면 짧은 변에서 실선처럼\n * 보인다. 꼭짓점 많은 폴리곤을 감안해 3배·1:1로 둔다.\n */\nexport const DASHED_SCALE: [number, number] = [3, 3];\n","import { DASHED_SCALE, DEFAULT_COLOR, FILL_ALPHA, POINT_RADIUS, STROKE_SIZE } from \"../_constants\";\nimport type { EditorShape } from \"./geometry\";\n\nexport interface ResolvedShapeRenderStyle {\n color: string;\n strokeWidth: number;\n opacity: number;\n fillAlpha: number;\n fillVisible: boolean;\n dash?: number[];\n pointRadius: number;\n}\n\nexport interface ShapeRenderStyleDefaults {\n strokeWidth?: number;\n pointRadius?: number;\n}\n\nexport function resolveShapeRenderStyle(\n shape: EditorShape,\n defaults: ShapeRenderStyleDefaults = {},\n): ResolvedShapeRenderStyle {\n // 외형은 style에서만 온다. readOnly는 편집 가능 여부(동작)일 뿐 생김새를 바꾸지 않는다 —\n // 읽기 전용처럼 보이고 싶으면 호출부가 dashed·opacity·strokeWidth로 표현한다.\n const color = shape.style?.color ?? DEFAULT_COLOR;\n const strokeWidth = shape.style?.strokeWidth ?? defaults.strokeWidth ?? STROKE_SIZE;\n const opacity = shape.style?.opacity ?? 1;\n const fillAlpha = shape.style?.fillOpacity ?? FILL_ALPHA;\n // 점선은 확정된 선 두께에 배수를 곱해 만든다 — 두께가 바뀌어도 칸/두께 비율이 유지된다.\n // 소비처는 dashed로 의도만 밝히고 배수(DASHED_SCALE)는 여기서 정한다.\n const dash =\n shape.style?.dash ??\n (shape.style?.dashed\n ? [strokeWidth * DASHED_SCALE[0], strokeWidth * DASHED_SCALE[1]]\n : undefined);\n\n return {\n color,\n strokeWidth,\n opacity,\n fillAlpha,\n fillVisible: !!shape.style?.filled,\n dash,\n pointRadius: shape.style?.pointRadius ?? defaults.pointRadius ?? POINT_RADIUS,\n };\n}\n\nexport function colorWithAlpha(color: string, alpha: number): string {\n const clampedAlpha = Math.max(0, Math.min(1, alpha));\n const hex = color.trim().replace(\"#\", \"\");\n if (hex.length === 3 || hex.length === 6) {\n const normalized = hex.length === 3 ? hex.replace(/./g, (char) => char + char) : hex;\n const value = Number.parseInt(normalized, 16);\n if (!Number.isNaN(value)) {\n const r = (value >> 16) & 255;\n const g = (value >> 8) & 255;\n const b = value & 255;\n return `rgba(${r}, ${g}, ${b}, ${clampedAlpha})`;\n }\n }\n return color;\n}\n","import { memo } from \"react\";\nimport type { EditorShape } from \"../_model/geometry\";\nimport { getBBox, SHAPE_TYPE } from \"../_model/geometry\";\nimport { resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\n\n// 미니맵용 도형 1개를 이미지 좌표 그대로 SVG로 렌더(부모 SVG viewBox가 축소 담당,\n// stroke는 non-scaling으로 화면 px 고정). 점 도형만 채움, 나머지는 외곽선.\nexport const MinimapShape = memo(function MinimapShape<TMeta>({\n shape,\n strokeSize,\n register,\n}: {\n shape: EditorShape<TMeta>;\n strokeSize?: number;\n register?: (id: string, el: SVGElement | null) => void;\n}) {\n const { type, points } = shape;\n const style = resolveShapeRenderStyle(shape, { strokeWidth: strokeSize });\n const ref = (el: SVGElement | null) => register?.(shape.id, el);\n const common = {\n ref,\n stroke: style.color,\n strokeWidth: style.strokeWidth,\n strokeDasharray: style.dash?.join(\" \"),\n opacity: style.opacity,\n fill: style.fillVisible && type !== SHAPE_TYPE.LINE ? style.color : \"none\",\n fillOpacity: style.fillAlpha,\n vectorEffect: \"non-scaling-stroke\" as const,\n };\n if (type === SHAPE_TYPE.POINT) {\n return (\n <circle\n ref={ref}\n cx={points[0].x}\n cy={points[0].y}\n r={style.pointRadius}\n fill={style.color}\n opacity={style.opacity}\n />\n );\n }\n if (type === SHAPE_TYPE.RECTANGLE || type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n if (type === SHAPE_TYPE.ELLIPSE) {\n return (\n <ellipse\n cx={(b.minX + b.maxX) / 2}\n cy={(b.minY + b.maxY) / 2}\n rx={(b.maxX - b.minX) / 2}\n ry={(b.maxY - b.minY) / 2}\n {...common}\n />\n );\n }\n return (\n <rect x={b.minX} y={b.minY} width={b.maxX - b.minX} height={b.maxY - b.minY} {...common} />\n );\n }\n const pts = points.map((p) => `${p.x},${p.y}`).join(\" \");\n if (type === SHAPE_TYPE.LINE) return <polyline points={pts} {...common} />;\n // fillRule: 자기교차 폴리곤(도넛)의 구멍을 비운다 — 캔버스 렌더러들과 동일한 evenodd.\n return <polygon points={pts} fillRule=\"evenodd\" {...common} />; // POLYGON, ROTATED_RECTANGLE\n});\n","import type { CSSProperties } from \"react\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\n\n/**\n * 영역 마스크 오버레이 SVG — 미니맵용.\n * 보이는 영역 밖을 딤으로 덮고, 가림 영역은 다시 덮으며, 경계선은 리졸브된\n * 윤곽 선분만 점선으로 그린다(미니맵 축소 특성상 색은 단일 흰색).\n * 좌표계는 이미지 좌표(viewBox=image), 화면 크기/선 두께는 호출부가 정한다.\n */\nexport function RegionOverlay({\n image,\n region,\n maskId,\n width,\n height,\n strokeWidth,\n strokeDasharray,\n style,\n}: {\n image: { w: number; h: number };\n region: RegionOverlayData;\n maskId: string;\n width: number;\n height: number;\n strokeWidth: number | string;\n strokeDasharray: string;\n style?: CSSProperties;\n}) {\n const outlines = [...region.visibleOutline, ...region.occludedOutline];\n return (\n <svg\n width={width}\n height={height}\n viewBox={`0 0 ${image.w} ${image.h}`}\n style={style}\n aria-hidden\n >\n <defs>\n <mask id={maskId}>\n <rect x={0} y={0} width={image.w} height={image.h} fill=\"white\" />\n {region.rects.map((r, i) => (\n <rect key={r.id ?? `area-${i}`} x={r.x} y={r.y} width={r.w} height={r.h} fill=\"black\" />\n ))}\n {region.zones.map((z, i) => (\n <polygon\n key={`occ-${i}`}\n points={z.points.map((p) => `${p.x},${p.y}`).join(\" \")}\n fill=\"white\"\n />\n ))}\n </mask>\n </defs>\n <rect\n x={0}\n y={0}\n width={image.w}\n height={image.h}\n fill={region.dim.color}\n fillOpacity={region.dim.opacity}\n mask={`url(#${maskId})`}\n />\n {outlines.length > 0 && (\n <path\n d={outlines.map(([a, b]) => `M${a.x} ${a.y}L${b.x} ${b.y}`).join(\"\")}\n fill=\"none\"\n stroke=\"#fff\"\n strokeWidth={strokeWidth}\n strokeDasharray={strokeDasharray}\n vectorEffect=\"non-scaling-stroke\"\n />\n )}\n </svg>\n );\n}\n","import type { ReactNode } from \"react\";\nimport { Button } from \"../../Button\";\nimport { Divider } from \"../../Divider\";\nimport {\n BrightIcon,\n ContrastIcon,\n PencilIcon,\n RefreshIcon,\n StrokeIcon,\n WheelIcon,\n} from \"../../Icon\";\nimport { Popover } from \"../../Popover\";\nimport { Slider } from \"../../Slider\";\nimport { Switch } from \"../../Switch\";\nimport { DEFAULT_EDITOR_STRINGS, type EditorStrings } from \"../_model/strings\";\nimport { VIEW_SETTING_RANGES, type ViewSettings } from \"../_model/viewSettings\";\n\nexport {\n DEFAULT_VIEW_SETTINGS,\n VIEW_SETTING_RANGES,\n type ViewSettings,\n} from \"../_model/viewSettings\";\n\n/** 보기 설정 항목 키 — 슬라이더 5종 + 토글 6종. */\nexport type ViewSettingItemKey =\n | \"brightness\"\n | \"contrast\"\n | \"strokeSize\"\n | \"simplifyStrength\"\n | \"zoomSensitivity\"\n | \"pixelation\"\n | \"cursorGuide\"\n | \"regionMask\"\n | \"keepZoomOnImageChange\"\n | \"wheelZoom\";\n\n/** 기본 항목 구성 — 전 항목, 기존 표시 순서. 호스트가 items로 재구성한다. */\nexport const DEFAULT_VIEW_SETTING_ITEMS: ViewSettingItemKey[] = [\n \"brightness\",\n \"contrast\",\n \"strokeSize\",\n \"simplifyStrength\",\n \"zoomSensitivity\",\n \"pixelation\",\n \"cursorGuide\",\n \"regionMask\",\n \"keepZoomOnImageChange\",\n \"wheelZoom\",\n];\n\nconst SLIDER_KEYS = new Set<ViewSettingItemKey>([\n \"brightness\",\n \"contrast\",\n \"strokeSize\",\n \"simplifyStrength\",\n \"zoomSensitivity\",\n]);\n\n/**\n * 미니맵 기어 버튼에서 열리는 보기 설정 팝오버(도메인 무관).\n * 바깥 클릭/Esc로 닫힘. 값은 호출부가 소유하고 onChange로 부분 갱신.\n * 컨트롤은 @aivex/ui(Button/Slider/Switch/Divider)로 렌더한다.\n */\nexport function SettingsPanel({\n value,\n defaults,\n onChange,\n labels = DEFAULT_EDITOR_STRINGS.viewSettings,\n items = DEFAULT_VIEW_SETTING_ITEMS,\n openDown = false,\n alignEnd = false,\n}: {\n value: ViewSettings;\n /** \"초기화\"가 되돌릴 기준값 — 호스트 기본값이 반영된 시드. */\n defaults: ViewSettings;\n onChange: (patch: Partial<ViewSettings>) => void;\n /** UI 문자열. 기본 한국어. */\n labels?: EditorStrings[\"viewSettings\"];\n /**\n * 표시할 항목과 순서 — 제품마다 노출 범위가 다르다(예: 아이브데이터는\n * 단순화 강도·픽셀화 없음, 6547:201301). 슬라이더와 토글은\n * 각자 블록 안에서 이 배열의 순서를 따른다.\n */\n items?: ViewSettingItemKey[];\n /** 미니맵이 위쪽 모서리에 붙으면 팝오버는 아래로 연다(기본은 위로). */\n openDown?: boolean;\n /** 미니맵이 오른쪽 모서리에 붙으면 우측 정렬로 열어 화면 밖으로 나가지 않게 한다. */\n alignEnd?: boolean;\n}) {\n return (\n <Popover.Content\n aria-label={labels.title}\n side={openDown ? \"bottom\" : \"top\"}\n align={alignEnd ? \"end\" : \"start\"}\n sideOffset={8}\n className=\"aivex:max-h-none aivex:overflow-visible aivex:shadow-[var(--aivex-elevation-md)]\"\n >\n <div className=\"aivex:px-xs aivex:text-body-md\">{labels.title}</div>\n\n {/* 컨테이너는 제목/본문/버튼을 12px로 벌리고, 본문 안 항목 간격은 8px.\n 항목 종류·순서는 items가 정한다 — 슬라이더 블록 뒤 토글 블록. */}\n <div className=\"aivex:flex aivex:flex-col aivex:gap-md\">\n {items\n .filter((key) => SLIDER_KEYS.has(key))\n .map((key) => {\n const slider = SLIDER_ROWS[key as SliderKey];\n return (\n <Row\n icon={slider.icon}\n key={key}\n label={labels[key as SliderKey]}\n value={slider.format(value[key as SliderKey])}\n >\n <Slider\n {...VIEW_SETTING_RANGES[key as SliderKey]}\n value={[value[key as SliderKey]]}\n onValueChange={([v]) => onChange({ [key]: v })}\n />\n </Row>\n );\n })}\n\n <div className=\"aivex:flex aivex:flex-col aivex:gap-xs\">\n {items\n .filter((key) => !SLIDER_KEYS.has(key))\n .map((key) => {\n const toggle = TOGGLE_ROWS[key as ToggleKey];\n return (\n <Toggle\n checked={toggle.checked(value)}\n key={key}\n label={labels[key as ToggleKey]}\n onChange={(v) => onChange(toggle.patch(v))}\n />\n );\n })}\n </div>\n\n <Divider />\n </div>\n\n {/* 초기화는 헤더가 아니라 하단 우측 — 실수로 누르기 어려운 자리. */}\n <div className=\"aivex:flex aivex:justify-end\">\n <Button\n variant=\"solid\"\n color=\"secondary\"\n size=\"md\"\n onClick={() => onChange({ ...defaults })}\n >\n <RefreshIcon size={20} />\n {labels.reset}\n </Button>\n </div>\n </Popover.Content>\n );\n}\n\n/**\n * 밝기/대비는 CSS 필터 배율(1 = 원본)로 저장하지만, 표시는 퍼센트가 직관적이다.\n * 저장값·ctx.filter에 들어가는 값은 그대로 배율이고 여기서 라벨만 바꾼다.\n */\nfunction formatPercent(multiplier: number) {\n return `${Math.round(multiplier * 100)}%`;\n}\n\ntype SliderKey = \"brightness\" | \"contrast\" | \"strokeSize\" | \"simplifyStrength\" | \"zoomSensitivity\";\ntype ToggleKey = Exclude<ViewSettingItemKey, SliderKey>;\n\n/** 슬라이더 행 정의 — 아이콘과 값 표기. 범위·라벨은 키로 함께 찾는다. */\nconst SLIDER_ROWS: Record<SliderKey, { icon: ReactNode; format: (v: number) => string }> = {\n brightness: { icon: <BrightIcon size={16} />, format: formatPercent },\n contrast: { icon: <ContrastIcon size={16} />, format: formatPercent },\n strokeSize: { icon: <StrokeIcon size={16} />, format: String },\n simplifyStrength: { icon: <PencilIcon size={16} />, format: String },\n zoomSensitivity: {\n icon: <WheelIcon size={16} />,\n format: (v) => v.toFixed(1),\n },\n};\n\n/** 토글 행 정의 — 설정값과의 대응(픽셀화는 imageSmoothing의 반전이다). */\nconst TOGGLE_ROWS: Record<\n ToggleKey,\n {\n checked: (value: ViewSettings) => boolean;\n patch: (v: boolean) => Partial<ViewSettings>;\n }\n> = {\n pixelation: {\n checked: (value) => !value.imageSmoothing,\n patch: (v) => ({ imageSmoothing: !v }),\n },\n cursorGuide: {\n checked: (value) => value.showCursorGuide,\n patch: (v) => ({ showCursorGuide: v }),\n },\n regionMask: {\n checked: (value) => value.showRegionMask,\n patch: (v) => ({ showRegionMask: v }),\n },\n keepZoomOnImageChange: {\n checked: (value) => value.keepZoomOnImageChange,\n patch: (v) => ({ keepZoomOnImageChange: v }),\n },\n wheelZoom: {\n checked: (value) => value.wheelZoom,\n patch: (v) => ({ wheelZoom: v }),\n },\n};\n\nfunction Row({\n icon,\n label,\n value,\n children,\n}: {\n icon: ReactNode;\n label: string;\n /** 현재 값 — 시안에는 없지만 정확한 수치가 필요해 우측에 표시한다. */\n value: string;\n children: ReactNode;\n}) {\n return (\n <div className=\"aivex:flex aivex:flex-col aivex:px-md aivex:py-2xs\">\n <div className=\"aivex:flex aivex:items-center aivex:gap-xs\">\n <span className=\"aivex:flex aivex:h-4 aivex:items-center aivex:text-text-secondary\">\n {icon}\n </span>\n <span className=\"aivex:flex-1 aivex:truncate aivex:text-label-md\">{label}</span>\n <span className=\"aivex:tabular-nums aivex:text-label-md aivex:text-text-secondary\">\n {value}\n </span>\n </div>\n {/* 레이블과 트랙 사이 여백은 대부분 Slider 루트가 썸(24px)을 담으려 잡는 높이다.\n 루트를 20px로 낮춰 트랙 위 여유를 8px→6px로 줄인다(썸은 넘쳐도 잘리지 않음). */}\n <div className=\"aivex:flex aivex:h-5 aivex:items-center\">{children}</div>\n </div>\n );\n}\n\nfunction Toggle({\n label,\n checked,\n onChange,\n}: {\n label: string;\n checked: boolean;\n onChange: (v: boolean) => void;\n}) {\n return (\n <div className=\"aivex:flex aivex:items-center aivex:gap-md aivex:rounded-md aivex:px-md aivex:py-sm\">\n <span className=\"aivex:flex-1 aivex:truncate aivex:text-label-lg\">{label}</span>\n {/* 디자인 트랙 32×20 = Switch md. 220px 좁은 패널 시절의 sm은 이제 작다. */}\n <Switch size=\"md\" checked={checked} onCheckedChange={onChange} />\n </div>\n );\n}\n","import { memo, type RefObject } from \"react\";\nimport { Button } from \"../../Button\";\nimport { CaretLineDownIcon, MapIcon, MinusIcon, PlusIcon, SettingIcon } from \"../../Icon\";\nimport { Popover } from \"../../Popover\";\nimport { MINIMAP_SIZE, MINIMAP_VP_FILL, MINIMAP_VP_STROKE } from \"../_constants\";\nimport { type EditorShape, isShapeVisible, sortShapesForRender } from \"../_model/geometry\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\nimport type { MinimapPosition } from \"../_model/props\";\nimport { DEFAULT_EDITOR_STRINGS, type EditorStrings } from \"../_model/strings\";\nimport type { ViewSettings } from \"../_model/viewSettings\";\nimport type { MinimapNavigation } from \"../_state/useMinimapNavigation\";\nimport { MinimapShape } from \"./MinimapShape\";\nimport { RegionOverlay } from \"./RegionOverlay\";\nimport type { ViewSettingItemKey } from \"./SettingsPanel\";\nimport { SettingsPanel } from \"./SettingsPanel\";\n\n/**\n * 미니맵 패널 — 축소 이미지 + ROI 오버레이 + 도형 미리보기 +\n * 현재 뷰포트 사각형 + 줌 컨트롤 바 + 보기설정 팝오버.\n *\n * 내비게이션 로직(패닝/줌)은 useMinimapNavigation(nav)에, 뷰포트 사각형/줌라벨의 실시간\n * 갱신은 호스트의 syncMinimap이 rectRef/zoomLabelRef로 담당한다. 여긴 순수 표시.\n *\n * position이 위쪽 모서리면 줌 바를 위에 고정하고 축소맵이 아래로 펼쳐진다 —\n * 접고 펴도 바가 제자리에 있어야 한다.\n */\nconst POSITION_CLASSES: Record<MinimapPosition, string> = {\n \"bottom-left\": \"aivex:bottom-2 aivex:left-2\",\n \"bottom-right\": \"aivex:bottom-2 aivex:right-2\",\n \"top-left\": \"aivex:top-2 aivex:left-2\",\n \"top-right\": \"aivex:top-2 aivex:right-2\",\n};\n\nexport const Minimap = memo(function Minimap<TMeta>({\n image,\n imageUrl,\n imageVisible = true,\n loading = false,\n region,\n roiMaskId,\n shapes,\n view,\n viewDefaults,\n onChangeView,\n nav,\n registerShape,\n rectRef,\n zoomLabelRef,\n onZoom100,\n open,\n onToggleOpen,\n position = \"bottom-left\",\n showSettings = true,\n settingsOpen,\n onToggleSettings,\n onCloseSettings,\n labels = DEFAULT_EDITOR_STRINGS.minimap,\n settingsLabels,\n settingsItems,\n}: {\n image: { w: number; h: number };\n imageUrl: string;\n /** 메인 캔버스와 동기화된 표시 여부 — 전환 시 즉시 숨기고 로드 후 페이드인. */\n imageVisible?: boolean;\n /** 문서 이미지 전환 중에는 패널을 유지하되 이미지 내비게이션만 잠근다. */\n loading?: boolean;\n /** 리졸브된 영역 마스크 오버레이(딤·윤곽 벡터). */\n region?: RegionOverlayData | null;\n roiMaskId: string;\n shapes: EditorShape<TMeta>[];\n view: ViewSettings;\n /** \"초기화\"가 되돌릴 기준값(호스트 기본값 반영). */\n viewDefaults: ViewSettings;\n onChangeView: (patch: Partial<ViewSettings>) => void;\n nav: MinimapNavigation;\n registerShape: (id: string, el: SVGElement | null) => void;\n rectRef: RefObject<HTMLDivElement | null>;\n zoomLabelRef: RefObject<HTMLSpanElement | null>;\n onZoom100: () => void;\n open: boolean;\n onToggleOpen: () => void;\n /** 패널이 붙는 모서리(기본 \"bottom-left\"). */\n position?: MinimapPosition;\n /** 보기설정(기어) 버튼 표시 여부(기본 true). */\n showSettings?: boolean;\n settingsOpen: boolean;\n onToggleSettings: () => void;\n onCloseSettings: () => void;\n /** UI 문자열(aria/버튼). 기본 한국어. */\n labels?: EditorStrings[\"minimap\"];\n /** 설정 팝오버 문자열. 기본 한국어. */\n settingsLabels?: EditorStrings[\"viewSettings\"];\n /** 설정 팝오버 항목 구성 — SettingsPanel.items 그대로 전달. */\n settingsItems?: ViewSettingItemKey[];\n}) {\n const { offX, offY, dispW, dispH, zoomCentered } = nav;\n const isTop = position.startsWith(\"top\");\n const imgStyle = {\n position: \"absolute\" as const,\n left: offX,\n top: offY,\n width: dispW,\n height: dispH,\n };\n const mapBlock = (\n <div\n className={`aivex:overflow-hidden aivex:rounded-sm aivex:transition-all aivex:duration-200 aivex:ease-in-out ${open ? `${isTop ? \"aivex:mt-md\" : \"aivex:mb-md\"} aivex:opacity-100` : \"aivex:opacity-0\"}`}\n style={{ maxHeight: open ? MINIMAP_SIZE : 0 }}\n >\n <div\n style={{ width: MINIMAP_SIZE, height: MINIMAP_SIZE }}\n className={`aivex:relative aivex:touch-none aivex:overflow-hidden aivex:rounded-sm aivex:bg-static-gray ${loading ? \"aivex:cursor-default\" : \"aivex:cursor-grab aivex:active:cursor-grabbing\"}`}\n onPointerDown={loading ? undefined : nav.handleMinimapPointerDown}\n onPointerMove={loading ? undefined : nav.handleMinimapPointerMove}\n onPointerUp={loading ? undefined : nav.endMinimapDrag}\n onPointerCancel={loading ? undefined : nav.endMinimapDrag}\n onWheel={loading ? undefined : nav.handleMinimapWheel}\n aria-busy={loading}\n >\n {/* 메인 캔버스와 동기 — 전환 시 즉시 숨기고, 로드 후 잔잔한 페이드인. */}\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n opacity: imageVisible ? 1 : 0,\n transition: imageVisible ? \"opacity 0.3s ease\" : \"none\",\n }}\n >\n {/* 캔버스(CORS fetch)와 요청 모드를 맞춰 no-cors 캐시 오염을 방지한다. */}\n {imageUrl && (\n <img src={imageUrl} alt=\"\" crossOrigin=\"anonymous\" draggable={false} style={imgStyle} />\n )}\n {view.showRegionMask && region && region.rects.length > 0 && (\n <RegionOverlay\n image={image}\n region={region}\n maskId={roiMaskId}\n width={dispW}\n height={dispH}\n strokeWidth={1}\n strokeDasharray=\"4 4\"\n style={{\n position: \"absolute\",\n left: offX,\n top: offY,\n pointerEvents: \"none\",\n }}\n />\n )}\n <svg\n viewBox={`0 0 ${image.w} ${image.h}`}\n width={dispW}\n height={dispH}\n style={{\n position: \"absolute\",\n left: offX,\n top: offY,\n pointerEvents: \"none\",\n }}\n aria-hidden\n >\n {sortShapesForRender(shapes)\n .filter(isShapeVisible)\n .map((s) => (\n <MinimapShape\n key={s.id}\n shape={s}\n strokeSize={view.strokeSize}\n register={registerShape}\n />\n ))}\n </svg>\n <div\n ref={rectRef}\n style={{\n position: \"absolute\",\n border: `1px solid ${MINIMAP_VP_STROKE}`,\n background: MINIMAP_VP_FILL,\n boxSizing: \"border-box\",\n pointerEvents: \"none\",\n }}\n />\n </div>\n </div>\n </div>\n );\n // 줌 바 — 디자인상 5개 버튼이 한 줄에 좌측 정렬. 설정 팝오버 기준점이라 relative.\n const zoomBar = (\n <div className=\"aivex:relative aivex:flex aivex:items-center aivex:gap-xs\">\n <Button\n variant=\"ghost\"\n size=\"icon-md\"\n aria-label={labels.zoomOut}\n onClick={() => zoomCentered(1 / 1.2)}\n disabled={loading}\n >\n <MinusIcon size={20} />\n </Button>\n <Button\n variant=\"ghost\"\n size=\"md\"\n aria-label={labels.zoom100}\n onClick={onZoom100}\n disabled={loading}\n // 자릿수(100%↔9999%)가 바뀌어도 뒤 버튼이 밀리지 않게 폭을 고정한다.\n className=\"aivex:w-[60px] aivex:tabular-nums\"\n >\n <span ref={zoomLabelRef}>100%</span>\n </Button>\n <Button\n variant=\"ghost\"\n size=\"icon-md\"\n aria-label={labels.zoomIn}\n onClick={() => zoomCentered(1.2)}\n disabled={loading}\n >\n <PlusIcon size={20} />\n </Button>\n {/* 배치와 열기/닫기는 공용 Popover가 관리한다. */}\n {showSettings && (\n <Popover\n open={settingsOpen}\n onOpenChange={(next) => (next ? onToggleSettings() : onCloseSettings())}\n >\n <Popover.Trigger asChild>\n <Button\n variant=\"ghost\"\n size=\"icon-md\"\n aria-label={labels.viewSettings}\n className={settingsOpen ? \"aivex:text-text-brand\" : undefined}\n >\n <SettingIcon size={20} />\n </Button>\n </Popover.Trigger>\n <SettingsPanel\n value={view}\n defaults={viewDefaults}\n onChange={onChangeView}\n labels={settingsLabels}\n items={settingsItems}\n openDown={isTop}\n alignEnd={position.endsWith(\"right\")}\n />\n </Popover>\n )}\n <Button\n variant=\"ghost\"\n size=\"icon-md\"\n aria-label={labels.toggleMinimap}\n title=\"(M)\"\n onClick={onToggleOpen}\n >\n {/* 접힘 상태는 \"미니맵을 연다\"는 뜻이라 지도 아이콘. 펼침 상태의 접기\n 화살표는 축소맵이 펼쳐지는 방향(위쪽 앵커면 아래)을 가리킨다. */}\n {open ? (\n <CaretLineDownIcon size={20} className={isTop ? \"aivex:rotate-180\" : undefined} />\n ) : (\n <MapIcon size={20} />\n )}\n </Button>\n </div>\n );\n return (\n <div\n className={`aivex:absolute ${POSITION_CLASSES[position]} aivex:w-[220px] aivex:rounded-[12px] aivex:border aivex:border-border-subtle aivex:bg-bg-primary aivex:p-md aivex:shadow-[0_4px_12px_rgba(13,13,18,0.24)]`}\n >\n {isTop ? zoomBar : mapBlock}\n {isTop ? mapBlock : zoomBar}\n </div>\n );\n});\n","import type { CSSProperties } from \"react\";\nimport { type EditorShape, getBBox, type Point, SHAPE_TYPE } from \"../_model/geometry\";\nimport type { EditorSelectionInfo } from \"../_model/props\";\n\n/**\n * 선택 도형 정보 오버레이. 각 선택 도형의 bbox 위/아래에 라벨 배지(색 점 + 텍스트)와\n * 정보 텍스트(기본 W × H px)를 표시한다. 캔버스 오버레이 레이어(이미지 좌표) 안에 놓여\n * 뷰포트를 따라가고, inverse-scale로 화면 크기를 일정하게 유지한다.\n *\n * 표시 **레이아웃/위치/실시간 추적은 에디터 소유**, **텍스트 내용은 호스트가 결정**한다:\n * 라벨은 getLabel, 정보 텍스트는 formatInfo(에디터가 계산한 픽셀 데이터 info를 받음).\n * 드래그/리사이즈 중에는 index가 formatInfo를 재계산해 ref로 즉시 갱신한다\n * (onTransformPreview 경로).\n */\n\nconst INV = \"var(--editor-overlay-inverse-scale, 1)\";\nconst GAP = 6; // bbox 모서리와의 화면 px 간격.\n\nconst TEXT: CSSProperties = {\n fontFamily: \"Pretendard, sans-serif\",\n fontSize: 12,\n fontWeight: 500,\n lineHeight: \"16px\",\n color: \"#fff\",\n textShadow: \"0 0 4px #000, 0 0 4px #000\",\n whiteSpace: \"nowrap\",\n};\n\nfunction getSelectionInfoBounds(points: Point[]) {\n const b = getBBox(points);\n return {\n x: b.minX,\n y: b.minY,\n width: b.maxX - b.minX,\n height: b.maxY - b.minY,\n };\n}\n\nfunction getDimensionTransform(bounds: ReturnType<typeof getSelectionInfoBounds>) {\n return `translate3d(${bounds.width}px, ${bounds.height}px, 0) scale(${INV}) translate(-100%, ${GAP}px)`;\n}\n\n/** 드래그 프리뷰 중 레이아웃 변경 없이 라벨과 크기 텍스트를 bbox 모서리로 이동한다. */\nexport function updateSelectionInfoBounds(el: HTMLDivElement, points: Point[]) {\n const bounds = getSelectionInfoBounds(points);\n el.style.transform = `translate3d(${bounds.x}px, ${bounds.y}px, 0)`;\n const dim = el.querySelector<HTMLElement>(\"[data-selinfo-dim]\");\n if (dim) dim.style.transform = getDimensionTransform(bounds);\n return dim;\n}\n\n/** shape + 실제 좌표(points)로 selection info 데이터를 만든다(에디터 계산분). */\nexport function buildSelectionInfo<TMeta>(\n shape: EditorShape<TMeta>,\n points: Point[],\n): EditorSelectionInfo<TMeta> {\n const bounds = getSelectionInfoBounds(points);\n return {\n shape,\n ...bounds,\n };\n}\n\n/** formatSelectionInfo 미지정 시 기본 텍스트. */\nexport function defaultSelectionInfoText<TMeta>(info: EditorSelectionInfo<TMeta>): string {\n return `${Math.round(info.width)} x ${Math.round(info.height)} px`;\n}\n\nfunction Dot({ color, striped }: { color: string; striped: boolean }) {\n return (\n <span\n style={{\n display: \"inline-block\",\n width: 12,\n height: 12,\n borderRadius: \"50%\",\n ...(striped\n ? { border: `2px dashed ${color}`, background: \"transparent\" }\n : { background: color }),\n }}\n />\n );\n}\n\nexport function SelectionInfo<TMeta>({\n shapes,\n getLabel,\n hideDot,\n formatInfo,\n register,\n}: {\n shapes: EditorShape<TMeta>[];\n getLabel?: (shape: EditorShape<TMeta>) => string | undefined;\n hideDot?: boolean;\n formatInfo?: (info: EditorSelectionInfo<TMeta>) => string;\n register: (id: string, el: HTMLDivElement | null) => void;\n}) {\n return (\n <>\n {shapes.map((shape) => {\n const bounds = getSelectionInfoBounds(shape.points);\n const isPoint = shape.type === SHAPE_TYPE.POINT;\n const label = isPoint ? undefined : getLabel?.(shape);\n const color = shape.style?.color ?? \"#00e5ff\";\n // 점선 도형(예측/readOnly)은 배지의 클래스 원도 점선으로 — 실선 원은 GT.\n // 배지 점도 외형 기준 — readOnly(동작)가 아니라 실제로 점선인지를 본다.\n const striped = !!shape.style?.dashed || !!shape.style?.dash;\n const info = buildSelectionInfo(shape, shape.points);\n const infoText = formatInfo ? formatInfo(info) : defaultSelectionInfoText(info);\n return (\n <div\n key={shape.id}\n ref={(el) => register(shape.id, el)}\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n transform: `translate3d(${bounds.x}px, ${bounds.y}px, 0)`,\n willChange: \"transform\",\n pointerEvents: \"none\",\n }}\n >\n {!!label && (\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n display: \"flex\",\n alignItems: \"center\",\n gap: 4,\n transform: `scale(${INV}) translateY(calc(-100% - ${GAP}px))`,\n transformOrigin: \"left top\",\n ...TEXT,\n }}\n >\n {!hideDot && <Dot color={color} striped={striped} />}\n <span>{label}</span>\n </div>\n )}\n {!isPoint && !!infoText && (\n <div\n data-selinfo-dim\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n transform: getDimensionTransform(bounds),\n transformOrigin: \"left top\",\n willChange: \"transform\",\n ...TEXT,\n }}\n >\n {infoText}\n </div>\n )}\n </div>\n );\n })}\n </>\n );\n}\n","import { type EditorShape, type Point, SHAPE_TYPE } from \"./geometry\";\n\nconst CLIPBOARD_PREFIX = \"AIVEX_SHAPE_EDITOR:\";\nconst CLIPBOARD_VERSION = 1;\nconst SHAPE_TYPES = new Set<string>(Object.values(SHAPE_TYPE));\n\nexport interface ShapeClipboardPayload<TMeta = unknown> {\n kind: \"aivex-shape-editor\";\n version: typeof CLIPBOARD_VERSION;\n scope?: string;\n documentId?: string;\n shapes: EditorShape<TMeta>[];\n}\n\nlet memoryClipboard: ShapeClipboardPayload | null = null;\nlet systemClipboardState: \"unavailable\" | \"pending\" | \"written\" = \"unavailable\";\nlet systemClipboardWriteGeneration = 0;\n\nfunction isFinitePoint(value: unknown): value is Point {\n if (!value || typeof value !== \"object\") return false;\n const point = value as Partial<Point>;\n return Number.isFinite(point.x) && Number.isFinite(point.y);\n}\n\nfunction isClipboardShape(value: unknown): value is EditorShape<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const shape = value as Partial<EditorShape<unknown>>;\n return (\n typeof shape.type === \"string\" &&\n SHAPE_TYPES.has(shape.type) &&\n Array.isArray(shape.points) &&\n shape.points.length > 0 &&\n shape.points.every(isFinitePoint)\n );\n}\n\nexport function createShapeClipboardPayload<TMeta>(\n shapes: EditorShape<TMeta>[],\n documentId?: string,\n scope?: string,\n): ShapeClipboardPayload<TMeta> {\n return {\n kind: \"aivex-shape-editor\",\n version: CLIPBOARD_VERSION,\n scope,\n documentId,\n shapes,\n };\n}\n\n/** 원본 URL을 클립보드에 노출하지 않고 같은 문서 여부만 비교하기 위한 짧은 식별자. */\nexport function createClipboardDocumentId(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return `fnv1a:${(hash >>> 0).toString(36)}`;\n}\n\nexport function serializeShapeClipboard(payload: ShapeClipboardPayload): string {\n return `${CLIPBOARD_PREFIX}${JSON.stringify(payload)}`;\n}\n\nexport function parseShapeClipboard<TMeta = unknown>(\n text: string,\n): ShapeClipboardPayload<TMeta> | null {\n if (!text.startsWith(CLIPBOARD_PREFIX)) return null;\n try {\n const value = JSON.parse(text.slice(CLIPBOARD_PREFIX.length)) as Partial<\n ShapeClipboardPayload<TMeta>\n >;\n if (\n value.kind !== \"aivex-shape-editor\" ||\n value.version !== CLIPBOARD_VERSION ||\n !Array.isArray(value.shapes) ||\n value.shapes.length === 0 ||\n !value.shapes.every(isClipboardShape) ||\n (value.scope !== undefined && typeof value.scope !== \"string\") ||\n (value.documentId !== undefined && typeof value.documentId !== \"string\")\n ) {\n return null;\n }\n return value as ShapeClipboardPayload<TMeta>;\n } catch {\n return null;\n }\n}\n\nexport function writeShapeClipboard<TMeta>(payload: ShapeClipboardPayload<TMeta>): void {\n memoryClipboard = payload;\n const writeGeneration = ++systemClipboardWriteGeneration;\n if (typeof navigator === \"undefined\" || !navigator.clipboard?.writeText) {\n systemClipboardState = \"unavailable\";\n return;\n }\n let serialized: string;\n try {\n serialized = serializeShapeClipboard(payload);\n } catch {\n systemClipboardState = \"unavailable\";\n return;\n }\n systemClipboardState = \"pending\";\n void navigator.clipboard.writeText(serialized).then(\n () => {\n if (writeGeneration !== systemClipboardWriteGeneration) return;\n systemClipboardState = \"written\";\n },\n () => {\n if (writeGeneration !== systemClipboardWriteGeneration) return;\n // 권한/보안 컨텍스트 제약 시 같은 탭 메모리 클립보드를 계속 사용한다.\n systemClipboardState = \"unavailable\";\n },\n );\n}\n\nfunction isMatchingScope(payload: ShapeClipboardPayload | null, scope?: string): boolean {\n return !!payload && payload.scope === scope;\n}\n\nexport function canReadShapeClipboard(scope?: string): boolean {\n return (\n isMatchingScope(memoryClipboard, scope) ||\n (typeof navigator !== \"undefined\" && typeof navigator.clipboard?.readText === \"function\")\n );\n}\n\nexport async function readShapeClipboard<TMeta>(\n scope?: string,\n): Promise<ShapeClipboardPayload<TMeta> | null> {\n const matchingMemoryClipboard = isMatchingScope(memoryClipboard, scope)\n ? (memoryClipboard as ShapeClipboardPayload<TMeta>)\n : null;\n if (matchingMemoryClipboard && systemClipboardState !== \"written\") {\n return matchingMemoryClipboard;\n }\n if (typeof navigator !== \"undefined\" && navigator.clipboard?.readText) {\n try {\n const payload = parseShapeClipboard<TMeta>(await navigator.clipboard.readText());\n if (payload?.scope === scope) {\n memoryClipboard = payload;\n return payload;\n }\n return null;\n } catch {\n // 권한/보안 컨텍스트 제약 시 아래 메모리 클립보드로 대체한다.\n }\n }\n return matchingMemoryClipboard;\n}\n\nexport function getClipboardCascadeOffset(\n pasteCount: number,\n isDifferentDocument: boolean,\n step: number,\n): { offset: number; nextPasteCount: number } {\n return {\n offset: step * (isDifferentDocument ? pasteCount : pasteCount + 1),\n nextPasteCount: pasteCount + 1,\n };\n}\n","import type { Anchor } from \"./geometry\";\nimport { TOOL, type Tool } from \"./tools\";\n\nconst DRAW_TOOLS = new Set<Tool>([\n TOOL.RECTANGLE,\n TOOL.ROTATED_RECTANGLE,\n TOOL.CIRCLE,\n TOOL.POLYGON,\n TOOL.PATH,\n TOOL.BRUSH,\n TOOL.POINT,\n TOOL.ASSISTANT_POLYGON,\n TOOL.ASSISTANT_RECT,\n TOOL.ASSISTANT_POINT,\n]);\n\nconst ANCHOR_ANGLE: Record<Anchor, number> = {\n tl: -135,\n t: -90,\n tr: -45,\n r: 0,\n br: 45,\n b: 90,\n bl: 135,\n l: 180,\n};\n\nconst RESIZE_CURSORS = [\"ew-resize\", \"nwse-resize\", \"ns-resize\", \"nesw-resize\"];\n\n/**\n * 비선택 도형 호버 힌트(CSS 커서 아님 — 소비층이 도구별로 해석).\n * 선택 도구는 grab으로 표시하고, 박스 그리기 도구는 무시한다(클릭=그리기이므로).\n */\nexport const UNSELECTED_HOVER_HINT = \"grab-unselected\";\n\n/** 선택된 도형을 트랜스포머로 다룰 수 있는 박스 그리기 도구(이동·핸들 힌트 수용). */\nconst TRANSFORMER_BOX_TOOLS = new Set<Tool>([TOOL.RECTANGLE, TOOL.ROTATED_RECTANGLE, TOOL.CIRCLE]);\n\nexport function resizeCursorForAnchor(anchor: Anchor, angleRad = 0) {\n const deg = ANCHOR_ANGLE[anchor] + (angleRad * 180) / Math.PI;\n const normalized = ((deg % 180) + 180) % 180;\n const bucket = Math.round(normalized / 45) % 4;\n return RESIZE_CURSORS[bucket];\n}\n\nexport function cursorForTool({\n tool,\n externalToolCursor,\n isSpacePressed,\n isPolygonDrawing,\n}: {\n tool: Tool;\n externalToolCursor?: string;\n isSpacePressed: boolean;\n isPolygonDrawing: boolean;\n}) {\n if (isSpacePressed) return \"grab\";\n if (externalToolCursor) return externalToolCursor;\n if (tool === TOOL.SELECT) return \"default\";\n if (DRAW_TOOLS.has(tool)) return isPolygonDrawing ? \"default\" : \"crosshair\";\n return \"default\";\n}\n\nexport type EditorInteractionMode =\n | \"idle\"\n | \"drawing\"\n | \"marquee\"\n | \"moving\"\n | \"panning\"\n | \"resizing\"\n | \"rotating\"\n | \"vertexDragging\";\n\nexport function resolveEditorCursor({\n tool,\n externalToolCursor,\n isSpacePressed,\n interactionMode,\n rendererCursorHint,\n isPolygonDrawing,\n}: {\n tool: Tool;\n externalToolCursor?: string;\n isSpacePressed: boolean;\n interactionMode: EditorInteractionMode;\n rendererCursorHint?: string | null;\n isPolygonDrawing: boolean;\n}) {\n if (interactionMode === \"marquee\") return \"default\";\n if (\n interactionMode === \"moving\" ||\n interactionMode === \"panning\" ||\n interactionMode === \"vertexDragging\"\n ) {\n return \"grabbing\";\n }\n if (interactionMode === \"resizing\" || interactionMode === \"rotating\") {\n return rendererCursorHint ?? \"grabbing\";\n }\n if (interactionMode === \"drawing\") return \"crosshair\";\n if (isSpacePressed) return \"grab\";\n if (externalToolCursor) return externalToolCursor;\n if (tool === TOOL.SELECT && rendererCursorHint) {\n // 선택 도구는 비선택 도형 호버도 grab(클릭=선택·이동 가능).\n return rendererCursorHint === UNSELECTED_HOVER_HINT ? \"grab\" : rendererCursorHint;\n }\n // 박스 그리기 도구: 선택 도형·핸들 힌트만 수용(비선택 도형 위는 그리기라 crosshair 유지).\n if (\n TRANSFORMER_BOX_TOOLS.has(tool) &&\n rendererCursorHint &&\n rendererCursorHint !== UNSELECTED_HOVER_HINT\n ) {\n return rendererCursorHint;\n }\n return cursorForTool({\n tool,\n externalToolCursor,\n isSpacePressed,\n isPolygonDrawing,\n });\n}\n","import type { Point } from \"./geometry\";\n\n/**\n * 미니맵/캔버스에 그리는 **도메인 무관 보조 표시물**.\n *\n * 에디터는 이게 \"ROI\"인지 \"제외영역\"인지 의미를 모른다 — 순수 기하(사각형/다각형)와\n * 색(팔레트)만 안다. 호스트가 자기 도메인 데이터(클래스색·인덱스맵 등)에서 계산해\n * 주입하고, 에디터는 그대로 그리기만 한다. 비즈니스 로직 비종속.\n */\n\n/** 이미지 좌표 사각형 영역 — 가림 효과에서 \"보이는 창\"(예: 호스트의 관심영역). */\nexport interface RectArea {\n id?: string;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** 이미지 좌표 다각형 영역 — 보이는 창 안에서 다시 가리는 부분(예: 호스트의 마스킹). */\nexport interface PolygonArea {\n points: Point[];\n}\n\n/** @deprecated 도메인 중립화로 `RectArea`로 개명. 다음 릴리스에서 제거 예정. */\nexport type RoiRect = RectArea;\n/** @deprecated 도메인 중립화로 `PolygonArea`로 개명. 다음 릴리스에서 제거 예정. */\nexport type ExcludedZone = PolygonArea;\n\n/** 영역 윤곽 스트로크 — 화면 px 기준(줌과 무관하게 고정). */\nexport interface RegionOutlineStyle {\n color?: string;\n opacity?: number;\n /** 두께(화면 px). */\n width?: number;\n /** 점선 패턴(화면 px). */\n dash?: [number, number];\n /** 점선 빈 구간의 밑선 색(대비용). null이면 밑선 없음. 기본 검정. */\n underlayColor?: string | null;\n}\n\n/**\n * 이미지 위 가림 효과를 위한 순수 시각 계약. 영역의 제품 의미(관심영역·마스킹 등)는\n * 호스트가 해석하고, 에디터는 \"보이는 영역과 가려지는 영역\"만 안다.\n * 표시 정책(딤 농도·윤곽 색)은 기본값일 뿐 호스트가 전부 재정의할 수 있다.\n */\nexport interface RegionMask {\n visibleAreas: RectArea[];\n occludedAreas?: PolygonArea[];\n /** 가림 면 스타일. 기본 검정 50%. */\n dim?: { color?: string; opacity?: number };\n /**\n * 윤곽 표시. false면 면만 그리고 윤곽은 도형 레이어에 맡긴다. 미지정=기본 스타일.\n * mode \"merged\"(기본)=유효 영역(합집합 − 가림) 경계 하나를 visibleStyle로(보기 맥락),\n * \"separate\"=사각형·가림 윤곽을 각각 visibleStyle/occludedStyle로 통째 표시(편집 맥락).\n */\n outline?:\n | false\n | {\n mode?: \"merged\" | \"separate\";\n visibleStyle?: RegionOutlineStyle;\n occludedStyle?: RegionOutlineStyle;\n };\n}\n\nfunction traceZone(ctx: CanvasRenderingContext2D, points: { x: number; y: number }[]) {\n ctx.beginPath();\n ctx.moveTo(points[0].x, points[0].y);\n for (let i = 1; i < points.length; i += 1) ctx.lineTo(points[i].x, points[i].y);\n ctx.closePath();\n}\n\n// ── 유효 ROI 경계(사각형 합집합 − 제외영역) 선분 클리핑 ──\n\n/** 이미지 좌표 선분. 렌더러가 화면고정(줌 무관) 점선 스트로크로 그린다. */\nexport type OutlineSegment = [Point, Point];\n\nconst rectToPoly = (r: RectArea): Point[] => [\n { x: r.x, y: r.y },\n { x: r.x + r.w, y: r.y },\n { x: r.x + r.w, y: r.y + r.h },\n { x: r.x, y: r.y + r.h },\n];\n\nfunction pointInPoly(p: Point, poly: Point[]): boolean {\n let inside = false;\n for (let i = 0, j = poly.length - 1; i < poly.length; j = i, i += 1) {\n const a = poly[i];\n const b = poly[j];\n if (a.y > p.y !== b.y > p.y) {\n const t = (p.y - a.y) / (b.y - a.y);\n if (p.x < a.x + t * (b.x - a.x)) inside = !inside;\n }\n }\n return inside;\n}\n\n/** 선분 [a,b]와 다각형 변들의 교차 파라미터 t들(양 끝 제외). */\nfunction segPolyIntersectionTs(a: Point, b: Point, poly: Point[]): number[] {\n const ts: number[] = [];\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n for (let i = 0; i < poly.length; i += 1) {\n const c = poly[i];\n const d = poly[(i + 1) % poly.length];\n const ex = d.x - c.x;\n const ey = d.y - c.y;\n const denom = dx * ey - dy * ex;\n if (!denom) continue;\n const t = ((c.x - a.x) * ey - (c.y - a.y) * ex) / denom;\n const u = ((c.x - a.x) * dy - (c.y - a.y) * dx) / denom;\n if (t > 0 && t < 1 && u >= 0 && u <= 1) ts.push(t);\n }\n return ts;\n}\n\n/**\n * 다각형 변들을 교차점에서 쪼개 보이는 조각만 남긴다. 판정은 조각 중점이 아니라\n * **변 법선 방향으로 살짝 벗어난 양쪽 표본**으로 한다 — 중점 자체는 경계 위라\n * 포함판정이 비일관해서, 타일처럼 맞닿은 사각형의 공유 변이 한쪽만 숨겨지는\n * seam이 생겼다. \"자기 내부 반대쪽(outward) 표본이 다른 다각형에 덮이면 합집합\n * 내부 경계\"라는 규칙은 맞닿음·부분중첩은 숨기고 완전중복(동일 사각형 2개)의\n * 진짜 외곽은 남긴다.\n * hideInside: outward 표본이 이들 중 하나(자기 제외) 안이면 숨김.\n * keepInsideAny: 지정 시 inward 표본이 이들 중 하나 안일 때만 유지.\n */\nfunction clipEdges(\n polys: Point[][],\n hideInside: Point[][],\n keepInsideAny: Point[][] | null,\n): OutlineSegment[] {\n // 표본 오프셋(이미지 px) — 시각적으로 무의미하게 작되 경계 부동소수 오차보다 크게.\n const SAMPLE_OFFSET = 1e-3;\n const out: OutlineSegment[] = [];\n const lerp = (a: Point, b: Point, t: number): Point => ({\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n });\n for (const poly of polys) {\n if (poly.length < 2) continue;\n for (let i = 0; i < poly.length; i += 1) {\n const a = poly[i];\n const b = poly[(i + 1) % poly.length];\n const cuts = [0, 1];\n for (const other of hideInside) {\n if (other !== poly) cuts.push(...segPolyIntersectionTs(a, b, other));\n }\n if (keepInsideAny) {\n for (const other of keepInsideAny) cuts.push(...segPolyIntersectionTs(a, b, other));\n }\n const len = Math.hypot(b.x - a.x, b.y - a.y);\n if (!len) continue;\n const nx = (-(b.y - a.y) / len) * SAMPLE_OFFSET;\n const ny = ((b.x - a.x) / len) * SAMPLE_OFFSET;\n cuts.sort((x, y) => x - y);\n for (let k = 0; k + 1 < cuts.length; k += 1) {\n const t0 = cuts[k];\n const t1 = cuts[k + 1];\n if (t1 - t0 < 1e-9) continue;\n const m = lerp(a, b, (t0 + t1) / 2);\n const p1 = { x: m.x + nx, y: m.y + ny };\n const p2 = { x: m.x - nx, y: m.y - ny };\n // 자기 다각형 내부 쪽이 inward(호스트 다각형 winding 불문).\n const inward = pointInPoly(p1, poly) ? p1 : p2;\n const outward = inward === p1 ? p2 : p1;\n if (hideInside.some((other) => other !== poly && pointInPoly(outward, other))) continue;\n if (keepInsideAny && !keepInsideAny.some((other) => pointInPoly(inward, other))) continue;\n out.push([lerp(a, b, t0), lerp(a, b, t1)]);\n }\n }\n }\n return out;\n}\n\n/** 사각형들의 합집합을 서로 겹치지 않는 사각형들로 분해한다(x-슬랩 스윕). */\nfunction decomposeUnionRects(rects: RectArea[]): RectArea[] {\n const xs = [...new Set(rects.flatMap((r) => [r.x, r.x + r.w]))].sort((a, b) => a - b);\n const out: RectArea[] = [];\n for (let i = 0; i + 1 < xs.length; i += 1) {\n const x0 = xs[i];\n const x1 = xs[i + 1];\n if (x1 <= x0) continue;\n const intervals = rects\n .filter((r) => r.x <= x0 && r.x + r.w >= x1)\n .map((r) => [r.y, r.y + r.h] as [number, number])\n .sort((a, b) => a[0] - b[0]);\n let cur: [number, number] | null = null;\n for (const [y0, y1] of intervals) {\n if (!cur || y0 > cur[1]) {\n if (cur) out.push({ x: x0, y: cur[0], w: x1 - x0, h: cur[1] - cur[0] });\n cur = [y0, y1];\n } else {\n cur[1] = Math.max(cur[1], y1);\n }\n }\n if (cur) out.push({ x: x0, y: cur[0], w: x1 - x0, h: cur[1] - cur[0] });\n }\n return out;\n}\n\n/**\n * Canvas2D에 벡터 딤을 그린다 — 이미지 전체를 딤 색으로 덮되 보이는 영역 합집합을\n * 구멍(dimHoles, 무겹침이라 nonzero에서 안전)으로 뚫고, 가림 영역은 합집합 안쪽만\n * 다시 덮는다. Konva 렌더러와 ShapeViewer가 공유한다(전체 경로 커버리지 채움이라\n * 인접 구멍 경계에 이음선이 생기지 않는다).\n */\nexport function drawRegionDim(\n ctx: CanvasRenderingContext2D,\n region: Pick<RegionOverlayData, \"rects\" | \"zones\" | \"dimHoles\" | \"dim\">,\n width: number,\n height: number,\n) {\n ctx.save();\n ctx.globalAlpha *= region.dim.opacity;\n ctx.fillStyle = region.dim.color;\n ctx.beginPath();\n ctx.rect(0, 0, width, height);\n for (const r of region.dimHoles) {\n // 반시계 서브패스 → nonzero 규칙에서 구멍.\n ctx.moveTo(r.x, r.y);\n ctx.lineTo(r.x, r.y + r.h);\n ctx.lineTo(r.x + r.w, r.y + r.h);\n ctx.lineTo(r.x + r.w, r.y);\n ctx.closePath();\n }\n ctx.fill();\n if (region.zones.length) {\n ctx.beginPath();\n for (const r of region.rects) ctx.rect(r.x, r.y, r.w, r.h);\n ctx.clip();\n for (const z of region.zones) {\n traceZone(ctx, z.points);\n ctx.fill();\n }\n }\n ctx.restore();\n}\n\n/**\n * 완료 딤 스타일 — static/black + opacity/dim 토큰을 호스트 엘리먼트의 계산값으로\n * 런타임에 해석한다. 캔버스는 CSS 변수를 직접 참조할 수 없어 여기서 읽어 넘긴다.\n * 폴백은 토큰 미로드 환경(단위 테스트 등)용으로 현재 토큰 값과 같다.\n */\nexport function resolveCompletedDimStyle(host: HTMLElement): {\n color: string;\n opacity: number;\n} {\n const style = getComputedStyle(host);\n const color = style.getPropertyValue(\"--aivex-static-black\").trim() || \"#17171c\";\n const opacity = Number.parseFloat(style.getPropertyValue(\"--aivex-opacity-dim\")) || 0.32;\n return { color, opacity };\n}\n\n/** 다각형 변들을 그대로 선분으로 편다(클리핑 없음 — separate 윤곽용). */\nfunction polysToSegments(polys: Point[][]): OutlineSegment[] {\n const out: OutlineSegment[] = [];\n for (const poly of polys) {\n if (poly.length < 2) continue;\n for (let i = 0; i < poly.length; i += 1) {\n out.push([poly[i], poly[(i + 1) % poly.length]]);\n }\n }\n return out;\n}\n\n/** 기본 표시 정책 — 호스트가 RegionMask.dim/outline으로 전부 재정의 가능. */\nconst DEFAULT_DIM = { color: \"#000000\", opacity: 0.5 };\nconst DEFAULT_VISIBLE_OUTLINE: ResolvedRegionOutlineStyle = {\n color: \"#ffffff\",\n opacity: 1,\n width: 2,\n dash: [6, 6],\n underlayColor: \"#000000\",\n};\nconst DEFAULT_OCCLUDED_OUTLINE: ResolvedRegionOutlineStyle = {\n color: \"#dc2626\",\n opacity: 0.8,\n width: 2,\n dash: [6, 6],\n underlayColor: \"#000000\",\n};\n\n/** 기본값이 채워진 윤곽 스트로크 — 렌더러가 그대로 그린다. */\nexport type ResolvedRegionOutlineStyle = Required<RegionOutlineStyle>;\n\n/**\n * 렌더러 오버레이용 영역 데이터. 딤(면)·윤곽 모두 벡터로 넘긴다 —\n * 래스터(캔버스 굽기 + 텍스처 업로드)가 없어 드래그 중 프레임마다 재계산해도 싸다.\n * 딤은 rects/zones로 각 렌더러가 직접 그리고(이미지 전체 − 사각형 합집합, 가림은\n * 합집합 안쪽만 다시 덮음), 윤곽은 선분 목록을 화면고정(줌 무관) 스트로크로 그린다.\n */\nexport interface RegionOverlayData {\n /** 딤 계산용 보이는 창들. visibleAreas가 비어 있으면 전체 이미지 사각형 1개. */\n rects: RectArea[];\n zones: PolygonArea[];\n /** 사각형 합집합의 무겹침 분해 — 캔버스 딤 경로의 구멍용(겹치는 영역 안전). */\n dimHoles: RectArea[];\n dim: { color: string; opacity: number };\n /** visibleStyle로 그릴 경계 조각. merged면 유효 영역 경계 전체가 여기 담긴다. */\n visibleOutline: OutlineSegment[];\n /** occludedStyle로 그릴 가림 윤곽 조각(separate 모드에서만 비어있지 않음). */\n occludedOutline: OutlineSegment[];\n /** null이면 윤곽 생략(outline: false). */\n outlineStyles: {\n visible: ResolvedRegionOutlineStyle;\n occluded: ResolvedRegionOutlineStyle;\n } | null;\n}\n\n/**\n * RegionMask를 렌더러가 그릴 벡터 데이터로 리졸브한다(기본 표시 정책 주입 포함).\n * outline.mode \"merged\"(기본)면 유효 영역(합집합 − 가림) 경계 하나를,\n * \"separate\"면 사각형·가림 윤곽을 각각 통째로 넘긴다.\n * 렌더러 오버레이 레이어(이미지↔도형 사이)에 그려 도형이 그 위에 보이게 한다.\n */\nexport const buildRegionOverlayData = (\n mask: RegionMask,\n width: number,\n height: number,\n): RegionOverlayData | null => {\n const zones = mask.occludedAreas?.filter((z) => z.points.length >= 3) ?? [];\n if (!width || !height || (!mask.visibleAreas.length && !zones.length)) return null;\n const rects = mask.visibleAreas;\n // 보이는 창이 없으면 전체 이미지를 창으로 본다(가림만 먼저 그리는 편집 초기 상태) —\n // 바깥 딤 없이 가림 영역만 딤·윤곽으로 표시되고, 전체 이미지 테두리는 윤곽에서 제외한다.\n const universe: RectArea[] = rects.length ? rects : [{ x: 0, y: 0, w: width, h: height }];\n const dimHoles = decomposeUnionRects(universe);\n const dim = { ...DEFAULT_DIM, ...mask.dim };\n const outline = mask.outline;\n if (outline === false) {\n return {\n rects: universe,\n zones,\n dimHoles,\n dim,\n visibleOutline: [],\n occludedOutline: [],\n outlineStyles: null,\n };\n }\n const outlineStyles = {\n visible: { ...DEFAULT_VISIBLE_OUTLINE, ...outline?.visibleStyle },\n occluded: { ...DEFAULT_OCCLUDED_OUTLINE, ...outline?.occludedStyle },\n };\n const rectPolys = rects.map(rectToPoly);\n const universePolys = universe.map(rectToPoly);\n const zonePolys = zones.map((z) => z.points);\n if (outline?.mode === \"separate\") {\n // 편집 맥락 — 사각형·가림 윤곽을 각각 통째로.\n return {\n rects: universe,\n zones,\n dimHoles,\n dim,\n visibleOutline: polysToSegments(rectPolys),\n occludedOutline: polysToSegments(zonePolys),\n outlineStyles,\n };\n }\n // 보기 맥락(기본) — 유효 영역 경계 하나를 visibleStyle로.\n return {\n rects: universe,\n zones,\n dimHoles,\n dim,\n visibleOutline: [\n // 사각형 변: 다른 사각형·가림 안쪽은 숨김(합집합 − 가림 경계만 남음).\n ...clipEdges(rectPolys, [...rectPolys, ...zonePolys], null),\n // 가림 변: 보이는 창(없으면 전체 이미지) 안쪽이면서 다른 가림 밖인 조각만.\n ...clipEdges(zonePolys, zonePolys, universePolys),\n ],\n occludedOutline: [],\n outlineStyles,\n };\n};\n","import type { Viewport } from \"../_renderers/types\";\nimport type { BBox, EditorShape, Point, ShapeType } from \"./geometry\";\nimport { getBBox, SHAPE_TYPE } from \"./geometry\";\n\n/** 기존 Editor `TARGET_CONTAINER_RATIO` — 레이블 줌 시 화면 대비 목표 비율. */\nexport const TARGET_CONTAINER_RATIO = 0.3;\nexport const DEFAULT_ZOOM_ANIMATION_MS = 300;\nexport const MIN_VIEWPORT_SCALE = 0.05;\nexport const MAX_VIEWPORT_SCALE = 20;\n\nexport interface ZoomBounds {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport function easeOutCubic(t: number) {\n return 1 - (1 - t) ** 3;\n}\n\nexport function bboxToZoomBounds(b: BBox): ZoomBounds {\n return {\n x: b.minX,\n y: b.minY,\n width: Math.max(0, b.maxX - b.minX),\n height: Math.max(0, b.maxY - b.minY),\n };\n}\n\nexport function zoomBoundsFromPoints(type: ShapeType, points: Point[]): ZoomBounds | null {\n if (!points.length) return null;\n if (type === SHAPE_TYPE.POINT) {\n const p = points[0];\n const r = 8;\n return { x: p.x - r, y: p.y - r, width: r * 2, height: r * 2 };\n }\n const b = getBBox(points);\n const width = Math.max(1, b.maxX - b.minX);\n const height = Math.max(1, b.maxY - b.minY);\n return { x: b.minX, y: b.minY, width, height };\n}\n\nexport function zoomBoundsFromShapes(shapes: EditorShape[]): ZoomBounds | null {\n if (!shapes.length) return null;\n const boxes = shapes\n .map((shape) => zoomBoundsFromPoints(shape.type, shape.points))\n .filter((box): box is ZoomBounds => box !== null);\n if (!boxes.length) return null;\n const b = getBBox(\n boxes.flatMap((box) => [\n { x: box.x, y: box.y },\n { x: box.x + box.width, y: box.y + box.height },\n ]),\n );\n return bboxToZoomBounds(b);\n}\n\nexport interface ViewportZoomOptions {\n pad?: number;\n containerRatio?: number;\n minScale?: number;\n maxScale?: number;\n}\n\n/** 레이블 리스트 클릭 등 — 기존 Editor `animateToBounds`와 동일한 스케일 계산. */\nexport function viewportForZoomBounds(\n bounds: ZoomBounds,\n screenW: number,\n screenH: number,\n options: ViewportZoomOptions = {},\n): Viewport | null {\n const {\n containerRatio = TARGET_CONTAINER_RATIO,\n minScale = MIN_VIEWPORT_SCALE,\n maxScale = MAX_VIEWPORT_SCALE,\n } = options;\n if (!screenW || !screenH || bounds.width <= 0 || bounds.height <= 0) return null;\n\n const targetScaleByContainer = Math.min(\n (screenW * containerRatio) / bounds.width,\n (screenH * containerRatio) / bounds.height,\n );\n const scale = Math.max(minScale, Math.min(maxScale, targetScaleByContainer));\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n return {\n scale,\n x: screenW / 2 - cx * scale,\n y: screenH / 2 - cy * scale,\n };\n}\n\n/** 선택 영역 맞춤 — 화면에 bbox가 최대한 들어오도록. */\nexport function viewportForBBox(\n b: BBox,\n screenW: number,\n screenH: number,\n pad = 80,\n): Viewport | null {\n if (!screenW || !screenH) return null;\n const bw = Math.max(1, b.maxX - b.minX);\n const bh = Math.max(1, b.maxY - b.minY);\n const scale = Math.max(\n MIN_VIEWPORT_SCALE,\n Math.min(MAX_VIEWPORT_SCALE, Math.min((screenW - pad) / bw, (screenH - pad) / bh)),\n );\n const cx = (b.minX + b.maxX) / 2;\n const cy = (b.minY + b.maxY) / 2;\n return {\n scale,\n x: screenW / 2 - cx * scale,\n y: screenH / 2 - cy * scale,\n };\n}\n\nexport function animateViewport(\n from: Viewport,\n to: Viewport,\n apply: (viewport: Viewport) => void,\n duration = DEFAULT_ZOOM_ANIMATION_MS,\n): () => void {\n const startTime = Date.now();\n let frame = 0;\n\n const tick = () => {\n const elapsed = Date.now() - startTime;\n const progress = Math.min(elapsed / duration, 1);\n const eased = easeOutCubic(progress);\n apply({\n scale: from.scale + (to.scale - from.scale) * eased,\n x: from.x + (to.x - from.x) * eased,\n y: from.y + (to.y - from.y) * eased,\n });\n if (progress < 1) frame = requestAnimationFrame(tick);\n };\n\n frame = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(frame);\n}\n","import type { RefObject } from \"react\";\nimport type { EditorInteractionMode } from \"../_model/cursors\";\nimport {\n circleToPolygon,\n type EditorShape,\n getBBox,\n isShapeDraggable,\n isShapeSelectable,\n type Point,\n rectTo4,\n SHAPE_TYPE,\n type ShapeStyle,\n sortShapesForRender,\n squareEnd,\n} from \"../_model/geometry\";\nimport type { EditorExternalTool, EditorExternalToolContext } from \"../_model/props\";\nimport { TOOL, type Tool } from \"../_model/tools\";\nimport type { EditorRenderer, EditorRendererCallbacks } from \"../_renderers/types\";\nimport type { AssistantSession } from \"./useAssistant\";\nimport type { DrawSession } from \"./useDrawSession\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\n/**\n * 캔버스 포인터 상호작용 상태머신. 렌더러가 올려주는 포인터 이벤트를 받아\n * 팬/그리기/마퀴/꼭짓점드래그/외부도구를 조율하고, 문서·선택·그리기세션에 위임한다.\n *\n * 엔진 인스턴스마다 1회 생성한다(그때의 상호작용 임시 상태를 클로저로 보관). 최신 상태는\n * 전부 ref/drawSession으로 읽으므로 재생성 없이 최신 값을 반영한다.\n */\nexport interface InteractionControllerCtx<TMeta> {\n engineRef: RefObject<EditorRenderer | null>;\n toolRef: RefObject<Tool>;\n externalToolMapRef: RefObject<Map<string, EditorExternalTool>>;\n spaceRef: RefObject<boolean>;\n docRef: RefObject<EditorDocument<TMeta>>;\n selRef: RefObject<string[]>;\n draftRef: RefObject<ShapeStyle | undefined>;\n readOnlyRef: RefObject<boolean | undefined>;\n /** true면 SELECT 도구 마퀴(범위 선택) 비활성 — 클릭 단건 선택만. */\n disableMarqueeRef?: RefObject<boolean | undefined>;\n /**\n * 편집 잠금(완료 등). 선택은 허용하고, 그리기·도형 드래그·정점 편집 진입\n * 시도는 막고 onLockedInteraction을 호출한다.\n */\n lockedRef: RefObject<boolean | undefined>;\n onLockedInteraction: () => void;\n /** 그리기 도구인데 draft가 없어 시작할 수 없을 때 호출(호스트가 안내). */\n onDrawAttemptWithoutDraft: () => void;\n createRef: RefObject<(type: EditorShape<TMeta>[\"type\"], points: Point[]) => void>;\n selectRef: RefObject<(ids: string[]) => void>;\n /** 폴리곤 정점 편집모드 진입(더블클릭). */\n enterEditRef: RefObject<(id: string) => void>;\n /** 현재 편집모드 대상 폴리곤 id(null이면 비편집). 마퀴를 정점 범위선택으로 전환. */\n editingIdRef: RefObject<string | null>;\n drawSessionRef: RefObject<DrawSession<TMeta>>;\n assistantRef: RefObject<AssistantSession<TMeta>>;\n setCursorHint: (cursor: string | null) => void;\n setInteractionMode: (mode: EditorInteractionMode) => void;\n syncMinimap: () => void;\n onTransformPreview: (updates: { id: string; points: Point[] }[]) => void;\n /**\n * 박스 드래그 그리는 중 미리보기 지오메트리 통지 — 좌상단 클래스 배지 + 우하단\n * 크기(W×H) 정보 오버레이용. 그리는 중엔 bbox 두 꼭짓점, 종료 시 null.\n */\n onDrawPreview: (info: { type: EditorShape<TMeta>[\"type\"]; points: Point[] } | null) => void;\n}\n\nexport function createInteractionController<TMeta>(\n ctx: InteractionControllerCtx<TMeta>,\n): EditorRendererCallbacks {\n const {\n engineRef,\n toolRef,\n externalToolMapRef,\n spaceRef,\n docRef,\n selRef,\n draftRef,\n readOnlyRef,\n disableMarqueeRef,\n lockedRef,\n onLockedInteraction,\n onDrawAttemptWithoutDraft,\n createRef,\n selectRef,\n enterEditRef,\n editingIdRef,\n drawSessionRef,\n assistantRef,\n setCursorHint,\n setInteractionMode,\n syncMinimap,\n onTransformPreview,\n onDrawPreview,\n } = ctx;\n const ds = () => drawSessionRef.current;\n const assist = () => assistantRef.current;\n\n // 상호작용 일시 상태(엔진 인스턴스 수명과 동일).\n // 팬은 직전 포인터 위치만 기억하고 현재 뷰포트에 증분을 더한다 — 드래그 도중\n // 휠 줌(zoomAt)이 뷰포트를 바꿔도 시작 시점 기준으로 덮어쓰며 점프하지 않게.\n let pan: { px: number; py: number } | null = null;\n let drawStart: Point | null = null;\n // 자유선(PATH)/붓(BRUSH)은 동일한 스트로크 파이프라인 — 종류만 구분.\n let strokeKind: \"path\" | \"scalar\" | null = null;\n let draftPointDrag: {\n start: Point;\n base: Point[];\n indices: number[];\n moved: boolean;\n } | null = null;\n let marquee: Point | null = null;\n // 편집모드 마퀴 = 정점 범위선택. non-null이면 마퀴가 도형이 아닌 정점을 고른다.\n // 값은 드래그 시작 시점의 기존 정점 선택(Shift 추가선택 기준, 아니면 빈 배열).\n let vertexMarqueeBase: number[] | null = null;\n // 정점 마퀴가 편집 중인 도형 몸통에서 시작했는지 — 무드래그 클릭 처리가 갈린다\n // (빈 공간 클릭=선택 해제·편집 종료, 몸통 클릭=정점 선택만 해제·편집 유지).\n let vertexMarqueeOnBody = false;\n let lastHit = \"\";\n // POINT는 같은 포인터의 짧은 좌클릭이 캔버스 안에서 끝날 때만 생성한다.\n // 화면 좌표를 써서 줌 배율과 무관하게 클릭/드래그를 구분한다.\n const pointClickThreshold = 4;\n let pointPress: { pointerId: number; global: Point; cancelled: boolean } | null = null;\n // 잠금 중 도형을 잡은 위치(화면 좌표). 클릭 선택은 허용하고, 임계값 이상 끌면\n // 그때 한 번만 알린다.\n let lockedDragPress: Point | null = null;\n // 폴리곤 더블클릭→편집모드 감지용(같은 도형을 짧은 간격으로 두 번 클릭).\n let lastClick: { id: string; t: number } | null = null;\n\n const isBox = (t: Tool) =>\n t === TOOL.RECTANGLE || t === TOOL.ROTATED_RECTANGLE || t === TOOL.CIRCLE;\n // 어시스트 박스 드래그 도구(폴리곤 결과 ASSISTANT_POLYGON + 사각형 결과 ASSISTANT_RECT).\n const isAssistantBox = (t: Tool) => t === TOOL.ASSISTANT_POLYGON || t === TOOL.ASSISTANT_RECT;\n const isClickPath = (t: Tool) => t === TOOL.POLYGON;\n // draft(새 도형에 찍을 값)가 있어야만 시작할 수 있는 도구들.\n const needsDraft = (t: Tool) =>\n isBox(t) ||\n isAssistantBox(t) ||\n isClickPath(t) ||\n t === TOOL.PATH ||\n t === TOOL.BRUSH ||\n t === TOOL.POINT;\n\n // 그리기/드래그 진행 중 도구가 바뀌면(단축키 등) 남은 일시 상태를 취소한다.\n // 방치하면 도구 복귀 시 이전 시작점 기준 유령 미리보기가 붙거나, 선택 도구로\n // 스트로크·마퀴가 이어지는 등 화면이 어긋난다 — 진행분은 그냥 버린다.\n const cancelStaleInteraction = (eng: EditorRenderer, tool: Tool) => {\n let cancelled = false;\n if (drawStart && !isBox(tool) && !isAssistantBox(tool)) {\n drawStart = null;\n eng.clearPreview();\n onDrawPreview(null);\n cancelled = true;\n }\n if (\n (strokeKind === \"path\" && tool !== TOOL.PATH) ||\n (strokeKind === \"scalar\" && tool !== TOOL.BRUSH)\n ) {\n strokeKind = null;\n cancelled = true;\n }\n if (draftPointDrag && !isClickPath(tool)) {\n draftPointDrag = null;\n cancelled = true;\n }\n if (marquee && tool !== TOOL.SELECT) {\n marquee = null;\n vertexMarqueeBase = null;\n vertexMarqueeOnBody = false;\n eng.clearMarquee();\n cancelled = true;\n }\n if (pointPress && tool !== TOOL.POINT) {\n pointPress = null;\n cancelled = true;\n }\n if (cancelled) setInteractionMode(\"idle\");\n };\n const getExternalTool = () => externalToolMapRef.current.get(toolRef.current);\n const makeExternalContext = (\n eng: EditorRenderer,\n point: Point,\n event: EditorExternalToolContext[\"event\"],\n targetId?: string | null,\n ): EditorExternalToolContext => ({\n point,\n targetId,\n event,\n readOnly: readOnlyRef.current,\n viewport: eng.viewport,\n });\n\n return {\n onCursorHint: setCursorHint,\n onInteractionModeChange: setInteractionMode,\n onPointerDown: (p, targetId, e) => {\n const eng = engineRef.current;\n if (!eng) return;\n const tool = toolRef.current;\n pointPress = null;\n lockedDragPress = null;\n cancelStaleInteraction(eng, tool);\n // 팬: 중간버튼 또는 Space.\n if (e.button === 1 || spaceRef.current) {\n setInteractionMode(\"panning\");\n setCursorHint(null);\n pan = { px: e.global.x, py: e.global.y };\n return;\n }\n // 우클릭=메뉴. 메뉴 액션은 커서 아래 도형을 대상으로 하되, 이미 선택된 도형이면\n // 다중 선택을 유지한다. 빈 공간과 렌더러 핸들처럼 문서에 없는 targetId에서는\n // 현재 선택을 보존한다(선택 폴리곤 바깥에서 \"이 지점 포함하기\"를 쓸 수 있어야 함).\n // 단, 마법봉(ASSISTANT_POINT)의 Alt+우클릭은 음성 정제로 쓴다.\n if (e.button === 2 && !(tool === TOOL.ASSISTANT_POINT && e.altKey)) {\n if (targetId && !selRef.current.includes(targetId)) {\n const targetShape = docRef.current.getShapes().find((shape) => shape.id === targetId);\n if (targetShape && isShapeSelectable(targetShape)) {\n selectRef.current([targetId]);\n }\n }\n return;\n }\n\n const externalTool = getExternalTool();\n if (externalTool) {\n ds().reset();\n selectRef.current([]);\n externalTool.onPointerDown?.(makeExternalContext(eng, p, e, targetId));\n return;\n }\n\n // 편집 잠금(완료 등): 선택은 편집이 아니다 — SELECT 도구는 통과시켜\n // 클릭 선택·마퀴는 허용하고(도형 드래그·정점 편집 진입은 아래에서 알림),\n // 그리기 도구 시도는 여기서 막고 호스트에 알린다.\n // 코멘트(외부도구)·팬·우클릭메뉴는 위 분기들에서 이미 통과했다.\n if (lockedRef.current && tool !== TOOL.SELECT) {\n onLockedInteraction();\n return;\n }\n\n // 박스 그리기 도구에서도 이미 선택된 도형의 몸통 드래그는 그리기 대신 이동 —\n // 트랜스포머(핸들 리사이즈·회전)는 렌더러가 도구 무관으로 선처리하므로 이동만\n // 여기서 잇는다. 생성 직후 자동 선택과 합쳐져 \"그리고 바로 손본다\"가 된다.\n // 겹치는 라벨은 선택 밖 영역에서 그리면 되고(해제는 Esc), 폴리곤 점찍기·\n // 자유곡선·어시스트는 도형 위 입력이 그리기 의미라 제외한다. draft(클래스)\n // 없이도 이동은 가능해야 하므로 draft 가드보다 앞에 둔다.\n if (isBox(tool) && targetId && selRef.current.includes(targetId) && !readOnlyRef.current) {\n const target = docRef.current.getShapes().find((shape) => shape.id === targetId);\n if (target && isShapeDraggable(target)) {\n eng.beginMove(p, selRef.current);\n return;\n }\n }\n\n // 그리기 도구인데 draft가 없으면 아래 분기가 전부 draft 가드에 걸려 무반응이\n // 된다. 조용히 삼키지 말고 호스트에 알린다(그리기 자체는 여전히 안 한다).\n if (needsDraft(tool) && !draftRef.current) {\n onDrawAttemptWithoutDraft();\n return;\n }\n\n // AI 어시스트(마법봉): 옵스식.\n // - 그냥 클릭 → 그 점 기반 새 폴리곤 생성(이전 세션은 확정).\n // - Alt+좌클릭 → 현재 폴리곤을 넓힘(+ 정제), Alt+우클릭 → 좁힘(− 정제).\n if (tool === TOOL.ASSISTANT_POINT) {\n if (e.altKey) assist().addPoint(p, e.button !== 2);\n else assist().newPolygon(p);\n return;\n }\n // AI 어시스트: 박스 프롬프트(드래그). 폴리곤/사각형 결과 모두 동일 드래그.\n if (isAssistantBox(tool) && draftRef.current) {\n drawStart = p;\n setInteractionMode(\"drawing\");\n return;\n }\n\n // 정점 편집모드: 캔버스 드래그는 시작 위치(편집 도형 몸통·다른 도형·빈 공간)와\n // 무관하게 전부 정점 범위선택이다 — 편집 중 다른 레이블이 선택되거나 도형이\n // 이동하면 안 된다. 무드래그 클릭만 위치에 따라 갈린다: 편집 도형 몸통이면\n // 정점 선택 해제(편집 유지), 그 밖(빈 공간·다른 도형)이면 선택 해제(편집 종료).\n if (tool === TOOL.SELECT && editingIdRef.current) {\n vertexMarqueeBase = e.shiftKey ? eng.getVertexSelection() : [];\n vertexMarqueeOnBody = targetId === editingIdRef.current;\n marquee = p;\n lastHit = \"\";\n setInteractionMode(\"marquee\");\n setCursorHint(null);\n return;\n }\n\n // Alt-클릭: 포인터 아래 겹친 도형들을 위→아래로 순환 선택.\n if (tool === TOOL.SELECT && e.altKey) {\n const under = sortShapesForRender(docRef.current.getShapes()).filter((s) => {\n if (!isShapeSelectable(s)) return false;\n const b = getBBox(s.points);\n return p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY;\n });\n if (under.length) {\n const ordered = [...under].reverse();\n const cur = ordered.findIndex((s) => selRef.current.includes(s.id));\n const next = [ordered[(cur + 1) % ordered.length].id];\n selectRef.current(next);\n return;\n }\n }\n\n // 도형 위 클릭.\n if (targetId && tool === TOOL.SELECT) {\n const targetShape = docRef.current.getShapes().find((shape) => shape.id === targetId);\n if (!targetShape || !isShapeSelectable(targetShape)) return;\n // 폴리곤/라인 더블클릭 → 정점 편집모드 진입(옵스식).\n const now = typeof performance !== \"undefined\" ? performance.now() : 0;\n const isDouble = !!lastClick && lastClick.id === targetId && now - lastClick.t < 300;\n lastClick = { id: targetId, t: now };\n const vertexEditable =\n (targetShape.type === SHAPE_TYPE.POLYGON || targetShape.type === SHAPE_TYPE.LINE) &&\n targetShape.interaction?.editable !== false &&\n !targetShape.readOnly;\n if (isDouble && vertexEditable && lockedRef.current) {\n selectRef.current([targetId]);\n onLockedInteraction();\n return;\n }\n if (isDouble && vertexEditable && !readOnlyRef.current) {\n selectRef.current([targetId]);\n enterEditRef.current(targetId);\n return;\n }\n let next = selRef.current;\n if (e.shiftKey) {\n const set = new Set(next);\n set.has(targetId) ? set.delete(targetId) : set.add(targetId);\n next = [...set];\n } else if (!next.includes(targetId)) {\n next = [targetId];\n }\n selectRef.current(next);\n // 이동 시작은 엔진이 관리(핸들도 함께 따라감).\n if (isShapeDraggable(targetShape)) {\n if (lockedRef.current) lockedDragPress = e.global;\n else if (!readOnlyRef.current) eng.beginMove(p, next);\n }\n return;\n }\n\n // 그리기 도구.\n if (isBox(tool) && draftRef.current) {\n drawStart = p;\n setInteractionMode(\"drawing\");\n return;\n }\n if (isClickPath(tool) && draftRef.current) {\n const draftPoints = ds().getDraftPointsSnapshot();\n if (!draftPoints.length && selRef.current.length) {\n selectRef.current([]);\n }\n if (ds().tryClosePolygon(p, 12 / eng.viewport.scale)) {\n return;\n }\n const hitIndex = ds().hitDraftPoint(p);\n if (hitIndex >= 0) {\n if (e.altKey) {\n ds().removeDraftPoint(hitIndex);\n return;\n }\n const drag = ds().selectDraftPointForDrag(hitIndex, e.shiftKey || e.ctrlKey || e.metaKey);\n if (!drag) return;\n draftPointDrag = {\n start: p,\n base: drag.base,\n indices: drag.indices,\n moved: false,\n };\n setInteractionMode(\"vertexDragging\");\n return;\n }\n ds().appendPolygonPoint(p);\n return;\n }\n if (tool === TOOL.PATH && draftRef.current) {\n if (selRef.current.length) selectRef.current([]);\n strokeKind = \"path\";\n setInteractionMode(\"drawing\");\n ds().beginStroke(p);\n return;\n }\n if (tool === TOOL.BRUSH && draftRef.current && !readOnlyRef.current) {\n strokeKind = \"scalar\";\n setInteractionMode(\"drawing\");\n ds().beginStroke(p);\n return;\n }\n if (tool === TOOL.POINT && draftRef.current && e.button === 0) {\n pointPress = { pointerId: e.pointerId, global: e.global, cancelled: false };\n return;\n }\n // 빈 공간 SELECT = 마퀴. 단, 다중선택 bbox 안의 빈 공간(레이블 사이 틈,\n // 채움 없는 도형 근처)은 그룹 이동으로 처리한다 — 다중선택을 \"잡아서 옮기는\"\n // 도중 히트가 빗나가 마퀴로 바뀌는 문제 방지(Shift는 마퀴 추가선택 우선).\n if (tool === TOOL.SELECT) {\n // 정점 편집모드는 위에서 이미 마퀴로 빠졌다 — 여긴 도형 마퀴만.\n vertexMarqueeBase = null;\n vertexMarqueeOnBody = false;\n const canGroupMove = !readOnlyRef.current || lockedRef.current;\n if (!e.shiftKey && canGroupMove && selRef.current.length >= 2) {\n const selShapes = docRef.current\n .getShapes()\n .filter((s) => selRef.current.includes(s.id) && isShapeDraggable(s));\n if (selShapes.length) {\n const b = getBBox(selShapes.flatMap((s) => s.points));\n if (p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY) {\n if (lockedRef.current) lockedDragPress = e.global;\n else eng.beginMove(p, selRef.current);\n return;\n }\n }\n }\n marquee = p;\n lastHit = \"\";\n setInteractionMode(\"marquee\");\n setCursorHint(null);\n }\n },\n onPointerMove: (p, e) => {\n const eng = engineRef.current;\n if (!eng) return;\n if (\n pointPress &&\n pointPress.pointerId === e.pointerId &&\n Math.hypot(e.global.x - pointPress.global.x, e.global.y - pointPress.global.y) >\n pointClickThreshold\n ) {\n pointPress.cancelled = true;\n }\n if (\n lockedDragPress &&\n Math.hypot(e.global.x - lockedDragPress.x, e.global.y - lockedDragPress.y) >\n pointClickThreshold\n ) {\n lockedDragPress = null;\n onLockedInteraction();\n return;\n }\n if (pan) {\n eng.applyViewport({\n scale: eng.viewport.scale,\n x: eng.viewport.x + (e.global.x - pan.px),\n y: eng.viewport.y + (e.global.y - pan.py),\n });\n pan.px = e.global.x;\n pan.py = e.global.y;\n return;\n }\n const tool = toolRef.current;\n cancelStaleInteraction(eng, tool);\n const externalTool = getExternalTool();\n if (externalTool) {\n externalTool.onPointerMove?.(makeExternalContext(eng, p, e));\n return;\n }\n if (draftPointDrag) {\n const dx = p.x - draftPointDrag.start.x;\n const dy = p.y - draftPointDrag.start.y;\n draftPointDrag.moved = draftPointDrag.moved || Math.hypot(dx, dy) > 0.5;\n ds().moveDraftPoints(draftPointDrag.base, draftPointDrag.indices, dx, dy);\n return;\n }\n if (drawStart && (isBox(tool) || isAssistantBox(tool))) {\n const end = e.shiftKey ? squareEnd(drawStart, p) : p;\n eng.previewBox(tool === TOOL.CIRCLE ? \"ellipse\" : \"rect\", drawStart, end, {\n ...draftRef.current,\n color: draftRef.current?.color ?? \"#00e5ff\",\n });\n // 어시스트 박스(프롬프트)는 라벨 대상이 아니므로 실제 그리기 도구에서만 정보 배지.\n if (isBox(tool)) {\n onDrawPreview({\n type: tool === TOOL.CIRCLE ? SHAPE_TYPE.ELLIPSE : SHAPE_TYPE.RECTANGLE,\n points: [drawStart, end],\n });\n }\n return;\n }\n if (strokeKind) {\n ds().appendStrokePoint(p, 2 / eng.viewport.scale);\n return;\n }\n if (isClickPath(tool) && ds().hasDraftPoints()) {\n ds().setDraftCursor(p);\n return;\n }\n if (marquee) {\n // 마퀴 비활성 시 드래그해도 박스/범위선택 없음(빈 공간 클릭 해제는 유지).\n if (disableMarqueeRef?.current) return;\n const box = {\n minX: Math.min(marquee.x, p.x),\n minY: Math.min(marquee.y, p.y),\n maxX: Math.max(marquee.x, p.x),\n maxY: Math.max(marquee.y, p.y),\n };\n eng.previewMarquee(marquee, p);\n // 정점 편집모드: 박스 안 정점 인덱스를 (Shift면 기존 선택에 더해) 선택한다.\n if (vertexMarqueeBase) {\n const editing = docRef.current.getShapes().find((s) => s.id === editingIdRef.current);\n const inBox = (editing?.points ?? []).flatMap((pt, i) =>\n pt.x >= box.minX && pt.x <= box.maxX && pt.y >= box.minY && pt.y <= box.maxY ? [i] : [],\n );\n const merged = [...new Set([...vertexMarqueeBase, ...inBox])].sort((a, b) => a - b);\n const key = merged.join(\",\");\n if (key !== lastHit) {\n lastHit = key;\n eng.setVertexSelection(merged);\n }\n return;\n }\n const hit = eng.shapesIntersecting(box);\n const key = hit.join(\",\");\n if (key !== lastHit) {\n lastHit = key;\n selectRef.current(hit);\n }\n }\n },\n onPointerUp: (p, e) => {\n const eng = engineRef.current;\n if (!eng) return;\n const completedPointPress = pointPress;\n pointPress = null;\n lockedDragPress = null;\n if (pan) {\n pan = null;\n setInteractionMode(\"idle\");\n return;\n }\n const tool = toolRef.current;\n cancelStaleInteraction(eng, tool);\n if (draftPointDrag) {\n ds().commitDraftPointDrag(draftPointDrag.moved);\n draftPointDrag = null;\n setInteractionMode(\"idle\");\n return;\n }\n const externalTool = getExternalTool();\n if (externalTool) {\n externalTool.onPointerUp?.(makeExternalContext(eng, p, e));\n return;\n }\n const pointMovement = completedPointPress\n ? Math.hypot(\n e.global.x - completedPointPress.global.x,\n e.global.y - completedPointPress.global.y,\n )\n : Number.POSITIVE_INFINITY;\n if (\n tool === TOOL.POINT &&\n draftRef.current &&\n completedPointPress &&\n !completedPointPress.cancelled &&\n completedPointPress.pointerId === e.pointerId &&\n e.insideCanvas &&\n pointMovement <= pointClickThreshold\n ) {\n createRef.current(SHAPE_TYPE.POINT, [p]);\n return;\n }\n if (strokeKind) {\n const kind = strokeKind;\n strokeKind = null;\n setInteractionMode(\"idle\");\n if (kind === \"path\") ds().completeFreehandStroke();\n else ds().finishScalarStroke();\n return;\n }\n if (drawStart && isAssistantBox(tool)) {\n const s = drawStart;\n drawStart = null;\n setInteractionMode(\"idle\");\n eng.clearPreview();\n // 프리뷰와 동일한 Shift 정사각 제약을 적용해 보여 준 범위 그대로 전달한다.\n const end = e.shiftKey ? squareEnd(s, p) : p;\n const box = {\n x: Math.min(s.x, end.x),\n y: Math.min(s.y, end.y),\n width: Math.abs(end.x - s.x),\n height: Math.abs(end.y - s.y),\n };\n // ASSISTANT_RECT는 결과를 사각형으로, ASSISTANT_POLYGON는 폴리곤으로 커밋.\n if (box.width > 2 && box.height > 2)\n assist().beginBox(box, tool === TOOL.ASSISTANT_RECT ? \"rect\" : \"polygon\");\n return;\n }\n if (drawStart && isBox(tool)) {\n const end = e.shiftKey ? squareEnd(drawStart, p) : p;\n const s = drawStart;\n drawStart = null;\n setInteractionMode(\"idle\");\n eng.clearPreview();\n onDrawPreview(null);\n if (Math.abs(end.x - s.x) > 2 && Math.abs(end.y - s.y) > 2) {\n if (tool === TOOL.ROTATED_RECTANGLE)\n createRef.current(SHAPE_TYPE.ROTATED_RECTANGLE, rectTo4([s, end]));\n else if (tool === TOOL.CIRCLE)\n createRef.current(SHAPE_TYPE.POLYGON, circleToPolygon(s, end));\n else createRef.current(SHAPE_TYPE.RECTANGLE, [s, end]);\n }\n return;\n }\n if (marquee) {\n const moved = Math.abs(p.x - marquee.x) > 3 || Math.abs(p.y - marquee.y) > 3;\n const wasVertexMarquee = vertexMarqueeBase !== null;\n const wasOnBody = vertexMarqueeOnBody;\n marquee = null;\n vertexMarqueeBase = null;\n vertexMarqueeOnBody = false;\n eng.clearMarquee();\n setInteractionMode(\"idle\");\n // 정점 범위선택 드래그였으면 편집모드·도형 선택을 유지한다.\n if (wasVertexMarquee && moved) return;\n // 편집 중인 도형 몸통 무드래그 클릭: 정점 선택만 해제하고 편집은 유지한다\n // (빈 공간 클릭과 달리 도형 선택 해제·편집 종료로 이어지면 안 된다).\n if (wasVertexMarquee && wasOnBody) {\n eng.setVertexSelection([]);\n return;\n }\n if (!moved && selRef.current.length) selectRef.current([]);\n }\n },\n onViewportChange: syncMinimap,\n onTransformPreview,\n onTransformCommit: (updates) => {\n const shapes = docRef.current.getShapes();\n const next = updates\n .map((u) => {\n const s = shapes.find((x) => x.id === u.id);\n return s ? { ...s, points: u.points } : null;\n })\n .filter((s): s is EditorShape<TMeta> => !!s);\n if (next.length) docRef.current.update(next);\n },\n };\n}\n","import { type RefObject, useCallback, useRef, useState } from \"react\";\nimport {\n type EditorShape,\n generateId,\n getBBox,\n minAreaRect,\n type Point,\n SHAPE_TYPE,\n type ShapeStyle,\n} from \"../_model/geometry\";\nimport type { AssistantPrompt, EditorAssistant } from \"../_model/props\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nexport type AssistantStatus = \"idle\" | \"loading\" | \"ready\";\n\ninterface UseAssistantParams<TMeta> {\n docRef: RefObject<EditorDocument<TMeta>>;\n draftRef: RefObject<ShapeStyle | undefined>;\n draftMeta: TMeta | undefined;\n changeSelection: (ids: string[]) => void;\n assistantRef: RefObject<EditorAssistant | undefined>;\n}\n\ntype Box = { x: number; y: number; width: number; height: number };\n\n/**\n * AI 어시스트 세션(SAM 식). 프롬프트 수집(박스/포인트)·호스트 infer 호출·**즉시 커밋**.\n * 옵스 에디터와 동일하게 추론 결과를 프리뷰 없이 바로 도형으로 만든다.\n *\n * 두 갈래의 수명 주기(옵스 파리티):\n * - **박스 프롬프트(ASSISTANT_POLYGON/RECT)**: 드래그마다 **병렬 독립 요청** —\n * 앞 요청이 진행 중이어도 새 드래그가 그것을 취소하지 않고 각자 완료 시 커밋된다.\n * 커밋된 결과는 확정(Esc로 지워지지 않음 — 일반 undo/삭제로 다룬다).\n * - **포인트 프롬프트(마법봉)**: 단일 세션. 클릭=이전 세션 확정+새 세션, Alt+클릭=\n * 같은 도형 제자리 refine. Esc=세션 취소(이번 세션 생성분 제거 + 진행 중 응답 폐기).\n */\nexport function useAssistant<TMeta>({\n docRef,\n draftRef,\n draftMeta,\n changeSelection,\n assistantRef,\n}: UseAssistantParams<TMeta>) {\n const [status, setStatus] = useState<AssistantStatus>(\"idle\");\n const [points, setPoints] = useState<{ x: number; y: number; positive: boolean }[]>([]);\n // 진행 중인 박스 프롬프트들(병렬). shimmer 표시 + isActive 판단용.\n const [pendingBoxes, setPendingBoxes] = useState<Box[]>([]);\n const pendingBoxesRef = useRef<Box[]>([]);\n\n const pointsRef = useRef<{ x: number; y: number; positive: boolean }[]>([]);\n const committedRef = useRef<string[]>([]); // 포인트 세션이 만든 도형 id.\n const statusRef = useRef<AssistantStatus>(\"idle\");\n const tokenRef = useRef(0); // 포인트 세션 최신 요청 토큰(stale 폐기).\n // 기존 도형 refine 세션: base(원본 좌표)를 프롬프트에 실어 보내고, Esc 시 원복한다.\n const baseRef = useRef<Point[] | null>(null);\n const originalShapeRef = useRef<EditorShape<TMeta> | null>(null);\n const boxEpochRef = useRef(0); // 박스 요청 세대 — cancel 시 증가, 이후 응답 폐기.\n\n const mutatePending = useCallback((updater: (list: Box[]) => Box[]) => {\n pendingBoxesRef.current = updater(pendingBoxesRef.current);\n setPendingBoxes(pendingBoxesRef.current);\n }, []);\n\n const setStatusBoth = useCallback((s: AssistantStatus) => {\n statusRef.current = s;\n setStatus(s);\n }, []);\n\n /**\n * 결과 폴리곤(들) → 커밋 도형. rect면 바운딩(축정렬 / rotatedRect면 최소회전) 사각형.\n * style은 호출부가 스냅샷해 넘긴다 — 박스 요청은 드래그 시점 클래스 스타일을\n * 캡처해서, 추론 중 클래스를 바꿔도 결과가 어긋나지 않게 한다(레거시 파리티).\n */\n const buildShapes = useCallback(\n (\n polys: Point[][],\n resultShape: \"polygon\" | \"rect\",\n style: ShapeStyle,\n ): EditorShape<TMeta>[] | null => {\n const rotated = assistantRef.current?.rectResult === \"rotatedRect\";\n return polys.map((pts) => {\n if (resultShape === \"rect\" && rotated)\n return {\n id: generateId(),\n type: SHAPE_TYPE.ROTATED_RECTANGLE,\n points: minAreaRect(pts),\n style,\n meta: draftMeta,\n };\n if (resultShape === \"rect\") {\n const b = getBBox(pts);\n return {\n id: generateId(),\n type: SHAPE_TYPE.RECTANGLE,\n points: [\n { x: b.minX, y: b.minY },\n { x: b.maxX, y: b.maxY },\n ],\n style,\n meta: draftMeta,\n };\n }\n return {\n id: generateId(),\n type: SHAPE_TYPE.POLYGON,\n points: pts,\n style,\n meta: draftMeta,\n };\n });\n },\n [draftMeta, assistantRef],\n );\n\n // 확정: 포인트 세션이 만든 도형은 문서에 남기고 세션만 정리. 박스 요청엔 영향 없음.\n const finalize = useCallback(() => {\n tokenRef.current++;\n pointsRef.current = [];\n committedRef.current = [];\n baseRef.current = null;\n originalShapeRef.current = null;\n setPoints([]);\n setStatusBoth(\"idle\");\n }, [setStatusBoth]);\n\n /**\n * 취소(Esc): 포인트 세션 생성분 제거 + 진행 중인 박스/포인트 응답 폐기.\n * 이미 커밋된 박스 결과는 유지한다(옵스와 동일 — 일반 삭제/undo로 다룬다).\n */\n const cancel = useCallback(() => {\n boxEpochRef.current++;\n mutatePending(() => []);\n const original = originalShapeRef.current;\n if (original) {\n // 기존 도형 refine 세션 — 생성분 삭제가 아니라 원본 좌표 복원.\n docRef.current.update([original]);\n } else if (committedRef.current.length) {\n docRef.current.remove(committedRef.current);\n }\n finalize();\n }, [docRef, finalize, mutatePending]);\n\n // ── 포인트 세션(마법봉) — 단일 세션, 제자리 refine ──\n\n const applyResult = useCallback(\n (polys: Point[][]) => {\n const ids = committedRef.current;\n if (!polys.length) {\n if (ids.length) {\n docRef.current.remove(ids);\n committedRef.current = [];\n }\n return;\n }\n if (ids.length === polys.length) {\n // 같은 개수 → 제자리 갱신(refine).\n const shapes = docRef.current.getShapes();\n const updates = polys\n .map((pts, i) => {\n const prev = shapes.find((s) => s.id === ids[i]);\n return prev ? { ...prev, points: pts } : null;\n })\n .filter((s): s is EditorShape<TMeta> => !!s);\n if (updates.length) docRef.current.update(updates);\n return;\n }\n // 개수가 달라짐 → 이전 것 제거 후 새로 생성(포인트 세션 결과는 항상 폴리곤).\n // refine 대상이 대체되므로 원복 스냅샷은 무효화한다.\n baseRef.current = null;\n originalShapeRef.current = null;\n if (ids.length) docRef.current.remove(ids);\n const style = draftRef.current;\n if (!style) return;\n const created = buildShapes(polys, \"polygon\", style);\n if (!created?.length) return;\n docRef.current.create(created);\n committedRef.current = created.map((s) => s.id);\n changeSelection(committedRef.current);\n },\n [docRef, draftRef, changeSelection, buildShapes],\n );\n\n const runInfer = useCallback(async () => {\n const infer = assistantRef.current?.infer;\n if (!infer) return;\n const prompt: AssistantPrompt = {\n kind: \"points\",\n points: pointsRef.current,\n base: baseRef.current ?? undefined,\n };\n const token = ++tokenRef.current;\n setStatusBoth(\"loading\");\n let polys: Point[][] = [];\n try {\n const result = await infer(prompt);\n polys = (result ?? []).filter((p) => p.length >= 3);\n } catch {\n polys = [];\n }\n if (token !== tokenRef.current) return; // stale — 더 최신 요청/취소.\n applyResult(polys);\n setStatusBoth(\"ready\");\n }, [assistantRef, applyResult, setStatusBoth]);\n\n const addPoint = useCallback(\n (p: Point, positive: boolean) => {\n // 누적 포인트(pointsRef)는 추론 프롬프트용으로 전부 유지하되, 화면 마커(setPoints)는\n // 이번에 찍은 점만 표시한다(옵스식 — 진행 중인 그 점만 보이고 끝나면 사라짐).\n pointsRef.current = [...pointsRef.current, { x: p.x, y: p.y, positive }];\n setPoints([{ x: p.x, y: p.y, positive }]);\n runInfer();\n },\n [runInfer],\n );\n\n // 옵스식 마법봉: 그냥 클릭 → 이전 세션 확정 후 그 점 기반 새 폴리곤 생성.\n const newPolygon = useCallback(\n (p: Point) => {\n finalize();\n const next = [{ x: p.x, y: p.y, positive: true }];\n pointsRef.current = next;\n setPoints(next);\n runInfer();\n },\n [finalize, runInfer],\n );\n\n /**\n * 기존 도형을 지정 지점으로 refine(우클릭 메뉴 \"이 지점 포함/제외\").\n * 같은 도형이면 세션을 이어 포인트를 누적하고, 다른 도형이면 새 refine 세션을\n * 시작한다(원본 좌표를 base로 프롬프트에 실어 제자리 갱신, Esc=원복).\n */\n const refineShape = useCallback(\n (shape: EditorShape<TMeta>, p: Point, positive: boolean) => {\n if (committedRef.current.length !== 1 || committedRef.current[0] !== shape.id) {\n finalize();\n committedRef.current = [shape.id];\n baseRef.current = shape.points;\n originalShapeRef.current = shape;\n }\n pointsRef.current = [...pointsRef.current, { x: p.x, y: p.y, positive }];\n setPoints([{ x: p.x, y: p.y, positive }]);\n runInfer();\n },\n [finalize, runInfer],\n );\n\n // ── 박스 프롬프트 — 병렬 독립 요청(옵스식: 연속 드래그가 서로를 취소하지 않음) ──\n\n const beginBox = useCallback(\n (b: Box, resultShape: \"polygon\" | \"rect\" = \"polygon\") => {\n const infer = assistantRef.current?.infer;\n const style = draftRef.current; // 드래그 시점 클래스 스타일 스냅샷.\n if (!infer || !style) return;\n const epoch = boxEpochRef.current;\n mutatePending((list) => [...list, b]);\n void (async () => {\n let polys: Point[][] = [];\n try {\n const result = await infer({ kind: \"box\", box: b });\n polys = (result ?? []).filter((p) => p.length >= 3);\n } catch {\n polys = [];\n }\n mutatePending((list) => list.filter((x) => x !== b));\n if (epoch !== boxEpochRef.current) return; // 취소됨 — 결과 폐기.\n const created = buildShapes(polys, resultShape, style);\n if (!created?.length) return;\n docRef.current.create(created);\n changeSelection(created.map((s) => s.id));\n })();\n },\n [assistantRef, draftRef, buildShapes, changeSelection, docRef, mutatePending],\n );\n\n const isActive = useCallback(\n () =>\n statusRef.current === \"loading\" ||\n pointsRef.current.length > 0 ||\n pendingBoxesRef.current.length > 0 ||\n committedRef.current.length > 0,\n [],\n );\n\n return {\n status,\n points,\n /** 진행 중인 박스 프롬프트들(병렬). 오버레이 shimmer 표시용. */\n boxes: pendingBoxes,\n beginBox,\n addPoint,\n newPolygon,\n refineShape,\n finalize,\n cancel,\n isActive,\n };\n}\n\nexport type AssistantSession<TMeta> = ReturnType<typeof useAssistant<TMeta>>;\n","import type { Point } from \"./geometry\";\n\nfunction perpendicularDistance(point: Point, lineStart: Point, lineEnd: Point) {\n const area = Math.abs(\n 0.5 *\n (lineStart.x * lineEnd.y +\n lineEnd.x * point.y +\n point.x * lineStart.y -\n lineEnd.x * lineStart.y -\n point.x * lineEnd.y -\n lineStart.x * point.y),\n );\n const bottom = Math.hypot(lineStart.x - lineEnd.x, lineStart.y - lineEnd.y);\n return bottom === 0 ? 0 : (area * 2) / bottom;\n}\n\n/** RDP 경로 단순화(이미지 좌표). */\nexport function simplifyPath(points: Point[], epsilon = 1.5): Point[] {\n if (points.length <= 2) return points;\n\n const rdp = (pts: Point[], eps: number): Point[] => {\n if (pts.length < 3) return pts;\n let dmax = 0;\n let index = 0;\n const end = pts.length - 1;\n for (let i = 1; i < end; i++) {\n const d = perpendicularDistance(pts[i], pts[0], pts[end]);\n if (d > dmax) {\n index = i;\n dmax = d;\n }\n }\n if (dmax > eps) {\n const left = rdp(pts.slice(0, index + 1), eps);\n const right = rdp(pts.slice(index), eps);\n return left.slice(0, -1).concat(right);\n }\n return [pts[0], pts[end]];\n };\n\n const simplified = rdp(points, epsilon);\n const last = points[points.length - 1];\n const tail = simplified[simplified.length - 1];\n if (last.x !== tail.x || last.y !== tail.y) simplified.push(last);\n return simplified;\n}\n","import { simplifyPath } from \"./brush\";\nimport {\n circleToPolygon,\n type EditorShape,\n getBBox,\n type Point,\n rectTo4,\n SHAPE_TYPE,\n} from \"./geometry\";\n\nconst MAX_CANVAS_DIM = 4096;\nconst MIN_POLYGON_AREA = 4;\n\nfunction polygonArea(points: Point[]): number {\n let sum = 0;\n for (let i = 0; i < points.length; i++) {\n const a = points[i];\n const b = points[(i + 1) % points.length];\n sum += a.x * b.y - b.x * a.y;\n }\n return Math.abs(sum / 2);\n}\n\nfunction extractAlpha(data: Uint8ClampedArray, width: number, height: number): Uint8Array {\n const alpha = new Uint8Array(width * height);\n for (let i = 0; i < width * height; i++) {\n alpha[i] = data[i * 4 + 3] > 128 ? 255 : 0;\n }\n return alpha;\n}\n\nfunction alphaToRgba(alpha: Uint8Array): Uint8ClampedArray {\n const data = new Uint8ClampedArray(alpha.length * 4);\n for (let i = 0; i < alpha.length; i++) {\n if (alpha[i] > 128) data[i * 4 + 3] = 255;\n }\n return data;\n}\n\nfunction floodFillComponent(\n work: Uint8Array,\n width: number,\n height: number,\n sx: number,\n sy: number,\n): Uint8Array {\n const component = new Uint8Array(width * height);\n const stack: [number, number][] = [[sx, sy]];\n while (stack.length) {\n const [x, y] = stack.pop()!;\n const idx = y * width + x;\n if (x < 0 || y < 0 || x >= width || y >= height) continue;\n if (work[idx] <= 128) continue;\n work[idx] = 0;\n component[idx] = 255;\n stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);\n }\n return component;\n}\n\n/** 마스크에서 분리된 모든 외곽선을 추출. */\nfunction traceAllOuterContours(data: Uint8ClampedArray, width: number, height: number): Point[][] {\n const work = extractAlpha(data, width, height);\n const contours: Point[][] = [];\n\n while (true) {\n let sx = -1;\n let sy = -1;\n outer: for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (work[y * width + x] > 128) {\n sx = x;\n sy = y;\n break outer;\n }\n }\n }\n if (sx < 0) break;\n\n const component = floodFillComponent(work, width, height, sx, sy);\n const contour = traceOuterContour(alphaToRgba(component), width, height);\n if (contour.length >= 3) contours.push(contour);\n }\n\n return contours;\n}\n\nexport type ScalarStrokeMode = \"add\" | \"erase\";\n\nexport interface ScalarStroke {\n points: Point[];\n mode: ScalarStrokeMode;\n}\n\nexport interface ScalarMaskRaster {\n canvas: HTMLCanvasElement;\n ox: number;\n oy: number;\n scale: number;\n}\n\nfunction isFilled(data: Uint8ClampedArray, width: number, height: number, x: number, y: number) {\n if (x < 0 || y < 0 || x >= width || y >= height) return false;\n return data[(y * width + x) * 4 + 3] > 128;\n}\n\n/** 채워진 영역의 외곽선을 Moore-neighbor로 추적. */\nfunction traceOuterContour(data: Uint8ClampedArray, width: number, height: number): Point[] {\n let sx = -1;\n let sy = -1;\n outer: for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (isFilled(data, width, height, x, y)) {\n sx = x;\n sy = y;\n break outer;\n }\n }\n }\n if (sx < 0) return [];\n\n const dx = [1, 1, 0, -1, -1, -1, 0, 1];\n const dy = [0, 1, 1, 1, 0, -1, -1, -1];\n const contour: Point[] = [];\n let x = sx;\n let y = sy;\n let dir = 7;\n const start = { x, y };\n let guard = 0;\n\n do {\n contour.push({ x, y });\n let found = false;\n for (let i = 0; i < 8; i++) {\n const nd = (dir + i) % 8;\n const nx = x + dx[nd];\n const ny = y + dy[nd];\n if (isFilled(data, width, height, nx, ny)) {\n x = nx;\n y = ny;\n dir = (nd + 6) % 8;\n found = true;\n break;\n }\n }\n if (!found) break;\n guard += 1;\n if (guard > width * height * 4) break;\n } while (x !== start.x || y !== start.y || contour.length === 1);\n\n return contour;\n}\n\nfunction collectPoints(strokes: ScalarStroke[], basePolygons: Point[][]): Point[] {\n const all: Point[] = [];\n for (const stroke of strokes) {\n for (const p of stroke.points) all.push(p);\n }\n for (const poly of basePolygons) {\n for (const p of poly) all.push(p);\n }\n return all;\n}\n\n/** 면적 편집 가능한 도형 → 채움 폴리곤 꼭짓점. */\nfunction shapeToFilledPolygon(shape: EditorShape): Point[] | null {\n switch (shape.type) {\n case SHAPE_TYPE.RECTANGLE:\n if (shape.points.length < 2) return null;\n return rectTo4(shape.points);\n case SHAPE_TYPE.POLYGON:\n case SHAPE_TYPE.ROTATED_RECTANGLE:\n case SHAPE_TYPE.ELLIPSE:\n return shape.points.length >= 3 ? shape.points : null;\n case SHAPE_TYPE.POINT: {\n const p = shape.points[0];\n if (!p) return null;\n const r = 6;\n return circleToPolygon({ x: p.x - r, y: p.y - r }, { x: p.x + r, y: p.y + r });\n }\n default:\n return null;\n }\n}\n\nexport function shapesToFilledPolygons(shapes: EditorShape[]): Point[][] {\n return shapes\n .map(shapeToFilledPolygon)\n .filter((points): points is Point[] => !!points && points.length >= 3);\n}\n\n/** 붓/지우개 스트로크(+ 선택 도형 베이스)를 이진 마스크 캔버스로 래스터화. */\nexport function buildScalarMaskRaster(\n strokes: ScalarStroke[],\n radius: number,\n basePolygons: Point[][] = [],\n): ScalarMaskRaster | null {\n if (radius <= 0) return null;\n if (!strokes.length && !basePolygons.length) return null;\n\n const allPoints = collectPoints(strokes, basePolygons);\n if (!allPoints.length) return null;\n\n const padding = radius + 4;\n const bbox = getBBox(allPoints);\n let width = Math.ceil(bbox.maxX - bbox.minX + padding * 2);\n let height = Math.ceil(bbox.maxY - bbox.minY + padding * 2);\n const scale = Math.min(1, MAX_CANVAS_DIM / Math.max(width, height, 1));\n width = Math.max(1, Math.ceil(width * scale));\n height = Math.max(1, Math.ceil(height * scale));\n\n const ox = bbox.minX - padding;\n const oy = bbox.minY - padding;\n const toLocal = (p: Point) => ({\n x: (p.x - ox) * scale,\n y: (p.y - oy) * scale,\n });\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n ctx.lineCap = \"round\";\n ctx.lineJoin = \"round\";\n ctx.lineWidth = radius * 2 * scale;\n\n ctx.fillStyle = \"#000\";\n for (const poly of basePolygons) {\n if (poly.length < 3) continue;\n ctx.beginPath();\n const start = toLocal(poly[0]);\n ctx.moveTo(start.x, start.y);\n for (let i = 1; i < poly.length; i++) {\n const p = toLocal(poly[i]);\n ctx.lineTo(p.x, p.y);\n }\n ctx.closePath();\n ctx.fill();\n }\n\n for (const stroke of strokes) {\n if (!stroke.points.length) continue;\n ctx.globalCompositeOperation = stroke.mode === \"erase\" ? \"destination-out\" : \"source-over\";\n ctx.strokeStyle = stroke.mode === \"erase\" ? \"rgba(0,0,0,1)\" : \"#000\";\n ctx.beginPath();\n const first = toLocal(stroke.points[0]);\n ctx.moveTo(first.x, first.y);\n for (let i = 1; i < stroke.points.length; i++) {\n const p = toLocal(stroke.points[i]);\n ctx.lineTo(p.x, p.y);\n }\n if (stroke.points.length === 1) {\n ctx.lineTo(first.x + 0.01, first.y);\n }\n ctx.stroke();\n }\n\n return { canvas, ox, oy, scale };\n}\n\n/** 스칼라 마스크를 분리된 폴리곤 외곽선들로 변환. */\nexport function scalarMaskToPolygons(raster: ScalarMaskRaster, simplifyEpsilon = 1.5): Point[][] {\n const { canvas, ox, oy, scale } = raster;\n const contours = traceAllOuterContours(\n canvas.getContext(\"2d\")!.getImageData(0, 0, canvas.width, canvas.height).data,\n canvas.width,\n canvas.height,\n );\n if (!contours.length) return [];\n\n const toWorld = (p: Point) => ({\n x: p.x / scale + ox,\n y: p.y / scale + oy,\n });\n\n const polys: Point[][] = [];\n for (const contour of contours) {\n const world = contour.map(toWorld);\n const simplified = simplifyPath(world, simplifyEpsilon);\n const points = simplified.length >= 3 ? simplified : world;\n if (points.length >= 3 && polygonArea(points) >= MIN_POLYGON_AREA) {\n polys.push(points);\n }\n }\n return polys;\n}\n\nexport { polygonArea };\n\n/** 미리보기용 색상 오버레이 캔버스. */\nexport function buildScalarMaskPreviewCanvas(\n raster: ScalarMaskRaster,\n color: string,\n): HTMLCanvasElement {\n const { canvas } = raster;\n const preview = document.createElement(\"canvas\");\n preview.width = canvas.width;\n preview.height = canvas.height;\n const ctx = preview.getContext(\"2d\");\n if (!ctx) return canvas;\n\n ctx.drawImage(canvas, 0, 0);\n ctx.globalCompositeOperation = \"source-in\";\n ctx.fillStyle = color;\n ctx.fillRect(0, 0, preview.width, preview.height);\n return preview;\n}\n","import type { Point } from \"../_model/geometry\";\nimport type { ScalarStroke } from \"../_model/scalarMask\";\n\nexport function cloneScalarStrokes(strokes: ScalarStroke[]): ScalarStroke[] {\n return strokes.map((stroke) => ({\n mode: stroke.mode,\n points: stroke.points.map((point) => ({ ...point })),\n }));\n}\n\nexport function scalarStrokesEqual(a: ScalarStroke[], b: ScalarStroke[]) {\n return (\n a.length === b.length &&\n a.every(\n (stroke, i) =>\n stroke.mode === b[i].mode &&\n stroke.points.length === b[i].points.length &&\n stroke.points.every((p, j) => p.x === b[i].points[j].x && p.y === b[i].points[j].y),\n )\n );\n}\n\nexport function clonePoints(points: Point[]): Point[] {\n return points.map((p) => ({ ...p }));\n}\n\nexport function pointsEqual(a: Point[], b: Point[]) {\n return a.length === b.length && a.every((p, i) => p.x === b[i].x && p.y === b[i].y);\n}\n","import { type RefObject, useCallback, useRef } from \"react\";\nimport { simplifyPath } from \"../_model/brush\";\nimport {\n type EditorShape,\n generateId,\n isShapeEditable,\n type Point,\n SHAPE_TYPE,\n type ShapeStyle,\n} from \"../_model/geometry\";\nimport type { DrawSessionChange, DrawSessionKind } from \"../_model/props\";\nimport {\n buildScalarMaskRaster,\n polygonArea,\n type ScalarStroke,\n scalarMaskToPolygons,\n shapesToFilledPolygons,\n} from \"../_model/scalarMask\";\nimport { type BrushScalarMode, TOOL, type Tool } from \"../_model/tools\";\nimport type { EditorRenderer } from \"../_renderers/types\";\nimport {\n clonePoints,\n cloneScalarStrokes,\n pointsEqual,\n scalarStrokesEqual,\n} from \"./drawSessionState\";\nimport type { useEditorDocument } from \"./useEditorDocument\";\n\nconst DRAFT_POINT_HIT_RADIUS = 10;\n\ntype DocApi<TMeta> = ReturnType<typeof useEditorDocument<TMeta>>;\n\nfunction isSameDrawSession(a: DrawSessionChange, b: DrawSessionChange): boolean {\n if (\n a.active !== b.active ||\n a.kind !== b.kind ||\n a.canUndo !== b.canUndo ||\n a.canRedo !== b.canRedo\n ) {\n return false;\n }\n const aBrush = a.brush;\n const bBrush = b.brush;\n if (!aBrush || !bBrush) return aBrush === bBrush;\n return (\n aBrush.mode === bBrush.mode &&\n aBrush.editing === bBrush.editing &&\n aBrush.editTargetIds.length === bBrush.editTargetIds.length &&\n aBrush.editTargetIds.every((id, index) => id === bBrush.editTargetIds[index])\n );\n}\n\n/** useDrawSession가 반환하는 그리기 세션 핸들. */\nexport type DrawSession<TMeta> = ReturnType<typeof useDrawSession<TMeta>>;\n\ninterface UseDrawSessionParams<TMeta> {\n toolRef: RefObject<Tool>;\n selRef: RefObject<string[]>;\n docRef: RefObject<DocApi<TMeta>>;\n readOnlyRef: RefObject<boolean | undefined>;\n draftRef: RefObject<ShapeStyle | undefined>;\n brushSizeRef: RefObject<number>;\n /** 자유선/붓→폴리곤 단순화 강도(RDP epsilon). */\n simplifyEpsilonRef: RefObject<number>;\n draftMeta: TMeta | undefined;\n engineRef: RefObject<EditorRenderer | null>;\n onDrawSessionChange?: (session: DrawSessionChange) => void;\n onDraftShapeChange?: (shape: Pick<EditorShape<TMeta>, \"type\" | \"points\" | \"meta\"> | null) => void;\n changeSelection: (ids: string[]) => void;\n createShape: (type: EditorShape<TMeta>[\"type\"], points: Point[]) => void;\n}\n\nexport function useDrawSession<TMeta>({\n toolRef,\n selRef,\n docRef,\n readOnlyRef,\n draftRef,\n brushSizeRef,\n simplifyEpsilonRef,\n draftMeta,\n engineRef,\n onDrawSessionChange,\n onDraftShapeChange,\n changeSelection,\n createShape,\n}: UseDrawSessionParams<TMeta>) {\n const onDrawSessionChangeRef = useRef(onDrawSessionChange);\n onDrawSessionChangeRef.current = onDrawSessionChange;\n const onDraftShapeChangeRef = useRef(onDraftShapeChange);\n onDraftShapeChangeRef.current = onDraftShapeChange;\n const draftMetaRef = useRef(draftMeta);\n draftMetaRef.current = draftMeta;\n const createShapeRef = useRef(createShape);\n createShapeRef.current = createShape;\n const lastNotifiedDrawSessionRef = useRef<DrawSessionChange | null>(null);\n\n const draftPathRef = useRef<Point[]>([]);\n const draftCursorRef = useRef<Point | null>(null);\n const draftSelectedPointIndicesRef = useRef<Set<number>>(new Set());\n const draftHistoryRef = useRef<Point[][]>([[]]);\n const draftHistoryIndexRef = useRef(0);\n const lastNotifiedDraftPathRef = useRef<Point[] | null>(null);\n\n const scalarStrokesRef = useRef<ScalarStroke[]>([]);\n const scalarBasePolygonsRef = useRef<Point[][]>([]);\n const scalarEditTargetIdsRef = useRef<string[]>([]);\n const scalarHistoryRef = useRef<ScalarStroke[][]>([[]]);\n const scalarHistoryIndexRef = useRef(0);\n const brushScalarModeRef = useRef<BrushScalarMode>(\"draw\");\n\n const brushStrokeMode = (): ScalarStroke[\"mode\"] =>\n brushScalarModeRef.current === \"erase\" ? \"erase\" : \"add\";\n\n const getBrushSessionActive = () =>\n scalarEditTargetIdsRef.current.length > 0 ||\n scalarStrokesRef.current.length > 0 ||\n (toolRef.current === TOOL.BRUSH && draftPathRef.current.length > 0);\n\n const getDrawSessionKind = (): DrawSessionKind => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH && getBrushSessionActive()) return \"brush\";\n if (tool === TOOL.POLYGON && draftPathRef.current.length > 0) {\n return \"polygon\";\n }\n if (tool === TOOL.PATH && draftPathRef.current.length > 0) return \"path\";\n return \"none\";\n };\n\n const canUndoBrushSession = () =>\n draftPathRef.current.length > 0 || scalarHistoryIndexRef.current > 0;\n\n const canRedoBrushSession = () =>\n draftPathRef.current.length === 0 &&\n scalarHistoryIndexRef.current < scalarHistoryRef.current.length - 1;\n\n const canUndoPolygonSession = () => draftHistoryIndexRef.current > 0;\n\n const canRedoPolygonSession = () =>\n draftHistoryIndexRef.current < draftHistoryRef.current.length - 1;\n\n const canUndoSession = () => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) return canUndoBrushSession();\n if (tool === TOOL.POLYGON || tool === TOOL.PATH) {\n return canUndoPolygonSession();\n }\n return false;\n };\n\n const canRedoSession = () => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) return canRedoBrushSession();\n if (tool === TOOL.POLYGON || tool === TOOL.PATH) {\n return canRedoPolygonSession();\n }\n return false;\n };\n\n const hasDraftSession = () => getDrawSessionKind() !== \"none\";\n\n const notifyDrawSession = useCallback(() => {\n const kind = getDrawSessionKind();\n const next: DrawSessionChange = {\n active: kind !== \"none\",\n kind,\n canUndo: canUndoSession(),\n canRedo: canRedoSession(),\n brush:\n kind === \"brush\"\n ? {\n mode: brushScalarModeRef.current,\n editing: scalarEditTargetIdsRef.current.length > 0,\n editTargetIds: [...scalarEditTargetIdsRef.current],\n }\n : undefined,\n };\n const previous = lastNotifiedDrawSessionRef.current;\n if (previous && isSameDrawSession(previous, next)) return;\n lastNotifiedDrawSessionRef.current = next;\n onDrawSessionChangeRef.current?.(next);\n }, []);\n\n const resetScalarHistory = useCallback(() => {\n scalarHistoryRef.current = [[]];\n scalarHistoryIndexRef.current = 0;\n }, []);\n\n const renderPreview = useCallback(() => {\n const eng = engineRef.current;\n if (!eng) return;\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) {\n const strokes: ScalarStroke[] = [...scalarStrokesRef.current];\n if (draftPathRef.current.length) {\n strokes.push({\n points: draftPathRef.current,\n mode: brushStrokeMode(),\n });\n }\n if (!strokes.length && !scalarBasePolygonsRef.current.length) {\n eng.clearPreview();\n return;\n }\n const raster = buildScalarMaskRaster(\n strokes,\n brushSizeRef.current,\n scalarBasePolygonsRef.current,\n );\n if (!raster) {\n eng.clearPreview();\n return;\n }\n const color = draftRef.current?.color ?? \"#00e5ff\";\n eng.previewScalarMask(raster, color);\n return;\n }\n const points = draftPathRef.current;\n if (!points.length) {\n eng.clearPreview();\n if (lastNotifiedDraftPathRef.current) {\n lastNotifiedDraftPathRef.current = null;\n onDraftShapeChangeRef.current?.(null);\n }\n return;\n }\n const style = {\n ...draftRef.current,\n color: draftRef.current?.color ?? \"#00e5ff\",\n };\n const selected = Array.from(draftSelectedPointIndicesRef.current);\n // PATH(자유선/펜)은 정점을 찍는 방식이 아니므로 그리는 중 점을 숨기고 선만 보여준다.\n const showVertices = tool !== TOOL.PATH;\n eng.previewPoly(points, draftCursorRef.current, style, false, selected, showVertices);\n if (tool === TOOL.POLYGON || tool === TOOL.PATH) {\n const onDraftShapeChange = onDraftShapeChangeRef.current;\n if (onDraftShapeChange && points !== lastNotifiedDraftPathRef.current) {\n lastNotifiedDraftPathRef.current = points;\n onDraftShapeChange({\n // PATH도 커밋 시 단순화된 POLYGON이 되므로 동일한 도형 타입으로 통지한다.\n type: SHAPE_TYPE.POLYGON,\n points: clonePoints(points),\n meta: draftMetaRef.current,\n });\n }\n }\n }, [brushSizeRef, draftRef, engineRef, toolRef]);\n\n const pushScalarHistory = useCallback(\n (strokes: ScalarStroke[]) => {\n const snapshot = cloneScalarStrokes(strokes);\n const history = scalarHistoryRef.current;\n const index = scalarHistoryIndexRef.current;\n const last = history[index];\n if (last && scalarStrokesEqual(last, snapshot)) return;\n scalarHistoryRef.current = [...history.slice(0, index + 1), snapshot];\n scalarHistoryIndexRef.current += 1;\n notifyDrawSession();\n },\n [notifyDrawSession],\n );\n\n const pushDraftHistory = useCallback((points: Point[]) => {\n const history = draftHistoryRef.current;\n const index = draftHistoryIndexRef.current;\n const last = history[index];\n if (last && pointsEqual(last, points)) return;\n draftHistoryRef.current = [...history.slice(0, index + 1), clonePoints(points)];\n draftHistoryIndexRef.current += 1;\n }, []);\n\n const reset = useCallback(() => {\n draftPathRef.current = [];\n scalarStrokesRef.current = [];\n scalarBasePolygonsRef.current = [];\n scalarEditTargetIdsRef.current = [];\n draftCursorRef.current = null;\n draftSelectedPointIndicesRef.current = new Set();\n draftHistoryRef.current = [[]];\n draftHistoryIndexRef.current = 0;\n lastNotifiedDraftPathRef.current = null;\n resetScalarHistory();\n engineRef.current?.clearPreview();\n onDraftShapeChangeRef.current?.(null);\n notifyDrawSession();\n }, [engineRef, notifyDrawSession, resetScalarHistory]);\n\n const setDraftPath = useCallback(\n (points: Point[], commitHistory: boolean) => {\n draftPathRef.current = points;\n const validIndices = new Set(\n Array.from(draftSelectedPointIndicesRef.current).filter(\n (index) => index >= 0 && index < points.length,\n ),\n );\n draftSelectedPointIndicesRef.current = validIndices;\n if (commitHistory) pushDraftHistory(points);\n renderPreview();\n notifyDrawSession();\n },\n [notifyDrawSession, pushDraftHistory, renderPreview],\n );\n\n const getDraftPointsSnapshot = useCallback(() => clonePoints(draftPathRef.current), []);\n\n const hasDraftPoints = useCallback(() => draftPathRef.current.length > 0, []);\n\n const tryClosePolygon = useCallback(\n (p: Point, closeRadius: number) => {\n if (toolRef.current !== TOOL.POLYGON) return false;\n const points = draftPathRef.current;\n if (points.length < 3) return false;\n const first = points[0];\n if (Math.hypot(p.x - first.x, p.y - first.y) > closeRadius) {\n return false;\n }\n createShapeRef.current(SHAPE_TYPE.POLYGON, points);\n reset();\n return true;\n },\n [reset, toolRef],\n );\n\n const removeDraftPoint = useCallback(\n (index: number) => {\n const points = draftPathRef.current;\n if (index < 0 || index >= points.length) return false;\n setDraftPath(\n points.filter((_, pointIndex) => pointIndex !== index),\n true,\n );\n return true;\n },\n [setDraftPath],\n );\n\n const selectDraftPointForDrag = useCallback(\n (index: number, additive: boolean) => {\n const points = draftPathRef.current;\n if (index < 0 || index >= points.length) return null;\n const selected = new Set(draftSelectedPointIndicesRef.current);\n if (additive) {\n if (selected.has(index)) selected.delete(index);\n else selected.add(index);\n } else if (!selected.has(index)) {\n selected.clear();\n selected.add(index);\n }\n draftSelectedPointIndicesRef.current = selected;\n draftCursorRef.current = null;\n renderPreview();\n notifyDrawSession();\n return {\n base: clonePoints(points),\n indices: Array.from(selected),\n };\n },\n [notifyDrawSession, renderPreview],\n );\n\n const appendPolygonPoint = useCallback(\n (p: Point) => {\n draftSelectedPointIndicesRef.current = new Set();\n draftCursorRef.current = p;\n setDraftPath([...draftPathRef.current, p], true);\n },\n [setDraftPath],\n );\n\n const beginStroke = useCallback(\n (p: Point) => {\n draftCursorRef.current = null;\n draftSelectedPointIndicesRef.current = new Set();\n draftPathRef.current = [{ ...p }];\n renderPreview();\n notifyDrawSession();\n },\n [notifyDrawSession, renderPreview],\n );\n\n const appendStrokePoint = useCallback(\n (p: Point, step: number) => {\n const last = draftPathRef.current[draftPathRef.current.length - 1];\n if (last && Math.hypot(p.x - last.x, p.y - last.y) < step) return false;\n draftPathRef.current = [...draftPathRef.current, { ...p }];\n draftCursorRef.current = null;\n renderPreview();\n notifyDrawSession();\n return true;\n },\n [notifyDrawSession, renderPreview],\n );\n\n const moveDraftPoints = useCallback(\n (base: Point[], indices: number[], dx: number, dy: number) => {\n const moving = new Set(indices);\n draftPathRef.current = base.map((point, index) =>\n moving.has(index) ? { x: point.x + dx, y: point.y + dy } : { ...point },\n );\n draftCursorRef.current = null;\n renderPreview();\n notifyDrawSession();\n },\n [notifyDrawSession, renderPreview],\n );\n\n const commitDraftPointDrag = useCallback(\n (moved: boolean) => {\n if (moved) {\n pushDraftHistory(draftPathRef.current);\n renderPreview();\n notifyDrawSession();\n }\n },\n [notifyDrawSession, pushDraftHistory, renderPreview],\n );\n\n const setDraftCursor = useCallback(\n (p: Point | null) => {\n draftCursorRef.current = p ? { ...p } : null;\n renderPreview();\n },\n [renderPreview],\n );\n\n const undoBrush = useCallback(() => {\n if (draftPathRef.current.length > 0) {\n draftPathRef.current = [];\n renderPreview();\n notifyDrawSession();\n return true;\n }\n if (scalarHistoryIndexRef.current <= 0) return false;\n scalarHistoryIndexRef.current -= 1;\n scalarStrokesRef.current = cloneScalarStrokes(\n scalarHistoryRef.current[scalarHistoryIndexRef.current],\n );\n renderPreview();\n notifyDrawSession();\n return true;\n }, [notifyDrawSession, renderPreview]);\n\n const redoBrush = useCallback(() => {\n if (draftPathRef.current.length > 0) return false;\n if (scalarHistoryIndexRef.current >= scalarHistoryRef.current.length - 1) {\n return false;\n }\n scalarHistoryIndexRef.current += 1;\n scalarStrokesRef.current = cloneScalarStrokes(\n scalarHistoryRef.current[scalarHistoryIndexRef.current],\n );\n renderPreview();\n notifyDrawSession();\n return true;\n }, [notifyDrawSession, renderPreview]);\n\n const undoPolygon = useCallback(() => {\n if (draftHistoryIndexRef.current <= 0) return false;\n draftHistoryIndexRef.current -= 1;\n draftPathRef.current = clonePoints(draftHistoryRef.current[draftHistoryIndexRef.current]);\n draftSelectedPointIndicesRef.current = new Set();\n renderPreview();\n notifyDrawSession();\n return true;\n }, [notifyDrawSession, renderPreview]);\n\n const redoPolygon = useCallback(() => {\n if (draftHistoryIndexRef.current >= draftHistoryRef.current.length - 1) {\n return false;\n }\n draftHistoryIndexRef.current += 1;\n draftPathRef.current = clonePoints(draftHistoryRef.current[draftHistoryIndexRef.current]);\n draftSelectedPointIndicesRef.current = new Set();\n renderPreview();\n notifyDrawSession();\n return true;\n }, [notifyDrawSession, renderPreview]);\n\n const undoSession = useCallback(() => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) return undoBrush();\n if (tool === TOOL.POLYGON || tool === TOOL.PATH) return undoPolygon();\n return false;\n }, [toolRef, undoBrush, undoPolygon]);\n\n const redoSession = useCallback(() => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) return redoBrush();\n if (tool === TOOL.POLYGON || tool === TOOL.PATH) return redoPolygon();\n return false;\n }, [redoBrush, redoPolygon, toolRef]);\n\n const seedBrushEditFromSelection = useCallback(() => {\n const ids = selRef.current;\n if (!ids.length) {\n return scalarEditTargetIdsRef.current.length > 0;\n }\n const shapes = docRef.current\n .getShapes()\n .filter((shape) => ids.includes(shape.id) && isShapeEditable(shape));\n const polygons = shapesToFilledPolygons(shapes);\n if (!polygons.length) {\n scalarEditTargetIdsRef.current = [];\n scalarBasePolygonsRef.current = [];\n return false;\n }\n scalarEditTargetIdsRef.current = shapes.map((shape) => shape.id);\n scalarBasePolygonsRef.current = polygons;\n return true;\n }, [docRef, selRef]);\n\n const commitBrush = useCallback(() => {\n if (readOnlyRef.current) return false;\n const strokes: ScalarStroke[] = [...scalarStrokesRef.current];\n if (draftPathRef.current.length) {\n strokes.push({\n points: clonePoints(draftPathRef.current),\n mode: brushStrokeMode(),\n });\n }\n const basePolygons = scalarBasePolygonsRef.current;\n const editTargetIds = [...scalarEditTargetIdsRef.current];\n if (!strokes.length && !basePolygons.length) return false;\n\n const raster = buildScalarMaskRaster(strokes, brushSizeRef.current, basePolygons);\n if (!raster) {\n reset();\n return false;\n }\n const polygons = scalarMaskToPolygons(raster, simplifyEpsilonRef.current);\n\n if (editTargetIds.length) {\n const targets = docRef.current\n .getShapes()\n .filter((shape) => editTargetIds.includes(shape.id));\n if (!polygons.length) {\n docRef.current.remove(editTargetIds);\n reset();\n changeSelection([]);\n return true;\n }\n polygons.sort((a, b) => polygonArea(b) - polygonArea(a));\n const updates: EditorShape<TMeta>[] = [];\n const creates: EditorShape<TMeta>[] = [];\n const nextSelection: string[] = [];\n for (let i = 0; i < polygons.length; i++) {\n const points = polygons[i];\n if (i < targets.length) {\n const shape = targets[i];\n updates.push({ ...shape, type: SHAPE_TYPE.POLYGON, points });\n nextSelection.push(shape.id);\n } else {\n const template = targets[0];\n const id = generateId();\n creates.push({\n ...template,\n id,\n type: SHAPE_TYPE.POLYGON,\n points,\n });\n nextSelection.push(id);\n }\n }\n const deleteIds = targets.slice(polygons.length).map((shape) => shape.id);\n if (updates.length) docRef.current.update(updates);\n if (creates.length) docRef.current.create(creates);\n if (deleteIds.length) docRef.current.remove(deleteIds);\n reset();\n changeSelection(nextSelection);\n return true;\n }\n\n if (!polygons.length) {\n reset();\n return false;\n }\n const style = draftRef.current;\n if (!style) return false;\n const shapes: EditorShape<TMeta>[] = polygons.map((points) => ({\n id: generateId(),\n type: SHAPE_TYPE.POLYGON,\n points,\n style,\n meta: draftMeta,\n }));\n docRef.current.create(shapes);\n changeSelection(shapes.map((shape) => shape.id));\n reset();\n return true;\n }, [brushSizeRef, changeSelection, docRef, draftMeta, draftRef, readOnlyRef, reset]);\n\n const commitDraftSession = useCallback(() => {\n const tool = toolRef.current;\n if (tool === TOOL.BRUSH) return commitBrush();\n const points = draftPathRef.current;\n if (tool === TOOL.POLYGON && points.length >= 3) {\n createShapeRef.current(SHAPE_TYPE.POLYGON, points);\n reset();\n return true;\n }\n return false;\n }, [commitBrush, reset, toolRef]);\n\n const completeFreehandStroke = useCallback(() => {\n const points = draftPathRef.current;\n if (toolRef.current === TOOL.PATH && points.length >= 3) {\n const simplified = simplifyPath(points, simplifyEpsilonRef.current);\n if (simplified.length >= 3) {\n createShapeRef.current(SHAPE_TYPE.POLYGON, simplified);\n }\n }\n reset();\n }, [reset, toolRef]);\n\n const setBrushScalarMode = useCallback(\n (mode: BrushScalarMode) => {\n brushScalarModeRef.current = mode;\n notifyDrawSession();\n renderPreview();\n },\n [notifyDrawSession, renderPreview],\n );\n\n const beginBrushEditFromSelection = useCallback(() => {\n if (readOnlyRef.current || toolRef.current !== TOOL.BRUSH) return false;\n scalarStrokesRef.current = [];\n draftPathRef.current = [];\n resetScalarHistory();\n const ok = seedBrushEditFromSelection();\n notifyDrawSession();\n renderPreview();\n return ok;\n }, [\n notifyDrawSession,\n readOnlyRef,\n renderPreview,\n resetScalarHistory,\n seedBrushEditFromSelection,\n toolRef,\n ]);\n\n const deleteDraftSelectedPoints = useCallback(() => {\n const selected = draftSelectedPointIndicesRef.current;\n if (!selected.size) return false;\n const next = draftPathRef.current.filter((_, i) => !selected.has(i));\n draftSelectedPointIndicesRef.current = new Set();\n setDraftPath(next, true);\n return true;\n }, [setDraftPath]);\n\n const hitDraftPoint = useCallback(\n (p: Point) => {\n const eng = engineRef.current;\n const points = draftPathRef.current;\n if (!eng || !points.length) return -1;\n const hitRadius = DRAFT_POINT_HIT_RADIUS / (eng.viewport.scale || 1);\n for (let i = points.length - 1; i >= 0; i--) {\n const point = points[i];\n if (Math.hypot(p.x - point.x, p.y - point.y) <= hitRadius) return i;\n }\n return -1;\n },\n [engineRef],\n );\n\n const finishScalarStroke = useCallback(() => {\n if (draftPathRef.current.length >= 1) {\n scalarStrokesRef.current.push({\n points: clonePoints(draftPathRef.current),\n mode: brushStrokeMode(),\n });\n draftPathRef.current = [];\n pushScalarHistory(scalarStrokesRef.current);\n }\n renderPreview();\n notifyDrawSession();\n }, [notifyDrawSession, pushScalarHistory, renderPreview]);\n\n const cancelBrush = useCallback(() => {\n if (toolRef.current !== TOOL.BRUSH) return;\n reset();\n }, [reset, toolRef]);\n\n const handleToolChange = useCallback(\n (tool: Tool, isExternalTool: boolean) => {\n if (isExternalTool) {\n reset();\n brushScalarModeRef.current = \"draw\";\n return;\n }\n if (tool !== TOOL.BRUSH) {\n reset();\n brushScalarModeRef.current = \"draw\";\n return;\n }\n brushScalarModeRef.current = \"draw\";\n scalarStrokesRef.current = [];\n draftPathRef.current = [];\n resetScalarHistory();\n seedBrushEditFromSelection();\n notifyDrawSession();\n renderPreview();\n },\n [notifyDrawSession, renderPreview, reset, resetScalarHistory, seedBrushEditFromSelection],\n );\n\n const handleBrushSelectionChange = useCallback(\n (selectedIds: string[], readOnly: boolean | undefined) => {\n if (toolRef.current !== TOOL.BRUSH || readOnly) return;\n if (!selectedIds.length) {\n notifyDrawSession();\n return;\n }\n const nextKey = [...selectedIds].sort().join(\",\");\n const editKey = [...scalarEditTargetIdsRef.current].sort().join(\",\");\n if (nextKey === editKey) return;\n if (scalarStrokesRef.current.length || draftPathRef.current.length) {\n return;\n }\n scalarStrokesRef.current = [];\n draftPathRef.current = [];\n resetScalarHistory();\n seedBrushEditFromSelection();\n notifyDrawSession();\n renderPreview();\n },\n [notifyDrawSession, renderPreview, resetScalarHistory, seedBrushEditFromSelection, toolRef],\n );\n\n return {\n reset,\n undoSession,\n redoSession,\n canUndoSession,\n canRedoSession,\n hasDraftSession,\n hasDraftPoints,\n commitDraftSession,\n completeFreehandStroke,\n setBrushScalarMode,\n getBrushScalarMode: () => brushScalarModeRef.current,\n hasBrushSession: getBrushSessionActive,\n commitBrush,\n cancelBrush,\n beginBrushEditFromSelection,\n deleteDraftSelectedPoints,\n hitDraftPoint,\n getDraftPointsSnapshot,\n tryClosePolygon,\n removeDraftPoint,\n selectDraftPointForDrag,\n appendPolygonPoint,\n beginStroke,\n appendStrokePoint,\n moveDraftPoints,\n commitDraftPointDrag,\n setDraftCursor,\n finishScalarStroke,\n handleToolChange,\n handleBrushSelectionChange,\n };\n}\n","import { useCallback, useReducer, useRef } from \"react\";\nimport type { EditorShape } from \"../_model/geometry\";\n\n/**\n * 에디터가 소유하는 도형 문서 + undo/redo 히스토리.\n *\n * 전역 zustand가 아니라 컴포넌트 로컬 useReducer라 멀티 인스턴스 안전.\n * 히스토리는 스냅샷 방식(MVP). 변경이 문서에 커밋된 뒤 호스트 이벤트를 방출하며,\n * undo/redo는 이전↔현재 도형을 diff해 역연산 이벤트를 낸다.\n */\ninterface DocState<TMeta> {\n shapes: EditorShape<TMeta>[];\n past: EditorShape<TMeta>[][];\n future: EditorShape<TMeta>[][];\n}\n\ntype DocAction<TMeta> =\n | { type: \"CREATE\"; shapes: EditorShape<TMeta>[] }\n | { type: \"UPDATE\"; shapes: EditorShape<TMeta>[] }\n | { type: \"DELETE\"; ids: string[] }\n | { type: \"REPLACE\"; removeIds: string[]; shapes: EditorShape<TMeta>[] }\n | { type: \"REORDER\"; ids: string[]; edge: \"front\" | \"back\" }\n | { type: \"RESET\"; shapes: EditorShape<TMeta>[] }\n | { type: \"UNDO\" }\n | { type: \"REDO\" };\n\nfunction withHistory<TMeta>(state: DocState<TMeta>, next: EditorShape<TMeta>[]): DocState<TMeta> {\n return { shapes: next, past: [...state.past, state.shapes], future: [] };\n}\n\nfunction reducer<TMeta>(state: DocState<TMeta>, action: DocAction<TMeta>): DocState<TMeta> {\n switch (action.type) {\n case \"CREATE\":\n return withHistory(state, [...state.shapes, ...action.shapes]);\n case \"UPDATE\": {\n const patch = new Map(action.shapes.map((a) => [a.id, a]));\n return withHistory(\n state,\n state.shapes.map((a) => patch.get(a.id) ?? a),\n );\n }\n case \"DELETE\": {\n const ids = new Set(action.ids);\n return withHistory(\n state,\n state.shapes.filter((a) => !ids.has(a.id)),\n );\n }\n case \"REPLACE\": {\n const removeIds = new Set(action.removeIds);\n return withHistory(state, [\n ...state.shapes.filter((a) => !removeIds.has(a.id)),\n ...action.shapes,\n ]);\n }\n case \"REORDER\": {\n const ids = new Set(action.ids);\n const picked = state.shapes.filter((a) => ids.has(a.id));\n const rest = state.shapes.filter((a) => !ids.has(a.id));\n if (picked.length === 0) return state;\n const next = action.edge === \"front\" ? [...rest, ...picked] : [...picked, ...rest];\n return withHistory(state, next);\n }\n case \"RESET\":\n return { shapes: action.shapes, past: [], future: [] };\n case \"UNDO\": {\n if (state.past.length === 0) return state;\n const prev = state.past[state.past.length - 1];\n return {\n shapes: prev,\n past: state.past.slice(0, -1),\n future: [state.shapes, ...state.future],\n };\n }\n case \"REDO\": {\n if (state.future.length === 0) return state;\n const next = state.future[0];\n return {\n shapes: next,\n past: [...state.past, state.shapes],\n future: state.future.slice(1),\n };\n }\n default:\n return state;\n }\n}\n\ninterface DocCallbacks<TMeta> {\n onShapesCreated?: (shapes: EditorShape<TMeta>[]) => void;\n onShapesUpdated?: (shapes: EditorShape<TMeta>[]) => void;\n onShapesDeleted?: (ids: string[]) => void;\n}\n\n/** useEditorDocument가 반환하는 문서 핸들(에디터 도형+히스토리 제어). */\nexport type EditorDocument<TMeta> = ReturnType<typeof useEditorDocument<TMeta>>;\n\nexport function useEditorDocument<TMeta>(callbacks: DocCallbacks<TMeta>) {\n const { onShapesCreated, onShapesUpdated, onShapesDeleted } = callbacks;\n const [state, dispatch] = useReducer(reducer<TMeta>, {\n shapes: [],\n past: [],\n future: [],\n });\n // 핸들/동기 읽기용 미러(클로저 stale 방지).\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // dispatch(useReducer)는 다음 렌더에야 반영되므로, 동기 읽기 미러(stateRef)를 즉시 함께\n // 갱신한다. 그래야 create 직후 getShapes()가 새 도형을 반영해 \"생성 후 자동 선택\" 같은\n // read-after-write가 정상 동작한다(예전엔 normalizeSelection이 stale 미러를 읽어 새 도형\n // id를 걸러내 선택이 비었다).\n const dispatchSync = useCallback((action: DocAction<TMeta>) => {\n stateRef.current = reducer(stateRef.current, action);\n dispatch(action);\n }, []);\n\n const emitDiff = useCallback(\n (prev: EditorShape<TMeta>[], next: EditorShape<TMeta>[]) => {\n const prevMap = new Map(prev.map((a) => [a.id, a]));\n const nextMap = new Map(next.map((a) => [a.id, a]));\n const created = next.filter((a) => !prevMap.has(a.id));\n if (created.length) onShapesCreated?.(created);\n const deletedIds = prev.filter((a) => !nextMap.has(a.id)).map((a) => a.id);\n if (deletedIds.length) onShapesDeleted?.(deletedIds);\n const updated = next.filter((a) => prevMap.has(a.id) && prevMap.get(a.id) !== a);\n if (updated.length) onShapesUpdated?.(updated);\n },\n [onShapesCreated, onShapesUpdated, onShapesDeleted],\n );\n\n const create = useCallback(\n (shapes: EditorShape<TMeta> | EditorShape<TMeta>[]) => {\n const next = Array.isArray(shapes) ? shapes : [shapes];\n if (!next.length) return;\n dispatchSync({ type: \"CREATE\", shapes: next });\n onShapesCreated?.(next);\n },\n [onShapesCreated],\n );\n\n const update = useCallback(\n (shapes: EditorShape<TMeta>[]) => {\n dispatchSync({ type: \"UPDATE\", shapes });\n onShapesUpdated?.(shapes);\n },\n [onShapesUpdated],\n );\n\n const remove = useCallback(\n (ids: string[]) => {\n if (ids.length === 0) return;\n dispatchSync({ type: \"DELETE\", ids });\n onShapesDeleted?.(ids);\n },\n [onShapesDeleted],\n );\n\n /** 원자적 교체(합치기 등) — 삭제+생성을 히스토리 한 칸으로. 이벤트는 각각 방출. */\n const replace = useCallback(\n (removeIds: string[], shapes: EditorShape<TMeta>[]) => {\n if (!removeIds.length && !shapes.length) return;\n dispatchSync({ type: \"REPLACE\", removeIds, shapes });\n if (removeIds.length) onShapesDeleted?.(removeIds);\n if (shapes.length) onShapesCreated?.(shapes);\n },\n [onShapesCreated, onShapesDeleted],\n );\n\n /** z-순서 변경(맨 앞/뒤). 점 변경이 아니라 배열 순서만 — create/update/delete 이벤트 없음. */\n const reorder = useCallback((ids: string[], edge: \"front\" | \"back\") => {\n if (ids.length === 0) return;\n dispatchSync({ type: \"REORDER\", ids, edge });\n }, []);\n\n /** 호스트가 새 문서를 시드(이미지 전환 등). 히스토리 초기화, 이벤트 없음. */\n const reset = useCallback((shapes: EditorShape<TMeta>[]) => {\n dispatchSync({ type: \"RESET\", shapes });\n }, []);\n\n const undo = useCallback(() => {\n const s = stateRef.current;\n if (s.past.length === 0) return;\n emitDiff(s.shapes, s.past[s.past.length - 1]);\n dispatchSync({ type: \"UNDO\" });\n }, [emitDiff]);\n\n const redo = useCallback(() => {\n const s = stateRef.current;\n if (s.future.length === 0) return;\n emitDiff(s.shapes, s.future[0]);\n dispatchSync({ type: \"REDO\" });\n }, [emitDiff]);\n\n const canUndo = useCallback(() => stateRef.current.past.length > 0, []);\n const canRedo = useCallback(() => stateRef.current.future.length > 0, []);\n const getShapes = useCallback(() => stateRef.current.shapes, []);\n\n return {\n shapes: state.shapes,\n create,\n update,\n remove,\n replace,\n reorder,\n reset,\n undo,\n redo,\n canUndo,\n canRedo,\n getShapes,\n };\n}\n","/**\n * 에디터 단축키 매핑. 조합키 문자열(예: \"mod+shift+z\")을 액션으로 잇는다.\n * 호스트는 keymap prop으로 재정의(문자열/배열)하거나 비활성(null)할 수 있다.\n *\n * 조합키 규칙: 수식어는 `mod`(⌘/Ctrl)·`shift`·`alt` 순, 그 뒤에 키 토큰.\n * 키 토큰은 e.code 기반(레이아웃/IME 무관): 글자 a–z, 숫자 0–9,\n * 기호(= - [ ] ; . , / `), 이름키(escape/enter/backspace/delete/arrow*).\n */\n\nexport type EditorAction =\n | \"undo\"\n | \"redo\"\n | \"selectAll\"\n | \"copy\"\n | \"cut\"\n | \"paste\"\n | \"duplicate\"\n | \"delete\"\n | \"cancel\"\n | \"commitDraft\"\n | \"bringToFront\"\n | \"sendToBack\"\n | \"zoomIn\"\n | \"zoomOut\"\n | \"zoom100\"\n | \"zoomFit\"\n | \"toggleMinimap\"\n | \"toggleCursorGuide\"\n | \"togglePixelation\"\n | \"selectTool\"\n | \"rectangleTool\"\n | \"rotatedRectangleTool\"\n | \"circleTool\"\n | \"polygonTool\"\n | \"pathTool\"\n | \"brushTool\"\n | \"pointTool\";\n\nexport const DEFAULT_KEYMAP: Record<EditorAction, string[]> = {\n undo: [\"mod+z\"],\n redo: [\"mod+shift+z\"],\n selectAll: [\"mod+a\"],\n copy: [\"mod+c\"],\n cut: [\"mod+x\"],\n paste: [\"mod+v\"],\n duplicate: [\"mod+d\"],\n delete: [\"delete\", \"backspace\"],\n cancel: [\"escape\"],\n commitDraft: [\"enter\"],\n bringToFront: [\"mod+]\"],\n sendToBack: [\"mod+[\"],\n zoomIn: [\"mod+=\", \"mod+shift+=\"],\n zoomOut: [\"mod+-\"],\n zoom100: [\"shift+1\"],\n zoomFit: [\"shift+2\"],\n toggleMinimap: [\"m\"],\n toggleCursorGuide: [\";\"],\n togglePixelation: [\".\"],\n selectTool: [\"s\"],\n rectangleTool: [\"r\"],\n rotatedRectangleTool: [\"shift+r\"],\n circleTool: [\"o\"],\n polygonTool: [\"p\"],\n pathTool: [\"g\"],\n brushTool: [\"b\"],\n pointTool: [\"i\"],\n};\n\nconst CODE_TOKEN: Record<string, string> = {\n Equal: \"=\",\n Minus: \"-\",\n BracketLeft: \"[\",\n BracketRight: \"]\",\n Semicolon: \";\",\n Period: \".\",\n Comma: \",\",\n Slash: \"/\",\n Backquote: \"`\",\n};\n\nconst KEY_TOKEN: Record<string, string> = {\n Escape: \"escape\",\n Enter: \"enter\",\n Backspace: \"backspace\",\n Delete: \"delete\",\n Tab: \"tab\",\n ArrowUp: \"arrowup\",\n ArrowDown: \"arrowdown\",\n ArrowLeft: \"arrowleft\",\n ArrowRight: \"arrowright\",\n};\n\n/** KeyboardEvent → 정규화된 키 토큰. 수식어 단독/Space/미매핑은 null. */\nfunction keyToken(e: KeyboardEvent): string | null {\n const code = e.code;\n const letter = /^Key([A-Z])$/.exec(code);\n if (letter) return letter[1].toLowerCase();\n const digit = /^Digit([0-9])$/.exec(code);\n if (digit) return digit[1];\n if (CODE_TOKEN[code]) return CODE_TOKEN[code];\n if (KEY_TOKEN[e.key]) return KEY_TOKEN[e.key];\n return null;\n}\n\n/** KeyboardEvent → 조합키 문자열(예: \"mod+shift+z\"). 매핑 불가 시 null. */\nexport function eventToCombo(e: KeyboardEvent): string | null {\n const token = keyToken(e);\n if (!token) return null;\n const parts: string[] = [];\n if (e.metaKey || e.ctrlKey) parts.push(\"mod\");\n if (e.shiftKey) parts.push(\"shift\");\n if (e.altKey) parts.push(\"alt\");\n parts.push(token);\n return parts.join(\"+\");\n}\n\nexport type KeymapOverrides = Partial<Record<EditorAction, string | string[] | null>>;\n\n/** 기본 keymap에 호스트 재정의를 병합해 조합키→액션 조회 맵을 만든다. */\nexport function resolveKeymap(overrides?: KeymapOverrides): Map<string, EditorAction> {\n const lookup = new Map<string, EditorAction>();\n for (const action of Object.keys(DEFAULT_KEYMAP) as EditorAction[]) {\n const override = overrides?.[action];\n const combos =\n override === undefined\n ? DEFAULT_KEYMAP[action]\n : override === null\n ? []\n : Array.isArray(override)\n ? override\n : [override];\n for (const combo of combos) lookup.set(combo.toLowerCase(), action);\n }\n return lookup;\n}\n","import { type RefObject, useEffect, useMemo, useRef } from \"react\";\nimport { isEditableTarget, isShortcutTarget } from \"@/utils/keyboard\";\nimport {\n type EditorAction,\n eventToCombo,\n type KeymapOverrides,\n resolveKeymap,\n} from \"../_model/keymap\";\n\n/** 액션 핸들러. false 반환 시 \"미처리\"로 보고 preventDefault를 건너뛴다. */\nexport type EditorActionHandlers = Partial<Record<EditorAction, () => boolean | void>>;\n\ninterface EditorHotkeysCtx {\n /** 호스트 재정의(문자열/배열=재매핑, null=비활성). 미지정 키는 기본값. */\n keymap?: KeymapOverrides;\n /** 에디터 루트 요소. 에디터를 포함하지 않는 모달 위에서는 액션을 무시하는 데 쓴다. */\n hostRef: RefObject<HTMLElement | null>;\n actions: EditorActionHandlers;\n spaceRef: RefObject<boolean>;\n /** Space 눌림/뗌 시 커서 갱신 등(index 소유). */\n onSpaceDown: () => void;\n onSpaceUp: () => void;\n /** 방향키 넛지. 이동 대상이 없으면 false를 반환해 호스트 단축키에 양보한다. */\n nudge: (dx: number, dy: number) => boolean | void;\n}\n\nconst ARROW_DELTA: Record<string, [number, number]> = {\n ArrowUp: [0, -1],\n ArrowDown: [0, 1],\n ArrowLeft: [-1, 0],\n ArrowRight: [1, 0],\n};\n\n/**\n * 에디터 키보드 단축키. 기본 keymap을 내장하되 호스트가 재정의/비활성할 수 있다.\n * Space 추적과 방향키 넛지는 고정(재매핑 불가), 그 외 액션은 keymap 기반.\n * Shift 등 수식키는 여기서 추적하지 않는다 — 포인터 이벤트가 실어 오는 값을 쓴다.\n * 최신 keymap/액션을 ref로 읽어 리스너는 1회만 바인딩한다.\n */\nexport function useEditorHotkeys(ctx: EditorHotkeysCtx) {\n const { spaceRef } = ctx;\n const lookup = useMemo(() => resolveKeymap(ctx.keymap), [ctx.keymap]);\n\n const ref = useRef(ctx);\n ref.current = ctx;\n const lookupRef = useRef(lookup);\n lookupRef.current = lookup;\n\n useEffect(() => {\n const host = ref.current.hostRef.current;\n const ownerWindow = host?.ownerDocument.defaultView;\n if (!host || !ownerWindow) return;\n const down = (e: KeyboardEvent) => {\n // 부모 모달이 capture에서 Escape 닫힘을 막아도 캔버스의 취소 단계는 이어받는다.\n if ((e.defaultPrevented && e.key !== \"Escape\") || isEditableTarget(e.target)) return;\n if (!isShortcutTarget(host, e.target)) return;\n if (e.code === \"Space\") {\n spaceRef.current = true;\n ref.current.onSpaceDown();\n }\n\n const arrow = ARROW_DELTA[e.key];\n if (arrow) {\n const step = e.shiftKey ? 10 : 1;\n if (ref.current.nudge(arrow[0] * step, arrow[1] * step) !== false) {\n e.preventDefault();\n }\n return;\n }\n\n const combo = eventToCombo(e);\n if (!combo) return;\n const action = lookupRef.current.get(combo);\n if (!action) return;\n const handled = ref.current.actions[action]?.();\n if (handled !== false) e.preventDefault();\n };\n const up = (e: KeyboardEvent) => {\n if (e.code === \"Space\" && spaceRef.current) {\n spaceRef.current = false;\n ref.current.onSpaceUp();\n }\n };\n const release = () => {\n if (spaceRef.current) {\n spaceRef.current = false;\n ref.current.onSpaceUp();\n }\n };\n host.addEventListener(\"keydown\", down);\n // 키 해제는 입력창의 전파 차단보다 먼저 처리한다. 창 밖에서 키를 떼어\n // keyup을 받지 못하는 경우에는 blur에서 눌림 상태를 정리한다.\n ownerWindow.addEventListener(\"keyup\", up, true);\n ownerWindow.addEventListener(\"blur\", release);\n return () => {\n host.removeEventListener(\"keydown\", down);\n ownerWindow.removeEventListener(\"keyup\", up, true);\n ownerWindow.removeEventListener(\"blur\", release);\n // effect 재설정 때도 팬 모드와 커서를 해제한다. ref만 지우면 엔진 상태가 남는다.\n release();\n };\n }, [spaceRef]);\n}\n","/** 소스 하나로 이미지 로드를 시도한다(실패 시 null — 호출부가 폴백/진단 결정). */\nexport function loadImageElement(\n src: string,\n options?: { crossOrigin?: boolean },\n): Promise<HTMLImageElement | null> {\n return new Promise((resolve) => {\n const img = new Image();\n if (options?.crossOrigin) img.crossOrigin = \"anonymous\";\n img.onload = () => resolve(img);\n img.onerror = () => resolve(null);\n img.src = src;\n });\n}\n\n/**\n * CORS-clean 이미지 로드 — `<img crossOrigin>` 직행이 기본이다. blob을 쓰지\n * 않으므로 CSP img-src blob:·보안 확장의 blob 간섭 여지가 없다. 실패하면 앱\n * 어딘가의 no-cors `<img>`가 채운 오염 캐시(CORS 헤더 없는 응답)일 수 있으므로,\n * cache:\"reload\" fetch로 캐시 항목을 정상 CORS 응답으로 수리한 뒤 한 번 더\n * 시도한다. 그래도 실패면 null — 호출부가 상태/진단(imageDiagnosis.ts)을 처리한다.\n * Konva/Pixi 렌더러와 ShapeViewer가 공유한다.\n */\nexport async function loadCorsImage(url: string): Promise<HTMLImageElement | null> {\n const direct = await loadImageElement(url, { crossOrigin: true });\n if (direct) return direct;\n try {\n const response = await fetch(url, { mode: \"cors\", credentials: \"omit\", cache: \"reload\" });\n if (!response.ok) return null;\n // 본문을 끝까지 읽어야 캐시 기록이 완결된다(중단된 부분 응답은 캐시되지 않는다).\n await response.blob();\n } catch {\n return null;\n }\n return loadImageElement(url, { crossOrigin: true });\n}\n","import { loadImageElement } from \"./imageLoad\";\n\nexport type EditorImageErrorKind =\n | \"mixed-content\"\n | \"cors\"\n | \"auth\"\n | \"forbidden\"\n | \"not-found\"\n | \"server-error\"\n | \"http\"\n | \"offline\"\n | \"network\"\n | \"unexpected-content\"\n | \"decode\"\n | \"csp-img\"\n | \"csp-eval\"\n | \"webgl\"\n | \"renderer-init\"\n | \"unknown\";\n\n/** 이미지 로드 실패 분류 + 기술 근거(에러 오버레이·문의 대응용). */\nexport type EditorImageDiagnosis = {\n kind: EditorImageErrorKind;\n /** 언어 중립 기술 근거(상태코드·오리진 등). 분류별 안내문은 EditorStrings 몫. */\n detail: string;\n};\n\n/**\n * <img> 로드를 한 번 더 시도하며 CSP img-src 위반 이벤트를 감지한다.\n * 로드는 connect-src(fetch)와 img-src(<img>)가 따로 지배되므로, fetch 프로브가\n * 성공해도 img-src 차단이면 표시가 실패한다 — 이걸 손상 파일(decode)과 구분한다.\n * 위반이면 지시어 문자열, 아니면 null.\n */\nfunction probeImgCspViolation(url: string): Promise<string | null> {\n return new Promise((resolve) => {\n let violation: string | null = null;\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n document.removeEventListener(\"securitypolicyviolation\", onViolation);\n resolve(violation);\n };\n const onViolation = (event: SecurityPolicyViolationEvent) => {\n // 이 프로브가 유발한 유일한 이미지 로드이므로 img-src 계열 위반이면 그것이다.\n // effectiveDirective는 구형 브라우저에서 없을 수 있다 — violatedDirective 폴백.\n const directive = event.effectiveDirective ?? event.violatedDirective ?? \"\";\n if (directive.includes(\"img-src\")) {\n violation = `CSP ${directive} blocked ${event.blockedURI || url}`;\n }\n };\n // 이미지가 영영 settle하지 않는 극단 상황에서 리스너가 잔류하지 않게 상한.\n const timer = setTimeout(finish, 10_000);\n document.addEventListener(\"securitypolicyviolation\", onViolation);\n void loadImageElement(url, { crossOrigin: true }).then(() => {\n // 위반 이벤트는 로드 실패보다 먼저 디스패치되지만, 태스크 경계를 한 번\n // 넘겨 지연 디스패치까지 수거한다.\n setTimeout(finish, 0);\n });\n });\n}\n\n// 진단 결과 메모 — 같은 URL의 반복 실패(가상화 리스트 재마운트·리렌더)가 프로브\n// 요청을 다발로 만들지 않게 한다. presigned 만료 등으로 원인이 변할 수 있어 짧게만\n// 유지하고, URL 단위로만 공유한다(같은 스토리지라도 URL마다 원인이 다를 수 있다).\nconst DIAGNOSIS_MEMO_TTL_MS = 30_000;\nconst DIAGNOSIS_MEMO_MAX = 200;\nconst diagnosisMemo = new Map<string, { at: number; result: Promise<EditorImageDiagnosis> }>();\n\n/** 테스트 전용 — 전역 fetch/Image 스텁과 메모가 얽히지 않게 비운다. */\nexport function clearImageDiagnosisMemo() {\n diagnosisMemo.clear();\n}\n\n/**\n * 이미지 로드가 최종 실패했을 때 원인을 프로브로 분류한다. 회색 캔버스만 보이는\n * 현장에서 콘솔 없이 원인을 특정하기 위한 것. 프로브는 cache:\"no-store\"로 보내\n * HTTP 캐시를 건드리지 않는다.\n */\nexport function diagnoseImageLoadFailure(url: string): Promise<EditorImageDiagnosis> {\n const cached = diagnosisMemo.get(url);\n const now = Date.now();\n if (cached && now - cached.at < DIAGNOSIS_MEMO_TTL_MS) return cached.result;\n // 진단은 절대 reject하지 않는다 — 프로브 자체가 죽으면 원인을 지어내지 않고\n // \"unknown\"으로 정직하게 보고한다(메모에는 고정하지 않아 다음에 재시도).\n const result = runImageLoadDiagnosis(url).catch((error): EditorImageDiagnosis => {\n diagnosisMemo.delete(url);\n return { kind: \"unknown\", detail: error instanceof Error ? error.message : String(error) };\n });\n diagnosisMemo.set(url, { at: now, result });\n if (diagnosisMemo.size > DIAGNOSIS_MEMO_MAX) {\n const oldest = diagnosisMemo.keys().next().value;\n if (oldest !== undefined) diagnosisMemo.delete(oldest);\n }\n return result;\n}\n\nasync function runImageLoadDiagnosis(url: string): Promise<EditorImageDiagnosis> {\n let origin = url;\n try {\n origin = new URL(url, location.href).origin;\n } catch {\n // 상대/비정형 URL이면 원문 그대로 노출.\n }\n if (location.protocol === \"https:\" && url.startsWith(\"http:\")) {\n return { kind: \"mixed-content\", detail: `http image on https page (${origin})` };\n }\n\n let response: Response;\n try {\n response = await fetch(url, { mode: \"cors\", credentials: \"omit\", cache: \"no-store\" });\n } catch {\n if (!navigator.onLine) return { kind: \"offline\", detail: \"navigator.onLine=false\" };\n // CORS 차단과 네트워크 불통은 같은 TypeError로 온다 — no-cors 프로브는\n // CORS 검사 없이 도달 여부만 보므로 성공하면 CORS 문제로 확정된다.\n try {\n await fetch(url, { mode: \"no-cors\", cache: \"no-store\" });\n return { kind: \"cors\", detail: `no Access-Control-Allow-Origin from ${origin}` };\n } catch {\n return { kind: \"network\", detail: `fetch failed: ${origin}` };\n }\n }\n\n const { status } = response;\n if (response.ok) {\n const type = response.headers.get(\"content-type\") ?? \"\";\n // 게이트웨이가 로그인 페이지 등을 200으로 돌려주는 경우 — 정상 응답이지만 픽셀이 없다.\n if (type && !type.startsWith(\"image/\")) {\n const redirected = response.redirected ? \" via redirect\" : \"\";\n return { kind: \"unexpected-content\", detail: `HTTP ${status} (${type})${redirected}` };\n }\n // 전송(connect-src)은 되는데 <img> 표시만 막히는 CSP img-src 차단을 손상 파일과 구분.\n const violation = await probeImgCspViolation(url);\n if (violation) return { kind: \"csp-img\", detail: violation };\n // 전송은 정상인데 표시가 실패 — 손상 파일이거나 브라우저 미지원 형식.\n return { kind: \"decode\", detail: `HTTP ${status}${type ? ` (${type})` : \"\"}` };\n }\n\n if (status === 401 || status === 403) {\n // 쿠키를 붙이면 통과하는지 — 통과하면 인증 요구 이미지(에디터는 쿠키 없이 요청).\n // 보안 노트: credentials:include GET은 crossOrigin 없는 평범한 <img>와 동일한\n // 능력이다(대상 호스트 자신의 쿠키만 실리고, 응답은 서버가 Allow-Credentials로\n // 옵트인해야만 읽힌다). 401/403일 때 1회만 수행한다.\n try {\n const withCookies = await fetch(url, {\n mode: \"cors\",\n credentials: \"include\",\n cache: \"no-store\",\n });\n if (withCookies.ok) {\n return {\n kind: \"auth\",\n detail: `HTTP ${status} without cookies, ${withCookies.status} with cookies`,\n };\n }\n } catch {\n // 쿠키 포함도 실패 — 접근 거부로 처리.\n }\n return { kind: \"forbidden\", detail: `HTTP ${status}` };\n }\n if (status === 404 || status === 410) return { kind: \"not-found\", detail: `HTTP ${status}` };\n if (status >= 500) return { kind: \"server-error\", detail: `HTTP ${status}` };\n return { kind: \"http\", detail: `HTTP ${status}` };\n}\n\n/** WebGL 컨텍스트 생성 가능 여부 — 하드웨어 가속 꺼짐·보안 모드·GPU 차단 판별. */\nexport function isWebglAvailable(): boolean {\n try {\n const canvas = document.createElement(\"canvas\");\n return Boolean(canvas.getContext(\"webgl2\") ?? canvas.getContext(\"webgl\"));\n } catch {\n return false;\n }\n}\n\n/**\n * 렌더러 엔진 초기화/렌더 중 예외 분류 — 네트워크 단계가 아니라 프로브 없이\n * 에러 메시지와 WebGL 가용성으로 판정한다(pixi는 CSP unsafe-eval 차단 시\n * 명시적 에러를 던진다).\n */\nexport function diagnoseEngineInitFailure(error: unknown): EditorImageDiagnosis {\n const message = error instanceof Error ? error.message : String(error);\n if (/unsafe-eval/i.test(message)) return { kind: \"csp-eval\", detail: message };\n if (!isWebglAvailable()) {\n return { kind: \"webgl\", detail: message || \"WebGL context unavailable\" };\n }\n return { kind: \"renderer-init\", detail: message || \"renderer init failed\" };\n}\n","export const IMAGE_TILE_SIZE = 4000;\n\nexport interface ImageTile {\n x: number;\n y: number;\n width: number;\n height: number;\n srcX: number;\n srcY: number;\n}\n\nexport function getImageTiles(\n width: number,\n height: number,\n tileSize = IMAGE_TILE_SIZE,\n): ImageTile[] {\n if (width <= 0 || height <= 0) return [];\n const cols = Math.ceil(width / tileSize);\n const rows = Math.ceil(height / tileSize);\n return Array.from({ length: rows }, (_, row) =>\n Array.from({ length: cols }, (_, col) => {\n const x = col * tileSize;\n const y = row * tileSize;\n const isLastCol = col === cols - 1;\n const isLastRow = row === rows - 1;\n return {\n x,\n y,\n width: isLastCol ? width - x : tileSize + 1,\n height: isLastRow ? height - y : tileSize + 1,\n srcX: x,\n srcY: y,\n };\n }),\n ).flat();\n}\n\nexport function createImageTileCanvas(image: HTMLImageElement, tile: ImageTile): HTMLCanvasElement {\n const canvas = document.createElement(\"canvas\");\n canvas.width = tile.width;\n canvas.height = tile.height;\n const context = canvas.getContext(\"2d\");\n if (!context) return canvas;\n context.drawImage(\n image,\n tile.srcX,\n tile.srcY,\n tile.width,\n tile.height,\n 0,\n 0,\n tile.width,\n tile.height,\n );\n return canvas;\n}\n","import type Konva from \"konva\";\nimport type { EditorShape, Point, ShapeType } from \"./geometry\";\nimport { getBBox, SHAPE_TYPE } from \"./geometry\";\n\n// 드래그로 옮겨진 노드의 새 절대 좌표(이미지 좌표)를 도형 타입별로 계산.\nexport function movedPoints<TMeta>(shape: EditorShape<TMeta>, node: Konva.Node): Point[] {\n const { type, points } = shape;\n if (type === SHAPE_TYPE.POINT) {\n return [{ x: node.x(), y: node.y() }];\n }\n if (type === SHAPE_TYPE.RECTANGLE) {\n const [a, b] = points;\n const dx = node.x() - Math.min(a.x, b.x);\n const dy = node.y() - Math.min(a.y, b.y);\n return [\n { x: a.x + dx, y: a.y + dy },\n { x: b.x + dx, y: b.y + dy },\n ];\n }\n if (type === SHAPE_TYPE.ELLIPSE) {\n // Ellipse는 중심(node.x/y) 기준 — old 중심과의 delta를 점에 적용.\n const b = getBBox(points);\n const dx = node.x() - (b.minX + b.maxX) / 2;\n const dy = node.y() - (b.minY + b.maxY) / 2;\n return points.map((p) => ({ x: p.x + dx, y: p.y + dy }));\n }\n // POLYGON / ROTATED_RECTANGLE / LINE: Line은 x/y=0 기준이라 node 위치가 곧 delta.\n return points.map((p) => ({ x: p.x + node.x(), y: p.y + node.y() }));\n}\n\n// Konva 노드를 주어진 점 좌표가 렌더된 모습과 동일하게 맞춘다(이동 커밋 + 리사이즈\n// 미리보기에 공용). 깜빡임 방지 + 명령형 미리보기.\nexport function applyPointsToNode(node: Konva.Node, type: ShapeType, points: Point[]) {\n if (type === SHAPE_TYPE.POINT) {\n node.setAttrs({ x: points[0].x, y: points[0].y });\n return;\n }\n if (type === SHAPE_TYPE.RECTANGLE) {\n const [a, b] = points;\n node.setAttrs({\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n });\n return;\n }\n if (type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n node.setAttrs({\n x: (b.minX + b.maxX) / 2,\n y: (b.minY + b.maxY) / 2,\n radiusX: (b.maxX - b.minX) / 2,\n radiusY: (b.maxY - b.minY) / 2,\n });\n return;\n }\n // POLYGON / ROTATED_RECTANGLE / LINE\n node.setAttrs({ x: 0, y: 0, points: points.flatMap((p) => [p.x, p.y]) });\n}\n","/**\n * 지도 핀(물방울) 마커 — 기존 옵스 에디터의 pin.svg를 그대로 가져온 것.\n * POINT 도형을 점(dot) 대신 핀 아이콘으로 렌더할 때 쓴다. 팁은 하단중앙 (8,22).\n * 렌더러는 이 경로를 그리고 하단중앙을 도형 좌표에 맞춘 뒤, 뷰포트 반비례 스케일로\n * 화면 크기를 일정하게 유지한다.\n */\nexport const PIN_PATH =\n \"M8 0C12.4183 0 16 3.58172 16 8C16 11.5323 13.71 14.5277 10.5342 15.5879L10.166 20.0068C10.0721 21.1334 9.13046 22 8 22C6.86954 22 5.92786 21.1334 5.83398 20.0068L5.46484 15.5879C2.28949 14.5275 0 11.532 0 8C0 3.58172 3.58172 0 8 0Z\";\n\nexport const PIN_WIDTH = 16;\nexport const PIN_HEIGHT = 22;\nexport const PIN_STROKE = \"#ffffff\";\nexport const PIN_STROKE_WIDTH = 1.5;\n\n/** pixi Graphics.svg()용 최소 SVG 문자열(색 입힘). */\nexport function pinSvg(fill: string): string {\n return `<svg width=\"${PIN_WIDTH}\" height=\"${PIN_HEIGHT}\" viewBox=\"0 0 ${PIN_WIDTH} ${PIN_HEIGHT}\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"${PIN_PATH}\" fill=\"${fill}\" stroke=\"${PIN_STROKE}\" stroke-width=\"${PIN_STROKE_WIDTH}\"/></svg>`;\n}\n","import { POINT_RADIUS } from \"../_constants\";\nimport {\n ANCHORS,\n type Anchor,\n anchorPoint,\n type BBox,\n boxFromAnchor,\n type EditorShape,\n getBBox,\n isShapeDraggable,\n isShapeEditable,\n isShapeSelectable,\n orientedHandles,\n type Point,\n rectTo4,\n rescalePoints,\n resizeRotatedRectFromAnchor,\n rotatePoint,\n SHAPE_TYPE,\n shapeIntersectsBox,\n} from \"../_model/geometry\";\nimport { resolveShapeRenderStyle } from \"../_model/shapeRenderStyle\";\n\n/**\n * 트랜스포머 드래그(이동/리사이즈/회전/정점) 상태와 지오메트리 계산 — 렌더러 공용.\n * Konva/Pixi 렌더러는 여기서 계산된 updates/box로 각자 프리뷰(노드 갱신·핸들 재배치)만\n * 수행한다. 수학이 한 곳에 있어 버그 수정이 양 백엔드에 동시에 적용된다.\n */\n\nexport const ROT_SNAP = Math.PI / 12; // Shift 회전 15° 스냅.\n\nexport interface ShapeUpdate {\n id: string;\n points: Point[];\n}\n\nexport type ActiveDrag =\n | {\n kind: \"resize\";\n anchor: Anchor;\n box: BBox;\n shapes: ShapeUpdate[];\n }\n | {\n kind: \"move\";\n start: Point;\n box: BBox;\n shapes: ShapeUpdate[];\n }\n | {\n kind: \"vertex\";\n id: string;\n indices: number[];\n base: Point[];\n start: Point;\n }\n | {\n kind: \"rotate\";\n id: string;\n center: Point;\n startAngle: number;\n points: Point[];\n shiftKey: boolean;\n };\n\n/** 드래그 대상이 단일 회전사각형인지(리사이즈/이동 핸들 분기용). */\nexport function dragTargetIsRotatedRect(shapes: EditorShape[], d: ActiveDrag): boolean {\n if (d.kind !== \"resize\" && d.kind !== \"move\") return false;\n if (d.shapes.length !== 1) return false;\n const shape = shapes.find((s) => s.id === d.shapes[0].id);\n return shape?.type === SHAPE_TYPE.ROTATED_RECTANGLE;\n}\n\n/**\n * 드래그 진행/확정 공용 지오메트리 — 현재 포인터(img) 기준 도형별 새 points와\n * 축정렬 핸들 박스(box, 회전 케이스는 null)를 계산한다.\n */\nexport function computeDragUpdates(\n d: ActiveDrag,\n img: Point,\n isRotatedRect: boolean,\n): { updates: ShapeUpdate[]; box: BBox | null } {\n if (d.kind === \"resize\") {\n const nb = isRotatedRect ? d.box : boxFromAnchor(d.anchor, d.box, img.x, img.y);\n return {\n updates: d.shapes.map((s) => ({\n id: s.id,\n points: isRotatedRect\n ? resizeRotatedRectFromAnchor(s.points, d.anchor, img)\n : rescalePoints(s.points, d.box, nb),\n })),\n box: nb,\n };\n }\n if (d.kind === \"move\") {\n const dx = img.x - d.start.x;\n const dy = img.y - d.start.y;\n return {\n updates: d.shapes.map((s) => ({\n id: s.id,\n points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })),\n })),\n box: {\n minX: d.box.minX + dx,\n minY: d.box.minY + dy,\n maxX: d.box.maxX + dx,\n maxY: d.box.maxY + dy,\n },\n };\n }\n if (d.kind === \"rotate\") {\n let a = Math.atan2(img.y - d.center.y, img.x - d.center.x) - d.startAngle;\n if (d.shiftKey) a = Math.round(a / ROT_SNAP) * ROT_SNAP;\n return {\n updates: [{ id: d.id, points: d.points.map((p) => rotatePoint(p, d.center, a)) }],\n box: null,\n };\n }\n const dx = img.x - d.start.x;\n const dy = img.y - d.start.y;\n const next = d.base.map((p, i) => (d.indices.includes(i) ? { x: p.x + dx, y: p.y + dy } : p));\n return { updates: [{ id: d.id, points: next }], box: getBBox(next) };\n}\n\n/**\n * 포인터 이동 전(클릭 유지 상태) 드래그 지오메트리를 바꾸지 않는 포인터 이미지 좌표.\n * 뷰포트 변경(줌/팬) 중 드래그 상태를 건드리지 않고 핸들·프리뷰만 재배치할 때 쓴다.\n */\nexport function dragIdentityImage(shapes: EditorShape[], d: ActiveDrag): Point {\n if (d.kind === \"move\" || d.kind === \"vertex\") return d.start;\n if (d.kind === \"rotate\") {\n return {\n x: d.center.x + Math.cos(d.startAngle),\n y: d.center.y + Math.sin(d.startAngle),\n };\n }\n if (dragTargetIsRotatedRect(shapes, d)) {\n return orientedHandles(d.shapes[0].points)[ANCHORS.indexOf(d.anchor)];\n }\n return anchorPoint(d.anchor, d.box);\n}\n\n/** 이동 드래그 시작 상태 — 드래그 가능한 대상만 추려 스냅샷과 합집합 박스를 만든다. */\nexport function makeMoveDrag(\n shapes: EditorShape[],\n ids: string[],\n start: Point,\n): Extract<ActiveDrag, { kind: \"move\" }> | null {\n const targets = shapes\n .filter((s) => ids.includes(s.id) && isShapeDraggable(s))\n .map((s) => ({ id: s.id, points: s.points }));\n if (!targets.length) return null;\n return { kind: \"move\", start, box: getBBox(targets.flatMap((s) => s.points)), shapes: targets };\n}\n\n// ── 렌더러 공용 순수 헬퍼 ──\n\nexport function cloneShapes<TMeta>(shapes: EditorShape<TMeta>[]): EditorShape<TMeta>[] {\n return shapes.map((shape) => ({\n ...shape,\n points: shape.points.map((point) => ({ ...point })),\n }));\n}\n\n/** 선택 중 편집 가능한 도형. */\nexport function selectEditable(shapes: EditorShape[], selected: string[]): EditorShape[] {\n const selectedSet = new Set(selected);\n return shapes.filter((s) => selectedSet.has(s.id) && isShapeEditable(s));\n}\n\n/** 박스와 실제 기하가 겹치는 선택 가능 도형 id(마퀴 선택) — bbox 근사 아님. */\nexport function intersectingShapeIds(shapes: EditorShape[], box: BBox): string[] {\n return shapes.filter((s) => isShapeSelectable(s) && shapeIntersectsBox(s, box)).map((s) => s.id);\n}\n\n/** 점 도형 화면고정 반경(이미지 좌표) — 도형별 스타일 반영. */\nexport function pointRadiusFor(\n shape: EditorShape | undefined,\n strokeSize: number,\n scale: number,\n): number {\n const radius = shape\n ? resolveShapeRenderStyle(shape, { strokeWidth: strokeSize }).pointRadius\n : POINT_RADIUS;\n return radius / (scale || 1);\n}\n\nexport function pointSelectionBoxAt(p: Point, radius: number): BBox {\n return { minX: p.x - radius, minY: p.y - radius, maxX: p.x + radius, maxY: p.y + radius };\n}\n\n/** 선택 아웃라인 4점 — 회전사각형은 원 점, 점은 반경 박스, 나머지는 bbox. */\nexport function outlinePointsFor(\n shape: EditorShape,\n points: Point[],\n pointRadius: number,\n): Point[] {\n if (shape.type === SHAPE_TYPE.ROTATED_RECTANGLE) return points;\n const b =\n shape.type === SHAPE_TYPE.POINT ? pointSelectionBoxAt(points[0], pointRadius) : getBBox(points);\n return rectTo4([\n { x: b.minX, y: b.minY },\n { x: b.maxX, y: b.maxY },\n ]);\n}\n\n/** 회전 핸들과 박스 사이 간격(이미지 좌표, 화면 24px 고정). */\nexport function rotationHandleGapFor(scale: number): number {\n return 24 / (scale || 1);\n}\n\n/** 회전사각형 핸들 각도(화면 좌표 상단 변 기준). */\nexport function orientedAngleFromScreenPoints(tl: Point, tr: Point): number {\n return Math.atan2(tr.y - tl.y, tr.x - tl.x);\n}\n","import Konva from \"konva\";\nimport { SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA } from \"../_constants\";\nimport { resizeCursorForAnchor, UNSELECTED_HOVER_HINT } from \"../_model/cursors\";\nimport {\n ANCHORS,\n anchorPoint,\n type BBox,\n centerOf,\n type EditorShape,\n getBBox,\n isShapeDraggable,\n isShapeSelectable,\n isShapeVisible,\n mid,\n orientedHandles,\n type Point,\n rectTo4,\n rotateHandlePos,\n SHAPE_TYPE,\n type ShapeStyle,\n sortShapesForRender,\n} from \"../_model/geometry\";\nimport { loadCorsImage } from \"../_model/imageLoad\";\nimport { getImageTiles } from \"../_model/imageTiles\";\nimport { applyPointsToNode } from \"../_model/konva\";\nimport {\n drawRegionDim,\n type RegionOverlayData,\n type ResolvedRegionOutlineStyle,\n resolveCompletedDimStyle,\n} from \"../_model/overlays\";\nimport { PIN_HEIGHT, PIN_PATH, PIN_STROKE, PIN_STROKE_WIDTH, PIN_WIDTH } from \"../_model/pinIcon\";\nimport type { ScalarMaskRaster } from \"../_model/scalarMask\";\nimport { buildScalarMaskPreviewCanvas } from \"../_model/scalarMask\";\nimport {\n colorWithAlpha,\n resolveShapeRenderStyle,\n type ShapeRenderStyleDefaults,\n} from \"../_model/shapeRenderStyle\";\nimport {\n type ActiveDrag,\n cloneShapes,\n computeDragUpdates,\n dragIdentityImage,\n dragTargetIsRotatedRect,\n intersectingShapeIds,\n makeMoveDrag,\n orientedAngleFromScreenPoints,\n outlinePointsFor,\n pointRadiusFor,\n rotationHandleGapFor,\n selectEditable,\n} from \"./transformSession\";\nimport type { EditorRenderer, EditorRendererCallbacks, PreviewKind, Viewport } from \"./types\";\n\nconst STROKE = 2;\nconst _POINT_RADIUS = 5;\nconst HANDLE_HEX = \"#1e88e5\";\nconst SEL_HEX = \"#669def\";\n\n/**\n * KonvaRenderer — EditorRenderer의 Konva(canvas2D) 구현(명령형, react-konva 아님).\n * 좌표계: world 그룹이 이미지 좌표를 담고 scale/position으로 줌/팬. 선두께는\n * strokeScaleEnabled:false로 네이티브 화면고정. 핸들은 화면좌표 그룹(비-scaled).\n */\nexport class KonvaRenderer implements EditorRenderer {\n private stage: Konva.Stage;\n private layer = new Konva.Layer();\n private world = new Konva.Group();\n private bgGroup = new Konva.Group();\n private overlayGroup = new Konva.Group({ listening: false });\n private regionOverlayGroup = new Konva.Group({ listening: false });\n private dimOverlayGroup = new Konva.Group({ listening: false });\n private shapeGroup = new Konva.Group();\n private selGroup = new Konva.Group();\n private previewGroup = new Konva.Group();\n private handleGroup = new Konva.Group();\n private cb: EditorRendererCallbacks;\n private host: HTMLElement;\n private baseCursor = \"default\";\n private strokeSize = STROKE;\n private imageSmoothing = true;\n imageWidth = 0;\n imageHeight = 0;\n\n private shapes: EditorShape[] = [];\n private selected: string[] = [];\n private nodes = new Map<string, Konva.Shape>();\n // 점선 도형의 보조색(alternateColor) 밑선 노드 — 본 노드 아래에 실선으로 깔린다.\n private altNodes = new Map<string, Konva.Shape>();\n // 마지막으로 적용한 뷰포트 스케일. 판(스케일 불변) 시 스케일 의존 갱신을 건너뛰기 위함.\n private lastAppliedScale = -1;\n // 연속 setImage 레이스 가드 — 마지막 요청만 타일을 교체한다.\n private imageLoadToken = 0;\n private transformEnabled = false;\n private handleNodes: Konva.Rect[] = [];\n private vertexNodes: Konva.Circle[] = [];\n private lastImg: Point = { x: 0, y: 0 };\n private lastDragImg: Point | null = null;\n private ro: ResizeObserver | null = null;\n private activeDrag: ActiveDrag | null = null;\n // 편집모드 변(edge) 호버용 히트 라인 — 보이지 않고 히트만 받는다(정점 추가 진입점).\n private midNodes: Konva.Line[] = [];\n // 변 호버 시 커서의 변 위 최근접 지점에 표시되는 정점 추가 고스트.\n private ghostNode: Konva.Circle | null = null;\n // 다중 선택된 정점 인덱스(현재 편집 폴리곤 기준). 함께 이동.\n private selectedVertices = new Set<number>();\n private vertexPolygonId: string | null = null;\n // 폴리곤 정점 편집모드 대상 id(옵스식). 이 값이 선택된 단일 폴리곤과 같을 때만 정점 표시.\n private editingId: string | null = null;\n private rotNode: Konva.Circle | null = null;\n private rotLineNode: Konva.Line | null = null;\n private transformerOutline: Konva.Line | null = null;\n private selectionBorders: Konva.Line[] = [];\n\n constructor(host: HTMLElement, cb: EditorRendererCallbacks) {\n this.host = host;\n this.cb = cb;\n this.stage = new Konva.Stage({\n container: host as HTMLDivElement,\n width: host.clientWidth || 1,\n height: host.clientHeight || 1,\n });\n this.overlayGroup.add(this.regionOverlayGroup, this.dimOverlayGroup);\n this.world.add(\n this.bgGroup,\n this.overlayGroup,\n this.shapeGroup,\n this.selGroup,\n this.previewGroup,\n );\n this.layer.add(this.world, this.handleGroup);\n // 뷰포트(fit)가 정해지기 전엔 콘텐츠를 숨긴다(초기 unfit 프레임 방지). 첫 applyViewport\n // 에서 노출한다.\n this.world.visible(false);\n this.stage.add(this.layer);\n }\n\n async init() {\n const mousePointerId = 1;\n const ev = (e: Konva.KonvaEventObject<MouseEvent>) => ({\n pointerId: mousePointerId,\n button: e.evt.button,\n shiftKey: e.evt.shiftKey,\n altKey: e.evt.altKey,\n ctrlKey: e.evt.ctrlKey,\n metaKey: e.evt.metaKey,\n global: this.stage.getPointerPosition() ?? { x: 0, y: 0 },\n });\n this.stage.on(\"mousedown\", (e) => {\n const id = e.target === this.stage ? null : (e.target.id() as string) || null;\n this.cb.onPointerDown(this.toImage(), id, ev(e));\n });\n this.stage.on(\"mousemove\", (e) => {\n this.lastImg = this.toImage();\n if (this.activeDrag) {\n this.lastDragImg = this.lastImg;\n this.dragTransform(this.lastImg);\n return;\n }\n this.cb.onPointerMove(this.lastImg, {\n pointerId: mousePointerId,\n global: this.stage.getPointerPosition() ?? { x: 0, y: 0 },\n shiftKey: e.evt.shiftKey,\n });\n });\n let handledMouseUp: MouseEvent | null = null;\n const up = (event: MouseEvent, insideCanvas: boolean) => {\n // stage mouseup은 같은 네이티브 이벤트로 window까지 버블링되므로 한 번만 처리한다.\n if (handledMouseUp === event) return;\n handledMouseUp = event;\n if (this.activeDrag) {\n this.endTransform();\n return;\n }\n this.cb.onPointerUp(this.lastImg, {\n pointerId: mousePointerId,\n global: this.stage.getPointerPosition() ?? { x: 0, y: 0 },\n shiftKey: event.shiftKey,\n insideCanvas,\n });\n };\n this.stage.on(\"mouseup\", (e) => up(e.evt, true));\n const onWindowMouseUp = (event: MouseEvent) => {\n const target = event.target;\n up(event, target instanceof Node && this.host.contains(target));\n };\n window.addEventListener(\"mouseup\", onWindowMouseUp);\n this.upCleanup = () => window.removeEventListener(\"mouseup\", onWindowMouseUp);\n\n this.ro = new ResizeObserver(() => {\n this.stage.size({\n width: this.host.clientWidth || 1,\n height: this.host.clientHeight || 1,\n });\n this.layer.batchDraw();\n });\n this.ro.observe(this.host);\n }\n\n private upCleanup: (() => void) | null = null;\n\n destroy() {\n this.ro?.disconnect();\n this.upCleanup?.();\n this.stage.destroy();\n }\n\n get dom(): HTMLElement {\n return this.stage.container();\n }\n\n get screenSize() {\n return { w: this.stage.width(), h: this.stage.height() };\n }\n\n setCursor(cursor: string) {\n this.baseCursor = cursor;\n this.applyCursor();\n }\n\n private emitCursorHint(cursor: string | null) {\n this.cb.onCursorHint?.(cursor);\n }\n\n private emitInteractionMode(\n mode: \"idle\" | \"moving\" | \"resizing\" | \"rotating\" | \"vertexDragging\",\n ) {\n this.cb.onInteractionModeChange?.(mode);\n }\n\n private applyCursor() {\n this.stage.container().style.cursor = this.baseCursor;\n for (const canvas of this.stage.container().querySelectorAll(\"canvas\")) {\n canvas.style.cursor = this.baseCursor;\n }\n }\n\n /** 도형 호버 커서 — 선택된 도형만 grab, 비선택은 힌트로 구분해 소비층이 도구별 해석. */\n private bindShapeCursor(node: Konva.Node, shape: EditorShape) {\n if (!isShapeDraggable(shape)) return this.bindCursor(node, \"default\");\n this.bindCursor(node, () =>\n this.selected.includes(shape.id) ? \"grab\" : UNSELECTED_HOVER_HINT,\n );\n }\n\n private bindCursor(node: Konva.Node, cursor: string | (() => string)) {\n const enter = () => {\n if (this.activeDrag) return;\n const resolved = typeof cursor === \"function\" ? cursor() : cursor;\n if (resolved === \"pointer\" && !this.transformEnabled) return;\n this.emitCursorHint(resolved);\n };\n const leave = () => {\n if (!this.activeDrag) this.emitCursorHint(null);\n };\n node.on(\"mouseenter\", enter);\n node.on(\"mouseover\", enter);\n node.on(\"mouseleave\", leave);\n node.on(\"mouseout\", leave);\n }\n\n private toImage(): Point {\n const p = this.world.getRelativePointerPosition();\n return p ? { x: p.x, y: p.y } : this.lastImg;\n }\n\n private imgToScreen(p: Point): Point {\n return this.world.getAbsoluteTransform().point(p);\n }\n\n async setImage(\n url: string,\n coordinateSize?: { width: number; height: number },\n imageSize?: { width: number; height: number },\n ) {\n const loadToken = ++this.imageLoadToken;\n // <img crossOrigin> 직행이 기본, 오염 캐시일 때만 reload fetch로 수리 후\n // 재시도한다(imageLoad.ts 참고).\n const img = await loadCorsImage(url);\n\n if (loadToken !== this.imageLoadToken) return true; // 더 최신 요청 있음.\n if (!img) {\n this.imageWidth ||= 800;\n this.imageHeight ||= 600;\n return false;\n }\n // 좌표계 고정: coordinateSize가 있으면 도형 좌표계는 그 크기, 이미지는\n // 배경 그룹 스케일로 늘려 맞춘다(썸네일 표시 + 원본 좌표 편집,\n // 화질 스왑 간 픽셀 크기가 달라도 좌표계 불변).\n this.imageWidth = coordinateSize?.width ?? img.naturalWidth;\n this.imageHeight = coordinateSize?.height ?? img.naturalHeight;\n // 이미지가 좌표공간의 일부만 덮으면(imageSize) 그 크기로(원점 기준),\n // 아니면 좌표공간 전체로 늘려 그린다.\n const drawWidth = imageSize?.width ?? this.imageWidth;\n const drawHeight = imageSize?.height ?? this.imageHeight;\n this.bgGroup.scale({\n x: drawWidth / img.naturalWidth,\n y: drawHeight / img.naturalHeight,\n });\n this.bgGroup.destroyChildren();\n for (const tile of getImageTiles(img.naturalWidth, img.naturalHeight)) {\n this.bgGroup.add(\n new Konva.Image({\n image: img,\n x: tile.x,\n y: tile.y,\n width: tile.width,\n height: tile.height,\n crop: {\n x: tile.srcX,\n y: tile.srcY,\n width: tile.width,\n height: tile.height,\n },\n listening: false,\n }),\n );\n }\n this.layer.batchDraw();\n return true;\n }\n\n clearImage() {\n // 이후 도착하는 이전 setImage 응답이 타일을 되살리지 않게 토큰도 올린다.\n this.imageLoadToken++;\n this.bgGroup.destroyChildren();\n this.layer.batchDraw();\n }\n\n setFilter(brightness: number, contrast: number) {\n // 이미지 노드에만 CSS filter는 불가 → 컨테이너 캔버스에 적용(옵스와 동일, 전체 캔버스).\n const f =\n brightness !== 1 || contrast !== 1 ? `brightness(${brightness}) contrast(${contrast})` : \"\";\n const canvas = this.stage.container().querySelector(\"canvas\");\n if (canvas) (canvas as HTMLCanvasElement).style.filter = f;\n }\n\n setRenderDefaults(defaults: Partial<ShapeRenderStyleDefaults>) {\n const strokeSize = defaults.strokeWidth ?? this.strokeSize;\n if (this.strokeSize === strokeSize) return;\n this.strokeSize = strokeSize;\n this.setShapes(this.shapes, this.selected);\n }\n\n /** 편집모드 정점 핸들 반지름 — 선두께에 비례(기본 두께 2에서 기존 크기 5 유지). */\n private vertexHandleRadius(): number {\n return Math.max(4, this.strokeSize * 2.5);\n }\n\n setImageSmoothing(smooth: boolean) {\n if (this.imageSmoothing === smooth) return;\n this.imageSmoothing = smooth;\n // imageSmoothingEnabled는 레이어 캔버스 컨텍스트에 적용된다(drawImage 스케일링에만 영향,\n // 벡터 도형 안티에일리어싱과는 무관).\n this.layer.imageSmoothingEnabled(smooth);\n this.layer.batchDraw();\n }\n\n setOverlays(region: RegionOverlayData | null, dimmed: boolean) {\n this.setRegionOverlay(region);\n this.dimOverlayGroup.destroyChildren();\n if (dimmed && this.imageWidth) {\n const dim = resolveCompletedDimStyle(this.host);\n this.dimOverlayGroup.add(\n new Konva.Rect({\n x: 0,\n y: 0,\n width: this.imageWidth,\n height: this.imageHeight,\n fill: dim.color,\n opacity: dim.opacity,\n listening: false,\n }),\n );\n }\n this.layer.batchDraw();\n }\n\n setRegionOverlay(region: RegionOverlayData | null) {\n this.regionOverlayGroup.destroyChildren();\n if (region) {\n // 벡터 딤 — 래스터(캔버스 굽기) 없이 매 프레임 재계산해도 싸서 드래그 중\n // 오버레이가 트랜스포머와 같은 박자로 따라온다.\n const { imageWidth, imageHeight } = this;\n this.regionOverlayGroup.add(\n new Konva.Shape({\n listening: false,\n sceneFunc: (konvaCtx) => {\n drawRegionDim(konvaCtx._context, region, imageWidth, imageHeight);\n },\n }),\n );\n if (region.outlineStyles) {\n // 경계 선분 — strokeScaleEnabled:false로 두께·점선 패턴이 화면 px 고정(줌 무관).\n const addSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n const fixedStroke = {\n strokeWidth: style.width,\n strokeScaleEnabled: false,\n listening: false,\n };\n for (const [a, b] of segments) {\n if (style.underlayColor) {\n this.regionOverlayGroup.add(\n new Konva.Line({\n points: [a.x, a.y, b.x, b.y],\n stroke: style.underlayColor,\n ...fixedStroke,\n }),\n );\n }\n this.regionOverlayGroup.add(\n new Konva.Line({\n points: [a.x, a.y, b.x, b.y],\n stroke: style.color,\n opacity: style.opacity,\n dash: style.dash,\n ...fixedStroke,\n }),\n );\n }\n };\n addSegments(region.visibleOutline, region.outlineStyles.visible);\n addSegments(region.occludedOutline, region.outlineStyles.occluded);\n }\n }\n this.layer.batchDraw();\n }\n\n get viewport(): Viewport {\n return { scale: this.world.scaleX(), x: this.world.x(), y: this.world.y() };\n }\n\n applyViewport(v: Viewport) {\n // 판(translate만)은 스케일 불변이라 스케일 의존 갱신(화면고정 도형·선택테두리·핸들)이\n // 불필요하다 — 줌 때만 갱신해 도형 많을 때 판 렉을 방지. batchDraw는 위치 반영을 위해 유지.\n const scaleChanged = v.scale !== this.lastAppliedScale;\n this.lastAppliedScale = v.scale;\n this.world.scale({ x: v.scale, y: v.scale });\n this.world.position({ x: v.x, y: v.y });\n this.world.visible(true); // 뷰포트 확정 → 콘텐츠 노출(초기 unfit 프레임 방지)\n if (scaleChanged) {\n this.syncScreenFixedShapes();\n this.updateSelectionBordersLive((shape) => shape.points);\n // 그리는 중 폴리곤 초안의 정점 원 크기를 새 스케일로 재계산.\n const p = this.lastPreviewPoly;\n if (p) {\n this.previewPoly(\n p.points,\n p.cursor,\n p.style,\n p.closed,\n p.selectedPointIndices,\n p.showVertices,\n );\n }\n }\n // 트랜스포머 핸들은 화면 고정 그룹(layer 직속)에 화면 좌표로 그려지므로\n // 판(이동)에서도 매번 위치를 재계산해야 한다. 선택분만 그려서 가볍다.\n // 드래그(클릭 유지 포함) 중에는 drawTransformer가 조기 종료하므로\n // 마지막(또는 identity) 포인터 좌표로 라이브 재배치한다.\n if (this.activeDrag) {\n this.dragTransform(this.lastDragImg ?? dragIdentityImage(this.shapes, this.activeDrag));\n } else {\n this.drawTransformer();\n }\n this.layer.batchDraw();\n this.cb.onViewportChange?.();\n }\n\n fit() {\n if (!this.imageWidth || !this.imageHeight) return;\n const { w, h } = this.screenSize;\n const scale = Math.min(w / this.imageWidth, h / this.imageHeight);\n this.applyViewport({\n scale,\n x: (w - this.imageWidth * scale) / 2,\n y: (h - this.imageHeight * scale) / 2,\n });\n }\n\n zoom100() {\n if (!this.imageWidth || !this.imageHeight) return;\n const { w, h } = this.screenSize;\n this.applyViewport({\n scale: 1,\n x: (w - this.imageWidth) / 2,\n y: (h - this.imageHeight) / 2,\n });\n }\n\n zoomAt(cx: number, cy: number, factor: number) {\n const s = this.world.scaleX();\n const ns = Math.min(20, Math.max(0.05, s * factor));\n const wx = (cx - this.world.x()) / s;\n const wy = (cy - this.world.y()) / s;\n this.applyViewport({ scale: ns, x: cx - wx * ns, y: cy - wy * ns });\n }\n\n // ── 도형 렌더 ──\n setShapes(shapes: EditorShape[], selected: string[]) {\n this.shapes = cloneShapes(shapes);\n this.selected = selected;\n if (this.activeDrag) return;\n this.shapeGroup.destroyChildren();\n this.nodes.clear();\n this.altNodes.clear();\n for (const shape of sortShapesForRender(shapes).filter(isShapeVisible)) {\n const node = this.makeNode(shape);\n // 점선의 빈 구간 보조색 — 보조색 실선 밑선 위에 주색 점선(프리뷰·뷰어와 동일 계약).\n const style = resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize });\n if (shape.style?.alternateColor && style.dash?.length && shape.type !== SHAPE_TYPE.POINT) {\n const alt = node.clone({\n id: `${shape.id}__alt`,\n stroke: shape.style.alternateColor,\n dash: [],\n fillEnabled: false,\n listening: false,\n }) as Konva.Shape;\n this.altNodes.set(shape.id, alt);\n this.shapeGroup.add(alt);\n }\n this.nodes.set(shape.id, node);\n this.shapeGroup.add(node);\n }\n this.drawSelectionBorders();\n this.drawTransformer();\n this.layer.batchDraw();\n }\n\n setSelection(selected: string[]) {\n this.selected = selected;\n // 편집 대상 폴리곤이 아니게 되면 정점 다중선택 초기화.\n if (selected.length !== 1 || selected[0] !== this.vertexPolygonId) {\n this.vertexPolygonId = null;\n this.selectedVertices.clear();\n }\n if (this.editingId && (selected.length !== 1 || selected[0] !== this.editingId)) {\n this.editingId = null;\n }\n if (this.activeDrag) return;\n this.drawSelectionBorders();\n this.drawTransformer();\n this.layer.batchDraw();\n }\n\n /** 폴리곤 정점 편집모드 진입/해제(null이면 해제). */\n setEditing(id: string | null) {\n if (this.editingId === id) return;\n this.editingId = id;\n this.selectedVertices.clear();\n if (!this.activeDrag) {\n this.drawTransformer();\n this.layer.batchDraw();\n }\n }\n\n getVertexSelection(): number[] {\n return [...this.selectedVertices];\n }\n\n /** 편집모드 정점 다중선택 교체(마퀴 범위선택). 편집모드가 아니면 무시. */\n setVertexSelection(indices: number[]) {\n if (!this.editingId) return;\n const next = new Set(indices);\n if (\n next.size === this.selectedVertices.size &&\n [...next].every((i) => this.selectedVertices.has(i))\n ) {\n return;\n }\n this.selectedVertices = next;\n if (!this.activeDrag) {\n this.drawTransformer();\n this.layer.batchDraw();\n }\n }\n\n private makeNode(shape: EditorShape): Konva.Shape {\n const { type, points } = shape;\n const style = resolveShapeRenderStyle(shape, {\n strokeWidth: this.strokeSize,\n });\n const listening = isShapeSelectable(shape);\n const common = {\n id: shape.id,\n stroke: style.color,\n strokeWidth: style.strokeWidth,\n dash: this.scaledDash(style.dash),\n opacity: style.opacity,\n strokeScaleEnabled: false,\n listening,\n };\n const fill = style.fillVisible ? colorWithAlpha(style.color, style.fillAlpha) : undefined;\n if (type === SHAPE_TYPE.POINT) {\n const inv = 1 / (this.world.scaleX() || 1);\n const node = new Konva.Path({\n id: shape.id,\n data: PIN_PATH,\n x: points[0].x,\n y: points[0].y,\n offsetX: PIN_WIDTH / 2,\n offsetY: PIN_HEIGHT,\n scaleX: inv,\n scaleY: inv,\n fill: style.color,\n stroke: PIN_STROKE,\n strokeWidth: PIN_STROKE_WIDTH,\n strokeScaleEnabled: false,\n shadowColor: \"#000\",\n shadowBlur: 2,\n shadowOpacity: 0.3,\n shadowForStrokeEnabled: false,\n opacity: style.opacity,\n listening,\n });\n this.bindShapeCursor(node, shape);\n return node;\n }\n if (type === SHAPE_TYPE.RECTANGLE) {\n const b = getBBox(points);\n const node = new Konva.Rect({\n x: b.minX,\n y: b.minY,\n width: b.maxX - b.minX,\n height: b.maxY - b.minY,\n fill,\n ...common,\n });\n this.bindShapeCursor(node, shape);\n return node;\n }\n if (type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n const node = new Konva.Ellipse({\n x: (b.minX + b.maxX) / 2,\n y: (b.minY + b.maxY) / 2,\n radiusX: (b.maxX - b.minX) / 2,\n radiusY: (b.maxY - b.minY) / 2,\n fill,\n ...common,\n });\n this.bindShapeCursor(node, shape);\n return node;\n }\n const flat = points.flatMap((p) => [p.x, p.y]);\n const closed = type !== SHAPE_TYPE.LINE;\n const node = new Konva.Line({\n points: flat,\n closed,\n fill: closed ? fill : undefined,\n // 자기교차 폴리곤(도넛)의 구멍을 비운다 — Pixi 렌더러의 evenodd 분해와 동일 결과.\n fillRule: \"evenodd\",\n lineJoin: \"round\",\n ...common,\n });\n this.bindShapeCursor(node, shape);\n return node;\n }\n\n liveUpdateShape(id: string, points: Point[]) {\n const node = this.nodes.get(id);\n const shape = this.shapes.find((s) => s.id === id);\n if (node && shape) {\n applyPointsToNode(node, shape.type, points);\n const alt = this.altNodes.get(id);\n if (alt) applyPointsToNode(alt, shape.type, points);\n if (shape.type === SHAPE_TYPE.POINT && node instanceof Konva.Circle) {\n node.radius(this.pointRadius(shape));\n }\n this.layer.batchDraw();\n }\n }\n\n private pointRadius(shape?: EditorShape) {\n return pointRadiusFor(shape, this.strokeSize, this.world.scaleX() || 1);\n }\n\n private scaledDash(dash?: number[]) {\n return dash;\n }\n\n private syncScreenFixedShapes() {\n const inv = 1 / (this.world.scaleX() || 1);\n for (const shape of this.shapes) {\n const node = this.nodes.get(shape.id);\n if (shape.type === SHAPE_TYPE.POINT) {\n // 핀은 뷰포트 반비례 스케일로 화면 크기 고정.\n node?.scale({ x: inv, y: inv });\n continue;\n }\n node?.dash(\n this.scaledDash(resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize }).dash),\n );\n }\n }\n\n shapesIntersecting(box: BBox): string[] {\n return intersectingShapeIds(this.shapes, box);\n }\n\n private drawSelectionBorders() {\n // Set 멤버십 + 노드 재사용(개수 변화 때만 재생성). 전체선택 후 줌/판마다\n // N개 노드를 destroy/생성하고 includes로 O(N²) 검사하던 렉 방지.\n const selectedSet = new Set(this.selected);\n const targets = this.selected.length\n ? this.shapes.filter((s) => selectedSet.has(s.id) && isShapeSelectable(s))\n : [];\n if (this.selectionBorders.length !== targets.length) {\n for (const rect of this.selectionBorders) rect.destroy();\n this.selectionBorders = targets.map(() => {\n const rect = new Konva.Line({\n closed: true,\n stroke: SEL_HEX,\n strokeWidth: 1.5,\n strokeScaleEnabled: false,\n listening: false,\n });\n this.selGroup.add(rect);\n return rect;\n });\n }\n targets.forEach((shape, i) => {\n this.selectionBorders[i].points(\n this.selectionOutlinePoints(shape, shape.points).flatMap((p) => [p.x, p.y]),\n );\n });\n }\n\n /** 드래그 중 선택 테두리를 라이브 좌표로 동기화. */\n private updateSelectionBordersLive(getPoints: (shape: EditorShape) => Point[]) {\n const selectedSet = new Set(this.selected);\n let i = 0;\n for (const shape of this.shapes) {\n if (!selectedSet.has(shape.id)) continue;\n if (!isShapeSelectable(shape)) continue;\n const points = this.selectionOutlinePoints(shape, getPoints(shape));\n const rect = this.selectionBorders[i++];\n if (rect) {\n rect.points(points.flatMap((p) => [p.x, p.y]));\n }\n }\n }\n\n private selectionOutlinePoints(shape: EditorShape, points: Point[]) {\n return outlinePointsFor(shape, points, this.pointRadius(shape));\n }\n\n // ── 미리보기 ──\n /** 그리는 중 폴리곤 초안 마지막 파라미터 — 줌 시 정점 원 크기 재계산용\n * (선은 strokeScaleEnabled=false로 화면 고정이라 재도색 불필요). */\n private lastPreviewPoly: {\n points: Point[];\n cursor: Point | null;\n style: ShapeStyle;\n closed: boolean;\n selectedPointIndices: number[];\n showVertices: boolean;\n } | null = null;\n clearPreview() {\n this.lastPreviewPoly = null;\n this.previewGroup.destroyChildren();\n this.layer.batchDraw();\n }\n clearMarquee() {\n this.marquee?.destroy();\n this.marquee = null;\n this.layer.batchDraw();\n }\n private preview: Konva.Shape | null = null;\n private marquee: Konva.Rect | null = null;\n\n previewBox(kind: PreviewKind, a: Point, b: Point, style: ShapeStyle) {\n this.lastPreviewPoly = null;\n this.previewGroup.destroyChildren();\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n const w = Math.abs(b.x - a.x);\n const h = Math.abs(b.y - a.y);\n const makePreview = (stroke: string, dash?: number[]) =>\n kind === \"ellipse\"\n ? new Konva.Ellipse({\n x: x + w / 2,\n y: y + h / 2,\n radiusX: w / 2,\n radiusY: h / 2,\n stroke,\n strokeWidth: style.strokeWidth ?? this.strokeSize,\n dash: this.scaledDash(dash),\n strokeScaleEnabled: false,\n })\n : new Konva.Rect({\n x,\n y,\n width: w,\n height: h,\n stroke,\n strokeWidth: style.strokeWidth ?? this.strokeSize,\n dash: this.scaledDash(dash),\n strokeScaleEnabled: false,\n });\n if (style.alternateColor) {\n this.previewGroup.add(makePreview(style.alternateColor));\n }\n this.preview = makePreview(style.color ?? \"#00e5ff\", style.dash);\n this.previewGroup.add(this.preview);\n this.layer.batchDraw();\n }\n\n previewPoly(\n points: Point[],\n cursor: Point | null,\n style: ShapeStyle,\n closed: boolean,\n selectedPointIndices: number[] = [],\n showVertices = true,\n ) {\n this.lastPreviewPoly = {\n points,\n cursor,\n style,\n closed,\n selectedPointIndices,\n showVertices,\n };\n this.previewGroup.destroyChildren();\n if (!points.length) return;\n const flat = points.flatMap((p) => [p.x, p.y]);\n if (cursor) flat.push(cursor.x, cursor.y);\n const makePreview = (stroke: string, dash?: number[]) =>\n new Konva.Line({\n points: flat,\n closed,\n stroke,\n strokeWidth: style.strokeWidth ?? this.strokeSize,\n dash: this.scaledDash(dash),\n strokeScaleEnabled: false,\n lineCap: \"round\",\n lineJoin: \"round\",\n });\n if (style.alternateColor) {\n this.previewGroup.add(makePreview(style.alternateColor));\n }\n this.previewGroup.add(makePreview(style.color ?? \"#00e5ff\", style.dash));\n // PATH(자유선)처럼 점을 안 찍는 도구는 정점 점을 숨기고 선만 보여준다.\n if (!showVertices) {\n this.layer.batchDraw();\n return;\n }\n const selected = new Set(selectedPointIndices);\n const scale = this.world.scaleX() || 1;\n for (let i = 0; i < points.length; i++) {\n const point = points[i];\n const isSelected = selected.has(i);\n this.previewGroup.add(\n new Konva.Circle({\n x: point.x,\n y: point.y,\n radius: (isSelected ? 6 : 5) / scale,\n fill: isSelected ? HANDLE_HEX : \"#ffffff\",\n stroke: isSelected ? \"#ffffff\" : HANDLE_HEX,\n strokeWidth: 1.5,\n strokeScaleEnabled: false,\n listening: false,\n }),\n );\n }\n this.layer.batchDraw();\n }\n\n previewScalarMask(raster: ScalarMaskRaster, color: string) {\n this.previewGroup.destroyChildren();\n const tint = color.length === 7 ? `${color}99` : color;\n const previewCanvas = buildScalarMaskPreviewCanvas(raster, tint);\n this.previewGroup.add(\n new Konva.Image({\n image: previewCanvas,\n x: raster.ox,\n y: raster.oy,\n scaleX: 1 / raster.scale,\n scaleY: 1 / raster.scale,\n listening: false,\n }),\n );\n this.layer.batchDraw();\n }\n\n previewMarquee(a: Point, b: Point) {\n if (!this.marquee) {\n this.marquee = new Konva.Rect({\n fill: colorWithAlpha(SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA),\n stroke: SELECTION_AREA_COLOR,\n strokeWidth: 1,\n strokeScaleEnabled: false,\n listening: false,\n perfectDrawEnabled: false,\n });\n this.previewGroup.add(this.marquee);\n }\n this.marquee.setAttrs({\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n });\n this.layer.batchDraw();\n }\n\n // ── 트랜스포머 ──\n setTransformEnabled(enabled: boolean) {\n this.transformEnabled = enabled;\n // 드래그 도중 비활성화(검수 완료 단축키 등으로 readOnly 전환) — 진행 중인\n // 드래그를 커밋 없이 취소한다. 안 하면 드래그가 끝날 때까지 핸들이 남고,\n // 마우스를 놓는 순간 잠근 뒤의 이동이 커밋된다.\n if (!enabled) this.cancelTransform();\n this.drawTransformer();\n this.layer.batchDraw();\n }\n\n // 팬 모드: 핸들 그룹 전체의 이벤트 수신만 끈다(핸들은 계속 보이되 클릭은 통과).\n // 그룹 속성이라 이후 drawTransformer 재생성에도 유지되고, 히트 그래프는 재도색해 반영.\n setPanMode(active: boolean) {\n this.handleGroup.listening(!active);\n this.layer.batchDraw();\n }\n\n private setTransformerOutline(box: BBox) {\n const w = Math.max(0, box.maxX - box.minX);\n const h = Math.max(0, box.maxY - box.minY);\n if (!w && !h) return;\n this.setTransformerOutlinePoints(\n rectTo4([\n { x: box.minX, y: box.minY },\n { x: box.maxX, y: box.maxY },\n ]),\n );\n }\n\n private setTransformerOutlinePoints(points: Point[]) {\n if (points.length < 2) return;\n if (!this.transformerOutline) {\n this.transformerOutline = new Konva.Line({\n closed: true,\n stroke: HANDLE_HEX,\n strokeWidth: 1,\n strokeScaleEnabled: false,\n listening: false,\n });\n this.selGroup.add(this.transformerOutline);\n }\n this.transformerOutline.points(points.flatMap((p) => [p.x, p.y]));\n }\n\n private rotationHandleGap() {\n return rotationHandleGapFor(this.viewport.scale);\n }\n\n private rotationHandleScreenPoint(points: Point[]) {\n return this.imgToScreen(rotateHandlePos(points, this.rotationHandleGap()));\n }\n\n private setRotationConnector(points: Point[]) {\n const from = this.imgToScreen(mid(points[0], points[1]));\n const to = this.rotationHandleScreenPoint(points);\n if (!this.rotLineNode) {\n this.rotLineNode = new Konva.Line({\n points: [from.x, from.y, to.x, to.y],\n stroke: HANDLE_HEX,\n strokeWidth: 1,\n listening: false,\n });\n this.handleGroup.add(this.rotLineNode);\n } else {\n this.rotLineNode.points([from.x, from.y, to.x, to.y]);\n }\n }\n\n private layoutResizeHandle(node: Konva.Rect, sp: Point, angleRad: number) {\n node.position({ x: sp.x, y: sp.y });\n node.offset({ x: 4, y: 4 });\n node.rotation((angleRad * 180) / Math.PI);\n }\n\n private orientedHandleAngle(points: Point[]): number {\n return orientedAngleFromScreenPoints(this.imgToScreen(points[0]), this.imgToScreen(points[1]));\n }\n\n private repositionOrientedHandles(points: Point[]) {\n const angleRad = this.orientedHandleAngle(points);\n orientedHandles(points).forEach((point, i) => {\n const sp = this.imgToScreen(point);\n const node = this.handleNodes[i];\n if (node) this.layoutResizeHandle(node, sp, angleRad);\n });\n this.setTransformerOutlinePoints(points);\n if (this.rotNode) {\n const sp = this.rotationHandleScreenPoint(points);\n this.rotNode.position({ x: sp.x, y: sp.y });\n }\n if (this.rotLineNode) this.setRotationConnector(points);\n }\n\n drawTransformer() {\n if (this.activeDrag) return;\n for (const h of this.handleNodes) h.destroy();\n for (const v of this.vertexNodes) v.destroy();\n for (const m of this.midNodes) m.destroy();\n this.ghostNode?.destroy();\n this.ghostNode = null;\n this.rotNode?.destroy();\n this.rotNode = null;\n this.rotLineNode?.destroy();\n this.rotLineNode = null;\n this.transformerOutline?.destroy();\n this.transformerOutline = null;\n this.handleNodes = [];\n this.vertexNodes = [];\n this.midNodes = [];\n if (!this.transformEnabled) return;\n const sel = selectEditable(this.shapes, this.selected);\n if (!sel.length) return;\n if (sel.length === 1 && sel[0].type === SHAPE_TYPE.POINT) return;\n\n const editingPoly =\n sel.length === 1 &&\n (sel[0].type === SHAPE_TYPE.POLYGON || sel[0].type === SHAPE_TYPE.LINE) &&\n this.editingId === sel[0].id\n ? sel[0]\n : null;\n\n const box = getBBox(sel.flatMap((s) => s.points));\n const rotatedRect =\n sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE ? sel[0] : null;\n const transformerHandles = rotatedRect\n ? orientedHandles(rotatedRect.points)\n : ANCHORS.map((a) => anchorPoint(a, box));\n rotatedRect\n ? this.setTransformerOutlinePoints(rotatedRect.points)\n : this.setTransformerOutline(box);\n if (rotatedRect) this.setRotationConnector(rotatedRect.points);\n const handleAngleRad = rotatedRect ? this.orientedHandleAngle(rotatedRect.points) : 0;\n // 편집모드(정점 편집) 중엔 bbox 리사이즈 핸들을 숨긴다.\n for (const a of editingPoly ? [] : ANCHORS) {\n const sp = this.imgToScreen(transformerHandles[ANCHORS.indexOf(a)]);\n const g = new Konva.Rect({\n x: sp.x,\n y: sp.y,\n width: 8,\n height: 8,\n offsetX: 4,\n offsetY: 4,\n rotation: (handleAngleRad * 180) / Math.PI,\n fill: \"#ffffff\",\n stroke: HANDLE_HEX,\n strokeWidth: 1,\n });\n const cursor = resizeCursorForAnchor(a, handleAngleRad);\n this.bindCursor(g, cursor);\n g.on(\"mousedown\", (e) => {\n e.cancelBubble = true;\n this.emitCursorHint(cursor);\n this.emitInteractionMode(\"resizing\");\n const cur = selectEditable(this.shapes, this.selected);\n this.activeDrag = {\n kind: \"resize\",\n anchor: a,\n box: getBBox(cur.flatMap((s) => s.points)),\n shapes: cur.map((s) => ({ id: s.id, points: s.points })),\n };\n this.lastDragImg = null;\n });\n this.handleGroup.add(g);\n this.handleNodes.push(g);\n }\n if (editingPoly) {\n const shape = editingPoly;\n const pts = shape.points;\n const isPoly = shape.type === SHAPE_TYPE.POLYGON;\n const edges = isPoly ? pts.length : pts.length - 1;\n const vertexR = this.vertexHandleRadius();\n // 정점 추가 고스트 — 변 호버 시에만, 커서의 변 위 최근접 지점에 표시.\n const ghost = new Konva.Circle({\n radius: vertexR * 0.8,\n fill: \"#ffffff\",\n opacity: 0.6,\n stroke: HANDLE_HEX,\n strokeWidth: 1,\n visible: false,\n listening: false,\n });\n this.handleGroup.add(ghost);\n this.ghostNode = ghost;\n for (let i = 0; i < edges; i++) {\n const a = pts[i];\n const b = pts[(i + 1) % pts.length];\n const sa = this.imgToScreen(a);\n const sb = this.imgToScreen(b);\n // 보이지 않는 넓은 히트 라인 — 변 근처 호버/클릭을 받는다.\n const g = new Konva.Line({\n points: [sa.x, sa.y, sb.x, sb.y],\n stroke: \"#ffffff\",\n strokeWidth: 1,\n opacity: 0,\n hitStrokeWidth: Math.max(14, vertexR * 2 + 4),\n });\n this.bindCursor(g, \"copy\");\n // 커서의 변 위 최근접 지점(이미지 좌표) — 자유 위치 정점 삽입 지점.\n const closestOnEdge = (): Point => {\n const p = this.toImage();\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len2 = dx * dx + dy * dy;\n const t = len2\n ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))\n : 0;\n return { x: a.x + t * dx, y: a.y + t * dy };\n };\n g.on(\"mousemove\", () => {\n if (this.activeDrag) return;\n const sp = this.imgToScreen(closestOnEdge());\n ghost.position({ x: sp.x, y: sp.y });\n ghost.visible(true);\n this.layer.batchDraw();\n });\n g.on(\"mouseleave\", () => {\n ghost.visible(false);\n this.layer.batchDraw();\n });\n g.on(\"mousedown\", (e) => {\n e.cancelBubble = true;\n const q = closestOnEdge();\n const idx = i + 1;\n const next = [...pts.slice(0, idx), q, ...pts.slice(idx)];\n // 로컬 도형·핸들을 먼저 갱신해 새 정점 노드를 만든 뒤 그 정점 드래그를\n // 즉시 시작한다(마우스다운 = 정점 생성 + 이동 개시).\n const target = this.shapes.find((s) => s.id === shape.id);\n if (target) target.points = next;\n this.liveUpdateShape(shape.id, next);\n this.selectedVertices = new Set([idx]);\n this.drawTransformer();\n this.cb.onTransformCommit?.([{ id: shape.id, points: next }]);\n this.activeDrag = {\n kind: \"vertex\",\n id: shape.id,\n indices: [idx],\n base: next,\n start: q,\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"vertexDragging\");\n });\n this.handleGroup.add(g);\n this.midNodes.push(g);\n }\n // 편집 대상 폴리곤이 바뀌면 정점 다중선택 초기화.\n if (this.vertexPolygonId !== shape.id) {\n this.vertexPolygonId = shape.id;\n this.selectedVertices.clear();\n }\n pts.forEach((pt, i) => {\n const sp = this.imgToScreen(pt);\n const isSel = this.selectedVertices.has(i);\n const g = new Konva.Circle({\n x: sp.x,\n y: sp.y,\n radius: vertexR,\n fill: isSel ? HANDLE_HEX : \"#ffffff\",\n stroke: isSel ? \"#ffffff\" : HANDLE_HEX,\n strokeWidth: Math.max(1.5, vertexR * 0.3),\n });\n this.bindCursor(g, \"pointer\");\n g.on(\"mousedown\", (e) => {\n e.cancelBubble = true;\n // Shift/Ctrl/Cmd: 정점 다중선택 토글(드래그 안 함).\n if (e.evt.shiftKey || e.evt.ctrlKey || e.evt.metaKey) {\n if (this.selectedVertices.has(i)) this.selectedVertices.delete(i);\n else this.selectedVertices.add(i);\n this.drawTransformer();\n return;\n }\n // 선택된 정점 위를 그냥 클릭하면 선택 세트 전체를 함께 이동, 아니면 그 정점만.\n const indices =\n this.selectedVertices.has(i) && this.selectedVertices.size > 1\n ? [...this.selectedVertices]\n : [i];\n if (indices.length === 1) {\n this.selectedVertices.clear();\n this.selectedVertices.add(i);\n }\n this.activeDrag = {\n kind: \"vertex\",\n id: shape.id,\n indices,\n base: pts,\n start: this.toImage(),\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"vertexDragging\");\n });\n this.handleGroup.add(g);\n this.vertexNodes.push(g);\n });\n }\n\n if (sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n const shape = sel[0];\n const center = centerOf(shape.points);\n const sp = this.rotationHandleScreenPoint(shape.points);\n const g = new Konva.Circle({\n x: sp.x,\n y: sp.y,\n radius: 6,\n fill: \"#ffffff\",\n stroke: HANDLE_HEX,\n strokeWidth: 1.5,\n });\n this.bindCursor(g, \"grab\");\n g.on(\"mousedown\", (e) => {\n e.cancelBubble = true;\n const ip = this.toImage();\n this.activeDrag = {\n kind: \"rotate\",\n id: shape.id,\n center,\n startAngle: Math.atan2(ip.y - center.y, ip.x - center.x),\n points: shape.points,\n shiftKey: e.evt.shiftKey,\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"rotating\");\n });\n this.handleGroup.add(g);\n this.rotNode = g;\n }\n this.layer.batchDraw();\n }\n\n beginMove(start: Point, ids: string[]) {\n const drag = makeMoveDrag(this.shapes, ids, start);\n if (!drag) return;\n if (this.transformEnabled && !this.handleNodes.length) this.drawTransformer();\n this.activeDrag = drag;\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"moving\");\n const selectedShape =\n drag.shapes.length === 1 ? this.shapes.find((s) => s.id === drag.shapes[0].id) : null;\n if (selectedShape?.type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n this.setTransformerOutlinePoints(drag.shapes[0].points);\n } else {\n this.setTransformerOutline(drag.box);\n }\n this.updateSelectionBordersLive((shape) => shape.points);\n }\n\n private repositionHandles(box: BBox) {\n ANCHORS.forEach((a, i) => {\n const sp = this.imgToScreen(anchorPoint(a, box));\n const node = this.handleNodes[i];\n if (node) this.layoutResizeHandle(node, sp, 0);\n });\n this.setTransformerOutline(box);\n }\n\n /** 폴리곤/라인 꼭짓점·변 중점 핸들을 이미지 좌표 기준으로 재배치. */\n private repositionPolygonHandles(pts: Point[], isPolygon: boolean) {\n if (!this.vertexNodes.length) return;\n pts.forEach((pt, i) => {\n const sp = this.imgToScreen(pt);\n this.vertexNodes[i]?.position({ x: sp.x, y: sp.y });\n });\n const edges = isPolygon ? pts.length : pts.length - 1;\n for (let i = 0; i < edges; i++) {\n const sa = this.imgToScreen(pts[i]);\n const sb = this.imgToScreen(pts[(i + 1) % pts.length]);\n this.midNodes[i]?.points([sa.x, sa.y, sb.x, sb.y]);\n }\n }\n\n private commitTransformUpdates(updates: { id: string; points: Point[] }[]) {\n if (!updates.length) return;\n for (const update of updates) {\n const shape = this.shapes.find((s) => s.id === update.id);\n if (!shape) continue;\n shape.points = update.points;\n this.liveUpdateShape(update.id, update.points);\n }\n this.cb.onTransformCommit?.(updates);\n this.drawTransformer();\n this.layer.batchDraw();\n }\n\n // lastDragImg 기록은 mousemove 콜러 소유 — 뷰포트 변경(줌/팬) 중 재호출해도\n // endTransform의 \"이동 없음 → 커밋 생략\" 판정이 유지된다.\n private dragTransform(img: Point) {\n const d = this.activeDrag;\n if (!d) return;\n this.applyCursor();\n const isRotatedRect = dragTargetIsRotatedRect(this.shapes, d);\n const { updates, box } = computeDragUpdates(d, img, isRotatedRect);\n for (const u of updates) this.liveUpdateShape(u.id, u.points);\n this.cb.onTransformPreview?.(updates);\n this.updateSelectionBordersLive(\n (shape) => updates.find((item) => item.id === shape.id)?.points ?? shape.points,\n );\n if (d.kind === \"resize\" || d.kind === \"move\") {\n if (isRotatedRect) this.repositionOrientedHandles(updates[0].points);\n else if (box) this.repositionHandles(box);\n const single =\n d.shapes.length === 1 ? this.shapes.find((s) => s.id === d.shapes[0].id) : null;\n const isPolyLike = single?.type === SHAPE_TYPE.POLYGON || single?.type === SHAPE_TYPE.LINE;\n const showPolyHandles =\n d.kind === \"resize\" ? isPolyLike : this.vertexNodes.length > 0 && d.shapes.length === 1;\n if (showPolyHandles) {\n this.repositionPolygonHandles(updates[0].points, single?.type === SHAPE_TYPE.POLYGON);\n }\n } else if (d.kind === \"rotate\") {\n this.repositionOrientedHandles(updates[0].points);\n const shape = this.shapes.find((s) => s.id === d.id);\n if (shape && (shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE)) {\n this.repositionPolygonHandles(updates[0].points, shape.type === SHAPE_TYPE.POLYGON);\n }\n } else {\n if (box) this.repositionHandles(box);\n const shape = this.shapes.find((s) => s.id === d.id);\n this.repositionPolygonHandles(updates[0].points, shape?.type === SHAPE_TYPE.POLYGON);\n }\n this.layer.batchDraw();\n }\n\n /** 진행 중인 드래그를 커밋 없이 취소 — 프리뷰가 옮긴 노드를 확정 좌표로 되돌린다. */\n private cancelTransform() {\n if (!this.activeDrag) return;\n this.activeDrag = null;\n this.lastDragImg = null;\n // 확정 좌표는 this.shapes에 그대로 있다(커밋은 드래그 끝에만 일어난다).\n for (const shape of this.shapes) this.liveUpdateShape(shape.id, shape.points);\n // 빈 프리뷰([])가 아니라 확정 좌표를 되쏜다 — 크기 배지·미니맵 오버레이는\n // 프리뷰 경로로 DOM을 직접 옮기므로, 원위치도 같은 경로로 되돌려야 한다.\n this.cb.onTransformPreview?.(\n this.shapes.map((shape) => ({ id: shape.id, points: shape.points })),\n );\n this.emitInteractionMode(\"idle\");\n this.emitCursorHint(null);\n this.drawSelectionBorders();\n }\n\n private endTransform() {\n const d = this.activeDrag;\n const img = this.lastDragImg;\n this.activeDrag = null;\n this.emitInteractionMode(\"idle\");\n this.emitCursorHint(d?.kind === \"move\" ? \"grab\" : null);\n if (!d || !img) {\n this.cb.onTransformPreview?.([]);\n this.drawTransformer();\n return;\n }\n if (d.kind === \"move\" && img.x === d.start.x && img.y === d.start.y) {\n this.cb.onTransformPreview?.([]);\n this.drawTransformer();\n return;\n }\n const { updates } = computeDragUpdates(d, img, dragTargetIsRotatedRect(this.shapes, d));\n this.commitTransformUpdates(updates);\n }\n}\n","// pixi는 유니폼 동기화 코드를 new Function으로 생성해 strict CSP(script-src에\n// 'unsafe-eval' 없음)에서 초기화가 죽는다. 공식 우회 모듈로 eval 의존을 제거한다.\nimport \"pixi.js/unsafe-eval\";\nimport {\n Application,\n ColorMatrixFilter,\n Container,\n type FederatedPointerEvent,\n Graphics,\n Polygon,\n Rectangle,\n Sprite,\n Texture,\n} from \"pixi.js\";\nimport { SELECTION_AREA_COLOR, SELECTION_AREA_FILL_ALPHA } from \"../_constants\";\nimport { resizeCursorForAnchor, UNSELECTED_HOVER_HINT } from \"../_model/cursors\";\nimport {\n ANCHORS,\n anchorPoint,\n type BBox,\n centerOf,\n computePolygonFillGroups,\n type EditorShape,\n getBBox,\n isShapeDraggable,\n isShapeSelectable,\n isShapeVisible,\n mid,\n orientedHandles,\n type Point,\n rectTo4,\n rotateHandlePos,\n SHAPE_TYPE,\n type ShapeStyle,\n sortShapesForRender,\n} from \"../_model/geometry\";\nimport { loadCorsImage } from \"../_model/imageLoad\";\nimport { createImageTileCanvas, getImageTiles, IMAGE_TILE_SIZE } from \"../_model/imageTiles\";\nimport {\n type RegionOverlayData,\n type ResolvedRegionOutlineStyle,\n resolveCompletedDimStyle,\n} from \"../_model/overlays\";\nimport { PIN_HEIGHT, PIN_WIDTH, pinSvg } from \"../_model/pinIcon\";\nimport { buildScalarMaskPreviewCanvas, type ScalarMaskRaster } from \"../_model/scalarMask\";\nimport { resolveShapeRenderStyle, type ShapeRenderStyleDefaults } from \"../_model/shapeRenderStyle\";\nimport {\n type ActiveDrag,\n cloneShapes,\n computeDragUpdates,\n dragIdentityImage,\n dragTargetIsRotatedRect,\n intersectingShapeIds,\n makeMoveDrag,\n orientedAngleFromScreenPoints,\n outlinePointsFor,\n pointRadiusFor,\n rotationHandleGapFor,\n selectEditable,\n} from \"./transformSession\";\nimport type { EditorRendererCallbacks, Viewport } from \"./types\";\n\nexport type { Viewport };\n\nconst STROKE = 2;\nconst _POINT_RADIUS = 5;\nconst DEFAULT_COLOR = 0x00e5ff;\nconst SELECTION_BORDER = 0x669def;\n\nfunction hexToNum(hex?: string): number {\n if (!hex) return DEFAULT_COLOR;\n const h = hex.replace(\"#\", \"\");\n return Number.parseInt(h.length === 3 ? h.replace(/./g, \"$&$&\") : h, 16);\n}\n\n/**\n * Pixi renderer backend(WebGL). React 비의존.\n * 좌표계: world 컨테이너가 이미지 좌표를 담고, scale/position으로 줌/팬.\n */\nexport class PixiRenderer {\n app = new Application();\n world = new Container();\n bgLayer = new Container(); // 이미지 + 색보정\n overlayLayer = new Container(); // 이미지↔도형 사이 오버레이 묶음\n private regionOverlayLayer = new Container();\n private dimOverlayLayer = new Container();\n shapeLayer = new Container();\n selLayer = new Container(); // 선택 테두리\n previewLayer = new Container(); // 그리기 미리보기\n handleLayer = new Container(); // 트랜스포머/핸들(화면고정)\n\n filter = new ColorMatrixFilter();\n imageWidth = 0;\n imageHeight = 0;\n private imageTileTextures: Texture[] = [];\n // 연속 setImage 레이스 가드 — 마지막 요청만 타일을 교체한다.\n private imageLoadToken = 0;\n // GPU 한계(maxTextureSize)에 맞춘 실제 타일 크기 — init에서 확정.\n private tileSize = IMAGE_TILE_SIZE;\n // 영역 윤곽 점선 — 줌 시 화면고정 두께로 재도색해야 해서 벡터 데이터를 보관.\n private region: RegionOverlayData | null = null;\n private regionDimMaskG = new Graphics();\n private regionDimG = new Graphics();\n private regionZoneMaskG = new Graphics();\n private regionZoneG = new Graphics();\n private regionOutlineG = new Graphics();\n\n private cb: EditorRendererCallbacks;\n private host: HTMLElement;\n private baseCursor = \"default\";\n private strokeSize = STROKE;\n private shapes: EditorShape[] = [];\n private selected: string[] = [];\n private nodes = new Map<string, Graphics>();\n // 마지막으로 적용한 뷰포트 스케일. 판(스케일 불변) 시 재도색을 건너뛰기 위한 비교용.\n private lastAppliedScale = -1;\n private brightness = 1;\n private contrast = 1;\n private imageSmoothing = true;\n private destroyed = false;\n private transformEnabled = false;\n private handleNodes: Graphics[] = [];\n private vertexNodes: Graphics[] = [];\n private lastDragImg: Point | null = null;\n private activeDrag: ActiveDrag | null = null;\n // 편집모드 변(edge) 호버용 히트 노드 — 그리지 않고 hitArea 쿼드로 히트만 받는다.\n private midNodes: Graphics[] = [];\n // 변 호버 시 커서의 변 위 최근접 지점에 표시되는 정점 추가 고스트.\n private ghostNode: Graphics | null = null;\n // 다중 선택된 정점 인덱스(현재 편집 폴리곤 기준). 함께 이동.\n private selectedVertices = new Set<number>();\n private vertexPolygonId: string | null = null;\n // 폴리곤 정점 편집모드 대상 id. 이 값이 선택된 단일 폴리곤과 같을 때만 정점/변중점\n // 핸들을 보여준다(단순 선택으로는 정점을 안 보이게 — 옵스식 편집모드).\n private editingId: string | null = null;\n private rotNode: Graphics | null = null;\n private rotLineNode: Graphics | null = null;\n private transformerOutline: Graphics | null = null;\n private selectionBorderGfx: Graphics[] = [];\n\n constructor(host: HTMLElement, cb: EditorRendererCallbacks) {\n this.host = host;\n this.cb = cb;\n }\n\n /** Pixi 이벤트 → 렌더러 추상화 이벤트. */\n private ev(e: FederatedPointerEvent) {\n return {\n pointerId: e.pointerId,\n button: e.button,\n shiftKey: e.shiftKey,\n altKey: e.altKey,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n global: { x: e.global.x, y: e.global.y },\n };\n }\n\n async init() {\n await this.app.init({\n resizeTo: this.host,\n background: \"#111111\",\n antialias: true,\n autoDensity: true,\n resolution: window.devicePixelRatio || 1,\n preference: \"webgl\",\n });\n if (this.destroyed) {\n this.app.destroy(true);\n return;\n }\n this.host.appendChild(this.app.canvas);\n // GPU 텍스처 한계에 타일 크기를 맞춘다 — 구형 GPU/VM(max 2048 등)에서 4000px\n // 타일 업로드가 조용히 실패해 회색 캔버스만 남는 것을 원천 차단.\n const gl = (this.app.renderer as unknown as { gl?: WebGLRenderingContext }).gl;\n const maxTextureSize = gl?.getParameter(gl.MAX_TEXTURE_SIZE);\n if (typeof maxTextureSize === \"number\" && maxTextureSize > 1) {\n // 타일은 이음새 방지로 +1px 겹치므로 한계에서 1을 뺀다.\n this.tileSize = Math.min(IMAGE_TILE_SIZE, maxTextureSize - 1);\n }\n this.applyCursor();\n\n this.overlayLayer.addChild(this.regionOverlayLayer, this.dimOverlayLayer);\n this.regionOverlayLayer.addChild(\n this.regionDimMaskG,\n this.regionDimG,\n this.regionZoneMaskG,\n this.regionZoneG,\n this.regionOutlineG,\n );\n this.regionDimG.setMask({ mask: this.regionDimMaskG, inverse: true });\n this.regionZoneG.setMask({ mask: this.regionZoneMaskG });\n this.world.addChild(\n this.bgLayer,\n this.overlayLayer,\n this.shapeLayer,\n this.selLayer,\n this.previewLayer,\n );\n this.app.stage.addChild(this.world, this.handleLayer);\n // 뷰포트(fit)가 정해지기 전엔 콘텐츠를 숨긴다. 안 그러면 이미지가 fit 전 기본\n // 뷰포트로 한 프레임 그려졌다가 fit되면서 위치/크기가 튀어 보인다. 첫 applyViewport\n // (fit 포함)에서 노출한다.\n this.world.visible = false;\n\n // 스테이지 전체 포인터 입력(팬/마퀴/그리기용).\n this.app.stage.eventMode = \"static\";\n this.syncHitArea();\n this.app.stage.on(\"pointerdown\", (e) => {\n // 도형이 먼저 처리(stopPropagation)하지 않은 경우만 = 빈 공간.\n this.cb.onPointerDown(this.toImage(e), null, this.ev(e));\n });\n this.app.stage.on(\"pointermove\", (e) => {\n if (this.activeDrag) {\n this.lastDragImg = this.toImage(e);\n this.dragTransform(this.lastDragImg);\n return;\n }\n this.cb.onPointerMove(this.toImage(e), this.ev(e));\n });\n const up = (e: FederatedPointerEvent, insideCanvas: boolean) => {\n if (this.activeDrag) {\n this.endTransform();\n return;\n }\n this.cb.onPointerUp(this.toImage(e), {\n pointerId: e.pointerId,\n global: { x: e.global.x, y: e.global.y },\n shiftKey: e.shiftKey,\n insideCanvas,\n });\n };\n this.app.stage.on(\"pointerup\", (e) => up(e, true));\n this.app.stage.on(\"pointerupoutside\", (e) => up(e, false));\n\n this.app.renderer.on(\"resize\", () => this.syncHitArea());\n }\n\n private syncHitArea() {\n // screenSize(CSS px)와 동일 기준을 써야 한다. 예전엔 renderer.width를 resolution으로\n // 다시 나눠 retina에서 hitArea가 절반이 됐고, 마퀴/빈공간 클릭이 좌상단에서만 됐다.\n const { w, h } = this.screenSize;\n this.app.stage.hitArea = new Rectangle(0, 0, w, h);\n }\n\n destroy() {\n this.destroyed = true;\n this.clearImageTiles();\n if (this.app.renderer) this.app.destroy(true, { children: true });\n }\n\n get screenSize() {\n // renderer.screen은 CSS 픽셀 기준 화면 크기다. renderer.width/height도 v8에서 CSS\n // 픽셀이라 resolution으로 다시 나누면 retina(dpr>1)에서 절반이 되는 버그가 있었다.\n return {\n w: this.app.renderer.screen.width,\n h: this.app.renderer.screen.height,\n };\n }\n\n setCursor(cursor: string) {\n this.baseCursor = cursor;\n this.syncShapeCursors();\n this.applyCursor();\n }\n\n private emitCursorHint(cursor: string | null) {\n this.cb.onCursorHint?.(cursor);\n }\n\n private emitInteractionMode(\n mode: \"idle\" | \"moving\" | \"resizing\" | \"rotating\" | \"vertexDragging\",\n ) {\n this.cb.onInteractionModeChange?.(mode);\n }\n\n private applyCursor() {\n if (this.destroyed || !this.app.renderer) return;\n const canvas = this.app.canvas;\n if (!canvas) return;\n canvas.style.cursor = this.baseCursor;\n }\n\n private syncShapeCursors() {\n for (const node of this.nodes.values()) {\n node.cursor = undefined;\n }\n }\n\n private bindCursor(node: Graphics, cursor: string) {\n node.cursor = undefined;\n node.on(\"pointerover\", () => {\n if (this.activeDrag) return;\n this.emitCursorHint(cursor);\n });\n node.on(\"pointerout\", () => {\n if (!this.activeDrag) this.emitCursorHint(null);\n });\n }\n\n /** 휠/컨텍스트메뉴 리스너 부착용 DOM 요소(렌더러 추상화). */\n get dom(): HTMLElement {\n return this.app.canvas;\n }\n\n /** 화면 좌표(global) → 이미지 좌표(world local). */\n toImage(e: FederatedPointerEvent): Point {\n const p = this.world.toLocal(e.global);\n return { x: p.x, y: p.y };\n }\n\n async setImage(\n url: string,\n coordinateSize?: { width: number; height: number },\n imageSize?: { width: number; height: number },\n ) {\n const loadToken = ++this.imageLoadToken;\n // WebGL 텍스처는 CORS-clean 이미지만 허용한다. <img crossOrigin> 직행이 기본,\n // 오염 캐시일 때만 reload fetch로 수리 후 재시도한다(imageLoad.ts 참고).\n const img = await loadCorsImage(url);\n\n if (this.destroyed || loadToken !== this.imageLoadToken) return true; // 더 최신 요청 있음.\n if (!img) {\n this.imageWidth ||= coordinateSize?.width ?? 800;\n this.imageHeight ||= coordinateSize?.height ?? 600;\n return false;\n }\n // 좌표계 고정: coordinateSize가 있으면 도형 좌표계는 그 크기, 이미지는\n // 배경 레이어 스케일로 늘려 맞춘다(썸네일 표시 + 원본 좌표 편집,\n // 화질 스왑 간 픽셀 크기가 달라도 좌표계 불변).\n this.imageWidth = coordinateSize?.width ?? img.naturalWidth;\n this.imageHeight = coordinateSize?.height ?? img.naturalHeight;\n // 이미지가 좌표공간의 일부만 덮으면(imageSize) 그 크기로(원점 기준),\n // 아니면 좌표공간 전체로 늘려 그린다.\n const drawWidth = imageSize?.width ?? this.imageWidth;\n const drawHeight = imageSize?.height ?? this.imageHeight;\n this.bgLayer.scale.set(drawWidth / img.naturalWidth, drawHeight / img.naturalHeight);\n this.clearImageTiles();\n for (const tile of getImageTiles(img.naturalWidth, img.naturalHeight, this.tileSize)) {\n const texture = Texture.from(createImageTileCanvas(img, tile));\n texture.source.scaleMode = this.imageSmoothing ? \"linear\" : \"nearest\";\n this.imageTileTextures.push(texture);\n const sprite = new Sprite(texture);\n sprite.x = tile.x;\n sprite.y = tile.y;\n sprite.width = tile.width;\n sprite.height = tile.height;\n this.bgLayer.addChild(sprite);\n }\n this.applySpriteFilter();\n return true;\n }\n\n setFilter(brightness: number, contrast: number) {\n this.brightness = brightness;\n this.contrast = contrast;\n this.applySpriteFilter();\n }\n\n setRenderDefaults(defaults: Partial<ShapeRenderStyleDefaults>) {\n const strokeSize = defaults.strokeWidth ?? this.strokeSize;\n if (this.strokeSize === strokeSize) return;\n this.strokeSize = strokeSize;\n this.setShapes(this.shapes, this.selected);\n }\n\n /** 편집모드 정점 핸들 반지름 — 선두께에 비례(기본 두께 2에서 기존 크기 5 유지). */\n private vertexHandleRadius(): number {\n return Math.max(4, this.strokeSize * 2.5);\n }\n\n private applySpriteFilter() {\n if (this.destroyed || !this.app.renderer) return;\n const hasFilter = this.brightness !== 1 || this.contrast !== 1;\n if (!hasFilter) {\n this.filter.reset();\n this.bgLayer.filters = undefined;\n return;\n }\n\n this.filter.brightness(this.brightness, false);\n // Pixi contrast uses 0 as identity, while Editor view settings use the\n // CSS convention where 1 is identity.\n this.filter.contrast(this.contrast - 1, true);\n this.bgLayer.filters = [this.filter];\n }\n\n clearImage() {\n if (this.destroyed) return;\n // 이후 도착하는 이전 setImage 응답이 타일을 되살리지 않게 토큰도 올린다.\n this.imageLoadToken++;\n this.clearImageTiles();\n }\n\n private clearImageTiles() {\n for (const child of this.bgLayer.removeChildren()) {\n child.destroy();\n }\n for (const texture of this.imageTileTextures) {\n texture.destroy(true);\n }\n this.imageTileTextures = [];\n }\n\n setImageSmoothing(smooth: boolean) {\n if (this.imageSmoothing === smooth) return;\n this.imageSmoothing = smooth;\n const mode = smooth ? \"linear\" : \"nearest\";\n for (const texture of this.imageTileTextures) {\n texture.source.scaleMode = mode;\n // scaleMode 세터는 필터만 대입하고 change를 안 쏨 → GPU 샘플러가 캐시된 채 유지된다.\n // style.update()로 리소스 무효화를 트리거해야 실제로 반영된다.\n texture.source.style.update();\n }\n if (!this.destroyed && this.app.renderer) this.app.render();\n }\n\n setOverlays(region: RegionOverlayData | null, dimmed: boolean) {\n this.setRegionOverlay(region);\n for (const child of this.dimOverlayLayer.removeChildren()) child.destroy();\n if (dimmed && this.imageWidth) {\n const dim = resolveCompletedDimStyle(this.host);\n this.dimOverlayLayer.addChild(\n new Graphics()\n .rect(0, 0, this.imageWidth, this.imageHeight)\n .fill({ color: hexToNum(dim.color), alpha: dim.opacity }),\n );\n }\n if (!this.destroyed && this.app.renderer) this.app.render();\n }\n\n setRegionOverlay(region: RegionOverlayData | null) {\n this.region = region;\n this.regionDimMaskG.clear();\n this.regionDimG.clear();\n this.regionZoneMaskG.clear();\n this.regionZoneG.clear();\n this.regionOutlineG.clear();\n if (!region) return;\n\n const dimColor = hexToNum(region.dim.color);\n for (const rect of region.rects) {\n this.regionDimMaskG.rect(rect.x, rect.y, rect.w, rect.h).fill(0xffffff);\n this.regionZoneMaskG.rect(rect.x, rect.y, rect.w, rect.h).fill(0xffffff);\n }\n this.regionDimG\n .rect(0, 0, this.imageWidth, this.imageHeight)\n .fill({ color: dimColor, alpha: region.dim.opacity });\n for (const zone of region.zones) {\n this.regionZoneG\n .poly(\n zone.points.flatMap((point) => [point.x, point.y]),\n true,\n )\n .fill({ color: dimColor, alpha: region.dim.opacity });\n }\n this.redrawRegionOutline();\n }\n\n // ── 뷰포트 ──\n get viewport(): Viewport {\n return { scale: this.world.scale.x, x: this.world.x, y: this.world.y };\n }\n\n applyViewport(v: Viewport) {\n // 판(translate만)은 스케일이 안 바뀌므로 재도색/핸들 재생성이 불필요하다\n // (월드 하위 노드가 함께 이동). 스트로크 폭·핸들 크기를 화면px로 유지하기 위한\n // 재도색은 줌(스케일 변경) 때만 한다 — 도형 많을 때 판이 매 프레임 전체 재그리기로\n // 렉 걸리던 것을 방지.\n const scaleChanged = v.scale !== this.lastAppliedScale;\n this.lastAppliedScale = v.scale;\n this.world.scale.set(v.scale);\n this.world.position.set(v.x, v.y);\n this.world.visible = true; // 뷰포트 확정 → 콘텐츠 노출(초기 unfit 프레임 방지)\n if (scaleChanged) this.restrokeShapes();\n // 트랜스포머 핸들은 화면 고정 레이어(stage 직속)에 화면 좌표로 그려지므로\n // 판(이동)에서도 매번 위치를 재계산해야 한다. 선택분만 그려서 가볍다.\n // 드래그(클릭 유지 포함) 중에는 drawTransformer가 조기 종료하므로\n // 마지막(또는 identity) 포인터 좌표로 라이브 재배치한다.\n if (this.activeDrag) {\n this.dragTransform(this.lastDragImg ?? dragIdentityImage(this.shapes, this.activeDrag));\n } else {\n this.drawTransformer();\n }\n this.cb.onViewportChange?.();\n }\n\n fit() {\n if (!this.imageWidth || !this.imageHeight) return;\n const { w, h } = this.screenSize;\n const scale = Math.min(w / this.imageWidth, h / this.imageHeight);\n this.applyViewport({\n scale,\n x: (w - this.imageWidth * scale) / 2,\n y: (h - this.imageHeight * scale) / 2,\n });\n }\n\n zoom100() {\n if (!this.imageWidth || !this.imageHeight) return;\n const { w, h } = this.screenSize;\n this.applyViewport({\n scale: 1,\n x: (w - this.imageWidth) / 2,\n y: (h - this.imageHeight) / 2,\n });\n }\n\n zoomAt(cx: number, cy: number, factor: number, min = 0.05, max = 20) {\n const s = this.world.scale.x;\n const ns = Math.min(max, Math.max(min, s * factor));\n const wx = (cx - this.world.x) / s;\n const wy = (cy - this.world.y) / s;\n this.applyViewport({ scale: ns, x: cx - wx * ns, y: cy - wy * ns });\n }\n\n panBy(dx: number, dy: number) {\n this.applyViewport({\n scale: this.world.scale.x,\n x: this.world.x + dx,\n y: this.world.y + dy,\n });\n }\n\n // ── 도형 렌더 ──\n setShapes(shapes: EditorShape[], selected: string[]) {\n this.shapes = cloneShapes(shapes);\n this.selected = selected;\n if (this.activeDrag) return;\n this.drawShapes();\n this.drawSelectionBorders();\n this.drawTransformer();\n }\n\n setSelection(selected: string[]) {\n this.selected = selected;\n if (selected.length !== 1 || selected[0] !== this.vertexPolygonId) {\n this.vertexPolygonId = null;\n this.selectedVertices.clear();\n }\n // 편집 대상이 더 이상 유일 선택이 아니면 편집모드 해제.\n if (this.editingId && (selected.length !== 1 || selected[0] !== this.editingId)) {\n this.editingId = null;\n }\n if (this.activeDrag) return;\n this.drawSelectionBorders();\n this.drawTransformer();\n }\n\n /** 폴리곤 정점 편집모드 진입/해제(null이면 해제). */\n setEditing(id: string | null) {\n if (this.editingId === id) return;\n this.editingId = id;\n this.selectedVertices.clear();\n if (!this.activeDrag) this.drawTransformer();\n }\n\n getVertexSelection(): number[] {\n return [...this.selectedVertices];\n }\n\n /** 편집모드 정점 다중선택 교체(마퀴 범위선택). 편집모드가 아니면 무시. */\n setVertexSelection(indices: number[]) {\n if (!this.editingId) return;\n const next = new Set(indices);\n if (\n next.size === this.selectedVertices.size &&\n [...next].every((i) => this.selectedVertices.has(i))\n ) {\n return;\n }\n this.selectedVertices = next;\n if (!this.activeDrag) this.drawTransformer();\n }\n\n /** SELECT 모드 + 비-readOnly일 때만 핸들 표시(호스트가 설정). */\n setTransformEnabled(enabled: boolean) {\n this.transformEnabled = enabled;\n // 드래그 도중 비활성화(검수 완료 단축키 등으로 readOnly 전환) — 진행 중인\n // 드래그를 커밋 없이 취소한다. 안 하면 드래그가 끝날 때까지 핸들이 남고,\n // 마우스를 놓는 순간 잠근 뒤의 이동이 커밋된다.\n if (!enabled) this.cancelTransform();\n this.syncShapeCursors();\n this.drawTransformer();\n }\n\n // 팬 모드: 핸들 레이어 자식의 히트테스트만 끈다(핸들은 계속 보이되 클릭은 통과).\n // interactiveChildren는 컨테이너 속성이라 이후 drawTransformer 재생성에도 유지된다.\n setPanMode(active: boolean) {\n this.handleLayer.interactiveChildren = !active;\n }\n\n private strokeW(shape?: EditorShape) {\n const strokeWidth = shape\n ? resolveShapeRenderStyle(shape, { strokeWidth: this.strokeSize }).strokeWidth\n : STROKE;\n return strokeWidth / this.world.scale.x;\n }\n\n private pointRadius(shape?: EditorShape) {\n return pointRadiusFor(shape, this.strokeSize, this.world.scale.x);\n }\n\n private dashForShape(shape: EditorShape): [number, number] | null {\n const dash = resolveShapeRenderStyle(shape, {\n strokeWidth: this.strokeSize,\n }).dash;\n if (!dash?.length) return null;\n const scale = this.world.scale.x || 1;\n return [dash[0] / scale, (dash[1] ?? dash[0]) / scale];\n }\n\n private drawShapes() {\n this.shapeLayer.removeChildren();\n for (const n of this.nodes.values()) n.destroy();\n this.nodes.clear();\n for (const shape of sortShapesForRender(this.shapes).filter(isShapeVisible)) {\n const g = new Graphics();\n this.paintShape(g, shape);\n g.eventMode = isShapeSelectable(shape) ? \"static\" : \"none\";\n g.cursor = undefined;\n if (isShapeSelectable(shape) && isShapeDraggable(shape)) {\n g.on(\"pointerover\", () => {\n if (this.activeDrag || !this.transformEnabled) return;\n // 선택된 도형만 grab — 비선택은 힌트로 구분해 소비층이 도구별로 해석.\n this.emitCursorHint(this.selected.includes(shape.id) ? \"grab\" : UNSELECTED_HOVER_HINT);\n });\n g.on(\"pointerout\", () => {\n if (!this.activeDrag) this.emitCursorHint(null);\n });\n }\n g.on(\"pointerdown\", (e) => {\n e.stopPropagation();\n this.cb.onPointerDown(this.toImage(e), shape.id, this.ev(e));\n });\n this.shapeLayer.addChild(g);\n this.nodes.set(shape.id, g);\n }\n }\n\n /** 도형 하나를 Graphics에 그린다(생성/라이브갱신 공용). */\n private paintShape(g: Graphics, shape: EditorShape) {\n g.clear();\n const style = resolveShapeRenderStyle(shape, {\n strokeWidth: this.strokeSize,\n });\n const color = hexToNum(style.color);\n const width = this.strokeW(shape);\n const alpha = style.opacity;\n const dash = this.dashForShape(shape);\n if (shape.type === SHAPE_TYPE.POINT) {\n // 핀 아이콘(하단중앙 앵커, 뷰포트 반비례 스케일로 화면 크기 고정).\n g.svg(pinSvg(style.color));\n g.position.set(shape.points[0].x, shape.points[0].y);\n g.pivot.set(PIN_WIDTH / 2, PIN_HEIGHT);\n const inv = 1 / (this.world.scale.x || 1);\n g.scale.set(inv, inv);\n g.alpha = alpha;\n return;\n }\n if (style.fillVisible && shape.type !== SHAPE_TYPE.LINE) {\n // 자기교차(모래시계·도넛) 폴리곤은 earcut 삼각분할이 교차 정점을 무시한 면을\n // 만들므로, 평면 배치 면 단위 채움 그룹으로 나눠 칠한다 — 도넛 구멍만\n // 비우고, 겹침은 겹수(layers)만큼 반투명을 포개 진해지며, 나머지는 칠해진다.\n const groups =\n shape.type === SHAPE_TYPE.POLYGON ? computePolygonFillGroups(shape.points) : null;\n if (groups && (groups.length > 1 || groups[0].holes.length > 0)) {\n for (const group of groups) {\n // 겹수 상한 4 — 그 이상은 시각적으로 구분되지 않고 불투명해질 뿐이다.\n for (let layer = 0; layer < Math.min(group.layers, 4); layer++) {\n g.poly(\n group.outline.flatMap((p) => [p.x, p.y]),\n true,\n );\n g.fill({ color, alpha: style.fillAlpha * alpha });\n for (const hole of group.holes) {\n g.poly(\n hole.flatMap((p) => [p.x, p.y]),\n true,\n );\n g.cut();\n }\n }\n }\n } else {\n this.path(g, shape);\n g.fill({ color, alpha: style.fillAlpha * alpha });\n }\n } else if (shape.type !== SHAPE_TYPE.LINE) {\n // 외곽선만 그리는 닫힌 도형(예: OBB 박스)도 내부를 클릭해 선택할 수 있도록\n // 투명 fill로 hit 영역을 확보한다(렌더에는 영향 없음). LINE(열린 패스)은 제외.\n this.path(g, shape);\n g.fill({ color, alpha: 0 });\n }\n if (dash) {\n // 점선의 빈 구간 보조색(alternateColor) — 보조색 실선 위에 주색 점선(프리뷰와 동일 계약).\n if (shape.style?.alternateColor) {\n this.path(g, shape);\n g.stroke({ width, color: hexToNum(shape.style.alternateColor), alpha });\n }\n this.dashedStrokeShape(g, shape, width, color, alpha, dash);\n return;\n }\n this.path(g, shape);\n g.stroke({ width, color, alpha });\n }\n\n /** 드래그 중 도형 노드를 새 점으로 즉시 다시 그림(리렌더 없음). */\n liveUpdateShape(id: string, points: Point[]) {\n const g = this.nodes.get(id);\n const shape = this.shapes.find((s) => s.id === id);\n if (g && shape) this.paintShape(g, { ...shape, points });\n }\n\n /** bbox가 박스와 교차하는 도형 id들(마퀴 선택). */\n shapesIntersecting(box: { minX: number; minY: number; maxX: number; maxY: number }): string[] {\n return intersectingShapeIds(this.shapes, box);\n }\n\n /** 점을 포함하는 도형들(위→아래 순서, Alt 순환용). */\n shapesAt(p: Point): string[] {\n return this.shapes\n .filter((s) => {\n const b = getBBox(s.points);\n return p.x >= b.minX && p.x <= b.maxX && p.y >= b.minY && p.y <= b.maxY;\n })\n .map((s) => s.id);\n }\n\n // ── 그리기 미리보기 ──\n private previewG = new Graphics();\n private marqueeG = new Graphics();\n private previewMaskSprite: Sprite | null = null;\n private previewMaskTexture: Texture | null = null;\n private previewReady = false;\n /** 그리는 중 초안(폴리곤/박스) 마지막 파라미터 — 줌 시 화면고정 두께로 재도색용. */\n private lastPreview:\n | {\n kind: \"poly\";\n points: Point[];\n cursor: Point | null;\n style: ShapeStyle;\n closed: boolean;\n selectedPointIndices: number[];\n showVertices: boolean;\n }\n | { kind: \"box\"; boxKind: \"rect\" | \"ellipse\"; a: Point; b: Point; style: ShapeStyle }\n | null = null;\n /** 줌 후 초안을 현재 스케일 기준 두께/정점 크기로 다시 그린다. */\n private repaintPreview() {\n const p = this.lastPreview;\n if (!p) return;\n if (p.kind === \"poly\") {\n this.previewPoly(\n p.points,\n p.cursor,\n p.style,\n p.closed,\n p.selectedPointIndices,\n p.showVertices,\n );\n } else {\n this.previewBox(p.boxKind, p.a, p.b, p.style);\n }\n }\n private ensurePreview() {\n if (this.previewReady) return;\n this.previewLayer.addChild(this.previewG, this.marqueeG);\n this.previewReady = true;\n }\n clearPreview() {\n this.lastPreview = null;\n this.previewG.clear();\n if (this.previewMaskSprite) this.previewMaskSprite.visible = false;\n }\n clearMarquee() {\n this.marqueeG.clear();\n }\n previewBox(kind: \"rect\" | \"ellipse\", a: Point, b: Point, style: ShapeStyle) {\n this.lastPreview = { kind: \"box\", boxKind: kind, a, b, style };\n this.ensurePreview();\n this.previewG.clear();\n const shape: EditorShape = {\n id: \"__preview__\",\n type: kind === \"ellipse\" ? SHAPE_TYPE.ELLIPSE : SHAPE_TYPE.RECTANGLE,\n points: [a, b],\n style,\n };\n const width = this.strokeW(shape);\n if (style.alternateColor) {\n this.path(this.previewG, shape);\n this.previewG.stroke({ width, color: hexToNum(style.alternateColor) });\n }\n const dash = this.dashForShape(shape);\n if (dash) {\n this.dashedStrokeShape(\n this.previewG,\n shape,\n width,\n hexToNum(style.color ?? \"#00e5ff\"),\n style.opacity ?? 1,\n dash,\n );\n return;\n }\n this.path(this.previewG, shape);\n this.previewG.stroke({\n width,\n color: hexToNum(style.color ?? \"#00e5ff\"),\n alpha: style.opacity ?? 1,\n });\n }\n previewPoly(\n points: Point[],\n cursor: Point | null,\n style: ShapeStyle,\n closed: boolean,\n selectedPointIndices: number[] = [],\n showVertices = true,\n ) {\n this.lastPreview = {\n kind: \"poly\",\n points,\n cursor,\n style,\n closed,\n selectedPointIndices,\n showVertices,\n };\n this.ensurePreview();\n this.previewG.clear();\n if (!points.length) return;\n const previewPoints = cursor ? [...points, cursor] : points;\n const shape: EditorShape = {\n id: \"__preview__\",\n type: closed ? SHAPE_TYPE.POLYGON : SHAPE_TYPE.LINE,\n points: previewPoints,\n style,\n };\n const width = this.strokeW(shape);\n if (style.alternateColor) {\n this.path(this.previewG, shape);\n this.previewG.stroke({ width, color: hexToNum(style.alternateColor) });\n }\n const dash = this.dashForShape(shape);\n if (dash) {\n this.dashedStrokeShape(\n this.previewG,\n shape,\n width,\n hexToNum(style.color ?? \"#00e5ff\"),\n style.opacity ?? 1,\n dash,\n );\n } else {\n this.path(this.previewG, shape);\n this.previewG.stroke({\n width,\n color: hexToNum(style.color ?? \"#00e5ff\"),\n alpha: style.opacity ?? 1,\n });\n }\n // PATH(자유선)처럼 점을 안 찍는 도구는 정점 점을 숨기고 선만 보여준다.\n if (!showVertices) return;\n const selected = new Set(selectedPointIndices);\n const radius = 5 / this.world.scale.x;\n const selectedRadius = 6 / this.world.scale.x;\n for (let i = 0; i < points.length; i++) {\n const point = points[i];\n const isSelected = selected.has(i);\n this.previewG\n .circle(point.x, point.y, isSelected ? selectedRadius : radius)\n .fill({ color: isSelected ? 0x1e88e5 : 0xffffff })\n .stroke({\n width: 1.5 / this.world.scale.x,\n color: isSelected ? 0xffffff : 0x1e88e5,\n });\n }\n }\n previewScalarMask(raster: ScalarMaskRaster, color: string) {\n // 래스터 스프라이트는 스케일 재도색이 필요 없다 — 초안 재도색 대상에서 제외.\n this.lastPreview = null;\n this.ensurePreview();\n this.previewG.clear();\n const tint = color.length === 7 ? `${color}99` : color;\n const previewCanvas = buildScalarMaskPreviewCanvas(raster, tint);\n if (this.previewMaskTexture) this.previewMaskTexture.destroy(true);\n this.previewMaskTexture = Texture.from(previewCanvas);\n if (!this.previewMaskSprite) {\n this.previewMaskSprite = new Sprite(this.previewMaskTexture);\n this.previewLayer.addChildAt(this.previewMaskSprite, 0);\n } else {\n this.previewMaskSprite.texture = this.previewMaskTexture;\n this.previewMaskSprite.visible = true;\n }\n this.previewMaskSprite.x = raster.ox;\n this.previewMaskSprite.y = raster.oy;\n this.previewMaskSprite.width = previewCanvas.width / raster.scale;\n this.previewMaskSprite.height = previewCanvas.height / raster.scale;\n }\n previewMarquee(a: Point, b: Point) {\n this.ensurePreview();\n this.marqueeG.clear();\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n const w = Math.abs(b.x - a.x);\n const h = Math.abs(b.y - a.y);\n const color = hexToNum(SELECTION_AREA_COLOR);\n this.marqueeG\n .rect(x, y, w, h)\n .fill({ color, alpha: SELECTION_AREA_FILL_ALPHA })\n .stroke({ width: 1 / this.world.scale.x, color });\n }\n\n /** 줌 시 화면고정 선두께 유지 위해 다시 그림(도형 수 많으면 비용 — 후속 최적화). */\n /**\n * 뷰포트 스케일 변경(줌) 시 스트로크 폭을 화면px 기준으로 다시 맞춘다.\n * 노드를 destroy/재생성하지 않고 기존 Graphics를 재도색(paintShape가 clear로 시작)해\n * 도형이 많아도 줌이 무겁지 않게 한다. 노드가 아직 없으면 최초 1회만 전체 생성.\n */\n private restrokeShapes() {\n if (!this.nodes.size) {\n if (this.shapes.length) this.drawShapes();\n } else {\n const byId = new Map(this.shapes.map((s) => [s.id, s]));\n for (const [id, g] of this.nodes) {\n const shape = byId.get(id);\n if (shape) this.paintShape(g, shape);\n }\n }\n this.drawSelectionBorders();\n this.redrawRegionOutline();\n this.repaintPreview();\n }\n\n /** 영역 윤곽 점선 — 두께·점선을 화면 px로 유지(줌 시 재도색). */\n private redrawRegionOutline() {\n const g = this.regionOutlineG;\n g.clear();\n const styles = this.region?.outlineStyles;\n if (!this.region || !styles) return;\n const scale = this.world.scale.x || 1;\n const drawSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n const width = style.width / scale;\n const dash: [number, number] = [style.dash[0] / scale, style.dash[1] / scale];\n for (const [a, b] of segments) {\n if (style.underlayColor) {\n g.poly([a.x, a.y, b.x, b.y], false).stroke({\n width,\n color: hexToNum(style.underlayColor),\n });\n }\n this.strokeDashedPolyline(\n g,\n [a, b],\n false,\n width,\n hexToNum(style.color),\n style.opacity,\n dash,\n );\n }\n };\n drawSegments(this.region.visibleOutline, styles.visible);\n drawSegments(this.region.occludedOutline, styles.occluded);\n }\n\n private path(g: Graphics, shape: EditorShape) {\n const { type, points } = shape;\n if (type === SHAPE_TYPE.POINT) {\n g.circle(points[0].x, points[0].y, this.pointRadius(shape));\n return;\n }\n if (type === SHAPE_TYPE.RECTANGLE) {\n const b = getBBox(points);\n g.rect(b.minX, b.minY, b.maxX - b.minX, b.maxY - b.minY);\n return;\n }\n if (type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n g.ellipse(\n (b.minX + b.maxX) / 2,\n (b.minY + b.maxY) / 2,\n (b.maxX - b.minX) / 2,\n (b.maxY - b.minY) / 2,\n );\n return;\n }\n const flat = points.flatMap((p) => [p.x, p.y]);\n g.poly(flat, type !== SHAPE_TYPE.LINE);\n }\n\n private dashedStrokeShape(\n g: Graphics,\n shape: EditorShape,\n width: number,\n color: number,\n alpha: number,\n dashPattern: [number, number],\n ) {\n const { type, points } = shape;\n if (type === SHAPE_TYPE.RECTANGLE) {\n const b = getBBox(points);\n this.strokeDashedPolyline(\n g,\n [\n { x: b.minX, y: b.minY },\n { x: b.maxX, y: b.minY },\n { x: b.maxX, y: b.maxY },\n { x: b.minX, y: b.maxY },\n ],\n true,\n width,\n color,\n alpha,\n dashPattern,\n );\n return;\n }\n if (type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n const cx = (b.minX + b.maxX) / 2;\n const cy = (b.minY + b.maxY) / 2;\n const rx = (b.maxX - b.minX) / 2;\n const ry = (b.maxY - b.minY) / 2;\n const samples = 96;\n const ellipsePoints = Array.from({ length: samples }, (_, i) => {\n const a = (i / samples) * Math.PI * 2;\n return { x: cx + Math.cos(a) * rx, y: cy + Math.sin(a) * ry };\n });\n this.strokeDashedPolyline(g, ellipsePoints, true, width, color, alpha, dashPattern);\n return;\n }\n this.strokeDashedPolyline(\n g,\n points,\n type !== SHAPE_TYPE.LINE,\n width,\n color,\n alpha,\n dashPattern,\n );\n }\n\n private strokeDashedPolyline(\n g: Graphics,\n points: Point[],\n closed: boolean,\n width: number,\n color: number,\n alpha: number,\n dashPattern: [number, number],\n ) {\n if (points.length < 2) return;\n const [dash, gap] = dashPattern;\n // 0 이하면 아래 루프가 전진하지 못해 멈춘다(선 두께 0 등).\n if (!(dash > 0) || !(gap > 0)) return;\n let drawing = true;\n let phase = 0;\n // 칸 하나가 꼭짓점을 가로지르면 그 꼭짓점을 포함한 하나의 선으로 그린다.\n // 칸마다 따로 stroke하면 두 선분으로 쪼개져 이음 없이 끝이 잘린다.\n // stroke 호출 횟수는 칸 수 그대로 — 전체를 한 패스로 모으면 지오메트리가 커진다.\n let pending: Point[] | null = null;\n const flushDash = () => {\n if (pending && pending.length >= 2) {\n g.moveTo(pending[0].x, pending[0].y);\n for (let k = 1; k < pending.length; k++) g.lineTo(pending[k].x, pending[k].y);\n g.stroke({ width, color, alpha });\n }\n pending = null;\n };\n const segmentCount = closed ? points.length : points.length - 1;\n for (let i = 0; i < segmentCount; i++) {\n const a = points[i];\n const b = points[(i + 1) % points.length];\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const length = Math.hypot(dx, dy);\n if (!length) continue;\n let consumed = 0;\n while (consumed < length) {\n const patternLength = drawing ? dash : gap;\n const step = Math.min(patternLength - phase, length - consumed);\n if (drawing) {\n const t0 = consumed / length;\n const t1 = (consumed + step) / length;\n if (!pending) pending = [{ x: a.x + dx * t0, y: a.y + dy * t0 }];\n pending.push({ x: a.x + dx * t1, y: a.y + dy * t1 });\n }\n consumed += step;\n phase += step;\n if (phase >= patternLength - 0.0001) {\n phase = 0;\n if (drawing) flushDash();\n drawing = !drawing;\n }\n }\n }\n flushDash();\n }\n\n private drawSelectionBorders() {\n this.selLayer.position.set(0, 0);\n // Set 멤버십 + 노드 재사용(개수 변화 때만 재생성). 전체선택 후 줌/판마다\n // N개 Graphics를 destroy/생성하고 includes로 O(N²) 검사하던 렉 방지.\n const selectedSet = new Set(this.selected);\n const targets = this.selected.length\n ? this.shapes.filter((s) => selectedSet.has(s.id) && isShapeSelectable(s))\n : [];\n if (this.selectionBorderGfx.length !== targets.length) {\n for (const g of this.selectionBorderGfx) g.destroy();\n this.selectionBorderGfx = targets.map(() => {\n const g = new Graphics();\n this.selLayer.addChild(g);\n return g;\n });\n }\n const w = 1.5 / this.world.scale.x;\n targets.forEach((shape, i) => {\n const g = this.selectionBorderGfx[i];\n g.clear();\n g.poly(\n this.selectionOutlinePoints(shape, shape.points).flatMap((point) => [point.x, point.y]),\n true,\n ).stroke({ width: w, color: SELECTION_BORDER });\n });\n }\n\n /** 드래그 중 선택 테두리를 라이브 좌표로 동기화. */\n private updateSelectionBordersLive(getPoints: (shape: EditorShape) => Point[]) {\n const selectedSet = new Set(this.selected);\n const w = 1.5 / this.world.scale.x;\n let i = 0;\n for (const shape of this.shapes) {\n if (!selectedSet.has(shape.id)) continue;\n if (!isShapeSelectable(shape)) continue;\n const g = this.selectionBorderGfx[i++];\n if (!g) continue;\n g.clear();\n g.poly(\n this.selectionOutlinePoints(shape, getPoints(shape)).flatMap((point) => [point.x, point.y]),\n true,\n ).stroke({ width: w, color: SELECTION_BORDER });\n }\n }\n\n private selectionOutlinePoints(shape: EditorShape, points: Point[]) {\n return outlinePointsFor(shape, points, this.pointRadius(shape));\n }\n\n // ── 트랜스포머(바운딩박스 리사이즈 + 꼭짓점 편집) ──\n\n private imgToScreen(p: Point): Point {\n const g = this.world.toGlobal({ x: p.x, y: p.y });\n return { x: g.x, y: g.y };\n }\n\n private setTransformerOutline(box: BBox) {\n const bw = box.maxX - box.minX;\n const bh = box.maxY - box.minY;\n if (bw <= 0 && bh <= 0) return;\n this.setTransformerOutlinePoints(\n rectTo4([\n { x: box.minX, y: box.minY },\n { x: box.maxX, y: box.maxY },\n ]),\n );\n }\n\n private setTransformerOutlinePoints(points: Point[]) {\n if (points.length < 2) return;\n if (!this.transformerOutline) {\n this.transformerOutline = new Graphics();\n this.selLayer.addChild(this.transformerOutline);\n }\n this.transformerOutline.clear();\n this.transformerOutline\n .poly(\n points.flatMap((point) => [point.x, point.y]),\n true,\n )\n .stroke({ width: 1 / this.world.scale.x, color: 0x1e88e5 });\n }\n\n private rotationHandleGap() {\n return rotationHandleGapFor(this.viewport.scale);\n }\n\n private rotationHandleScreenPoint(points: Point[]) {\n return this.imgToScreen(rotateHandlePos(points, this.rotationHandleGap()));\n }\n\n private setRotationConnector(points: Point[]) {\n const from = this.imgToScreen(mid(points[0], points[1]));\n const to = this.rotationHandleScreenPoint(points);\n if (!this.rotLineNode) {\n this.rotLineNode = new Graphics();\n this.rotLineNode.eventMode = \"none\";\n this.handleLayer.addChild(this.rotLineNode);\n }\n this.rotLineNode.clear();\n this.rotLineNode\n .moveTo(from.x, from.y)\n .lineTo(to.x, to.y)\n .stroke({ width: 1, color: 0x1e88e5 });\n }\n\n private layoutResizeHandle(g: Graphics, sp: Point, angleRad: number) {\n g.position.set(sp.x, sp.y);\n g.rotation = angleRad;\n }\n\n private orientedHandleAngle(points: Point[]): number {\n return orientedAngleFromScreenPoints(this.imgToScreen(points[0]), this.imgToScreen(points[1]));\n }\n\n /** 핸들(8개 bbox + 단일 폴리곤/라인 꼭짓점)을 화면좌표로 그림. */\n drawTransformer() {\n if (this.activeDrag) return; // 드래그 중엔 repositionHandlesLive가 담당\n for (const h of this.handleNodes) h.destroy();\n for (const v of this.vertexNodes) v.destroy();\n for (const m of this.midNodes) m.destroy();\n this.ghostNode?.destroy();\n this.ghostNode = null;\n this.rotNode?.destroy();\n this.rotNode = null;\n this.rotLineNode?.destroy();\n this.rotLineNode = null;\n this.transformerOutline?.destroy();\n this.transformerOutline = null;\n this.handleNodes = [];\n this.vertexNodes = [];\n this.midNodes = [];\n if (!this.transformEnabled) return;\n const sel = selectEditable(this.shapes, this.selected);\n if (sel.length === 0) return;\n if (sel.length === 1 && sel[0].type === SHAPE_TYPE.POINT) return;\n\n // 폴리곤/라인이 편집모드일 때만 정점 편집 UI를 보여준다.\n const editingPoly =\n sel.length === 1 &&\n (sel[0].type === SHAPE_TYPE.POLYGON || sel[0].type === SHAPE_TYPE.LINE) &&\n this.editingId === sel[0].id\n ? sel[0]\n : null;\n\n const box = getBBox(sel.flatMap((s) => s.points));\n const rotatedRect =\n sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE ? sel[0] : null;\n const transformerHandles = rotatedRect\n ? orientedHandles(rotatedRect.points)\n : ANCHORS.map((a) => anchorPoint(a, box));\n rotatedRect\n ? this.setTransformerOutlinePoints(rotatedRect.points)\n : this.setTransformerOutline(box);\n if (rotatedRect) this.setRotationConnector(rotatedRect.points);\n const handleAngleRad = rotatedRect ? this.orientedHandleAngle(rotatedRect.points) : 0;\n // 편집모드(정점 편집) 중엔 bbox 리사이즈 핸들을 숨겨 정점 편집만 보이게 한다.\n for (const a of editingPoly ? [] : ANCHORS) {\n const sp = this.imgToScreen(transformerHandles[ANCHORS.indexOf(a)]);\n const g = new Graphics();\n g.rect(-4, -4, 8, 8).fill({ color: 0xffffff }).stroke({ width: 1, color: 0x1e88e5 });\n this.layoutResizeHandle(g, sp, handleAngleRad);\n g.eventMode = \"static\";\n const cursor = resizeCursorForAnchor(a, handleAngleRad);\n this.bindCursor(g, cursor);\n g.on(\"pointerdown\", (e) => {\n e.stopPropagation();\n this.emitCursorHint(cursor);\n this.emitInteractionMode(\"resizing\");\n const cur = selectEditable(this.shapes, this.selected);\n this.activeDrag = {\n kind: \"resize\",\n anchor: a,\n box: getBBox(cur.flatMap((s) => s.points)),\n shapes: cur.map((s) => ({ id: s.id, points: s.points })),\n };\n this.lastDragImg = null;\n });\n this.handleLayer.addChild(g);\n this.handleNodes.push(g);\n }\n\n if (editingPoly) {\n const shape = editingPoly;\n const pts = shape.points;\n const isPoly = shape.type === SHAPE_TYPE.POLYGON;\n const edges = isPoly ? pts.length : pts.length - 1;\n const vertexR = this.vertexHandleRadius();\n // 정점 추가 고스트 — 변 호버 시에만, 커서의 변 위 최근접 지점에 표시.\n const ghost = new Graphics();\n ghost\n .circle(0, 0, vertexR * 0.8)\n .fill({ color: 0xffffff, alpha: 0.6 })\n .stroke({ width: 1, color: 0x1e88e5 });\n ghost.visible = false;\n ghost.eventMode = \"none\";\n this.handleLayer.addChild(ghost);\n this.ghostNode = ghost;\n for (let i = 0; i < edges; i++) {\n const a = pts[i];\n const b = pts[(i + 1) % pts.length];\n // 보이지 않는 변 히트 영역(변 주위 ±7px 쿼드) — 호버/클릭만 받는다.\n const g = new Graphics();\n g.hitArea = this.edgeHitQuad(a, b);\n g.eventMode = \"static\";\n this.bindCursor(g, \"copy\");\n // 커서의 변 위 최근접 지점(이미지 좌표) — 자유 위치 정점 삽입 지점.\n const closestOnEdge = (e: FederatedPointerEvent): Point => {\n const p = this.toImage(e);\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len2 = dx * dx + dy * dy;\n const t = len2\n ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))\n : 0;\n return { x: a.x + t * dx, y: a.y + t * dy };\n };\n g.on(\"pointermove\", (e) => {\n if (this.activeDrag) return;\n const sp = this.imgToScreen(closestOnEdge(e));\n ghost.position.set(sp.x, sp.y);\n ghost.visible = true;\n });\n g.on(\"pointerleave\", () => {\n ghost.visible = false;\n });\n g.on(\"pointerdown\", (e) => {\n e.stopPropagation();\n const q = closestOnEdge(e);\n const idx = i + 1;\n const next = [...pts.slice(0, idx), q, ...pts.slice(idx)];\n // 로컬 도형·핸들을 먼저 갱신해 새 정점 노드를 만든 뒤 그 정점 드래그를\n // 즉시 시작한다(마우스다운 = 정점 생성 + 이동 개시).\n const target = this.shapes.find((s) => s.id === shape.id);\n if (target) target.points = next;\n this.liveUpdateShape(shape.id, next);\n this.selectedVertices = new Set([idx]);\n this.drawTransformer();\n this.cb.onTransformCommit?.([{ id: shape.id, points: next }]);\n this.activeDrag = {\n kind: \"vertex\",\n id: shape.id,\n indices: [idx],\n base: next,\n start: q,\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"vertexDragging\");\n });\n this.handleLayer.addChild(g);\n this.midNodes.push(g);\n }\n // 편집 대상 폴리곤이 바뀌면 정점 다중선택 초기화.\n if (this.vertexPolygonId !== shape.id) {\n this.vertexPolygonId = shape.id;\n this.selectedVertices.clear();\n }\n // 꼭짓점 핸들(드래그=이동, Shift/Ctrl/Cmd=다중선택).\n pts.forEach((pt, i) => {\n const sp = this.imgToScreen(pt);\n const isSel = this.selectedVertices.has(i);\n const g = new Graphics();\n g.circle(0, 0, vertexR)\n .fill({ color: isSel ? 0x1e88e5 : 0xffffff })\n .stroke({ width: Math.max(1.5, vertexR * 0.3), color: isSel ? 0xffffff : 0x1e88e5 });\n g.position.set(sp.x, sp.y);\n g.eventMode = \"static\";\n this.bindCursor(g, \"pointer\");\n g.on(\"pointerdown\", (e) => {\n e.stopPropagation();\n if (e.shiftKey || e.ctrlKey || e.metaKey) {\n if (this.selectedVertices.has(i)) this.selectedVertices.delete(i);\n else this.selectedVertices.add(i);\n this.drawTransformer();\n return;\n }\n const indices =\n this.selectedVertices.has(i) && this.selectedVertices.size > 1\n ? [...this.selectedVertices]\n : [i];\n if (indices.length === 1) {\n this.selectedVertices.clear();\n this.selectedVertices.add(i);\n }\n this.activeDrag = {\n kind: \"vertex\",\n id: shape.id,\n indices,\n base: pts,\n start: this.toImage(e),\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"vertexDragging\");\n });\n this.handleLayer.addChild(g);\n this.vertexNodes.push(g);\n });\n }\n\n // 회전 핸들(회전사각형 단일 선택). bbox 위 중앙 바깥.\n if (sel.length === 1 && sel[0].type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n const shape = sel[0];\n const center = centerOf(shape.points);\n const sp = this.rotationHandleScreenPoint(shape.points);\n const g = new Graphics();\n g.circle(0, 0, 6).fill({ color: 0xffffff }).stroke({ width: 1.5, color: 0x1e88e5 });\n g.position.set(sp.x, sp.y);\n g.eventMode = \"static\";\n this.bindCursor(g, \"grab\");\n g.on(\"pointerdown\", (e) => {\n e.stopPropagation();\n const ip = this.toImage(e);\n this.activeDrag = {\n kind: \"rotate\",\n id: shape.id,\n center,\n startAngle: Math.atan2(ip.y - center.y, ip.x - center.x),\n points: shape.points,\n shiftKey: e.shiftKey,\n };\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"rotating\");\n });\n this.handleLayer.addChild(g);\n this.rotNode = g;\n }\n }\n\n /** 도형 본체 드래그 이동 시작(호스트가 도형 위 포인터다운 시 호출). */\n beginMove(start: Point, ids: string[]) {\n const drag = makeMoveDrag(this.shapes, ids, start);\n if (!drag) return;\n if (this.transformEnabled && !this.handleNodes.length) this.drawTransformer();\n this.activeDrag = drag;\n this.lastDragImg = null;\n this.emitCursorHint(\"grabbing\");\n this.emitInteractionMode(\"moving\");\n const selectedShape =\n drag.shapes.length === 1 ? this.shapes.find((s) => s.id === drag.shapes[0].id) : null;\n if (selectedShape?.type === SHAPE_TYPE.ROTATED_RECTANGLE) {\n this.setTransformerOutlinePoints(drag.shapes[0].points);\n } else {\n this.setTransformerOutline(drag.box);\n }\n this.updateSelectionBordersLive((shape) => shape.points);\n }\n\n private repositionHandlesForBox(box: BBox) {\n ANCHORS.forEach((a, i) => {\n const sp = this.imgToScreen(anchorPoint(a, box));\n const node = this.handleNodes[i];\n if (node) this.layoutResizeHandle(node, sp, 0);\n });\n this.setTransformerOutline(box);\n }\n\n private repositionOrientedHandles(points: Point[]) {\n const angleRad = this.orientedHandleAngle(points);\n orientedHandles(points).forEach((point, i) => {\n const sp = this.imgToScreen(point);\n const node = this.handleNodes[i];\n if (node) this.layoutResizeHandle(node, sp, angleRad);\n });\n this.setTransformerOutlinePoints(points);\n if (this.rotNode) {\n const sp = this.rotationHandleScreenPoint(points);\n this.rotNode.position.set(sp.x, sp.y);\n }\n if (this.rotLineNode) this.setRotationConnector(points);\n }\n\n /** 폴리곤/라인 꼭짓점·변 중점 핸들을 이미지 좌표 기준으로 재배치. */\n private repositionPolygonHandles(pts: Point[], isPolygon: boolean) {\n if (!this.vertexNodes.length) return;\n pts.forEach((pt, i) => {\n const sp = this.imgToScreen(pt);\n this.vertexNodes[i]?.position.set(sp.x, sp.y);\n });\n const edges = isPolygon ? pts.length : pts.length - 1;\n for (let i = 0; i < edges; i++) {\n const node = this.midNodes[i];\n if (node) node.hitArea = this.edgeHitQuad(pts[i], pts[(i + 1) % pts.length]);\n }\n }\n\n /** 변(이미지 좌표 a→b) 주위 히트 쿼드 — 변 호버/클릭 히트영역(정점 핸들에 비례). */\n private edgeHitQuad(a: Point, b: Point): Polygon {\n const half = Math.max(7, this.vertexHandleRadius() + 2);\n const sa = this.imgToScreen(a);\n const sb = this.imgToScreen(b);\n const ex = sb.x - sa.x;\n const ey = sb.y - sa.y;\n const len = Math.hypot(ex, ey) || 1;\n const nx = (-ey / len) * half;\n const ny = (ex / len) * half;\n return new Polygon([\n sa.x + nx,\n sa.y + ny,\n sb.x + nx,\n sb.y + ny,\n sb.x - nx,\n sb.y - ny,\n sa.x - nx,\n sa.y - ny,\n ]);\n }\n\n private resetMoveOffsets() {\n for (const [id, g] of this.nodes) {\n // POINT 핀은 position이 절대 앵커(paintShape가 설정) — 0으로 리셋하면\n // 원점으로 튄다. 커밋 시 paintShape가 새 앵커로 다시 세팅하므로 건너뛴다.\n if (this.shapes.find((s) => s.id === id)?.type === SHAPE_TYPE.POINT) continue;\n g.position.set(0, 0);\n }\n this.selLayer.position.set(0, 0);\n }\n\n private commitTransformUpdates(updates: { id: string; points: Point[] }[]) {\n if (!updates.length) return;\n for (const update of updates) {\n const shape = this.shapes.find((s) => s.id === update.id);\n if (!shape) continue;\n shape.points = update.points;\n const g = this.nodes.get(update.id);\n if (g) this.paintShape(g, { ...shape, points: update.points });\n }\n this.cb.onTransformCommit?.(updates);\n this.drawTransformer();\n }\n\n // lastDragImg 기록은 pointermove 콜러 소유 — 뷰포트 변경(줌/팬) 중 재호출해도\n // endTransform의 \"이동 없음 → 커밋 생략\" 판정이 유지된다.\n private dragTransform(img: Point) {\n const d = this.activeDrag;\n if (!d) return;\n this.applyCursor();\n const isRotatedRect = dragTargetIsRotatedRect(this.shapes, d);\n const { updates, box } = computeDragUpdates(d, img, isRotatedRect);\n if (d.kind === \"move\") {\n // 순수 이동은 지오메트리 재생성 없이 노드 transform만 이동(마우스와 1:1, 즉각).\n // 단 POINT 핀은 paintShape가 position을 절대 앵커(points[0])로 쓰므로,\n // 델타를 덮어쓰면 원점 근처로 튄다 — 절대 좌표로 이동시킨다.\n const dx = img.x - d.start.x;\n const dy = img.y - d.start.y;\n for (const s of d.shapes) {\n const g = this.nodes.get(s.id);\n if (!g) continue;\n const type = this.shapes.find((x) => x.id === s.id)?.type;\n if (type === SHAPE_TYPE.POINT) g.position.set(s.points[0].x + dx, s.points[0].y + dy);\n else g.position.set(dx, dy);\n }\n } else {\n for (const u of updates) this.liveUpdateShape(u.id, u.points);\n }\n this.cb.onTransformPreview?.(updates);\n this.updateSelectionBordersLive(\n (shape) => updates.find((item) => item.id === shape.id)?.points ?? shape.points,\n );\n if (d.kind === \"resize\" || d.kind === \"move\") {\n if (isRotatedRect) this.repositionOrientedHandles(updates[0].points);\n else if (box) this.repositionHandlesForBox(box);\n const single =\n d.shapes.length === 1 ? this.shapes.find((s) => s.id === d.shapes[0].id) : null;\n const isPolyLike = single?.type === SHAPE_TYPE.POLYGON || single?.type === SHAPE_TYPE.LINE;\n const showPolyHandles =\n d.kind === \"resize\" ? isPolyLike : this.vertexNodes.length > 0 && d.shapes.length === 1;\n if (showPolyHandles) {\n this.repositionPolygonHandles(updates[0].points, single?.type === SHAPE_TYPE.POLYGON);\n }\n } else if (d.kind === \"rotate\") {\n this.repositionOrientedHandles(updates[0].points);\n const shape = this.shapes.find((s) => s.id === d.id);\n if (shape && (shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE)) {\n this.repositionPolygonHandles(updates[0].points, shape.type === SHAPE_TYPE.POLYGON);\n }\n } else {\n if (box) this.repositionHandlesForBox(box);\n const shape = this.shapes.find((s) => s.id === d.id);\n this.repositionPolygonHandles(updates[0].points, shape?.type === SHAPE_TYPE.POLYGON);\n }\n }\n\n /** 진행 중인 드래그를 커밋 없이 취소 — 프리뷰가 옮긴 노드를 확정 좌표로 되돌린다. */\n private cancelTransform() {\n if (!this.activeDrag) return;\n const wasMove = this.activeDrag.kind === \"move\";\n this.activeDrag = null;\n this.lastDragImg = null;\n // 이동 프리뷰는 노드 transform 오프셋으로만 움직였다 — 오프셋을 되돌린다.\n if (wasMove) this.resetMoveOffsets();\n // 확정 좌표는 this.shapes에 그대로 있다(커밋은 드래그 끝에만 일어난다).\n for (const shape of this.shapes) this.liveUpdateShape(shape.id, shape.points);\n // 빈 프리뷰([])가 아니라 확정 좌표를 되쏜다 — 크기 배지·미니맵 오버레이는\n // 프리뷰 경로로 DOM을 직접 옮기므로, 원위치도 같은 경로로 되돌려야 한다.\n this.cb.onTransformPreview?.(\n this.shapes.map((shape) => ({ id: shape.id, points: shape.points })),\n );\n this.emitInteractionMode(\"idle\");\n this.emitCursorHint(null);\n this.drawSelectionBorders();\n }\n\n private endTransform() {\n const d = this.activeDrag;\n const img = this.lastDragImg;\n this.activeDrag = null;\n this.emitInteractionMode(\"idle\");\n this.emitCursorHint(d?.kind === \"move\" ? \"grab\" : null);\n if (!d || !img) {\n this.cb.onTransformPreview?.([]);\n this.drawTransformer();\n return;\n }\n if (d.kind === \"move\" && img.x === d.start.x && img.y === d.start.y) {\n this.cb.onTransformPreview?.([]);\n this.drawTransformer();\n return;\n }\n const { updates } = computeDragUpdates(d, img, dragTargetIsRotatedRect(this.shapes, d));\n if (d.kind === \"move\") this.resetMoveOffsets();\n this.commitTransformUpdates(updates);\n }\n}\n","import { type RefObject, useEffect, useRef } from \"react\";\nimport type { EditorShape, Point } from \"../_model/geometry\";\nimport {\n diagnoseEngineInitFailure,\n diagnoseImageLoadFailure,\n type EditorImageDiagnosis,\n} from \"../_model/imageDiagnosis\";\nimport type { RegionOverlayData } from \"../_model/overlays\";\nimport { TOOL, type Tool } from \"../_model/tools\";\nimport type { ViewSettings } from \"../_model/viewSettings\";\nimport { KonvaRenderer } from \"../_renderers/KonvaRenderer\";\nimport { PixiRenderer } from \"../_renderers/PixiRenderer\";\nimport type { EditorRenderer, EditorRendererCallbacks, Viewport } from \"../_renderers/types\";\n\n// missing은 생명주기가 아니라 ShapeEditor가 파생한다(문서는 있는데 이미지 URL이 빈 경우).\nexport type EditorImageStatus = \"loading\" | \"ready\" | \"error\" | \"missing\";\n\n/**\n * 이미지 전환 판정(테스트가 명세). currentDocId/loadedUrl=엔진 반영 상태,\n * documentId/renderedImageUrl=이번 요청. currentDocId=null이면 항상 문서 전환.\n */\nexport type ImageTransition =\n | { kind: \"none\" }\n | { kind: \"clear\" }\n | { kind: \"load\"; docChange: boolean };\n\nexport function classifyImageTransition({\n currentDocId,\n documentId,\n loadedUrl,\n renderedImageUrl,\n}: {\n currentDocId: string | null;\n documentId: string;\n loadedUrl: string | null;\n renderedImageUrl: string;\n}): ImageTransition {\n // 빈 렌더 URL = 아직 이미지가 없는 상태(문서 전환 중 시드 대기).\n if (!renderedImageUrl) {\n return currentDocId !== null || loadedUrl !== null ? { kind: \"clear\" } : { kind: \"none\" };\n }\n const docChange = currentDocId !== documentId;\n if (!docChange && loadedUrl === renderedImageUrl) return { kind: \"none\" };\n return { kind: \"load\", docChange };\n}\n\n/**\n * 문서 전환 시 이전 뷰포트를 유지할지. \"확대 유지\"는 이 엔진에 이미 확정된 뷰포트가\n * 있을 때만 의미가 있다 — 렌더러는 첫 applyViewport(fit 포함) 전까지 콘텐츠를 숨기므로,\n * 첫 이미지에서 fit을 건너뛰면 사용자가 팬/줌할 때까지 빈 캔버스만 보인다.\n */\nexport function shouldKeepViewportOnDocChange({\n keepZoomOnImageChange,\n viewportSeeded,\n}: {\n keepZoomOnImageChange: boolean;\n viewportSeeded: boolean;\n}): boolean {\n return keepZoomOnImageChange && viewportSeeded;\n}\n\n/**\n * 렌더러 엔진 생명주기 — backend당 1회 생성/파괴, 이미지 전환(문서 전환 vs 화질 스왑),\n * 휠 줌/팬·우클릭 메뉴 네이티브 리스너를 소유한다.\n *\n * 이미지 로딩/에러 상태는 별도 프리로드가 아니라 setImage 결과에서 파생한다 —\n * 판정 경로가 캔버스와 다르면(no-cors <img> 등) CORS가 깨진 환경에서 캔버스만\n * 실패하고 상태는 ready가 되는 어긋남이 생긴다. 실패 시 diagnoseImageLoadFailure로\n * 원인을 분류해 함께 올린다.\n *\n * 이미지 변경은 엔진을 재사용해 setImage로 스왑한다. 문서 전환 중에는 이전 문서의\n * 이미지·도형을 비우지만 캔버스 DOM과 렌더러 인스턴스는 유지한다.\n */\nexport function useEngineLifecycle<TMeta>({\n backend,\n hostRef,\n engineRef,\n documentId,\n renderedImageUrl,\n makeCallbacks,\n viewRef,\n readOnlyRef,\n toolRef,\n renderShapesRef,\n coordinateSizeRef,\n imageSizeRef,\n selRef,\n regionOverlayRef,\n dimmedRef,\n syncMinimap,\n setImage,\n setImageVisible,\n setReady,\n setImageStatus,\n onContextMenuRequest,\n}: {\n backend: \"konva\" | \"pixi\";\n hostRef: RefObject<HTMLDivElement | null>;\n engineRef: RefObject<EditorRenderer | null>;\n /** 문서 identity — 문서 전환 vs 화질 스왑 구분용(URL 모양과 무관한 명시적 식별자). */\n documentId: string;\n /** 실제 렌더 URL(화질 스왑 반영). */\n renderedImageUrl: string;\n /** 상호작용 컨트롤러(콜백) 팩토리 — 엔진 생성 직전에 1회 호출. */\n makeCallbacks: () => EditorRendererCallbacks;\n viewRef: RefObject<ViewSettings>;\n readOnlyRef: RefObject<boolean>;\n toolRef: RefObject<Tool>;\n /** 렌더 도형(문서 + 오버라이드 + 장식) — 이미지 전환 시 엔진 재시드용. */\n renderShapesRef: RefObject<EditorShape<TMeta>[]>;\n /** 도형 좌표계 크기(미지정 시 이미지 실제 픽셀 크기). */\n coordinateSizeRef: RefObject<{ width: number; height: number } | undefined>;\n /** 좌표공간 안에서 이미지가 차지하는 크기(미지정 시 좌표공간 전체). */\n imageSizeRef: RefObject<{ width: number; height: number } | undefined>;\n selRef: RefObject<string[]>;\n regionOverlayRef: RefObject<RegionOverlayData | null>;\n dimmedRef: RefObject<boolean>;\n syncMinimap: () => void;\n setImage: (size: { w: number; h: number } | null) => void;\n setImageVisible: (visible: boolean) => void;\n setReady: (ready: boolean) => void;\n /** error일 때만 diagnosis가 실린다(원인 분류 + 기술 근거). */\n setImageStatus: (status: EditorImageStatus, diagnosis?: EditorImageDiagnosis) => void;\n onContextMenuRequest: (menu: { x: number; y: number; img: Point }) => void;\n}) {\n // 실제 렌더 URL(화질 스왑). documentId는 문서 identity, displayImageUrl은 텍스처만.\n const displayUrlRef = useRef(renderedImageUrl);\n displayUrlRef.current = renderedImageUrl;\n const docIdRef = useRef(documentId);\n docIdRef.current = documentId;\n const loadedUrlRef = useRef<string | null>(null);\n // 엔진에 반영된 문서 identity. null = 비었거나 로드 중(다음은 항상 문서 전환).\n const lastDocIdRef = useRef<string | null>(null);\n const engineInitedRef = useRef(false);\n const previousEngineStateRef = useRef<{ imageUrl: string; viewport: Viewport } | null>(null);\n // 현재 엔진에 fit/복원으로 뷰포트를 확정한 적이 있는지(엔진 생성마다 리셋).\n const viewportSeededRef = useRef(false);\n const makeCallbacksRef = useRef(makeCallbacks);\n makeCallbacksRef.current = makeCallbacks;\n const onContextMenuRequestRef = useRef(onContextMenuRequest);\n onContextMenuRequestRef.current = onContextMenuRequest;\n\n // 엔진 초기화 + 상호작용 상태머신 — **backend당 1회 생성**.\n useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n let cancelled = false;\n let onWheel: ((e: WheelEvent) => void) | null = null;\n let onContextMenu: ((e: MouseEvent) => void) | null = null;\n\n const cb = makeCallbacksRef.current();\n const eng = backend === \"konva\" ? new KonvaRenderer(host, cb) : new PixiRenderer(host, cb);\n engineRef.current = eng;\n viewportSeededRef.current = false;\n\n (async () => {\n try {\n await eng.init();\n } catch (error) {\n // 엔진 초기화 실패(CSP unsafe-eval 차단·WebGL 불가 등) — 이미지 로드 전\n // 단계라 캔버스가 영영 비므로, 진단을 분류해 에러 오버레이로 알린다.\n if (!cancelled) setImageStatus(\"error\", diagnoseEngineInitFailure(error));\n return;\n }\n if (cancelled) return;\n // 엔진 레벨 설정은 이미지와 무관하게 항상 적용.\n eng.setFilter(viewRef.current.brightness, viewRef.current.contrast);\n eng.setRenderDefaults({ strokeWidth: viewRef.current.strokeSize });\n eng.setImageSmoothing(viewRef.current.imageSmoothing);\n eng.setTransformEnabled(!readOnlyRef.current);\n engineInitedRef.current = true;\n\n // 초기 마운트/백엔드 스왑 시 현재 이미지 로드(있을 때만 — 빈 URL이면\n // 아래 이미지 전환 이펙트가 URL 도착 시 로드한다).\n if (displayUrlRef.current) {\n // 로드 도중 URL/문서가 바뀔 수 있다 — 장부에는 엔진이 실제 로드한 캡처값만\n // 기록한다(바뀐 경우는 전환 이펙트가 처리·갱신한다).\n const targetUrl = displayUrlRef.current;\n const targetDocId = docIdRef.current;\n setImageStatus(\"loading\");\n // 렌더 중 예외(텍스처 업로드 등 미지의 실패)도 회색 화면 대신 진단으로.\n // null = 예외 — 엔진 상태를 모르므로 시드·상태 갱신을 건너뛴다.\n let loaded: boolean | null = null;\n try {\n loaded = await eng.setImage(targetUrl, coordinateSizeRef.current, imageSizeRef.current);\n } catch (error) {\n if (!cancelled && displayUrlRef.current === targetUrl) {\n setImageStatus(\"error\", diagnoseEngineInitFailure(error));\n }\n }\n if (cancelled) return;\n if (loaded !== null) {\n loadedUrlRef.current = targetUrl;\n lastDocIdRef.current = targetDocId;\n setImage({ w: eng.imageWidth, h: eng.imageHeight });\n setImageVisible(true);\n eng.setShapes(renderShapesRef.current, selRef.current);\n eng.setOverlays(\n viewRef.current.showRegionMask ? regionOverlayRef.current : null,\n dimmedRef.current,\n );\n // 백엔드 스왑(같은 이미지)·줌 유지 설정이면 이전 뷰포트 복원, 아니면 fit.\n const previousEngineState = previousEngineStateRef.current;\n if (\n previousEngineState?.viewport &&\n (previousEngineState.imageUrl === loadedUrlRef.current ||\n viewRef.current.keepZoomOnImageChange)\n ) {\n eng.applyViewport(previousEngineState.viewport);\n } else {\n eng.fit();\n }\n viewportSeededRef.current = true;\n syncMinimap();\n setReady(true);\n // 이 이펙트는 backend당 1회라 URL 변경으로 취소되지 않는다. 로드 중 URL이\n // 바뀌었으면 전환 이펙트가 상태를 소유한다 — 늦게 끝난 초기 로드(특히\n // 비동기 진단의 error)가 새 이미지의 상태를 덮어쓰지 않게 가드한다.\n const isCurrentUrl = () => displayUrlRef.current === targetUrl;\n if (loaded) {\n if (isCurrentUrl()) setImageStatus(\"ready\");\n } else {\n // 진단은 reject하지 않는다(프로브 실패는 unknown 분류로 보고).\n void diagnoseImageLoadFailure(targetUrl).then((diagnosis) => {\n if (!cancelled && isCurrentUrl()) setImageStatus(\"error\", diagnosis);\n });\n }\n }\n }\n\n // 한 휠 이벤트의 줌 배율 — 일반 휠 줌·⌘/Ctrl+휠·핀치 공통(경로별 계수 차이가\n // 있으면 \"그냥 확대와 커맨드 확대의 정도가 다른\" 문제가 생긴다).\n // |delta|≥10px(마우스 노치·빠른 핀치)는 이벤트당 exp(0.1)≈1.105배로 수렴\n // (기존 옵스의 노치당 1.1배 체감)하고, 그 미만의 잘은 delta(트랙패드 핀치,\n // 고해상도 휠의 잔 이벤트)만 0.01/px 비례로 부드럽게 줌한다. 민감도는 설정값.\n const wheelZoomFactor = (deltaY: number, sensitivity: number) =>\n Math.exp(-Math.sign(deltaY) * Math.min(Math.abs(deltaY) * 0.01, 0.1) * sensitivity);\n onWheel = (ev: WheelEvent) => {\n ev.preventDefault();\n const r = eng.dom.getBoundingClientRect();\n const sensitivity = viewRef.current.zoomSensitivity ?? 1;\n // 트랙패드 핀치는 브라우저가 ctrlKey=true 휠로 전달한다. ⌘/Ctrl+휠 포함\n // 커서 기준 부드러운 줌(지수 배율 — 핀치의 연속적인 delta에 맞춤).\n if (ev.ctrlKey || ev.metaKey) {\n eng.zoomAt(\n ev.clientX - r.left,\n ev.clientY - r.top,\n wheelZoomFactor(ev.deltaY, sensitivity),\n );\n return;\n }\n // 휠/두손가락 스크롤 동작은 \"휠 줌\" 설정이 결정한다(장치 자동 감지는\n // macOS 마우스 휠 가속 때문에 트랙패드와 구분이 불가능해 포기).\n // 켬(기본) = 줌(기존 옵스 동작), 끔 = 팬(트랙패드 사용자용).\n // 핀치·⌘/Ctrl+휠 줌은 위에서 설정과 무관하게 항상 동작.\n if (!viewRef.current.wheelZoom) {\n const v = eng.viewport;\n eng.applyViewport({\n scale: v.scale,\n x: v.x - ev.deltaX,\n y: v.y - ev.deltaY,\n });\n return;\n }\n eng.zoomAt(\n ev.clientX - r.left,\n ev.clientY - r.top,\n wheelZoomFactor(ev.deltaY, sensitivity),\n );\n };\n eng.dom.addEventListener(\"wheel\", onWheel, { passive: false });\n onContextMenu = (ev: MouseEvent) => {\n ev.preventDefault();\n // 마법봉 Alt+우클릭은 음성(−) 정제이므로 컨텍스트 메뉴를 띄우지 않는다.\n if (toolRef.current === TOOL.ASSISTANT_POINT && ev.altKey) return;\n const r = host.getBoundingClientRect();\n const hostX = ev.clientX - r.left;\n const hostY = ev.clientY - r.top;\n const v = eng.viewport;\n // 도형 선택은 앞선 pointerdown에서 반영된다. 여기서는 메뉴 위치와 이미지 좌표만 전달.\n onContextMenuRequestRef.current({\n x: hostX,\n y: hostY,\n img: { x: (hostX - v.x) / v.scale, y: (hostY - v.y) / v.scale },\n });\n };\n eng.dom.addEventListener(\"contextmenu\", onContextMenu);\n })();\n\n return () => {\n cancelled = true;\n engineInitedRef.current = false;\n previousEngineStateRef.current = {\n imageUrl: loadedUrlRef.current ?? \"\",\n viewport: eng.viewport,\n };\n engineRef.current = null;\n if (onWheel && eng.dom) eng.dom.removeEventListener(\"wheel\", onWheel);\n if (onContextMenu && eng.dom) {\n eng.dom.removeEventListener(\"contextmenu\", onContextMenu);\n }\n eng.destroy();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [backend]);\n\n // 렌더 이미지 전환 — 엔진 재사용(파괴/재생성 없음). documentId 변경(문서 전환)과\n // renderedImageUrl 스왑(고화질 토글)을 공용 처리한다. 문서 전환일 때만 이전 문서를\n // 비우고 도형/오버레이/fit을 갱신하며, 화질 스왑은 문서·뷰포트를 유지한다.\n useEffect(() => {\n const eng = engineRef.current;\n if (!eng || !engineInitedRef.current) return; // 초기/백엔드 스왑 로드는 엔진 이펙트 담당\n const transition = classifyImageTransition({\n currentDocId: lastDocIdRef.current,\n documentId,\n loadedUrl: loadedUrlRef.current,\n renderedImageUrl,\n });\n if (transition.kind === \"none\") return;\n const clearDocument = () => {\n setReady(false);\n setImageVisible(false);\n eng.clearImage();\n eng.setShapes([], []);\n eng.setOverlays(null, false);\n };\n if (transition.kind === \"clear\") {\n loadedUrlRef.current = null;\n lastDocIdRef.current = null;\n clearDocument();\n // 빈 URL은 에러가 아니라 아직 이미지가 없는 상태(시드 대기).\n setImageStatus(\"loading\");\n return;\n }\n const target = renderedImageUrl;\n // 문서 전환은 이전 이미지·도형을 즉시 비운다(잔상 없이 어두운 캔버스+로딩 딤만).\n // 화질 스왑은 같은 이미지라 유지 — 로드 완료 시 텍스처만 교체.\n if (transition.docChange) {\n // 로드 완료 전까지 null — 취소 후 재시도도 문서 전환으로 판정되게.\n lastDocIdRef.current = null;\n clearDocument();\n }\n let cancelled = false;\n (async () => {\n setImageStatus(\"loading\");\n // 렌더 중 예외(텍스처 업로드 등 미지의 실패)도 회색 화면 대신 진단으로.\n let loaded = false;\n try {\n loaded = await eng.setImage(target, coordinateSizeRef.current, imageSizeRef.current);\n } catch (error) {\n if (!cancelled && engineRef.current === eng) {\n setImageStatus(\"error\", diagnoseEngineInitFailure(error));\n }\n return;\n }\n if (cancelled || engineRef.current !== eng) return;\n loadedUrlRef.current = target;\n const finishImageStatus = () => {\n if (loaded) {\n setImageStatus(\"ready\");\n return;\n }\n // 진단은 reject하지 않는다(프로브 실패는 unknown 분류로 보고).\n void diagnoseImageLoadFailure(target).then((diagnosis) => {\n if (!cancelled) setImageStatus(\"error\", diagnosis);\n });\n };\n if (!transition.docChange) {\n // 화질 스왑 — 텍스처만 교체.\n finishImageStatus();\n return;\n }\n lastDocIdRef.current = documentId;\n setImage({ w: eng.imageWidth, h: eng.imageHeight });\n setImageVisible(true);\n eng.setShapes(renderShapesRef.current, selRef.current);\n eng.setOverlays(\n viewRef.current.showRegionMask ? regionOverlayRef.current : null,\n dimmedRef.current,\n );\n const keepViewport = shouldKeepViewportOnDocChange({\n keepZoomOnImageChange: viewRef.current.keepZoomOnImageChange,\n viewportSeeded: viewportSeededRef.current,\n });\n if (!keepViewport) eng.fit();\n viewportSeededRef.current = true;\n syncMinimap();\n setReady(true);\n finishImageStatus();\n })();\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [documentId, renderedImageUrl]);\n}\n","import {\n type PointerEvent as ReactPointerEvent,\n type WheelEvent as ReactWheelEvent,\n type RefObject,\n useCallback,\n useMemo,\n useRef,\n} from \"react\";\nimport type { EditorRenderer } from \"../_renderers/types\";\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 20;\n\n/** deltaMode/정수 여부로 트랙패드 휠을 추정(마우스 휠 대비 감도 보정용). */\nfunction isTrackpadWheel(event: WheelEvent): boolean {\n const { deltaY, deltaX, deltaMode } = event;\n\n if (deltaMode === 0) {\n const absDeltaY = Math.abs(deltaY);\n const absDeltaX = Math.abs(deltaX);\n return (\n absDeltaY < 10 || absDeltaX < 10 || !Number.isInteger(deltaY) || !Number.isInteger(deltaX)\n );\n }\n\n if (deltaMode === 1) return false;\n\n return !Number.isInteger(deltaY) || !Number.isInteger(deltaX);\n}\n\nfunction getMinimapPointer(\n event: ReactPointerEvent<HTMLDivElement> | ReactWheelEvent<HTMLDivElement>,\n) {\n const rect = event.currentTarget.getBoundingClientRect();\n return { x: event.clientX - rect.left, y: event.clientY - rect.top };\n}\n\n/**\n * 미니맵 내비게이션(패닝/줌) 훅. 미니맵 위 포인터·휠 조작을 캔버스 뷰포트로 변환한다.\n * 미니맵 사각형 갱신(syncMinimap)은 뷰포트 동기화 쪽 책임이라 여기서 다루지 않는다.\n */\nexport function useMinimapNavigation({\n engineRef,\n image,\n wheelZoom,\n minimapSize,\n}: {\n engineRef: RefObject<EditorRenderer | null>;\n image: { w: number; h: number } | null;\n wheelZoom: boolean;\n minimapSize: number;\n}) {\n const dragRef = useRef<{\n pointerId: number;\n offsetX: number;\n offsetY: number;\n } | null>(null);\n\n // 이미지 로드 전/전환 중엔 {w:0,h:0}가 올 수 있다 — 0 나눗셈이면\n // mm=Infinity, dispW=0*Infinity=NaN으로 스타일에 NaN이 흘러간다.\n const hasImage = !!image && image.w > 0 && image.h > 0;\n const mm = hasImage ? Math.min(minimapSize / image.w, minimapSize / image.h) : 1;\n const dispW = hasImage ? image.w * mm : 0;\n const dispH = hasImage ? image.h * mm : 0;\n const offX = hasImage ? (minimapSize - dispW) / 2 : 0;\n const offY = hasImage ? (minimapSize - dispH) / 2 : 0;\n\n const getMinimapViewportRect = useCallback(() => {\n const eng = engineRef.current;\n if (!eng) return null;\n const v = eng.viewport;\n return {\n x: (-v.x / v.scale) * mm + offX,\n y: (-v.y / v.scale) * mm + offY,\n width: (eng.screenSize.w / v.scale) * mm,\n height: (eng.screenSize.h / v.scale) * mm,\n };\n }, [engineRef, mm, offX, offY]);\n\n const applyMinimapPointerView = useCallback(\n (\n pointer: { x: number; y: number },\n targetScale: number,\n dragOffset?: { offsetX: number; offsetY: number },\n ) => {\n const eng = engineRef.current;\n if (!eng || !image) return;\n const viewport = getMinimapViewportRect();\n if (!viewport) return;\n\n const offsetX = dragOffset?.offsetX ?? viewport.width / 2;\n const offsetY = dragOffset?.offsetY ?? viewport.height / 2;\n const targetX = pointer.x - offsetX + viewport.width / 2;\n const targetY = pointer.y - offsetY + viewport.height / 2;\n const imageX = (targetX - offX) / mm;\n const imageY = (targetY - offY) / mm;\n\n eng.applyViewport({\n scale: targetScale,\n x: eng.screenSize.w / 2 - imageX * targetScale,\n y: eng.screenSize.h / 2 - imageY * targetScale,\n });\n },\n [engineRef, getMinimapViewportRect, image, mm, offX, offY],\n );\n\n const handleMinimapPointerDown = useCallback(\n (e: ReactPointerEvent<HTMLDivElement>) => {\n const eng = engineRef.current;\n const viewport = getMinimapViewportRect();\n if (!eng || !viewport) return;\n e.preventDefault();\n e.stopPropagation();\n\n const pointer = getMinimapPointer(e);\n const insideViewport =\n pointer.x >= viewport.x &&\n pointer.x <= viewport.x + viewport.width &&\n pointer.y >= viewport.y &&\n pointer.y <= viewport.y + viewport.height;\n const dragOffset = insideViewport\n ? { offsetX: pointer.x - viewport.x, offsetY: pointer.y - viewport.y }\n : { offsetX: viewport.width / 2, offsetY: viewport.height / 2 };\n\n dragRef.current = { pointerId: e.pointerId, ...dragOffset };\n e.currentTarget.setPointerCapture(e.pointerId);\n applyMinimapPointerView(pointer, eng.viewport.scale, dragOffset);\n },\n [applyMinimapPointerView, engineRef, getMinimapViewportRect],\n );\n\n const handleMinimapPointerMove = useCallback(\n (e: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n const eng = engineRef.current;\n if (!drag || !eng || drag.pointerId !== e.pointerId) return;\n e.preventDefault();\n e.stopPropagation();\n applyMinimapPointerView(getMinimapPointer(e), eng.viewport.scale, drag);\n },\n [applyMinimapPointerView, engineRef],\n );\n\n const endMinimapDrag = useCallback((e: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== e.pointerId) return;\n dragRef.current = null;\n if (e.currentTarget.hasPointerCapture(e.pointerId)) {\n e.currentTarget.releasePointerCapture(e.pointerId);\n }\n }, []);\n\n const handleMinimapWheel = useCallback(\n (e: ReactWheelEvent<HTMLDivElement>) => {\n const eng = engineRef.current;\n if (!eng || !wheelZoom) return;\n e.preventDefault();\n e.stopPropagation();\n\n const trackpadMultiplier = isTrackpadWheel(e.nativeEvent) ? 2.5 : 1;\n const adjustedDeltaY = e.deltaY * trackpadMultiplier;\n const scaleBy = 1.05;\n const nextScale =\n adjustedDeltaY > 0 ? eng.viewport.scale / scaleBy : eng.viewport.scale * scaleBy;\n const clampedScale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));\n applyMinimapPointerView(getMinimapPointer(e), clampedScale);\n },\n [applyMinimapPointerView, engineRef, wheelZoom],\n );\n\n const zoomCentered = useCallback(\n (factor: number) => {\n const eng = engineRef.current;\n if (!eng) return;\n const { w, h } = eng.screenSize;\n eng.zoomAt(w / 2, h / 2, factor);\n },\n [engineRef],\n );\n\n return useMemo(\n () => ({\n mm,\n offX,\n offY,\n dispW,\n dispH,\n handleMinimapPointerDown,\n handleMinimapPointerMove,\n endMinimapDrag,\n handleMinimapWheel,\n zoomCentered,\n }),\n [\n mm,\n offX,\n offY,\n dispW,\n dispH,\n handleMinimapPointerDown,\n handleMinimapPointerMove,\n endMinimapDrag,\n handleMinimapWheel,\n zoomCentered,\n ],\n );\n}\n\nexport type MinimapNavigation = ReturnType<typeof useMinimapNavigation>;\n","import { type RefObject, useCallback, useRef } from \"react\";\nimport { type EditorShape, getBBox, type Point, SHAPE_TYPE } from \"../_model/geometry\";\nimport type { EditorRenderer, Viewport } from \"../_renderers/types\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nfunction updateMinimapShapeEl<TMeta>(\n el: SVGElement | undefined,\n shape: EditorShape<TMeta>,\n points: Point[],\n) {\n if (!el || !points.length) return;\n if (shape.type === SHAPE_TYPE.POINT) {\n el.setAttribute(\"cx\", String(points[0].x));\n el.setAttribute(\"cy\", String(points[0].y));\n return;\n }\n if (shape.type === SHAPE_TYPE.RECTANGLE || shape.type === SHAPE_TYPE.ELLIPSE) {\n const b = getBBox(points);\n if (shape.type === SHAPE_TYPE.ELLIPSE) {\n el.setAttribute(\"cx\", String((b.minX + b.maxX) / 2));\n el.setAttribute(\"cy\", String((b.minY + b.maxY) / 2));\n el.setAttribute(\"rx\", String((b.maxX - b.minX) / 2));\n el.setAttribute(\"ry\", String((b.maxY - b.minY) / 2));\n return;\n }\n el.setAttribute(\"x\", String(b.minX));\n el.setAttribute(\"y\", String(b.minY));\n el.setAttribute(\"width\", String(b.maxX - b.minX));\n el.setAttribute(\"height\", String(b.maxY - b.minY));\n return;\n }\n el.setAttribute(\"points\", points.map((p) => `${p.x},${p.y}`).join(\" \"));\n}\n\n/**\n * 뷰포트 → 미니맵 사각형·줌 % 라벨·캔버스 위 DOM 오버레이(transform) 동기화와\n * 미니맵 SVG 도형의 명령형 갱신(드래그/변형 미리보기). 전부 리렌더 0 경로.\n */\nexport function useMinimapSync<TMeta>({\n engineRef,\n docRef,\n overlayRef,\n zoomLabelRef,\n minimapRectRef,\n minimapSize,\n onViewportChangeRef,\n}: {\n engineRef: RefObject<EditorRenderer | null>;\n docRef: RefObject<EditorDocument<TMeta>>;\n overlayRef: RefObject<HTMLDivElement | null>;\n zoomLabelRef: RefObject<HTMLSpanElement | null>;\n minimapRectRef: RefObject<HTMLDivElement | null>;\n minimapSize: number;\n onViewportChangeRef: RefObject<((viewport: Viewport) => void) | undefined>;\n}) {\n const minimapShapeRefs = useRef(new Map<string, SVGElement>());\n\n const registerMinimapShape = useCallback((id: string, el: SVGElement | null) => {\n if (el) minimapShapeRefs.current.set(id, el);\n else minimapShapeRefs.current.delete(id);\n }, []);\n\n const applyMinimapPreview = useCallback(\n (updates: { id: string; points: Point[] }[]) => {\n const shapes = docRef.current.getShapes();\n if (!updates.length) {\n for (const shape of shapes) {\n updateMinimapShapeEl(minimapShapeRefs.current.get(shape.id), shape, shape.points);\n }\n return;\n }\n const shapeMap = new Map(shapes.map((shape) => [shape.id, shape]));\n for (const update of updates) {\n const shape = shapeMap.get(update.id);\n if (shape) {\n updateMinimapShapeEl(minimapShapeRefs.current.get(shape.id), shape, update.points);\n }\n }\n },\n [docRef],\n );\n\n // 뷰포트 변경 시 미니맵 사각형 + 줌 % 라벨 + 캔버스 위 ROI/마스크 오버레이 동기화.\n const syncMinimap = useCallback(() => {\n const eng = engineRef.current;\n if (!eng?.imageWidth) return;\n const v = eng.viewport;\n onViewportChangeRef.current?.(v);\n // 오버레이(이미지 좌표 콘텐츠)를 뷰포트 변환으로 캔버스에 정렬.\n if (overlayRef.current) {\n overlayRef.current.style.transform = `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;\n const inverseScale = 1 / (v.scale || 1);\n overlayRef.current.style.setProperty(\"--editor-overlay-stroke\", `${inverseScale}`);\n overlayRef.current.style.setProperty(\"--editor-overlay-dash\", `${4 * inverseScale}`);\n overlayRef.current.style.setProperty(\"--editor-overlay-inverse-scale\", `${inverseScale}`);\n }\n if (zoomLabelRef.current) {\n zoomLabelRef.current.textContent = `${Math.round(v.scale * 100)}%`;\n }\n const rect = minimapRectRef.current;\n if (!rect) return;\n const mm = Math.min(minimapSize / eng.imageWidth, minimapSize / eng.imageHeight);\n const offX = (minimapSize - eng.imageWidth * mm) / 2;\n const offY = (minimapSize - eng.imageHeight * mm) / 2;\n const { w, h } = eng.screenSize;\n rect.style.left = `${(-v.x / v.scale) * mm + offX}px`;\n rect.style.top = `${(-v.y / v.scale) * mm + offY}px`;\n rect.style.width = `${(w / v.scale) * mm}px`;\n rect.style.height = `${(h / v.scale) * mm}px`;\n }, [engineRef, overlayRef, zoomLabelRef, minimapRectRef, minimapSize, onViewportChangeRef]);\n\n return { registerMinimapShape, applyMinimapPreview, syncMinimap };\n}\n","import { type RefObject, useCallback, useEffect, useRef } from \"react\";\nimport {\n canReadShapeClipboard,\n createShapeClipboardPayload,\n getClipboardCascadeOffset,\n readShapeClipboard,\n writeShapeClipboard,\n} from \"../_model/clipboard\";\nimport {\n type EditorShape,\n generateId,\n getBBox,\n isShapeEditable,\n isShapeSelectable,\n type Point,\n SHAPE_TYPE,\n} from \"../_model/geometry\";\nimport {\n buildScalarMaskRaster,\n scalarMaskToPolygons,\n shapesToFilledPolygons,\n} from \"../_model/scalarMask\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\nconst DUP_OFFSET = 12;\n\n/**\n * 선택 기반 문서 액션(키보드·컨텍스트메뉴·명령형 핸들 공용) — 복사/붙여넣기/복제/삭제/\n * z순서/합치기/넛지. 붙여넣기 오프셋 카운터를 소유한다.\n */\nexport function useSelectionActions<TMeta>({\n doc,\n selRef,\n effectiveReadOnly,\n changeSelection,\n canMergeSelection,\n clipboardDocumentId,\n clipboardScope,\n}: {\n doc: EditorDocument<TMeta>;\n selRef: RefObject<string[]>;\n effectiveReadOnly: boolean;\n changeSelection: (ids: string[]) => void;\n canMergeSelection?: (shapes: EditorShape<TMeta>[]) => boolean;\n clipboardDocumentId: string;\n clipboardScope?: string;\n}) {\n const pasteN = useRef(0);\n const mountedRef = useRef(true);\n const effectiveReadOnlyRef = useRef(effectiveReadOnly);\n const clipboardDocumentIdRef = useRef(clipboardDocumentId);\n const clipboardScopeRef = useRef(clipboardScope);\n effectiveReadOnlyRef.current = effectiveReadOnly;\n clipboardDocumentIdRef.current = clipboardDocumentId;\n clipboardScopeRef.current = clipboardScope;\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n pasteN.current = 0;\n }, [clipboardDocumentId]);\n\n const selectAll = useCallback(\n () =>\n changeSelection(\n doc\n .getShapes()\n .filter((shape) => isShapeSelectable(shape))\n .map((shape) => shape.id),\n ),\n [doc, changeSelection],\n );\n const clearSelection = useCallback(() => changeSelection([]), [changeSelection]);\n // 현재 선택 중 편집 가능한 도형(선택 기반 액션 공용).\n const getEditableSelection = useCallback(\n () => doc.getShapes().filter((s) => selRef.current.includes(s.id) && isShapeEditable(s)),\n [doc, selRef],\n );\n const deleteSelection = useCallback(() => {\n if (effectiveReadOnly || !selRef.current.length) return;\n const ids = getEditableSelection().map((s) => s.id);\n if (!ids.length) return;\n doc.remove(ids);\n changeSelection([]);\n }, [doc, effectiveReadOnly, changeSelection, getEditableSelection, selRef]);\n const copySelection = useCallback(() => {\n const copied = getEditableSelection();\n if (!copied.length) return;\n pasteN.current = 0;\n writeShapeClipboard(createShapeClipboardPayload(copied, clipboardDocumentId, clipboardScope));\n }, [clipboardDocumentId, clipboardScope, getEditableSelection]);\n const canPaste = useCallback(() => canReadShapeClipboard(clipboardScope), [clipboardScope]);\n const paste = useCallback(\n (at?: Point) => {\n if (effectiveReadOnly) return;\n const requestedDocumentId = clipboardDocumentId;\n void readShapeClipboard<TMeta>(clipboardScope).then((payload) => {\n if (\n !mountedRef.current ||\n effectiveReadOnlyRef.current ||\n clipboardDocumentIdRef.current !== requestedDocumentId ||\n clipboardScopeRef.current !== clipboardScope ||\n !payload?.shapes.length\n ) {\n return;\n }\n let dx: number;\n let dy: number;\n const copiedPoints = payload.shapes.flatMap((shape) => shape.points);\n if (at && copiedPoints.length) {\n const bounds = getBBox(copiedPoints);\n dx = at.x - (bounds.minX + bounds.maxX) / 2;\n dy = at.y - (bounds.minY + bounds.maxY) / 2;\n } else {\n const isDifferentDocument =\n !!payload.documentId && payload.documentId !== clipboardDocumentId;\n const cascade = getClipboardCascadeOffset(\n pasteN.current,\n isDifferentDocument,\n DUP_OFFSET,\n );\n dx = cascade.offset;\n pasteN.current = cascade.nextPasteCount;\n dy = dx;\n }\n const pasted = payload.shapes.map((shape) => ({\n ...shape,\n id: generateId(),\n points: shape.points.map((point) => ({ x: point.x + dx, y: point.y + dy })),\n }));\n doc.create(pasted);\n changeSelection(pasted.map((shape) => shape.id));\n });\n },\n [clipboardDocumentId, clipboardScope, doc, effectiveReadOnly, changeSelection],\n );\n const duplicate = useCallback(() => {\n if (effectiveReadOnly || !selRef.current.length) return;\n const dup = getEditableSelection().map((s) => ({\n ...s,\n id: generateId(),\n points: s.points.map((p) => ({\n x: p.x + DUP_OFFSET,\n y: p.y + DUP_OFFSET,\n })),\n }));\n if (!dup.length) return;\n doc.create(dup);\n changeSelection(dup.map((s) => s.id));\n }, [doc, effectiveReadOnly, changeSelection, getEditableSelection, selRef]);\n const bringToFront = useCallback(() => {\n if (effectiveReadOnly) return;\n const ids = getEditableSelection().map((s) => s.id);\n if (ids.length) doc.reorder(ids, \"front\");\n }, [doc, effectiveReadOnly, getEditableSelection]);\n const sendToBack = useCallback(() => {\n if (effectiveReadOnly) return;\n const ids = getEditableSelection().map((s) => s.id);\n if (ids.length) doc.reorder(ids, \"back\");\n }, [doc, effectiveReadOnly, getEditableSelection]);\n const nudgeSelection = useCallback(\n (dx: number, dy: number) => {\n if (effectiveReadOnly || !selRef.current.length) return false;\n // readOnly·편집불가 도형은 방향키 이동에서도 제외한다(다른 편집 경로와 동일 규칙).\n const sel = doc\n .getShapes()\n .filter((s) => selRef.current.includes(s.id) && isShapeEditable(s));\n if (!sel.length) return false;\n doc.update(\n sel.map((s) => ({\n ...s,\n points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })),\n })),\n );\n return true;\n },\n [doc, effectiveReadOnly, selRef],\n );\n\n /** 합치기 대상: 선택된 편집 가능 '닫힌' 도형들(2개 이상일 때 유효). */\n const getMergeTargets = useCallback(\n () =>\n getEditableSelection().filter(\n (shape) =>\n shape.type === SHAPE_TYPE.POLYGON ||\n shape.type === SHAPE_TYPE.RECTANGLE ||\n shape.type === SHAPE_TYPE.ROTATED_RECTANGLE ||\n shape.type === SHAPE_TYPE.ELLIPSE,\n ),\n [getEditableSelection],\n );\n /**\n * 선택 도형 합치기(래스터 유니온) — 붓 커밋과 같은 파이프라인으로 채운 마스크를\n * 만들어 외곽선을 다시 딴다. 결과 style/meta는 첫 도형을 따르고, 서로 떨어져\n * 있으면 조각 수만큼 폴리곤이 남는다. 원자적 replace라 undo 한 번에 복원된다.\n */\n const mergeSelection = useCallback(() => {\n if (effectiveReadOnly) return;\n const targets = getMergeTargets();\n if (targets.length < 2) return;\n if (canMergeSelection && !canMergeSelection(targets)) return;\n const raster = buildScalarMaskRaster([], 1, shapesToFilledPolygons(targets));\n if (!raster) return;\n const merged = scalarMaskToPolygons(raster, 1);\n if (!merged.length) return;\n const first = targets[0];\n const created = merged.map((points) => ({\n id: generateId(),\n type: SHAPE_TYPE.POLYGON,\n points,\n style: first.style,\n meta: first.meta,\n }));\n doc.replace(\n targets.map((shape) => shape.id),\n created,\n );\n changeSelection(created.map((shape) => shape.id));\n }, [doc, effectiveReadOnly, getMergeTargets, canMergeSelection, changeSelection]);\n\n return {\n selectAll,\n clearSelection,\n getEditableSelection,\n deleteSelection,\n copySelection,\n canPaste,\n paste,\n duplicate,\n bringToFront,\n sendToBack,\n nudgeSelection,\n getMergeTargets,\n mergeSelection,\n };\n}\n","import { type RefObject, useCallback, useEffect, useRef } from \"react\";\nimport { getBBox } from \"../_model/geometry\";\nimport {\n animateViewport,\n viewportForBBox,\n viewportForZoomBounds,\n type ZoomBounds,\n zoomBoundsFromShapes,\n} from \"../_model/viewport\";\nimport type { EditorRenderer, Viewport } from \"../_renderers/types\";\nimport type { EditorDocument } from \"./useEditorDocument\";\n\n/**\n * 뷰포트 줌 액션(애니메이션 줌·선택/도형/영역 맞춤·중앙 줌) + zoomBound prop 반영.\n * 진행 중 애니메이션 취소 핸들을 소유하고 언마운트 시 정리한다.\n */\nexport function useViewportControls<TMeta>({\n engineRef,\n doc,\n selRef,\n zoomAnimationDuration,\n zoomBound,\n ready,\n}: {\n engineRef: RefObject<EditorRenderer | null>;\n doc: EditorDocument<TMeta>;\n selRef: RefObject<string[]>;\n zoomAnimationDuration: number;\n zoomBound: ZoomBounds | undefined;\n ready: boolean;\n}) {\n const cancelZoomAnimationRef = useRef<(() => void) | null>(null);\n const previousZoomBoundRef = useRef<string | null>(null);\n\n const cancelZoomAnimation = useCallback(() => {\n cancelZoomAnimationRef.current?.();\n cancelZoomAnimationRef.current = null;\n }, []);\n\n const runViewportAnimation = useCallback(\n (target: Viewport, duration = zoomAnimationDuration) => {\n const eng = engineRef.current;\n if (!eng) return;\n cancelZoomAnimation();\n cancelZoomAnimationRef.current = animateViewport(\n eng.viewport,\n target,\n (viewport) => eng.applyViewport(viewport),\n duration,\n );\n },\n [cancelZoomAnimation, zoomAnimationDuration, engineRef],\n );\n\n const zoomToBounds = useCallback(\n (bounds: ZoomBounds, duration = zoomAnimationDuration) => {\n const eng = engineRef.current;\n if (!eng) return;\n const target = viewportForZoomBounds(bounds, eng.screenSize.w, eng.screenSize.h);\n if (target) runViewportAnimation(target, duration);\n },\n [runViewportAnimation, zoomAnimationDuration, engineRef],\n );\n\n const zoomToShapes = useCallback(\n (ids: string[], duration = zoomAnimationDuration) => {\n const shapes = doc.getShapes().filter((shape) => ids.includes(shape.id));\n const bounds = zoomBoundsFromShapes(shapes);\n if (bounds) zoomToBounds(bounds, duration);\n },\n [doc, zoomToBounds, zoomAnimationDuration],\n );\n\n const zoomToSelection = useCallback(() => {\n const sel = doc.getShapes().filter((s) => selRef.current.includes(s.id));\n if (!sel.length) return;\n const eng = engineRef.current;\n if (!eng) return;\n const target = viewportForBBox(\n getBBox(sel.flatMap((s) => s.points)),\n eng.screenSize.w,\n eng.screenSize.h,\n 80,\n );\n if (target) runViewportAnimation(target);\n }, [doc, runViewportAnimation, engineRef, selRef]);\n\n const zoomAtCenter = useCallback(\n (factor: number) => {\n const eng = engineRef.current;\n if (!eng) return;\n const { w, h } = eng.screenSize;\n eng.zoomAt(w / 2, h / 2, factor);\n },\n [engineRef],\n );\n\n useEffect(() => () => cancelZoomAnimation(), [cancelZoomAnimation]);\n\n useEffect(() => {\n if (!zoomBound) {\n previousZoomBoundRef.current = null;\n return;\n }\n if (!ready) return;\n const eng = engineRef.current;\n if (!eng?.imageWidth) return;\n const { w, h } = eng.screenSize;\n if (!w || !h) return;\n const key = JSON.stringify(zoomBound);\n if (previousZoomBoundRef.current === key) return;\n zoomToBounds(zoomBound);\n previousZoomBoundRef.current = key;\n }, [zoomBound, ready, zoomToBounds, engineRef]);\n\n return {\n cancelZoomAnimation,\n runViewportAnimation,\n zoomToBounds,\n zoomToShapes,\n zoomToSelection,\n zoomAtCenter,\n };\n}\n","\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { MagicWandIcon } from \"../Icon\";\nimport { AssistantOverlay } from \"./_components/AssistantOverlay\";\nimport { ContextMenu, type ContextMenuItem } from \"./_components/ContextMenu\";\nimport { CursorGuide } from \"./_components/CursorGuide\";\nimport { ImageStateOverlay } from \"./_components/ImageStateOverlay\";\nimport { Minimap } from \"./_components/Minimap\";\nimport {\n buildSelectionInfo,\n defaultSelectionInfoText,\n SelectionInfo,\n updateSelectionInfoBounds,\n} from \"./_components/SelectionInfo\";\nimport { MINIMAP_SIZE } from \"./_constants\";\nimport { createClipboardDocumentId } from \"./_model/clipboard\";\nimport { type EditorInteractionMode, resolveEditorCursor } from \"./_model/cursors\";\nimport {\n type EditorShape,\n generateId,\n isShapeEditable,\n isShapeSelectable,\n isShapeVisible,\n type Point,\n SHAPE_TYPE,\n} from \"./_model/geometry\";\nimport type { EditorImageDiagnosis } from \"./_model/imageDiagnosis\";\nimport { buildRegionOverlayData } from \"./_model/overlays\";\nimport type { DrawSessionChange, ShapeEditorProps } from \"./_model/props\";\nimport { mergeEditorStrings } from \"./_model/strings\";\nimport { TOOL } from \"./_model/tools\";\nimport { DEFAULT_ZOOM_ANIMATION_MS } from \"./_model/viewport\";\nimport { clampViewSettings, DEFAULT_VIEW_SETTINGS, type ViewSettings } from \"./_model/viewSettings\";\nimport type { EditorRenderer } from \"./_renderers/types\";\nimport { createInteractionController } from \"./_state/createInteractionController\";\nimport { useAssistant } from \"./_state/useAssistant\";\nimport { useDrawSession } from \"./_state/useDrawSession\";\nimport { useEditorDocument } from \"./_state/useEditorDocument\";\nimport { type EditorActionHandlers, useEditorHotkeys } from \"./_state/useEditorHotkeys\";\nimport { type EditorImageStatus, useEngineLifecycle } from \"./_state/useEngineLifecycle\";\nimport { useMinimapNavigation } from \"./_state/useMinimapNavigation\";\nimport { useMinimapSync } from \"./_state/useMinimapSync\";\nimport { useSelectionActions } from \"./_state/useSelectionActions\";\nimport { useViewportControls } from \"./_state/useViewportControls\";\n\n// 그리는 중 정보 배지용 합성 도형 id(선택 배지와 같은 오버레이를 재사용).\nconst DRAFT_PREVIEW_ID = \"__draft_preview__\";\nconst READ_ONLY_CONTEXT_MENU_IDS = new Set([\n \"copy\",\n \"selectAll\",\n \"clearSelection\",\n \"zoomToSelection\",\n]);\n\nfunction sameSelection(a: string[], b: string[]) {\n return a.length === b.length && a.every((id, i) => id === b[i]);\n}\n\n/**\n * ShapeEditor — renderer backend 기반 도형 에디터. 상호작용/문서/키보드/메뉴는 여기서 소유하고,\n * 그리기·히트테스트·뷰포트는 `EditorRenderer`(Konva/Pixi)에 위임한다. `backend`로 교체.\n * 갭(회전/꼭짓점추가 등)은 여기서 한 번 구현하면 양쪽 렌더러에 적용된다.\n */\nexport default function ShapeEditor<TMeta, TMarkerMeta = unknown>({\n document: editorDocument,\n clipboardScope,\n renderImageState,\n dimmed = false,\n selectedIds: controlledSelectedIds,\n activeTool,\n draftStyle,\n draftMeta,\n readOnly,\n disableMarquee,\n locked,\n onLockedInteraction,\n onDrawAttemptWithoutDraft,\n onIdleEscape,\n overrideShapeInteraction,\n defaultViewSettings,\n viewSettings,\n onViewSettingsChange,\n showMinimap = true,\n minimapPosition = \"bottom-left\",\n showViewSettings = true,\n getContextMenuItems,\n strings,\n viewSettingItems,\n canMergeSelection,\n brushSize = 20,\n zoomBound,\n zoomAnimationDuration = DEFAULT_ZOOM_ANIMATION_MS,\n decorationShapes,\n regionMask,\n overlayMarkers,\n renderOverlayMarker,\n onOverlayMarkerClick,\n renderImageOverlay,\n getSelectionLabel,\n hideSelectionLabelDot,\n formatSelectionInfo,\n externalTools,\n assistant,\n keymap,\n handleRef,\n backend = \"pixi\",\n onActiveToolChange,\n onSelectionChange,\n onEditingChange,\n onShapesCreated,\n onShapesUpdated,\n onShapesDeleted,\n onDrawSessionChange,\n onDraftShapeChange,\n onViewportChange,\n onShapesTransformPreview,\n}: ShapeEditorProps<TMeta, TMarkerMeta> & { backend?: \"konva\" | \"pixi\" }) {\n const hostRef = useRef<HTMLDivElement>(null);\n const engineRef = useRef<EditorRenderer | null>(null);\n const minimapRectRef = useRef<HTMLDivElement>(null);\n const overlayRef = useRef<HTMLDivElement>(null);\n const zoomLabelRef = useRef<HTMLSpanElement>(null);\n const roiMaskId = useId();\n const minimapRoiMaskId = `${roiMaskId}-minimap`;\n const [image, setImage] = useState<{ w: number; h: number } | null>(null);\n // 이미지 표시 페이드인 — 전환 시 즉시 숨겼다가(transition 없음) 로드 완료 후\n // 잔잔하게 나타난다. 화질 스왑은 건드리지 않는다(같은 이미지 유지).\n const [imageVisible, setImageVisible] = useState(false);\n const [ready, setReady] = useState(false);\n const [menu, setMenu] = useState<{\n x: number;\n y: number;\n /** 우클릭 지점(이미지 좌표) — 어시스트 지점 확장/제외용. */\n img: Point;\n } | null>(null);\n const [drawSessionState, setDrawSessionState] = useState<DrawSessionChange>({\n active: false,\n kind: \"none\",\n canUndo: false,\n canRedo: false,\n });\n const [minimapOpen, setMinimapOpen] = useState(true);\n const [settingsOpen, setSettingsOpen] = useState(false);\n\n // document=null은 빈 필드로 정규화 — 빈 렌더 URL이 정리(clear) 경로를 탄다.\n const documentId = editorDocument?.id ?? \"\";\n const imageUrl = editorDocument?.imageUrl ?? \"\";\n const displayImageUrl = editorDocument?.displayImageUrl;\n const coordinateSize = editorDocument?.coordinateSize;\n const initialShapes = editorDocument?.initialShapes;\n const initialSelectedIds = editorDocument?.initialSelectedIds;\n // 실제 렌더 URL(화질 스왑).\n const renderedImageUrl = displayImageUrl ?? imageUrl;\n const [imageStatus, setImageStatus] = useState<EditorImageStatus>(\"loading\");\n // 문서는 도착했는데 이미지 URL이 빈 경우 = 이미지가 없는 문서(원본 미수신 등) —\n // 무한 로딩이 아니라 확정 상태로 표시한다. 문서 시드 대기 중에는 로딩을 유지한다.\n const effectiveImageStatus: EditorImageStatus =\n imageStatus === \"loading\" && editorDocument !== null && !renderedImageUrl\n ? \"missing\"\n : imageStatus;\n const [imageError, setImageError] = useState<EditorImageDiagnosis | null>(null);\n const handleImageStatus = useCallback(\n (status: EditorImageStatus, diagnosis?: EditorImageDiagnosis) => {\n setImageStatus(status);\n setImageError(status === \"error\" ? (diagnosis ?? null) : null);\n },\n [],\n );\n\n const doc = useEditorDocument<TMeta>({\n onShapesCreated,\n onShapesUpdated,\n onShapesDeleted,\n });\n const [uncontrolledSelectedIds, setUncontrolledSelectedIds] = useState<string[]>([]);\n const selectedIds = controlledSelectedIds ?? uncontrolledSelectedIds;\n const selectionControlled = controlledSelectedIds !== undefined;\n const externalToolMap = useMemo(\n () => new Map((externalTools ?? []).map((tool) => [tool.id, tool])),\n [externalTools],\n );\n const externalToolMapRef = useRef(externalToolMap);\n useLayoutEffect(() => {\n externalToolMapRef.current = externalToolMap;\n }, [externalToolMap]);\n const drawSessionStateRef = useRef(drawSessionState);\n drawSessionStateRef.current = drawSessionState;\n\n // 보기 설정(에디터-로컬). defaultViewSettings는 초기값(seed)일 뿐, 이후 설정 팝오버가 소유.\n // undefined 값은 기본값을 덮어쓰지 않는다(부분 지정 seed가 brightness 등을 NaN화하는 것 방지).\n // 호스트가 준 기본값을 얹은 시드 — 마운트 초기값이자 \"초기화\"가 되돌릴 기준.\n // 라이브러리 기본값으로 되돌리면 호스트가 의도한 기본과 어긋난다.\n // 범위(VIEW_SETTING_RANGES)를 벗어난 값은 클램프한다 — 구버전 저장값도 자동 교정된다.\n const seededDefaults = useMemo<ViewSettings>(() => {\n const defined = Object.fromEntries(\n Object.entries(defaultViewSettings ?? {}).filter(([, v]) => v !== undefined),\n ) as Partial<ViewSettings>;\n return clampViewSettings({ ...DEFAULT_VIEW_SETTINGS, ...defined });\n }, [defaultViewSettings]);\n const seededDefaultsRef = useRef(seededDefaults);\n seededDefaultsRef.current = seededDefaults;\n const [view, setView] = useState<ViewSettings>(() => seededDefaultsRef.current);\n const updateView = useCallback(\n (patch: Partial<ViewSettings>) => setView((v) => clampViewSettings({ ...v, ...patch })),\n [],\n );\n\n // UI 문자열(기본 한국어 + 호스트 부분 재정의).\n const S = useMemo(() => mergeEditorStrings(strings), [strings]);\n\n // 외부 → 에디터 동기화(viewSettings prop). 값이 실제로 다를 때만 반영해\n // 동기화 루프(에디터 변경 → 호스트 스토어 → prop → 에디터)를 끊는다.\n useEffect(() => {\n if (!viewSettings) return;\n const clamped = clampViewSettings(viewSettings);\n setView((v) => {\n const entries = Object.entries(clamped).filter(\n ([key, value]) => value !== undefined && v[key as keyof ViewSettings] !== value,\n );\n if (!entries.length) return v;\n return { ...v, ...Object.fromEntries(entries) };\n });\n }, [viewSettings]);\n\n // 에디터 → 외부 통지(onViewSettingsChange). 마운트 시드는 변경이 아니므로 건너뛴다.\n const onViewSettingsChangeRef = useRef(onViewSettingsChange);\n onViewSettingsChangeRef.current = onViewSettingsChange;\n const viewNotifiedRef = useRef(false);\n useEffect(() => {\n if (!viewNotifiedRef.current) {\n viewNotifiedRef.current = true;\n return;\n }\n onViewSettingsChangeRef.current?.(view);\n }, [view]);\n\n // 영역 마스크 → 딤·윤곽 벡터(렌더러 오버레이용, 이미지↔도형 사이. 윤곽은 화면고정).\n const regionOverlay = useMemo(() => {\n // 빈 마스크(창·가림 모두 없음) 판정은 buildRegionOverlayData가 담당한다.\n if (!image || !regionMask) return null;\n return buildRegionOverlayData(regionMask, image.w, image.h);\n }, [image, regionMask]);\n const regionOverlayRef = useRef(regionOverlay);\n regionOverlayRef.current = regionOverlay;\n const dimmedRef = useRef(dimmed);\n dimmedRef.current = dimmed;\n const loadedImageRef = useRef(image);\n loadedImageRef.current = image;\n const coordinateSizeRef = useRef(coordinateSize);\n coordinateSizeRef.current = coordinateSize;\n // 이미지 배치 크기는 coordinateSize의 하위 옵션 — 좌표공간 없이는 존재할 수 없다.\n const imageSizeRef = useRef(coordinateSize?.imageSize);\n imageSizeRef.current = coordinateSize?.imageSize;\n\n // 콜백이 최신값을 읽도록 ref 미러(엔진 콜백은 init 때 1회 캡처).\n const selRef = useRef(selectedIds);\n useLayoutEffect(() => {\n selRef.current = selectedIds;\n }, [selectedIds]);\n const toolRef = useRef(activeTool);\n toolRef.current = activeTool;\n const draftRef = useRef(draftStyle);\n draftRef.current = draftStyle;\n const draftMetaRef = useRef(draftMeta);\n draftMetaRef.current = draftMeta;\n const brushSizeRef = useRef(brushSize);\n brushSizeRef.current = brushSize;\n const simplifyEpsilonRef = useRef(view.simplifyStrength);\n simplifyEpsilonRef.current = view.simplifyStrength;\n // 완료(locked) 상태는 편집 관점에서 읽기전용과 동일하다 — 변이 경로는\n // effectiveReadOnly로 막고, 편집 시도(도형 드래그·정점 편집 진입·편집 단축키·\n // 명령형 핸들의 문서 변경)는 onLockedInteraction으로 호스트에 알린다.\n const effectiveReadOnly = !!readOnly || !!locked;\n const readOnlyRef = useRef(effectiveReadOnly);\n readOnlyRef.current = effectiveReadOnly;\n const disableMarqueeRef = useRef(disableMarquee);\n disableMarqueeRef.current = disableMarquee;\n const lockedRef = useRef(locked);\n lockedRef.current = locked;\n const onLockedInteractionRef = useRef(onLockedInteraction);\n onLockedInteractionRef.current = onLockedInteraction;\n const hostReadOnlyRef = useRef(readOnly);\n hostReadOnlyRef.current = readOnly;\n // 잠금으로 막힌 편집 시도면 호스트에 알리고 true. 대상이 없으면 조용히 false —\n // 선택 없는 단축키 등이 호스트 단축키와 겹치지 않게.\n const rejectLockedEdit = useCallback((hasTarget = true): boolean => {\n if (hostReadOnlyRef.current || !lockedRef.current || !hasTarget) return false;\n onLockedInteractionRef.current?.();\n return true;\n }, []);\n const onDrawAttemptWithoutDraftRef = useRef(onDrawAttemptWithoutDraft);\n onDrawAttemptWithoutDraftRef.current = onDrawAttemptWithoutDraft;\n const overrideInteractionRef = useRef(overrideShapeInteraction);\n overrideInteractionRef.current = overrideShapeInteraction;\n const docRef = useRef(doc);\n docRef.current = doc;\n const spaceRef = useRef(false);\n const interactionModeRef = useRef<EditorInteractionMode>(\"idle\");\n const rendererCursorHintRef = useRef<string | null>(null);\n const applyEditorCursor = useCallback(() => {\n const eng = engineRef.current;\n if (!eng) return;\n const tool = toolRef.current;\n const externalTool = externalToolMapRef.current.get(tool);\n const session = drawSessionStateRef.current;\n eng.setCursor(\n resolveEditorCursor({\n tool,\n externalToolCursor: externalTool?.cursor,\n isSpacePressed: spaceRef.current,\n interactionMode: interactionModeRef.current,\n rendererCursorHint: rendererCursorHintRef.current,\n isPolygonDrawing: session.kind === \"polygon\" && session.active,\n }),\n );\n }, []);\n const setEditorInteractionMode = useCallback(\n (mode: EditorInteractionMode) => {\n if (interactionModeRef.current === mode) return;\n interactionModeRef.current = mode;\n applyEditorCursor();\n },\n [applyEditorCursor],\n );\n const setEditorCursorHint = useCallback(\n (cursor: string | null) => {\n if (rendererCursorHintRef.current === cursor) return;\n rendererCursorHintRef.current = cursor;\n applyEditorCursor();\n },\n [applyEditorCursor],\n );\n const normalizeSelection = useCallback((ids: string[]) => {\n const seen = new Set<string>();\n const shapes = new Map(docRef.current.getShapes().map((s) => [s.id, s]));\n return ids.filter((id) => {\n if (seen.has(id)) return false;\n seen.add(id);\n const shape = shapes.get(id);\n if (!shape) return false;\n // 호스트 상호작용 오버라이드(숨김/비활성) 반영 — 숨겨진 도형은 선택 불가.\n const ov = overrideInteractionRef.current?.(shape);\n const effective = ov ? { ...shape, interaction: { ...shape.interaction, ...ov } } : shape;\n return isShapeSelectable(effective);\n });\n }, []);\n const changeSelection = useCallback(\n (ids: string[]) => {\n const next = normalizeSelection(ids);\n if (sameSelection(selRef.current, next)) return;\n if (!selectionControlled) setUncontrolledSelectedIds(next);\n engineRef.current?.setSelection(next);\n onSelectionChange?.(next);\n },\n [normalizeSelection, onSelectionChange, selectionControlled],\n );\n const selectRef = useRef(changeSelection);\n selectRef.current = changeSelection;\n\n // 폴리곤 정점 편집모드(옵스식). 더블클릭으로 진입, 툴 변경/선택 해제/Esc로 종료.\n const [editingId, setEditingId] = useState<string | null>(null);\n const enterEdit = useCallback((id: string) => setEditingId(id), []);\n const enterEditRef = useRef(enterEdit);\n enterEditRef.current = enterEdit;\n const editingIdRef = useRef<string | null>(null);\n editingIdRef.current = editingId;\n\n useEffect(() => {\n if (!selectionControlled) return;\n const next = normalizeSelection(controlledSelectedIds);\n if (!sameSelection(controlledSelectedIds, next)) onSelectionChange?.(next);\n }, [\n controlledSelectedIds,\n doc.shapes,\n normalizeSelection,\n onSelectionChange,\n selectionControlled,\n ]);\n\n const onViewportChangeRef = useRef(onViewportChange);\n onViewportChangeRef.current = onViewportChange;\n const { registerMinimapShape, applyMinimapPreview, syncMinimap } = useMinimapSync<TMeta>({\n engineRef,\n docRef,\n overlayRef,\n zoomLabelRef,\n minimapRectRef,\n minimapSize: MINIMAP_SIZE,\n onViewportChangeRef,\n });\n\n // 선택 정보 배지 — 드래그/변형 중 bbox 위치·정보텍스트를 ref로 즉시 갱신(문서 커밋 전).\n const selectionInfoRefs = useRef(new Map<string, HTMLDivElement>());\n const formatSelectionInfoRef = useRef(formatSelectionInfo);\n formatSelectionInfoRef.current = formatSelectionInfo;\n const registerSelectionInfo = useCallback((id: string, el: HTMLDivElement | null) => {\n if (el) selectionInfoRefs.current.set(id, el);\n else selectionInfoRefs.current.delete(id);\n }, []);\n // 그리는 중 정보 배지의 합성 도형(문서에 없음) — preview 갱신 시 lookup에 섞는다.\n const drawPreviewRef = useRef<EditorShape<TMeta> | null>(null);\n const [drawPreviewShape, setDrawPreviewShape] = useState<EditorShape<TMeta> | null>(null);\n const applySelectionInfoPreview = useCallback((updates: { id: string; points: Point[] }[]) => {\n if (!updates.length) return;\n const shapeMap = new Map(docRef.current.getShapes().map((s) => [s.id, s]));\n if (drawPreviewRef.current) {\n shapeMap.set(drawPreviewRef.current.id, drawPreviewRef.current);\n }\n for (const { id, points } of updates) {\n const el = selectionInfoRefs.current.get(id);\n const shape = shapeMap.get(id);\n if (!el || !shape) continue;\n const dim = updateSelectionInfoBounds(el, points);\n if (dim) {\n const info = buildSelectionInfo(shape, points);\n dim.textContent = formatSelectionInfoRef.current?.(info) ?? defaultSelectionInfoText(info);\n }\n }\n }, []);\n const handleTransformPreview = useCallback(\n (updates: { id: string; points: Point[] }[]) => {\n applyMinimapPreview(updates);\n applySelectionInfoPreview(updates);\n onShapesTransformPreview?.(updates);\n },\n [applyMinimapPreview, applySelectionInfoPreview, onShapesTransformPreview],\n );\n\n // 박스 드래그 그리는 중 정보 배지(좌상단 클래스 + 우하단 W×H). 선택 배지 오버레이를\n // 재사용한다: 시작/종료 때만 합성 도형을 React에 마운트/언마운트하고, 이동 중에는\n // 선택 배지와 동일한 ref 기반 DOM 갱신으로 위치·크기 텍스트만 즉시 반영한다.\n const handleDrawPreview = useCallback(\n (info: { type: EditorShape<TMeta>[\"type\"]; points: Point[] } | null) => {\n onDraftShapeChange?.(info ? { ...info, meta: draftMetaRef.current } : null);\n if (!info || !draftRef.current) {\n if (drawPreviewRef.current) {\n drawPreviewRef.current = null;\n setDrawPreviewShape(null);\n }\n return;\n }\n const shape = {\n id: DRAFT_PREVIEW_ID,\n type: info.type,\n points: info.points,\n style: draftRef.current,\n meta: draftMetaRef.current,\n } as EditorShape<TMeta>;\n const wasActive = drawPreviewRef.current !== null;\n drawPreviewRef.current = shape;\n if (wasActive) {\n applySelectionInfoPreview([{ id: DRAFT_PREVIEW_ID, points: info.points }]);\n } else {\n setDrawPreviewShape(shape);\n }\n },\n [applySelectionInfoPreview, onDraftShapeChange],\n );\n\n const createShape = useCallback(\n (type: EditorShape<TMeta>[\"type\"], points: Point[]) => {\n const style = draftRef.current;\n if (!style || readOnlyRef.current) return;\n const id = generateId();\n docRef.current.create({ id, type, points, style, meta: draftMeta });\n selectRef.current([id]);\n },\n [draftMeta],\n );\n const createRef = useRef(createShape);\n createRef.current = createShape;\n const handleDrawSessionChange = useCallback(\n (session: DrawSessionChange) => {\n setDrawSessionState(session);\n onDrawSessionChange?.(session);\n },\n [onDrawSessionChange],\n );\n\n const drawSession = useDrawSession<TMeta>({\n toolRef,\n selRef,\n docRef,\n readOnlyRef,\n draftRef,\n brushSizeRef,\n simplifyEpsilonRef,\n draftMeta,\n engineRef,\n onDrawSessionChange: handleDrawSessionChange,\n onDraftShapeChange,\n changeSelection,\n createShape,\n });\n // cb(상호작용 컨트롤러)에서 쓰는 그리기 세션 메서드는 drawSessionRef로 최신값을 읽는다.\n const drawSessionRef = useRef(drawSession);\n drawSessionRef.current = drawSession;\n const {\n reset: resetDraftPath,\n undoSession,\n redoSession,\n canUndoSession,\n canRedoSession,\n hasDraftSession,\n hasDraftPoints,\n commitDraftSession: completeDraftPath,\n setBrushScalarMode,\n getBrushScalarMode,\n hasBrushSession: getBrushSessionActive,\n commitBrush,\n cancelBrush,\n beginBrushEditFromSelection,\n deleteDraftSelectedPoints,\n handleToolChange,\n handleBrushSelectionChange,\n } = drawSession;\n\n // ── AI 어시스트 세션(호스트 assistant.infer 위임) ──\n const assistantRef = useRef(assistant);\n assistantRef.current = assistant;\n const assistantSession = useAssistant<TMeta>({\n docRef,\n draftRef,\n draftMeta,\n changeSelection,\n assistantRef,\n });\n const assistantSessionRef = useRef(assistantSession);\n assistantSessionRef.current = assistantSession;\n\n // ── 선택 기반 액션(키보드·컨텍스트메뉴·명령형 핸들 공용) ──\n const clipboardDocumentId = useMemo(() => createClipboardDocumentId(documentId), [documentId]);\n const effectiveClipboardScope = clipboardScope ?? clipboardDocumentId;\n const {\n selectAll,\n clearSelection,\n deleteSelection,\n copySelection,\n canPaste,\n paste,\n duplicate,\n bringToFront,\n sendToBack,\n nudgeSelection,\n getMergeTargets,\n mergeSelection,\n } = useSelectionActions<TMeta>({\n doc,\n selRef,\n effectiveReadOnly,\n changeSelection,\n canMergeSelection,\n clipboardDocumentId,\n clipboardScope: effectiveClipboardScope,\n });\n const { zoomToBounds, zoomToShapes, zoomToSelection, zoomAtCenter } = useViewportControls<TMeta>({\n engineRef,\n doc,\n selRef,\n zoomAnimationDuration,\n zoomBound,\n ready,\n });\n\n // 명령형 핸들(ShapeEditorHandle과 동일) — 데모 엔진 교체 시 그대로 동작.\n useImperativeHandle(\n handleRef,\n () => ({\n // 드래그·드로잉 중 고빈도 프리뷰 — React 상태를 우회해 렌더러에 즉시 반영한다.\n // ref만 읽으므로 핸들 재생성 없이 항상 최신 컨텍스트로 동작한다.\n previewRegionMask: (mask) => {\n const img = loadedImageRef.current;\n if (!img) return;\n // mask가 있으면 빈 판정 포함 build에 위임, null이면 prop 오버레이로 복귀.\n const overlay = mask\n ? buildRegionOverlayData(mask, img.w, img.h)\n : regionOverlayRef.current;\n engineRef.current?.setRegionOverlay(viewRef.current.showRegionMask ? overlay : null);\n },\n // 문서 히스토리는 완료 뒤에도 남아 있다 — 잠금·읽기전용이면 되돌리지 않는다.\n undo: () => {\n if (readOnlyRef.current) return;\n if (!undoSession()) doc.undo();\n },\n redo: () => {\n if (readOnlyRef.current) return;\n if (!redoSession()) doc.redo();\n },\n canUndo: () => canUndoSession() || doc.canUndo(),\n canRedo: () => canRedoSession() || doc.canRedo(),\n undoSession,\n redoSession,\n canUndoSession,\n canRedoSession,\n hasDraftSession,\n cancelDraftSession: resetDraftPath,\n commitDraftSession: completeDraftPath,\n setSelection: changeSelection,\n createShapes: (shapes) => {\n if (!shapes.length || rejectLockedEdit()) return;\n doc.create(shapes);\n changeSelection(shapes.map((s) => s.id));\n },\n updateShapes: (shapes) => {\n if (!shapes.length || rejectLockedEdit()) return;\n doc.update(shapes);\n },\n deleteShapes: (ids) => {\n if (!ids.length || rejectLockedEdit()) return;\n doc.remove(ids);\n },\n getShapes: doc.getShapes,\n selectAll,\n clearSelection,\n deleteSelection,\n copySelection,\n paste,\n duplicate,\n bringToFront,\n sendToBack,\n zoomFit: () => engineRef.current?.fit(),\n zoom100: () => engineRef.current?.zoom100(),\n zoomIn: () => {\n const eng = engineRef.current;\n if (!eng) return;\n const { w, h } = eng.screenSize;\n eng.zoomAt(w / 2, h / 2, 1.2);\n },\n zoomOut: () => {\n const eng = engineRef.current;\n if (!eng) return;\n const { w, h } = eng.screenSize;\n eng.zoomAt(w / 2, h / 2, 1 / 1.2);\n },\n zoomToSelection,\n zoomToShapes,\n zoomToBounds,\n brush: {\n setScalarMode: setBrushScalarMode,\n getScalarMode: getBrushScalarMode,\n hasSession: getBrushSessionActive,\n commit: commitBrush,\n cancel: cancelBrush,\n beginEditFromSelection: beginBrushEditFromSelection,\n },\n }),\n [\n doc,\n changeSelection,\n rejectLockedEdit,\n undoSession,\n redoSession,\n completeDraftPath,\n resetDraftPath,\n commitBrush,\n cancelBrush,\n selectAll,\n clearSelection,\n deleteSelection,\n copySelection,\n paste,\n duplicate,\n bringToFront,\n sendToBack,\n zoomToSelection,\n zoomToShapes,\n zoomToBounds,\n setBrushScalarMode,\n getBrushScalarMode,\n getBrushSessionActive,\n beginBrushEditFromSelection,\n ],\n );\n\n const viewRef = useRef(view);\n viewRef.current = view;\n\n // 엔진 생명주기 — backend당 1회 생성, 이미지 전환/화질 스왑, 휠 줌·우클릭 리스너,\n // 이미지 로딩 상태 프리로드. 상호작용 컨트롤러는 엔진 생성 직전 팩토리로 만든다.\n const makeRendererCallbacks = useCallback(\n () =>\n createInteractionController<TMeta>({\n engineRef,\n toolRef,\n externalToolMapRef,\n spaceRef,\n docRef,\n selRef,\n draftRef,\n readOnlyRef,\n disableMarqueeRef,\n lockedRef,\n onLockedInteraction: () => onLockedInteractionRef.current?.(),\n onDrawAttemptWithoutDraft: () => onDrawAttemptWithoutDraftRef.current?.(),\n createRef,\n selectRef,\n enterEditRef,\n editingIdRef,\n drawSessionRef,\n assistantRef: assistantSessionRef,\n setCursorHint: setEditorCursorHint,\n setInteractionMode: setEditorInteractionMode,\n syncMinimap,\n onTransformPreview: handleTransformPreview,\n onDrawPreview: handleDrawPreview,\n }),\n [\n setEditorCursorHint,\n setEditorInteractionMode,\n syncMinimap,\n handleTransformPreview,\n handleDrawPreview,\n ],\n );\n // renderShapes 메모(아래)보다 먼저 선언 — 라이프사이클 훅이 ref 객체만 캡처하고\n // .current는 이펙트 시점에 읽으므로 렌더 후반 대입으로 충분하다.\n const renderShapesRef = useRef<EditorShape<TMeta>[]>([]);\n useEngineLifecycle<TMeta>({\n backend,\n hostRef,\n engineRef,\n documentId,\n renderedImageUrl,\n makeCallbacks: makeRendererCallbacks,\n viewRef,\n readOnlyRef,\n toolRef,\n renderShapesRef,\n coordinateSizeRef,\n imageSizeRef,\n selRef,\n regionOverlayRef,\n dimmedRef,\n syncMinimap,\n setImage,\n setImageVisible,\n setReady,\n setImageStatus: handleImageStatus,\n onContextMenuRequest: setMenu,\n });\n\n // 렌더 시점 상호작용 오버라이드 적용본. 문서(undo 히스토리)는 불변으로 두고\n // 엔진/미니맵/선택배지에만 반영한다 — 가시성 토글이 undo에 안 섞이게.\n // 장식 도형(decorationShapes)도 여기서만 합류한다 — 문서 밖이라 히스토리·선택·\n // getShapes에 안 섞이고, 상호작용은 강제로 잠근다.\n const renderShapes = useMemo(() => {\n const docShapes = !overrideShapeInteraction\n ? doc.shapes\n : doc.shapes.map((s) => {\n const ov = overrideShapeInteraction(s);\n return ov ? { ...s, interaction: { ...s.interaction, ...ov } } : s;\n });\n if (!decorationShapes?.length) return docShapes;\n const decorations = decorationShapes.map((s) => ({\n ...s,\n interaction: {\n ...s.interaction,\n selectable: false,\n draggable: false,\n editable: false,\n hitTestDisabled: true,\n },\n }));\n return [...decorations, ...docShapes];\n }, [doc.shapes, overrideShapeInteraction, decorationShapes]);\n renderShapesRef.current = renderShapes;\n\n // 문서 변경은 도형 전체를 다시 그리고 미니맵을 동기화한다.\n useEffect(() => {\n engineRef.current?.setShapes(renderShapes, selRef.current);\n syncMinimap();\n }, [renderShapes, syncMinimap]);\n\n // 선택만 바뀐 경우 이미 그린 도형은 유지하고 선택 표시만 갱신한다.\n useEffect(() => {\n engineRef.current?.setSelection(selectedIds);\n }, [selectedIds]);\n\n // 폴리곤 편집모드 → 엔진 반영.\n useEffect(() => {\n engineRef.current?.setEditing(editingId);\n }, [editingId, ready]);\n\n // 편집모드 진입/해제 통지(호스트 안내 툴바용).\n const onEditingChangeRef = useRef(onEditingChange);\n onEditingChangeRef.current = onEditingChange;\n useEffect(() => {\n onEditingChangeRef.current?.(editingId);\n }, [editingId]);\n\n // 툴이 바뀌면 편집모드 해제.\n useEffect(() => {\n setEditingId(null);\n }, [activeTool]);\n\n // 선택이 편집 대상 단일 폴리곤이 아니게 되면 편집모드 해제.\n useEffect(() => {\n if (editingId && (selectedIds.length !== 1 || selectedIds[0] !== editingId)) {\n setEditingId(null);\n }\n }, [selectedIds, editingId]);\n\n // 보기 설정(밝기·대비·선두께·픽셀화)을 엔진에 동기. 각 setter는 값이 같으면 no-op.\n useEffect(() => {\n const eng = engineRef.current;\n if (!eng) return;\n eng.setFilter(view.brightness, view.contrast);\n eng.setRenderDefaults({ strokeWidth: view.strokeSize });\n eng.setImageSmoothing(view.imageSmoothing);\n syncMinimap();\n }, [view.brightness, view.contrast, view.strokeSize, view.imageSmoothing, syncMinimap]);\n\n // ROI 딤을 렌더러 오버레이(이미지↔도형 사이)에 반영.\n // useLayoutEffect — 드래그 중 regionMask가 호스트 왕복으로 프레임마다 갱신되는데,\n // useEffect(페인트 후)면 도형·핸들보다 오버레이가 한 프레임 늦게 따라온다.\n // 페인트 전에 렌더러에 반영해 같은 프레임의 렌더 틱에 함께 태운다.\n useLayoutEffect(() => {\n if (!ready) return;\n engineRef.current?.setOverlays(view.showRegionMask ? regionOverlay : null, dimmed);\n }, [ready, regionOverlay, view.showRegionMask, dimmed]);\n\n useEffect(() => {\n if (!ready || !image) return;\n syncMinimap();\n }, [ready, image, view.showRegionMask, regionMask, syncMinimap]);\n\n useEffect(() => {\n if (!ready) return;\n engineRef.current?.setTransformEnabled(!effectiveReadOnly && activeTool !== TOOL.BRUSH);\n }, [effectiveReadOnly, ready, activeTool]);\n\n // 잠기면 정점 편집모드를 빠져나온다(정점 핸들이 남아 편집처럼 보이지 않게).\n useEffect(() => {\n if (locked) setEditingId(null);\n }, [locked]);\n\n useEffect(() => {\n handleToolChange(activeTool, externalToolMapRef.current.has(activeTool));\n }, [activeTool, handleToolChange]);\n\n // 도구가 바뀌면 어시스트 세션을 확정(만든 도형은 유지, 프롬프트 마커만 정리).\n // 어시스트 도구 사이(박스↔포인트) 전환도 새 세션으로 시작하도록 매번 확정한다.\n const finalizeAssistant = assistantSession.finalize;\n useEffect(() => {\n finalizeAssistant();\n }, [activeTool, finalizeAssistant]);\n\n useEffect(() => {\n interactionModeRef.current = \"idle\";\n rendererCursorHintRef.current = null;\n applyEditorCursor();\n }, [activeTool, backend, applyEditorCursor]);\n\n useEffect(() => {\n handleBrushSelectionChange(selectedIds, effectiveReadOnly);\n }, [selectedIds, activeTool, effectiveReadOnly, handleBrushSelectionChange]);\n\n useEffect(() => {\n if (!ready) return;\n applyEditorCursor();\n }, [activeTool, drawSessionState, externalToolMap, ready, applyEditorCursor]);\n\n // 초기 시드 — 문서 identity당 1회(이미지 도착·화질 스왑은 재시드 없음, undo 보존).\n // 초기 선택은 ref로 읽어 값 변경이 재시드를 유발하지 않게 한다.\n const initialSelectedIdsRef = useRef(initialSelectedIds);\n initialSelectedIdsRef.current = initialSelectedIds;\n const hasDocument = editorDocument !== null;\n const seedRef = useRef<string | null>(null);\n useEffect(() => {\n const seedKey = hasDocument ? documentId : null;\n if (seedRef.current === seedKey) return;\n seedRef.current = seedKey;\n setMenu(null);\n setEditingId(null);\n interactionModeRef.current = \"idle\";\n rendererCursorHintRef.current = null;\n doc.reset(hasDocument ? (initialShapes ?? []) : []);\n // doc.reset이 동기 미러를 갱신한 뒤라 새 문서 기준으로 정규화된다.\n changeSelection(hasDocument ? (initialSelectedIdsRef.current ?? []) : []);\n resetDraftPath();\n finalizeAssistant();\n applyEditorCursor();\n }, [\n hasDocument,\n documentId,\n initialShapes,\n doc.reset,\n changeSelection,\n resetDraftPath,\n finalizeAssistant,\n applyEditorCursor,\n ]);\n\n // 편집모드 Delete: 선택된 정점만 제거(도형 삭제 아님). 남는 점이 최소 개수\n // (폴리곤 3, 라인 2) 미만이면 false를 돌려 기존 도형 삭제로 폴백한다.\n const deleteEditingVertices = useCallback((): boolean => {\n const id = editingIdRef.current;\n if (!id || effectiveReadOnly) return false;\n const eng = engineRef.current;\n const selected = new Set(eng?.getVertexSelection() ?? []);\n if (!selected.size) return false;\n const shape = docRef.current.getShapes().find((s) => s.id === id);\n if (!shape) return false;\n const keep = shape.points.filter((_, i) => !selected.has(i));\n const min = shape.type === SHAPE_TYPE.LINE ? 2 : 3;\n if (keep.length < min) return false;\n docRef.current.update([{ ...shape, points: keep }]);\n eng?.setVertexSelection([]);\n return true;\n }, [effectiveReadOnly]);\n\n const hasEditableSelection = () =>\n doc.getShapes().some((s) => selRef.current.includes(s.id) && isShapeEditable(s));\n\n // ── 키보드 단축키(기본 내장 + keymap prop으로 재정의/비활성) ──\n const hotkeyActions: EditorActionHandlers = {\n undo: () => {\n if (effectiveReadOnly) return;\n if (!undoSession()) doc.undo();\n },\n redo: () => {\n if (effectiveReadOnly) return;\n if (!redoSession()) doc.redo();\n },\n selectAll,\n copy: copySelection,\n cut: () => {\n if (rejectLockedEdit(hasEditableSelection())) return;\n copySelection();\n deleteSelection();\n },\n paste: () => {\n if (rejectLockedEdit(canPaste())) return;\n paste();\n },\n duplicate: () => {\n if (rejectLockedEdit(hasEditableSelection())) return;\n duplicate();\n },\n delete: () => {\n if (rejectLockedEdit(hasEditableSelection())) return;\n if (hasDraftPoints() && deleteDraftSelectedPoints()) return;\n if (deleteEditingVertices()) return;\n deleteSelection();\n },\n cancel: () => {\n // 외부 툴이 소비하면 종료, false(취소할 것 없음)면 아래 사슬로 계속.\n const externalTool = externalToolMapRef.current.get(toolRef.current);\n if (externalTool?.onCancel && externalTool.onCancel() !== false) {\n return;\n }\n if (assistantSession.isActive()) {\n assistantSession.cancel();\n return;\n }\n if (hasDraftSession()) {\n resetDraftPath();\n return;\n }\n if (editingId) {\n setEditingId(null);\n return;\n }\n if (selRef.current.length) {\n clearSelection();\n return;\n }\n // 취소할 것이 없음 — 호스트 후속 동작(툴 복귀/에디터 닫기, 옵스 Esc 사슬 꼬리).\n onIdleEscape?.();\n },\n commitDraft: () => {\n if (assistantSession.isActive()) {\n assistantSession.finalize();\n return;\n }\n if (hasDraftSession()) {\n completeDraftPath();\n return;\n }\n // 옵스식 Enter: 그리기 중이 아니면 폴리곤 편집모드 완료/시작 토글.\n if (effectiveReadOnly) return;\n if (editingId) {\n setEditingId(null);\n return;\n }\n const sel = selRef.current;\n if (sel.length !== 1) return;\n const shape = docRef.current.getShapes().find((s) => s.id === sel[0]);\n const editable =\n shape &&\n (shape.type === SHAPE_TYPE.POLYGON || shape.type === SHAPE_TYPE.LINE) &&\n shape.interaction?.editable !== false &&\n !shape.readOnly;\n if (editable) setEditingId(sel[0]);\n },\n bringToFront,\n sendToBack,\n zoomIn: () => zoomAtCenter(1.2),\n zoomOut: () => zoomAtCenter(1 / 1.2),\n zoom100: () => engineRef.current?.zoom100(),\n zoomFit: () => engineRef.current?.fit(),\n toggleMinimap: () => setMinimapOpen((o) => !o),\n toggleCursorGuide: () => setView((v) => ({ ...v, showCursorGuide: !v.showCursorGuide })),\n togglePixelation: () => setView((v) => ({ ...v, imageSmoothing: !v.imageSmoothing })),\n selectTool: () => onActiveToolChange?.(TOOL.SELECT),\n rectangleTool: () => onActiveToolChange?.(TOOL.RECTANGLE),\n rotatedRectangleTool: () => onActiveToolChange?.(TOOL.ROTATED_RECTANGLE),\n circleTool: () => onActiveToolChange?.(TOOL.CIRCLE),\n polygonTool: () => onActiveToolChange?.(TOOL.POLYGON),\n pathTool: () => onActiveToolChange?.(TOOL.PATH),\n brushTool: () => onActiveToolChange?.(TOOL.BRUSH),\n pointTool: () => onActiveToolChange?.(TOOL.POINT),\n };\n useEditorHotkeys({\n keymap,\n hostRef,\n actions: hotkeyActions,\n spaceRef,\n onSpaceDown: () => {\n // 스페이스=무조건 팬: 핸들 히트테스트를 꺼 트랜스포머 위 클릭도 팬으로 흐르게.\n engineRef.current?.setPanMode(true);\n applyEditorCursor();\n },\n onSpaceUp: () => {\n engineRef.current?.setPanMode(false);\n if (interactionModeRef.current === \"panning\") {\n setEditorInteractionMode(\"idle\");\n } else {\n applyEditorCursor();\n }\n },\n nudge: (dx, dy) => rejectLockedEdit(hasEditableSelection()) || nudgeSelection(dx, dy),\n });\n\n // 선택 정보 배지 대상(선택 && 표시 중인 도형 — 오버라이드 반영).\n const selectedShapes = useMemo(\n () => renderShapes.filter((s) => selectedIds.includes(s.id) && isShapeVisible(s)),\n [renderShapes, selectedIds],\n );\n // 선택 배지 + 그리는 중 미리보기 배지(합성 도형)를 같은 오버레이로 렌더.\n const selectionInfoShapes = useMemo(\n () => (drawPreviewShape ? [...selectedShapes, drawPreviewShape] : selectedShapes),\n [selectedShapes, drawPreviewShape],\n );\n\n // 컨텍스트 메뉴 항목.\n const hasSel = selectedIds.length > 0;\n const hasEditableSel = doc.shapes.some(\n (shape) => selectedIds.includes(shape.id) && isShapeEditable(shape),\n );\n // 정점 편집 진입 가능 여부(단일 폴리곤/라인 선택, 편집 가능).\n const editableSinglePoly =\n !effectiveReadOnly &&\n selectedIds.length === 1 &&\n (() => {\n const s = doc.shapes.find((shape) => shape.id === selectedIds[0]);\n return (\n !!s &&\n (s.type === SHAPE_TYPE.POLYGON || s.type === SHAPE_TYPE.LINE) &&\n s.interaction?.editable !== false &&\n !s.readOnly\n );\n })();\n // 합치기/어시스트 refine 가용성(메뉴 열릴 때 평가).\n const mergeTargets = getMergeTargets();\n const mergeDisabled =\n effectiveReadOnly ||\n mergeTargets.length < 2 ||\n (canMergeSelection ? !canMergeSelection(mergeTargets) : false);\n const showAssistantMenu = !!assistant && !effectiveReadOnly;\n const assistRefineTarget =\n showAssistantMenu && selectedIds.length === 1\n ? (() => {\n const s = doc.shapes.find((shape) => shape.id === selectedIds[0]);\n return s &&\n s.type === SHAPE_TYPE.POLYGON &&\n s.interaction?.editable !== false &&\n !s.readOnly\n ? s\n : null;\n })()\n : null;\n const fullMenuItems: ContextMenuItem[] = [\n {\n id: \"copy\",\n label: S.contextMenu.copy,\n shortcut: \"⌘C\",\n disabled: !hasEditableSel,\n onClick: copySelection,\n },\n {\n id: \"paste\",\n label: S.contextMenu.paste,\n shortcut: \"⌘V\",\n disabled: effectiveReadOnly || !canPaste(),\n onClick: () => paste(menu?.img),\n },\n {\n id: \"duplicate\",\n label: S.contextMenu.duplicate,\n shortcut: \"⌘D\",\n disabled: !hasEditableSel || effectiveReadOnly,\n onClick: duplicate,\n },\n {\n id: \"delete\",\n label: S.contextMenu.delete,\n shortcut: \"Del\",\n danger: true,\n disabled: !hasEditableSel || effectiveReadOnly,\n onClick: deleteSelection,\n },\n { separator: true },\n {\n id: \"editVertices\",\n label: S.contextMenu.editVertices,\n shortcut: \"Enter\",\n disabled: !editableSinglePoly,\n onClick: () => setEditingId(selectedIds[0]),\n },\n {\n id: \"merge\",\n label: S.contextMenu.merge,\n disabled: mergeDisabled,\n onClick: mergeSelection,\n },\n ...(showAssistantMenu\n ? [\n {\n id: \"assistExpand\",\n label: S.contextMenu.assistExpand,\n icon: <MagicWandIcon size={14} />,\n disabled: !assistRefineTarget,\n onClick: () => {\n if (menu && assistRefineTarget)\n assistantSession.refineShape(assistRefineTarget, menu.img, true);\n },\n },\n {\n id: \"assistExclude\",\n label: S.contextMenu.assistExclude,\n icon: <MagicWandIcon size={14} />,\n disabled: !assistRefineTarget,\n onClick: () => {\n if (menu && assistRefineTarget)\n assistantSession.refineShape(assistRefineTarget, menu.img, false);\n },\n },\n ]\n : []),\n {\n id: \"bringToFront\",\n label: S.contextMenu.bringToFront,\n disabled: !hasEditableSel || effectiveReadOnly,\n onClick: bringToFront,\n },\n {\n id: \"sendToBack\",\n label: S.contextMenu.sendToBack,\n disabled: !hasEditableSel || effectiveReadOnly,\n onClick: sendToBack,\n },\n { separator: true },\n {\n id: \"undo\",\n label: S.contextMenu.undo,\n shortcut: \"⌘Z\",\n disabled: effectiveReadOnly || (!canUndoSession() && !doc.canUndo()),\n onClick: () => {\n if (!undoSession()) doc.undo();\n },\n },\n {\n id: \"redo\",\n label: S.contextMenu.redo,\n shortcut: \"⇧⌘Z\",\n disabled: effectiveReadOnly || (!canRedoSession() && !doc.canRedo()),\n onClick: () => {\n if (!redoSession()) doc.redo();\n },\n },\n { separator: true },\n { id: \"selectAll\", label: S.contextMenu.selectAll, shortcut: \"⌘A\", onClick: selectAll },\n {\n id: \"clearSelection\",\n label: S.contextMenu.clearSelection,\n disabled: !hasSel,\n onClick: clearSelection,\n },\n {\n id: \"zoomToSelection\",\n label: S.contextMenu.zoomToSelection,\n disabled: !hasSel,\n onClick: zoomToSelection,\n },\n ];\n // 실제 읽기전용 화면은 조회 액션만 노출한다. 완료 잠금(locked)은 편집 전환 가능성을\n // 보여줘야 하므로 전체 메뉴를 유지하고 각 항목의 effectiveReadOnly 조건으로 비활성화한다.\n const defaultMenuItems = readOnly\n ? fullMenuItems.filter(\n (item) => \"separator\" in item || (!!item.id && READ_ONLY_CONTEXT_MENU_IDS.has(item.id)),\n )\n : fullMenuItems;\n // 호스트가 도메인 액션(예: 클래스 변경)을 추가/제거할 수 있는 확장 지점.\n const menuItems = getContextMenuItems\n ? getContextMenuItems(defaultMenuItems, {\n selectedIds,\n readOnly: effectiveReadOnly,\n })\n : defaultMenuItems;\n\n const minimapNav = useMinimapNavigation({\n engineRef,\n image,\n wheelZoom: view.wheelZoom,\n minimapSize: MINIMAP_SIZE,\n });\n const handleMinimapZoom100 = useCallback(() => {\n engineRef.current?.zoom100();\n }, []);\n const handleMinimapToggle = useCallback(() => {\n setMinimapOpen((open) => !open);\n }, []);\n const handleSettingsToggle = useCallback(() => {\n setSettingsOpen((open) => !open);\n }, []);\n const handleSettingsClose = useCallback(() => {\n setSettingsOpen(false);\n }, []);\n\n return (\n <div className=\"aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black\">\n {/* 숨길 땐 즉시(transition 없음), 나타날 땐 잔잔한 페이드인. */}\n <div\n ref={hostRef}\n role=\"application\"\n aria-label={S.canvasLabel}\n // biome-ignore lint/a11y/noNoninteractiveTabindex: 캔버스의 키보드 편집을 위한 포커스 대상이다.\n tabIndex={0}\n onPointerDownCapture={(event) => event.currentTarget.focus({ preventScroll: true })}\n className=\"aivex:h-full aivex:w-full\"\n style={{\n opacity: imageVisible ? 1 : 0,\n transition: imageVisible ? \"opacity 0.3s ease\" : \"none\",\n }}\n />\n\n {/* 이미지 로딩/없음/에러 상태 오버레이. */}\n {effectiveImageStatus !== \"ready\" && (\n <ImageStateOverlay\n status={effectiveImageStatus}\n error={imageError}\n render={renderImageState}\n loadingLabel={S.imageLoading}\n missingLabel={S.imageMissing}\n errorLabel={S.imageLoadError}\n errorHints={S.imageErrorHints}\n />\n )}\n\n {/* 캔버스 위 ROI/제외영역/가이드마스크 오버레이(뷰포트 동기, 렌더러 무관). */}\n {ready && image && (\n <div className=\"aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden\">\n <div\n ref={overlayRef}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: image.w,\n height: image.h,\n transformOrigin: \"0 0\",\n }}\n >\n {/* ROI 딤은 렌더러 오버레이(이미지↔도형 사이)에서 그린다.\n 여기(도형 위 DOM)에는 마커/선택정보/어시스트만 둔다. */}\n {!!overlayMarkers?.length && renderOverlayMarker && (\n <div\n style={{\n position: \"absolute\",\n left: 0,\n top: 0,\n width: image.w,\n height: image.h,\n pointerEvents: \"none\",\n }}\n >\n {overlayMarkers.map((marker) => (\n <div\n key={marker.id}\n role={marker.disabled ? undefined : \"button\"}\n tabIndex={marker.disabled ? undefined : 0}\n aria-pressed={marker.selected || undefined}\n onClick={(e) => {\n e.stopPropagation();\n if (!marker.disabled) onOverlayMarkerClick?.(marker);\n }}\n onKeyDown={(e) => {\n if (marker.disabled) return;\n if (e.key !== \"Enter\" && e.key !== \" \") return;\n e.preventDefault();\n e.stopPropagation();\n onOverlayMarkerClick?.(marker);\n }}\n style={{\n position: \"absolute\",\n left: marker.point.x,\n top: marker.point.y,\n // topLeft: 앵커점을 콘텐츠 원점(0,0)에 두고 그 점 기준으로 스케일.\n // center(기본): 콘텐츠 중앙을 앵커점에 맞춘다.\n transform:\n marker.anchor === \"topLeft\"\n ? \"scale(var(--editor-overlay-inverse-scale, 1))\"\n : \"translate(-50%, -50%) scale(var(--editor-overlay-inverse-scale, 1))\",\n transformOrigin: marker.anchor === \"topLeft\" ? \"0 0\" : \"center\",\n // 선택된 마커(열린 패널 포함)는 다른 마커 위에 — DOM 순서상\n // 뒤 마커가 앞 마커의 패널을 덮는 것을 방지.\n zIndex: marker.selected ? 1 : undefined,\n pointerEvents: marker.disabled ? \"none\" : \"auto\",\n cursor: marker.disabled ? \"default\" : \"pointer\",\n }}\n >\n {renderOverlayMarker(marker)}\n </div>\n ))}\n </div>\n )}\n {renderImageOverlay?.({\n image,\n viewport: engineRef.current?.viewport ?? { scale: 1, x: 0, y: 0 },\n })}\n {selectionInfoShapes.length > 0 && (\n <SelectionInfo\n shapes={selectionInfoShapes}\n getLabel={getSelectionLabel}\n hideDot={hideSelectionLabelDot}\n formatInfo={formatSelectionInfo}\n register={registerSelectionInfo}\n />\n )}\n {/* 어시스트 오버레이(+/− 마커·박스 shimmer·스피너)는 추론 진행 중에만\n 표시한다(포인트 세션 loading 또는 병렬 박스 요청 pending). 옵스는\n processingBoundingBoxes(진행 중에만 채워짐)로 그렸으므로, 추론이\n 끝나면 마커/shimmer가 남지 않아야 한다. */}\n {assistant &&\n (assistantSession.status === \"loading\" || assistantSession.boxes.length > 0) && (\n <AssistantOverlay\n image={image}\n points={assistantSession.points}\n boxes={assistantSession.boxes}\n status={assistantSession.status}\n />\n )}\n </div>\n </div>\n )}\n\n {/* 커서 가이드라인. */}\n {ready && view.showCursorGuide && <CursorGuide color=\"#1e88e5\" />}\n\n {/* 미니맵(좌하단) + 줌 컨트롤 바 + 설정 팝오버. */}\n {image && showMinimap && (\n <Minimap\n image={image}\n imageUrl={renderedImageUrl}\n imageVisible={imageVisible}\n loading={!ready}\n region={regionOverlay}\n roiMaskId={minimapRoiMaskId}\n shapes={renderShapes}\n view={view}\n viewDefaults={seededDefaults}\n onChangeView={updateView}\n nav={minimapNav}\n registerShape={registerMinimapShape}\n rectRef={minimapRectRef}\n zoomLabelRef={zoomLabelRef}\n onZoom100={handleMinimapZoom100}\n open={minimapOpen}\n onToggleOpen={handleMinimapToggle}\n position={minimapPosition}\n labels={S.minimap}\n settingsLabels={S.viewSettings}\n settingsItems={viewSettingItems}\n showSettings={showViewSettings}\n settingsOpen={settingsOpen}\n onToggleSettings={handleSettingsToggle}\n onCloseSettings={handleSettingsClose}\n />\n )}\n\n {menu && (\n <ContextMenu x={menu.x} y={menu.y} items={menuItems} onClose={() => setMenu(null)} />\n )}\n </div>\n );\n}\n","\"use client\";\n\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n type EditorShape,\n getBBox,\n type Point,\n SHAPE_TYPE,\n sortShapesForRender,\n} from \"./_model/geometry\";\nimport { diagnoseImageLoadFailure, type EditorImageDiagnosis } from \"./_model/imageDiagnosis\";\nimport { loadCorsImage } from \"./_model/imageLoad\";\nimport {\n buildRegionOverlayData,\n drawRegionDim,\n type RegionMask,\n type ResolvedRegionOutlineStyle,\n} from \"./_model/overlays\";\nimport { resolveShapeRenderStyle } from \"./_model/shapeRenderStyle\";\nimport { DEFAULT_EDITOR_STRINGS } from \"./_model/strings\";\nimport { clampViewSettings } from \"./_model/viewSettings\";\n\n/**\n * ShapeViewer가 지원하는 EditorShape **표시 서브셋 계약**:\n * - 도형: POINT / RECTANGLE / ELLIPSE / POLYGON / LINE / ROTATED_RECTANGLE(꼭짓점 배열)\n * - 스타일: color·alternateColor·strokeWidth·dash·opacity·filled·fillOpacity·\n * pointRadius·zIndex, readOnly 줄무늬 — 에디터 렌더러와 같은 의미\n * (resolveShapeRenderStyle 공유)로 그린다.\n * - 상호작용·선택·핸들·마커 등 편집 표현은 렌더링하지 않는다(interaction.visible만 존중).\n */\nexport interface ShapeViewerProps<TMeta = unknown> {\n imageUrl: string;\n alt?: string;\n /** 도형 좌표계 크기. 썸네일 이미지의 실제 픽셀 크기와 다를 때 지정한다. */\n coordinateSize?: { width: number; height: number };\n shapes?: EditorShape<TMeta>[];\n regionMask?: RegionMask;\n /** 지정한 도형이 화면을 채우도록 확대한다. */\n focusedShapeId?: string;\n /**\n * 포커스 줌 시 이미지 밖 여백 처리. \"cover\"면 이미지가 항상 컨테이너를\n * 가득 채우도록 배율을 올리고 오프셋을 이미지 안쪽으로 클램프한다(썸네일용).\n */\n focusFit?: \"contain\" | \"cover\";\n zoomPadding?: number;\n strokeSize?: number;\n brightness?: number;\n contrast?: number;\n imageSmoothing?: boolean;\n lazy?: boolean;\n className?: string;\n style?: CSSProperties;\n /** error일 때 diagnosis에 원인 분류·기술 근거가 실린다(진단 전/실패 시 null). */\n renderImageState?: (\n status: \"loading\" | \"error\" | \"missing\",\n diagnosis?: EditorImageDiagnosis | null,\n ) => ReactNode;\n}\n\nfunction tracePoints(\n ctx: CanvasRenderingContext2D,\n points: { x: number; y: number }[],\n closed: boolean,\n) {\n if (points.length === 0) return;\n ctx.beginPath();\n ctx.moveTo(points[0].x, points[0].y);\n for (let index = 1; index < points.length; index += 1) {\n ctx.lineTo(points[index].x, points[index].y);\n }\n if (closed) ctx.closePath();\n}\n\n// 스타일 해석은 에디터 렌더러(Konva/Pixi)와 공유(resolveShapeRenderStyle) —\n// 썸네일과 편집기의 표현이 어긋나지 않게 한다. 도형 경로만 이 파일 소유.\nfunction drawShape(\n ctx: CanvasRenderingContext2D,\n shape: EditorShape,\n viewportScale: number,\n defaultStrokeSize: number,\n) {\n if (shape.interaction?.visible === false) return;\n const style = resolveShapeRenderStyle(shape, {\n strokeWidth: defaultStrokeSize,\n pointRadius: 2,\n });\n ctx.save();\n ctx.globalAlpha = style.opacity;\n ctx.lineWidth = style.strokeWidth / viewportScale;\n ctx.lineJoin = \"round\";\n ctx.lineCap = \"round\";\n\n if (shape.type === SHAPE_TYPE.POINT) {\n const point = shape.points[0];\n if (point) {\n ctx.fillStyle = style.color;\n ctx.beginPath();\n ctx.arc(point.x, point.y, style.pointRadius / viewportScale, 0, Math.PI * 2);\n ctx.fill();\n }\n ctx.restore();\n return;\n }\n\n if (shape.type === SHAPE_TYPE.RECTANGLE || shape.type === SHAPE_TYPE.ELLIPSE) {\n const [start, end] = shape.points;\n if (start && end) {\n const x = Math.min(start.x, end.x);\n const y = Math.min(start.y, end.y);\n const width = Math.abs(end.x - start.x);\n const height = Math.abs(end.y - start.y);\n ctx.beginPath();\n if (shape.type === SHAPE_TYPE.ELLIPSE) {\n ctx.ellipse(x + width / 2, y + height / 2, width / 2, height / 2, 0, 0, Math.PI * 2);\n } else {\n ctx.rect(x, y, width, height);\n }\n }\n } else {\n tracePoints(ctx, shape.points, shape.type !== SHAPE_TYPE.LINE);\n }\n\n if (style.fillVisible) {\n ctx.save();\n ctx.fillStyle = style.color;\n ctx.globalAlpha *= style.fillAlpha;\n // 자기교차 폴리곤(도넛)의 구멍을 비운다 — 에디터 렌더러들과 동일한 evenodd 채움.\n ctx.fill(\"evenodd\");\n ctx.restore();\n }\n // 점선의 빈 구간 보조색 — 에디터 렌더러와 동일 의미(보조색 실선 위에 주색 점선).\n if (shape.style?.alternateColor && style.dash?.length) {\n ctx.setLineDash([]);\n ctx.strokeStyle = shape.style.alternateColor;\n ctx.stroke();\n }\n ctx.setLineDash((style.dash ?? []).map((value) => value / viewportScale));\n ctx.strokeStyle = style.color;\n ctx.stroke();\n ctx.restore();\n}\n\n/** 목록·카드 미리보기를 위한 상호작용 없는 Canvas2D 도형 뷰어. */\nexport default function ShapeViewer<TMeta = unknown>({\n imageUrl,\n alt = \"Shape preview\",\n coordinateSize,\n shapes = [],\n regionMask,\n focusedShapeId,\n focusFit = \"contain\",\n zoomPadding = 0.3,\n strokeSize = 1,\n brightness = 1,\n contrast = 1,\n imageSmoothing = true,\n lazy = true,\n className,\n style,\n renderImageState,\n}: ShapeViewerProps<TMeta>) {\n const containerRef = useRef<HTMLDivElement>(null);\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const imageRef = useRef<HTMLImageElement | null>(null);\n const [visible, setVisible] = useState(!lazy);\n const [status, setStatus] = useState<\"loading\" | \"ready\" | \"error\" | \"missing\">(\"loading\");\n const [diagnosis, setDiagnosis] = useState<EditorImageDiagnosis | null>(null);\n const [sizeRevision, setSizeRevision] = useState(0);\n\n useEffect(() => {\n if (!lazy || visible) return;\n const element = containerRef.current;\n if (!element) return;\n const observer = new IntersectionObserver(([entry]) => {\n if (!entry.isIntersecting) return;\n setVisible(true);\n observer.disconnect();\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [lazy, visible]);\n\n useEffect(() => {\n const element = containerRef.current;\n if (!element) return;\n const observer = new ResizeObserver(() => setSizeRevision((value) => value + 1));\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n\n useEffect(() => {\n if (!visible || !imageUrl) {\n // 빈 URL은 로드 실패가 아니라 이미지가 없는 문서 — 전용 상태로 표시한다.\n setStatus(imageUrl ? \"loading\" : \"missing\");\n setDiagnosis(null);\n return;\n }\n let active = true;\n setStatus(\"loading\");\n setDiagnosis(null);\n void loadCorsImage(imageUrl).then(async (image) => {\n if (!active) return;\n if (image) {\n imageRef.current = image;\n setStatus(\"ready\");\n return;\n }\n // URL 교체 실패 시 이전 항목의 이미지가 에러 상태 뒤에 남지 않게 해제.\n imageRef.current = null;\n setStatus(\"error\");\n // 진단은 reject하지 않는다(프로브 실패는 unknown 분류로 보고).\n const result = await diagnoseImageLoadFailure(imageUrl);\n if (active) setDiagnosis(result);\n });\n return () => {\n active = false;\n };\n }, [imageUrl, visible]);\n\n useEffect(\n () => () => {\n imageRef.current = null;\n },\n [],\n );\n\n const focusedShape = useMemo(\n () => shapes.find((shape) => shape.id === focusedShapeId),\n [focusedShapeId, shapes],\n );\n useEffect(() => {\n if (status === \"error\") {\n // 실패한 항목이 직전 그림을 계속 보여주지 않도록 캔버스를 비운다.\n // (loading 중에는 비우지 않는다 — 목록 페이징 시 깜빡임 방지.)\n const canvas = canvasRef.current;\n canvas?.getContext(\"2d\")?.clearRect(0, 0, canvas.width, canvas.height);\n }\n if (status !== \"ready\") return;\n const container = containerRef.current;\n const canvas = canvasRef.current;\n const image = imageRef.current;\n if (!container || !canvas || !image) return;\n\n const { width: cssWidth, height: cssHeight } = container.getBoundingClientRect();\n if (!cssWidth || !cssHeight) return;\n const dpr = window.devicePixelRatio || 1;\n canvas.width = Math.max(1, Math.round(cssWidth * dpr));\n canvas.height = Math.max(1, Math.round(cssHeight * dpr));\n canvas.style.width = `${cssWidth}px`;\n canvas.style.height = `${cssHeight}px`;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return;\n\n const imageWidth = coordinateSize?.width ?? image.naturalWidth;\n const imageHeight = coordinateSize?.height ?? image.naturalHeight;\n // 좌표계 크기 0(호스트가 서버 메타 수신 전 전달 등)이면 scale이 Infinity가 된다.\n if (!imageWidth || !imageHeight) return;\n let scale = Math.min(cssWidth / imageWidth, cssHeight / imageHeight);\n let offsetX = (cssWidth - imageWidth * scale) / 2;\n let offsetY = (cssHeight - imageHeight * scale) / 2;\n\n if (focusedShape && focusedShape.points.length > 0) {\n const bounds = getBBox(focusedShape.points);\n const width = Math.max(bounds.maxX - bounds.minX, 50);\n const height = Math.max(bounds.maxY - bounds.minY, 50);\n const padding = Math.min(width, height) * zoomPadding;\n scale = Math.min(cssWidth / (width + padding * 2), cssHeight / (height + padding * 2));\n if (focusFit === \"cover\") {\n scale = Math.max(scale, Math.max(cssWidth / imageWidth, cssHeight / imageHeight));\n }\n offsetX = cssWidth / 2 - ((bounds.minX + bounds.maxX) / 2) * scale;\n offsetY = cssHeight / 2 - ((bounds.minY + bounds.maxY) / 2) * scale;\n if (focusFit === \"cover\") {\n offsetX = Math.min(0, Math.max(offsetX, cssWidth - imageWidth * scale));\n offsetY = Math.min(0, Math.max(offsetY, cssHeight - imageHeight * scale));\n }\n }\n\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n ctx.clearRect(0, 0, cssWidth, cssHeight);\n ctx.save();\n ctx.translate(offsetX, offsetY);\n ctx.scale(scale, scale);\n ctx.imageSmoothingEnabled = imageSmoothing;\n // 편집기와 같은 허용 범위로 묶는다 — 범위 밖 값이 들어와도 사진이 사라지지 않는다.\n const filter = clampViewSettings({ brightness, contrast });\n ctx.filter = `brightness(${filter.brightness}) contrast(${filter.contrast})`;\n ctx.drawImage(image, 0, 0, imageWidth, imageHeight);\n ctx.filter = \"none\";\n\n const regionOverlay = regionMask\n ? buildRegionOverlayData(regionMask, imageWidth, imageHeight)\n : null;\n if (regionOverlay) {\n drawRegionDim(ctx, regionOverlay, imageWidth, imageHeight);\n if (regionOverlay.outlineStyles) {\n // 경계 선분 — 스타일은 에디터와 동일하게 RegionMask에서 리졸브된 값을 쓴다.\n const strokeSegments = (segments: [Point, Point][], style: ResolvedRegionOutlineStyle) => {\n ctx.lineWidth = style.width / scale;\n if (style.underlayColor) {\n ctx.setLineDash([]);\n ctx.strokeStyle = style.underlayColor;\n for (const [a, b] of segments) {\n tracePoints(ctx, [a, b], false);\n ctx.stroke();\n }\n }\n ctx.save();\n ctx.globalAlpha *= style.opacity;\n ctx.setLineDash(style.dash.map((value) => value / scale));\n ctx.strokeStyle = style.color;\n for (const [a, b] of segments) {\n tracePoints(ctx, [a, b], false);\n ctx.stroke();\n }\n ctx.restore();\n };\n strokeSegments(regionOverlay.visibleOutline, regionOverlay.outlineStyles.visible);\n strokeSegments(regionOverlay.occludedOutline, regionOverlay.outlineStyles.occluded);\n }\n }\n\n for (const shape of sortShapesForRender(shapes)) {\n drawShape(ctx, shape, scale, strokeSize);\n }\n ctx.restore();\n }, [\n brightness,\n contrast,\n coordinateSize,\n focusedShape,\n focusFit,\n imageSmoothing,\n regionMask,\n shapes,\n sizeRevision,\n status,\n strokeSize,\n zoomPadding,\n ]);\n\n return (\n <div\n ref={containerRef}\n className={className}\n style={{ position: \"relative\", width: \"100%\", height: \"100%\", ...style }}\n >\n <canvas ref={canvasRef} role=\"img\" aria-label={alt} style={{ display: \"block\" }} />\n {status !== \"ready\" && (\n <div style={{ position: \"absolute\", inset: 0 }}>\n {/* 커스텀 렌더가 없거나 null을 주면 기본 에러 표시로 폴백한다 —\n \"메시지 없는 빈 화면\"이 만들어질 수 없게 하는 불변식(로딩은 표시 생략 허용). */}\n {renderImageState?.(status, diagnosis) ??\n (status === \"missing\" ? (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n padding: 8,\n textAlign: \"center\",\n color: \"rgba(255,255,255,0.7)\",\n background: \"rgba(13,13,18,0.85)\",\n fontSize: 12,\n }}\n >\n {DEFAULT_EDITOR_STRINGS.imageMissing}\n </div>\n ) : status === \"error\" ? (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n gap: 4,\n padding: 8,\n textAlign: \"center\",\n color: \"rgba(255,255,255,0.85)\",\n background: \"rgba(13,13,18,0.85)\",\n fontSize: 12,\n }}\n >\n <span aria-hidden>⚠</span>\n <span>{DEFAULT_EDITOR_STRINGS.imageLoadError}</span>\n {diagnosis && (\n <span style={{ fontSize: 11, opacity: 0.7, wordBreak: \"break-all\" }}>\n {DEFAULT_EDITOR_STRINGS.imageErrorHints[diagnosis.kind]}\n </span>\n )}\n </div>\n ) : null)}\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;IAeE,IAAW;CACX,OAAA;CACA,WAAS;CACT,mBAAS;CACT,SAAM;CACP,SAAA;CAsED,MAAA;CACE;;AAGF,QAAA,EAAgB,aAAA,YAAgD;;;AAIhE,QAAA,EAAgB,EAAkB,IAAA,EAA6B,aAAA,oBAAA;;;AAI/D,QAAA,GAAgC,EAA6B,IAAA,EAAA,aAAA,eAAA;;;AAI7D,QAAA,EAAiC,EAAA,IAA6B,CAAA,EAAA,YAAA,EAAA,aAAA,aAAA;;;AAI9D,QAAA,GAAgB,EAA2B,IAAA,EAAoD,aAAA,cAAA;;SAEjE,GAAA,GAAA;QAAO,EAAA,KAAA,GAAA,OAAA;EAAO;EAEtC;EACA,EAAA,CAA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EACA,oBAAc;EACd,oBAAe;EACb,cAAY;EACZ,eAAW,MAAO;AAClB,IAAA,EAAA,UAAgB,IAAwB,kBAE1C,GAAe,EAAA,KAAW,MAAA,EAAA,GAAA,CAAA;;EAExB,eAAW,MAAO;wBAEpB,EAAA,OAAA,EAAe;;EAEb,eAAW,MAAI;wBAEjB,EAAA,OAAW,EAAI;;EAEf,WAAA,EAAA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAc,EAAA,SAAA,KAAA;iBACA,EAAU,SAAA,SAAA;EACtB,cAAU;GACV,IAAM,IAAK,EAAU;AACrB,OAAI,CAAA,EAAA;;AAEN,KAAA,OAAA,IAAe,GAAA,IAAA,GAAA,IAAA;;EAEb,eAAU;GACV,IAAM,IAAK,EAAU;AACrB,OAAI,CAAA,EAAA;;AAEN,KAAA,OAAA,IAAA,GAAA,IAAA,GAAA,IAAA,IAAA;;EAEA;EACA;;SAEE;GACA,eAAY;GACZ,eAAQ;GACR,YAAQ;GACR,QAAA;GACD,QAAA;GACF,wBACD;GACE;EACA,GAAA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;EAGH;EACA,CAAA;CAIA,IAAM,KAAA,EAAA,EAAA;IAGA,UAAA;KACA,KAAA,QAAA,GAAA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,2BAAA,GAAA,WAAA;EACA,iCAAA,GAAA,WAAA;EACA;EACA;EACA;EACA;EACA;EACA,cAAA;EACA,eAAA;EACA,oBAAoB;EACpB;EACD,oBACH;EACE,eAAA;EACA,CAAA,EAAA;EACA;EACA;EACA;EACD;EAIH;EACA,CAAA,EACE,KAAA,EAAA,EAAA,CAAA;IACA;EACA;EACA;EACA;EACA;EACA;EACA,eAAA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,gB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